"""Google Drive helpers for transcript/source + state persistence. Production mode (Hugging Face Spaces): - Uses a service account JSON provided via env var `GOOGLE_SERVICE_ACCOUNT_JSON` (stringified JSON). - Optional fallback: `GOOGLE_SERVICE_ACCOUNT_FILE` path to a JSON file. - Folder is configured via `GOOGLE_DRIVE_FOLDER_ID`. No browser OAuth flow is required at runtime. """ from __future__ import annotations import io import json import os import sys import traceback from datetime import datetime from pathlib import Path from typing import Any, Optional from google.oauth2.service_account import Credentials from googleapiclient.discovery import build from googleapiclient.http import MediaIoBaseDownload, MediaIoBaseUpload # ───────────────────────────────────────────────────────────────────────────── # Configuration # ───────────────────────────────────────────────────────────────────────────── SCOPES = ["https://www.googleapis.com/auth/drive"] # Default fallback so local dev still works without env var. _DEFAULT_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" def format_drive_diagnostic( action: str, researcher_id: str = "", file_id: str = "", file_name: str = "", error: Exception | None = None, extra: dict[str, Any] | None = None, ) -> str: """Return a copyable plain-text block for troubleshooting Drive issues.""" info = { "GOOGLE_SERVICE_ACCOUNT_JSON": "SET" if os.environ.get("GOOGLE_SERVICE_ACCOUNT_JSON", "").strip() else "MISSING", "GOOGLE_SERVICE_ACCOUNT_FILE": os.environ.get("GOOGLE_SERVICE_ACCOUNT_FILE", "").strip() or "MISSING", "GOOGLE_DRIVE_FOLDER_ID": os.environ.get("GOOGLE_DRIVE_FOLDER_ID", _DEFAULT_FOLDER_ID).strip() or "MISSING", } lines = [ "=== DRIVE DEBUG START ===", f"action: {action}", f"researcher_id: {researcher_id or 'MISSING'}", f"file_id: {file_id or 'MISSING'}", f"file_name: {file_name or 'MISSING'}", f"service_account_json: {info['GOOGLE_SERVICE_ACCOUNT_JSON']}", f"service_account_file: {info['GOOGLE_SERVICE_ACCOUNT_FILE']}", f"drive_folder_id: {info['GOOGLE_DRIVE_FOLDER_ID']}", ] if extra: for key, value in extra.items(): lines.append(f"{key}: {value}") if error is not None: lines.append(f"error_type: {type(error).__name__}") lines.append(f"error_message: {error}") lines.append("traceback:") lines.extend(traceback.format_exception(type(error), error, error.__traceback__)) lines.append("=== DRIVE DEBUG END ===") return "\n".join(lines) def _log_drive_diagnostic(*args, **kwargs) -> str: block = format_drive_diagnostic(*args, **kwargs) print(block, file=sys.stderr) return block # ───────────────────────────────────────────────────────────────────────────── # Credentials / service bootstrap # ───────────────────────────────────────────────────────────────────────────── def _folder_id() -> str: return os.environ.get("GOOGLE_DRIVE_FOLDER_ID", _DEFAULT_FOLDER_ID).strip() def _service_account_info() -> Optional[dict]: raw = os.environ.get("GOOGLE_SERVICE_ACCOUNT_JSON", "").strip() if raw: try: return json.loads(raw) except json.JSONDecodeError as e: _log_drive_diagnostic("load_service_account_info", error=e) return None path = os.environ.get("GOOGLE_SERVICE_ACCOUNT_FILE", "").strip() if path: p = Path(path) if not p.exists(): _log_drive_diagnostic( "load_service_account_file", extra={"path": path, "exists": False}, ) return None try: return json.loads(p.read_text(encoding="utf-8")) except json.JSONDecodeError as e: _log_drive_diagnostic("load_service_account_file", extra={"path": path, "exists": True}, error=e) return None return None def get_drive_service(_: str = "") -> Optional[object]: """Return an authenticated Drive service (service-account), else None.""" info = _service_account_info() if not info: return None try: creds = Credentials.from_service_account_info(info, scopes=SCOPES) return build("drive", "v3", credentials=creds) except Exception as e: _log_drive_diagnostic("build_drive_service", error=e) return None # ───────────────────────────────────────────────────────────────────────────── # 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"'{_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: _log_drive_diagnostic("list_transcripts", error=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: _log_drive_diagnostic("read_file_from_drive", file_id=file_id, error=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": [_folder_id()], } media = MediaIoBaseUpload( io.BytesIO(json.dumps(state_data, indent=2, ensure_ascii=False).encode("utf-8")), mimetype="application/json", resumable=False, ) file = service.files().create( body=file_metadata, media_body=media, fields='id' ).execute() return file.get('id') except Exception as e: _log_drive_diagnostic( "write_session_to_drive", researcher_id=researcher_name, file_name=filename, error=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"'{_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: _log_drive_diagnostic("load_session_from_drive", researcher_id=researcher_name, error=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())