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 lines242526272829301114 unmodified lines1145114611471148114911501211 unmodified lines236223632364236523662367236823692370432 unmodified lines28032804280528062807280828092810281123 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 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 linessession_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)transcript_file = gr.File(label="Transcript file (.txt or .vtt Zoom export)",file_types=[".txt", ".vtt"],)process_btn = gr.Button("β‘ Process Transcript β", variant="primary")432 unmodified linesgo_library_btn.click(lambda: _show("library"), outputs=ALL_PAGES)# Setup: process transcript + detect sectionsprocess_btn.click(fn=fn_process,inputs=[transcript_file, session_id_box, researcher_id_box, state],outputs=PROCESS_OUTPUTS,)23 unmodified lines2425262728291114 unmodified lines11441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731211 unmodified lines24852486248724882489249024912492249324942495249624972498249925002501250225032504432 unmodified lines29372938293929402941294229432944294529462947294829492950295129522953295429552956295723 unmodified linesfrom agent1b_coder import code_sectionfrom drive_utils import (get_drive_service,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_namedef 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"] = ridsid = 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 = Noneservice = Noneeffective_file = file_objif 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 = Nonetry: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 outfinally: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:passdef 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 linessession_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, .vtt, .json)",file_types=[".txt", ".vtt", ".json"],)process_btn = gr.Button("β‘ Process Transcript β", variant="primary")432 unmodified linesgo_library_btn.click(lambda: _show("library"), outputs=ALL_PAGES)# Setup: process transcript + detect sectionsdrive_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_with_source,inputs=[transcript_file, drive_file_dropdown, session_id_box, researcher_id_box, state],outputs=PROCESS_OUTPUTS,)
123456789101112131415161718192021222324252627282930313233343536373839404142434445463 unmodified lines505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514610 unmodified lines15715815916016116216364 unmodified lines22822923023123223323423523623720 unmodified lines258259260261262263264"""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 datetimefrom 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"3 unmodified lines# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 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 flowauth_url, _ = flow.authorization_url(prompt='consent')return auth_urldef 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 cachingreturn {"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 Nonetoken_data = json.loads(token_file.read_text())creds = UserCredentials.from_authorized_user_info(token_data, SCOPES)# Refresh if neededif creds.expired and creds.refresh_token:try:creds.refresh(Request())except RefreshError:return Nonereturn credsdef 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 Nonereturn build("drive", "v3", credentials=creds)10 unmodified linesreturn []try:query = f"'{TRANSCRIPTS_FOLDER_ID}' in parents and trashed=false"results = service.files().list(q=query,spaces='drive',64 unmodified linestry: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,20 unmodified linestry:# Search for files matching pattern: researcher_name_*_state.jsonquery = (f"'{TRANSCRIPTS_FOLDER_ID}' in parents and "f"name contains '{researcher_name}' and "f"name contains '_state.json' and "f"trashed=false"12345678910111213141516171819202122232425262728293031323334353 unmodified lines3940414243444546474849505152535455565758596061626364656667686970717273747510 unmodified lines8687888990919264 unmodified lines15715815916016116216316416516616716816917020 unmodified lines191192193194195196197"""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 annotationsimport ioimport jsonimport osfrom datetime import datetimefrom pathlib import Pathfrom typing import Optionalfrom google.oauth2.service_account import Credentialsfrom googleapiclient.discovery import buildfrom 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"3 unmodified lines# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# 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:raise RuntimeError("Invalid GOOGLE_SERVICE_ACCOUNT_JSON") from epath = 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"))return Nonedef get_drive_service(_: str = "") -> Optional[object]:"""Return an authenticated Drive service (service-account), else None."""info = _service_account_info()if not info:return Nonecreds = Credentials.from_service_account_info(info, scopes=SCOPES)return build("drive", "v3", credentials=creds)10 unmodified linesreturn []try:query = f"'{_folder_id()}' in parents and trashed=false"results = service.files().list(q=query,spaces='drive',64 unmodified linestry: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,20 unmodified linestry:# Search for files matching pattern: researcher_name_*_state.jsonquery = (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