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 lines293031323334351125 unmodified lines1161116211631164116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195116611671168116911701171117211731174119611971198117611771178119912001201120212031181120412051206120712081209121012111184118511861187118811891190119111921212121312141215121612171218119912001201121912201221122212231224122512261203120412051227122812291230123112321233123412071208120912101235123612371238123912121213121412151216124012411242124312441245124612471248124912501251125212531254125512564 unmodified lines12611262126312641265126612271228122912301231123212331234123512361237126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129728 unmodified lines write_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: 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=[], 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", }, ), gr.update(choices=choices, value=choices[0][1], interactive=True), _status_card("Drive connected. Select a transcript and click Process.", "success", {"Files": len(choices)}), )
files = list_transcripts(service) if not files: 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("No transcript files found in the configured Drive folder.", "warning"), _status_card( "Drive check failed.", "error", {"Tip": "Copy the DRIVE DEBUG block below and send it with the issue."}, diag, ), )
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")
try: service = get_drive_service(rid) if not service: return state, gr.update(), _status_card("Drive not configured yet.", "warning") 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") 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"] = rid sid = new_state.get("session_id", "") 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}), ) 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 lines
if effective_file is None and drive_choice: rid = (researcher_id or "").strip() try: service = get_drive_service(rid) if not service: 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)})() 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: raise except Exception as e: file_id, file_name = ("", "") try: file_id, file_name = _parse_drive_choice(drive_choice) except Exception: pass diag = 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 lines14151617181920192122232415 unmodified lines4041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878 unmodified lines9697985556579910010110210310410564106107108109110111112113691141151161174 unmodified lines122123124125808112612712812913013113213334 unmodified lines16816917012217117217317417 unmodified lines19219319419519619719833 unmodified lines23223323423523623723823924024124224342 unmodified lines28628728823328929029129213 unmodified linesimport ioimport jsonimport osimport sysimport tracebackfrom datetime import datetimefrom pathlib import Pathfrom typing import Optionalfrom typing import Any, Optional
from 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 lines try: return json.loads(raw) except json.JSONDecodeError as e: # Log warning but don't crash; Drive features will be unavailable import sys print(f"β οΈ GOOGLE_SERVICE_ACCOUNT_JSON is invalid JSON. Drive features disabled.", file=sys.stderr) _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(): print(f"β οΈ GOOGLE_SERVICE_ACCOUNT_FILE not found: {path}. Drive features disabled.", file=sys.stderr) _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: print(f"β οΈ GOOGLE_SERVICE_ACCOUNT_FILE is invalid JSON. Drive features disabled.", file=sys.stderr) _log_drive_diagnostic("load_service_account_file", extra={"path": path, "exists": True}, error=e) return None
return None4 unmodified lines 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) 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 lines transcripts.sort(key=lambda x: x["modified_time"], reverse=True) return transcripts except Exception as e: print(f"[Drive] Error listing transcripts: {e}") _log_drive_diagnostic("list_transcripts", error=e) return []
17 unmodified lines 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}")
33 unmodified lines 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}")
42 unmodified lines file_obj.seek(0) return json.loads(file_obj.read().decode('utf-8')) except Exception as e: print(f"[Drive] Error loading session: {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