Lara Monteagudo Tubau commited on
Commit ·
e612a97
1
Parent(s): 6dc4dd3
feat: full session resume — persist file_id, re-parse on load, cache Agent 1b
Browse files1290 unmodified lines129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133620 unmodified lines135713581359136013611362638 unmodified lines2001200220032004200520061842 unmodified lines38493850385138523853385438551290 unmodified linesdef 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", "") or _auto_session_id(rid, "restored_session")new_state["session_id"] = sidreturn (new_state,_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, _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(drive_choice: str, researcher_id: str, state: dict):20 unmodified linestemp_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:raise638 unmodified linesstate["section_boundaries"][sec["section_id"]] = boundariesstate["section_segments"][sec["section_id"]] = segmentsyield (state,_loading_card("Loading coding stage…", f"Agent 1b is preparing {len(segments)} episode(s) for coding."),1842 unmodified linesload_prev_btn.click(fn=fn_load_previous_session,inputs=[researcher_id_box, state],outputs=[state, process_status],)process_btn.click(fn=fn_process_with_source,1290 unmodified lines1291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142720 unmodified lines14481449145014511452145314541455145614571458638 unmodified lines20972098209921002101210221032104210521062107210821092110211121122113211421151842 unmodified lines39583959396039613962396339641290 unmodified linesdef fn_load_previous_session(researcher_id: str, state: dict):"""Generator: load saved session from Drive, re-parse transcript, navigate to screener.Outputs: PARSE_OUTPUTS (state, pipeline_bar_html, process_status, process_btn,screener_summary_html, screener_turns_html_c, screener_to_sections_btn, *ALL_PAGES)"""rid = (researcher_id or "").strip()def _bail(msg: str, kind: str = "warning"):yield (state, _pipeline_bar_html(state),_status_card(msg, kind), _BTN_FREE,"", "", gr.update(visible=False), *_show("setup"))if not rid:yield from _bail("Enter Researcher ID first.")return# ── Step 1: initial feedback ──────────────────────────────────────────────yield (state, _pipeline_bar_html(state),_status_card("Connecting to Drive…", "info"), _BTN_BUSY,"", "", gr.update(visible=False), *_show("setup"))try:service = get_drive_service(rid)except Exception as e:yield from _bail(f"Drive connection failed: {e}", "error")returnif not service:yield from _bail("Drive not configured — check GOOGLE_CREDENTIALS.", "warning")return# ── Step 2: load saved state ──────────────────────────────────────────────yield (state, _pipeline_bar_html(state),_status_card("Loading saved session…", "info"), _BTN_BUSY,"", "", gr.update(visible=False), *_show("setup"))try:loaded = load_session_from_drive(service, rid)except Exception as e:diag = format_drive_diagnostic("load_previous_session", researcher_id=rid, error=e)print(diag, file=_sys.stderr)yield from _bail(f"Could not load Drive session: {e}", "error")returnif not loaded:yield from _bail("No previous session found for this researcher ID.", "warning")returnnew_state = _empty_state()new_state.update(loaded)new_state["researcher_id"] = ridsid = new_state.get("session_id") or _auto_session_id(rid, "restored_session")new_state["session_id"] = sid# ── Step 3: re-parse transcript to restore `turns` ────────────────────────drive_file_id = new_state.get("_drive_file_id")source_name = new_state.get("_source_file_name", "transcript.vtt")if drive_file_id:yield (new_state, _pipeline_bar_html(new_state),_status_card(f"Re-parsing '{source_name}' to restore transcript…", "info"),_BTN_BUSY, "", "", gr.update(visible=False), *_show("setup"))try:text = read_file_from_drive(service, drive_file_id)suffix = Path(source_name).suffix or ".vtt"tmp = Path(tempfile.mktemp(suffix=suffix))tmp.write_text(text, encoding="utf-8")parsed = parse_transcript(str(tmp))new_state["turns"] = parsed.get("turns", [])new_state["speakers"] = parsed.get("speakers", new_state.get("speakers", {}))try:tmp.unlink()except Exception:passexcept Exception as e:yield from _bail(f"Could not re-parse transcript: {e}. ""Re-upload the file manually to continue.", "warning")returnelse:# No file_id stored (old session or local upload) — warn, turns unavailablegr.Warning("Transcript not available for re-parsing — turns will be missing. ""Re-upload the file to restore the full view.")# ── Step 4: build resume summary card ────────────────────────────────────n_turns = len(new_state.get("turns", []))n_sections = len(new_state.get("sections", []))n_codings = len(new_state.get("codings", {}))stage_map = {"complete": "All sections coded ✓","coding": "Coding in progress","sectioned": "Sections detected, boundaries pending","parsed": "Transcript parsed, screener run",}stage_label = stage_map.get(new_state.get("stage", ""), "Screener complete")sum_html = ('<div style="background:#f0fdf4;border:2px solid #86efac;border-radius:10px;''padding:16px;font-family:system-ui,sans-serif">''<div style="font-weight:700;color:#166534;font-size:1.05em;margin-bottom:10px">''✓ Session Resumed</div>''<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-bottom:10px">'f'<div style="text-align:center"><div style="font-size:1.7em;font-weight:800;color:#15803d">{n_turns}</div>''<div style="font-size:0.75em;color:#4b5563">Turns</div></div>'f'<div style="text-align:center"><div style="font-size:1.7em;font-weight:800;color:#15803d">{n_sections}</div>''<div style="font-size:0.75em;color:#4b5563">Sections</div></div>'f'<div style="text-align:center"><div style="font-size:1.7em;font-weight:800;color:#15803d">{n_codings}</div>''<div style="font-size:0.75em;color:#4b5563">Episodes coded</div></div>''</div>'f'<div style="font-size:0.85em;color:#374151">Stage: <strong>{stage_label}</strong>'f' · Session: <code style="background:#dcfce7;padding:1px 5px;border-radius:3px">{sid}</code></div>''<div style="margin-top:8px;font-size:0.78em;color:#6b7280">''Click <strong>Detect Sections →</strong> to continue — sections and boundaries ''are loaded from your saved session (no LLM re-run).</div>''</div>')gr.Info(f"Session resumed: {n_sections} sections · {n_codings} episodes coded.")yield (new_state,_pipeline_bar_html(new_state),_status_card(f"Session loaded · {n_turns} turns · {n_sections} sections · {n_codings} coded","success", {"Session": sid}),_BTN_FREE,sum_html,"", # screener_turns_html_c (no turn detail on resume)gr.update(visible=True), # screener_to_sections_btn — clicking uses cached sections*_show("screener"),)def fn_process_with_source(drive_choice: str, researcher_id: str, state: dict):20 unmodified linestemp_path = Path(tempfile.mktemp(prefix="drive_transcript_", suffix=suffix))temp_path.write_text(text, encoding="utf-8")# Store Drive source so we can re-parse on session resumestate = dict(state)state["_drive_file_id"] = file_idstate["_source_file_name"] = file_nameeffective_file = type("DriveFile", (), {"name": str(temp_path)})()except gr.Error:raise638 unmodified linesstate["section_boundaries"][sec["section_id"]] = boundariesstate["section_segments"][sec["section_id"]] = segments# ── Agent 1b cache: if proposals already exist for this section, skip LLM ─cached_coded = state.get("section_segments_coded", {}).get(sec["section_id"])if cached_coded:state["section_stages"][sec["section_id"]] = "coding"state["coding_idx"] = 0n_uncertain = sum(1 for s in cached_coded if s.get("uncertain"))msg = f"✓ {len(cached_coded)} episodes (cached — no LLM re-run)."if n_uncertain:msg += f" **{n_uncertain} flagged ⚠**"gr.Info(f"Using cached Agent 1b proposals ({len(cached_coded)} episodes).")yield state, msg, gr.update(visible=True), *_render_coding(state), _agent_log_html(state.get("agent_logs", []))returnyield (state,_loading_card("Loading coding stage…", f"Agent 1b is preparing {len(segments)} episode(s) for coding."),1842 unmodified linesload_prev_btn.click(fn=fn_load_previous_session,inputs=[researcher_id_box, state],outputs=PARSE_OUTPUTS,)process_btn.click(fn=fn_process_with_source,
app.py+139-30