Lara Monteagudo Tubau commited on
Commit Β·
da4b58e
1
Parent(s): 449fffb
Add Drive dropdown workflow and session restore
Browse files- setup page: refresh Drive files + load previous session buttons
- process flow: accept upload OR Drive dropdown source
- persist lightweight session snapshot to Drive after processing
- switch Drive auth to service-account env secrets for HF Spaces
Files changed (2)
- app.py+151-5
- drive_utils.py+48-115
23 unmodified lines242526272728291114 unmodified lines11441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731211 unmodified lines2485248624872488248924902491249224932494249524962497249824992366236725002501250225032504432 unmodified lines2937293829392940294129422943294429452946294729482949295029512952280728082953295429552956295723 unmodified linesfrom agent1b_coder import code_sectionfrom drive_utils import ( get_drive_service, load_user_credentials, list_transcripts, read_file_from_drive, write_session_to_drive,1114 unmodified lines
# ββ Process: Parse + Agent 0 combined ββββββββββββββββββββββββββββββββββββββββ
def _parse_drive_choice(choice: str) -> tuple[str, str]: if not choice or "::" not in choice: raise gr.Error("Pick a transcript from Drive first.") file_id, file_name = choice.split("::", 1) return file_id, file_name
def fn_refresh_drive_transcripts(researcher_id: str): rid = (researcher_id or "").strip() if not rid: return ( gr.update(choices=[], value=None, interactive=False), _status_card("Enter Researcher ID first, then refresh Drive files.", "warning"), )
register_researcher(rid) service = get_drive_service(rid) if not service: return ( gr.update(choices=[], value=None, interactive=False), _status_card( "Google Drive is not configured yet.", "warning", { "Needed secret": "GOOGLE_SERVICE_ACCOUNT_JSON", "Folder ID": "GOOGLE_DRIVE_FOLDER_ID", }, ), )
files = list_transcripts(service) if not files: return ( gr.update(choices=[], value=None, interactive=False), _status_card("No transcript files found in the configured Drive folder.", "warning"), )
choices = [ (f"{f['name']} Β· {f.get('modified_time', '')[:10]}", f"{f['id']}::{f['name']}") for f in files ] return ( gr.update(choices=choices, value=choices[0][1], interactive=True), _status_card("Drive connected. Select a transcript and click Process.", "success", {"Files": len(choices)}), )
def fn_load_previous_session(researcher_id: str, state: dict): rid = (researcher_id or "").strip() if not rid: return state, gr.update(), _status_card("Enter Researcher ID first.", "warning")
service = get_drive_service(rid) if not service: return state, gr.update(), _status_card("Drive not configured yet.", "warning")
loaded = load_session_from_drive(service, rid) if not loaded: return state, gr.update(), _status_card("No previous Drive session found for this researcher.", "warning")
new_state = _empty_state() new_state.update(loaded) new_state["researcher_id"] = rid sid = new_state.get("session_id", "")
return ( new_state, gr.update(value=sid), _status_card("Previous session loaded from Drive.", "success", {"Session ID": sid}), )
def fn_process_with_source(file_obj, drive_choice: str, session_id: str, researcher_id: str, state: dict): """Wrapper: accept either local upload or Drive dropdown selection.""" temp_path: Path | None = None service = None effective_file = file_obj
if effective_file is None and drive_choice: rid = (researcher_id or "").strip() service = get_drive_service(rid) if not service: raise gr.Error("Drive is not configured. Add Google secrets in Hugging Face first.")
file_id, file_name = _parse_drive_choice(drive_choice) text = read_file_from_drive(service, file_id) suffix = Path(file_name).suffix or ".txt" temp_path = Path(tempfile.mktemp(prefix="drive_transcript_", suffix=suffix)) temp_path.write_text(text, encoding="utf-8")
effective_file = type("DriveFile", (), {"name": str(temp_path)})()
if effective_file is None: raise gr.Error("Upload a transcript or choose one from Drive.")
final_state: dict | None = None try: for out in fn_process(effective_file, session_id, researcher_id, state): if isinstance(out, tuple) and out and isinstance(out[0], dict): final_state = out[0] yield out finally: if temp_path and temp_path.exists(): try: temp_path.unlink() except Exception: pass
# Persist lightweight state snapshot to Drive for resume. if final_state and (service or get_drive_service((researcher_id or "").strip())): try: svc = service or get_drive_service((researcher_id or "").strip()) if svc: slim = {k: v for k, v in final_state.items() if k not in {"turns", "kappa_report"}} write_session_to_drive( svc, final_state.get("researcher_id", researcher_id.strip()), final_state.get("session_id", session_id.strip()), slim, ) except Exception: pass
def fn_process(file_obj, session_id: str, researcher_id: str, state: dict): """Generator: parse transcript then run Agent 0. Navigates to sections page.""" if file_obj is None:1211 unmodified lines session_id_box = gr.Textbox(label="Session ID", placeholder="e.g. dyad_01", scale=1) researcher_id_box = gr.Textbox(label="Researcher ID", placeholder="e.g. R1", scale=1)
with gr.Row(): drive_refresh_btn = gr.Button("π Refresh Drive transcripts", variant="secondary") load_prev_btn = gr.Button("βΊ Load previous session", variant="secondary")
drive_file_dropdown = gr.Dropdown( label="Google Drive transcript (optional, instead of upload)", choices=[], interactive=False, ) drive_status_html = gr.HTML()
transcript_file = gr.File( label="Transcript file (.txt or .vtt Zoom export)", file_types=[".txt", ".vtt"], label="Transcript file (.txt, .vtt, .json)", file_types=[".txt", ".vtt", ".json"], )
process_btn = gr.Button("β‘ Process Transcript β", variant="primary")432 unmodified lines go_library_btn.click(lambda: _show("library"), outputs=ALL_PAGES)
# Setup: process transcript + detect sections drive_refresh_btn.click( fn=fn_refresh_drive_transcripts, inputs=[researcher_id_box], outputs=[drive_file_dropdown, drive_status_html], )
load_prev_btn.click( fn=fn_load_previous_session, inputs=[researcher_id_box, state], outputs=[state, session_id_box, process_status], )
process_btn.click( fn=fn_process, inputs=[transcript_file, session_id_box, researcher_id_box, state], fn=fn_process_with_source, inputs=[transcript_file, drive_file_dropdown, session_id_box, researcher_id_box, state], outputs=PROCESS_OUTPUTS, )
12345678910111213141512345678910111213181415202116171819202421262728223031232425262728373839402930424331323334353 unmodified lines394041534243445657585960616263646566676869707172454647487576777879808182838485868788899091929394959697989910010110210310410510610710810911011111249505152114115116117118535455565758596061626312112212312412512612712812913013113264656613513613713813914014167686970711437273747510 unmodified lines8687881608990919264 unmodified lines15715815923116016116223416316416516616716816917020 unmodified lines191192193261194195196197"""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."""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 osimport ioimport jsonfrom pathlib import Pathfrom typing import Optional, listimport osfrom datetime import datetimefrom pathlib import Pathfrom typing import Optional
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 iofrom googleapiclient.http import MediaIoBaseDownload, MediaIoBaseUpload
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 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"SCOPES = ["https://www.googleapis.com/auth/drive"]
# Google Drive folder ID where transcripts are storedTRANSCRIPTS_FOLDER_ID = "1RkjxApl2WRAw2gRzuw8yESPNV9quGmQo"# 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"3 unmodified lines
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# OAuth2 Management# Credentials / service bootstrap# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
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_urldef _folder_id() -> str: return os.environ.get("GOOGLE_DRIVE_FOLDER_ID", _DEFAULT_FOLDER_ID).strip()
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:def _service_account_info() -> Optional[dict]: raw = os.environ.get("GOOGLE_SERVICE_ACCOUNT_JSON", "").strip() if raw: try: creds.refresh(Request()) except RefreshError: return None
return creds return json.loads(raw) except json.JSONDecodeError as e: raise RuntimeError("Invalid GOOGLE_SERVICE_ACCOUNT_JSON") from e
path = os.environ.get("GOOGLE_SERVICE_ACCOUNT_FILE", "").strip() if path: p = Path(path) if not p.exists(): raise RuntimeError(f"GOOGLE_SERVICE_ACCOUNT_FILE not found: {path}") return json.loads(p.read_text(encoding="utf-8"))
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)) return None
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: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
creds = Credentials.from_service_account_info(info, scopes=SCOPES) return build("drive", "v3", credentials=creds)
10 unmodified lines return []
try: query = f"'{TRANSCRIPTS_FOLDER_ID}' in parents and trashed=false" query = f"'{_folder_id()}' in parents and trashed=false" results = service.files().list( q=query, spaces='drive',64 unmodified lines try: file_metadata = { "name": filename, "parents": [TRANSCRIPTS_FOLDER_ID], "parents": [_folder_id()], } media = io.BytesIO(json.dumps(state_data, indent=2).encode('utf-8')) 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,20 unmodified lines try: # Search for files matching pattern: researcher_name_*_state.json query = ( f"'{TRANSCRIPTS_FOLDER_ID}' in parents and " f"'{_folder_id()}' in parents and " f"name contains '{researcher_name}' and " f"name contains '_state.json' and " f"trashed=false"app.py+151-5
drive_utils.py+48-115