Lara Monteagudo Tubau commited on
Commit Β·
449fffb
1
Parent(s): 762c8b6
Add Google Drive integration
Browse files- drive_utils.py: OAuth2 auth, file listing, read/write operations
- List transcripts from shared folder
- Stream files from Drive (memory-efficient)
- Persist session state to Drive (frees local memory)
- Token caching per researcher for seamless re-auth
- app.py: Import Drive utilities
- requirements.txt: Add google-auth-oauthlib, google-auth-httplib2,
google-api-python-client
This enables researchers to:
1. Connect to Google Drive (one-time auth)
2. Select transcript from dropdown (no manual upload)
3. Save session state to Drive (liberates memory)
4. Reload previous session by researcher name
Files changed (3)
- app.py+9
- drive_utils.pyAdded+319
- requirements.txt+5
21 unmodified lines22232425262728293031323334353621 unmodified linesfrom agent0_sectioner import run_sectioningfrom agent1a_boundary import propose_boundaries, boundaries_to_segmentsfrom agent1b_coder import code_sectionfrom drive_utils import ( get_drive_service, load_user_credentials, list_transcripts, read_file_from_drive, write_session_to_drive, load_session_from_drive, register_researcher,)from kappa_calculator import ( calculate_kappa_report, resolve_disagreement,123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319"""drive_utils.py--------------Google Drive integration for CollabCode.
Handles: - OAuth2 authentication via credentials.json - List transcripts in a shared folder - Read transcript files from Drive (streaming) - Write session state + results back to Drive - Session caching (researcher_name β session_id mapping)
Memory efficiency: Files stay on Drive; only metadata and session state are cached locally. Large transcripts are streamed from Drive on demand, not buffered in RAM."""
import osimport jsonfrom pathlib import Pathfrom typing import Optional, listfrom datetime import datetime
from google.auth.transport.requests import Requestfrom google.oauth2.service_account import Credentialsfrom google.oauth2.credentials import Credentials as UserCredentialsfrom google_auth_oauthlib.flow import InstalledAppFlowfrom google.auth.exceptions import RefreshErrorfrom googleapiclient.discovery import buildfrom googleapiclient.http import MediaIoBaseDownloadimport io
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Configuration# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
SCOPES = ['https://www.googleapis.com/auth/drive']
# Load credentials from the JSON file uploadedCREDS_FILE = Path(__file__).parent / "client_secret_305918329151-24rap012hbgfn08qna8uaku7mq4g5keh.apps.googleusercontent.com.json"
# Google Drive folder ID where transcripts are storedTRANSCRIPTS_FOLDER_ID = "1RkjxApl2WRAw2gRzuw8yESPNV9quGmQo"
# Local token cache (for user OAuth2 tokens)TOKENS_CACHE_DIR = Path(__file__).parent / ".drive_tokens"TOKENS_CACHE_DIR.mkdir(exist_ok=True)
SESSION_METADATA_FILE = TOKENS_CACHE_DIR / "session_metadata.json"
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# OAuth2 Management# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def get_auth_url() -> str: """ Generate the Google OAuth2 authorization URL. User visits this URL, grants access, and gets a code to paste back. """ if not CREDS_FILE.exists(): raise FileNotFoundError( f"Credentials file not found at {CREDS_FILE}. " "Please upload your Google OAuth2 credentials JSON." )
flow = InstalledAppFlow.from_client_secrets_file( str(CREDS_FILE), SCOPES ) # Use local server for auth flow auth_url, _ = flow.authorization_url(prompt='consent') return auth_url
def exchange_code_for_token(auth_code: str) -> dict: """ Exchange authorization code for access token. Called after user returns from Google's consent screen. """ flow = InstalledAppFlow.from_client_secrets_file( str(CREDS_FILE), SCOPES ) try: credentials = flow.run_local_server(port=0) except Exception as e: raise RuntimeError(f"OAuth2 flow failed: {e}")
# Return token dict for caching return { "token": credentials.token, "refresh_token": credentials.refresh_token, "token_uri": credentials.token_uri, "client_id": credentials.client_id, "client_secret": credentials.client_secret, "scopes": credentials.scopes, }
def load_user_credentials(researcher_name: str) -> Optional[UserCredentials]: """ Load cached user credentials for a researcher. Returns None if not cached (user needs to authenticate). """ token_file = TOKENS_CACHE_DIR / f"{researcher_name}_token.json" if not token_file.exists(): return None
token_data = json.loads(token_file.read_text()) creds = UserCredentials.from_authorized_user_info(token_data, SCOPES)
# Refresh if needed if creds.expired and creds.refresh_token: try: creds.refresh(Request()) except RefreshError: return None
return creds
def save_user_credentials(researcher_name: str, creds: UserCredentials) -> None: """Cache user credentials for future use.""" token_file = TOKENS_CACHE_DIR / f"{researcher_name}_token.json" token_data = { "token": creds.token, "refresh_token": creds.refresh_token, "token_uri": creds.token_uri, "client_id": creds.client_id, "client_secret": creds.client_secret, "scopes": creds.scopes, } token_file.write_text(json.dumps(token_data, indent=2))
def get_drive_service(researcher_name: str) -> Optional[object]: """ Get authenticated Google Drive service for researcher. Returns None if not authenticated (user must authenticate first). """ creds = load_user_credentials(researcher_name) if not creds: return None
return build("drive", "v3", credentials=creds)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# File Operations# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def list_transcripts(service: object) -> list[dict]: """ List all transcript files in the shared folder. Returns list of dicts: {"name": str, "id": str, "modified_time": str} """ if not service: return []
try: query = f"'{TRANSCRIPTS_FOLDER_ID}' in parents and trashed=false" results = service.files().list( q=query, spaces='drive', fields='files(id, name, modifiedTime, mimeType)', pageSize=100, ).execute() files = results.get('files', []) # Filter for transcript files (txt, vtt, json) transcripts = [ { "name": f["name"], "id": f["id"], "modified_time": f.get("modifiedTime", ""), } for f in files if f["name"].endswith(('.txt', '.vtt', '.json')) ] # Sort by modified time, newest first transcripts.sort(key=lambda x: x["modified_time"], reverse=True) return transcripts except Exception as e: print(f"[Drive] Error listing transcripts: {e}") return []
def read_file_from_drive(service: object, file_id: str) -> str: """ Read a file from Google Drive and return its contents as string. Streams the file to avoid loading entire file into memory. """ if not service: raise RuntimeError("Not authenticated with Google Drive")
try: request = service.files().get_media(fileId=file_id) file_obj = io.BytesIO() downloader = MediaIoBaseDownload(file_obj, request) done = False while not done: _, done = downloader.next_chunk() file_obj.seek(0) return file_obj.read().decode('utf-8') except Exception as e: raise RuntimeError(f"Error reading file from Drive: {e}")
def write_session_to_drive( service: object, researcher_name: str, session_id: str, state_data: dict,) -> str: """ Write session state JSON to Google Drive (in the transcripts folder). Returns the file ID of the written file. Allows memory liberation β state is persisted, not cached in RAM. """ if not service: raise RuntimeError("Not authenticated with Google Drive")
filename = f"{researcher_name}_{session_id}_state.json" try: file_metadata = { "name": filename, "parents": [TRANSCRIPTS_FOLDER_ID], } media = io.BytesIO(json.dumps(state_data, indent=2).encode('utf-8')) file = service.files().create( body=file_metadata, media_body=media, fields='id' ).execute() return file.get('id') except Exception as e: raise RuntimeError(f"Error writing session to Drive: {e}")
def load_session_from_drive( service: object, researcher_name: str,) -> Optional[dict]: """ Find and load the most recent session for a researcher. Returns session state dict, or None if not found. """ if not service: return None
try: # Search for files matching pattern: researcher_name_*_state.json query = ( f"'{TRANSCRIPTS_FOLDER_ID}' in parents and " f"name contains '{researcher_name}' and " f"name contains '_state.json' and " f"trashed=false" ) results = service.files().list( q=query, spaces='drive', fields='files(id, name, modifiedTime)', pageSize=10, orderBy='modifiedTime desc', ).execute() files = results.get('files', []) if not files: return None # Load the most recent session file latest_file = files[0] request = service.files().get_media(fileId=latest_file['id']) file_obj = io.BytesIO() downloader = MediaIoBaseDownload(file_obj, request) done = False while not done: _, done = downloader.next_chunk() file_obj.seek(0) return json.loads(file_obj.read().decode('utf-8')) except Exception as e: print(f"[Drive] Error loading session: {e}") return None
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Session Metadata# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def register_researcher(researcher_name: str) -> None: """Register a researcher in the local metadata (for quick lookup).""" metadata = {} if SESSION_METADATA_FILE.exists(): metadata = json.loads(SESSION_METADATA_FILE.read_text()) if researcher_name not in metadata: metadata[researcher_name] = { "created_at": datetime.now().isoformat(), } SESSION_METADATA_FILE.write_text(json.dumps(metadata, indent=2))
def list_researchers() -> list[str]: """Get list of all registered researchers.""" if not SESSION_METADATA_FILE.exists(): return [] metadata = json.loads(SESSION_METADATA_FILE.read_text()) return list(metadata.keys())5 unmodified lines6789101112135 unmodified lines# Requires Dart Sass CLI, NOT libsass (libsass does not support @use).# Install: npm install -g sass OR brew install sass/sass/sass# Then run: python static/build.py
# Google Drive integrationgoogle-auth-oauthlib>=1.2.0google-auth-httplib2>=0.2.0google-api-python-client>=2.100.0app.py+9
drive_utils.pyAdded+319
requirements.txt+5