Lara Monteagudo Tubau commited on
Commit ·
77b1d4b
1
Parent(s): 201f02a
Make Drive transcript flow sessionless and add loading states
Browse files994 unmodified lines9959969979989991000234 unmodified lines123512361237123812391240124112421243124412451246124712481249125012511 unmodified line1253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913009 unmodified lines1310131113121313131413151316131713181319132013211322132313243 unmodified lines1328132913301331133213331334133513361337133810 unmodified lines134913501351135213531354135513561357135829 unmodified lines1388138913901391139213931394382 unmodified lines17771778177917801781178215 unmodified lines1798179918001801180218031804180518061807180818091810181118121813657 unmodified lines247124722473247424752476247753 unmodified lines2531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561441 unmodified lines300330043005300630073008300930103011301230133014994 unmodified lines}def _session_dir(state: dict) -> Path:return SESSIONS_ROOT / state["session_id"]234 unmodified linesnew_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."},1 unmodified line)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()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.")final_state: dict | None = Nonetry:9 unmodified linespass# 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:3 unmodified linesdef 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:raise gr.Error("Upload a transcript file first.")if not session_id.strip():raise gr.Error("Enter a Session ID (e.g. dyad_01).")if not researcher_id.strip():raise gr.Error("Enter your Researcher ID (e.g. R1).")_BTN_BUSY = gr.update(interactive=False, value="⏳ Processing…")_BTN_FREE = gr.update(interactive=True, value="⚡ Process Transcript →")10 unmodified lines)# Immediately disable the button to prevent double-submissionyield _setup_yield("Reading transcript file…")t0 = time.perf_counter()try:turns = parse_transcript(file_obj.name)except Exception as e:raise gr.Error(f"Could not parse transcript: {e}") from e29 unmodified lines# Confirm parse before starting LLM workyield _setup_yield(f"Parsed {len(turns)} turns from {len(speakers)} speaker(s). Starting Agent 0…","processing",{"Turns": len(turns), "Speakers": ", ".join(speakers), "Duration": duration},)382 unmodified linesif not sec:raise gr.Error("No section loaded.")turns = _turns_for_section(state["turns"], sec)valid_ids = {t["turn_id"] for t in turns}boundaries: list[dict] = []15 unmodified lines"confidence": "high", "boundary_signal": "researcher_defined","rationale": "Set by researcher."})boundaries.sort(key=lambda b: b["after_turn_id"])segments = boundaries_to_segments(sec, turns, boundaries, state["session_id"])if not segments:raise gr.Error("No segments produced — check your boundary turn IDs.")state = dict(state)state["section_boundaries"][sec["section_id"]] = boundariesstate["section_segments"][sec["section_id"]] = segmentsyield state, f"⏳ Agent 1b coding {len(segments)} episode(s)…", gr.update(visible=False), *CODING_EMPTY, ""agent1a_result = state.get("section_a1a_results", {}).get(sec["section_id"])t0 = time.perf_counter()657 unmodified lines'<div class="cc-entry-card">''<span class="cc-entry-kicker">Primary workflow</span>''<h3 class="cc-entry-title">Code a Transcript</h3>''<p class="cc-entry-desc">Upload a Zoom transcript, let AI detect ''sections and episode boundaries, then code each segment ''against the D1–D9 collaborative learning dimensions.</p>''</div>'53 unmodified linesgr.HTML('<div class="cc-setup-box">''<p style="margin:0;font-size:0.9em;color:#334155;line-height:1.6">''Both researchers should run the full pipeline independently on the ''<strong>same transcript file</strong>. ''Use the same Session ID so your files can be compared in the Agreement check.''</p>''</div>')with gr.Row():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, .vtt, .json)",file_types=[".txt", ".vtt", ".json"],)process_btn = gr.Button("⚡ Process Transcript →", variant="primary")441 unmodified linesload_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,)994 unmodified lines99599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019234 unmodified lines125412551256125712581259126012611262126312641265126612671268126912701 unmodified line1272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813199 unmodified lines1329133013311332133313341335133613371338133913401341134213433 unmodified lines134713481349135013511352135313541355135610 unmodified lines1367136813691370137113721373137413751376137729 unmodified lines1407140814091410141114121413382 unmodified lines179617971798179918001801180218031804180515 unmodified lines182118221823182418251826182718281829183018311832183318341835183618371838183918401841657 unmodified lines249925002501250225032504250553 unmodified lines255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591441 unmodified lines303330343035303630373038303930403041304230433044994 unmodified lines}def _auto_session_id(researcher_id: str = "", source_name: str = "") -> str:stamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")base = (Path(source_name).stem or "drive").replace(" ", "_")rid = (researcher_id or "R").strip().replace(" ", "_")return f"{rid}_{base}_{stamp}"def _loading_card(title: str, subtitle: str = "Please wait…", spin: str = "◐") -> str:return ('<div style="background:#eff6ff;border:2px solid #93c5fd;border-radius:12px;''padding:18px 20px;margin:10px 0;font-family:system-ui,sans-serif">''<div style="display:flex;align-items:center;gap:12px">'f'<div style="font-size:1.35em;color:#1e3a8a">{spin}</div>'f'<div><div style="font-weight:800;color:#1e3a8a;font-size:1.02em">{_h(title)}</div>'f'<div style="margin-top:4px;font-size:0.86em;color:#475569">{_h(subtitle)}</div></div>''</div></div>')def _session_dir(state: dict) -> Path:return SESSIONS_ROOT / state["session_id"]234 unmodified linesnew_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."},1 unmodified line)def fn_process_with_source(drive_choice: str, researcher_id: str, state: dict):"""Wrapper: Drive-only transcript selection with automatic session IDs."""temp_path: Path | None = Noneservice = Nonerid = (researcher_id or "").strip()if not rid:raise gr.Error("Enter your Researcher ID first.")if not drive_choice:raise gr.Error("Choose a transcript from Drive first.")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)session_id = _auto_session_id(rid, file_name)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.")final_state: dict | None = Nonetry:9 unmodified linespass# Persist lightweight state snapshot to Drive for resume.if final_state and (service or get_drive_service(rid)):try:svc = service or get_drive_service(rid)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", rid),final_state.get("session_id", session_id),slim,)except Exception:3 unmodified linesdef 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:raise gr.Error("Choose a transcript from Drive first.")if not researcher_id.strip():raise gr.Error("Enter your Researcher ID (e.g. R1).")session_id = session_id.strip() or _auto_session_id(researcher_id, getattr(file_obj, "name", "drive_transcript"))_BTN_BUSY = gr.update(interactive=False, value="⏳ Processing…")_BTN_FREE = gr.update(interactive=True, value="⚡ Process Transcript →")10 unmodified lines)# Immediately disable the button to prevent double-submissionyield _setup_yield("Loading transcript from Drive…")t0 = time.perf_counter()try:yield _setup_yield("Parsing transcript…", details={"Session": session_id})turns = parse_transcript(file_obj.name)except Exception as e:raise gr.Error(f"Could not parse transcript: {e}") from e29 unmodified lines# Confirm parse before starting LLM workyield _setup_yield(f"Parsed {len(turns)} turns from {len(speakers)} speaker(s). Preparing Agent 0…","processing",{"Turns": len(turns), "Speakers": ", ".join(speakers), "Duration": duration},)382 unmodified linesif not sec:raise gr.Error("No section loaded.")session_id = state.get("session_id") or _auto_session_id(state.get("researcher_id", ""), sec.get("label", "section"))state = dict(state)state["session_id"] = session_idturns = _turns_for_section(state["turns"], sec)valid_ids = {t["turn_id"] for t in turns}boundaries: list[dict] = []15 unmodified lines"confidence": "high", "boundary_signal": "researcher_defined","rationale": "Set by researcher."})boundaries.sort(key=lambda b: b["after_turn_id"])segments = boundaries_to_segments(sec, turns, boundaries, session_id)if not segments:raise gr.Error("No segments produced — check your boundary turn IDs.")state["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."),gr.update(visible=False),*CODING_EMPTY,"",)agent1a_result = state.get("section_a1a_results", {}).get(sec["section_id"])t0 = time.perf_counter()657 unmodified lines'<div class="cc-entry-card">''<span class="cc-entry-kicker">Primary workflow</span>''<h3 class="cc-entry-title">Code a Transcript</h3>''<p class="cc-entry-desc">Choose a Zoom transcript from Drive, let AI detect ''sections and episode boundaries, then code each segment ''against the D1–D9 collaborative learning dimensions.</p>''</div>'53 unmodified linesgr.HTML('<div class="cc-setup-box">''<p style="margin:0;font-size:0.9em;color:#334155;line-height:1.6">''Choose a transcript from Google Drive, then start coding. ''Session IDs are generated automatically and saved for you.''</p>''</div>')with gr.Row():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",choices=[],interactive=False,)drive_status_html = gr.HTML()gr.HTML('<div class="cc-callout">''<strong>Drive-only workflow:</strong> refresh the list, select one transcript, ''and click <em>Process Transcript</em>. ''The app will create a session ID automatically and show loading screens as it moves ''through parsing, section detection, boundary review, and coding.''</div>')process_btn = gr.Button("⚡ Process Transcript →", variant="primary")441 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,inputs=[drive_file_dropdown, researcher_id_box, state],outputs=PROCESS_OUTPUTS,)
app.py+94-64