""" 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 import json import html as html_lib import queue as _queue import tempfile import threading import time from datetime import datetime, timezone, timedelta from pathlib import Path import gradio as gr from transcript_parser import parse_transcript from agent0_sectioner import run_sectioning from metacog_screener import ( 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, ) from kappa_calculator import ( 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, ) from llm_client import circuit_state, compute_timeout, reset_circuit from sequential_analysis import ( load_and_analyse, render_transition_matrix_html, render_significant_transitions_html, 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" 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 v4 — startup") print("=" * 60) 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 "" # --------------------------------------------------------------------------- # Design system — dimensions # --------------------------------------------------------------------------- DIMENSIONS = [ ("D1", "Sustaining Mutual Understanding", "Speakers ensure contributions are understood; actively seek comprehension."), ("D2", "Dialogue Management", "Smooth conversational flow with clear turn-taking and minimal overlap."), ("D3", "Information Pooling", "Partners share, elaborate, and elicit domain-specific information."), ("D4", "Reaching Consensus", "Partners critically evaluate options before reaching a joint decision."), ("D5", "Task Division", "Task is systematically divided into subtasks with clear work phases."), ("D6", "Time Management", "Partners monitor time and adjust pace to ensure task completion."), ("D7", "Technical Coordination", "Partners manage shared technical tools effectively."), ("D8", "Reciprocal Interaction", "Partners interact as equals with mutual respect and balanced contribution."), ("D9", "Individual Task Orientation", "Each participant actively engages, contributes knowledge, avoids distraction."), ("NS", "Not Sure", "Cannot confidently assign — competing interpretations remain unresolved."), ("NA", "Not Applicable", "Doesn't fit any dimension: off-topic, administrative, or technical noise."), ] 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} SEC_NONE = "None — single dimension only" SEC_DIM_CHOICES = [SEC_NONE] + DIM_CHOICES SEC_ID_FROM_CHOICE = {SEC_NONE: None, **DIM_ID_FROM_CHOICE} # SSRL phase tagging (Iiskala 2011; Järvelä & Hadwin 2013) SSRL_PHASES = [ ("M-MON", "Individual monitoring — one speaker tracks own/others' understanding"), ("M-REG", "Individual regulation — one speaker adjusts plan, strategy or effort"), ("CO-REG", "Co-regulation — one speaker scaffolds another's metacognitive process"), ("SSRL", "Socially shared — group jointly monitors and regulates together"), ] SSRL_NONE = "None — no metacognitive activity" SSRL_CHOICES = [SSRL_NONE] + [f"{c} — {l}" for c, l in SSRL_PHASES] SSRL_ID_FROM_CHOICE = {SSRL_NONE: None, **{f"{c} — {l}": c for c, l in SSRL_PHASES}} # --------------------------------------------------------------------------- # Speaker palette # --------------------------------------------------------------------------- SPEAKER_PALETTE = [ ("#4338ca", "#eef2ff", "#c7d2fe", "🔵"), ("#b45309", "#fffbeb", "#fde68a", "🟡"), ("#065f46", "#ecfdf5", "#a7f3d0", "🟢"), ("#9a3412", "#fff7ed", "#fed7aa", "🟠"), ("#6b21a8", "#faf5ff", "#e9d5ff", "🟣"), ("#0e7490", "#ecfeff", "#a5f3fc", "🔷"), ] def _assign_speakers(turns: list[dict]) -> dict: seen: dict[str, dict] = {} for t in turns: sp = t.get("speaker", "?") if sp not in seen: i = len(seen) % len(SPEAKER_PALETTE) c, bg, ibg, emoji = SPEAKER_PALETTE[i] seen[sp] = {"color": c, "bg": bg, "initials_bg": ibg, "emoji": emoji, "index": i} return seen def _speaker_avatar(name: str, entry: dict) -> str: initials = "".join(w[0] for w in name.split()[:2]).upper() or "?" return ( f'{initials}' ) _TURN_MERGE_GAP_S = 5 # merge same-speaker turns with gap < this many seconds def _format_turns_html(seg: dict, speaker_map: dict) -> str: """Render episode turns, grouping consecutive same-speaker turns with small gaps.""" turns = seg.get("turns", []) if not turns: return '

No turns in this segment.

' # ── Group consecutive same-speaker turns with gap < _TURN_MERGE_GAP_S ──── groups: list[dict] = [] for t in turns: sp = t.get("speaker", "?") cur = t.get("start_seconds", 0) if (groups and groups[-1]["speaker"] == sp and (cur - groups[-1]["last_seconds"]) < _TURN_MERGE_GAP_S): groups[-1]["texts"].append(t.get("text", "")) groups[-1]["last_seconds"] = cur groups[-1]["last_id"] = t.get("turn_id", "") else: groups.append({ "speaker": sp, "texts": [t.get("text", "")], "start_time": t.get("start_time", ""), "last_seconds": cur, "first_id": t.get("turn_id", ""), "last_id": t.get("turn_id", ""), }) parts = [] for g in groups: sp = g["speaker"] entry = speaker_map.get(sp, {"color": "#64748b", "bg": "#f8fafc", "initials_bg": "#e2e8f0", "emoji": "○"}) avatar = _speaker_avatar(sp, entry) ts = _h(g["start_time"]) merged = " ".join(g["texts"]) fid, lid = g["first_id"], g["last_id"] id_label = f"#{fid}–#{lid}" if fid != lid else f"#{fid}" # Wrap separate sentences for readability sentences = [s.strip() for s in merged.replace("…", "… ").split(" ") if s.strip()] body = " ".join(f'{_h(s)}' for s in sentences) or _h(merged) parts.append( f'
' f'{avatar}' f'
' f'
' f'{_h(sp)}' f'{ts}' f'{id_label}' f'
' f'
{body}
' f'
' ) return f'
{"".join(parts)}
' def _h(s) -> str: return html_lib.escape(str(s)) 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: 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}
' ) 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'
' ) 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: colors = { "success": ("#f0fdf4", "#065f46", "#86efac", "✓"), "error": ("#fef2f2", "#991b1b", "#fca5a5", "✗"), "warning": ("#fffbeb", "#78350f", "#fbbf24", "⚠"), "processing": ("#eff6ff", "#1e40af", "#93c5fd", "⏳"), } bg, tc, bc, icon = colors.get(status, colors["success"]) detail_html = "" if details: detail_html = '
' for k, v in details.items(): detail_html += ( f'
{_h(k)}: ' f'{_h(str(v))}
' ) detail_html += '
' error_html = ( f'
{_h(error_msg)}
' if error_msg else "" ) return ( f'
' f'
' f'{icon} {_h(title)}
' f'{detail_html}{error_html}' f'
' ) # --------------------------------------------------------------------------- # 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: """ 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'{elapsed}s elapsed' f'
' # ── Progress bar ────────────────────────────────────────────────── f'
' f'
' f'{pct}%' f'
' # ── Metrics row ─────────────────────────────────────────────────── f'
' f'⏱ Est. total: ~{est_total}s' f'⌛ ETA: {eta_str}' f'🔢 ~{tok_str} tokens in' f'' f'LLM circuit: {circ_icon} {circ}' f'
' # ── Note ────────────────────────────────────────────────────────── f'
' f'Processing in background — UI stays responsive. ' f'Typical 250-turn transcript: 45–90 s on HF shared inference.' f'
' 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'{_h(name)}' ) return ( f'
' f'{"".join(chips)}
' ) 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)
' ) 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'
' 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 _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 _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. 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. 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'
' ) # ── 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 ] warnings = [] detail_items = [] 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 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.' ) # ── Bar ── bar = ( f'
' f'
' f'
' ) # ── 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'
' ) 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'
    ' ) return agent_card + section_list + warn_html + instr 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. 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.

    ' ) bmap: dict[int, dict] = {} for b in boundaries: bmap[b.get("after_turn_id", -1)] = b conf_colors = { "high": ("#065f46", "#f0fdf4", "#86efac"), "medium": ("#92400e", "#fffbeb", "#fde68a"), "low": ("#991b1b", "#fef2f2", "#fca5a5"), } 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'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 '') + '
    ' ) # 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'
    ' ) if n_turns > 5: parts.append( f'
    ' f'⋯ {n_turns - 5} more turn{"s" if n_turns-5>1 else ""} in this episode
    ' ) # 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'
    ' ) return ( f'
    ' + "".join(parts) + '
    ' ) def _agent_log_html(logs: list[dict]) -> str: if not logs: return ( '

    ' 'No agents have run yet.

    ' ) 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'{agent}' f'{ts} · {runtime}s' f'
    ' f'
    model: {model}
    ' f'{extra_lines}' f'
    ' ) return "".join(parts) 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, } 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 {} 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'
    ' 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'
    ' ) # =========================================================================== # 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": {}, "stage": "upload", "kappa_report": None, "agent_logs": [], "screener_result": None, "ssrl_codings": {}, } def _auto_session_id(researcher_id: str = "", source_name: str = "") -> str: stamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S") base = (Path(source_name).stem or "drive").replace(" ", "_") rid = (researcher_id or "R").strip().replace(" ", "_") return f"{rid}_{base}_{stamp}" def _loading_card(title: str, subtitle: str = "Please wait…", spin: str = "◐") -> str: return ( '
    ' '
    ' 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: """Save state to local disk AND Drive (if Drive is configured).""" skip = {"turns", "kappa_report"} slim = {k: v for k, v in state.items() if k not in skip} # Local save (fast, always) try: d = _session_dir(state) d.mkdir(parents=True, exist_ok=True) (d / "app_state.json").write_text( json.dumps(slim, indent=2, ensure_ascii=False), encoding="utf-8" ) except Exception: pass # Drive save (async-ish — run in background thread so UI isn't blocked) rid = state.get("researcher_id", "") sid = state.get("session_id", "") if rid and sid: def _drive_save(): try: svc = get_drive_service(rid) if svc: write_session_to_drive(svc, rid, sid, slim) except Exception as e: print(f"[Drive] Background save failed: {e}", file=_sys.stderr) import threading as _threading _threading.Thread(target=_drive_save, daemon=True).start() 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 "" multi = f"+{sec}" if sec else "" return f"{coded} ep{ep} [{did}{multi}]{flag}" def _proposal_md(seg: dict) -> str: did = seg.get("dimension_id", "?") rat = seg.get("rationale", "") sec_did = seg.get("secondary_dimension_id") sec_rat = seg.get("secondary_rationale", "") lines = [f"> **AI primary: {did}** \n> {rat}"] if sec_did: lines.append(f"> **AI secondary: {sec_did}** \n> _{sec_rat or 'co-occurring dimension'}_") tags = [] if seg.get("confident"): tags.append("✅ Confident") if seg.get("uncertain"): tags.append(f"⚠️ Uncertain — {seg.get('uncertainty_note', '')}") if sec_did: tags.append(f"🔗 Multi-dimensional: {did} + {sec_did}") return ("\n\n".join(lines) + ("\n\n" + " ".join(tags) if tags else "")).strip() CODING_EMPTY = ( "", # 0 coding_progress_comp gr.update(choices=[], value=None), # 1 segment_jump "", # 2 turns_html_comp "", # 3 uncertainty_comp gr.update(value="", visible=False), # 4 proposal_comp gr.update(choices=DIM_CHOICES, value=None), # 5 dim_radio "", # 6 dim_desc_comp gr.update(choices=SEC_DIM_CHOICES, value=SEC_NONE), # 7 secondary_dim_drop "", # 8 comment_box gr.update(visible=False), # 9 next_section_btn gr.update(choices=SSRL_CHOICES, value=SSRL_NONE), # 10 ssrl_radio gr.update(visible=False), # 11 ssrl_col — hidden when no D1-D9 ) 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 ) saved_ssrl = existing.get("ssrl_phase") ssrl_choice = ( next((c for c in SSRL_CHOICES if c.startswith(saved_ssrl)), SSRL_NONE) if saved_ssrl else SSRL_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] _skip_prefixes = ("NS", "NA", "None", "") show_ssrl = bool(choice) and not any(choice.startswith(p) for p in _skip_prefixes) return ( _coding_progress_html(state), # 0 gr.update(choices=labels, value=labels[min(cidx, len(segs) - 1)]), # 1 _format_turns_html(seg, speaker_map), # 2 _uncertainty_html(seg), # 3 gr.update(value=_proposal_md(seg), visible=False), # 4 gr.update(choices=DIM_CHOICES, value=choice), # 5 _dim_desc_html(choice or ""), # 6 gr.update(choices=SEC_DIM_CHOICES, value=sec_choice), # 7 existing.get("comment", ""), # 8 gr.update(visible=all_done), # 9 gr.update(choices=SSRL_CHOICES, value=ssrl_choice), # 10 gr.update(visible=show_ssrl), # 11 ssrl_col ) # =========================================================================== # PAGE NAVIGATION HELPER # =========================================================================== _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] # =========================================================================== # CALLBACKS # =========================================================================== # ── 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 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, 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 is not configured yet.", "warning", { "Needed secret": "GOOGLE_SERVICE_ACCOUNT_JSON", "Folder ID": "GOOGLE_DRIVE_FOLDER_ID", "Tip": "Copy the DRIVE DEBUG block from the logs if this should already be working.", }, ), ) files = list_transcripts(service) if not files: return ( gr.update(choices=[], value=None, interactive=False), _status_card( "No transcript files found in the configured Drive folder.", "warning", {"Tip": "If this is unexpected, copy the DRIVE DEBUG block from the logs."}, ), ) choices = [ (f"{f['name']} · {f.get('modified_time', '')[:10]}", f"{f['id']}::{f['name']}") for f in files ] return ( gr.update(choices=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_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): """ Generator: load saved session from Drive, re-parse transcript, navigate to screener. Outputs: PARSE_OUTPUTS (state, pipeline_bar_html, process_status, process_btn, screener_summary_html, screener_turns_html_c, screener_to_sections_btn, *ALL_PAGES) """ rid = (researcher_id or "").strip() def _bail(msg: str, kind: str = "warning"): yield (state, _pipeline_bar_html(state), _status_card(msg, kind), _BTN_FREE, "", "", gr.update(visible=False), *_show("setup")) if not rid: yield from _bail("Enter Researcher ID first.") return # ── Step 1: initial feedback ────────────────────────────────────────────── yield (state, _pipeline_bar_html(state), _status_card("Connecting to Drive…", "info"), _BTN_BUSY, "", "", gr.update(visible=False), *_show("setup")) try: service = get_drive_service(rid) except Exception as e: yield from _bail(f"Drive connection failed: {e}", "error") return if not service: yield from _bail("Drive not configured — check GOOGLE_CREDENTIALS.", "warning") return # ── Step 2: load saved state ────────────────────────────────────────────── yield (state, _pipeline_bar_html(state), _status_card("Loading saved session…", "info"), _BTN_BUSY, "", "", gr.update(visible=False), *_show("setup")) try: loaded = load_session_from_drive(service, rid) except Exception as e: diag = format_drive_diagnostic("load_previous_session", researcher_id=rid, error=e) print(diag, file=_sys.stderr) yield from _bail(f"Could not load Drive session: {e}", "error") return if not loaded: yield from _bail("No previous session found for this researcher ID.", "warning") return 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_session") new_state["session_id"] = sid # ── Step 3: re-parse transcript to restore `turns` ──────────────────────── drive_file_id = new_state.get("_drive_file_id") source_name = new_state.get("_source_file_name", "transcript.vtt") if drive_file_id: yield (new_state, _pipeline_bar_html(new_state), _status_card(f"Re-parsing '{source_name}' to restore transcript…", "info"), _BTN_BUSY, "", "", gr.update(visible=False), *_show("setup")) try: text = read_file_from_drive(service, drive_file_id) suffix = Path(source_name).suffix or ".vtt" tmp = Path(tempfile.mktemp(suffix=suffix)) tmp.write_text(text, encoding="utf-8") parsed = parse_transcript(str(tmp)) new_state["turns"] = parsed.get("turns", []) new_state["speakers"] = parsed.get("speakers", new_state.get("speakers", {})) try: tmp.unlink() except Exception: pass except Exception as e: yield from _bail( f"Could not re-parse transcript: {e}. " "Re-upload the file manually to continue.", "warning" ) return else: # No file_id stored (old session or local upload) — warn, turns unavailable gr.Warning("Transcript not available for re-parsing — turns will be missing. " "Re-upload the file to restore the full view.") # ── Step 4: build resume summary card ──────────────────────────────────── n_turns = len(new_state.get("turns", [])) n_sections = len(new_state.get("sections", [])) n_codings = len(new_state.get("codings", {})) stage_map = { "complete": "All sections coded ✓", "coding": "Coding in progress", "sectioned": "Sections detected, boundaries pending", "parsed": "Transcript parsed, screener run", } stage_label = stage_map.get(new_state.get("stage", ""), "Screener complete") sum_html = ( '
    ' '
    ' '✓ Session Resumed
    ' '
    ' f'
    {n_turns}
    ' '
    Turns
    ' f'
    {n_sections}
    ' '
    Sections
    ' f'
    {n_codings}
    ' '
    Episodes coded
    ' '
    ' f'
    Stage: {stage_label}' f' · Session: {sid}
    ' '
    ' 'Click Detect Sections → to continue — sections and boundaries ' 'are loaded from your saved session (no LLM re-run).
    ' '
    ' ) gr.Info(f"Session resumed: {n_sections} sections · {n_codings} episodes coded.") yield ( new_state, _pipeline_bar_html(new_state), _status_card(f"Session loaded · {n_turns} turns · {n_sections} sections · {n_codings} coded", "success", {"Session": sid}), _BTN_FREE, sum_html, "", # screener_turns_html_c (no turn detail on resume) gr.update(visible=True), # screener_to_sections_btn — clicking uses cached sections *_show("screener"), ) def fn_process_with_source(drive_choice: str, researcher_id: str, state: dict): """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.") try: service = get_drive_service(rid) if not service: diag = format_drive_diagnostic("process_drive_file", researcher_id=rid) print(diag, file=_sys.stderr) raise gr.Error("Drive is not configured. Copy the DRIVE DEBUG block from the logs.") file_id, file_name = _parse_drive_choice(drive_choice) session_id = _auto_session_id(rid, file_name) text = read_file_from_drive(service, file_id) suffix = Path(file_name).suffix or ".txt" temp_path = Path(tempfile.mktemp(prefix="drive_transcript_", suffix=suffix)) temp_path.write_text(text, encoding="utf-8") # Store Drive source so we can re-parse on session resume state = dict(state) state["_drive_file_id"] = file_id state["_source_file_name"] = file_name effective_file = type("DriveFile", (), {"name": str(temp_path)})() except gr.Error: raise except Exception as e: file_id, file_name = ("", "") try: file_id, file_name = _parse_drive_choice(drive_choice) except Exception: pass diag = format_drive_diagnostic( "process_drive_file", researcher_id=rid, file_id=file_id, file_name=file_name, error=e, ) print(diag, file=_sys.stderr) raise gr.Error("Drive file could not be read. Copy the DRIVE DEBUG block from the logs.") final_state: dict | None = None try: for out in fn_parse_transcript(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_parse_transcript(file_obj, session_id: str, researcher_id: str, state: dict): """ Phase 1 — Generator: parse transcript, auto-run screener, navigate to screener page. Outputs: state, pipeline_bar_html, process_status, process_btn, screener_summary_html, screener_turns_html_c, screener_to_sections_btn, *ALL_PAGES """ if file_obj is None: raise gr.Error("Choose a transcript 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", "transcript") ) rid = researcher_id.strip() _BTN_BUSY = gr.update(interactive=False, value="⏳ Processing…") _BTN_FREE = gr.update(interactive=True, value="Process Drive Transcript →") def _parse_yield(msg, status="processing", details=None, btn=None, nav="setup"): return ( state, _pipeline_bar_html(state), _status_card(msg, status, details), btn if btn is not None else _BTN_BUSY, "", # screener_summary_html "", # screener_turns_html_c gr.update(visible=False), # screener_to_sections_btn *_show(nav), ) yield _parse_yield("Parsing transcript…") try: turns = parse_transcript(file_obj.name) except Exception as e: raise gr.Error(f"Could not parse transcript: {e}") from e if len(turns) < 5: raise gr.Error(f"Only {len(turns)} turns found — check the transcript format.") speaker_map = _assign_speakers(turns) speakers = list(speaker_map.keys()) duration = _seconds_to_hms(turns[-1]["start_seconds"] - turns[0]["start_seconds"]) new_state = _empty_state() new_state.update({ "session_id": session_id, "researcher_id": rid, "turns": turns, "speakers": speaker_map, "stage": "upload", }) d = SESSIONS_ROOT / session_id d.mkdir(parents=True, exist_ok=True) (d / "parsed_turns.json").write_text( json.dumps(turns, indent=2, ensure_ascii=False), encoding="utf-8" ) yield _parse_yield( f"Running pre-screen on {len(turns)} turns…", details={"Turns": len(turns), "Speakers": ", ".join(speakers), "Duration": duration}, ) # ── Auto-run screener (pre-LLM, fast) ──────────────────────────────────── screener_ok = False try: result = screen_transcript(turns) rd = result_to_dict(result) new_state["screener_result"] = rd new_state["stage"] = "screened" n_wins = len(rd["candidate_windows"]) savings = f"{rd['estimated_llm_savings']:.0%}" sum_html = _screener_summary_html(rd) turns_html = _screener_turns_html(rd, speaker_map) screener_ok = True except Exception as e: sum_html = ( f'
    ' f'Screener could not run automatically.
    ' f'Error: {html_lib.escape(str(e))}
    ' f'Click Re-run Screener below to try again, ' f'or click Detect Sections → to continue without screening.
    ' ) turns_html = "" yield ( new_state, _pipeline_bar_html(new_state), _status_card( f"Parsed {len(turns)} turns · {len(speakers)} speaker(s).", "success", {"Session": session_id, "Turns": len(turns), "Speakers": ", ".join(speakers)}, ), _BTN_FREE, sum_html, # screener_summary_html turns_html, # screener_turns_html_c gr.update(visible=True), # screener_to_sections_btn — always show *_show("screener"), ) def fn_run_agent0(state: dict): """ Phase 2 — Generator: run Agent 0 on parsed turns, navigate to sections. Triggered by 'Continue to Sections' button on screener page. Outputs: state, pipeline_bar_html, sections_display_html, sections_labels_box, *ALL_PAGES """ reset_circuit() # fresh start — don't carry over failures from a previous run turns = state.get("turns", []) if not turns: raise gr.Error("No transcript loaded — process a file first.") # ── Sections cache: if Agent 0 already ran, skip LLM and go to sections ─ existing_sections = state.get("sections", []) if existing_sections: n_t = len(turns) speakers = list(state.get("speakers", {}).keys()) sec_html = _sections_html(existing_sections, n_t, 0, len(speakers), all_turns=turns) labels_txt = "\n".join(f"{s['section_id']}: {s['label']}" for s in existing_sections) gr.Info(f"Using cached sections ({len(existing_sections)} detected). Re-run via Back if you need fresh detection.") yield ( state, _pipeline_bar_html(state), sec_html, labels_txt, *_show("sections"), ) return session_id = state.get("session_id", "") 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 est_out_tok = 900 est_timeout = max(45, int((est_in_tok + est_out_tok) / 35 + 20)) def _hb(elapsed: int, spin_i: int): return ( state, _pipeline_bar_html(state), _llm_progress_html( f"Agent 0 — Structural Segmenter: analysing {n_t} turns…", elapsed, est_timeout, est_in_tok, circuit_state(), spin_i, ), "", # sections_labels_box *_show("screener"), ) yield _hb(0, 0) result_q: _queue.Queue = _queue.Queue() def _run_a0(): try: res = run_sectioning(turns=turns, session_id=session_id) result_q.put(("ok", res)) except Exception as exc: result_q.put(("err", exc)) thread = threading.Thread(target=_run_a0, daemon=True) thread.start() t_llm = time.perf_counter() spin_i = 1 while thread.is_alive(): time.sleep(2) elapsed = int(time.perf_counter() - t_llm) yield _hb(elapsed, spin_i) spin_i += 1 outcome, payload = result_q.get() if outcome == "err": raise gr.Error(f"Section detection failed: {payload}") from payload 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 agent0_rt = round(time.perf_counter() - t_llm, 1) new_state = dict(state) new_state.update({ "sections": sections, "section_stages": {s["section_id"]: "pending" for s in sections}, "stage": "sectioned", "_agent0_overview": result.get("session_overview", ""), }) log_entry = _make_log_entry( "Agent 0 — Structural Segmenter", agent0_rt, sections_proposed=len(sections), warnings=len(result.get("warnings", [])), system_prompt_preview=build_system_prompt(load_dimension_labels())[:120], ) new_state = _push_log(new_state, log_entry) d = SESSIONS_ROOT / session_id d.mkdir(parents=True, exist_ok=True) (d / "sections_proposed.json").write_text( json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8" ) overview = result.get("session_overview", "") speakers = list(state.get("speakers", {}).keys()) sec_html = _sections_html(sections, n_t, agent0_rt, len(speakers), all_turns=turns) 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: {n_t} turns · {len(sections)} sections detected in {agent0_rt}s.") yield ( new_state, _pipeline_bar_html(new_state), sec_html, labels_txt, *_show("sections"), ) # ── Legacy wrapper kept for Drive flow ──────────────────────────────────────── def fn_process(file_obj, session_id: str, researcher_id: str, state: dict): """Alias → fn_parse_transcript (Drive flow calls this via fn_process_with_source).""" yield from fn_parse_transcript(file_obj, session_id, researcher_id, state) # ── Local file upload (new, no Drive needed) ────────────────────────────────── def fn_process_local(file, researcher_id: str, state: dict): """ Generator: load a local .txt/.vtt/.csv transcript, run screener, navigate to screener. Outputs match PARSE_OUTPUTS. """ rid = (researcher_id or "").strip() if not file: raise gr.Error("Select a local transcript file first.") if not rid: raise gr.Error("Enter your Researcher ID first.") path = Path(file.name) if hasattr(file, "name") else Path(str(file)) sid = _auto_session_id(rid, path.stem) file_mock = type("F", (), {"name": str(path)})() yield from fn_parse_transcript(file_mock, sid, rid, state) # ── Original fn_process body (kept below for Drive fn_process_with_source) ─── # ── 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: 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(): labels.append(rest.strip()) continue labels.append(line) 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.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 / "sections_confirmed.json").write_text( json.dumps(confirmed, indent=2, ensure_ascii=False), encoding="utf-8" ) _persist(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 ) # ── Agent 1a — parallel boundary detection ─────────────────────────────────── def fn_run_all_boundaries(state: dict): reset_circuit() # fresh start for this pipeline step sections = state.get("sections", []) if not sections: raise gr.Error("Confirm sections first.") if not state.get("turns"): raise gr.Error("No parsed turns — parse the transcript first.") # ── Cache check: if all sections already have boundaries, skip LLM ─────── existing = state.get("section_a1a_results", {}) if existing and all(s["section_id"] in existing for s in sections): collected = {sid: r for sid, r in existing.items()} # Jump straight to showing first section review 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) yield ( state, "✓ Episode boundaries already detected — showing cached results.", "", gr.update(visible=False), gr.update(visible=True, value=_episode_table_html(turns, bounds)), gr.update(visible=True, value=ids_txt), _section_header_md(sec), _agent_log_html(state.get("agent_logs", [])), "", gr.update(value=_episode_dialogue_html(turns, bounds)), ) return 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'
    ' ) # 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 ) pstats = PipelineStats(agent_name="Agent 1a — Boundary Detector", n_sections=n) try: 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 ) 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" 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, ) state = _push_log(state, log) _persist(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)") # 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"]) 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 ) # ── 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.") 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] = [] 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) if not segments: raise gr.Error("No segments produced — check your boundary turn IDs.") # ── Min-episode guard: merge segments with < 2 turns into the next one ─── _MIN_TURNS = 2 merged: list[dict] = [] pending_turns: list = [] for seg in segments: seg_turns = seg.get("turns", []) combined = pending_turns + seg_turns pending_turns = [] if len(combined) < _MIN_TURNS: pending_turns = combined # carry forward, merge into next else: if merged: seg["turns"] = combined else: seg["turns"] = combined merged.append(seg) # Any remaining tiny tail — append to last segment if pending_turns and merged: merged[-1]["turns"] = merged[-1].get("turns", []) + pending_turns elif pending_turns: merged = [{"turns": pending_turns, "segment_id": "s_merged", "label": "Merged", "section_id": sec["section_id"]}] segments = merged if merged else segments if not segments: raise gr.Error("No segments produced after merging short episodes.") state["section_boundaries"][sec["section_id"]] = boundaries state["section_segments"][sec["section_id"]] = segments # ── Agent 1b cache: if proposals already exist for this section, skip LLM ─ cached_coded = state.get("section_segments_coded", {}).get(sec["section_id"]) if cached_coded: state["section_stages"][sec["section_id"]] = "coding" state["coding_idx"] = 0 n_uncertain = sum(1 for s in cached_coded if s.get("uncertain")) msg = f"✓ {len(cached_coded)} episodes (cached — no LLM re-run)." if n_uncertain: msg += f" **{n_uncertain} flagged ⚠**" gr.Info(f"Using cached Agent 1b proposals ({len(cached_coded)} episodes).") yield state, msg, gr.update(visible=True), *_render_coding(state), _agent_log_html(state.get("agent_logs", [])) return yield ( state, _loading_card("Loading coding stage…", f"Agent 1b is preparing {len(segments)} episode(s) for coding."), gr.update(visible=False), *CODING_EMPTY, "", ) agent1a_result = state.get("section_a1a_results", {}).get(sec["section_id"]) t0 = time.perf_counter() try: 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, ssrl_choice: 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(), "ssrl_phase": SSRL_ID_FROM_CHOICE.get(ssrl_choice or SSRL_NONE), } 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 description HTML + SSRL visibility update.""" desc = _dim_desc_html(choice or "") # Show SSRL only when a substantive D1-D9 code is selected (not NS / NA / None) _skip_prefixes = ("NS", "NA", "None", "") show_ssrl = bool(choice) and not any(choice.startswith(p) for p in _skip_prefixes) return desc, gr.update(visible=show_ssrl) def fn_skip_episode(state: dict): """Mark current episode as non-codeable and advance to next.""" idx = state.get("current_index", 0) segs = state.get("segments", []) if 0 <= idx < len(segs): sid = segs[idx].get("segment_id") state.setdefault("codings", {})[sid] = { "dimension_id": "SKIP", "secondary_dim": None, "ssrl_phase": None, "comment": "Not codeable — skipped", } return fn_navigate(+1, "SKIP", SEC_NONE, "", SSRL_NONE, state) # ── Next section / finish ───────────────────────────────────────────────────── def fn_next_section(dim_choice: str, sec_choice: str, comment: str, ssrl_choice: 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(), "ssrl_phase": SSRL_ID_FROM_CHOICE.get(ssrl_choice or SSRL_NONE), } 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"), "ssrl_phase": codings.get(s["segment_id"], {}).get("ssrl_phase"), "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" ) 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: 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 ''}*" ) 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: 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: 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_discard(seg_id: str, note: str, state: dict): if not seg_id.strip(): raise gr.Error("Enter the segment ID.") try: discard_disagreement( report_path=_session_dir(state) / "kappa_report.json", segment_id=seg_id.strip(), discard_note=note.strip(), ) except Exception as e: raise gr.Error(f"Could not discard: {e}") from e gr.Info(f"Discarded {seg_id.strip()}") return state, f"Discarded `{seg_id.strip()}`" # ── 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; } :root { --cc-bg: #ececee; --cc-surface: #f6f6f7; --cc-paper: #ffffff; --cc-ink: #111217; --cc-muted: #6b6f76; --cc-border: #d8dade; --cc-accent: #ff5a3d; --cc-accent-deep: #ea4425; } :focus-visible { outline: 2px solid var(--cc-accent) !important; outline-offset: 2px; } :focus { outline: none; } /* Primary button */ .gradio-container button.primary { background: var(--cc-accent) !important; border-color: var(--cc-accent) !important; color: #fff !important; font-weight: 700 !important; } .gradio-container button.primary:hover { background: var(--cc-accent-deep) !important; border-color: var(--cc-accent-deep) !important; } .gradio-container button.secondary, .gradio-container button:not(.primary) { border-color: #c9cdd3 !important; } /* ── Welcome ── */ .cc-hero { text-align: center; padding: 56px 24px 40px; } .cc-hero-title { font-size: clamp(3.5rem, 10vw, 7rem); font-weight: 900; letter-spacing: -0.06em; color: var(--cc-ink); line-height: 0.88; margin: 0 0 16px; } .cc-hero-sub { font-size: 1rem; color: var(--cc-muted); max-width: 44ch; margin: 0 auto 48px; line-height: 1.55; } .cc-entry-card { background: var(--cc-paper); border: 1px solid var(--cc-border); border-radius: 16px; padding: 24px; min-height: 190px; position: relative; overflow: hidden; } .cc-entry-card::after { content: ""; position: absolute; right: -24px; bottom: -24px; width: 96px; height: 96px; border-radius: 999px; background: rgba(255,90,61,0.1); } .cc-entry-kicker { font-size: 0.7rem; font-weight: 800; text-transform: uppercase; letter-spacing: 0.1em; color: var(--cc-accent-deep); margin-bottom: 10px; display: block; } .cc-entry-title { font-size: 1.28rem; font-weight: 800; letter-spacing: -0.025em; color: var(--cc-ink); margin: 0 0 8px; line-height: 1.1; } .cc-entry-desc { font-size: 0.87rem; color: #434852; line-height: 1.55; max-width: 32ch; } /* ── Page nav bar ── */ .cc-page-nav { display: flex; align-items: center; gap: 12px; padding: 16px 0 14px; border-bottom: 2px solid var(--cc-border); margin-bottom: 24px; } .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-page-meta { font-size: 0.78rem; color: var(--cc-muted); margin-left: auto; font-family: monospace; } /* ── 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; } /* ── Setup page ── */ .cc-setup-box { background: var(--cc-paper); border: 1px solid var(--cc-border); border-radius: 12px; padding: 24px; margin-bottom: 16px; } /* ── 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; } """ CSS = _load_css() + EXTRA_CSS # =========================================================================== # Pipeline header + Screener + Lexicon helpers # =========================================================================== _PIPE_STAGES = [ ("upload", "Upload"), ("screened", "Screen"), ("sectioned", "Section"), ("coded", "Code"), ("done", "Done"), ("agreed", "Agreement"), ] _PIPE_ORDER = [s for s, _ in _PIPE_STAGES] 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 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'
    ' ) return ( f'
    ' f'
    ' f'
    {session}
    ' f'
    ' f'{turns} turns · {n_wins} windows · ~{savings} LLM saved
    ' f'
    ' + "".join(steps) + f'
    ' ) 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) 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 — returns (state, bar, summary_html, turns_html, rerun_btn_update) def fn_run_screener(state: dict): turns = state.get("turns", []) if not turns: err = ('
    No transcript loaded — go back to Upload.
    ') return state, _pipeline_bar_html(state), err, "", gr.update(visible=True) try: result = screen_transcript(turns) rd = result_to_dict(result) new_state = dict(state) new_state["screener_result"] = rd new_state["stage"] = "screened" speaker_map = new_state.get("speakers", {}) return ( new_state, _pipeline_bar_html(new_state), _screener_summary_html(rd), _screener_turns_html(rd, speaker_map), gr.update(visible=False), # hide re-run btn — success ) except Exception as e: err = ( f'
    Screener error: ' f'{html_lib.escape(str(e))}
    ' ) return state, _pipeline_bar_html(state), err, "", gr.update(visible=True) # 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}", "" # =========================================================================== # 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 # Hidden buttons kept so wiring stays intact # ───────────────────────────────────────────────────────────────────── with gr.Column(visible=True) as pg_welcome: # Hidden nav buttons (agreement / library) — wiring requires them to exist agreement_nav_btn = gr.Button(visible=False) library_nav_btn = gr.Button(visible=False) gr.HTML( '
    ' '

    CollabCode

    ' '

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

    ' '
    ' ) # ── Primary entry card ──────────────────────────────────────────── with gr.Row(equal_height=True): with gr.Column(scale=2): gr.HTML( '
    ' 'Primary workflow' '

    Code a Transcript

    ' '

    Upload a Zoom transcript or load from Drive. ' 'AI pre-screens turns for metacognitive signals, detects discussion sections, ' 'finds episode boundaries, and proposes D1–D9 codes — ' 'you review and confirm every decision.

    ' '
    ' ) start_btn = gr.Button("Start Coding →", variant="primary", size="lg") # ── About / system logic ────────────────────────────────────────── gr.HTML( '
    ' '
    How CollabCode works
    ' '
    ' ) with gr.Row(equal_height=True): gr.HTML( '
    ' 'Step 1 — Pre-screen' '

    Metacognitive Screener

    ' '

    Before any LLM call, every turn is scored against ' 'a three-tier lexicon (Iiskala 2011; Schoor & Bannert 2012). ' 'Turns with no metacognitive signal are filtered out — typically cutting ' 'LLM cost by 40–70 %. Only candidate windows reach Agent 0.

    ' '
    ' ) gr.HTML( '
    ' 'Step 2 — Structure' '

    Agent 0 — Sectioner

    ' '

    Agent 0 reads the full transcript and proposes ' 'thematic sections (e.g. "Problem framing", "Solution negotiation"). ' 'You rename or merge them before the next stage. ' 'Sections give Agent 1a its scope and anchor all downstream analysis.

    ' '
    ' ) gr.HTML( '
    ' 'Step 3 — Episodes' '

    Agent 1a — Boundary Detector

    ' '

    Within each section, Agent 1a runs in parallel ' 'to find episode boundaries — moments where the collaborative activity ' 'shifts. Boundary proposals are shown to you for review and adjustment ' 'before coding begins.

    ' '
    ' ) gr.HTML( '
    ' 'Step 4 — Code' '

    Agent 1b + Human

    ' '

    Agent 1b proposes D1–D9 codes ' '(Meier, Spada & Rummel 2007) and SSRL phases (M-MON, M-REG, CO-REG, SSRL) ' 'for each episode. You code independently first, then reveal the AI proposal ' 'to resolve ambiguity. All decisions are yours.

    ' '
    ' ) with gr.Row(equal_height=True): gr.HTML( '
    ' 'Step 5 — Agreement' '

    Inter-rater Reliability

    ' '

    Upload a second coder\'s file to compute ' 'Gwet\'s AC1 (primary) and Cohen\'s κ (reference) per dimension. ' 'Disagreements are listed segment by segment so you can resolve ' 'or flag them for discussion.

    ' '
    ' ) gr.HTML( '
    ' 'Step 6 — Learn' '

    Agent 2 — Rule Learner

    ' '

    After each validated session, Agent 2 induces ' 'tentative coding rules from agreed codings. Rules are held in Tier 3 ' 'until a researcher promotes them to the validated lexicon — ' 'keeping the human firmly in the loop.

    ' '
    ' ) gr.HTML( '
    ' 'Design principle' '

    Human-in-the-loop

    ' '

    Every AI action is a proposal, not a decision. ' 'The researcher confirms sections, adjusts boundaries, codes independently, ' 'and approves lexicon updates. AI reduces mechanical effort; ' 'expert judgment drives all coding outcomes.

    ' '
    ' ) gr.HTML( '
    ' f'Model: {MODEL_ID.split("/")[-1]} · ' f'Temperature: {TEMPERATURE} · ' 'Framework: Meier, Spada & Rummel (2007) · Iiskala (2011)' '
    ' ) # ───────────────────────────────────────────────────────────────────── # PAGE 1: Setup # ───────────────────────────────────────────────────────────────────── with gr.Column(visible=False) as pg_setup: gr.HTML( '
    ' 'Step 1 of 5 — Upload' '

    Load a Transcript

    ' '
    ' '
    ' '1 Upload' '›' '2 Screen' '›' '3 Sections' '›' '4 Code' '›' '5 Done' '
    ' ) # ── Researcher ID ───────────────────────────────────────────────── gr.HTML( '
    Your Researcher ID
    ' '
    ' 'A short label used to identify your coding file (e.g. R1, lara, jsmith).
    ' ) researcher_id_box = gr.Textbox( label="", placeholder="e.g. R1", max_lines=1, ) # ── Option A: Google Drive ──────────────────────────────────────── gr.HTML( '
    ' '
    Option A — Google Drive
    ' '
    ' 'Refresh the list, pick a transcript, then click Load.
    ' ) with gr.Row(): drive_refresh_btn = gr.Button("Refresh Drive list", variant="secondary", scale=2) load_prev_btn = gr.Button("Resume session", variant="secondary", scale=1) drive_file_dropdown = gr.Dropdown( label="Select transcript", choices=[], interactive=False, ) drive_status_html = gr.HTML() process_btn = gr.Button("Load from Drive →", variant="primary") process_status = gr.HTML() process_log = 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' '

    Metacognitive Screener

    ' '
    ' '
    ' '✓ Upload' '›' '2 Screen' '›' '3 Sections' '›' '4 Code' '›' '5 Done' '
    ' ) # Summary chips — auto-populated when the page loads screener_summary_html = gr.HTML( value='
    ' 'Running screener…
    ' ) # Primary CTA — shown once screener finishes screener_to_sections_btn = gr.Button( "Detect Sections →", variant="primary", size="lg", visible=False ) # Collapsible turn detail with gr.Accordion("Turn-by-turn detail", open=False): gr.HTML( '
    ' 'Turns are colour-coded by composite score. ' 'Orange rows are candidate windows passed to Agent 0; ' 'grey rows are filtered out.
    ' ) screener_turns_html_c = gr.HTML() # Re-run (only needed if auto-run failed) run_screener_btn = gr.Button( "Re-run Screener", variant="secondary", size="sm", visible=False ) back_screener_btn = gr.Button("← Back to Upload", 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' '
    ' ) sections_display_html = gr.HTML() 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' '
    ' ) sections_overview_html = 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.
    ' ) # 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.' '
    ' ) # 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, ) 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() # ── Jump to segment — at the TOP before the transcript ────────── segment_jump = gr.Dropdown( label="Jump to segment", choices=[], value=None, interactive=True, info="Quickly navigate to any episode by ID." ) 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("#### D1–D9 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, ) # ── SSRL section — hidden until a D1-D9 code is chosen ── with gr.Column(visible=False) as ssrl_col: gr.HTML( '
    ' '
    SSRL Phase
    ' '
    Iiskala (2011) · ' 'Järvelä & Hadwin (2013) — only shown when a D1-D9 code is selected
    ' ) ssrl_radio = gr.Radio( choices=SSRL_CHOICES, label="Metacognitive phase", value=SSRL_NONE, info="Tag the dominant SSRL phase if metacognition is present.", ) comment_box = gr.Textbox( label="Note (optional)", lines=2, placeholder="Ambiguity, competing codes…" ) with gr.Row(): prev_btn = gr.Button("← Prev", size="sm") next_btn = gr.Button("Next →", variant="primary", size="sm") skip_btn = gr.Button("⊘ Skip", size="sm", variant="secondary") gr.HTML( '

    ' 'Skip marks the episode as not codeable (small talk, off-topic) and moves on.

    ' ) next_section_btn = gr.Button( "→ Finish Section & Continue", variant="secondary", visible=False ) with gr.Accordion("Agent Activity Log", open=False): pipeline_log = gr.HTML(_agent_log_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. ' '
    ' '
    ' ) 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, ) 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

    ' '
    ' ) 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() 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(): 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(): 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 ssrl_radio, # 10 — SSRL phase tag ssrl_col, # 11 — SSRL section visibility (show only for D1-D9) ] # fn_parse_transcript / fn_process_with_source outputs # state, pipeline_bar_html, process_status, process_btn, # screener_summary_html, screener_turns_html_c, screener_to_sections_btn, *ALL_PAGES PARSE_OUTPUTS = [ state, pipeline_bar_html, process_status, process_btn, screener_summary_html, screener_turns_html_c, screener_to_sections_btn, *ALL_PAGES, ] # fn_run_agent0 outputs # state, pipeline_bar_html, sections_display_html, sections_labels_box, *ALL_PAGES AGENT0_OUTPUTS = [ state, pipeline_bar_html, sections_display_html, sections_labels_box, *ALL_PAGES, ] # Legacy alias (used by load_prev_btn and other legacy code paths) PROCESS_OUTPUTS = PARSE_OUTPUTS # 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, ] # 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 ] # 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( fn=lambda st: _show("screener") if st.get("screener_result") else _show("setup"), inputs=[state], 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) back_screener_btn.click(lambda: _show("setup"), 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: Drive — Phase 1 (parse + screen) drive_refresh_btn.click( fn=fn_refresh_drive_transcripts, inputs=[researcher_id_box], outputs=[drive_file_dropdown, drive_status_html], ) load_prev_btn.click( fn=fn_load_previous_session, inputs=[researcher_id_box, state], outputs=PARSE_OUTPUTS, ) process_btn.click( fn=fn_process_with_source, inputs=[drive_file_dropdown, researcher_id_box, state], outputs=PARSE_OUTPUTS, ).then(fn=lambda: gr.update(visible=True), outputs=[pipeline_bar_html]) # Screener: manual re-run (only shown when auto-run failed) run_screener_btn.click( fn=fn_run_screener, inputs=[state], outputs=[state, pipeline_bar_html, screener_summary_html, screener_turns_html_c, run_screener_btn], ) # Screener → Sections: Phase 2 (run Agent 0) screener_to_sections_btn.click( fn=fn_run_agent0, inputs=[state], outputs=AGENT0_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 (now includes ssrl_radio) next_btn.click( fn=lambda d, sec, c, ssrl, s: fn_navigate(+1, d, sec, c, ssrl, s), inputs=[dim_radio, secondary_dim_drop, comment_box, ssrl_radio, state], outputs=[state] + CODING_OUTPUTS, ) prev_btn.click( fn=lambda d, sec, c, ssrl, s: fn_navigate(-1, d, sec, c, ssrl, s), inputs=[dim_radio, secondary_dim_drop, comment_box, ssrl_radio, 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 controls description AND shows/hides SSRL section dim_radio.change( fn=fn_dim_desc, inputs=[dim_radio], outputs=[dim_desc_comp, ssrl_col], ) # Skip episode — mark as not codeable and advance skip_btn.click( fn=fn_skip_episode, inputs=[state], outputs=[state] + CODING_OUTPUTS, ) # Finish section / go to done (now includes ssrl_radio) next_section_btn.click( fn=fn_next_section, inputs=[dim_radio, secondary_dim_drop, comment_box, ssrl_radio, 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) # Lexicon navigation + actions back_lexicon_btn.click(lambda: _show("library"), outputs=ALL_PAGES) home_from_lex.click(lambda: _show("welcome"), outputs=ALL_PAGES) load_lexicon_btn.click( fn=fn_load_lexicon, outputs=[tier1_html, tier2_html, tier3_html, lex_error], ) 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], ) 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], ) if __name__ == "__main__": demo.launch(css=CSS, theme=gr.themes.Soft(), ssr_mode=False)