Lara Monteagudo Tubau commited on
Commit Β·
201f02a
1
Parent(s): 673acc0
Add copyable Drive debug diagnostics for troubleshooting
Browse filesFiles changed (2)
- app.py+107-50
- drive_utils.py+66-10
28 unmodified lines2930313233341125 unmodified lines1160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812194 unmodified lines1224122512261227122812291230123112321233123412351236123712381239124028 unmodified lineswrite_session_to_drive,load_session_from_drive,register_researcher,)from kappa_calculator import (calculate_kappa_report,1125 unmodified lines)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):4 unmodified linesif 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.")28 unmodified lines293031323334351125 unmodified lines1161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512564 unmodified lines126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129728 unmodified lineswrite_session_to_drive,load_session_from_drive,register_researcher,format_drive_diagnostic,)from kappa_calculator import (calculate_kappa_report,1125 unmodified lines)register_researcher(rid)try: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","Tip": "Copy the DRIVE DEBUG block from the logs if this should already be working.",},),)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",{"Tip": "If this is unexpected, copy the DRIVE DEBUG block from the logs."},),)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)}),)except Exception as e:diag = format_drive_diagnostic("refresh_drive_transcripts", researcher_id=rid, error=e)print(diag, file=_sys.stderr)return (gr.update(choices=[], value=None, interactive=False),_status_card("Drive check failed.","error",{"Tip": "Copy the DRIVE DEBUG block below and send it with the issue."},diag,),)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")try:service = get_drive_service(rid)if not service:return state, gr.update(), _status_card("Drive not configured yet.","warning",{"Tip": "Copy the DRIVE DEBUG block from the logs if this should already work."},)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",{"Tip": "If you expected one, copy the DRIVE DEBUG block from the logs."},)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}),)except Exception as e:diag = format_drive_diagnostic("load_previous_session", researcher_id=rid, error=e)print(diag, file=_sys.stderr)return state, gr.update(), _status_card("Could not load the Drive session.","error",{"Tip": "Copy the DRIVE DEBUG block below and send it with the issue."},diag,)def fn_process_with_source(file_obj, drive_choice: str, session_id: str, researcher_id: str, state: dict):4 unmodified linesif effective_file is None and drive_choice:rid = (researcher_id or "").strip()try:service = get_drive_service(rid)if not service:diag = format_drive_diagnostic("process_drive_file", researcher_id=rid)print(diag, file=_sys.stderr)raise gr.Error("Drive is not configured. Copy the DRIVE DEBUG block from the logs.")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)})()except gr.Error:raiseexcept Exception as e:file_id, file_name = ("", "")try:file_id, file_name = _parse_drive_choice(drive_choice)except Exception:passdiag = format_drive_diagnostic("process_drive_file",researcher_id=rid,file_id=file_id,file_name=file_name,error=e,)print(diag, file=_sys.stderr)raise gr.Error("Drive file could not be read. Copy the DRIVE DEBUG block from the logs.")if effective_file is None:raise gr.Error("Upload a transcript or choose one from Drive.")
13 unmodified lines14151617181920212215 unmodified lines3839404142438 unmodified lines5253545556575859606162636465666768697071724 unmodified lines777879808182838434 unmodified lines11912012112212312412517 unmodified lines14314414514614714833 unmodified lines18218318418518618742 unmodified lines23023123223323423523613 unmodified linesimport ioimport jsonimport osfrom datetime import datetimefrom pathlib import Pathfrom typing import Optionalfrom google.oauth2.service_account import Credentialsfrom googleapiclient.discovery import build15 unmodified linesSESSION_METADATA_FILE = TOKENS_CACHE_DIR / "session_metadata.json"# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Credentials / service bootstrap# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ8 unmodified linestry:return json.loads(raw)except json.JSONDecodeError as e:# Log warning but don't crash; Drive features will be unavailableimport sysprint(f"β οΈ GOOGLE_SERVICE_ACCOUNT_JSON is invalid JSON. Drive features disabled.", file=sys.stderr)return Nonepath = os.environ.get("GOOGLE_SERVICE_ACCOUNT_FILE", "").strip()if path:p = Path(path)if not p.exists():print(f"β οΈ GOOGLE_SERVICE_ACCOUNT_FILE not found: {path}. Drive features disabled.", file=sys.stderr)return Nonetry:return json.loads(p.read_text(encoding="utf-8"))except json.JSONDecodeError as e:print(f"β οΈ GOOGLE_SERVICE_ACCOUNT_FILE is invalid JSON. Drive features disabled.", file=sys.stderr)return Nonereturn None4 unmodified linesinfo = _service_account_info()if not info:return Nonecreds = Credentials.from_service_account_info(info, scopes=SCOPES)return build("drive", "v3", credentials=creds)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ34 unmodified linestranscripts.sort(key=lambda x: x["modified_time"], reverse=True)return transcriptsexcept Exception as e:print(f"[Drive] Error listing transcripts: {e}")return []17 unmodified linesfile_obj.seek(0)return file_obj.read().decode('utf-8')except Exception as e:raise RuntimeError(f"Error reading file from Drive: {e}")33 unmodified linesreturn file.get('id')except Exception as e:raise RuntimeError(f"Error writing session to Drive: {e}")42 unmodified linesfile_obj.seek(0)return json.loads(file_obj.read().decode('utf-8'))except Exception as e:print(f"[Drive] Error loading session: {e}")return None13 unmodified lines141516171819202122232415 unmodified lines4041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878 unmodified lines969798991001011021031041051061071081091101111121131141151161174 unmodified lines12212312412512612712812913013113213334 unmodified lines16816917017117217317417 unmodified lines19219319419519619719833 unmodified lines23223323423523623723823924024124224342 unmodified lines28628728828929029129213 unmodified linesimport ioimport jsonimport osimport sysimport tracebackfrom datetime import datetimefrom pathlib import Pathfrom typing import Any, Optionalfrom google.oauth2.service_account import Credentialsfrom googleapiclient.discovery import build15 unmodified linesSESSION_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# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ8 unmodified linestry:return json.loads(raw)except json.JSONDecodeError as e:_log_drive_diagnostic("load_service_account_info", error=e)return Nonepath = 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 Nonetry: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 Nonereturn None4 unmodified linesinfo = _service_account_info()if not info:return Nonetry: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# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ34 unmodified linestranscripts.sort(key=lambda x: x["modified_time"], reverse=True)return transcriptsexcept Exception as e:_log_drive_diagnostic("list_transcripts", error=e)return []17 unmodified linesfile_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}")33 unmodified linesreturn 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}")42 unmodified linesfile_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
app.py+107-50
drive_utils.py+66-10