I can access files stored on a standard Google Shared Drive with no issues as an “editor” using the API, however I can’t access files stored on a Google Shared Drive in Google Workspace even as “manager” using the API.
Why? How to solve this?
I have tried using the Google Drive API to access files stored on a Google Shared Drive within Google Workspace. Despite having “manager” permissions on the Workspace Shared Drive, I was unable to access the files via the API. I expected that having “manager” permissions would allow me to access and manipulate these files without any issues, similar to how I can access files on a standard Google Shared Drive with “editor” permissions.
I was hoping the API access would be seamless across both standard and Workspace Shared Drives, but that hasn’t been the case. I have checked my API credentials, ensured that the necessary permissions are granted, and even re-authenticated my access, but the issue persists.
Here is the code:
import os
import openai
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import shutil
# OpenAI API Configuration
openai.api_key = 'API-key-here'
# Supported file formats for transcription
SUPPORTED_FORMATS = ['flac', 'm4a', 'mp3', 'mp4', 'mpeg', 'mpga', 'oga', 'ogg', 'wav', 'webm']
# Function to authenticate and get an instance of Google Drive
def authenticate_google_drive():
gauth = GoogleAuth()
# Try to load saved credentials
gauth.LoadCredentialsFile("mycreds.txt")
if gauth.credentials is None:
# Local authentication
gauth.LocalWebserverAuth()
elif gauth.access_token_expired:
# Refresh the expired token
gauth.Refresh()
else:
# Authorize the existing token
gauth.Authorize()
# Save the credentials
gauth.SaveCredentialsFile("mycreds.txt")
return GoogleDrive(gauth)
# Authenticate and get an instance of Google Drive
drive = authenticate_google_drive()
# IDs of the input and output folders
input_folder_id = 'id-here'
output_folder_id = 'id-here'
# Function to check the existence of the folder
def verify_folder_exists(folder_id):
try:
folder = drive.CreateFile({'id': folder_id})
folder.FetchMetadata(fields='title')
return True
except:
return False
if not verify_folder_exists(input_folder_id):
print(f"Error: The input folder with ID {input_folder_id} was not found or you do not have permission to access it.")
exit(1)
if not verify_folder_exists(output_folder_id):
print(f"Error: The output folder with ID {output_folder_id} was not found or you do not have permission to access it.")
exit(1)
# Function to download files from the input folder and its subfolders
def download_files_from_drive(folder_id, destination_folder):
query = f"'{folder_id}' in parents and trashed=false"
file_list = drive.ListFile({'q': query}).GetList()
if not os.path.exists(destination_folder):
os.makedirs(destination_folder)
for file in file_list:
if file['mimeType'] == 'application/vnd.google-apps.folder':
# Create subfolder locally and download files within it
subfolder_path = os.path.join(destination_folder, file['title'])
os.makedirs(subfolder_path, exist_ok=True)
download_files_from_drive(file['id'], subfolder_path)
else:
file_ext = file['title'].split('.')[-1].lower()
if file_ext in SUPPORTED_FORMATS:
print(f"Downloading file {file['title']}...")
file.GetContentFile(os.path.join(destination_folder, file['title']))
else:
print(f"File {file['title']} is not in a supported format and will be ignored.")
# Function to transcribe files using Whisper
def transcribe_files(input_folder, output_folder):
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for root, _, files in os.walk(input_folder):
for filename in files:
input_path = os.path.join(root, filename)
output_subfolder = os.path.join(output_folder, os.path.relpath(root, input_folder))
os.makedirs(output_subfolder, exist_ok=True)
output_path = os.path.join(output_subfolder, os.path.splitext(filename)[0] + '.txt')
try:
with open(input_path, 'rb') as audio_file:
response = openai.Audio.transcribe("whisper-1", audio_file)
with open(output_path, 'w') as output_file:
output_file.write(response['text'])
print(f"Transcription of {filename} saved to {output_path}")
except Exception as e:
print(f"Error transcribing {filename}: {e}")
# Function to upload transcribed files to the output folder
def upload_files_to_drive(folder_id, source_folder):
for root, _, files in os.walk(source_folder):
for filename in files:
file_path = os.path.join(root, filename)
rel_path = os.path.relpath(file_path, source_folder)
parents = [{'id': folder_id}]
# Create subfolders on Google Drive, if necessary
for subfolder in rel_path.split(os.sep)[:-1]:
folder_query = f"'{folder_id}' in parents and trashed=false and title='{subfolder}' and mimeType='application/vnd.google-apps.folder'"
folder_list = drive.ListFile({'q': folder_query}).GetList()
if not folder_list:
new_folder = drive.CreateFile({'title': subfolder, 'parents': parents, 'mimeType': 'application/vnd.google-apps.folder'})
new_folder.Upload()
folder_id = new_folder['id']
else:
folder_id = folder_list[0]['id']
parents = [{'id': folder_id}]
file_drive = drive.CreateFile({'title': filename, 'parents': parents})
file_drive.SetContentFile(file_path)
file_drive.Upload()
print(f"File {filename} uploaded to the output folder.")
# Temporary paths for download and upload
temp_download_folder = './downloaded_files'
temp_transcribed_folder = './transcribed_files'
# Executing the workflow
print(f"Downloading files from folder {input_folder_id} to {temp_download_folder}...")
download_files_from_drive(input_folder_id, temp_download_folder)
print(f"Transcribing files from folder {temp_download_folder} to {temp_transcribed_folder}...")
transcribe_files(temp_download_folder, temp_transcribed_folder)
print(f"Uploading transcribed files to folder {output_folder_id}...")
upload_files_to_drive(output_folder_id, temp_transcribed_folder)
# Clean up temporary files
shutil.rmtree(temp_download_folder)
shutil.rmtree(temp_transcribed_folder)
print("Process completed successfully!")
user1 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
0