Lara Monteagudo Tubau commited on
Commit ·
77b1d4b
1
Parent(s): 201f02a
Make Drive transcript flow sessionless and add loading states
Browse files994 unmodified lines99599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019234 unmodified lines125412551256123812571258125912601261124212621263126412651266124812671268126912701 unmodified line12721273127412561257127512761277127812601261126212631264126512661267126812691279128012811282128312841271127212731274127512761277127812791280128112821283128412851286128712881289129012911292128512861287128812891294129012911292129312941295129612971298129612971299130013011302130313041305130613071308130913101311131213131314131513161317131813199 unmodified lines13291330133113131332133313151334133513361337133813201321133913401341134213433 unmodified lines134713481349133113321333135013511352135313541355135610 unmodified lines13671368136913521370137113721373137413751376137729 unmodified lines14071408140913911410141114121413382 unmodified lines179617971798179918001801180218031804180515 unmodified lines182118221823180118241825182618271828180618291830183118101832183318341835183618371838183918401841657 unmodified lines2499250025012474250225032504250553 unmodified lines255925602561253425352536256225632564256525662567256825422543256925702571257225732574257525502576257725782579258025812556255725582582258325842585258625872588258925902591441 unmodified lines30333034303530063036303730383039304030113041304230433044994 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 lines new_state = _empty_state() new_state.update(loaded) new_state["researcher_id"] = rid sid = new_state.get("session_id", "") sid = new_state.get("session_id", "") or _auto_session_id(rid, "restored_session") new_state["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( 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(file_obj, drive_choice: str, session_id: str, researcher_id: str, state: dict): """Wrapper: accept either local upload or Drive dropdown selection."""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 = None service = None effective_file = file_obj
if 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.") rid = (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.")
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, ) 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 file could not be read. Copy the DRIVE DEBUG block from the logs.") 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")
if effective_file is None: raise gr.Error("Upload a transcript or choose one from Drive.") 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.")
final_state: dict | None = None try:9 unmodified lines pass
# Persist lightweight state snapshot to Drive for resume. if final_state and (service or get_drive_service((researcher_id or "").strip())): if final_state and (service or get_drive_service(rid)): try: svc = service or get_drive_service((researcher_id or "").strip()) 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", researcher_id.strip()), final_state.get("session_id", session_id.strip()), 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("Upload a transcript file first.") if not session_id.strip(): raise gr.Error("Enter a Session ID (e.g. dyad_01).") 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-submission yield _setup_yield("Reading transcript file…") yield _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 work yield _setup_yield( f"Parsed {len(turns)} turns from {len(speakers)} speaker(s). Starting Agent 0…", f"Parsed {len(turns)} turns from {len(speakers)} speaker(s). Preparing Agent 0…", "processing", {"Turns": len(turns), "Speakers": ", ".join(speakers), "Duration": duration}, )382 unmodified lines if 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_id
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"]) segments = boundaries_to_segments(sec, turns, boundaries, 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"]] = boundaries state["section_segments"][sec["section_id"]] = segments
yield state, f"⏳ Agent 1b coding {len(segments)} episode(s)…", gr.update(visible=False), *CODING_EMPTY, "" yield ( 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">Upload a Zoom transcript, let AI detect ' '<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 lines gr.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.' 'Choose a transcript from Google Drive, then start coding. ' 'Session IDs are generated automatically and saved for you.' '</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) 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)", label="Google Drive transcript", choices=[], interactive=False, ) drive_status_html = gr.HTML()
transcript_file = gr.File( label="Transcript file (.txt, .vtt, .json)", file_types=[".txt", ".vtt", ".json"], 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 lines load_prev_btn.click( fn=fn_load_previous_session, inputs=[researcher_id_box, state], outputs=[state, session_id_box, process_status], outputs=[state, process_status], )
process_btn.click( fn=fn_process_with_source, inputs=[transcript_file, drive_file_dropdown, session_id_box, researcher_id_box, state], inputs=[drive_file_dropdown, researcher_id_box, state], outputs=PROCESS_OUTPUTS, )
app.py+94-64