diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -1,18 +1,8 @@ """ -app.py (v5) — CollabCode Research Interface -============================================= -Full redesign: tab-based layout, persistent pipeline status, -metacognitive screener view, inline label editing, Tier 1/2/3 lexicon editor. - -Tabs: - 1. Session — setup, transcript upload / Drive - 2. Screener — metacognitive turn scanner (pre-LLM, editable) - 3. Sections — Agent 0 structural sectioning - 4. Pipeline — Agent 1a/1b coding with live stream - 5. Review — inspect + edit coded segments inline - 6. Agreement — IRR (Gwet AC1 / kappa), disagreement resolution - 7. Lexicon — Tier 1 (locked) · Tier 2 (validated) · Tier 3 (candidates) - 8. Learning — Agent 2 rule review +app.py (v4) — CollabCode Researcher Interface +============================================== +Page-based flow: Welcome → Setup → Sections → Pipeline → Done → Agreement → Library +No tabs. One task per screen. """ from __future__ import annotations @@ -20,8 +10,6 @@ from __future__ import annotations import json import html as html_lib import queue as _queue -import sys as _sys -import importlib.metadata as _meta import tempfile import threading import time @@ -32,71 +20,99 @@ import gradio as gr from transcript_parser import parse_transcript from agent0_sectioner import run_sectioning -from agent1a_boundary import propose_boundaries, boundaries_to_segments -from agent1b_coder import code_section from metacog_screener import ( - screen_transcript, result_to_dict, save_screener_result, + screen_transcript, result_to_dict, add_tier2_term, propose_tier3_candidate, approve_tier3_candidate, reject_tier3_candidate, load_full_lexicon, ) +from agent1a_boundary import propose_boundaries, boundaries_to_segments +from agent1b_coder import code_section from drive_utils import ( - get_drive_service, list_transcripts, read_file_from_drive, - write_session_to_drive, load_session_from_drive, - register_researcher, format_drive_diagnostic, + get_drive_service, + list_transcripts, + read_file_from_drive, + write_session_to_drive, + load_session_from_drive, + register_researcher, + format_drive_diagnostic, ) from kappa_calculator import ( - calculate_kappa_report, resolve_disagreement, discard_disagreement, + calculate_kappa_report, + resolve_disagreement, + discard_disagreement, ) from agent2_learner import list_pending_rules, approve_rule, reject_rule from pipeline import ( - run_boundaries_parallel, run_coding_with_context, - render_pipeline_stats_html, PipelineStats, + run_boundaries_parallel, + run_coding_with_context, + render_pipeline_stats_html, + PipelineStats, ) from llm_client import circuit_state, compute_timeout from sequential_analysis import ( - load_and_analyse, render_transition_matrix_html, + load_and_analyse, + render_transition_matrix_html, render_significant_transitions_html, - to_csv as seq_to_csv, lag_to_csv, + to_csv as seq_to_csv, + lag_to_csv, ) SESSIONS_ROOT = Path("sessions") SESSIONS_ROOT.mkdir(parents=True, exist_ok=True) -_STYLES_DIR = Path(__file__).parent / "static" / "styles" +_STYLES_DIR = Path(__file__).parent / "static" / "styles" MODEL_ID = "Qwen/Qwen2.5-72B-Instruct" TEMPERATURE = 0.1 +import sys as _sys, importlib.metadata as _meta def _startup_log() -> None: + import gradio as _gr try: hf_ver = _meta.version("huggingface_hub") except Exception: hf_ver = "unknown" hf_tok = "SET" if __import__("os").environ.get("HF_TOKEN") else "MISSING ⚠" print("=" * 60) - print(" CollabCode v5 — startup") + print(" CollabCode v4 — startup") print("=" * 60) - print(f" Python : {_sys.version.split()[0]}") - print(f" HF_TOKEN : {hf_tok}") - print(f" Sessions : {SESSIONS_ROOT.resolve()}") - print(f" Model : {MODEL_ID}") + print(f" Python : {_sys.version.split()[0]}") + print(f" Gradio : {_gr.__version__}") + print(f" HF hub : {hf_ver}") + print(f" HF_TOKEN : {hf_tok}") + print(f" Sessions root: {SESSIONS_ROOT.resolve()}") + print(f" Model : {MODEL_ID}") print("=" * 60) - _startup_log() def _load_css() -> str: + scss_entry = _STYLES_DIR / "main.scss" + if scss_entry.exists(): + try: + import subprocess + result = subprocess.run( + ["sass", str(scss_entry), "--style=expanded", + "--load-path", str(_STYLES_DIR), "--no-source-map"], + capture_output=True, text=True, timeout=30, + ) + if result.returncode == 0 and result.stdout: + css = result.stdout + (_STYLES_DIR / "main.css").write_text(css, encoding="utf-8") + return css + except (FileNotFoundError, subprocess.TimeoutExpired): + pass compiled = _STYLES_DIR / "main.css" if compiled.exists(): return compiled.read_text(encoding="utf-8") return "" -# ────────────────────────────────────────────────────────────────────────────── -# Dimension system (D1-D9 + SSRL metacog phases) -# ────────────────────────────────────────────────────────────────────────────── +# --------------------------------------------------------------------------- +# Design system — dimensions +# --------------------------------------------------------------------------- DIMENSIONS = [ ("D1", "Sustaining Mutual Understanding", @@ -122,46 +138,29 @@ DIMENSIONS = [ ("NA", "Not Applicable", "Doesn't fit any dimension: off-topic, administrative, or technical noise."), ] - -# SSRL metacognitive phases — shown alongside D1-D9 in Review tab -SSRL_PHASES = [ - ("M-MON", "Metacognitive Monitoring", "#ff5a3d", "#fff5f2"), - ("M-REG", "Metacognitive Regulation", "#065f46", "#ecfdf5"), - ("CO-REG", "Co-Regulation", "#b45309", "#fffbeb"), - ("SSRL", "Socially Shared Regulation", "#7c2d12", "#fff5f2"), - ("NONE", "Not Metacognitive", "#64748b", "#f8fafc"), -] - DIM_CHOICES = [f"{d} — {l}" for d, l, _ in DIMENSIONS] DIM_ID_FROM_CHOICE = {f"{d} — {l}": d for d, l, _ in DIMENSIONS} DIM_DESC_FROM_ID = {d: desc for d, _, desc in DIMENSIONS} -SSRL_CHOICES = [f"{p} — {l}" for p, l, _, _ in SSRL_PHASES] -SSRL_ID_FROM_CHOICE = {f"{p} — {l}": p for p, l, _, _ in SSRL_PHASES} -SSRL_COLOR_FROM_ID = {p: (c, bg) for p, _, c, bg in SSRL_PHASES} - SEC_NONE = "None — single dimension only" SEC_DIM_CHOICES = [SEC_NONE] + DIM_CHOICES SEC_ID_FROM_CHOICE = {SEC_NONE: None, **DIM_ID_FROM_CHOICE} + +# --------------------------------------------------------------------------- +# Speaker palette +# --------------------------------------------------------------------------- + SPEAKER_PALETTE = [ - ("#ff5a3d", "#fff5f2", "#ffc5b5", "🟠"), - ("#0e7490", "#ecfeff", "#a5f3fc", "🔷"), + ("#4338ca", "#eef2ff", "#c7d2fe", "🔵"), + ("#b45309", "#fffbeb", "#fde68a", "🟡"), ("#065f46", "#ecfdf5", "#a7f3d0", "🟢"), + ("#9a3412", "#fff7ed", "#fed7aa", "🟠"), ("#6b21a8", "#faf5ff", "#e9d5ff", "🟣"), - ("#b45309", "#fffbeb", "#fde68a", "🟡"), - ("#be123c", "#fff1f2", "#fecdd3", "🔴"), + ("#0e7490", "#ecfeff", "#a5f3fc", "🔷"), ] -# ────────────────────────────────────────────────────────────────────────────── -# Utility -# ────────────────────────────────────────────────────────────────────────────── - -def _h(s) -> str: - return html_lib.escape(str(s)) - - def _assign_speakers(turns: list[dict]) -> dict: seen: dict[str, dict] = {} for t in turns: @@ -179,172 +178,156 @@ def _speaker_avatar(name: str, entry: dict) -> str: return ( f'{initials}' + f'width:30px;height:30px;border-radius:50%;background:{entry["initials_bg"]};' + f'color:{entry["color"]};font-weight:800;font-size:0.72em;flex-shrink:0;' + f'border:1.5px solid {entry["color"]}20">{initials}' ) -def _seconds_to_hms(s: float) -> str: - return str(timedelta(seconds=int(s))) - - -_SPINNERS = ["◐", "◓", "◑", "◒"] - - -# ────────────────────────────────────────────────────────────────────────────── -# STATE -# ────────────────────────────────────────────────────────────────────────────── - -def _empty_state() -> dict: - return { - "session_id": "", - "researcher_id": "", - "turns": [], - "speakers": {}, - "sections": [], - "section_idx": 0, - "section_stages": {}, - "section_boundaries": {}, - "section_segments": {}, - "section_segments_coded": {}, - "coding_idx": 0, - "codings": {}, - "ssrl_codings": {}, # NEW: {segment_id: ssrl_phase_id} - "stage": "upload", - "kappa_report": None, - "agent_logs": [], - "screener_result": None, # NEW: serialised ScreenerResult dict - } - - -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 _session_dir(state: dict) -> Path: - return SESSIONS_ROOT / state["session_id"] - - -def _current_section(state: dict) -> dict | None: - secs = state.get("sections", []) - idx = state.get("section_idx", 0) - return secs[idx] if secs and idx < len(secs) else None - - -def _current_section_segments(state: dict) -> list[dict]: - sec = _current_section(state) - return state["section_segments_coded"].get(sec["section_id"], []) if sec else [] - - -def _turns_for_section(turns: list[dict], section: dict) -> list[dict]: - return [t for t in turns - if section["start_turn_id"] <= t["turn_id"] <= section["end_turn_id"]] - - -def _persist(state: dict) -> None: - try: - d = _session_dir(state) - d.mkdir(parents=True, exist_ok=True) - skip = {"turns", "kappa_report"} - (d / "app_state.json").write_text( - json.dumps({k: v for k, v in state.items() if k not in skip}, - indent=2, ensure_ascii=False), - encoding="utf-8", +def _format_turns_html(seg: dict, speaker_map: dict) -> str: + turns = seg.get("turns", []) + if not turns: + return '

No turns in this segment.

' + parts = [] + for t in turns: + sp = t.get("speaker", "?") + entry = speaker_map.get(sp, {"color": "#64748b", "bg": "#f8fafc", + "initials_bg": "#e2e8f0", "emoji": "○"}) + avatar = _speaker_avatar(sp, entry) + ts = _h(t.get("start_time", "")) + text = _h(t.get("text", "")) + turn_id = t.get("turn_id", "") + parts.append( + f'
' + f'{avatar}' + f'
' + f'
' + f'' + f'{_h(sp)}' + f'{ts}' + f'#{turn_id}' + f'
' + f'
{text}
' + f'
' ) - except Exception: - pass - - -def _push_log(state: dict, entry: dict) -> dict: - logs = list(state.get("agent_logs", [])) - logs.append(entry) - state["agent_logs"] = logs[-10:] - return state - - -def _make_log_entry(agent: str, runtime_s: float, **stats) -> dict: - return { - "agent": agent, - "model": MODEL_ID, - "temperature": TEMPERATURE, - "runtime_s": round(runtime_s, 1), - "timestamp": datetime.now(timezone.utc).strftime("%H:%M:%S"), - **stats, - } - - -# ────────────────────────────────────────────────────────────────────────────── -# Pipeline status header (always visible at top of every tab) -# ────────────────────────────────────────────────────────────────────────────── - -PIPELINE_STAGES = [ - ("upload", "Upload"), - ("screened", "Screen"), - ("sectioned", "Section"), - ("coded", "Code"), - ("reviewed", "Review"), - ("agreed", "Agreement"), - ("learned", "Learn"), -] + return f'
{"".join(parts)}
' -_STAGE_ORDER = [s for s, _ in PIPELINE_STAGES] +def _h(s) -> str: + return html_lib.escape(str(s)) -def _pipeline_status_html(state: dict) -> str: - current = state.get("stage", "upload") - session = _h(state.get("session_id", "—")) - turns = len(state.get("turns", [])) - try: - cur_idx = _STAGE_ORDER.index(current) - except ValueError: - cur_idx = 0 - steps = [] - for i, (stage, label) in enumerate(PIPELINE_STAGES): - if i < cur_idx: - bg, tc, border, dot = "#dcfce7", "#15803d", "#86efac", "✓" - elif i == cur_idx: - bg, tc, border, dot = "#fff5f2", "#ea4425", "#ff8c75", "▶" +def _section_cards_html(sections: list[dict], stages: dict, current_idx: int) -> str: + if not sections: + return "" + cards = [] + for i, s in enumerate(sections): + stage = stages.get(s["section_id"], "pending") + if stage == "done": + bc, fc, icon = "#86efac", "#065f46", "✓" + elif i == current_idx: + bc, fc, icon = "#93c5fd", "#1d4ed8", "▶" else: - bg, tc, border, dot = "#fafaf9", "#a8a29e", "#e7e5e4", "○" - steps.append( - f'
' - f'{dot}' - f'{label}' + bc, fc, icon = "#e2e8f0", "#94a3b8", "○" + n = s["end_turn_id"] - s["start_turn_id"] + 1 + cards.append( + f'
' + f'
' + f'{icon} {_h(s["label"])}
' + f'
' + f'{_h(s["start_time"])}–{_h(s["end_time"])} · {n} turns
' f'
' ) + return f'
{"".join(cards)}
' + + +def _episode_table_html(turns: list[dict], boundaries: list[dict]) -> str: + if not turns: + return '

No turns.

' + turn_ids = sorted(t["turn_id"] for t in turns) + bmap = {b["after_turn_id"]: b for b in boundaries} + cuts = [turn_ids[0]] + for b in sorted(boundaries, key=lambda x: x["after_turn_id"]): + idx = turn_ids.index(b["after_turn_id"]) if b["after_turn_id"] in turn_ids else -1 + if idx >= 0 and idx < len(turn_ids) - 1: + cuts.append(turn_ids[idx + 1]) + + rows = ( + "" + "Episode" + "Turns" + "Count" + "" + ) + for i, start in enumerate(cuts): + end = turn_ids[turn_ids.index(cuts[i + 1]) - 1] if i + 1 < len(cuts) else turn_ids[-1] + bg = "#f8fafc" if i % 2 else "white" + rows += ( + f'' + f'ep{i+1:02d}' + f'{start}–{end}' + f'{end-start+1}' + f'' + ) + if i < len(cuts) - 1: + after = cuts[i + 1] - 1 + b = bmap.get(after, {}) + sig = _h(b.get("boundary_signal", "boundary")) + conf = b.get("confidence", "?") + rat = _h(b.get("rationale", "")) + cc = {"high": "#065f46", "medium": "#b45309", "low": "#be123c"}.get(conf, "#64748b") + rows += ( + f'' + f'' + f'─── after turn {after} · {sig} · ' + f'{conf} confidence — {rat}' + f'' + ) + + n_ep = len(cuts) + n_b = len(boundaries) + return ( + f'
' + f'{n_b} boundary{"ies" if n_b!=1 else ""} → {n_ep} episode{"s" if n_ep!=1 else ""}' + f'
' + f'
' + f'{rows}
' + ) - screener = state.get("screener_result") - savings = f"{screener['estimated_llm_savings']:.0%}" if screener else "—" - n_wins = len(screener["candidate_windows"]) if screener else "—" +def _uncertainty_html(seg: dict) -> str: + if not seg.get("uncertain"): + return "" + note = _h(seg.get("uncertainty_note") or "") return ( - f'
' - f'
' - f'
' - f'
' - f'
{session}
' - f'
' - f'{turns} turns · {n_wins} candidate windows · ~{savings} LLM savings' - f'
' - f'
{"".join(steps)}
' + f'
' + f'⚠' + f'
AI flagged uncertain' + f' — {note}
' f'
' ) -# ────────────────────────────────────────────────────────────────────────────── -# Status cards + shared helpers -# ────────────────────────────────────────────────────────────────────────────── +def _dim_desc_html(choice: str) -> str: + if not choice: + return "" + did = DIM_ID_FROM_CHOICE.get(choice, "") + desc = DIM_DESC_FROM_ID.get(did, "") + if not desc: + return "" + return ( + f'
{_h(desc)}
' + ) + def _status_card(title: str, status: str = "success", details: dict | None = None, error_msg: str | None = None) -> str: @@ -352,7 +335,7 @@ def _status_card(title: str, status: str = "success", "success": ("#f0fdf4", "#065f46", "#86efac", "✓"), "error": ("#fef2f2", "#991b1b", "#fca5a5", "✗"), "warning": ("#fffbeb", "#78350f", "#fbbf24", "⚠"), - "processing": ("#fff5f2", "#7c2d12", "#ff8c75", "⏳"), + "processing": ("#eff6ff", "#1e40af", "#93c5fd", "⏳"), } bg, tc, bc, icon = colors.get(status, colors["success"]) detail_html = "" @@ -380,628 +363,724 @@ def _status_card(title: str, status: str = "success", ) -def _loading_card(title: str, subtitle: str = "Please wait…", spin: str = "◐") -> str: - return ( - '
' - '
' - f'
{spin}
' - f'
{_h(title)}
' - f'
{_h(subtitle)}
' - '
' - ) +# --------------------------------------------------------------------------- +# LLM progress indicator — shown while a blocking LLM call runs in background. +# Updates every 2 s via heartbeat yields; spinner cycles to signal activity. +# --------------------------------------------------------------------------- +_SPINNERS = ["◐", "◓", "◑", "◒"] def _llm_progress_html(message: str, elapsed: int, est_total: int, tokens_in: int, circ: str, spin_i: int) -> str: - pct = min(int(elapsed / max(est_total, 1) * 85), 85) - remaining = max(est_total - elapsed, 0) - spinner = _SPINNERS[spin_i % len(_SPINNERS)] + """ + Rich status card shown during LLM calls. + Never freezes the UI — fn_process calls this from a heartbeat loop + while the actual LLM request runs in a daemon thread. + """ + pct = min(int(elapsed / max(est_total, 1) * 85), 85) # max 85% until done + remaining = max(est_total - elapsed, 0) + spinner = _SPINNERS[spin_i % len(_SPINNERS)] + bar_color = "#4338ca" circ_color = "#065f46" if circ == "CLOSED" else "#b45309" if circ == "HALF_OPEN" else "#be123c" circ_icon = "✓" if circ == "CLOSED" else "⚠" if circ == "HALF_OPEN" else "✗" + tok_str = f"{tokens_in:,}" eta_str = f"~{remaining}s" if remaining > 5 else "finishing…" + return ( - f'
' + + # ── Header row ──────────────────────────────────────────��───────── f'
' - f'{spinner}' - f'{_h(message)}' + f'{spinner}' + f'{_h(message)}' f'' - f'{elapsed}s elapsed
' - f'
' - f'
' + f'background:#dbeafe;padding:3px 9px;border-radius:6px;color:#1e40af;' + f'white-space:nowrap">{elapsed}s elapsed' f'
' + + # ── Progress bar ────────────────────────────────────────────────── + f'
' + f'
' + f'{pct}%' + f'
' + + # ── Metrics row ─────────────────────────────────────────────────── f'
' - f'Est: ~{est_total}s' - f'ETA: {eta_str}' - f'~{tokens_in:,} tokens' + f'⏱ Est. total: ~{est_total}s' + f'⌛ ETA: {eta_str}' + f'🔢 ~{tok_str} tokens in' f'' - f'Circuit: {circ_icon} {circ}' - f'
' - ) - + f'LLM circuit: {circ_icon} {circ}' + f'
' -def _agent_log_html(logs: list[dict]) -> str: - if not logs: - return '

No agent calls yet.

' - parts = [] - for entry in reversed(logs[-5:]): - agent = _h(entry.get("agent", "")) - model = _h(entry.get("model", "")) - runtime = entry.get("runtime_s", "?") - ts = _h(entry.get("timestamp", "")) - extras = {k: v for k, v in entry.items() - if k not in ("agent","model","temperature","runtime_s", - "timestamp","system_prompt_preview","user_prompt_preview")} - extra_lines = "".join( - f'
' - f'{_h(str(k))}' - f'{_h(str(v))}
' - for k, v in extras.items() - ) - parts.append( - f'
' - f'
' - f'{agent}' - f'{ts} · {runtime}s' - f'
' - f'
model: ' - f'{model}
' - f'{extra_lines}' - f'
' - ) - return "".join(parts) + # ── Note ────────────────────────────────────────────────────────── + f'
' + f'Processing in background — UI stays responsive. ' + f'Typical 250-turn transcript: 45–90 s on HF shared inference.' + f'
' + f'
' + ) -def _format_turns_html(seg: dict, speaker_map: dict) -> str: - turns = seg.get("turns", []) - if not turns: - return '

No turns in this segment.

' - parts = [] - for t in turns: - sp = t.get("speaker", "?") - entry = speaker_map.get(sp, {"color": "#64748b", "bg": "#f8fafc", - "initials_bg": "#e2e8f0", "emoji": "○"}) - avatar = _speaker_avatar(sp, entry) - ts = _h(t.get("start_time", "")) - text = _h(t.get("text", "")) - turn_id = t.get("turn_id", "") - parts.append( - f'
' +def _speaker_legend_html(speaker_map: dict) -> str: + if not speaker_map: + return "" + chips = [] + for name, entry in speaker_map.items(): + avatar = _speaker_avatar(name, entry) + chips.append( + f'' f'{avatar}' - f'
' - f'
' - f'' - f'{_h(sp)}' - f'{ts}' - f'#{turn_id}' - f'
' - f'
{text}
' - f'
' + f'' + f'{_h(name)}' ) - return f'
{"".join(parts)}
' - + return ( + f'
' + f'{"".join(chips)}
' + ) -# ────────────────────────────────────────────────────────────────────────────── -# Screener render helpers -# ────────────────────────────────────────────────────────────────────────────── -def _score_to_color(score: float, excluded: bool) -> tuple[str, str]: - """Returns (background, text-color) for a turn score badge.""" - if excluded: - return "#f1f5f9", "#94a3b8" - if score >= 0.8: - return "#dcfce7", "#15803d" - if score >= 0.55: - return "#d1fae5", "#065f46" - if score >= 0.40: - return "#fef9c3", "#854d0e" - if score >= 0.2: - return "#fff5f2", "#ea4425" - return "#f8fafc", "#94a3b8" +def _kappa_html(report: dict) -> str: + ac1 = report.get("overall_ac1", report.get("overall_kappa", 0.0)) + ac1_interp = report.get("ac1_interpretation", report.get("kappa_interpretation", "")) + ac1_ci = report.get("ac1_ci_95", [None, None]) + gate = report.get("gate_passed", False) + col = "#065f46" if gate else "#be123c" + icon = "✓" if gate else "✗" + pct = int(min(max(ac1, 0) * 100, 100)) + kappa = report.get("overall_kappa", 0.0) + kappa_ci = report.get("kappa_ci_95", [None, None]) + divergence = report.get("kappa_ac1_divergence", 0.0) + div_flag = report.get("kappa_ac1_divergence_flag", False) + prev_warn = report.get("prevalence_warning", False) + n_segs = report.get("n_segments_total", 0) + n_dis = len(report.get("segments_in_disagreement", [])) + + ci_text = "" + if ac1_ci[0] is not None: + ci_text = f' 95% CI [{ac1_ci[0]:.3f}, {ac1_ci[1]:.3f}]' + + prev_banner = "" + if prev_warn: + dominant = max( + ((d, v["prevalence"]) for d, v in (report.get("category_distribution") or {}).items()), + key=lambda x: x[1], default=("?", 0) + ) + prev_banner = ( + f'
' + f'⚠ Prevalence bias detected: {_h(dominant[0])} accounts for ' + f'{dominant[1]:.0%} of codings. AC1 is the appropriate metric here.
' + ) + kc = "#065f46" if kappa >= 0.70 else "#be123c" + if div_flag: + div_note = ( + f'
' + f'Cohen\'s κ = {kappa:.3f}' + + (f' [{kappa_ci[0]:.3f}, {kappa_ci[1]:.3f}]' if kappa_ci[0] is not None else '') + + f' · |AC1 − κ| = {divergence:.3f} (prevalence bias)' + f'
' + ) + else: + div_note = ( + f'
' + f'Cohen\'s κ = {kappa:.3f}' + + (f' [{kappa_ci[0]:.3f}, {kappa_ci[1]:.3f}]' if kappa_ci[0] is not None else '') + + f' (reference — Gwet 2008 primary)
' + ) -def _screener_summary_html(result_dict: dict) -> str: - total = result_dict.get("total_turns", 0) - flagged = result_dict.get("flagged_turns", 0) - windows = len(result_dict.get("candidate_windows", [])) - savings = result_dict.get("estimated_llm_savings", 0) + dim_src = report.get("ac1_per_dimension") or report.get("kappa_per_dimension") or {} + dim_label = "AC1" if "ac1_per_dimension" in report else "κ" + dim_rows = "" + for dim in ["D1","D2","D3","D4","D5","D6","D7","D8","D9","NS","NA"]: + v = dim_src.get(dim) + if v is None: + dim_rows += ( + f'
' + f'{dim}' + f'insufficient data' + f'
' + ) + continue + vp = int(min(max(v, 0) * 100, 100)) + vc = "#065f46" if v >= 0.70 else "#b45309" if v >= 0.50 else "#be123c" + dim_rows += ( + f'
' + f'{dim}' + f'
' + f'
' + f'' + f'{v:.3f}' + f'
' + ) return ( - f'
' - + _stat_chip(str(total), "Total turns", "#ff5a3d", "#fff5f2") - + _stat_chip(str(flagged), "Flagged turns", "#065f46", "#dcfce7") - + _stat_chip(str(windows), "Candidate windows", "#b45309", "#fffbeb") - + _stat_chip(f"{savings:.0%}", "LLM savings", "#be123c", "#fef2f2") - + f'
' + f'
' + f'{prev_banner}' + f'
' + f'{ac1:.3f}' + f'
' + f'
{icon} {_h(ac1_interp)}
' + f'
Gwet\'s AC1 · gate ≥ 0.70
' + f'
' + f'{ci_text}' + f'
' + f'
' + f'
' + f'
0.70
' + f'
' + f'
' + f'{n_segs} segments · {n_dis} disagreement{"s" if n_dis!=1 else ""}
' + f'{div_note}' + f'
Per-Dimension {dim_label}
' + f'{dim_rows}' + f'
' ) -def _stat_chip(value: str, label: str, tc: str, bg: str) -> str: - return ( - f'
' - f'
{_h(value)}
' - f'
{_h(label)}
' - f'
' - ) - +def _rules_html(rules: list[dict]) -> str: + if not rules: + return ( + '
No rules pending review.
' + ) + TYPE_META = { + "boundary_clarification": ("#dbeafe", "#1e3a8a", "Boundary"), + "disambiguation_rule": ("#fce7f3", "#831843", "Disambiguation"), + "behavioral_marker_refinement": ("#d1fae5", "#064e3b", "Marker Refinement"), + } + cards = [] + for r in rules: + bg, tc, label = TYPE_META.get(r.get("rule_type", ""), ("#f1f5f9", "#334155", "Rule")) + dims = _h(", ".join(r.get("dimensions_involved") or [])) + desc = _h(r.get("description", "")) + rat = _h(r.get("rationale", "")) + conf = _h(r.get("confidence", "")) + note = _h(r.get("agent2_note", "")) + rid = _h(r.get("rule_id", "")) + created = r.get("created_at", "")[:10] + cards.append( + f'
' + f'
' + f'
' + f'{label}' + f'{rid} · {created}' + f'
' + f'dims: {dims}' + f'
' + f'

{desc}

' + f'

Evidence: {rat}

' + f'
' + f'Confidence: {conf}' + + (f' · Note: {note}' if note else '') + + f'
' + ) + return "".join(cards) -def _screener_turns_html(result_dict: dict, speaker_map: dict, - max_turns: int = 300) -> str: - turn_scores = result_dict.get("turn_scores", []) - if not turn_scores: - return '

Run the screener first.

' - parts = [] - parts.append( - '
' - '
' - '
#
Speaker
Score
Text
Triggers
' - '
' - ) +def _sections_html(sections: list[dict], n_turns: int, + agent0_rt: float, n_speakers: int, + all_turns: list[dict] | None = None) -> str: + """ + Rich sections display for the Review Sections page. - shown = 0 - for ts in turn_scores: - if shown >= max_turns: - remaining = len(turn_scores) - max_turns - parts.append( - f'
{remaining} more turns — use the search filter
' - ) - break - shown += 1 - - excluded = bool(ts.get("excluded_reason")) - flagged = ts.get("flagged", False) - score = ts.get("composite", 0) - sp = ts.get("speaker", "?") - text = ts.get("text", "") - tid = ts.get("turn_id", "") - stime = ts.get("start_time", "") - hits = ts.get("hits", []) - signals = ts.get("signals", []) - - entry = speaker_map.get(sp, {"color": "#64748b", "initials_bg": "#e2e8f0"}) - sbg, stc = _score_to_color(score, excluded) - - # Highlight matched terms in text - display_text = _h(text[:140] + ("…" if len(text) > 140 else "")) - - # Trigger chips - trigger_chips = "" - for hit in hits[:3]: - ph = hit.get("phase", "") - lbl = hit.get("category_label", "") - tier = hit.get("tier", 1) - tchip_bg = {"planning": "#fff5f2", "monitoring": "#f0fdf4", - "evaluating": "#fff5f2", "ssrl": "#faf5ff"}.get(ph, "#f8fafc") - tchip_c = {"planning": "#ea4425", "monitoring": "#15803d", - "evaluating": "#ea4425", "ssrl": "#7c3aed"}.get(ph, "#64748b") - tier_mark = "⟨2⟩" if tier == 2 else "⟨3?⟩" if tier == 3 else "" - trigger_chips += ( - f'' - f'{_h(lbl[:25])}{tier_mark} ' - ) - for sig in signals[:2]: - trigger_chips += ( - f'' - f'⚡{_h(sig)} ' - ) - if excluded: - trigger_chips = ( - f'small talk' - ) + Uses native HTML
/ for expand-to-read-content — no JS required. + Each section is collapsed by default (researcher sees the label and size at a glance) + and can be expanded to read the AI summary + first 8 turns of actual transcript. - row_bg = "#fffbeb" if flagged else ("#f8fafc" if excluded else "white") - flag_icon = "🟢" if flagged else ("⬜" if not excluded else "🔘") + Label format in the textarea is "s01: Label" so the mapping is unambiguous. + """ + if not sections: + return '

No sections detected.

' + + avg = n_turns // len(sections) if sections else 0 + total = n_turns + + # ── 1. Agent completion card ───────────────────────────────────────────── + agent_card = ( + f'
' + f'
' + f'
' + f'
' + f'✓' + f'Agent 0 — Structural Segmenter' + f'completed in {agent0_rt:.1f}s' + f'
' + f'
' + f'{total} turns · {n_speakers} speaker(s) → ' + f'{len(sections)} sections detected ' + f'(avg {avg} turns/section)
' + f'Basis: lexical cohesion (Hearst 1997) · topic modelling (Purver et al. 2006) ' + f'· activity phases (Stahl 2006; Roschelle & Teasley 1995)' + f'
' + f'
' + f'
' + f'Qwen2.5-72B · T=0.1
' + f'
' + f'
' + ) - parts.append( - f'
' + # ── 2. Expandable section list ─────────────────────────────────────────── + palette = [ + ("#4338ca", "#eef2ff"), # indigo + ("#b45309", "#fffbeb"), # amber + ("#065f46", "#f0fdf4"), # emerald + ("#9a3412", "#fff7ed"), # orange + ("#6b21a8", "#faf5ff"), # purple + ("#0e7490", "#ecfeff"), # cyan + ("#be123c", "#fff1f2"), # rose + ] - # Turn ID - f'
{flag_icon} {_h(str(tid))}
' + warnings = [] + detail_items = [] - # Speaker - f'
' - f'{_h(sp[:10])}
' + for i, s in enumerate(sections): + col, bg = palette[i % len(palette)] + n = s["end_turn_id"] - s["start_turn_id"] + 1 + pct = round(n / total * 100) if total else 0 - # Score badge - f'
' - f'{score:.2f}' - f'
{_h(stime)}
' - f'
' + if pct > 30 and len(sections) > 2: + warnings.append( + f'{_h(s["label"])} ({n} turns, {pct}%) is unusually large. ' + f'Expand it below to check if it contains distinct sub-topics.' + ) - # Text - f'
' - f'{display_text}
' + # ── Bar ── + bar = ( + f'
' + f'
' + f'
' + ) - # Triggers - f'
{trigger_chips}
' + # ── Transcript excerpt ── + excerpt_html = "" + if all_turns: + sec_turns = [ + t for t in all_turns + if s["start_turn_id"] <= t["turn_id"] <= s["end_turn_id"] + ] + shown = sec_turns[:8] + rows = [] + for t in shown: + sp = _h(t.get("speaker", "?")) + ts = _h(t.get("start_time", "")) + txt = t.get("text", "") + if len(txt) > 180: + txt = txt[:180] + "…" + rows.append( + f'
' + f'' + f'{sp}' + f'{ts}' + f'{_h(txt)}' + f'
' + ) + if len(sec_turns) > 8: + rows.append( + f'
⋯ {len(sec_turns)-8} more turns
' + ) + excerpt_html = ( + f'
' + f'
' + f'Transcript excerpt (first {len(shown)} of {n} turns)
' + f'{"".join(rows)}' + f'
' + ) + summary_text = _h(s.get("summary", "No summary provided.")) + + detail_items.append( + f'
' + + # ── Collapsed header (always visible) ────────────────────────── + f'' + f'' + f'{_h(s["section_id"])}' + f'' + f'{_h(s["label"])}' + f'{_h(s["start_time"])}–{_h(s["end_time"])}' + f'' + f' {n} turns ({pct}%)' + f'{bar}' + f'▼ read' + f'' + + # ── Expanded content ──────────────────────────────────────────── + f'
' + f'

' + f'AI summary: {summary_text}

' + f'{excerpt_html}' f'
' + f'
' ) - parts.append('
') - return "".join(parts) + section_list = f'
{"".join(detail_items)}
' + + # ── 3. Warnings ────────────────────────────────────────────────────────── + warn_html = "" + if warnings: + items = "".join(f"
  • {w}
  • " for w in warnings) + warn_html = ( + f'
    ' + f'⚠ Size note' + f'
      {items}
    ' + f'
    ' + ) + # ── 4. Label editor instruction ────────────────────────────────────────── + instr = ( + f'
    ' + f'Rename sections below — each line follows the format ' + f'' + f's01: Your Label. ' + f'Edit the text after the colon only; the s01: prefix keeps the order clear. ' + f'Turn boundaries are fixed — only labels change. ' + f'Expand any section above to read its content before renaming.' + f'
    ' + ) -def _candidate_windows_html(result_dict: dict) -> str: - wins = result_dict.get("candidate_windows", []) - if not wins: - return '

    No candidate windows found.

    ' + return agent_card + section_list + warn_html + instr - parts = ['
    '] - for i, w in enumerate(wins, 1): - tids = w.get("turn_ids", []) - score = w.get("score", 0) - summary = w.get("trigger_summary", "") - n = w.get("turn_count", len(tids)) - start = tids[0] if tids else "?" - end = tids[-1] if tids else "?" - sbg, stc = _score_to_color(score, False) - parts.append( - f'
    ' - f'
    ' - f'{i:02d}
    ' - f'
    ' - f'
    ' - f'Turns {_h(str(start))}–{_h(str(end))} ' - f'({n} turns)
    ' - f'
    ' - f'{_h(summary)}
    ' - f'
    ' - f'
    score {score:.2f}
    ' - f'
    ' - ) - parts.append('
    ') - return "".join(parts) +def _episode_dialogue_html(segments: list[dict], boundaries: list[dict], + speaker_map: dict) -> str: + """ + Render each proposed episode with its actual dialogue turns + boundary markers. + Design goal: the researcher must be able to READ the transcript before + deciding whether to accept the AI's proposed boundary positions. + Showing only turn-ID tables (the old approach) is opaque. -# ────────────────────────────────────────────────────────────────────────────── -# Lexicon render helpers -# ────────────────────────────────────────────────────────────────────────────── + Rules: + - Up to 5 turns shown per episode; truncation indicated clearly + - Speaker avatars + timestamps match the coding canvas + - Boundary markers show signal type, confidence, and AI rationale + - Entire view is scrollable so the page does not grow unbounded + """ + if not segments: + return ( + '

    ' + 'No episode data yet.

    ' + ) -def _lexicon_tier1_html(tier1_data: dict) -> str: - cats = tier1_data.get("categories", []) - if not cats: - return '

    Lexicon file not found.

    ' + bmap: dict[int, dict] = {} + for b in boundaries: + bmap[b.get("after_turn_id", -1)] = b - phase_colors = { - "planning": ("#ea4425", "#fff5f2", "#fff5f2"), - "monitoring": ("#15803d", "#f0fdf4", "#dcfce7"), - "evaluating": ("#ea4425", "#fff5f2", "#ffc5b5"), - "ssrl": ("#7c3aed", "#faf5ff", "#e9d5ff"), + conf_colors = { + "high": ("#065f46", "#f0fdf4", "#86efac"), + "medium": ("#92400e", "#fffbeb", "#fde68a"), + "low": ("#991b1b", "#fef2f2", "#fca5a5"), } - parts = [ - '
    ' - '
    ' - '🔒 Tier 1 is research-locked. To add custom terms, use the Tier 2 tab.
    ' - ] - - for cat in cats: - phase = cat.get("phase", "monitoring") - tc, bg, border = phase_colors.get(phase, ("#475569", "#f8fafc", "#e2e8f0")) - label = _h(cat.get("label", "")) - cat_id = _h(cat.get("id", "")) - weight = cat.get("weight", 0) - source = _h(cat.get("source", "")) - terms = cat.get("terms", []) - - term_chips = " ".join( - f'' - f'{_h(t)}' - for t in terms - ) + parts: list[str] = [] + for i, seg in enumerate(segments): + turns = seg.get("turns", []) + ep_id = seg.get("segment_id", f"ep{i+1:02d}") + ep_num = ep_id.split("_ep")[-1] if "_ep" in ep_id else str(i + 1) + n_turns = len(turns) + # Episode header strip parts.append( - f'
    ' - f'
    ' - f'{cat_id}' - f'{label}' - f'' - f'w={weight} · {_h(phase)}' - f'
    ' - f'
    ' - f'Source: {source}
    ' - f'
    {term_chips}
    ' - f'
    ' + f'
    ' + f'Episode {ep_num}' + f'{n_turns} turns' + + (f'' + f'{_h(seg.get("rationale","")[:80])}{"…" if len(seg.get("rationale",""))>80 else ""}' + f'' if seg.get("rationale") else '') + + '
    ' ) - parts.append('
    ') - return "".join(parts) + # Show up to 5 turns + shown = turns[:5] + for t in shown: + sp = t.get("speaker", "?") + entry = speaker_map.get( + sp, {"color": "#64748b", "bg": "#f8fafc", "initials_bg": "#e2e8f0"} + ) + avatar = _speaker_avatar(sp, entry) + text = t.get("text", "") + if len(text) > 220: + text = text[:220] + "…" + ts = _h(t.get("start_time", "")) + parts.append( + f'
    ' + f'{avatar}' + f'
    ' + f'
    ' + f'' + f'{_h(sp)}' + f'{ts}' + f'' + f'#{t.get("turn_id","")}' + f'
    ' + f'
    {_h(text)}
    ' + f'
    ' + ) -def _lexicon_tier2_html(tier2_data: dict) -> str: - entries = tier2_data.get("entries", []) - if not entries: - return ( - '
    ' - '
    📝
    ' - '
    No validated terms yet.
    ' - '
    ' - 'Use the form below to add researcher-validated terms.
    ' - ) + if n_turns > 5: + parts.append( + f'
    ' + f'⋯ {n_turns - 5} more turn{"s" if n_turns-5>1 else ""} in this episode
    ' + ) - parts = ['
    '] - for e in entries: - active = e.get("active", True) - bg = "white" if active else "#f8fafc" - tc = "#1e293b" if active else "#94a3b8" - badge = ("🟢 Active" if active else "⬜ Inactive") - label = _h(e.get("label", "")) - cat_id = _h(e.get("category_id", "")) - terms = e.get("terms", []) - note = _h(e.get("note", "")) - added = _h(e.get("added_by", "")) - - term_chips = " ".join( - f'{_h(t)}' - for t in terms - ) + # Boundary marker before the next episode + if i < len(segments) - 1 and turns: + last_tid = turns[-1].get("turn_id", -1) + b = bmap.get(last_tid, {}) + sig = b.get("boundary_signal", "boundary") + conf = b.get("confidence", "medium") + rat = b.get("rationale", "") + tc, bg, bc = conf_colors.get(conf, conf_colors["medium"]) + parts.append( + f'
    ' + f'━ boundary' + f'{_h(sig)}' + f'{conf} confidence' + + (f'' + f'— {_h(rat[:100])}{"…" if len(rat)>100 else ""}' if rat else '') + + f'after #{last_tid}' + f'
    ' + ) - parts.append( - f'
    ' - f'
    ' - f'{badge}' - f'{label}' - f'{cat_id}' - f'by {added}' - f'
    ' - f'
    {term_chips}
    ' - + (f'
    {note}
    ' if note else "") - + f'
    ' - ) - parts.append('
    ') - return "".join(parts) + return ( + f'
    ' + + "".join(parts) + + '
    ' + ) -def _lexicon_tier3_html(tier3_data: dict) -> str: - candidates = [c for c in tier3_data.get("candidates", []) - if not c.get("approved") and not c.get("rejected")] - if not candidates: +def _agent_log_html(logs: list[dict]) -> str: + if not logs: return ( - '
    ' - '
    ✅
    ' - '
    No pending candidates.
    ' - '
    ' - 'Candidates appear here when the system proposes new terms from coded segments.
    ' - '
    ' + '

    ' + 'No agents have run yet.

    ' ) - - parts = ['
    '] - for c in candidates: - terms = c.get("terms", []) - label = _h(c.get("label", "")) - ctx = _h(c.get("context", "")[:200]) - session = _h(c.get("session_id", "")) - - term_chips = " ".join( - f'{_h(t)}' - for t in terms + parts = [] + for entry in reversed(logs[-4:]): + agent = _h(entry.get("agent", "?")) + model = _h(entry.get("model", "?").split("/")[-1]) + runtime = entry.get("runtime_s", "?") + ts = _h(entry.get("timestamp", "")) + extras = {k: v for k, v in entry.items() + if k not in ("agent", "model", "temperature", "runtime_s", + "timestamp", "system_prompt_preview", "user_prompt_preview")} + extra_lines = "".join( + f'
    ' + f'{_h(str(k))}' + f'{_h(str(v))}
    ' + for k, v in extras.items() ) - parts.append( - f'
    ' - f'
    ' - f'⏳ Pending' - f'{label}' - f'{session}' + f'
    ' + f'
    ' + f'{agent}' + f'{ts} · {runtime}s' + f'
    ' + f'
    model: {model}
    ' + f'{extra_lines}' f'
    ' - f'
    {term_chips}
    ' - + (f'
    “{ctx}”
    ' if ctx else "") - + f'
    ' ) - parts.append('
    ') return "".join(parts) -# ────────────────────────────────────────────────────────────────────────────── -# Segment review helpers (enhanced for inline editing) -# ────────────────────────────────────────────────────────────────────────────── - -def _dim_badge(did: str) -> str: - colors = { - "D1": ("#ff5a3d","#fff5f2"), "D2": ("#0e7490","#ecfeff"), - "D3": ("#065f46","#ecfdf5"), "D4": ("#b45309","#fffbeb"), - "D5": ("#6b21a8","#faf5ff"), "D6": ("#7c2d12","#fff5f2"), - "D7": ("#7c2d12","#fff5f2"), "D8": ("#be123c","#fef2f2"), - "D9": ("#374151","#f3f4f6"), "NS": ("#78716c","#f5f5f4"), - "NA": ("#94a3b8","#f8fafc"), +def _make_log_entry(agent: str, runtime_s: float, **stats) -> dict: + return { + "agent": agent, + "model": MODEL_ID, + "temperature": TEMPERATURE, + "runtime_s": round(runtime_s, 1), + "timestamp": datetime.now(timezone.utc).strftime("%H:%M:%S"), + **stats, } - tc, bg = colors.get(did, ("#64748b","#f8fafc")) - return ( - f'' - f'{_h(did)}' - ) -def _ssrl_badge(phase_id: str) -> str: - if not phase_id or phase_id == "NONE": +def _coding_progress_html(state: dict) -> str: + sections = state.get("sections", []) + idx = state.get("section_idx", 0) + segs = _current_section_segments(state) + codings = state.get("codings", {}) + cidx = state.get("coding_idx", 0) + if not segs: return "" - tc, bg = SSRL_COLOR_FROM_ID.get(phase_id, ("#64748b","#f8fafc")) - label = next((l for p, l, _, _ in SSRL_PHASES if p == phase_id), phase_id) - return ( - f'' - f'⟡ {_h(label)}' - ) - - -def _segment_review_html(seg: dict, codings: dict, ssrl_codings: dict, - speaker_map: dict, screener_hit: bool = False) -> str: - sid = seg["segment_id"] - existing = codings.get(sid, {}) - dim_id = existing.get("dimension_id") or seg.get("dimension_id") or "?" - ssrl_id = ssrl_codings.get(sid, "NONE") - rationale = _h(seg.get("rationale", "")) - uncertain = seg.get("uncertain", False) - conf = seg.get("confident", False) - unote = _h(seg.get("uncertainty_note", "")) - n_turns = (seg.get("end_turn_id", 0) - seg.get("start_turn_id", 0) + 1) - stime = _h(seg.get("start_time", "")) - etime = _h(seg.get("end_time", "")) - - screener_tag = "" - if screener_hit: - screener_tag = ( - '' - 'screener hit' - ) - - uncertain_tag = "" - if uncertain: - uncertain_tag = ( - f'
    ⚠ AI uncertain — {unote}
    ' - ) - + coded = sum(1 for s in segs if codings.get(s["segment_id"], {}).get("dimension_id")) + total = len(segs) + pct = int(coded / total * 100) if total else 0 + sec = sections[idx] if idx < len(sections) else {} + ep_num = min(cidx, total - 1) + 1 + # Total across all sections + all_coded = sum(1 for v in codings.values() if v.get("dimension_id")) + all_segs = sum( + len(state.get("section_segments_coded", {}).get(s["section_id"], [])) + for s in sections + ) return ( - f'
    ' - f'
    ' - f'{_h(sid)}' - f'{_dim_badge(dim_id)}' - f'{_ssrl_badge(ssrl_id)}' - f'{screener_tag}' - f'' - f'{stime}–{etime} · {n_turns} turns' + f'
    ' + f'
    ' + f'
    ' + f'Section {idx+1}/{len(sections)} — {_h(sec.get("label",""))}
    ' + f'
    Episode {ep_num} of {total}
    ' + f'
    ' + f'
    ' + f'
    ' + f'
    ' + f'{coded}/{total} episodes coded this section' + f'{all_coded}/{all_segs} total' f'
    ' - f'
    ' - f'{rationale or "No rationale."}
    ' - f'{uncertain_tag}' f'
    ' ) -def _all_segments_review_html(state: dict) -> str: - all_segs = [] - codings = state.get("codings", {}) - ssrl = state.get("ssrl_codings", {}) - speaker_map = state.get("speakers", {}) - screener = state.get("screener_result") - flagged_wins = set() - if screener: - for w in screener.get("candidate_windows", []): - flagged_wins.update(w.get("turn_ids", [])) +# =========================================================================== +# STATE +# =========================================================================== - for sec in state.get("sections", []): - segs = state.get("section_segments_coded", {}).get(sec["section_id"], []) - for seg in segs: - start = seg.get("start_turn_id", 0) - end = seg.get("end_turn_id", 0) - hit = any(t in flagged_wins for t in range(start, end + 1)) - all_segs.append((seg, hit)) - - if not all_segs: - return '

    No coded segments yet.

    ' - - coded = sum(1 for s, _ in all_segs if codings.get(s["segment_id"], {}).get("dimension_id")) - total = len(all_segs) - ssrl_ct = sum(1 for s, _ in all_segs if ssrl.get(s["segment_id"], "NONE") != "NONE") - - header = ( - f'
    ' - + _stat_chip(str(total), "Segments", "#ff5a3d", "#fff5f2") - + _stat_chip(str(coded), "D1-D9 coded", "#065f46", "#dcfce7") - + _stat_chip(str(ssrl_ct), "SSRL tagged", "#7c3aed", "#faf5ff") - + f'
    ' - ) +def _empty_state() -> dict: + return { + "session_id": "", + "researcher_id": "", + "turns": [], + "speakers": {}, + "sections": [], + "section_idx": 0, + "section_stages": {}, + "section_boundaries": {}, + "section_segments": {}, + "section_segments_coded": {}, + "coding_idx": 0, + "codings": {}, + "stage": "upload", + "kappa_report": None, + "agent_logs": [], + "screener_result": None, + "ssrl_codings": {}, + } - rows = "".join( - _segment_review_html(seg, codings, ssrl, speaker_map, hit) - for seg, hit in all_segs - ) - return header + rows +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}" -# ────────────────────────────────────────────────────────────────────────────── -# Section display helpers (from v4, kept intact) -# ────────────────────────────────────────────────────────────────────────────── -def _sections_html(sections: list[dict], n_turns: int, elapsed: float, - n_speakers: int, all_turns: list[dict] | None = None) -> str: - if not sections: - return "" - cards = [] - for s in sections: - n = s["end_turn_id"] - s["start_turn_id"] + 1 - pct = round(n / max(n_turns, 1) * 100) - cards.append( - f'
    ' - f'
    ' - f'{_h(s["label"])}
    ' - f'
    {_h(s["start_time"])}–{_h(s["end_time"])}
    ' - f'
    Turns {s["start_turn_id"]}–' - f'{s["end_turn_id"]} ({n} turns · {pct}%)
    ' - f'
    ' - f'
    ' - f'
    ' - f'
    ' - ) +def _loading_card(title: str, subtitle: str = "Please wait…", spin: str = "◐") -> str: return ( - f'
    ' - f'
    ' - + _stat_chip(str(n_turns), "Turns", "#ff5a3d", "#fff5f2") - + _stat_chip(str(len(sections)), "Sections", "#065f46", "#dcfce7") - + _stat_chip(str(n_speakers), "Speakers", "#b45309", "#fffbeb") - + _stat_chip(f"{elapsed}s", "Agent 0", "#7c3aed", "#faf5ff") - + f'
    ' - f'
    {"".join(cards)}
    ' - f'
    ' + '
    ' + '
    ' + f'
    {spin}
    ' + f'
    {_h(title)}
    ' + f'
    {_h(subtitle)}
    ' + '
    ' ) +def _session_dir(state: dict) -> Path: + return SESSIONS_ROOT / state["session_id"] + + +def _current_section(state: dict) -> dict | None: + secs = state.get("sections", []) + idx = state.get("section_idx", 0) + return secs[idx] if secs and idx < len(secs) else None + + +def _current_section_segments(state: dict) -> list[dict]: + sec = _current_section(state) + return state["section_segments_coded"].get(sec["section_id"], []) if sec else [] + + +def _turns_for_section(turns: list[dict], section: dict) -> list[dict]: + return [t for t in turns + if section["start_turn_id"] <= t["turn_id"] <= section["end_turn_id"]] + + +def _persist(state: dict) -> None: + try: + d = _session_dir(state) + d.mkdir(parents=True, exist_ok=True) + skip = {"turns", "kappa_report"} + (d / "app_state.json").write_text( + json.dumps({k: v for k, v in state.items() if k not in skip}, + indent=2, ensure_ascii=False), + encoding="utf-8", + ) + except Exception: + pass + + +def _seconds_to_hms(s: float) -> str: + return str(timedelta(seconds=int(s))) + + +def _push_log(state: dict, entry: dict) -> dict: + logs = list(state.get("agent_logs", [])) + logs.append(entry) + state["agent_logs"] = logs[-10:] + return state + + +# =========================================================================== +# CODING RENDER HELPERS +# =========================================================================== + def _segment_label(seg: dict, codings: dict) -> str: sid = seg["segment_id"] + ep = sid.split("_ep")[-1] if "_ep" in sid else sid[-4:] c = codings.get(sid, {}) did = c.get("dimension_id") or seg.get("dimension_id") or "?" + sec = c.get("secondary_dimension_id") coded = "✓" if c.get("dimension_id") else "○" flag = " ⚠" if seg.get("uncertain") else "" - return f"{coded} [{did}]{flag} — {sid[-12:]}" + multi = f"+{sec}" if sec else "" + return f"{coded} ep{ep} [{did}{multi}]{flag}" def _proposal_md(seg: dict) -> str: @@ -1016,503 +1095,501 @@ def _proposal_md(seg: dict) -> str: if seg.get("confident"): tags.append("✅ Confident") if seg.get("uncertain"): - tags.append(f"⚠️ Uncertain — {seg.get('uncertainty_note','')}") + tags.append(f"⚠️ Uncertain — {seg.get('uncertainty_note', '')}") if sec_did: - tags.append(f"🔗 Multi-dim: {did} + {sec_did}") + tags.append(f"🔗 Multi-dimensional: {did} + {sec_did}") return ("\n\n".join(lines) + ("\n\n" + " ".join(tags) if tags else "")).strip() -def _uncertainty_html(seg: dict) -> str: - if not seg.get("uncertain"): - return "" - note = _h(seg.get("uncertainty_note") or "") - return ( - f'
    ' - f'⚠' - f'
    AI flagged uncertain' - f' — {note}
    ' - f'
    ' - ) - +CODING_EMPTY = ( + "", + gr.update(choices=[], value=None), + "", + "", + gr.update(value="", visible=False), + gr.update(choices=DIM_CHOICES, value=None), + "", + gr.update(choices=SEC_DIM_CHOICES, value=SEC_NONE), + "", + gr.update(visible=False), +) -def _dim_desc_html(choice: str) -> str: - if not choice: - return "" - did = DIM_ID_FROM_CHOICE.get(choice, "") - desc = DIM_DESC_FROM_ID.get(did, "") - if not desc: - return "" - return ( - f'
    {_h(desc)}
    ' - ) +def _render_coding(state: dict) -> tuple: + segs = _current_section_segments(state) + codings = state.get("codings", {}) + cidx = state.get("coding_idx", 0) + speaker_map = state.get("speakers", {}) -def _coding_progress_html(state: dict) -> str: - sections = state.get("sections", []) - idx = state.get("section_idx", 0) - segs = _current_section_segments(state) - codings = state.get("codings", {}) - cidx = state.get("coding_idx", 0) - if not segs: - return "" - coded = sum(1 for s in segs if codings.get(s["segment_id"], {}).get("dimension_id")) - total = len(segs) - pct = int(coded / total * 100) if total else 0 - sec = sections[idx] if idx < len(sections) else {} - all_coded = sum(1 for v in codings.values() if v.get("dimension_id")) - all_segs = sum( - len(state.get("section_segments_coded", {}).get(s["section_id"], [])) - for s in sections - ) - return ( - f'
    ' - f'
    ' - f'
    ' - f'Section {idx+1}/{len(sections)} — {_h(sec.get("label",""))}
    ' - f'
    Episode {min(cidx,total-1)+1} of {total}
    ' - f'
    ' - f'
    ' - f'
    ' - f'
    ' - f'
    ' - f'{coded}/{total} coded this section' - f'{all_coded}/{all_segs} total
    ' - f'
    ' - ) - - -CODING_EMPTY = ( - "", gr.update(choices=[], value=None), "", "", - gr.update(value="", visible=False), - gr.update(choices=DIM_CHOICES, value=None), "", - gr.update(choices=SEC_DIM_CHOICES, value=SEC_NONE), "", - gr.update(visible=False), -) - - -def _render_coding(state: dict) -> tuple: - segs = _current_section_segments(state) - codings = state.get("codings", {}) - cidx = state.get("coding_idx", 0) - speaker_map = state.get("speakers", {}) if not segs: return CODING_EMPTY + seg = segs[min(cidx, len(segs) - 1)] sid = seg["segment_id"] existing = codings.get(sid, {}) saved = existing.get("dimension_id", "") choice = next((c for c in DIM_CHOICES if c.startswith(saved)), None) + saved_sec = existing.get("secondary_dimension_id") sec_choice = ( next((c for c in DIM_CHOICES if c.startswith(saved_sec)), SEC_NONE) if saved_sec else SEC_NONE ) + + all_done = len(codings) >= len(segs) and all( + codings.get(s["segment_id"], {}).get("dimension_id") for s in segs + ) + labels = [_segment_label(s, codings) for s in segs] + return ( _coding_progress_html(state), - gr.update(choices=[_segment_label(s, codings) for s in segs], - value=_segment_label(seg, codings)), + gr.update(choices=labels, value=labels[min(cidx, len(segs) - 1)]), _format_turns_html(seg, speaker_map), - _proposal_md(seg), - gr.update(value=_uncertainty_html(seg), visible=seg.get("uncertain", False)), + _uncertainty_html(seg), + gr.update(value=_proposal_md(seg), visible=False), gr.update(choices=DIM_CHOICES, value=choice), _dim_desc_html(choice or ""), gr.update(choices=SEC_DIM_CHOICES, value=sec_choice), - "", - gr.update(visible=True), + existing.get("comment", ""), + gr.update(visible=all_done), ) -# ────────────────────────────────────────────────────────────────────────────── -# Agreement helpers (from v4) -# ────────────────────────────────────────────────────────────────────────────── +# =========================================================================== +# PAGE NAVIGATION HELPER +# =========================================================================== -def _kappa_summary_html(report: dict) -> str: - ac1 = report.get("ac1", 0) - kappa = report.get("kappa", 0) - ci = report.get("ac1_ci_95", [0, 0]) - gate = report.get("gate_passed", False) - nseg = report.get("n_segments", 0) - color = "#15803d" if gate else "#be123c" - bg = "#dcfce7" if gate else "#fef2f2" - label = "Gate PASSED ✓" if gate else "Gate FAILED ✗" - return ( - f'
    ' - f'
    ' - f'{label}
    ' - f'
    ' - f'
    Gwet AC1: ' - f'{ac1:.3f}
    ' - f'
    95% CI: ' - f'[{ci[0]:.3f}, {ci[1]:.3f}]
    ' - f'
    Cohen κ: ' - f'{kappa:.3f}
    ' - f'
    Segments: ' - f'{nseg}
    ' - f'
    ' - ) +_PAGE_NAMES = ["welcome", "setup", "screener", "sections", "pipeline", + "done", "agreement", "library", "lexicon"] +def _show(page: str) -> list: + """Return 9 gr.update(visible=...) items, one per page.""" + return [gr.update(visible=(p == page)) for p in _PAGE_NAMES] -def _disagreement_html(report: dict, all_segs: list[dict]) -> str: - disags = report.get("disagreements", []) - disags = [d for d in disags if d.get("resolution_status", "unresolved") == "unresolved"] - if not disags: - return '
    All disagreements resolved ✓
    ' - seg_map = {s["segment_id"]: s for s in all_segs} - parts = [f'
    ' - f'
    ' - f'{len(disags)} unresolved disagreements
    '] +# =========================================================================== +# CALLBACKS +# =========================================================================== - for d in disags: - sid = d["segment_id"] - r1 = _h(d.get("r1_code", "?")) - r2 = _h(d.get("r2_code", "?")) - seg = seg_map.get(sid, {}) - rat = _h(seg.get("rationale", "")) - parts.append( - f'
    ' - f'
    ' - f'{_h(sid)}' - f'R1: {r1}' - f'vs' - f'R2: {r2}' - f'
    ' - f'
    {rat}
    ' - f'
    ' - ) - parts.append('
    ') - return "".join(parts) +# ── Process: Parse + Agent 0 combined ──────────────────────────────────────── +def _parse_drive_choice(choice: str) -> tuple[str, str]: + if not choice or "::" not in choice: + raise gr.Error("Pick a transcript from Drive first.") + file_id, file_name = choice.split("::", 1) + return file_id, file_name -# ────────────────────────────────────────────────────────────────────────────── -# Drive / session handlers (from v4) -# ────────────────────────────────────────────────────────────────────────────── -def fn_refresh_drive_transcripts(researcher_id: str, state: dict): +def fn_refresh_drive_transcripts(researcher_id: str): rid = (researcher_id or "").strip() if not rid: - return gr.update(choices=[], value=None, interactive=False), \ - _status_card("Enter Researcher ID first.", "warning") + return ( + gr.update(choices=[], value=None, interactive=False), + _status_card("Enter Researcher ID first, then refresh Drive files.", "warning"), + ) + + register_researcher(rid) try: service = get_drive_service(rid) if not service: - return gr.update(choices=[], value=None, interactive=False), \ - _status_card("Google Drive not configured.", "warning") + 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.", "warning") + 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']}") + (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.", "success", {"Files": len(choices)}) + 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", researcher_id=rid, error=e) - return gr.update(choices=[], interactive=False), \ - _status_card("Drive failed.", "error", error_msg=diag) + 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, _status_card("Enter Researcher ID first.", "warning") + return state, gr.update(), _status_card("Enter Researcher ID first.", "warning") + try: service = get_drive_service(rid) if not service: - return state, _status_card("Drive not configured.", "warning") + 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, _status_card("No previous session found.", "warning") + 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") or _auto_session_id(rid, "restored") + sid = new_state.get("session_id", "") or _auto_session_id(rid, "restored_session") new_state["session_id"] = sid - return new_state, _status_card("Session loaded from Drive.", "success", {"Session": sid}) - except Exception as e: - return state, _status_card("Load failed.", "error", - error_msg=format_drive_diagnostic("load", researcher_id=rid, error=e)) - - -# ────────────────────────────────────────────────────────────────────────────── -# Screener handlers -# ────────────────────────────────────────────────────────���───────────────────── - -def fn_run_screener(state: dict): - turns = state.get("turns", []) - if not turns: - return (state, - _status_card("No transcript loaded. Upload a transcript first.", "warning"), - "", "") - - try: - result = screen_transcript(turns) - result_dict = result_to_dict(result) - state["screener_result"] = result_dict - state["stage"] = "screened" - _persist(state) - - speaker_map = state.get("speakers", {}) - summary_html = _screener_summary_html(result_dict) - turns_html = _screener_turns_html(result_dict, speaker_map) - windows_html = _candidate_windows_html(result_dict) return ( - state, - _status_card( - f"Screener complete — {result.flagged_turns} turns flagged, " - f"{len(result.candidate_windows)} candidate windows, " - f"~{result.estimated_llm_savings:.0%} estimated LLM savings.", - "success", - {"Total turns": result.total_turns, - "Flagged": result.flagged_turns, - "Windows": len(result.candidate_windows)}, - ), - summary_html + turns_html, - windows_html, + new_state, + _status_card("Previous session loaded from Drive.", "success", {"Session ID": sid}), ) except Exception as e: - return state, _status_card(f"Screener failed: {e}", "error"), "", "" + 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, + ) -# ────────────────────────────────────────────────────────────────────────────── -# Lexicon handlers -# ────────────────────────────────────────────────────────────────────────────── +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 + 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.") -def fn_load_lexicon_view(): try: - data = load_full_lexicon() - t1_html = _lexicon_tier1_html(data["tier1"]) - t2_html = _lexicon_tier2_html(data["tier2"]) - t3_html = _lexicon_tier3_html(data["tier3"]) - n_t1 = sum(len(c.get("terms", [])) for c in data["tier1"].get("categories", [])) - n_t2 = sum(len(e.get("terms", [])) for e in data["tier2"].get("entries", [])) - n_t3 = sum(1 for c in data["tier3"].get("candidates", []) - if not c.get("approved") and not c.get("rejected")) - return ( - t1_html, t2_html, t3_html, - _status_card( - "Lexicon loaded.", - "success", - {"Tier 1 terms": n_t1, "Tier 2 validated": n_t2, "Tier 3 pending": n_t3}, - ), - ) + 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: + raise except Exception as e: - return "", "", "", _status_card(f"Could not load lexicon: {e}", "error") - + 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.") -def fn_add_tier2(category_id: str, label: str, phase: str, - terms_text: str, weight: float, researcher_id: str, note: str): - terms = [t.strip() for t in terms_text.replace(",", "\n").splitlines() if t.strip()] - if not terms: - return _status_card("Enter at least one term.", "warning"), "", "" + final_state: dict | None = None try: - add_tier2_term( - terms=terms, category_id=category_id or "TIER2_custom", - label=label or "Custom term", phase=phase or "monitoring", - weight=float(weight), added_by=researcher_id or "researcher", note=note, - ) - data = load_full_lexicon() - t2_html = _lexicon_tier2_html(data["tier2"]) - return ( - _status_card(f"Added {len(terms)} term(s) to Tier 2.", "success", - {"Terms": ", ".join(terms[:5])}), - t2_html, "", - ) - except Exception as e: - return _status_card(f"Failed: {e}", "error"), "", "" + for out in fn_process(effective_file, session_id, researcher_id, state): + if isinstance(out, tuple) and out and isinstance(out[0], dict): + final_state = out[0] + yield out + finally: + if temp_path and temp_path.exists(): + try: + temp_path.unlink() + except Exception: + pass + + # 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: + pass -def fn_approve_candidate(term: str, researcher_id: str): - if not term.strip(): - return _status_card("Enter a term to approve.", "warning"), "" - try: - approve_tier3_candidate(term.strip(), approved_by=researcher_id or "researcher") - data = load_full_lexicon() - return ( - _status_card(f"'{term}' approved and moved to Tier 2.", "success"), - _lexicon_tier3_html(data["tier3"]), - ) - except Exception as e: - return _status_card(f"Failed: {e}", "error"), "" +def 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 →") -def fn_reject_candidate(term: str, researcher_id: str, note: str): - if not term.strip(): - return _status_card("Enter a term to reject.", "warning"), "" - try: - reject_tier3_candidate(term.strip(), rejected_by=researcher_id or "researcher", note=note) - data = load_full_lexicon() + def _setup_yield(msg, status="processing", details=None, btn=None): return ( - _status_card(f"'{term}' rejected.", "success"), - _lexicon_tier3_html(data["tier3"]), + state, + _status_card(msg, status, details), + *_show("setup"), + "", # sections_display_html + "", # sections_labels_box + _agent_log_html(state.get("agent_logs", [])), + btn if btn is not None else _BTN_BUSY, ) - except Exception as e: - return _status_card(f"Failed: {e}", "error"), "" - - -# ────────────────────────────────────────────────────────────────────────────── -# SSRL tagging handler (for Review tab) -# ────────────────────────────────────────────────────────────────────────────── - -def fn_save_ssrl_tag(seg_label: str, ssrl_choice: str, state: dict): - segs = _current_section_segments(state) - codings = state.get("codings", {}) - cidx = state.get("coding_idx", 0) - if not segs: - return state, "" - seg = segs[min(cidx, len(segs) - 1)] - sid = seg["segment_id"] - phase = SSRL_ID_FROM_CHOICE.get(ssrl_choice, "NONE") - ssrl = dict(state.get("ssrl_codings", {})) - ssrl[sid] = phase - state["ssrl_codings"] = ssrl - _persist(state) - return state, _status_card(f"SSRL tag '{phase}' saved for {sid}.", "success") - -# ────────────────────────────────────────────────────────────────────────────── -# Transcript processing (from v4, generator) -# ────────────────────────────────────────────────────────────────────────────── + # Immediately disable the button to prevent double-submission + yield _setup_yield("Loading transcript from Drive…") -def fn_process_local(file, researcher_id: str, state: dict): - """Process an uploaded local transcript file.""" - rid = (researcher_id or "").strip() - if not file: - yield state, _status_card("No file selected.", "warning"), _pipeline_status_html(state) - return + t0 = time.perf_counter() try: - path = Path(file.name) if hasattr(file, "name") else Path(str(file)) - text = path.read_text(encoding="utf-8", errors="replace") - turns = parse_transcript(text) + yield _setup_yield("Parsing transcript…", details={"Session": session_id}) + turns = parse_transcript(file_obj.name) except Exception as e: - yield state, _status_card(f"Parse failed: {e}", "error"), _pipeline_status_html(state) - return + raise gr.Error(f"Could not parse transcript: {e}") from e - if not turns: - yield state, _status_card("No turns found in transcript.", "error"), _pipeline_status_html(state) - return + if len(turns) < 5: + raise gr.Error(f"Only {len(turns)} turns found — check the transcript format.") - sid = _auto_session_id(rid, path.name) - speakers = _assign_speakers(turns) - new_state = _empty_state() - new_state.update({"session_id": sid, "researcher_id": rid, - "turns": turns, "speakers": speakers, "stage": "upload"}) - (SESSIONS_ROOT / sid).mkdir(parents=True, exist_ok=True) - (SESSIONS_ROOT / sid / "turns.json").write_text( - json.dumps(turns, indent=2, ensure_ascii=False), encoding="utf-8" - ) - _persist(new_state) + rt = round(time.perf_counter() - t0, 1) + speaker_map = _assign_speakers(turns) + speakers = list(speaker_map.keys()) - yield ( - new_state, - _status_card("Transcript loaded.", "success", - {"Turns": len(turns), "Speakers": len(speakers), "Session": sid}), - _pipeline_status_html(new_state), + new_state = _empty_state() + new_state.update({ + "session_id": session_id.strip(), + "researcher_id": researcher_id.strip(), + "turns": turns, + "speakers": speaker_map, + "stage": "parsed", + }) + log_entry = _make_log_entry( + "Transcript Parser", rt, + turns=len(turns), speakers=len(speakers), + system_prompt_preview="(rule-based parser — no LLM call)", ) + new_state = _push_log(new_state, log_entry) - -def fn_process_with_source(drive_choice: str, researcher_id: str, state: dict): - rid = (researcher_id or "").strip() - if not drive_choice: - yield state, _status_card("Select a transcript first.", "warning"), _pipeline_status_html(state) - return - try: - file_id, file_name = drive_choice.split("::", 1) - service = get_drive_service(rid) - text = read_file_from_drive(service, file_id) - turns = parse_transcript(text) - except Exception as e: - yield state, _status_card(f"Drive load failed: {e}", "error"), _pipeline_status_html(state) - return - - sid = _auto_session_id(rid, file_name) - speakers = _assign_speakers(turns) - new_state = _empty_state() - new_state.update({"session_id": sid, "researcher_id": rid, - "turns": turns, "speakers": speakers, "stage": "upload"}) - (SESSIONS_ROOT / sid).mkdir(parents=True, exist_ok=True) - (SESSIONS_ROOT / sid / "turns.json").write_text( + d = SESSIONS_ROOT / session_id.strip() + d.mkdir(parents=True, exist_ok=True) + (d / "parsed_turns.json").write_text( json.dumps(turns, indent=2, ensure_ascii=False), encoding="utf-8" ) - _persist(new_state) - yield ( - new_state, - _status_card("Drive transcript loaded.", "success", - {"Turns": len(turns), "Speakers": len(speakers), "Session": sid}), - _pipeline_status_html(new_state), + duration = _seconds_to_hms(turns[-1]["start_seconds"] - turns[0]["start_seconds"]) + + # Confirm parse before starting LLM work + yield _setup_yield( + f"Parsed {len(turns)} turns from {len(speakers)} speaker(s). Preparing Agent 0…", + "processing", + {"Turns": len(turns), "Speakers": ", ".join(speakers), "Duration": duration}, ) + # ── Estimate LLM cost BEFORE the call (no extra network hit) ─────────��─── + # Mirrors agent0_sectioner._format_turns_compact() tiers: + # > 600 turns → every other turn shown (×0.5), 30 chars → ~9 tok/turn + # > 400 turns → every turn, 40 chars → ~12 tok/turn + # > 200 turns → every turn, 60 chars → ~16 tok/turn + # ≤ 200 turns → every turn, 120 chars → ~22 tok/turn + n_t = len(turns) + if n_t > 600: + tok_per_turn = 9; effective_turns = n_t // 2 + elif n_t > 400: + tok_per_turn = 12; effective_turns = n_t + elif n_t > 200: + tok_per_turn = 16; effective_turns = n_t + else: + tok_per_turn = 22; effective_turns = n_t + est_in_tok = effective_turns * tok_per_turn + 700 # +700 for system prompt + est_out_tok = 900 # sections JSON is typically 500–1200 tokens + # 35 tok/s observed throughput on HF shared inference; 20s network buffer + est_timeout = max(45, int((est_in_tok + est_out_tok) / 35 + 20)) + + # First heartbeat — LLM call starting + def _hb(elapsed: int, spin_i: int): + return ( + new_state, + _llm_progress_html( + f"Agent 0 — Structural Segmenter: analysing {len(turns)} turns…", + elapsed, est_timeout, est_in_tok, circuit_state(), spin_i, + ), + *_show("setup"), + "", # sections_display_html (empty while processing) + "", # sections_labels_box + _agent_log_html(new_state["agent_logs"]), + _BTN_BUSY, + ) -# ────────────────────────────────────────────────────────────────────────────── -# Agent 0 — sectioning (generator) -# ────────────────────────────────────────────────────────────────────────────── + yield _hb(0, 0) -def fn_run_agent0(state: dict): - turns = state.get("turns", []) - if not turns: - yield state, _status_card("Load a transcript first.", "warning"), _pipeline_status_html(state) - return + # ── Run Agent 0 in a daemon thread so Gradio stays responsive ──────────── + result_q: _queue.Queue = _queue.Queue() - yield (state, - _loading_card("Agent 0 — detecting structural sections…", - f"Processing {len(turns)} turns"), - _pipeline_status_html(state)) + def _run_agent0(): + try: + res = run_sectioning(turns=new_state["turns"], + session_id=new_state["session_id"]) + result_q.put(("ok", res)) + except Exception as exc: + result_q.put(("err", exc)) + + thread = threading.Thread(target=_run_agent0, daemon=True) + thread.start() + t_llm = time.perf_counter() + spin_i = 1 + + # Heartbeat: yield progress every 2 s while the LLM call is in flight + while thread.is_alive(): + time.sleep(2) + elapsed = int(time.perf_counter() - t_llm) + yield _hb(elapsed, spin_i) + spin_i += 1 - t0 = time.time() - try: - result = run_sectioning(turns, state.get("session_id", "")) - except Exception as e: - yield state, _status_card(f"Agent 0 failed: {e}", "error"), _pipeline_status_html(state) - return + # ── Collect result ──────────────────────────────────────────────────────── + outcome, payload = result_q.get() + if outcome == "err": + raise gr.Error(f"Section detection failed: {payload}") from payload - sections = result.get("sections", []) - elapsed = round(time.time() - t0, 1) - speakers = state.get("speakers", {}) + result = payload + sections = result["sections"] + if not sections: + raise gr.Error("Agent 0 returned no sections — try again.") + + from agent0_sectioner import build_system_prompt, load_dimension_labels + sys_prev = build_system_prompt(load_dimension_labels())[:120] + agent0_rt = round(time.perf_counter() - t_llm, 1) + + new_state = dict(new_state) + new_state.update({ + "sections": sections, + "section_stages": {s["section_id"]: "pending" for s in sections}, + "stage": "sectioned", + "_agent0_overview": result.get("session_overview", ""), + }) + log2 = _make_log_entry( + "Agent 0 — Structural Segmenter", agent0_rt, + sections_proposed=len(sections), + warnings=len(result.get("warnings", [])), + system_prompt_preview=sys_prev, + ) + new_state = _push_log(new_state, log2) - new_state = dict(state) - new_state["sections"] = sections - new_state["stage"] = "sectioned" - d = _session_dir(new_state) - d.mkdir(parents=True, exist_ok=True) (d / "sections_proposed.json").write_text( json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8" ) - new_state = _push_log(new_state, _make_log_entry( - "Agent 0", elapsed, sections=len(sections), turns=len(turns) - )) - _persist(new_state) - sec_html = _sections_html(sections, len(turns), elapsed, len(speakers), turns) + overview = result.get("session_overview", "") + sections_md = ( + "| # | Label | Turns | Time |\n|---|---|---|---|\n" + + "\n".join( + f"| {s['section_id']} | **{s['label']}** | " + f"{s['start_turn_id']}–{s['end_turn_id']} | " + f"{s['start_time']}–{s['end_time']} |" + for s in sections + ) + + (f"\n\n*{overview}*" if overview else "") + ) + # Pre-fill with "s01: Label" format so the mapping is unambiguous + labels_txt = "\n".join(f"{s['section_id']}: {s['label']}" for s in sections) + + if result.get("warnings"): + gr.Warning("Coverage warnings — check the section table.") + gr.Info(f"Ready: {len(turns)} turns · {len(sections)} sections detected in {agent0_rt}s.") + + # Build the rich sections HTML — pass turns so sections are expandable + sec_html = _sections_html(sections, len(turns), agent0_rt, len(speakers), + all_turns=turns) + yield ( new_state, - _status_card("Agent 0 done.", "success", - {"Turns": len(turns), "Sections": len(sections), "Time": f"{elapsed}s"}), - _pipeline_status_html(new_state), + _status_card( # shown briefly, then page switches + "Agent 0 done — review sections.", "success", + {"Turns": len(turns), "Sections": len(sections), "Time": f"{agent0_rt}s"}, + ), + *_show("sections"), # ← navigate to sections page + sec_html, # rich HTML card + visual grid + labels_txt, # pre-fill the label editor + _agent_log_html(new_state["agent_logs"]), + _BTN_FREE, # re-enable process button ) +# ── Confirm sections ────────────────────────────────────────────────────────── + def fn_confirm_sections(labels_text: str, state: dict): + """ + Generator: immediately shows a 'confirming' state (so the user knows + their click registered), then navigates to the pipeline page. + """ sections = state.get("sections", []) if not sections: - return state, _status_card("No sections to confirm.", "warning"), _pipeline_status_html(state) + raise gr.Error("No sections to confirm — process a transcript first.") + + _BUSY_HTML = ( + '
    ' + '
    ' + '◑' + 'Saving section labels and loading pipeline…' + '
    ' + '
    ' + 'Please wait — this takes only a moment.' + '
    ' + ) + + # ── Yield 1: immediate feedback, stay on sections page ──────────────────── + yield ( + state, + *_show("sections"), + gr.update(value=_BUSY_HTML), # sections_display_html + gr.update(interactive=False, value="⏳ Saving…"), # confirm_sections_btn + gr.update(visible=True), # col_run_all_boundaries (Column — visible only) + gr.update(visible=False), # col_boundary_review + gr.update(visible=False), # col_coding + ) + # ── Process (fast: no LLM, just in-memory + disk) ───────────────────────── + # Parse "s01: My Label" or plain "My Label" (both accepted) raw_lines = [l.strip() for l in labels_text.strip().splitlines() if l.strip()] labels = [] for line in raw_lines: + # Strip "sXX: " or "sXX:" prefix if present if ":" in line: prefix, _, rest = line.partition(":") if prefix.strip().lower().startswith("s") and prefix.strip()[1:].isdigit(): @@ -1523,236 +1600,671 @@ def fn_confirm_sections(labels_text: str, state: dict): confirmed = [dict(s, label=labels[i] if i < len(labels) else s["label"]) for i, s in enumerate(sections)] + if len(labels) != len(sections): + gr.Warning( + f"Label count mismatch ({len(labels)} labels for {len(sections)} sections) — " + f"AI labels used for any extras." + ) + new_state = dict(state) - new_state["sections"] = confirmed - new_state["section_idx"] = 0 - new_state["section_stages"] = {s["section_id"]: "pending" for s in confirmed} + new_state.update({ + "sections": confirmed, + "section_idx": 0, + "section_stages": {s["section_id"]: "pending" for s in confirmed}, + "section_a1a_results": {}, + "stage": "coding", + }) + d = _session_dir(new_state) - d.mkdir(parents=True, exist_ok=True) (d / "sections_confirmed.json").write_text( - json.dumps({"sections": confirmed}, indent=2, ensure_ascii=False), encoding="utf-8" + json.dumps(confirmed, indent=2, ensure_ascii=False), encoding="utf-8" ) _persist(new_state) - labels_txt = "\n".join(f"{s['section_id']}: {s['label']}" for s in confirmed) - return (new_state, - _status_card("Sections confirmed.", "success", {"Count": len(confirmed)}), - _pipeline_status_html(new_state)) + gr.Info(f"{len(confirmed)} sections confirmed. Click 'Detect Episode Boundaries' to continue.") + print(f"[Confirm Sections] {len(confirmed)} sections saved for session {new_state['session_id']}") + + # ── Yield 2: navigate to pipeline page ──────────────────────────────────── + yield ( + new_state, + *_show("pipeline"), + gr.update(value=""), # sections_display_html (leaving) + gr.update(interactive=True, value="Confirm Sections →"), # reset button for if user navigates back + gr.update(visible=True), # col_run_all_boundaries + gr.update(visible=False), # col_boundary_review + gr.update(visible=False), # col_coding + ) -# ────────────────────────────────────────────────────────────────────────────── -# Pipeline — boundaries + coding (generator) -# ────────────────────────────────────────────────────────────────────────────── +# ── Agent 1a — parallel boundary detection ─────────────────────────────────── -def fn_run_pipeline(state: dict): +def fn_run_all_boundaries(state: dict): sections = state.get("sections", []) - turns = state.get("turns", []) - if not sections or not turns: - yield state, _status_card("Confirm sections first.", "warning"), _pipeline_status_html(state) - return + if not sections: + raise gr.Error("Confirm sections first.") + if not state.get("turns"): + raise gr.Error("No parsed turns — parse the transcript first.") + + n = len(sections) + session_overview = state.get("_agent0_overview", "") + collected = {} + pipeline_stats_html = "" + + def _a1a_banner(done: int, total: int, status: str = "running") -> str: + pct = int(done / total * 100) if total else 0 + color = "#4338ca" if status == "running" else "#065f46" if status == "done" else "#be123c" + icon = "⏳" if status == "running" else "✓" if status == "done" else "✗" + return ( + f'
    ' + f'
    ' + f'{icon}' + f'Agent 1a — Boundary Detector' + f'' + f'{done}/{total} sections · {pct}%' + f'
    ' + f'
    ' + f'
    ' + f'
    ' + f'Parallel map pattern (Dean & Ghemawat 2004) · ' + f'Basis: Schegloff (2007) adjacency pairs · ' + f'Krippendorff (2004) unitising precedes categorising' + f'
    ' + ) - q = _queue.Queue() - new_state = dict(state) - t0 = time.time() - done = threading.Event() + # Initial yield — show banner immediately + yield ( + state, + f"⏳ Running Agent 1a on {n} section(s) (max 3 concurrent)…", + "", + gr.update(visible=False), + gr.update(visible=False, value=""), + gr.update(visible=False, value=""), + "", + _agent_log_html(state.get("agent_logs", [])), + _a1a_banner(0, n, "running"), + gr.update(value=""), # episode_dialogue_html — clear while processing + ) - def _worker(): - try: - result = run_coding_with_context( - turns=turns, sections=sections, - session_id=new_state.get("session_id", ""), - progress_queue=q, - ) - q.put({"type": "done", "result": result}) - except Exception as e: - q.put({"type": "error", "msg": str(e)}) - finally: - done.set() - - threading.Thread(target=_worker, daemon=True).start() - - spin_i = 0 - while not done.is_set(): - time.sleep(1.5) - elapsed = int(time.time() - t0) - circ = circuit_state() - yield ( - new_state, - _llm_progress_html("Running pipeline (boundaries + coding)…", - elapsed, 180, len(turns) * 500, circ, spin_i), - _pipeline_status_html(new_state), - ) - spin_i += 1 + pstats = PipelineStats(agent_name="Agent 1a — Boundary Detector", n_sections=n) try: - msg = q.get_nowait() - except _queue.Empty: - msg = {"type": "error", "msg": "Queue empty after done signal."} + for sr, pstats in run_boundaries_parallel( + sections=sections, + all_turns=state["turns"], + session_id=state["session_id"], + session_overview=session_overview, + ): + if sr.success: + collected[sr.section_id] = sr.result + else: + gr.Warning(f"Section {sr.section_id} failed: {sr.error}") + + processed = len(pstats.results) + failed_sids = {x.section_id for x in pstats.results if not x.success} + prog_lines = [] + for s in sections: + sid = s["section_id"] + res = collected.get(sid) + failed = sid in failed_sids + if res: + b = len(res.get("boundaries", [])) + e = len(res.get("segments", [])) + prog_lines.append(f"✓ **{sid}** {s['label']} — {b} boundaries → {e} episodes") + elif failed: + prog_lines.append(f"✗ **{sid}** {s['label']} — ERROR") + else: + prog_lines.append(f"⏳ **{sid}** {s['label']}…") + + status_md = f"**{processed}/{n} sections complete**\n\n" + "\n\n".join(prog_lines) + pipeline_stats_html = render_pipeline_stats_html(pstats) + + yield ( + state, + status_md, + pipeline_stats_html, + gr.update(visible=False), + gr.update(visible=False, value=""), + gr.update(visible=False, value=""), + "", + _agent_log_html(state.get("agent_logs", [])), + _a1a_banner(processed, n, "running"), + gr.update(value=""), # episode_dialogue_html — still processing + ) - if msg.get("type") == "error": - yield new_state, _status_card(f"Pipeline failed: {msg['msg']}", "error"), \ - _pipeline_status_html(new_state) - return + except Exception as e: + raise gr.Error(f"Parallel boundary detection failed: {e}") from e + + # All done — update state + state = dict(state) + n_success = len(collected) + n_error = n - n_success + + for sec in sections: + sid = sec["section_id"] + result = collected.get(sid) + if result: + state["section_boundaries"][sid] = result["boundaries"] + state["section_segments"][sid] = result["segments"] + state["section_stages"][sid] = "boundaries" + state.setdefault("section_a1a_results", {})[sid] = result + else: + state["section_stages"][sid] = "error" - result = msg["result"] - elapsed = round(time.time() - t0, 1) - coded_map = result.get("section_segments_coded", {}) - n_segs = sum(len(v) for v in coded_map.values()) - - new_state["section_segments_coded"] = coded_map - new_state["codings"] = result.get("codings", {}) - new_state["stage"] = "coded" - new_state = _push_log(new_state, _make_log_entry( - "Pipeline", elapsed, segments=n_segs, sections=len(sections) - )) - d = _session_dir(new_state) - d.mkdir(parents=True, exist_ok=True) - (d / "codings.json").write_text( - json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8" + log = _make_log_entry( + "Agent 1a — Boundary Detector (parallel)", round(pstats.parallel_wall_s, 1), + sections_ok=n_success, sections_error=n_error, + speedup=f"{pstats.speedup:.1f}x", + total_est_tokens=pstats.total_estimated_tokens, ) - _persist(new_state) + state = _push_log(state, log) + _persist(state) - yield ( - new_state, - _status_card("Pipeline complete.", "success", - {"Segments": n_segs, "Sections": len(sections), "Time": f"{elapsed}s"}), - _pipeline_status_html(new_state), + sec = sections[0] + turns = _turns_for_section(state["turns"], sec) + result = collected.get(sec["section_id"], {}) + bounds = result.get("boundaries", []) + ids_txt = ", ".join(str(b["after_turn_id"]) for b in bounds) + + status_final = ( + f"✓ {n_success}/{n} sections analysed " + f"({pstats.parallel_wall_s:.0f}s parallel · {pstats.speedup:.1f}× speedup).\n\n" + f"Review boundaries for each section below, then confirm to start coding." ) + if n_error: + status_final += f"\n\n⚠ {n_error} section(s) failed — enter boundary turn IDs manually." + gr.Info(f"Parallel analysis complete: {n_success}/{n} sections OK.") + print(f"[Agent 1a] Complete: {n_success}/{n} OK in {pstats.parallel_wall_s:.1f}s " + f"({pstats.speedup:.1f}× speedup)") -# ────────────────────────────────────────────────────────────────────────────── -# Segment coding (manual, per-episode) -# ────────────────────────────────────────────────────────────────────────────── + # Build dialogue view for the first section to review + first_result = collected.get(sec["section_id"], {}) + first_segs = first_result.get("segments", []) + ep_dial_html = _episode_dialogue_html(first_segs, bounds, state["speakers"]) -def fn_save_coding(dim_choice: str, sec_choice: str, note: str, state: dict): - segs = _current_section_segments(state) - codings = state.get("codings", {}) - cidx = state.get("coding_idx", 0) - if not segs or not dim_choice: - return state, "", _pipeline_status_html(state) - seg = segs[min(cidx, len(segs) - 1)] - sid = seg["segment_id"] - did = DIM_ID_FROM_CHOICE.get(dim_choice, "") - sec_id = SEC_ID_FROM_CHOICE.get(sec_choice or SEC_NONE) - codings = dict(codings) - codings[sid] = {"dimension_id": did, "secondary_dimension_id": sec_id, - "note": note, "coded_by": state.get("researcher_id", "")} - state["codings"] = codings - _persist(state) - return state, _status_card(f"Saved {did} for {sid}.", "success"), _pipeline_status_html(state) + yield ( + state, + status_final, + pipeline_stats_html, + gr.update(visible=True), + gr.update(visible=True, value=_episode_table_html(turns, bounds)), + gr.update(visible=True, value=ids_txt), + f"### Reviewing: {sec['label']} ({sec['section_id']})", + _agent_log_html(state["agent_logs"]), + _a1a_banner(n_success, n, "done" if n_error == 0 else "error"), + ep_dial_html, # full dialogue view — researcher reads this before confirming + ) -def fn_nav_segment(direction: str, state: dict): - segs = _current_section_segments(state) - cidx = state.get("coding_idx", 0) - if not segs: - return state - if direction == "next": - cidx = min(cidx + 1, len(segs) - 1) - else: - cidx = max(cidx - 1, 0) - state["coding_idx"] = cidx - return state +# ── Confirm boundaries + run Agent 1b ──────────────────────────────────────── +def fn_confirm_and_code(boundary_ids_text: str, state: dict): + sec = _current_section(state) + if not sec: + raise gr.Error("No section loaded.") -def fn_nav_section(direction: str, state: dict): - secs = state.get("sections", []) - idx = state.get("section_idx", 0) - if direction == "next": - idx = min(idx + 1, len(secs) - 1) - else: - idx = max(idx - 1, 0) - state["section_idx"] = idx - state["coding_idx"] = 0 - return state + 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] = [] -# ────────────────────────────────────────────────────────────────────────────── -# Agreement handlers -# ────────────────────────────────────────────────────────────────────────────── + for tok in boundary_ids_text.split(","): + tok = tok.strip() + if not tok: + continue + try: + tid = int(tok) + except ValueError: + raise gr.Error(f"'{tok}' is not a valid turn ID.") + if tid not in valid_ids: + raise gr.Error( + f"Turn {tid} is outside this section " + f"(valid: {min(valid_ids)}–{max(valid_ids)})." + ) + boundaries.append({"boundary_id": f"r_{tid}", "after_turn_id": tid, + "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) -def fn_calculate_kappa(r1_file, r2_file, state: dict): - if not r1_file or not r2_file: - return state, _status_card("Upload both R1 and R2 coding files.", "warning"), \ - _pipeline_status_html(state) - try: - r1 = json.loads(Path(r1_file.name).read_text(encoding="utf-8")) - r2 = json.loads(Path(r2_file.name).read_text(encoding="utf-8")) - all_segs = [] - for sec_segs in state.get("section_segments_coded", {}).values(): - all_segs.extend(sec_segs) - report = calculate_kappa_report(r1, r2, all_segs) - state["kappa_report"] = report - state["stage"] = "agreed" - _persist(state) - d = _session_dir(state) - d.mkdir(parents=True, exist_ok=True) - (d / "kappa_report.json").write_text( - json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8" - ) - summary = _kappa_summary_html(report) - disag_h = _disagreement_html(report, all_segs) - return state, _status_card("Kappa calculated.", "success"), _pipeline_status_html(state) - except Exception as e: - return state, _status_card(f"Kappa failed: {e}", "error"), _pipeline_status_html(state) + if not segments: + raise gr.Error("No segments produced — check your boundary turn IDs.") + state["section_boundaries"][sec["section_id"]] = boundaries + state["section_segments"][sec["section_id"]] = segments -# ────────────────────────────────────────────────────────────────────────────── -# Learning (Agent 2) handlers -# ────────────────────────────────────────────────────────────────────────────── + yield ( + state, + _loading_card("Loading coding stage…", f"Agent 1b is preparing {len(segments)} episode(s) for coding."), + gr.update(visible=False), + *CODING_EMPTY, + "", + ) -def fn_load_pending_rules(): + agent1a_result = state.get("section_a1a_results", {}).get(sec["section_id"]) + t0 = time.perf_counter() try: - rules = list_pending_rules() - if not rules: - return '

    No pending rules.

    ' - parts = ['
    '] - for r in rules: - rid = _h(r.get("rule_id", "")) - desc = _h(r.get("description", "")) - src = _h(r.get("source_sessions", "")) - parts.append( - f'
    ' - f'
    {rid}
    ' - f'
    {desc}
    ' - f'
    ' - f'From sessions: {src}
    ' - f'
    ' + coded, llm_stats = run_coding_with_context( + section=sec, + segments=segments, + agent1a_result=agent1a_result, + ) + except Exception as e: + raise gr.Error(f"Agent 1b failed: {e}") from e + + rt = round(time.perf_counter() - t0, 1) + n_uncertain = sum(1 for s in coded if s.get("uncertain")) + state["section_segments_coded"][sec["section_id"]] = coded + state["section_stages"][sec["section_id"]] = "coding" + state["coding_idx"] = 0 + log = _make_log_entry( + "Agent 1b — Dimension Coder", rt, + segments_coded=len(coded), + uncertain_flagged=n_uncertain, + system_prompt_preview=f"Context chain: section={sec['label']}", + user_prompt_preview=f"Code {len(segments)} segments", + ) + state = _push_log(state, log) + + d = _session_dir(state) + (d / f"segments_{sec['section_id']}.json").write_text( + json.dumps(coded, indent=2, ensure_ascii=False), encoding="utf-8" + ) + + msg = f"✓ {len(coded)} segments coded ({rt}s)." + if n_uncertain: + msg += f" **{n_uncertain} flagged ⚠ — review these first.**" + gr.Info(f"{len(coded)} segments coded. {n_uncertain} uncertain.") + + yield state, msg, gr.update(visible=True), *_render_coding(state), _agent_log_html(state["agent_logs"]) + + +# ── Navigate segments ───────────────────────────────────────────────────────── + +def fn_navigate(direction: int, dim_choice: str, sec_choice: str, comment: str, state: dict): + segs = _current_section_segments(state) + if not segs: + return state, *_render_coding(state) + idx = state.get("coding_idx", 0) + codings = dict(state.get("codings", {})) + sid = segs[idx]["segment_id"] + if dim_choice: + codings[sid] = { + "dimension_id": DIM_ID_FROM_CHOICE[dim_choice], + "secondary_dimension_id":SEC_ID_FROM_CHOICE.get(sec_choice or SEC_NONE), + "comment": comment.strip(), + } + state = dict(state) + state["codings"] = codings + state["coding_idx"] = max(0, min(idx + direction, len(segs) - 1)) + return state, *_render_coding(state) + + +def fn_jump(label: str, state: dict): + segs = _current_section_segments(state) + if not segs or not label: + return state, *_render_coding(state) + codings = state.get("codings", {}) + labels = [_segment_label(s, codings) for s in segs] + state = dict(state) + if label in labels: + state["coding_idx"] = labels.index(label) + return state, *_render_coding(state) + + +def fn_reveal(state: dict): + segs = _current_section_segments(state) + if not segs: + return gr.update(visible=False) + seg = segs[min(state.get("coding_idx", 0), len(segs) - 1)] + return gr.update(value=_proposal_md(seg), visible=True) + + +def fn_dim_desc(choice: str): + return _dim_desc_html(choice or "") + + +# ── Next section / finish ───────────────────────────────────────────────────── + +def fn_next_section(dim_choice: str, sec_choice: str, comment: str, state: dict): + segs = _current_section_segments(state) + codings = dict(state.get("codings", {})) + idx = state.get("coding_idx", 0) + if segs and dim_choice: + sid = segs[min(idx, len(segs) - 1)]["segment_id"] + codings[sid] = { + "dimension_id": DIM_ID_FROM_CHOICE[dim_choice], + "secondary_dimension_id":SEC_ID_FROM_CHOICE.get(sec_choice or SEC_NONE), + "comment": comment.strip(), + } + + new_state = dict(state) + new_state["codings"] = codings + sections = new_state.get("sections", []) + sec_idx = new_state.get("section_idx", 0) + cur_id = sections[sec_idx]["section_id"] + new_state["section_stages"][cur_id] = "done" + next_idx = sec_idx + 1 + + if next_idx >= len(sections): + # All done — navigate to done page + new_state["stage"] = "complete" + _write_coding_file(new_state) + _persist(new_state) + gr.Info("All sections coded! Download your coding file.") + print(f"[Done] All {len(sections)} sections coded for session {new_state['session_id']}") + return ( + new_state, + *_show("done"), + _section_cards_html(sections, new_state["section_stages"], sec_idx), + "", # section_header_md + gr.update(visible=False), # col_boundary_review + gr.update(visible=False), # col_coding + gr.update(value=""), # boundary_display_html + gr.update(value=""), # boundary_ids_box + gr.update(value=""), # episode_dialogue_html + ) + + # More sections remain — populate boundary review for the next section + new_state["section_idx"] = next_idx + new_state["coding_idx"] = 0 + next_sec = sections[next_idx] + n = next_sec["end_turn_id"] - next_sec["start_turn_id"] + 1 + hdr = ( + f"### Section {next_idx+1} of {len(sections)}: {next_sec['label']}\n" + f"*{next_sec.get('summary','')}* · " + f"turns {next_sec['start_turn_id']}–{next_sec['end_turn_id']} ({n} turns)" + ) + _persist(new_state) + + result = new_state.get("section_a1a_results", {}).get(next_sec["section_id"], {}) + bounds = result.get("boundaries", []) + next_segs = result.get("segments", []) + turns = _turns_for_section(new_state["turns"], next_sec) + ids_txt = ", ".join(str(b["after_turn_id"]) for b in bounds) + ep_html = _episode_dialogue_html(next_segs, bounds, new_state["speakers"]) + + gr.Info(f"Section {next_idx+1} of {len(sections)}: {next_sec['label']}") + print(f"[Next Section] Moving to section {next_idx+1}: {next_sec['label']}") + return ( + new_state, + *_show("pipeline"), + _section_cards_html(sections, new_state["section_stages"], next_idx), + hdr, + gr.update(visible=True), # col_boundary_review + gr.update(visible=False), # col_coding + gr.update(value=_episode_table_html(turns, bounds)), # boundary_display_html + gr.update(value=ids_txt), # boundary_ids_box + ep_html, # episode_dialogue_html + ) + + +# ── Download ────────────────────────────────────────────────────────────────── + +def _write_coding_file(state: dict) -> Path: + all_segs: list[dict] = [] + for sec in state.get("sections", []): + all_segs.extend(state["section_segments_coded"].get(sec["section_id"], [])) + codings = state.get("codings", {}) + output = { + "session_id": state["session_id"], + "researcher_id": state["researcher_id"], + "codings": [ + { + "segment_id": s["segment_id"], + "section_id": s.get("section_id", ""), + "dimension_id": codings.get(s["segment_id"], {}).get("dimension_id", ""), + "secondary_dimension_id":codings.get(s["segment_id"], {}).get("secondary_dimension_id"), + "comment": codings.get(s["segment_id"], {}).get("comment", ""), + } + for s in all_segs + ], + } + segs_all = {"segments": [{k: v for k, v in s.items() if k != "turns"} for s in all_segs]} + d = _session_dir(state) + (d / "segments_all.json").write_text( + json.dumps(segs_all, indent=2, ensure_ascii=False), encoding="utf-8" + ) + out = d / f"coding_{state['researcher_id']}.json" + out.write_text(json.dumps(output, indent=2, ensure_ascii=False), encoding="utf-8") + return out + + +def fn_download(state: dict): + if not state.get("sections"): + raise gr.Error("No coding to download yet.") + path = _write_coding_file(state) + tmp = Path(tempfile.mktemp(suffix=f"_{path.name}")) + tmp.write_bytes(path.read_bytes()) + return str(tmp) + + +# ── Agreement ───────────────────────────────────────────────────────────────── + +def fn_calculate_kappa(r2_file, state: dict): + if r2_file is None: + raise gr.Error("Upload your co-researcher's coding file first.") + if not state.get("session_id"): + raise gr.Error("Complete the Pipeline first — session ID not set.") + + d = _session_dir(state) + r1_path = d / f"coding_{state['researcher_id']}.json" + segs_path = d / "segments_all.json" + + if not r1_path.exists(): + raise gr.Error("Your own coding file not found — download it from the Pipeline first.") + if not segs_path.exists(): + raise gr.Error("Segments file not found — complete the coding pipeline first.") + + r2_path = d / "coding_R2.json" + r2_path.write_bytes(Path(r2_file.name).read_bytes()) + + t0 = time.perf_counter() + try: + report = calculate_kappa_report( + session_id=state["session_id"], + coding_r1_path=r1_path, + coding_r2_path=r2_path, + proposed_segments_path=segs_path, + output_path=d / "kappa_report.json", + ) + except Exception as e: + raise gr.Error(f"Kappa calculation failed: {e}") from e + + rt = round(time.perf_counter() - t0, 1) + gate = report.get("gate_passed", False) + n_dis = len(report.get("segments_in_disagreement", [])) + + state = dict(state) + state["kappa_report"] = report + log = _make_log_entry("Kappa Calculator", rt, + kappa=round(report.get("overall_kappa", 0), 3), + gate_passed=gate, disagreements=n_dis) + state = _push_log(state, log) + + if gate: + gr.Info(f"κ={report['overall_kappa']:.3f} — gate passed! {n_dis} disagreements to resolve.") + else: + gr.Warning(f"κ={report['overall_kappa']:.3f} — below 0.70 threshold.") + + dis_md = "" + if n_dis: + dis = report.get("segments_in_disagreement", []) + rows = "| Segment | R1 | R2 | Agent 1b |\n|---|---|---|---|\n" + for di in dis[:20]: + rows += ( + f"| `{di['segment_id']}` " + f"| {di.get('r1_dimension','?')} " + f"| {di.get('r2_dimension','?')} " + f"| {di.get('agent_dimension','?')} |\n" ) - parts.append('
    ') - return "".join(parts) + if len(dis) > 20: + rows += f"| *…{len(dis)-20} more* | | | |\n" + dis_md = f"### Disagreements ({n_dis})\n\n{rows}" + + return ( + state, + _kappa_html(report), + dis_md, + gr.update(visible=bool(n_dis)), + _agent_log_html(state["agent_logs"]), + ) + + +def fn_run_sequence_analysis(rater_choice: str, state: dict): + if not state.get("session_id"): + raise gr.Error("No session loaded — complete the Pipeline first.") + + d = _session_dir(state) + try: + path = d / "coding_R2.json" if "R2" in rater_choice else d / f"coding_{state['researcher_id']}.json" + if not path.exists(): + raise gr.Error(f"Coding file not found: {path.name}.") + analysis = load_and_analyse(path, max_lag=3) + except gr.Error: + raise except Exception as e: - return f'

    Error: {_h(str(e))}

    ' + raise gr.Error(f"Sequence analysis failed: {e}") from e + + if "error" in analysis: + raise gr.Error(analysis["error"]) + + stat = analysis.get("statistics", {}) + n_ep = stat.get("n_episodes", 0) + n_tr = stat.get("n_transitions", 0) + cats = stat.get("categories_used", []) + entropy = stat.get("transition_entropy", 0.0) + ent_max = stat.get("entropy_max", 0.0) + sig_pos = stat.get("significant_pos", []) + sig_neg = stat.get("significant_neg", []) + + ent_note = ( + f"**{entropy:.3f}** bits / max {ent_max:.3f} — " + + ("high entropy: no strong sequential pattern" + if ent_max > 0 and entropy / ent_max > 0.80 + else "moderate entropy: some transitions dominate" + if ent_max > 0 and entropy / ent_max > 0.50 + else "low entropy: a few transitions strongly dominate") + ) + warnings = analysis.get("sparse_warnings", []) + warn_md = "" + if warnings: + warn_md = ( + f"\n\n*⚠ {len(warnings)} sparse cell(s): " + f"{'; '.join(warnings[:3])}{'…' if len(warnings) > 3 else ''}*" + ) -def fn_approve_rule_action(rule_id: str): - if not rule_id.strip(): - return _status_card("Enter a rule ID.", "warning"), fn_load_pending_rules() + summary_md = ( + f"**{n_ep}** episodes · **{n_tr}** transitions · " + f"**{len(cats)}** dimensions: `{'`, `'.join(cats)}` \n" + f"Entropy: {ent_note} \n" + f"**{len(sig_pos)}** significantly common · **{len(sig_neg)}** significantly rare" + f"{warn_md}" + ) + + gr.Info(f"Sequence analysis: {n_ep} episodes, {len(sig_pos)} significant transitions.") + return summary_md, render_transition_matrix_html(analysis), render_significant_transitions_html(analysis), gr.update(visible=True) + + +def fn_download_seq_csv(rater_choice: str, state: dict): + if not state.get("session_id"): + raise gr.Error("No session loaded.") + d = _session_dir(state) + path = d / ("coding_R2.json" if "R2" in rater_choice else f"coding_{state['researcher_id']}.json") + if not path.exists(): + raise gr.Error(f"Coding file not found: {path.name}") + analysis = load_and_analyse(path) + if "error" in analysis: + raise gr.Error(analysis["error"]) + csv_str = seq_to_csv(analysis) + tmp = Path(tempfile.mktemp(suffix=f"_transitions_{state['session_id']}.csv")) + tmp.write_text(csv_str, encoding="utf-8") + return str(tmp) + + +def fn_resolve(seg_id: str, dim_choice: str, note: str, state: dict): + if not seg_id.strip(): + raise gr.Error("Enter the segment ID.") + if not dim_choice: + raise gr.Error("Select the resolved dimension.") + resolved = DIM_ID_FROM_CHOICE.get(dim_choice, dim_choice) try: - approve_rule(rule_id.strip()) - return _status_card(f"Rule '{rule_id}' approved.", "success"), fn_load_pending_rules() + resolve_disagreement( + report_path=_session_dir(state) / "kappa_report.json", + segment_id=seg_id.strip(), resolved_dimension=resolved, + resolution_note=note.strip(), + ) except Exception as e: - return _status_card(f"Failed: {e}", "error"), fn_load_pending_rules() + raise gr.Error(f"Could not resolve: {e}") from e + gr.Info(f"Resolved {seg_id.strip()} → {resolved}") + return state, f"✓ `{seg_id.strip()}` → **{resolved}**" -def fn_reject_rule_action(rule_id: str, note: str): - if not rule_id.strip(): - return _status_card("Enter a rule ID.", "warning"), fn_load_pending_rules() +def fn_discard(seg_id: str, note: str, state: dict): + if not seg_id.strip(): + raise gr.Error("Enter the segment ID.") try: - reject_rule(rule_id.strip(), note) - return _status_card(f"Rule '{rule_id}' rejected.", "success"), fn_load_pending_rules() + discard_disagreement( + report_path=_session_dir(state) / "kappa_report.json", + segment_id=seg_id.strip(), discard_note=note.strip(), + ) except Exception as e: - return _status_card(f"Failed: {e}", "error"), fn_load_pending_rules() + raise gr.Error(f"Could not discard: {e}") from e + gr.Info(f"Discarded {seg_id.strip()}") + return state, f"Discarded `{seg_id.strip()}`" -# ────────────────────────────────────────────────────────────────────────────── -# GRADIO UI -# ────────────────────────────────────────────��───────────────────────────────── +# ── Rules ───────────────────────────────────────────────────────────────────── + +def fn_load_rules(): + pending = list_pending_rules() + choices = [f"{r['rule_id']}: {r['description'][:55]}…" for r in pending] + return _rules_html(pending), choices + + +def fn_approve(choice: str, researcher: str, note: str): + if not choice: + raise gr.Error("Select a rule.") + if not researcher.strip(): + raise gr.Error("Enter your Researcher ID.") + rid = choice.split(":")[0].strip() + approve_rule(rid, researcher.strip(), note.strip()) + gr.Info(f"Rule {rid} approved.") + return f"✓ Rule **{rid}** approved — now active for Agent 1b." + + +def fn_reject(choice: str, researcher: str, note: str): + if not choice: + raise gr.Error("Select a rule.") + if not researcher.strip(): + raise gr.Error("Enter your Researcher ID.") + if not note.strip(): + raise gr.Error("Provide a rejection reason — Agent 2 learns from it.") + rid = choice.split(":")[0].strip() + reject_rule(rid, researcher.strip(), note.strip()) + gr.Info(f"Rule {rid} rejected.") + return f"✗ Rule **{rid}** rejected." + + +# =========================================================================== +# CSS +# =========================================================================== + +EXTRA_CSS = """ +.gradio-container { + max-width: 1200px !important; + margin: 0 auto !important; + background: #ececee !important; + font-family: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Arial, sans-serif !important; +} +footer { display: none !important; } -CUSTOM_CSS = """ -/* ── Palette (matches original) ─────────────────────── */ :root { --cc-bg: #ececee; --cc-surface: #f6f6f7; @@ -1764,18 +2276,10 @@ CUSTOM_CSS = """ --cc-accent-deep: #ea4425; } -/* ── Global ──────────────────────────────────────────── */ -.gradio-container { - max-width: 1200px !important; - margin: 0 auto !important; - background: var(--cc-bg) !important; - font-family: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Arial, sans-serif !important; -} -footer { display: none !important; } :focus-visible { outline: 2px solid var(--cc-accent) !important; outline-offset: 2px; } :focus { outline: none; } -/* ── Buttons ─────────────────────────────────────────── */ +/* Primary button */ .gradio-container button.primary { background: var(--cc-accent) !important; border-color: var(--cc-accent) !important; @@ -1786,36 +2290,12 @@ footer { display: none !important; } background: var(--cc-accent-deep) !important; border-color: var(--cc-accent-deep) !important; } -.gradio-container button:not(.primary) { border-color: #c9cdd3 !important; } - -/* ── Pipeline header ─────────────────────────────────── */ -.pipeline-header { - position: sticky; - top: 0; - z-index: 100; - background: white; - border-bottom: 2px solid var(--cc-border); - box-shadow: 0 2px 8px rgba(234,88,12,0.07); +.gradio-container button.secondary, +.gradio-container button:not(.primary) { + border-color: #c9cdd3 !important; } -/* ── Tabs ────────────────────────────────────────────── */ -.tabs > .tab-nav { border-bottom: 2px solid var(--cc-border) !important; } -.tabs > .tab-nav button { - font-weight: 700 !important; - font-size: 0.88em !important; - color: var(--cc-muted) !important; - padding: 10px 18px !important; - border-radius: 0 !important; - transition: color 0.15s !important; -} -.tabs > .tab-nav button.selected { - color: var(--cc-accent) !important; - border-bottom: 3px solid var(--cc-accent) !important; - background: transparent !important; -} -.tabs > .tab-nav button:hover { color: var(--cc-accent-deep) !important; } - -/* ── Hero (original) ─────────────────────────────────── */ +/* ── Welcome ── */ .cc-hero { text-align: center; padding: 56px 24px 40px; @@ -1835,8 +2315,6 @@ footer { display: none !important; } margin: 0 auto 48px; line-height: 1.55; } - -/* ── Entry cards (original) ──────────────────────────── */ .cc-entry-card { background: var(--cc-paper); border: 1px solid var(--cc-border); @@ -1878,618 +2356,1383 @@ footer { display: none !important; } max-width: 32ch; } -/* ── Top header bar ──────────────────────────────────── */ -.cc-header { - background: linear-gradient(135deg, #7c2d12 0%, #ff5a3d 60%, #ff7a5a 100%); - padding: 18px 32px; +/* ── Page nav bar ── */ +.cc-page-nav { display: flex; align-items: center; - gap: 16px; - box-shadow: 0 2px 12px rgba(234,88,12,0.22); + gap: 12px; + padding: 16px 0 14px; + border-bottom: 2px solid var(--cc-border); + margin-bottom: 24px; } -.cc-header-logo { - font-size: 1.6em; - font-weight: 900; - color: white; +.cc-page-label { + font-size: 0.68rem; + font-weight: 800; + text-transform: uppercase; + letter-spacing: 0.12em; + color: var(--cc-accent-deep); +} +.cc-page-title { + font-size: 1.5rem; + font-weight: 800; letter-spacing: -0.03em; + color: var(--cc-ink); + margin: 0; } -.cc-header-logo span { opacity: 0.65; font-weight: 400; } -.cc-header-tag { - font-size: 0.72em; - background: rgba(255,255,255,0.18); - color: white; - padding: 3px 10px; - border-radius: 20px; - font-weight: 600; - letter-spacing: 0.06em; - text-transform: uppercase; +.cc-page-meta { + font-size: 0.78rem; + color: var(--cc-muted); + margin-left: auto; + font-family: monospace; } -.cc-header-right { margin-left: auto; font-size: 0.78em; color: rgba(255,255,255,0.6); } -/* ── Inputs ──────────────────────────────────────────── */ -input[type=text]:focus, textarea:focus { - border-color: var(--cc-accent) !important; - box-shadow: 0 0 0 3px rgba(255,90,61,0.12) !important; - outline: none !important; +/* ── Step indicator ── */ +.cc-steps { + display: flex; + gap: 6px; + align-items: center; + flex-wrap: wrap; + margin-bottom: 20px; } +.cc-step-done { color:#065f46;background:#f0fdf4;border:1px solid #86efac;border-radius:999px;padding:4px 12px;font-size:0.76rem;font-weight:700; } +.cc-step-active { color:#4338ca;background:#eef2ff;border:1px solid #818cf8;border-radius:999px;padding:4px 12px;font-size:0.76rem;font-weight:700; } +.cc-step-next { color:#94a3b8;background:transparent;border:1px solid #e2e8f0;border-radius:999px;padding:4px 12px;font-size:0.76rem;font-weight:500; } +.cc-step-sep { color:#d1d5db;font-size:0.7rem; } -/* ── Scrollbars ──────────────────────────────────────── */ -::-webkit-scrollbar { width: 6px; height: 6px; } -::-webkit-scrollbar-track { background: #f5f5f4; } -::-webkit-scrollbar-thumb { background: #d8dade; border-radius: 3px; } -::-webkit-scrollbar-thumb:hover { background: #ff5a3d; } - -/* ── Markdown headings ───────────────────────────────── */ -.gr-markdown h2 { - font-size: 1.22em !important; - font-weight: 800 !important; - color: var(--cc-ink) !important; - border-bottom: 2px solid var(--cc-border) !important; - padding-bottom: 8px !important; - margin-bottom: 12px !important; +/* ── Setup page ── */ +.cc-setup-box { + background: var(--cc-paper); + border: 1px solid var(--cc-border); + border-radius: 12px; + padding: 24px; + margin-bottom: 16px; } -.gr-markdown h3 { - font-size: 1.0em !important; - font-weight: 700 !important; - color: var(--cc-accent-deep) !important; + +/* ── Pipeline page ── */ +.cc-section-header { + background: #eff6ff; + border: 1px solid #93c5fd; + border-left: 4px solid #3b82f6; + border-radius: 0 8px 8px 0; + padding: 10px 16px; + margin: 12px 0; + font-size:0.92em; + color: #1e3a8a; +} + +/* ── Coding canvas ── */ +.cc-coding-transcript { + background: var(--cc-paper); + border: 1px solid var(--cc-border); + border-radius: 10px; + padding: 16px; + max-height: 62vh; + overflow-y: auto; +} +.cc-coding-controls { + background: var(--cc-paper); + border: 1px solid var(--cc-border); + border-radius: 10px; + padding: 16px; +} +.cc-coding-footer { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 12px 0 0; + border-top: 1px solid var(--cc-border); + margin-top: 12px; +} + +/* ── Done page ── */ +.cc-done-card { + background: #f0fdf4; + border: 2px solid #86efac; + border-radius: 16px; + padding: 32px; + text-align: center; + margin: 24px 0; +} +.cc-done-title { + font-size: 2rem; + font-weight: 800; + color: #065f46; + margin: 0 0 8px; +} +.cc-done-sub { + color: #14532d; + font-size: 0.95rem; + max-width: 50ch; + margin: 0 auto; + line-height: 1.6; +} + +/* ── Info callout ── */ +.cc-callout { + background: #eff6ff; + border: 1px solid #93c5fd; + border-radius: 10px; + padding: 16px 20px; + margin-bottom: 16px; + font-size: 0.88em; + color: #1e3a8a; + line-height: 1.7; +} + +/* ── Pipeline progress header (always visible) ── */ +.cc-pipeline-bar { + display: flex; + align-items: center; + gap: 10px; + padding: 10px 20px; + background: var(--cc-paper); + border-bottom: 1.5px solid var(--cc-border); + flex-wrap: wrap; + position: sticky; + top: 0; + z-index: 50; + box-shadow: 0 1px 6px rgba(0,0,0,0.05); +} +.cc-pipeline-step { + display: flex; + flex-direction: column; + align-items: center; + gap: 2px; + padding: 5px 12px; + border-radius: 7px; + min-width: 64px; + border: 1.5px solid var(--cc-border); + background: var(--cc-surface); +} +.cc-pipeline-step.done { background: #f0fdf4; border-color: #86efac; } +.cc-pipeline-step.active { background: #fff5f2; border-color: var(--cc-accent); } +.cc-pipeline-step .dot { font-size: 0.82em; color: var(--cc-muted); } +.cc-pipeline-step.done .dot { color: #15803d; } +.cc-pipeline-step.active .dot { color: var(--cc-accent); } +.cc-pipeline-step .lbl { + font-size: 0.66em; font-weight: 800; text-transform: uppercase; + letter-spacing: 0.06em; color: var(--cc-muted); +} +.cc-pipeline-step.done .lbl { color: #15803d; } +.cc-pipeline-step.active .lbl { color: var(--cc-accent-deep); } + +/* ── Screener view ── */ +.cc-screener-row { + display: grid; + grid-template-columns: 36px 80px 64px 1fr 160px; + gap: 8px; + padding: 7px 12px; + border-bottom: 1px solid var(--cc-border); + align-items: start; + font-size: 0.85em; +} +.cc-screener-header { + background: var(--cc-surface); + border-radius: 8px 8px 0 0; + font-size: 0.7em; + font-weight: 800; + text-transform: uppercase; + letter-spacing: 0.06em; + color: var(--cc-muted); +} + +/* ── Lexicon tier cards ── */ +.cc-tier-card { + border: 1.5px solid var(--cc-border); + border-radius: 10px; + padding: 12px 16px; + margin-bottom: 10px; + background: var(--cc-paper); +} +.cc-tier-kicker { + font-size: 0.68em; + font-weight: 800; + text-transform: uppercase; + letter-spacing: 0.08em; + color: var(--cc-accent-deep); + margin-bottom: 4px; } -""" + _load_css() - - -_BRANDED_HEADER = """ -
    - -
    Research Preview
    -
    - - Metacognitive Talk Detector - - - SSRL · D1-D9 - -
    -
    v5 · Qwen2.5-72B
    -
    """ +CSS = _load_css() + EXTRA_CSS -def build_ui(): - with gr.Blocks( - title="CollabCode — Metacognitive Talk Detector", - css=CUSTOM_CSS, - theme=gr.themes.Soft( - primary_hue="orange", - neutral_hue="stone", - ), - ) as demo: +# =========================================================================== +# Pipeline header + Screener + Lexicon helpers +# =========================================================================== - state = gr.State(_empty_state()) +_PIPE_STAGES = [ + ("upload", "Upload"), + ("screened", "Screen"), + ("sectioned", "Section"), + ("coded", "Code"), + ("done", "Done"), + ("agreed", "Agreement"), +] +_PIPE_ORDER = [s for s, _ in _PIPE_STAGES] - # ── Branded top header ──────────────────────────────────────────────── - gr.HTML(value=_BRANDED_HEADER) - # ── Persistent pipeline status ──────────────────────────────────────── - with gr.Row(elem_classes=["pipeline-header"]): - pipeline_header = gr.HTML(value=_pipeline_status_html(_empty_state())) +def _pipeline_bar_html(state: dict) -> str: + current = state.get("stage", "upload") + session = html_lib.escape(state.get("session_id", "—") or "—") + turns = len(state.get("turns", [])) + sc = state.get("screener_result") + savings = f"{sc['estimated_llm_savings']:.0%}" if sc else "—" + n_wins = len(sc["candidate_windows"]) if sc else "—" + try: + cur_i = _PIPE_ORDER.index(current) + except ValueError: + cur_i = 0 - # ── Main tabs ───────────────────────────────────────────────────────── - with gr.Tabs(): + steps = [] + for i, (stage, label) in enumerate(_PIPE_STAGES): + cls = "done" if i < cur_i else ("active" if i == cur_i else "") + dot = "✓" if i < cur_i else ("▶" if i == cur_i else "○") + steps.append( + f'
    ' + f'{dot}' + f'{label}' + f'
    ' + ) - # ================================================================ - # TAB 1 — SESSION - # ================================================================ - with gr.Tab("Session"): - # ── Hero ───────────────────────────────────────────────── - gr.HTML( - '
    ' - '

    CollabCode

    ' - '

    Human-in-the-loop metacognitive talk detection ' - 'for collaborative learning research

    ' - '
    ' - ) + return ( + f'
    ' + f'
    ' + f'
    {session}
    ' + f'
    ' + f'{turns} turns · {n_wins} windows · ~{savings} LLM saved
    ' + f'
    ' + + "".join(steps) + + f'
    ' + ) - # ── Three entry cards ───────────────────────────────────── - with gr.Row(equal_height=True): - with gr.Column(scale=2): - gr.HTML( - '
    ' - 'Primary workflow' - '

    Code a Transcript

    ' - '

    Upload a Zoom transcript, run the ' - 'metacognitive screener, let AI detect sections and segment ' - 'boundaries, then code each episode against SSRL and D1-D9 dimensions.

    ' - '
    ' - ) - gr.Markdown("**Researcher ID** — enter before loading a transcript") - researcher_id = gr.Textbox( - placeholder="e.g. R1_Lara", - show_label=False, - ) - local_file = gr.File( - label="Upload .txt / .vtt / .srt transcript", - file_types=[".txt", ".vtt", ".srt"], - ) - upload_btn = gr.Button("Load local file", variant="primary", size="lg") - with gr.Column(scale=1): - gr.HTML( - '
    ' - 'From Drive' - '

    Load from Drive

    ' - '

    Connect to Google Drive and pick a ' - 'transcript from your shared research folder.

    ' - '
    ' - ) - refresh_drive_btn = gr.Button("Connect to Drive") - drive_dropdown = gr.Dropdown( - label="Select transcript", - choices=[], interactive=False, - ) - drive_load_btn = gr.Button("Load from Drive") +def _screener_summary_html(rd: dict) -> str: + total = rd.get("total_turns", 0) + flagged = rd.get("flagged_turns", 0) + windows = len(rd.get("candidate_windows", [])) + savings = rd.get("estimated_llm_savings", 0) - with gr.Column(scale=1): - gr.HTML( - '
    ' - 'Continue' - '

    Restore Session

    ' - '

    Pick up a previous coding session ' - 'saved to Drive — all codings and screener results restored.

    ' - '
    ' - ) - load_session_btn = gr.Button("Restore previous session") + def chip(v, lbl, tc, bg): + return ( + f'
    ' + f'
    {html_lib.escape(str(v))}
    ' + f'
    {lbl}
    ' + ) + + return ( + f'
    ' + + chip(total, "Total turns", "#111217", "#f6f6f7") + + chip(flagged, "Flagged", "#15803d", "#f0fdf4") + + chip(windows, "LLM windows", "#b45309", "#fffbeb") + + chip(f"{savings:.0%}", "LLM saved", "#ff5a3d", "#fff5f2") + + f'
    ' + ) + +def _screener_turns_html(rd: dict, speaker_map: dict) -> str: + scores = rd.get("turn_scores", []) + if not scores: + return '

    No turns scored.

    ' + + rows = [ + '
    ' + '
    ' + '
    #
    Speaker
    Score
    Text
    Triggers
    ' + '
    ' + ] + for ts in scores[:250]: + excl = bool(ts.get("excluded_reason")) + flagged = ts.get("flagged", False) + score = ts.get("composite", 0) + sp = ts.get("speaker", "?") + text = html_lib.escape(ts.get("text", "")[:130]) + tid = ts.get("turn_id", "") + hits = ts.get("hits", []) + sigs = ts.get("signals", []) + + if excl: + sbg, stc = "#f6f6f7", "#a8a29e" + elif score >= 0.8: + sbg, stc = "#f0fdf4", "#15803d" + elif score >= 0.4: + sbg, stc = "#fffbeb", "#b45309" + elif score >= 0.2: + sbg, stc = "#fff5f2", "#ff5a3d" + else: + sbg, stc = "#f6f6f7", "#6b6f76" + + chips = "" + for h in hits[:3]: + lbl = html_lib.escape(h.get("category_label", "")[:22]) + t = h.get("tier", 1) + mark = "²" if t == 2 else "³?" if t == 3 else "" + chips += ( + f'{lbl}{mark} ' + ) + for sig in sigs[:2]: + chips += ( + f'{html_lib.escape(sig)} ' + ) + if excl: + chips = 'small talk' + + flag = "▶" if flagged else ("–" if excl else "·") + row_bg = "#fffbeb" if flagged else ("#f6f6f7" if excl else "white") + + rows.append( + f'
    ' + f'
    ' + f'{flag}{html_lib.escape(str(tid))}
    ' + f'
    {html_lib.escape(sp[:12])}
    ' + f'
    ' + f'{score:.2f}
    ' + f'
    {text}
    ' + f'
    {chips}
    ' + f'
    ' + ) + if len(scores) > 250: + rows.append( + f'
    ' + f'{len(scores)-250} more turns not shown
    ' + ) + rows.append('
    ') + return "".join(rows) + + +def _lexicon_tier1_html(data: dict) -> str: + cats = data.get("categories", []) + phase_colors = { + "planning": ("#1d4ed8","#eff6ff"), + "monitoring": ("#15803d","#f0fdf4"), + "evaluating": ("#b45309","#fffbeb"), + "ssrl": ("#7c3aed","#faf5ff"), + } + parts = ['
    ' + 'Tier 1 is research-locked. Add custom terms in Tier 2.
    '] + for cat in cats: + tc, bg = phase_colors.get(cat.get("phase",""), ("#6b6f76","#f6f6f7")) + terms = " ".join( + f'' + f'{html_lib.escape(t)}' + for t in cat.get("terms", []) + ) + parts.append( + f'
    ' + f'
    {html_lib.escape(cat.get("phase",""))}
    ' + f'
    ' + f'{html_lib.escape(cat.get("label",""))}
    ' + f'
    ' + f'w={cat.get("weight",0)} · {html_lib.escape(cat.get("source",""))}
    ' + f'
    {terms}
    ' + ) + return "".join(parts) + + +def _lexicon_tier2_html(data: dict) -> str: + entries = data.get("entries", []) + if not entries: + return ('
    ' + 'No validated terms yet. Use the form below to add them.
    ') + parts = [] + for e in entries: + terms = " ".join( + f'{html_lib.escape(t)}' + for t in e.get("terms", []) + ) + note = html_lib.escape(e.get("note","")) + parts.append( + f'
    ' + f'
    {html_lib.escape(e.get("label",""))}
    ' + f'
    ' + f'by {html_lib.escape(e.get("added_by",""))} · {html_lib.escape(e.get("category_id",""))}
    ' + f'
    {terms}
    ' + + (f'
    {note}
    ' if note else "") + + f'
    ' + ) + return "".join(parts) + + +def _lexicon_tier3_html(data: dict) -> str: + cands = [c for c in data.get("candidates", []) + if not c.get("approved") and not c.get("rejected")] + if not cands: + return ('
    ' + 'No pending candidates.
    ') + parts = [] + for c in cands: + terms = " ".join( + f'{html_lib.escape(t)}' + for t in c.get("terms", []) + ) + ctx = html_lib.escape(c.get("context","")[:180]) + parts.append( + f'
    ' + f'
    Pending review
    ' + f'
    ' + f'{html_lib.escape(c.get("label",""))}
    ' + f'
    {terms}
    ' + + (f'
    “{ctx}”
    ' if ctx else "") + + f'
    ' + ) + return "".join(parts) + + +# Screener handler +def fn_run_screener(state: dict): + turns = state.get("turns", []) + if not turns: + return state, "No transcript loaded.", "", "" + try: + result = screen_transcript(turns) + rd = result_to_dict(result) + state["screener_result"] = rd + state["stage"] = "screened" + speaker_map = state.get("speakers", {}) + return ( + state, + _pipeline_bar_html(state), + _screener_summary_html(rd) + _screener_turns_html(rd, speaker_map), + _screener_summary_html(rd), # summary only, for the status card + ) + except Exception as e: + return state, _pipeline_bar_html(state), f"Screener error: {e}", "" + + +# Lexicon handlers +def fn_load_lexicon(): + try: + d = load_full_lexicon() + return _lexicon_tier1_html(d["tier1"]), _lexicon_tier2_html(d["tier2"]), _lexicon_tier3_html(d["tier3"]), "" + except Exception as e: + return "", "", "", f"Error loading lexicon: {e}" + + +def fn_add_tier2_term(cat_id, label, phase, terms_text, weight, researcher_id, note): + terms = [t.strip() for t in terms_text.replace(",","\n").splitlines() if t.strip()] + if not terms: + return "Enter at least one term.", "", "" + try: + add_tier2_term(terms=terms, category_id=cat_id or "TIER2_custom", + label=label or "Custom", phase=phase or "monitoring", + weight=float(weight), added_by=researcher_id or "researcher", note=note) + d = load_full_lexicon() + return f"Added {len(terms)} term(s) to Tier 2.", _lexicon_tier2_html(d["tier2"]), "" + except Exception as e: + return f"Failed: {e}", "", "" + + +def fn_approve_t3(term, researcher_id): + if not term.strip(): + return "Enter a term.", "" + try: + approve_tier3_candidate(term.strip(), approved_by=researcher_id or "researcher") + d = load_full_lexicon() + return f"'{term}' approved.", _lexicon_tier3_html(d["tier3"]) + except Exception as e: + return f"Failed: {e}", "" + + +def fn_reject_t3(term, researcher_id, note): + if not term.strip(): + return "Enter a term.", "" + try: + reject_tier3_candidate(term.strip(), rejected_by=researcher_id or "researcher", note=note) + d = load_full_lexicon() + return f"'{term}' rejected.", _lexicon_tier3_html(d["tier3"]) + except Exception as e: + return f"Failed: {e}", "" + + +# Local file upload handler (new — original was Drive-only) +def fn_process_local(file, researcher_id: str, state: dict): + rid = (researcher_id or "").strip() + if not file: + yield state, _pipeline_bar_html(state), "No file selected." + return + try: + path = Path(file.name) if hasattr(file, "name") else Path(str(file)) + text = path.read_text(encoding="utf-8", errors="replace") + turns = parse_transcript(text) + except Exception as e: + yield state, _pipeline_bar_html(state), f"Parse failed: {e}" + return + if not turns: + yield state, _pipeline_bar_html(state), "No turns found in transcript." + return + + from app import _assign_speakers, _auto_session_id # inline import avoided — use helpers + stamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S") + sid = f"{rid or 'R'}_{Path(path).stem}_{stamp}" + speakers = {} + for t in turns: + sp = t.get("speaker","?") + if sp not in speakers: + i = len(speakers) % len(SPEAKER_PALETTE) + c,bg,ibg,em = SPEAKER_PALETTE[i] + speakers[sp] = {"color":c,"bg":bg,"initials_bg":ibg,"emoji":em,"index":i} + + new_state = _empty_state() + new_state.update({"session_id": sid, "researcher_id": rid, + "turns": turns, "speakers": speakers, "stage": "upload"}) + (SESSIONS_ROOT / sid).mkdir(parents=True, exist_ok=True) + (SESSIONS_ROOT / sid / "turns.json").write_text( + json.dumps(turns, indent=2, ensure_ascii=False), encoding="utf-8" + ) + yield new_state, _pipeline_bar_html(new_state), f"Loaded {len(turns)} turns from {path.name}." + + +# =========================================================================== +# UI — page-based (no tabs) +# =========================================================================== + +with gr.Blocks(title="CollabCode") as demo: + + state = gr.State(_empty_state()) + + # Persistent pipeline status bar (hidden on welcome) + pipeline_bar_html = gr.HTML( + value=_pipeline_bar_html(_empty_state()), + visible=False, + elem_id="cc-pipeline-bar-root", + ) + + # ───────────────────────────────────────────────────────────────────── + # PAGE 0: Welcome + # ───────────────────────────────────────────────────────────────────── + with gr.Column(visible=True) as pg_welcome: + gr.HTML( + '
    ' + '

    CollabCode

    ' + '

    Human-in-the-loop qualitative coding ' + 'for collaborative learning research

    ' + '
    ' + ) + with gr.Row(equal_height=True): + with gr.Column(scale=2): gr.HTML( - '
    ' - f'Model: {MODEL_ID.split("/")[-1]} · ' - f'Temperature: {TEMPERATURE} · ' - 'Frameworks: Iiskala et al. 2011 (SSRL) · Meier, Spada & Rummel 2007 (D1-D9)' + '
    ' + 'Primary workflow' + '

    Code a Transcript

    ' + '

    Choose a Zoom transcript from Drive, let AI detect ' + 'sections and episode boundaries, then code each segment ' + 'against the D1–D9 collaborative learning dimensions.

    ' '
    ' ) + start_btn = gr.Button("Start Coding →", variant="primary", size="lg") - session_status = gr.HTML() - - upload_btn.click( - fn_process_local, - inputs=[local_file, researcher_id, state], - outputs=[state, session_status, pipeline_header], - ) - refresh_drive_btn.click( - fn_refresh_drive_transcripts, - inputs=[researcher_id, state], - outputs=[drive_dropdown, session_status], - ) - drive_load_btn.click( - fn_process_with_source, - inputs=[drive_dropdown, researcher_id, state], - outputs=[state, session_status, pipeline_header], - ) - load_session_btn.click( - fn_load_previous_session, - inputs=[researcher_id, state], - outputs=[state, session_status], + with gr.Column(scale=1): + gr.HTML( + '
    ' + 'After coding' + '

    Check Agreement

    ' + '

    Upload both coders\' files, ' + 'compute Gwet\'s AC1 and Cohen\'s κ, resolve disagreements.

    ' + '
    ' ) + agreement_nav_btn = gr.Button("Open Agreement →") - # ================================================================ - # TAB 2 — SCREENER - # ================================================================ - with gr.Tab("Screener"): - gr.Markdown( - "## Metacognitive Talk Screener\n" - "Scans every turn with the research-backed trigger lexicon before any LLM call. " - "Green rows → candidate windows sent to LLM. Grey rows → small talk, skipped. " - "Yellow → structural signal (question mark, interruption, rapid exchange)." + with gr.Column(scale=1): + gr.HTML( + '
    ' + 'Advanced' + '

    Review AI Rules

    ' + '

    Approve or reject Agent 2\'s proposed ' + 'coding rules before they enter the validated library.

    ' + '
    ' ) - with gr.Row(): - run_screener_btn = gr.Button("Run Screener", variant="primary", scale=2) - screener_info = gr.HTML(scale=3) + library_nav_btn = gr.Button("Open Library →") - screener_status = gr.HTML() + gr.HTML( + '
    ' + f'Model: {MODEL_ID.split("/")[-1]} · ' + f'Temperature: {TEMPERATURE} · ' + 'Framework: Meier, Spada & Rummel (2007)' + '
    ' + ) - with gr.Tabs(): - with gr.Tab("Turn-by-turn view"): - gr.Markdown( - "*Color key:* 🟢 Flagged (score ≥ 0.40) | ⬛ Low score | 🔘 Small talk excluded" - ) - screener_turns_html = gr.HTML() - with gr.Tab("Candidate windows"): - gr.Markdown( - "These windows will be sent to the LLM for SSRL coding. " - "Each window = a flagged turn ± 3 turns context." - ) - screener_windows_html = gr.HTML() + # ───────────────────────────────────────────────────────────────────── + # PAGE 1: Setup + # ───────────────────────────────────────────────────────────────────── + with gr.Column(visible=False) as pg_setup: + gr.HTML( + '
    ' + 'Step 1 of 4' + '

    Session Setup

    ' + '
    ' + '
    ' + '1 Setup' + '›' + '2 Sections' + '›' + '3 Code' + '›' + '4 Done' + '
    ' + ) - run_screener_btn.click( - fn_run_screener, - inputs=[state], - outputs=[state, screener_status, screener_turns_html, screener_windows_html], - ) + gr.HTML( + '
    ' + '

    ' + 'Choose a transcript from Google Drive, then start coding. ' + 'Session IDs are generated automatically and saved for you.' + '

    ' + '
    ' + ) - # ================================================================ - # TAB 3 — SECTIONS - # ================================================================ - with gr.Tab("Sections"): - gr.Markdown( - "## Structural Sections (Agent 0)\n" - "Agent 0 detects the high-level structure of the session " - "(e.g. warm-up, main task, wrap-up). Review and edit labels before coding." - ) - with gr.Row(): - run_agent0_btn = gr.Button("Run Agent 0 — Detect sections", variant="primary") - sections_status = gr.HTML() - sections_display = gr.HTML() - - gr.Markdown("### Edit section labels") - gr.Markdown( - "One label per line. Prefix `s01: ` is optional. " - "Labels here become the section headers throughout the app." - ) - sections_labels = gr.Textbox( - label="Section labels (one per line)", - lines=6, placeholder="Introduction\nMain Task\nWrap-up" - ) - with gr.Row(): - confirm_sections_btn = gr.Button("Confirm sections", variant="primary") - sections_confirm_status = gr.HTML() + with gr.Row(): + researcher_id_box = gr.Textbox(label="Researcher ID", placeholder="e.g. R1", scale=1) - run_agent0_btn.click( - fn_run_agent0, - inputs=[state], - outputs=[state, sections_status, pipeline_header], - ) - confirm_sections_btn.click( - fn_confirm_sections, - inputs=[sections_labels, state], - outputs=[state, sections_confirm_status, pipeline_header], - ) + with gr.Row(): + drive_refresh_btn = gr.Button("🔄 Refresh Drive transcripts", variant="secondary") + load_prev_btn = gr.Button("↺ Load previous session", variant="secondary") - # ================================================================ - # TAB 4 — PIPELINE - # ================================================================ - with gr.Tab("Pipeline"): - gr.Markdown( - "## Coding Pipeline (Agent 1a + 1b)\n" - "Runs boundary detection and dimension coding on all confirmed sections. " - "Uses screener windows to focus LLM calls on metacognitive candidate turns." - ) - with gr.Row(): - run_pipeline_btn = gr.Button("Run full pipeline", variant="primary", scale=2) - pipeline_info = gr.HTML(scale=3) + drive_file_dropdown = gr.Dropdown( + label="Google Drive transcript", + choices=[], + interactive=False, + ) + drive_status_html = gr.HTML() - pipeline_status_out = gr.HTML() - pipeline_log = gr.HTML(label="Agent log") + gr.HTML( + '
    ' + 'Option A — Google Drive: refresh the list and select a transcript, ' + 'then click Process Transcript.
    ' + 'Option B — Local file: upload a .txt or .vtt transcript below.' + '
    ' + ) - with gr.Accordion("Manual episode-by-episode coding", open=False): - gr.Markdown( - "Use this if you want to code or override one episode at a time " - "rather than running the full automatic pipeline." - ) - with gr.Row(): - prev_sec_btn = gr.Button("◀ Prev section") - next_sec_btn = gr.Button("Next section ▶") - with gr.Row(): - prev_ep_btn = gr.Button("◀ Prev episode") - next_ep_btn = gr.Button("Next episode ▶") - - coding_progress = gr.HTML() - episode_dropdown = gr.Dropdown(label="Episode", choices=[]) - turns_display = gr.HTML(label="Turns in episode") - proposal_md = gr.Markdown() - uncertainty_display = gr.HTML(visible=False) - dim_dropdown = gr.Dropdown(label="Dimension (D1-D9)", choices=DIM_CHOICES) - dim_desc_display = gr.HTML() - sec_dropdown = gr.Dropdown(label="Secondary dimension (optional)", - choices=SEC_DIM_CHOICES, value=SEC_NONE) - coding_note = gr.Textbox(label="Note (optional)", lines=2) - save_btn = gr.Button("Save coding", variant="primary") - save_status_out = gr.HTML() - manual_btn_visible = gr.Column(visible=False) - - run_pipeline_btn.click( - fn_run_pipeline, - inputs=[state], - outputs=[state, pipeline_status_out, pipeline_header], - ) - save_btn.click( - fn_save_coding, - inputs=[dim_dropdown, sec_dropdown, coding_note, state], - outputs=[state, save_status_out, pipeline_header], - ) - dim_dropdown.change( - lambda c: _dim_desc_html(c), - inputs=[dim_dropdown], outputs=[dim_desc_display], - ) + process_btn = gr.Button("Process Drive Transcript →", variant="primary") + process_status = gr.HTML() + process_log = gr.HTML() - def _nav_and_render(direction, is_section, state): - if is_section: - state = fn_nav_section(direction, state) - else: - state = fn_nav_segment(direction, state) - return (state,) + _render_coding(state) - - for btn, dirn, is_sec in [ - (prev_ep_btn, "prev", False), (next_ep_btn, "next", False), - (prev_sec_btn, "prev", True), (next_sec_btn, "next", True), - ]: - btn.click( - lambda d=dirn, s=is_sec: _nav_and_render(d, s, state), - inputs=[state], - outputs=[state, coding_progress, episode_dropdown, turns_display, - proposal_md, uncertainty_display, dim_dropdown, - dim_desc_display, sec_dropdown, coding_note, manual_btn_visible], - ) + gr.HTML('
    ' + '
    Or upload a local file
    ') + local_file_upload = gr.File( + label="Transcript file (.txt, .vtt, .csv)", + file_types=[".txt", ".vtt", ".csv"], + ) + process_local_btn = gr.Button("Process Local File →", variant="secondary") + local_process_status = gr.HTML() + + back_setup_btn = gr.Button("← Back to Home", size="sm") + + # ───────────────────────────────────────────────────────────────────── + # PAGE 2: Screener + # ───────────────────────────────────────────────────────────────────── + with gr.Column(visible=False) as pg_screener: + gr.HTML( + '
    ' + 'Step 2 of 5' + '

    Pre-screen Transcript

    ' + '
    ' + '
    ' + '✓ Setup' + '›' + '2 Screen' + '›' + '3 Sections' + '›' + '4 Code' + '›' + '5 Done' + '
    ' + ) + gr.HTML( + '
    ' + 'The screener scores every turn using the tiered metacognitive lexicon ' + 'before sending anything to the LLM. Only turns inside candidate windows ' + 'are passed to Agent 0 — everything else is skipped, saving API cost.' + '
    ' + ) + run_screener_btn = gr.Button("Run Screener", variant="primary") + screener_summary_html = gr.HTML() + screener_turns_html_c = gr.HTML() + screener_to_sections_btn = gr.Button("Continue to Sections →", variant="primary", visible=False) + back_screener_btn = gr.Button("← Back to Setup", size="sm") + + # ───────────────────────────────────────────────────────────────────── + # PAGE 3: Sections review + # ───────────────────────────────────────────────────────────────────── + with gr.Column(visible=False) as pg_sections: + gr.HTML( + '
    ' + 'Step 2 of 4' + '

    Review Sections

    ' + '
    ' + '
    ' + '✓ Setup' + '›' + '2 Sections' + '›' + '3 Code' + '›' + '4 Done' + '
    ' + ) - # ================================================================ - # TAB 5 — REVIEW - # ================================================================ - with gr.Tab("Review"): - gr.Markdown( - "## Segment Review & Editing\n" - "All coded segments. Green 🔍 badge = screener flagged this segment " - "as metacognitive. Use the SSRL phase dropdown to add a metacognitive tag." - ) + sections_display_html = gr.HTML() - with gr.Row(): - refresh_review_btn = gr.Button("Refresh view", scale=1) - review_info = gr.HTML(scale=4) + gr.Markdown("**Rename sections** — edit the text after the colon, keep the `s01:` prefix:") + sections_labels_box = gr.Textbox( + lines=10, show_label=False, + placeholder="s01: Introduction\ns02: Main Discussion\n…", + ) + confirm_sections_btn = gr.Button("Confirm Sections →", variant="primary") + back_sections_btn = gr.Button("← Back to Setup", size="sm") + + # ───────────────────────────────────────────────────────────────────── + # PAGE 3: Pipeline — boundaries + coding (per section) + # ───────────────────────────────────────────────────────────────────── + with gr.Column(visible=False) as pg_pipeline: + gr.HTML( + '
    ' + 'Step 3 of 4' + '

    Detect Episodes & Code

    ' + '
    ' + '
    ' + '✓ Setup' + '›' + '✓ Sections' + '›' + '3 Code' + '›' + '4 Done' + '
    ' + ) - review_display = gr.HTML() + sections_overview_html = gr.HTML() - gr.Markdown("### Add SSRL metacognitive phase tag to current episode") - gr.Markdown( - "This tags the current episode (shown in Pipeline tab) with a " - "Socially Shared Regulation of Learning phase. " - "These tags are stored separately from D1-D9 codings." - ) - with gr.Row(): - ssrl_dropdown = gr.Dropdown( - label="SSRL metacognitive phase", - choices=SSRL_CHOICES, - value=SSRL_CHOICES[-1], # NONE - ) - save_ssrl_btn = gr.Button("Save SSRL tag", variant="secondary") - ssrl_status = gr.HTML() + # Live agent-activity banner — updated by callbacks to show what is running + agent_activity_html = gr.HTML( + '
    ' + 'No agent running. Click Detect Episode Boundaries to start.
    ' + ) - refresh_review_btn.click( - lambda s: _all_segments_review_html(s), - inputs=[state], outputs=[review_display], - ) - save_ssrl_btn.click( - fn_save_ssrl_tag, - inputs=[episode_dropdown, ssrl_dropdown, state], - outputs=[state, ssrl_status], - ) + # Sub-step A: Parallel boundary detection + with gr.Column(visible=True) as col_run_all_boundaries: + gr.HTML( + '
    ' + 'Agent 1a — Boundary Detector runs in parallel on all sections ' + 'simultaneously. Processing time scales with the longest section, not ' + 'total transcript length. ' + '(Dean & Ghemawat 2004 — parallel map; Schegloff 2007 — episode boundaries; ' + 'Krippendorff 2004 — unitising precedes categorising)' + '
    ' + ) + run_all_btn = gr.Button("⚡ Detect Episode Boundaries (All Sections)", variant="primary") + parallel_status_md = gr.Markdown() + parallel_stats_html = gr.HTML() + + section_header_md = gr.Markdown() + + # Sub-step B: Per-section boundary review + with gr.Column(visible=False) as col_boundary_review: + # Agent 1b will run here ��� show what principles it uses + gr.HTML( + '
    ' + 'Agent 1b — Dimension Coder will run after you confirm these boundaries. ' + 'It uses: D1–D9 framework (Meier, Spada & Rummel 2007) · ' + 'Tier 1 hard rules (R01–R08) · Tier 2 learned rules · ' + 'Uncertainty sampling (Settles 2012) to flag hard cases for your review.' + '
    ' + ) - # ================================================================ - # TAB 6 — AGREEMENT - # ================================================================ - with gr.Tab("Agreement"): - gr.Markdown( - "## Inter-Rater Reliability\n" - "Upload coding files from both researchers. " - "The system calculates Gwet's AC1 (primary) and Cohen's κ (secondary) " - "with 95% bootstrap CIs (B=1000). Gate: AC1 ≥ 0.70." + # Episode count summary (compact table) + boundary_display_html = gr.HTML() + + # Full dialogue view — the key UX improvement + gr.HTML( + '
    ' + 'Read the dialogue — verify each episode boundary
    ' + ) + episode_dialogue_html = gr.HTML() + + # Edit controls + gr.HTML( + '
    ' + 'Adjust if needed: enter the turn ID after which ' + 'each new episode begins. Leave empty for a single undivided episode. ' + 'The AI proposal is pre-filled — edit only where you disagree.' + '
    ' + ) + with gr.Row(): + boundary_ids_box = gr.Textbox( + label="Boundary turn IDs (comma-separated)", + placeholder="e.g. 12, 28, 35", + lines=1, scale=3, ) - with gr.Row(): - r1_file = gr.File(label="R1 codings (.json)", file_types=[".json"]) - r2_file = gr.File(label="R2 codings (.json)", file_types=[".json"]) - - calc_kappa_btn = gr.Button("Calculate agreement", variant="primary") - kappa_status_out = gr.HTML() - kappa_summary_out = gr.HTML() - disagreement_out = gr.HTML() - - with gr.Accordion("Resolve disagreement", open=False): - gr.Markdown( - "Enter the segment ID and the agreed resolution. " - "Resolved disagreements are written to Tier 3 as training candidates." + confirm_boundaries_btn = gr.Button("Confirm & Run Agent 1b →", + variant="primary", scale=1) + code_status = gr.Markdown() + + # Sub-step C: Coding canvas + with gr.Column(visible=False) as col_coding: + coding_progress_comp = gr.HTML() + + with gr.Row(equal_height=False): + # Left: transcript + with gr.Column(scale=3, elem_classes=["cc-coding-transcript"]): + uncertainty_comp = gr.HTML() + turns_html_comp = gr.HTML() + with gr.Row(): + reveal_btn = gr.Button("▶ Reveal AI proposal", variant="secondary", size="sm") + gr.HTML( + '

    ' + 'Code independently first — reveal only if unsure ' + '(Settles 2012)

    ' + ) + proposal_comp = gr.Markdown(visible=False) + + # Right: coding controls + with gr.Column(scale=2, elem_classes=["cc-coding-controls"]): + gr.Markdown("#### Dimension") + dim_radio = gr.Radio(choices=DIM_CHOICES, label="Primary", value=None) + dim_desc_comp = gr.HTML() + + secondary_dim_drop = gr.Dropdown( + choices=SEC_DIM_CHOICES, + value=SEC_NONE, + label="Secondary dimension (optional)", + info="Only when a second dimension is clearly sustained throughout. Strijbos et al. (2006).", + interactive=True, ) - resolve_seg_id = gr.Textbox(label="Segment ID") - resolve_dim = gr.Dropdown(label="Resolved dimension", choices=DIM_CHOICES) - resolve_note = gr.Textbox(label="Resolution note", lines=2) - resolve_btn = gr.Button("✓ Resolve") - discard_btn = gr.Button("✗ Discard (irresolvable)") - resolve_status = gr.HTML() - - calc_kappa_btn.click( - fn_calculate_kappa, - inputs=[r1_file, r2_file, state], - outputs=[state, kappa_status_out, pipeline_header], - ) + comment_box = gr.Textbox( + label="Note (optional)", lines=2, + placeholder="Ambiguity, competing codes…" + ) + with gr.Row(): + prev_btn = gr.Button("← Previous", size="sm") + next_btn = gr.Button("Next →", variant="primary", size="sm") - def _resolve(seg_id, dim_choice, note, state): - report = state.get("kappa_report") - if not report: - return state, _status_card("Run agreement calculation first.", "warning") - try: - d = _session_dir(state) - report_path = d / "kappa_report.json" - did = DIM_ID_FROM_CHOICE.get(dim_choice, "") - resolve_disagreement(report_path, seg_id, did, note) - return state, _status_card(f"Resolved: {seg_id} → {did}.", "success") - except Exception as e: - return state, _status_card(f"Failed: {e}", "error") - - def _discard(seg_id, note, state): - report = state.get("kappa_report") - if not report: - return state, _status_card("Run agreement calculation first.", "warning") - try: - d = _session_dir(state) - report_path = d / "kappa_report.json" - discard_disagreement(report_path, seg_id, note or "irresolvable") - return state, _status_card(f"Discarded: {seg_id}.", "success") - except Exception as e: - return state, _status_card(f"Failed: {e}", "error") - - resolve_btn.click( - _resolve, - inputs=[resolve_seg_id, resolve_dim, resolve_note, state], - outputs=[state, resolve_status], - ) - discard_btn.click( - _discard, - inputs=[resolve_seg_id, resolve_note, state], - outputs=[state, resolve_status], - ) + segment_jump = gr.Dropdown( + label="Jump to segment", choices=[], value=None, interactive=True + ) + next_section_btn = gr.Button( + "→ Finish Section & Continue", variant="secondary", visible=False + ) - # ================================================================ - # TAB 7 — LEXICON - # ================================================================ - with gr.Tab("Lexicon"): - gr.Markdown( - "## Trigger Word Lexicon\n" - "The research-backed vocabulary used to screen turns before LLM coding. " - "Tier 1 is locked (from published research). " - "Tier 2 is your validated additions. " - "Tier 3 holds candidates proposed by the system — review and approve or reject them." - ) - with gr.Row(): - load_lexicon_btn = gr.Button("Load / refresh lexicon", variant="primary") - lexicon_status = gr.HTML() - - with gr.Tabs(): - with gr.Tab("Tier 1 — Research-locked"): - gr.Markdown( - "Source: Halmo et al. 2022, Zimmerman SRL model, " - "Järvelä & Hadwin SSRL, LIWC cognitive categories, " - "Schegloff et al. conversation analysis." - ) - tier1_html = gr.HTML() + with gr.Accordion("Agent Activity Log", open=False): + pipeline_log = gr.HTML(_agent_log_html([])) - with gr.Tab("Tier 2 — Validated terms"): - gr.Markdown( - "Terms you've validated in your specific participant population. " - "These are used at full weight by the screener." - ) - tier2_html = gr.HTML() - - gr.Markdown("### Add new validated terms") - with gr.Row(): - t2_category = gr.Textbox( - label="Category ID", - placeholder="MON_custom_01", - info="Use existing category IDs to extend them, or create new ones." - ) - t2_label = gr.Textbox(label="Label", placeholder="My custom category") - with gr.Row(): - t2_phase = gr.Dropdown( - label="SRL Phase", - choices=["planning", "monitoring", "evaluating", "ssrl"], - value="monitoring", - ) - t2_weight = gr.Slider( - label="Weight (0.3 = weak, 1.0 = strong)", - minimum=0.3, maximum=1.0, step=0.05, value=0.7, - ) - t2_terms = gr.Textbox( - label="Terms (one per line, or comma-separated)", - lines=4, - placeholder="what do you mean\ncan you clarify\nhow did you get that", - ) - t2_note = gr.Textbox(label="Note / source", lines=2, - placeholder="Observed in Session 3 and 4.") - add_t2_btn = gr.Button("Add to Tier 2", variant="primary") - add_t2_status = gr.HTML() - - with gr.Tab("Tier 3 — Candidates"): - gr.Markdown( - "Words that appeared in LLM-coded metacognitive segments but " - "aren't in Tier 1 or 2 yet. Review each one: approve to move to Tier 2, " - "or reject with a note." - ) - tier3_html = gr.HTML() - - gr.Markdown("### Approve or reject a candidate") - with gr.Row(): - t3_term = gr.Textbox(label="Term to approve/reject") - t3_note = gr.Textbox(label="Rejection note (optional)") - with gr.Row(): - approve_t3_btn = gr.Button("Approve", variant="primary") - reject_t3_btn = gr.Button("Reject") - t3_action_status = gr.HTML() - - load_lexicon_btn.click( - fn_load_lexicon_view, - outputs=[tier1_html, tier2_html, tier3_html, lexicon_status], - ) - add_t2_btn.click( - fn_add_tier2, - inputs=[t2_category, t2_label, t2_phase, t2_terms, - t2_weight, researcher_id, t2_note], - outputs=[add_t2_status, tier2_html, t2_terms], - ) - approve_t3_btn.click( - fn_approve_candidate, - inputs=[t3_term, researcher_id], - outputs=[t3_action_status, tier3_html], - ) - reject_t3_btn.click( - fn_reject_candidate, - inputs=[t3_term, researcher_id, t3_note], - outputs=[t3_action_status, tier3_html], - ) + back_pipeline_btn = gr.Button("← Back to Sections", size="sm") + + # ───────────────────────────────────────────────────────────────────── + # PAGE 4: Done + # ───────────────────────────────────────────────────────────────────── + with gr.Column(visible=False) as pg_done: + gr.HTML( + '
    ' + 'Step 4 of 4' + '

    All Sections Coded

    ' + '
    ' + '
    ' + '✓ Setup' + '›' + '✓ Sections' + '›' + '✓ Coded' + '›' + '4 Done' + '
    ' + ) + + gr.HTML( + '
    ' + '
    Coding complete ✓
    ' + '

    ' + 'Download your coding file and share it with your co-researcher. ' + 'Both of you should complete the pipeline independently on the same ' + 'transcript, then bring both files to the Agreement Check.' + '

    ' + '
    ' + ) + + download_btn = gr.Button("Download My Coding File", variant="primary") + download_file = gr.File(visible=False, label="Download") + + with gr.Row(): + go_agreement_btn = gr.Button("→ Check Agreement", variant="secondary") + back_done_btn = gr.Button("← Back to Pipeline") + + # ───────────────────────────────────────────────────────────────────── + # PAGE 5: Agreement + # ───────────────────────────────────────────────────────────────────── + with gr.Column(visible=False) as pg_agreement: + gr.HTML( + '
    ' + 'Inter-Rater Reliability' + '

    Agreement Check

    ' + '
    ' + ) + + gr.HTML( + '
    ' + 'How it works:' + '
      ' + '
    1. You complete the pipeline → download coding_R1.json
    2. ' + '
    3. Your co-researcher runs the same pipeline independently → downloads their file
    4. ' + '
    5. Upload their file here to compute Gwet\'s AC1 and Cohen\'s κ
    6. ' + '
    7. Gate: AC1 ≥ 0.70 (Landis & Koch 1977)
    8. ' + '
    9. Resolve remaining disagreements — they feed Agent 2\'s learning cycle
    10. ' + '
    ' + '
    ' + ) - # ================================================================ - # TAB 8 — LEARNING - # ================================================================ - with gr.Tab("Learning"): - gr.Markdown( - "## Agent 2 — Rule Learning\n" - "After sessions accumulate disagreements, Agent 2 proposes coding rules " - "based on patterns in researcher corrections. Review and approve rules " - "before they become active in Tier 2." + with gr.Row(): + r2_upload = gr.File( + label="Co-researcher coding file (.json)", + file_types=[".json"], scale=2 + ) + kappa_btn = gr.Button("Calculate Agreement", variant="primary", scale=1) + + kappa_html_comp = gr.HTML() + disagreements_md = gr.Markdown() + + with gr.Column(visible=False) as col_disagreements: + gr.HTML( + '
    ' + 'Disagreement Resolution' + '

    For each disagreement: enter the ' + 'segment ID, select the consensus dimension, add a rationale. ' + 'Resolved segments become training data for Agent 2.

    ' + '
    ' + ) + with gr.Row(): + dis_seg_id = gr.Textbox(label="Segment ID", placeholder="e.g. dyad_01_s01_ep03", scale=2) + dis_dim = gr.Dropdown(label="Resolved dimension", choices=DIM_CHOICES, scale=2) + dis_note = gr.Textbox( + label="Rationale — why this dimension?", lines=2, + placeholder="After discussion we agreed… because…" + ) + with gr.Row(): + resolve_btn = gr.Button("Resolve ✓", variant="primary") + discard_btn = gr.Button("Discard segment", variant="secondary") + dis_status = gr.Markdown() + + with gr.Accordion("Sequence Analysis (optional)", open=False): + gr.HTML( + '
    ' + 'Temporal structure of the coded sequence. ' + 'Frequency counts show how much; sequential analysis shows ' + 'what follows what. ' + 'Bakeman & Gottman (1986)' + '
    ' + ) + with gr.Row(): + seq_rater_choice = gr.Dropdown( + label="Analyse coding from", + choices=["R1 (you)", "R2 (co-researcher)"], + value="R1 (you)", scale=2, ) - with gr.Row(): - load_rules_btn = gr.Button("Load pending rules", variant="primary") - learning_status = gr.HTML() + seq_run_btn = gr.Button("Run →", variant="primary", scale=1) + + seq_summary_md = gr.Markdown() + seq_matrix_html = gr.HTML() + seq_sig_html = gr.HTML() + with gr.Column(visible=False) as col_seq_download: + seq_dl_btn = gr.Button("Download transition matrix (CSV)", variant="secondary", size="sm") + seq_dl_file = gr.File(visible=False) + + with gr.Accordion("Agent Activity Log", open=False): + agreement_log = gr.HTML(_agent_log_html([])) + + with gr.Row(): + back_agreement_btn = gr.Button("← Back to Done") + go_library_btn = gr.Button("→ Review AI Rules") + + # ───────────────────────────────────────────────────────────────────── + # PAGE 6: Library + # ───────────────────────────────────────────────────────────────────── + with gr.Column(visible=False) as pg_library: + gr.HTML( + '
    ' + 'Advanced' + '

    AI Rule Library

    ' + '
    ' + ) - pending_rules_html = gr.HTML() + gr.HTML( + '
    ' + 'How the learning loop works: Agent 2 analyses patterns ' + 'across resolved disagreements and proposes rules to improve Agent 1b\'s ' + 'future coding. Rules are inactive until approved here. ' + 'Approved rules enter Tier 2 immediately. ' + '(Amershi et al. 2014; Monarch 2021)' + '

    ' + '⚠ Agent 2 requires ≥ 3 validated sessions and ≥ 90 coded segments ' + 'before proposing rules (Bujang & Baharum 2017).' + '
    ' + ) + + load_rules_btn = gr.Button("Load Pending Rules", variant="primary") + rules_html_comp = gr.HTML() - gr.Markdown("### Approve or reject a rule") + with gr.Group(): + gr.Markdown("#### Approve or Reject a Rule") + gr.Markdown( + "Rejection reasons are logged — Agent 2 learns from them on the next cycle." + ) + rule_selector = gr.Dropdown(label="Select rule", choices=[]) + rule_rid = gr.Textbox(label="Researcher ID", placeholder="e.g. R1") + rule_note = gr.Textbox( + label="Note (required for rejection, optional for approval)", lines=2, + placeholder="This rule is consistent with sessions 3–5 because…" + ) + with gr.Row(): + reject_rule_btn = gr.Button("Reject ✗", variant="secondary") + approve_rule_btn = gr.Button("Approve ✓", variant="primary") + rule_status = gr.Markdown() + + with gr.Row(): + back_library_btn = gr.Button("← Back to Agreement") + home_from_lib = gr.Button("Home") + open_lexicon_btn = gr.Button("Open Lexicon →") + + # ───────────────────────────────────────────────────────────────────── + # PAGE 8: Lexicon manager + # ───────────────────────────────────────────────────────────────────── + with gr.Column(visible=False) as pg_lexicon: + gr.HTML( + '
    ' + '

    Lexicon Manager

    ' + '
    ' + '
    ' + 'Tier 1 is research-locked (Iiskala 2011; Schoor & Bannert 2012). ' + 'Tier 2 accepts researcher-validated additions. ' + 'Tier 3 collects candidates found during screening — review and promote them here.' + '
    ' + ) + + with gr.Tabs(): + with gr.Tab("Tier 1 — Core (read-only)"): + tier1_html = gr.HTML() + with gr.Tab("Tier 2 — Validated"): + tier2_html = gr.HTML() + gr.HTML('
    Add term to Tier 2
    ') + with gr.Row(): + t2_cat_id = gr.Textbox(label="Category ID", placeholder="MON_custom") + t2_label = gr.Textbox(label="Label", placeholder="Metacognitive hedge") + t2_phase = gr.Dropdown(label="Phase", choices=["planning","monitoring","evaluating","ssrl"], value="monitoring") + t2_weight = gr.Number(label="Weight (0–1)", value=0.5, minimum=0, maximum=1) + t2_terms_box = gr.Textbox(label="Terms (one per line or comma-separated)", lines=3) + with gr.Row(): + t2_researcher = gr.Textbox(label="Researcher ID", placeholder="R1") + t2_note = gr.Textbox(label="Note (optional)") + add_t2_btn = gr.Button("Add to Tier 2", variant="primary") + t2_status = gr.HTML() + with gr.Tab("Tier 3 — Candidates"): + tier3_html = gr.HTML() + gr.HTML('
    Approve or reject a candidate
    ') with gr.Row(): - rule_id_box = gr.Textbox(label="Rule ID") - rule_note_box = gr.Textbox(label="Rejection note (optional)") + t3_term = gr.Textbox(label="Term (exact text)") + t3_researcher = gr.Textbox(label="Researcher ID", placeholder="R1") + t3_note = gr.Textbox(label="Rejection note (optional)") with gr.Row(): - approve_rule_btn = gr.Button("Approve rule", variant="primary") - reject_rule_btn = gr.Button("Reject rule") - rule_action_status = gr.HTML() + t3_reject_btn = gr.Button("Reject", variant="secondary") + t3_approve_btn = gr.Button("Approve", variant="primary") + t3_status = gr.HTML() + + lex_error = gr.HTML() + load_lexicon_btn = gr.Button("Refresh Lexicon", variant="secondary", size="sm") + + with gr.Row(): + back_lexicon_btn = gr.Button("← Back to Library") + home_from_lex = gr.Button("Home") + + # ===================================================================== + # ALL PAGES list (order must match _PAGE_NAMES) + # ===================================================================== + ALL_PAGES = [pg_welcome, pg_setup, pg_screener, pg_sections, pg_pipeline, + pg_done, pg_agreement, pg_library, pg_lexicon] + + CODING_OUTPUTS = [ + coding_progress_comp, # 0 + segment_jump, # 1 + turns_html_comp, # 2 + uncertainty_comp, # 3 + proposal_comp, # 4 + dim_radio, # 5 + dim_desc_comp, # 6 + secondary_dim_drop, # 7 + comment_box, # 8 + next_section_btn, # 9 + ] - load_rules_btn.click( - fn_load_pending_rules, - outputs=[pending_rules_html], - ) - approve_rule_btn.click( - fn_approve_rule_action, - inputs=[rule_id_box], - outputs=[rule_action_status, pending_rules_html], - ) - reject_rule_btn.click( - fn_reject_rule_action, - inputs=[rule_id_box, rule_note_box], - outputs=[rule_action_status, pending_rules_html], - ) + # fn_process outputs (13 total — includes process_btn so we can disable it while running) + PROCESS_OUTPUTS = [state, process_status, *ALL_PAGES, + sections_display_html, sections_labels_box, process_log, process_btn] + + # fn_confirm_sections outputs (13 total — generator; includes button + sections_display) + CONFIRM_SECTIONS_OUTPUTS = [ + state, *ALL_PAGES, + sections_display_html, # show busy state on yield-1; clear on yield-2 + confirm_sections_btn, # disable on yield-1; re-enable on yield-2 + col_run_all_boundaries, + col_boundary_review, + col_coding, + ] - # ── Auto-load lexicon on launch ─────────────────────────────────────── - demo.load( - fn_load_lexicon_view, - outputs=[tier1_html, tier2_html, tier3_html, lexicon_status], - ) + # fn_run_all_boundaries outputs (10 total) + RUN_ALL_OUTPUTS = [ + state, + parallel_status_md, + parallel_stats_html, + col_boundary_review, + boundary_display_html, + boundary_ids_box, + section_header_md, + pipeline_log, + agent_activity_html, + episode_dialogue_html, # NEW — full dialogue view per episode + ] - return demo + # fn_confirm_and_code outputs (14 total) + CONFIRM_CODE_OUTPUTS = [state, code_status, col_coding] + CODING_OUTPUTS + [pipeline_log] + + # fn_next_section outputs (15 total — includes boundary + dialogue update for next section) + NEXT_SECTION_OUTPUTS = [ + state, *ALL_PAGES, + sections_overview_html, + section_header_md, + col_boundary_review, + col_coding, + boundary_display_html, # re-populate for next section + boundary_ids_box, # re-populate for next section + episode_dialogue_html, # re-populate for next section + ] + # ===================================================================== + # WIRING + # ===================================================================== + + # Welcome navigation + start_btn.click(lambda: _show("setup"), outputs=ALL_PAGES) + agreement_nav_btn.click(lambda: _show("agreement"), outputs=ALL_PAGES) + library_nav_btn.click(lambda: _show("library"), outputs=ALL_PAGES) + + # Back buttons + back_setup_btn.click(lambda: _show("welcome"), outputs=ALL_PAGES) + back_sections_btn.click(lambda: _show("setup"), outputs=ALL_PAGES) + back_pipeline_btn.click(lambda: _show("sections"), outputs=ALL_PAGES) + back_done_btn.click(lambda: _show("pipeline"), outputs=ALL_PAGES) + back_agreement_btn.click(lambda: _show("done"), outputs=ALL_PAGES) + back_library_btn.click(lambda: _show("agreement"), outputs=ALL_PAGES) + home_from_lib.click(lambda: _show("welcome"), outputs=ALL_PAGES) + + # Forward navigation + go_agreement_btn.click(lambda: _show("agreement"), outputs=ALL_PAGES) + go_library_btn.click(lambda: _show("library"), outputs=ALL_PAGES) + + # Setup: process transcript + detect sections + drive_refresh_btn.click( + fn=fn_refresh_drive_transcripts, + inputs=[researcher_id_box], + outputs=[drive_file_dropdown, drive_status_html], + ) -# ────────────────────────────────────────────────────────────────────────────── -# Entry point -# ────────────────────────────────────────────────────────────────────────────── + load_prev_btn.click( + fn=fn_load_previous_session, + inputs=[researcher_id_box, state], + outputs=[state, process_status], + ) -if __name__ == "__main__": - app = build_ui() - app.launch( - server_name="0.0.0.0", - server_port=7860, - share=False, - show_error=True, + process_btn.click( + fn=fn_process_with_source, + inputs=[drive_file_dropdown, researcher_id_box, state], + outputs=PROCESS_OUTPUTS, + ) + + # Sections: confirm labels + confirm_sections_btn.click( + fn=fn_confirm_sections, + inputs=[sections_labels_box, state], + outputs=CONFIRM_SECTIONS_OUTPUTS, + ) + + # Pipeline: run boundaries in parallel + run_all_btn.click( + fn=fn_run_all_boundaries, + inputs=[state], + outputs=RUN_ALL_OUTPUTS, + ) + + # Pipeline: confirm boundaries + run Agent 1b + confirm_boundaries_btn.click( + fn=fn_confirm_and_code, + inputs=[boundary_ids_box, state], + outputs=CONFIRM_CODE_OUTPUTS, + ) + + # Coding navigation + next_btn.click( + fn=lambda d, sec, c, s: fn_navigate(+1, d, sec, c, s), + inputs=[dim_radio, secondary_dim_drop, comment_box, state], + outputs=[state] + CODING_OUTPUTS, + ) + prev_btn.click( + fn=lambda d, sec, c, s: fn_navigate(-1, d, sec, c, s), + inputs=[dim_radio, secondary_dim_drop, comment_box, state], + outputs=[state] + CODING_OUTPUTS, + ) + segment_jump.change( + fn=fn_jump, + inputs=[segment_jump, state], + outputs=[state] + CODING_OUTPUTS, + ) + reveal_btn.click(fn=fn_reveal, inputs=[state], outputs=[proposal_comp]) + dim_radio.change(fn=fn_dim_desc, inputs=[dim_radio], outputs=[dim_desc_comp]) + + # Finish section / go to done + next_section_btn.click( + fn=fn_next_section, + inputs=[dim_radio, secondary_dim_drop, comment_box, state], + outputs=NEXT_SECTION_OUTPUTS, ) + + # Download + download_btn.click(fn=fn_download, inputs=[state], outputs=[download_file]).then( + fn=lambda: gr.update(visible=True), outputs=[download_file] + ) + + # Agreement + kappa_btn.click( + fn=fn_calculate_kappa, + inputs=[r2_upload, state], + outputs=[state, kappa_html_comp, disagreements_md, col_disagreements, agreement_log], + ) + resolve_btn.click( + fn=fn_resolve, + inputs=[dis_seg_id, dis_dim, dis_note, state], + outputs=[state, dis_status], + ) + discard_btn.click( + fn=fn_discard, + inputs=[dis_seg_id, dis_note, state], + outputs=[state, dis_status], + ) + + # Sequence analysis + seq_run_btn.click( + fn=fn_run_sequence_analysis, + inputs=[seq_rater_choice, state], + outputs=[seq_summary_md, seq_matrix_html, seq_sig_html, col_seq_download], + ) + seq_dl_btn.click( + fn=fn_download_seq_csv, + inputs=[seq_rater_choice, state], + outputs=[seq_dl_file], + ).then(fn=lambda: gr.update(visible=True), outputs=[seq_dl_file]) + + # Library + load_rules_btn.click(fn=fn_load_rules, outputs=[rules_html_comp, rule_selector]) + approve_rule_btn.click( + fn=fn_approve, inputs=[rule_selector, rule_rid, rule_note], outputs=[rule_status] + ) + reject_rule_btn.click( + fn=fn_reject, inputs=[rule_selector, rule_rid, rule_note], outputs=[rule_status] + ) + open_lexicon_btn.click( + fn=fn_load_lexicon, + outputs=[tier1_html, tier2_html, tier3_html, lex_error], + ).then(lambda: _show("lexicon"), outputs=ALL_PAGES) + + # Screener — local file path: Setup → Screener + def _process_local_wrapper(f, rid, st): + """Thin wrapper so fn_process_local results feed screener page.""" + results = list(fn_process_local(f, rid, st)) + if not results: + return st, _pipeline_bar_html(st), "No output.", *_show("setup") + new_st, bar, msg = results[-1] + show = _show("screener") + return new_st, bar, msg, *show + + process_local_btn.click( + fn=_process_local_wrapper, + inputs=[local_file_upload, researcher_id_box, state], + outputs=[state, pipeline_bar_html, local_process_status, *ALL_PAGES], + ) + + # Screener run button + def _run_screener_and_show(st): + new_st, bar, turns_h, summary_h = fn_run_screener(st) + return new_st, bar, turns_h, summary_h, gr.update(visible=True) + + run_screener_btn.click( + fn=_run_screener_and_show, + inputs=[state], + outputs=[state, pipeline_bar_html, screener_turns_html_c, + screener_summary_html, screener_to_sections_btn], + ) + + # Screener → Sections, back buttons + screener_to_sections_btn.click(lambda: _show("sections"), outputs=ALL_PAGES) + back_screener_btn.click(lambda: _show("setup"), outputs=ALL_PAGES) + + # Lexicon navigation + back_lexicon_btn.click(lambda: _show("library"), outputs=ALL_PAGES) + home_from_lex.click(lambda: _show("welcome"), outputs=ALL_PAGES) + + # Lexicon: refresh + load_lexicon_btn.click( + fn=fn_load_lexicon, + outputs=[tier1_html, tier2_html, tier3_html, lex_error], + ) + + # Lexicon: add Tier 2 term + add_t2_btn.click( + fn=fn_add_tier2_term, + inputs=[t2_cat_id, t2_label, t2_phase, t2_terms_box, t2_weight, + t2_researcher, t2_note], + outputs=[t2_status, tier2_html, lex_error], + ) + + # Lexicon: approve / reject Tier 3 candidates + t3_approve_btn.click( + fn=fn_approve_t3, + inputs=[t3_term, t3_researcher], + outputs=[t3_status, tier3_html], + ) + t3_reject_btn.click( + fn=fn_reject_t3, + inputs=[t3_term, t3_researcher, t3_note], + outputs=[t3_status, tier3_html], + ) + + # Pipeline bar: update on process (Drive) — append to existing PROCESS_OUTPUTS + # We also need back_sections_btn to go to screener rather than setup when screener was used + back_sections_btn.click(lambda: _show("screener"), outputs=ALL_PAGES) + + # Pipeline bar visibility: show on any page except welcome + def _toggle_bar_on_nav(page): + return gr.update(visible=(page != "welcome")) + + # Auto-load lexicon Tier 1 when entering the lexicon page + pg_lexicon.select( + fn=fn_load_lexicon, + outputs=[tier1_html, tier2_html, tier3_html, lex_error], + ) if hasattr(pg_lexicon, "select") else None + + +if __name__ == "__main__": + demo.launch(css=CSS, theme=gr.themes.Soft(), ssr_mode=False)