diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -1,37 +1,25 @@ """ -app.py (v2) ------------ -CollabCode — Researcher Interface (redesigned). - -Four-agent, human-in-the-loop pipeline for qualitative coding of -collaborative learning transcripts. All stages in one Gradio application. - -Pipeline --------- - 1. Parse Upload transcript → confirm structure [human confirms] - 2. Agent 0 Topical section detection → researcher edits [human edits] - 3. Agent 1a Episode boundary detection → researcher adjusts [human adjusts] - 4. Agent 1b Dimension coding per section → researcher codes [human codes] - 5. Agreement Upload R2 coding → kappa gate → disagreements [human resolves] - 6. Rules Agent 2 proposals → approve / reject [human decides] - -References ----------- -Settles, B. (2012). Active learning. Morgan & Claypool. -Amershi et al. (2014). Power to the people. IEEE Intelligent Systems, 29(4). -Monarch, R. (2021). Human-in-the-loop machine learning. Manning. -Krippendorff, K. (2004). Content analysis (ch. 7). Sage. -Cohen, J. (1960). Educational and Psychological Measurement, 20(1), 37-46. -Landis & Koch (1977). Biometrics, 33(1), 159-174. -Meier, Spada & Rummel (2007). IJCSCL, 2(1), 63-86. -Rummel & Spada (2005). Journal of the Learning Sciences, 14(2). +app.py (v3) — CollabCode Researcher Interface +============================================== +Human-in-the-loop pipeline for qualitative coding of collaborative learning +transcripts. Four agents, six human checkpoints, full transparency. + +References (complete list in RESEARCH_INFO below) +-------------------------------------------------- +Settles (2012); Amershi et al. (2014); Monarch (2021); +Krippendorff (2004); Cohen (1960); Landis & Koch (1977); +Meier, Spada & Rummel (2007); Rummel & Spada (2005); +Hearst (1997); Purver et al. (2006); Schegloff (2007). """ +from __future__ import annotations + import json import html as html_lib import tempfile +import time +from datetime import datetime, timezone, timedelta from pathlib import Path -from datetime import timedelta import gradio as gr @@ -49,143 +37,33 @@ from agent2_learner import list_pending_rules, approve_rule, reject_rule SESSIONS_ROOT = Path("sessions") _STYLES_DIR = Path(__file__).parent / "static" / "styles" +MODEL_ID = "Qwen/Qwen2.5-72B-Instruct" +TEMPERATURE = 0.1 + # --------------------------------------------------------------------------- -# CSS loading — compile SCSS design system if libsass is available, -# otherwise fall back to the pre-compiled main.css committed alongside. +# CSS loading (compile SCSS with libsass if available, else pre-compiled CSS) # --------------------------------------------------------------------------- def _load_css() -> str: - """ - Try to compile SCSS with libsass; fall back to the committed main.css. - The pre-compiled file means the app runs even without libsass installed - (e.g. on Hugging Face Spaces where pip install may be restricted). - """ - # 1. Try live compile scss_entry = _STYLES_DIR / "main.scss" if scss_entry.exists(): try: import sass # type: ignore - css = sass.compile( - filename=str(scss_entry), - output_style="expanded", - include_paths=[str(_STYLES_DIR)], - ) - # Cache the compiled output for the next cold start + css = sass.compile(filename=str(scss_entry), output_style="expanded", + include_paths=[str(_STYLES_DIR)]) (_STYLES_DIR / "main.css").write_text(css, encoding="utf-8") return css except Exception as e: - print(f"[CollabCode] libsass compile error (falling back to main.css): {e}") - - # 2. Fall back to pre-compiled CSS + print(f"[CollabCode] SCSS compile error: {e}") compiled = _STYLES_DIR / "main.css" if compiled.exists(): return compiled.read_text(encoding="utf-8") - - # 3. Last resort — inline minimal CSS so the app is at least usable - return _INLINE_CSS_FALLBACK - - -# Inline fallback — only used if SCSS and main.css are both missing. -_INLINE_CSS_FALLBACK = """ -/* ── Layout ─────────────────────────────────────────────────────────── */ -.gradio-container { max-width: 1160px !important; margin: 0 auto !important; } -footer { display: none !important; } - -/* ── Pipeline stepper ────────────────────────────────────────────────── */ -.pipeline-bar { - display: flex; align-items: center; gap: 0; - background: #f8fafc; border: 1px solid #e2e8f0; - border-radius: 10px; padding: 12px 20px; margin-bottom: 8px; -} -.step-done { color: #16a34a; font-weight: 600; font-size: 0.9em; } -.step-active { color: #2563eb; font-weight: 700; font-size: 0.9em; } -.step-pending { color: #94a3b8; font-size: 0.9em; } -.step-sep { color: #cbd5e1; margin: 0 10px; } - -/* ── Section cards ───────────────────────────────────────────────────── */ -.section-cards { display: flex; gap: 8px; flex-wrap: wrap; margin: 10px 0 6px 0; } -.sec-card { - flex: 1; min-width: 140px; - border-radius: 8px; padding: 10px 14px; - border: 1px solid #e2e8f0; -} -.sec-done { background: #f0fdf4; border-color: #86efac !important; } -.sec-active { background: #eff6ff; border-color: #93c5fd !important; border-width: 2px !important; } -.sec-pending { background: #f8fafc; border-color: #e2e8f0 !important; } - -/* ── Status banners ──────────────────────────────────────────────────── */ -.banner { - border-radius: 8px; padding: 12px 16px; margin: 8px 0; - font-size: 0.93em; line-height: 1.5; -} -.banner-warn { background: #fffbeb; border: 1px solid #fbbf24; color: #92400e; } -.banner-error { background: #fef2f2; border: 1px solid #fca5a5; color: #991b1b; } -.banner-success { background: #f0fdf4; border: 1px solid #86efac; color: #14532d; } -.banner-info { background: #eff6ff; border: 1px solid #93c5fd; color: #1e3a8a; } - -/* ── Cards ───────────────────────────────────────────────────────────── */ -.card { - background: white; border: 1px solid #e2e8f0; - border-radius: 10px; padding: 16px 20px; margin: 8px 0; -} -.card-header { - font-size: 0.8em; font-weight: 700; letter-spacing: 0.08em; - color: #64748b; text-transform: uppercase; margin-bottom: 8px; -} - -/* ── Episode table ───────────────────────────────────────────────────── */ -.ep-table { border-collapse: collapse; width: 100%; font-size: 0.88em; } -.ep-table th { - background: #f1f5f9; padding: 7px 10px; - text-align: left; font-weight: 600; color: #475569; -} -.ep-table td { padding: 6px 10px; border-top: 1px solid #f1f5f9; } -.ep-table .boundary-row td { - background: #fefce8; color: #78350f; - font-size: 0.83em; border-top: 1px dashed #fde68a; -} - -/* ── Kappa visualization ─────────────────────────────────────────────── */ -.kappa-score { font-size: 2.8em; font-weight: 800; letter-spacing: -0.02em; } -.kappa-bar { - height: 8px; background: #e2e8f0; - border-radius: 4px; margin: 8px 0; overflow: hidden; -} -.kappa-bar-fill { height: 100%; border-radius: 4px; transition: width 0.4s; } -.dim-bar { - height: 6px; background: #e2e8f0; - border-radius: 3px; display: inline-block; width: 100px; vertical-align: middle; -} -.dim-bar-fill { height: 100%; border-radius: 3px; } - -/* ── Rule cards ──────────────────────────────────────────────────────── */ -.rule-card { - border: 1px solid #e2e8f0; border-radius: 10px; - padding: 16px 20px; margin: 10px 0; background: white; -} -.rule-type-badge { - display: inline-block; font-size: 0.75em; font-weight: 700; - letter-spacing: 0.06em; text-transform: uppercase; - border-radius: 4px; padding: 2px 8px; margin-bottom: 8px; -} -.badge-boundary { background: #dbeafe; color: #1d4ed8; } -.badge-disambiguation { background: #fce7f3; color: #9d174d; } -.badge-marker { background: #dcfce7; color: #15803d; } - -/* ── Coding UI ───────────────────────────────────────────────────────── */ -.progress-mini { - height: 6px; background: #e2e8f0; - border-radius: 3px; margin: 6px 0 10px 0; overflow: hidden; -} -.progress-mini-fill { height: 100%; background: #3b82f6; border-radius: 3px; } -""" - -CSS = _load_css() + return "" # --------------------------------------------------------------------------- -# Dimension registry +# Design system — dimensions # --------------------------------------------------------------------------- DIMENSIONS = [ @@ -212,34 +90,307 @@ DIMENSIONS = [ ("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} + + +# --------------------------------------------------------------------------- +# Speaker palette — 6 perceptually distinct colours (deuteranopia-safe pair +# tested via Coblis simulator). Each entry: text colour, light bg, initials bg. +# --------------------------------------------------------------------------- + +SPEAKER_PALETTE = [ + # (text_color, bg_color, initials_bg, emoji) + ("#4338ca", "#eef2ff", "#c7d2fe", "🔵"), # indigo + ("#b45309", "#fffbeb", "#fde68a", "🟡"), # amber + ("#065f46", "#ecfdf5", "#a7f3d0", "🟢"), # emerald + ("#9a3412", "#fff7ed", "#fed7aa", "🟠"), # orange + ("#6b21a8", "#faf5ff", "#e9d5ff", "🟣"), # purple + ("#0e7490", "#ecfeff", "#a5f3fc", "🔷"), # cyan +] + + +def _assign_speakers(turns: list[dict]) -> dict: + """Map speaker name → palette entry 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}' + ) -DIM_CHOICES = [f"{did} — {label}" for did, label, _ in DIMENSIONS] -DIM_ID_FROM_CHOICE = {f"{did} — {label}": did for did, label, _ in DIMENSIONS} -DIM_DESC_FROM_ID = {did: desc for did, _, desc in DIMENSIONS} -DIM_BADGE_COLOR = { - "D1": "#dbeafe", "D2": "#e0f2fe", "D3": "#dcfce7", "D4": "#fef9c3", - "D5": "#fce7f3", "D6": "#ede9fe", "D7": "#ffedd5", "D8": "#f0fdf4", - "D9": "#fef2f2", "NS": "#f1f5f9", "NA": "#f8fafc", + +def _format_turns_html(seg: dict, speaker_map: dict) -> str: + """Render transcript turns as rich HTML with speaker avatars and colours.""" + turns = seg.get("turns", []) + if not turns: + return '

No turns in this segment.

' + parts = [] + for t in turns: + sp = t.get("speaker", "?") + entry = speaker_map.get(sp, {"color": "#64748b", "bg": "#f8fafc", + "initials_bg": "#e2e8f0", "emoji": "○"}) + avatar = _speaker_avatar(sp, entry) + ts = _h(t.get("start_time", "")) + text = _h(t.get("text", "")) + turn_id = t.get("turn_id", "") + parts.append( + f'
' + f'{avatar}' + f'
' + f'
' + f'' + f'{_h(sp)}' + f'' + f'{ts}' + f'' + f'#{turn_id}' + f'
' + f'
{text}
' + f'
' + ) + return f'
{"".join(parts)}
' + + +# --------------------------------------------------------------------------- +# Research information panels — citations and rationale per step +# --------------------------------------------------------------------------- + +RESEARCH_INFO: dict[str, str] = { + "parse": """ +
+

Step 1 — Parse Transcript

+

Parsing converts raw Zoom output into structured turns — +the minimal unit of analysis. Consistent unitisation is prerequisite +to reliable coding.

+

Krippendorff (2004) ch.7: +"Units of analysis must be defined before codes can be reliably assigned." +Content Analysis, Sage.

+

MacWhinney (2000): CHILDES/CLAN +annotation protocols separate utterance units from tier labelling.

+
+

✓ Review speaker count and duration before proceeding. +Errors here propagate through the entire pipeline.

+
""", + + "sections": """ +
+

Step 2 — Topical Sections

+

Agent 0 detects activity phases — macro-level structure +before episode coding. This mirrors how expert analysts orient to data.

+

Hearst (1997): TextTiling — +lexical cohesion as a proxy for topic shift. +Computational Linguistics 23(1).

+

Purver et al. (2006): +Unsupervised topic modelling for multi-party spoken discourse. +COLING-ACL.

+

Sweller (1988): Analysts hold +15–50 turns in working memory comfortably. +Cognitive Science 12(2).

+
+

✓ Edit section labels to match +your theoretical framing. Turn boundaries stay as proposed.

+
""", + + "boundaries": """ +
+

Step 3a — Episode Boundaries

+

Agent 1a finds where one behavioral episode ends and another begins — +before assigning any codes. Separating unitising from coding +is a core principle of reliable annotation.

+

Schegloff (2007): Adjacency pairs, +sequence completion, transition relevance points. +Sequence Organization in Interaction, Cambridge.

+

Krippendorff (2004): +"Unitising must precede categorising."

+

Pustejovsky & Stubbs (2012): +Natural Language Annotation for Machine Learning, ch.4. O'Reilly.

+
+

✓ Review the episode table. +Edit turn IDs to adjust boundary positions before coding.

+
""", + + "coding": """ +
+

Step 3b — Dimension Coding

+

The D1–D9 framework measures collaborative process quality across +nine dimensions. Code each episode based on observable turn content only.

+

Meier, Spada & Rummel (2007): +A rating scheme for assessing the quality of computer-supported +collaboration processes. IJCSCL 2(1), 63–86.

+

Rummel & Spada (2005): +Learning to collaborate. Journal of the Learning Sciences 14(2).

+

Settles (2012): +⚠ markers = uncertainty sampling — review these first. +Active Learning, Morgan & Claypool.

+
+

✓ Code independently first. +Reveal the AI proposal only if you are genuinely unsure.

+
""", + + "agreement": """ +
+

Inter-Rater Agreement

+

Cohen's κ measures agreement beyond chance between two coders +on the same segments. Gate: κ ≥ 0.70.

+

Cohen (1960): +A coefficient of agreement for nominal scales. +Educational & Psychological Measurement 20(1), 37–46.

+

Landis & Koch (1977): +κ < 0.40 poor · 0.40–0.60 moderate · 0.60–0.80 substantial · > 0.80 almost perfect. +Biometrics 33(1).

+

Bujang & Baharum (2017): +≥90 segments needed for 80% power with 9 dimensions. +Epidemiology, Biostatistics and Public Health.

+
+

Both researchers must code the +same segments. Share the session ID and transcript with your +co-researcher.

+
""", + + "rules": """ +
+

AI Learning Review

+

Agent 2 analyses resolved disagreements and proposes rules to improve +Agent 1b's future coding. Rules are inactive until a researcher +approves them here — the human is always the final authority.

+

Amershi et al. (2014): +Power to the People — Human-in-the-Loop ML. +IEEE Intelligent Systems 29(4), 40–47.

+

Monarch (2021): +Human-in-the-Loop Machine Learning, ch.9. +Manning — human oversight of learned updates.

+

Settles (2012): +Active learning update loop — human labels improve the model. +Morgan & Claypool.

+
+

Approve rules that are consistent +with your theoretical framework. Reject with a reason — Agent 2 learns +from rejections too.

+
""", } -# =========================================================================== -# HTML GENERATION HELPERS -# =========================================================================== +# --------------------------------------------------------------------------- +# Agent activity log +# --------------------------------------------------------------------------- -def _h(text: str) -> str: - """HTML-escape a string.""" - return html_lib.escape(str(text)) +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 _agent_log_html(logs: list[dict]) -> str: + if not logs: + return ( + '

' + 'No agents have run yet.

' + ) + parts = [] + for entry in reversed(logs[-6:]): + agent = _h(entry.get("agent", "?")) + model = _h(entry.get("model", "?").split("/")[-1]) + runtime = entry.get("runtime_s", "?") + temp = entry.get("temperature", "?") + ts = _h(entry.get("timestamp", "")) + + # Extra stats + 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))}' + f'
' + for k, v in extras.items() + ) + + # Prompt previews + sys_prev = _h((entry.get("system_prompt_preview") or "")[:120]) + user_prev = _h((entry.get("user_prompt_preview") or "")[:120]) + prompts = "" + if sys_prev: + prompts += ( + f'
' + f'
System prompt
' + f'
{sys_prev}…
' + f'
' + ) + if user_prev: + prompts += ( + f'
' + f'
User prompt
' + f'
{user_prev}…
' + f'
' + ) + + parts.append( + f'
' + f'
' + f'' + f'{agent}' + f'{ts}' + f'
' + f'
' + f'model: {model}' + f'T={temp}' + f'{runtime_s}s' + f'
' + f'{extra_lines}' + f'{prompts}' + f'
' + ) + return "".join(parts) + + +# --------------------------------------------------------------------------- +# HTML helpers +# --------------------------------------------------------------------------- + +def _h(s) -> str: + return html_lib.escape(str(s)) def _pipeline_html(stage: str) -> str: - """Render the pipeline progress stepper using design-system classes.""" stages = [ - ("upload", "1 · Parse"), - ("parsed", "2 · Sections"), - ("sectioned", "3 · Review"), - ("coding", "4 · Code"), - ("complete", "5 · Done"), + ("upload", "1 Parse"), + ("parsed", "2 Sections"), + ("sectioned", "3 Review"), + ("coding", "4 Code"), + ("complete", "5 Done"), ] order = [s[0] for s in stages] cur = order.index(stage) if stage in order else 0 @@ -247,127 +398,134 @@ def _pipeline_html(stage: str) -> str: parts = [] for i, (_, label) in enumerate(stages): if i < cur: - mod, prefix = "cc-stepper__step--done", "✓ " + bg, col, fw = "#ecfdf5", "#065f46", "600" + prefix = "✓ " elif i == cur: - mod, prefix = "cc-stepper__step--active", "▶ " + bg, col, fw = "#eef2ff", "#4338ca", "700" + prefix = "▶ " else: - mod, prefix = "cc-stepper__step--pending", "" - parts.append(f'{prefix}{_h(label)}') - - steps_html = ''.join(parts) + bg, col, fw = "transparent", "#94a3b8", "400" + prefix = "" + parts.append( + f'' + f'{prefix}{label}' + ) + sep = '›' return ( - f'' + f'
' + f'PIPELINE' + f'{sep.join(parts)}' + f'
' ) def _section_cards_html(sections: list[dict], stages: dict, current_idx: int) -> str: - """Render section status cards using design-system classes.""" if not sections: return "" - cards = [] for i, s in enumerate(sections): stage = stages.get(s["section_id"], "pending") if stage == "done": - mod, icon = "cc-section--done", "✓" + bc, fc, icon = "#86efac", "#065f46", "✓" elif i == current_idx: - mod, icon = "cc-section--active", "◑" + bc, fc, icon = "#93c5fd", "#1d4ed8", "◑" else: - mod, icon = "cc-section--pending", "○" - + bc, fc, icon = "#e2e8f0", "#94a3b8", "○" n = s["end_turn_id"] - s["start_turn_id"] + 1 - aria = f"Section {i+1}: {s['label']}, {stage}" cards.append( - f'
' - f'
{icon} {_h(s["label"])}
' - f'
' + f'
' + f'
' + f'{icon} {_h(s["label"])}
' + f'
' f'{_h(s["start_time"])}–{_h(s["end_time"])} · {n} turns
' f'
' ) - - return f'
{"".join(cards)}
' + return f'
{"".join(cards)}
' def _episode_table_html(turns: list[dict], boundaries: list[dict]) -> str: - """Render proposed episodes and boundaries as a design-system table.""" if not turns: - return '

No turns loaded.

' - + return '

No turns.

' turn_ids = sorted(t["turn_id"] for t in turns) - bmap = {b["after_turn_id"]: b for b in boundaries} - - cut_starts = [turn_ids[0]] + 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"]): - after = b["after_turn_id"] - if after in turn_ids: - idx = turn_ids.index(after) - if idx < len(turn_ids) - 1: - cut_starts.append(turn_ids[idx + 1]) + 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" + "" + "Episode" + "Turns" + "Count" "" ) - for i, start in enumerate(cut_starts): - end = turn_ids[turn_ids.index(cut_starts[i + 1]) - 1] if i + 1 < len(cut_starts) else turn_ids[-1] - n = end - start + 1 + 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'turns {start}–{end}' - f'{n}' + f'' + f'ep{i+1:02d}' + f'{start}–{end}' + f'{end-start+1}' f'' ) - if i < len(cut_starts) - 1: - after_turn = cut_starts[i + 1] - 1 - b = bmap.get(after_turn, {}) - sig = _h(b.get("boundary_signal", "boundary")) - conf = b.get("confidence", "?") - rat = _h(b.get("rationale", "")) - conf_cls = {"high": "confidence-high", "medium": "confidence-medium", "low": "confidence-low"}.get(conf, "") + if i < len(cuts) - 1: + after = cuts[i + 1] - 1 + b = bmap.get(after, {}) + sig, conf, rat = ( + _h(b.get("boundary_signal", "boundary")), + b.get("confidence", "?"), + _h(b.get("rationale", "")) + ) + cc = {"high": "#065f46", "medium": "#b45309", "low": "#be123c"}.get(conf, "#64748b") rows += ( - f'' - f'' - f'─── after turn {after_turn} · {sig} · ' - f'{_h(conf)} — {rat}' + f'' + f'' + f'─── after turn {after} · {sig} · ' + f'{conf} confidence — {rat}' f'' ) - n_eps = len(cut_starts) - n_bounds = len(boundaries) + n_ep = len(cuts) + n_b = len(boundaries) return ( - f'
' - f'{n_bounds} boundary{"ies" if n_bounds != 1 else ""} → {n_eps} episode{"s" if n_eps != 1 else ""}' + f'
' + f'{n_b} boundary{"ies" if n_b!=1 else ""} → {n_ep} episode{"s" if n_ep!=1 else ""}' f'
' f'
' - f'{rows}
' - f'
' + f'{rows}
' ) def _uncertainty_html(seg: dict) -> str: - """Render an uncertainty warning banner using design-system classes.""" if not seg.get("uncertain"): return "" note = _h(seg.get("uncertainty_note") or "") return ( - f'' + f'
' + f'' + f'
AI flagged uncertain' + f' — {note}
' + f'
' ) def _dim_desc_html(choice: str) -> str: - """Render a dimension description box using design-system classes.""" if not choice: return "" did = DIM_ID_FROM_CHOICE.get(choice, "") @@ -375,97 +533,93 @@ def _dim_desc_html(choice: str) -> str: if not desc: return "" return ( - f'
' - f'{_h(desc)}' - f'
' + f'
{_h(desc)}
' + ) + + +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: - """Render a visual kappa report card.""" kappa = report.get("overall_kappa", 0.0) interp = report.get("kappa_interpretation", "") gate = report.get("gate_passed", False) n_segs = report.get("n_segments_total", 0) n_dis = len(report.get("segments_in_disagreement", [])) - - color = "#16a34a" if gate else "#dc2626" + col = "#065f46" if gate else "#be123c" icon = "✓" if gate else "✗" pct = int(min(max(kappa, 0) * 100, 100)) - # Threshold marker at 70 % - threshold_left = 70 - - # Per-dimension rows dim_rows = "" for dim, k in sorted((report.get("kappa_per_dimension") or {}).items()): if k is None: continue - k_pct = int(min(max(k, 0) * 100, 100)) - k_mod = "cc-kappa__dim-value--pass" if k >= 0.70 else "cc-kappa__dim-value--warn" if k >= 0.50 else "cc-kappa__dim-value--fail" - k_bar_color = "#047857" if k >= 0.70 else "#b45309" if k >= 0.50 else "#be123c" + kp = int(min(max(k, 0) * 100, 100)) + kc = "#065f46" if k >= 0.70 else "#b45309" if k >= 0.50 else "#be123c" dim_rows += ( - f'
' - f'{_h(dim)}' - f'
' - f'
' - f'
' - f'' - f'{k:.3f}' - f'
' + f'{_h(dim)}' + f'
' + f'
' + f'' + f'{k:.3f}
' ) - if not dim_rows: - dim_rows = '
No per-dimension data.
' - - score_mod = "cc-kappa__score--pass" if gate else "cc-kappa__score--fail" - interp_mod = "cc-kappa__interp--pass" if gate else "cc-kappa__interp--fail" - return ( - f'
' - f'
' - f'{kappa:.3f}' - f'
' - f'
{icon} {_h(interp)}
' - f'
threshold κ=0.70 — Landis & Koch (1977)
' - f'
' - f'
' - f'
' - f'
' - f'0.70' + f'
' + f'
' + f'{kappa:.3f}' + f'
{icon} {_h(interp)}
' + f'
threshold κ=0.70 — Landis & Koch (1977)
' f'
' - f'
' - f'{n_segs} segments · {n_dis} disagreement{"s" if n_dis != 1 else ""}' + f'
' + f'
' + f'
' + f'
0.70
' f'
' - f'
Per-Dimension Agreement
' - f'
' - f'
' - f'Dim' - f'Agreement' - f'κ' - f'
' - f'{dim_rows}
' + f'
' + f'{n_segs} segments · {n_dis} disagreement{"s" if n_dis!=1 else ""}
' + f'
Per-Dimension κ
' + f'{dim_rows}
' ) def _rules_html(rules: list[dict]) -> str: - """Render pending rules as design-system rule cards.""" if not rules: - return '
No rules pending review.
' - - TYPE_BADGE = { - "boundary_clarification": ("cc-rule-badge--boundary", "Boundary Clarification"), - "disambiguation_rule": ("cc-rule-badge--disambiguation", "Disambiguation Rule"), - "behavioral_marker_refinement": ("cc-rule-badge--marker", "Marker Refinement"), + 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: - rule_type = r.get("rule_type", "unknown") - badge_mod, badge_label = TYPE_BADGE.get(rule_type, ("cc-rule-badge--marker", rule_type)) + 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", "")) @@ -473,64 +627,60 @@ def _rules_html(rules: list[dict]) -> str: note = _h(r.get("agent2_note", "")) rid = _h(r.get("rule_id", "")) created = r.get("created_at", "")[:10] - cards.append( - f'
' - f'
' - f'
' - f'{badge_label}' - f'{rid} · {created}' + f'
' + f'
' + f'
' + f'{label}' + f'' + f'{rid} · {created}' f'
' - f'dims: {dims}' + f'dims: {dims}' f'
' - f'

{desc}

' - f'

Rationale: {rat}

' - f'
' + f'
' ) - return "".join(cards) def _coding_progress_html(state: dict) -> str: - """Render coding progress using design-system classes.""" 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 - return ( - f'
' - f'
' - f'Section {idx + 1} of {len(sections)} — ' - f'{_h(sec.get("label", ""))}' - f' · Episode {ep_num} of {total}' + f'
' + f'
' + f'Section {idx+1}/{len(sections)} — ' + f'{_h(sec.get("label",""))} · Episode {ep_num}/{total}' f'
' - f'
' - f'
' - f'
' - f'
{coded} of {total} coded ({pct}%)
' + f'
' + f'
' + f'
{coded}/{total} coded ({pct}%)
' f'
' ) # =========================================================================== -# STATE HELPERS +# STATE # =========================================================================== def _empty_state() -> dict: @@ -538,6 +688,7 @@ def _empty_state() -> dict: "session_id": "", "researcher_id": "", "turns": [], + "speakers": {}, # name → palette entry "sections": [], "section_idx": 0, "section_stages": {}, @@ -548,7 +699,7 @@ def _empty_state() -> dict: "codings": {}, "stage": "upload", "kappa_report": None, - "_last_error": None, + "agent_logs": [], # list of log entry dicts } @@ -564,33 +715,23 @@ def _current_section(state: dict) -> dict | None: def _current_section_segments(state: dict) -> list[dict]: sec = _current_section(state) - if not sec: - return [] - return state["section_segments_coded"].get(sec["section_id"], []) + 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 _all_sections_done(state: dict) -> bool: - stages = state.get("section_stages", {}) - secs = state.get("sections", []) - return bool(secs) and all( - stages.get(s["section_id"]) == "done" for s in secs - ) + return [t for t in turns + if section["start_turn_id"] <= t["turn_id"] <= section["end_turn_id"]] def _persist(state: dict) -> None: try: d = _session_dir(state) d.mkdir(parents=True, exist_ok=True) - payload = {k: v for k, v in state.items() if k not in ("turns", "kappa_report")} + skip = {"turns", "kappa_report"} (d / "app_state.json").write_text( - json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8" + json.dumps({k: v for k, v in state.items() if k not in skip}, + indent=2, ensure_ascii=False), + encoding="utf-8", ) except Exception: pass @@ -600,34 +741,26 @@ 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 UI HELPERS +# CODING RENDER HELPERS # =========================================================================== -def _segment_dropdown_label(seg: dict, codings: dict) -> str: - sid = seg["segment_id"] - ep = sid.split("_ep")[-1] if "_ep" in sid else sid[-4:] - did = seg.get("dimension_id") or "?" - coded = "✓" if codings.get(sid, {}).get("dimension_id") else "○" - flag = " ⚠" if seg.get("uncertain") else "" +def _segment_label(seg: dict, codings: dict) -> str: + sid = seg["segment_id"] + ep = sid.split("_ep")[-1] if "_ep" in sid else sid[-4:] + did = seg.get("dimension_id") or "?" + coded = "✓" if codings.get(sid, {}).get("dimension_id") else "○" + flag = " ⚠" if seg.get("uncertain") else "" return f"{coded} ep{ep} [{did}]{flag}" -def _format_turns_md(seg: dict) -> str: - turns = seg.get("turns", []) - if not turns: - return "*No turns in this segment.*" - speakers = list(dict.fromkeys(t.get("speaker", "") for t in turns)) - lines = [] - for t in turns: - sp = t.get("speaker", "?") - time = t.get("start_time", "") - text = t.get("text", "") - fmt = f"**{sp}**" if speakers.index(sp) % 2 == 0 else f"_{sp}_" - lines.append(f"{fmt} `{time}` \n{text}") - return "\n\n---\n\n".join(lines) - - def _proposal_md(seg: dict) -> str: did = seg.get("dimension_id", "?") rat = seg.get("rationale", "") @@ -636,84 +769,95 @@ def _proposal_md(seg: dict) -> str: tags.append("✅ Confident") if seg.get("uncertain"): tags.append(f"⚠️ Uncertain — {seg.get('uncertainty_note', '')}") - tag_line = " ".join(tags) - return f"> **AI proposal: {did}** \n> {rat}\n\n{tag_line}".strip() + return f"> **AI proposal: {did}** \n> {rat}\n\n{' '.join(tags)}".strip() CODING_EMPTY = ( - "", # progress html - gr.update(choices=[], value=None), # segment_jump - "*Run Agent 1a and confirm boundaries first.*", # turns_display - "", # uncertainty_html - gr.update(value="", visible=False), # proposal_md - gr.update(choices=DIM_CHOICES, value=None), # dim_radio - "", # dim_desc_html - "", # comment_box - gr.update(visible=False), # next_section_btn + "", # progress html + gr.update(choices=[], value=None), # segment_jump + "", # turns_display_html + "", # uncertainty_html + gr.update(value="", visible=False), # proposal_md + gr.update(choices=DIM_CHOICES, value=None), # dim_radio + "", # dim_desc_html + "", # comment_box + gr.update(visible=False), # next_section_btn ) def _render_coding(state: dict) -> tuple: - segs = _current_section_segments(state) - codings = state.get("codings", {}) - cidx = state.get("coding_idx", 0) + 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_dim = existing.get("dimension_id", "") - choice = next((c for c in DIM_CHOICES if c.startswith(saved_dim)), None) - - all_coded = len(codings) >= len(segs) and all( + 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) + all_done = len(codings) >= len(segs) and all( codings.get(s["segment_id"], {}).get("dimension_id") for s in segs ) - jump_choices = [_segment_dropdown_label(s, codings) for s in segs] + labels = [_segment_label(s, codings) for s in segs] return ( _coding_progress_html(state), - gr.update(choices=jump_choices, value=jump_choices[min(cidx, len(segs) - 1)]), - _format_turns_md(seg), + gr.update(choices=labels, value=labels[min(cidx, len(segs) - 1)]), + _format_turns_html(seg, speaker_map), _uncertainty_html(seg), gr.update(value=_proposal_md(seg), visible=False), gr.update(choices=DIM_CHOICES, value=choice), _dim_desc_html(choice or ""), existing.get("comment", ""), - gr.update(visible=all_coded), + gr.update(visible=all_done), ) # =========================================================================== -# BACKEND CALLBACKS +# CALLBACKS # =========================================================================== -# ── Stage 1: Parse ─────────────────────────────────────────────────────── +# ── Stage 1: Parse ─────────────────────────────────────────────────────────── def fn_parse(file_obj, session_id: str, researcher_id: str, state: dict): if file_obj is None: raise gr.Error("Upload a transcript file first.") if not session_id.strip(): - raise gr.Error("Enter a session ID.") + raise gr.Error("Enter a Session ID (e.g. dyad_01).") if not researcher_id.strip(): - raise gr.Error("Enter your researcher ID.") + raise gr.Error("Enter your Researcher ID (e.g. R1).") + t0 = time.perf_counter() try: turns = parse_transcript(file_obj.name) except Exception as e: raise gr.Error(f"Could not parse transcript: {e}") from e if len(turns) < 5: - raise gr.Error(f"Only {len(turns)} turns found. Check that the transcript format is correct.") + raise gr.Error(f"Only {len(turns)} turns found — check the transcript format.") + + rt = round(time.perf_counter() - t0, 1) + speaker_map = _assign_speakers(turns) + speakers = list(speaker_map.keys()) new_state = _empty_state() new_state.update({ "session_id": session_id.strip(), "researcher_id": researcher_id.strip(), "turns": turns, + "speakers": speaker_map, "stage": "parsed", }) + log_entry = _make_log_entry( + "Transcript Parser", rt, + turns=len(turns), speakers=len(speakers), + system_prompt_preview="(no LLM call — rule-based parser)", + ) + new_state = _push_log(new_state, log_entry) d = SESSIONS_ROOT / session_id.strip() d.mkdir(parents=True, exist_ok=True) @@ -721,65 +865,69 @@ def fn_parse(file_obj, session_id: str, researcher_id: str, state: dict): json.dumps(turns, indent=2, ensure_ascii=False), encoding="utf-8" ) - speakers = list(dict.fromkeys(t["speaker"] for t in turns)) duration = _seconds_to_hms(turns[-1]["start_seconds"] - turns[0]["start_seconds"]) - summary_md = ( - f"**Session:** `{session_id.strip()}` · **Researcher:** `{researcher_id.strip()}`\n\n" + legend = _speaker_legend_html(speaker_map) + summary = ( + f"{legend}" f"| | |\n|---|---|\n" - f"| Turns | {len(turns)} |\n" + f"| Turns | **{len(turns)}** |\n" f"| Speakers | {', '.join(speakers)} |\n" f"| Duration | {duration} |\n" + f"| Session | `{session_id.strip()}` |\n" ) - gr.Info(f"Parsed {len(turns)} turns. Review the summary, then detect sections.") + gr.Info(f"Parsed {len(turns)} turns from {len(speakers)} speaker(s).") return ( new_state, _pipeline_html("parsed"), - summary_md, - gr.update(visible=True), # col_agent0 + summary, + gr.update(visible=True), # col_agent0 + _agent_log_html(new_state["agent_logs"]), ) -# ── Stage 2: Agent 0 section detection ─────────────────────────────────── +# ── Stage 2: Agent 0 ───────────────────────────────────────────────────────── def fn_run_agent0(state: dict): if not state.get("turns"): raise gr.Error("Parse a transcript first.") - yield ( - state, - _pipeline_html("parsed"), - gr.update(visible=False), - "", "", - ) + yield state, _pipeline_html("parsed"), gr.update(visible=False), "", "", "" + t0 = time.perf_counter() try: - result = run_sectioning( - turns=state["turns"], - session_id=state["session_id"], - ) + result = run_sectioning(turns=state["turns"], session_id=state["session_id"]) except Exception as e: raise gr.Error(f"Agent 0 failed: {e}") from e + rt = round(time.perf_counter() - t0, 1) sections = result["sections"] if not sections: - raise gr.Error("Agent 0 returned no sections. Try again or check the transcript.") + raise gr.Error("Agent 0 returned no sections. Try again.") - warnings = result.get("warnings", []) - if warnings: - gr.Warning("Section coverage warnings detected — check the transcript range.") + from agent0_sectioner import build_system_prompt, load_dimension_labels + sys_prev = build_system_prompt(load_dimension_labels())[:120] + user_prev = f"Segment {len(state['turns'])} turns into topical sections." state = dict(state) state["sections"] = sections state["section_stages"] = {s["section_id"]: "pending" for s in sections} state["stage"] = "sectioned" + log = _make_log_entry( + "Agent 0 — Structural Segmenter", rt, + sections_proposed=len(sections), + warnings=len(result.get("warnings", [])), + system_prompt_preview=sys_prev, + user_prompt_preview=user_prev, + ) + state = _push_log(state, log) d = _session_dir(state) (d / "sections_proposed.json").write_text( json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8" ) - overview = result.get("session_overview", "") + overview = result.get("session_overview", "") sections_md = ( "| # | Label | Turns | Time |\n|---|---|---|---|\n" + "\n".join( @@ -788,45 +936,45 @@ def fn_run_agent0(state: dict): f"{s['start_time']}–{s['end_time']} |" for s in sections ) + + (f"\n\n*{overview}*" if overview else "") ) labels_txt = "\n".join(s["label"] for s in sections) - gr.Info(f"{len(sections)} sections detected. Review and edit labels, then confirm.") + if result.get("warnings"): + gr.Warning("Coverage warnings detected — check the section table.") + gr.Info(f"{len(sections)} sections detected in {rt}s.") + yield ( state, _pipeline_html("sectioned"), - gr.update(visible=True), # col_sections - sections_md + (f"\n\n*{overview}*" if overview else ""), + gr.update(visible=True), + sections_md, labels_txt, + _agent_log_html(state["agent_logs"]), ) -# ── Stage 2b: Confirm sections ──────────────────────────────────────────── +# ── Stage 2b: Confirm sections ──────────────────────────────────────────────── def fn_confirm_sections(labels_text: str, state: dict): sections = state.get("sections", []) if not sections: raise gr.Error("No sections to confirm — run Agent 0 first.") - labels = [l.strip() for l in labels_text.strip().splitlines() if l.strip()] - if len(labels) != len(sections): - gr.Warning( - f"Label count ({len(labels)}) doesn't match section count ({len(sections)}). " - "Using original labels for unmatched sections." - ) + labels = [l.strip() for l in labels_text.strip().splitlines() if l.strip()] + confirmed = [dict(s, label=labels[i] if i < len(labels) else s["label"]) + for i, s in enumerate(sections)] - confirmed = [] - for i, s in enumerate(sections): - updated = dict(s) - if i < len(labels): - updated["label"] = labels[i] - confirmed.append(updated) + if len(labels) != len(sections): + gr.Warning(f"Label count mismatch ({len(labels)} vs {len(sections)}) — unmatched sections keep original labels.") state = dict(state) - state["sections"] = confirmed - state["section_idx"] = 0 - state["section_stages"] = {s["section_id"]: "pending" for s in confirmed} - state["stage"] = "coding" + state.update({ + "sections": confirmed, + "section_idx": 0, + "section_stages": {s["section_id"]: "pending" for s in confirmed}, + "stage": "coding", + }) d = _session_dir(state) (d / "sections_confirmed.json").write_text( @@ -841,21 +989,20 @@ def fn_confirm_sections(labels_text: str, state: dict): f"*{sec.get('summary', '')}* · " f"turns {sec['start_turn_id']}–{sec['end_turn_id']} ({n} turns)" ) - - gr.Info(f"{len(confirmed)} sections confirmed. Now detect boundaries for Section 1.") + gr.Info(f"{len(confirmed)} sections confirmed. Detect boundaries for Section 1.") return ( state, _pipeline_html("coding"), _section_cards_html(confirmed, state["section_stages"], 0), hdr, - gr.update(visible=True), # col_section_work - gr.update(visible=True), # col_boundary_btn - gr.update(visible=False), # col_boundary_review - gr.update(visible=False), # col_coding + gr.update(visible=True), # col_section_work + gr.update(visible=True), # col_boundary_btn + gr.update(visible=False), # col_boundary_review + gr.update(visible=False), # col_coding ) -# ── Stage 3a: Agent 1a boundary detection ──────────────────────────────── +# ── Stage 3a: Agent 1a ──────────────────────────────────────────────────────── def fn_propose_boundaries(state: dict): sec = _current_section(state) @@ -866,56 +1013,70 @@ def fn_propose_boundaries(state: dict): if not turns: raise gr.Error(f"No turns found for section {sec['section_id']}.") - yield (state, "⏳ Detecting episode boundaries…", gr.update(visible=False), "", "") + yield state, "⏳ Detecting episode boundaries…", gr.update(visible=False), "", "", "" + t0 = time.perf_counter() try: - result = propose_boundaries( - section=sec, turns=turns, session_id=state["session_id"] - ) + result = propose_boundaries(section=sec, turns=turns, + session_id=state["session_id"]) except Exception as e: raise gr.Error(f"Agent 1a failed: {e}") from e + rt = round(time.perf_counter() - t0, 1) + + from agent1a_boundary import build_system_prompt as a1a_sys + from agent1a_boundary import build_user_prompt as a1a_user + sys_prev = a1a_sys()[:120] + user_prev = f"Section: {sec['section_id']} — {sec['label']} ({len(turns)} turns)" + boundaries = result["boundaries"] - n_low = sum(1 for b in boundaries if b.get("confidence") == "low") + n_low = sum(1 for b in boundaries if b.get("confidence") == "low") if n_low: - gr.Warning(f"{n_low} boundary{'is' if n_low == 1 else 'ies'} have low confidence — review carefully.") + gr.Warning(f"{n_low} low-confidence boundary{'ies' if n_low>1 else ''} — review carefully.") state = dict(state) state["section_boundaries"][sec["section_id"]] = boundaries state["section_segments"][sec["section_id"]] = result["segments"] state["section_stages"][sec["section_id"]] = "boundaries" + log = _make_log_entry( + "Agent 1a — Boundary Detector", rt, + boundaries_proposed=len(boundaries), + episodes=len(result["segments"]), + low_confidence=n_low, + system_prompt_preview=sys_prev, + user_prompt_preview=user_prev, + ) + state = _push_log(state, log) ids_text = ", ".join(str(b["after_turn_id"]) for b in boundaries) - - status = ( - f"**{len(boundaries)} boundary{'ies' if len(boundaries) != 1 else ''} proposed " + status = ( + f"**{len(boundaries)} boundary{'ies' if len(boundaries)!=1 else ''} proposed " f"→ {len(result['segments'])} episodes.** \n" - f"Review the episode table. Edit turn IDs below if needed, then confirm." + f"Review the episode table, edit turn IDs if needed, then confirm." ) + gr.Info(f"{len(boundaries)} boundaries detected in {rt}s.") yield ( state, status, gr.update(visible=True), _episode_table_html(turns, boundaries), ids_text, + _agent_log_html(state["agent_logs"]), ) -# ── Stage 3b: Confirm boundaries + run Agent 1b ─────────────────────────── +# ── Stage 3b: Confirm + 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.") - turns = _turns_for_section(state["turns"], sec) - if not turns: - raise gr.Error(f"No turns for section {sec['section_id']}.") - - # Parse researcher-edited boundary IDs + 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: @@ -923,141 +1084,124 @@ def fn_confirm_and_code(boundary_ids_text: str, state: dict): try: tid = int(tok) except ValueError: - raise gr.Error(f"'{tok}' is not a valid turn ID. Enter integers only.") + raise gr.Error(f"'{tok}' is not a valid turn ID.") if tid not in valid_ids: - raise gr.Error( - f"Turn ID {tid} is not in this section " - f"(valid range: {min(valid_ids)}–{max(valid_ids)})." - ) - boundaries.append({ - "boundary_id": f"r_{tid}", - "after_turn_id": tid, - "confidence": "high", - "boundary_signal": "researcher_defined", - "rationale": "Boundary defined by researcher review.", - }) + raise gr.Error(f"Turn {tid} is outside this section (range {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, state["session_id"]) + if not segments: - raise gr.Error("Boundary IDs produced zero segments. Check your turn ID entries.") + raise gr.Error("No segments produced — check your boundary turn IDs.") state = dict(state) state["section_boundaries"][sec["section_id"]] = boundaries state["section_segments"][sec["section_id"]] = segments - n_segs = len(segments) - yield ( - state, - f"⏳ Agent 1b coding {n_segs} episode{'s' if n_segs != 1 else ''}…", - gr.update(visible=False), - *CODING_EMPTY, - ) + yield state, f"⏳ Agent 1b coding {len(segments)} episode(s)…", gr.update(visible=False), *CODING_EMPTY, "" + t0 = time.perf_counter() try: coded = code_section(section=sec, segments=segments) except Exception as e: raise gr.Error(f"Agent 1b failed: {e}") from e + rt = round(time.perf_counter() - t0, 1) + + from agent1b_coder import build_system_prompt as a1b_sys, load_tier1, load_tier2 + tier1 = load_tier1() + tier2 = load_tier2() + sys_prev = a1b_sys(tier1, tier2, sec)[:120] + user_prev = f"Code {len(segments)} segments in section: {sec['label']}" + + 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=sys_prev, + user_prompt_preview=user_prev, + ) + 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" ) - n_uncertain = sum(1 for s in coded if s.get("uncertain")) - msg = f"✓ {len(coded)} segments coded." + msg = f"✓ {len(coded)} segments coded in {rt}s." if n_uncertain: - msg += f" **{n_uncertain} flagged uncertain** — check ⚠ markers." - msg += " AI proposals hidden — code independently, then reveal if needed." + msg += f" **{n_uncertain} flagged ⚠ uncertain** — review those first." + gr.Info(f"{len(coded)} segments coded. {n_uncertain} uncertain.") - gr.Info(f"{len(coded)} segments ready for coding.") - yield ( - state, - msg, - gr.update(visible=True), - *_render_coding(state), - ) + yield state, msg, gr.update(visible=True), *_render_coding(state), _agent_log_html(state["agent_logs"]) -# ── Stage 3c: Navigate segments ────────────────────────────────────────── +# ── Navigate segments ───────────────────────────────────────────────────────── def fn_navigate(direction: int, dim_choice: str, comment: str, state: dict): - segs = _current_section_segments(state) + 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], - "comment": comment.strip(), - } - - state = dict(state) - state["codings"] = codings + codings[sid] = {"dimension_id": DIM_ID_FROM_CHOICE[dim_choice], "comment": comment.strip()} + state = dict(state) + state["codings"] = codings state["coding_idx"] = max(0, min(idx + direction, len(segs) - 1)) return state, *_render_coding(state) -def fn_jump_to_segment(label: str, state: dict): +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_dropdown_label(s, codings) for s in segs] + 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_proposal(state: dict): +def fn_reveal(state: dict): segs = _current_section_segments(state) if not segs: return gr.update(visible=False) - idx = state.get("coding_idx", 0) - seg = segs[min(idx, len(segs) - 1)] + seg = segs[min(state.get("coding_idx", 0), len(segs) - 1)] return gr.update(value=_proposal_md(seg), visible=True) -def fn_update_dim_desc(choice: str): +def fn_dim_desc(choice: str): return _dim_desc_html(choice or "") -# ── Stage 3d: Next section ──────────────────────────────────────────────── +# ── Next section ────────────────────────────────────────────────────────────── def fn_next_section(dim_choice: str, comment: str, state: dict): segs = _current_section_segments(state) codings = dict(state.get("codings", {})) idx = state.get("coding_idx", 0) - - # Save last segment's coding if a dimension was selected if segs and dim_choice: - sid = segs[min(idx, len(segs) - 1)]["segment_id"] - codings[sid] = { - "dimension_id": DIM_ID_FROM_CHOICE[dim_choice], - "comment": comment.strip(), - } + sid = segs[min(idx, len(segs) - 1)]["segment_id"] + codings[sid] = {"dimension_id": DIM_ID_FROM_CHOICE[dim_choice], "comment": comment.strip()} - state = dict(state) - state["codings"] = codings - - sections = state.get("sections", []) - sec_idx = state.get("section_idx", 0) - cur_sec = sections[sec_idx] - state["section_stages"][cur_sec["section_id"]] = "done" + state = dict(state) + state["codings"] = codings + sections = state.get("sections", []) + sec_idx = state.get("section_idx", 0) + cur_id = sections[sec_idx]["section_id"] + state["section_stages"][cur_id] = "done" next_idx = sec_idx + 1 - if next_idx >= len(sections): - # All done state["stage"] = "complete" _write_coding_file(state) _persist(state) @@ -1067,110 +1211,92 @@ def fn_next_section(dim_choice: str, comment: str, state: dict): _pipeline_html("complete"), _section_cards_html(sections, state["section_stages"], sec_idx), "", - gr.update(visible=False), # col_boundary_btn - gr.update(visible=False), # col_boundary_review - gr.update(visible=False), # col_coding - gr.update(visible=True), # col_complete + gr.update(visible=False), + gr.update(visible=False), + gr.update(visible=False), + gr.update(visible=True), ) - state["section_idx"] = next_idx - state["coding_idx"] = 0 - next_sec = sections[next_idx] - n = next_sec["end_turn_id"] - next_sec["start_turn_id"] + 1 + state["section_idx"] = next_idx + 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"### 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(state) - - gr.Info(f"Moving to section {next_idx + 1}: {next_sec['label']}") + gr.Info(f"Section {next_idx+1}: {next_sec['label']}") return ( state, _pipeline_html("coding"), _section_cards_html(sections, state["section_stages"], next_idx), hdr, - gr.update(visible=True), # col_boundary_btn - gr.update(visible=False), # col_boundary_review - gr.update(visible=False), # col_coding - gr.update(visible=False), # col_complete + gr.update(visible=True), + gr.update(visible=False), + gr.update(visible=False), + gr.update(visible=False), ) -# ── Download coding file ────────────────────────────────────────────────── +# ── Download ────────────────────────────────────────────────────────────────── def _write_coding_file(state: dict) -> Path: all_segs: list[dict] = [] for sec in state.get("sections", []): - coded = state["section_segments_coded"].get(sec["section_id"], []) - all_segs.extend(coded) - + 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", ""), - "comment": codings.get(s["segment_id"], {}).get("comment", ""), - } + {"segment_id": s["segment_id"], "section_id": s.get("section_id", ""), + "dimension_id": codings.get(s["segment_id"], {}).get("dimension_id", ""), + "comment": codings.get(s["segment_id"], {}).get("comment", "")} for s in all_segs ], } - - segments_all = { - "segments": [{k: v for k, v in s.items() if k != "turns"} 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(segments_all, indent=2, ensure_ascii=False), encoding="utf-8" + json.dumps(segs_all, indent=2, ensure_ascii=False), encoding="utf-8" ) - rid = state["researcher_id"] - out_path = d / f"coding_{rid}.json" - out_path.write_text( - json.dumps(output, indent=2, ensure_ascii=False), encoding="utf-8" - ) - return out_path + 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.") - try: - path = _write_coding_file(state) - tmp = Path(tempfile.mktemp(suffix=f"_{path.name}")) - tmp.write_bytes(path.read_bytes()) - return str(tmp) - except Exception as e: - raise gr.Error(f"Download failed: {e}") from e + path = _write_coding_file(state) + tmp = Path(tempfile.mktemp(suffix=f"_{path.name}")) + tmp.write_bytes(path.read_bytes()) + return str(tmp) -# ── Agreement tab ───────────────────────────────────────────────────────── +# ── 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("Load a session in the Pipeline tab first.") + 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 coding file was not found. Complete and download your coding in the Pipeline tab." - ) + raise gr.Error("Your own coding file not found — download it from the Pipeline tab first.") if not segs_path.exists(): - raise gr.Error( - "Segments file not found. Make sure you completed the coding pipeline." - ) + 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"], @@ -1182,69 +1308,74 @@ def fn_calculate_kappa(r2_file, state: dict): except Exception as e: raise gr.Error(f"Kappa calculation failed: {e}") from e - state = dict(state) - state["kappa_report"] = report - + 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"Kappa gate passed! {n_dis} disagreement(s) to resolve.") + gr.Info(f"κ={report['overall_kappa']:.3f} — gate passed! {n_dis} disagreements to resolve.") else: - gr.Warning("Kappa below 0.70 threshold — review and re-code before proceeding.") + gr.Warning(f"κ={report['overall_kappa']:.3f} — below 0.70 threshold. Review and re-code.") dis_md = "" if n_dis: - dis = report.get("segments_in_disagreement", []) - rows = "| Segment | R1 | R2 | Agent |\n|---|---|---|---|\n" - for di in dis[:15]: + 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" + f"| {di.get('r1_dimension','?')} " + f"| {di.get('r2_dimension','?')} " + f"| {di.get('agent_dimension','?')} |\n" ) - if len(dis) > 15: - rows += f"| *…{len(dis) - 15} more* | | | |\n" - dis_md = f"### Disagreements ({n_dis} total)\n\n{rows}" + 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_resolve(seg_id: str, dim_choice: str, note: str, state: dict): if not seg_id.strip(): - raise gr.Error("Enter the segment ID to resolve.") + raise gr.Error("Enter the segment ID.") if not dim_choice: raise gr.Error("Select the resolved dimension.") - d = _session_dir(state) - resolved_dim = DIM_ID_FROM_CHOICE.get(dim_choice, dim_choice) + resolved = DIM_ID_FROM_CHOICE.get(dim_choice, dim_choice) try: resolve_disagreement( - report_path=d / "kappa_report.json", - segment_id=seg_id.strip(), - resolved_dimension=resolved_dim, + 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 disagreement: {e}") from e - gr.Info(f"Resolved {seg_id.strip()} → {resolved_dim}") - return state, f"✓ Resolved `{seg_id.strip()}` → **{resolved_dim}**" + 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 to discard.") - d = _session_dir(state) + raise gr.Error("Enter the segment ID.") try: discard_disagreement( - report_path=d / "kappa_report.json", - segment_id=seg_id.strip(), - discard_note=note.strip(), + 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 @@ -1252,282 +1383,408 @@ def fn_discard(seg_id: str, note: str, state: dict): return state, f"Discarded `{seg_id.strip()}`" -# ── Rule review tab ─────────────────────────────────────────────────────── +# ── Rules ───────────────────────────────────────────────────────────────────── def fn_load_rules(): - try: - pending = list_pending_rules() - except Exception as e: - raise gr.Error(f"Could not load rules: {e}") from e + pending = list_pending_rules() choices = [f"{r['rule_id']}: {r['description'][:55]}…" for r in pending] return _rules_html(pending), choices -def fn_approve_rule(choice: str, researcher_id: str, note: str): +def fn_approve(choice: str, researcher: str, note: str): if not choice: - raise gr.Error("Select a rule to approve.") - if not researcher_id.strip(): - raise gr.Error("Enter your researcher ID.") - rule_id = choice.split(":")[0].strip() - try: - approve_rule(rule_id, researcher_id.strip(), note.strip()) - except Exception as e: - raise gr.Error(f"Approval failed: {e}") from e - gr.Info(f"Rule {rule_id} approved — now active for Agent 1b.") - return f"✓ Rule **{rule_id}** approved by {researcher_id.strip()}." + 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 — now active for Agent 1b.") + return f"✓ Rule **{rid}** approved." -def fn_reject_rule(choice: str, researcher_id: str, note: str): +def fn_reject(choice: str, researcher: str, note: str): if not choice: - raise gr.Error("Select a rule to reject.") - if not researcher_id.strip(): - raise gr.Error("Enter your researcher ID.") + 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 so Agent 2 can learn from it.") - rule_id = choice.split(":")[0].strip() - try: - reject_rule(rule_id, researcher_id.strip(), note.strip()) - except Exception as e: - raise gr.Error(f"Rejection failed: {e}") from e - gr.Info(f"Rule {rule_id} rejected.") - return f"✗ Rule **{rule_id}** rejected." + 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." + + +# =========================================================================== +# EXTRA CSS +# =========================================================================== + +EXTRA_CSS = """ +.gradio-container { max-width: 1200px !important; margin: 0 auto !important; } +footer { display: none !important; } +.info-sidebar { font-size: 0.83em; } +.info-sidebar h4 { font-size: 0.95em; color: #1e293b; margin: 0 0 8px; } +/* Gradio tab styling */ +.tab-nav { border-bottom: 2px solid #e2e8f0 !important; } +.tab-nav button { font-weight: 600 !important; font-size: 0.88em !important; } +.tab-nav button.selected { color: #4338ca !important; border-bottom-color: #4338ca !important; } +/* Focus rings */ +:focus-visible { outline: 2px solid #4338ca; outline-offset: 2px; } +:focus { outline: none; } +/* Gradio primary button */ +.gradio-container button.primary { + background: #4338ca !important; border-color: #4338ca !important; +} +.gradio-container button.primary:hover { + background: #3730a3 !important; border-color: #3730a3 !important; +} +""" # =========================================================================== -# UI DEFINITION +# UI # =========================================================================== +CSS = _load_css() + EXTRA_CSS + with gr.Blocks(title="CollabCode", css=CSS, theme=gr.themes.Soft()) as demo: state = gr.State(_empty_state()) - # ── Header ─────────────────────────────────────────────────────────── + # ── App header ──────────────────────────────────────────────────────── gr.HTML( - '
' - '

' - 'CollabCode

' - '

' + '

' + '
' + '

CollabCode

' + '

' 'Human-in-the-loop pipeline for collaborative learning transcript analysis' - '

' + '

' + '
' + '
' + f'Model: {MODEL_ID.split("/")[-1]}' + f'
Temperature: {TEMPERATURE}' + '
' + '
' ) - # ── Pipeline progress stepper (dynamic) ────────────────────────────── + # ── Pipeline stepper (always visible) ──────────────────────────────── pipeline_html = gr.HTML(_pipeline_html("upload")) + # ── Agent activity log (shared across all tabs) ─────────────────────── + agent_log_html = gr.HTML(_agent_log_html([])) + with gr.Tabs(): # ================================================================== - # TAB 1: Pipeline + # TAB 1 — Research Pipeline # ================================================================== - with gr.Tab("Pipeline"): - - # Stage 1: Upload & Parse - with gr.Group(): - gr.Markdown("### Step 1 — Upload Transcript") - with gr.Row(equal_height=True): - transcript_file = gr.File( - label="Transcript file (.txt / .vtt)", - file_types=[".txt", ".vtt"], - scale=2, - ) - with gr.Column(scale=1): - session_id_box = gr.Textbox(label="Session ID", placeholder="e.g. dyad_01") - researcher_id_box = gr.Textbox(label="Researcher ID", placeholder="e.g. R1") - parse_btn = gr.Button("Parse Transcript →", variant="primary") - parse_status = gr.Markdown(visible=False) - - # Stage 2: Detect sections - with gr.Column(visible=False) as col_agent0: - gr.HTML('
') - gr.Markdown("### Step 2 — Detect Topical Sections (Agent 0)") - gr.Markdown( - "Agent 0 segments the transcript into activity phases — not behavioral codes. " - "You will review and rename sections before coding begins. " - "*(Hearst 1997; Purver et al. 2006)*" - ) - agent0_btn = gr.Button("Detect Sections →", variant="primary") - agent0_status = gr.Markdown() - - # Stage 2b: Section review - with gr.Column(visible=False) as col_sections: - gr.HTML('
') - gr.Markdown("### Step 2b — Review Sections") - sections_display_md = gr.Markdown() - with gr.Accordion("Edit section labels", open=True): - gr.Markdown( - "One label per line. Turn boundaries stay as proposed. " - "To remove a section, delete its label — remaining labels " - "will map to sections in order." - ) - sections_labels_box = gr.Textbox(lines=8, show_label=False) - confirm_sections_btn = gr.Button("Confirm Sections →", variant="primary") - - # Stage 3: Per-section pipeline - with gr.Column(visible=False) as col_section_work: - gr.HTML('
') - gr.Markdown("### Step 3 — Section-by-Section Coding") - sections_overview_html = gr.HTML() - section_header_md = gr.Markdown() - - # 3a: Propose boundaries - with gr.Column() as col_boundary_btn: - propose_btn = gr.Button( - "Detect Episode Boundaries (Agent 1a) →", variant="primary" - ) - boundary_status = gr.Markdown() - - # 3b: Boundary review + confirm - with gr.Column(visible=False) as col_boundary_review: - gr.HTML('
' - '
Episode Structure
') - boundary_display_html = gr.HTML() - gr.HTML('
') - with gr.Row(): - with gr.Column(scale=3): - boundary_ids_box = gr.Textbox( - label="Boundary turn IDs — comma-separated turns after which a new episode begins", - placeholder="e.g. 12, 28, 35 (leave empty for one episode)", - lines=1, + with gr.Tab("Research Pipeline"): + + with gr.Row(equal_height=False): + + # ── Main content (4/5) ──────────────────────────────────── + with gr.Column(scale=4): + + # Step 1: Upload & Parse + with gr.Group(): + gr.Markdown("### Step 1 — Upload Transcript") + gr.Markdown( + "Upload your Zoom `.txt` or `.vtt` transcript. " + "Both researchers should run the full pipeline " + "independently on the **same** transcript file.", + elem_id="parse-help", + ) + with gr.Row(equal_height=True): + transcript_file = gr.File( + label="Transcript (.txt / .vtt)", file_types=[".txt", ".vtt"], scale=2 ) - with gr.Column(scale=1): - confirm_boundaries_btn = gr.Button( - "Confirm & Code (Agent 1b) →", variant="primary" - ) - code_status = gr.Markdown() - - # 3c: Segment coding - with gr.Column(visible=False) as col_coding: - coding_progress_html_comp = gr.HTML() - segment_jump = gr.Dropdown( - label="Jump to segment", choices=[], value=None, - interactive=True, scale=1, - ) - with gr.Row(equal_height=False): - # Left: turns display - with gr.Column(scale=3): - uncertainty_html_comp = gr.HTML() - turns_display_md = gr.Markdown( - label="Transcript segment", show_label=True - ) - proposal_md_comp = gr.Markdown(visible=False) - - # Right: coding controls - with gr.Column(scale=2): - gr.Markdown("#### Your coding") - dim_radio = gr.Radio( - choices=DIM_CHOICES, label="Dimension", - value=None, interactive=True, + with gr.Column(scale=1): + session_id_box = gr.Textbox(label="Session ID", placeholder="e.g. dyad_01") + researcher_id_box = gr.Textbox(label="Researcher ID", placeholder="e.g. R1") + parse_btn = gr.Button("Parse Transcript →", variant="primary") + parse_status = gr.Markdown(visible=False) + + # Step 2: Detect Sections + with gr.Column(visible=False) as col_agent0: + gr.HTML('
') + gr.Markdown("### Step 2 — Detect Topical Sections (Agent 0)") + gr.Markdown( + "Agent 0 segments the transcript into **activity phases** using " + "lexical cohesion signals *(Hearst 1997; Purver et al. 2006)*. " + "You will review and rename sections before any coding begins." + ) + agent0_btn = gr.Button("Detect Sections →", variant="primary") + agent0_status = gr.Markdown() + + # Step 2b: Review sections + with gr.Column(visible=False) as col_sections: + gr.HTML('
') + gr.Markdown("### Step 2b — Review Sections") + sections_display_md = gr.Markdown() + with gr.Accordion("Edit section labels (one per line)", open=True): + gr.Markdown( + "Edit labels to match your theoretical framing. " + "**Turn boundaries are fixed** — to merge sections, " + "delete the label line and adjust manually." ) - dim_desc_html_comp = gr.HTML() - comment_box = gr.Textbox( - label="Comment (optional)", lines=2, placeholder="Notes for disagreement review…" + sections_labels_box = gr.Textbox(lines=8, show_label=False) + confirm_sections_btn = gr.Button("Confirm Sections →", variant="primary") + + # Step 3: Per-section coding + with gr.Column(visible=False) as col_section_work: + gr.HTML('
') + gr.Markdown("### Step 3 — Section-by-Section Coding") + sections_overview_html = gr.HTML() + section_header_md = gr.Markdown() + + # 3a: Boundary detection + with gr.Column() as col_boundary_btn: + propose_btn = gr.Button( + "Detect Episode Boundaries (Agent 1a) →", variant="primary" ) - reveal_btn = gr.Button( - "Reveal AI proposal", variant="secondary", size="sm" + boundary_status = gr.Markdown() + + # 3b: Boundary review + with gr.Column(visible=False) as col_boundary_review: + gr.HTML( + '
' + '
Episode Structure
' ) + boundary_display_html = gr.HTML() + gr.HTML('
') gr.Markdown( - '' - 'AI proposal hidden by default — code independently first ' - '(Settles 2012)' + "**Review boundaries above.** Edit the turn IDs below " + "to adjust, add, or remove boundaries. " + "Leave empty for a single undivided episode." ) with gr.Row(): - prev_btn = gr.Button("← Previous", size="sm") - next_btn = gr.Button("Next →", variant="primary", size="sm") - next_section_btn = gr.Button( - "→ Finish Section & Continue", variant="secondary", visible=False - ) + boundary_ids_box = gr.Textbox( + label="Boundary turn IDs (comma-separated) — the turn after which each new episode begins", + placeholder="e.g. 12, 28, 35", + lines=1, scale=3, + ) + confirm_boundaries_btn = gr.Button( + "Confirm & Code (Agent 1b) →", + variant="primary", scale=1, + ) + code_status = gr.Markdown() + + # 3c: Coding interface + with gr.Column(visible=False) as col_coding: + coding_progress_comp = gr.HTML() + segment_jump = gr.Dropdown( + label="Jump to segment", choices=[], value=None, interactive=True + ) + with gr.Row(equal_height=False): + # Left: transcript + with gr.Column(scale=3): + uncertainty_comp = gr.HTML() + turns_html_comp = gr.HTML( + label="Transcript", show_label=True + ) + proposal_comp = gr.Markdown(visible=False) + reveal_btn = gr.Button( + "Reveal AI proposal", variant="secondary", size="sm" + ) + gr.HTML( + '

' + 'AI proposal hidden by default — code independently first ' + '(Settles 2012 — uncertainty sampling)

' + ) + + # Right: coding controls + with gr.Column(scale=2): + gr.Markdown("#### Your Coding") + dim_radio = gr.Radio( + choices=DIM_CHOICES, label="Dimension", value=None + ) + dim_desc_comp = gr.HTML() + comment_box = gr.Textbox( + label="Comment (optional)", lines=2, + placeholder="Note any ambiguity for the disagreement review…" + ) + with gr.Row(): + prev_btn = gr.Button("← Previous", size="sm") + next_btn = gr.Button("Next →", variant="primary", size="sm") + + next_section_btn = gr.Button( + "→ Finish Section & Continue", variant="secondary", visible=False + ) - # Stage 4: Complete - with gr.Column(visible=False) as col_complete: - gr.HTML( - '' - ) - download_btn = gr.Button("Download Coding File", variant="primary") - download_file = gr.File(visible=False) + # Step 4: Complete + with gr.Column(visible=False) as col_complete: + gr.HTML( + '
' + '

All sections coded ✓

' + '

Download your coding file and share it ' + 'with your co-researcher. They should complete the same pipeline ' + 'independently, then both files go to the ' + 'Inter-Rater Agreement tab.

' + '
' + ) + download_btn = gr.Button("Download My Coding File", variant="primary") + download_file = gr.File(visible=False) + + # ── Info sidebar (1/5) ──────────────────────────────────── + with gr.Column(scale=1, min_width=200): + with gr.Accordion("Research Basis", open=True): + pipeline_info = gr.HTML(RESEARCH_INFO["parse"]) + + with gr.Accordion("Agent Activity Log", open=True): + gr.Markdown( + '' + f'Model: {MODEL_ID.split("/")[-1]} · ' + f'Temperature: {TEMPERATURE}' + ) + sidebar_log = gr.HTML(_agent_log_html([])) # ================================================================== - # TAB 2: Agreement & Kappa + # TAB 2 — Inter-Rater Agreement # ================================================================== - with gr.Tab("Agreement & Kappa"): - gr.Markdown( - "## Inter-Rater Agreement\n" - "Upload your co-researcher's completed `coding_RX.json`. " - "The system calculates Cohen's κ — gate is **κ ≥ 0.70** " - "*(Landis & Koch 1977; Bujang & Baharum 2017)*." - ) - with gr.Row(): - r2_upload = gr.File( - label="Co-researcher coding (.json)", file_types=[".json"], scale=2 - ) - kappa_btn = gr.Button("Calculate Kappa", variant="primary", scale=1) - - kappa_html_comp = gr.HTML() - disagreements_md = gr.Markdown() - - with gr.Column(visible=False) as col_disagreements: - gr.HTML('') - 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="Resolution note — explain why this dimension was chosen", - lines=2, placeholder="Both researchers agreed after discussion that…" - ) - with gr.Row(): - resolve_btn = gr.Button("Resolve", variant="primary") - discard_btn = gr.Button("Discard segment", variant="secondary") - dis_status = gr.Markdown() + with gr.Tab("Inter-Rater Agreement"): + with gr.Row(equal_height=False): + with gr.Column(scale=4): + + # How it works + gr.HTML( + '
' + '

How dual-coding works

' + '
    ' + '
  1. You complete the Pipeline tab → download coding_R1.json
  2. ' + '
  3. Your co-researcher runs the same Pipeline independently on the same transcript → downloads coding_R2.json
  4. ' + '
  5. Both files are uploaded here to calculate Cohen\'s κ
  6. ' + '
  7. Gate: κ ≥ 0.70 to proceed *(Landis & Koch 1977)*
  8. ' + '
  9. Remaining disagreements are resolved below → feed Agent 2\'s learning
  10. ' + '
' + '
' + ) + + gr.Markdown("### Upload Co-Researcher Coding") + with gr.Row(): + r2_upload = gr.File( + label="Co-researcher coding file (.json)", file_types=[".json"], scale=2 + ) + kappa_btn = gr.Button("Calculate κ", 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, and add a ' + 'note explaining your decision. 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="Resolution note — why this dimension?", + lines=2, + placeholder="After discussion we agreed that… 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.Column(scale=1, min_width=200): + with gr.Accordion("Research Basis", open=True): + gr.HTML(RESEARCH_INFO["agreement"]) + with gr.Accordion("Agent Activity Log", open=False): + kappa_log = gr.HTML(_agent_log_html([])) # ================================================================== - # TAB 3: Rule Review + # TAB 3 — AI Learning Review # ================================================================== - with gr.Tab("Rule Review"): - gr.Markdown( - "## Agent 2 Rule Proposals\n" - "Rules proposed by Agent 2 from researcher corrections. " - "**Inactive until approved here.** " - "Once approved, they become part of Agent 1b's coding guidelines " - "and are versioned in Tier 2. *(Settles 2012 — active learning update loop)*" - ) - 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") - rule_selector = gr.Dropdown(label="Select rule", choices=[]) - rule_researcher_id = gr.Textbox( - label="Your Researcher ID", placeholder="e.g. R1" - ) - rule_note = gr.Textbox( - label="Approval note / Rejection reason", - lines=2, - placeholder="This rule is consistent with sessions 3 and 4…", - ) - 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.Tab("AI Learning Review"): + with gr.Row(equal_height=False): + with gr.Column(scale=4): + + gr.HTML( + '
' + '

How the learning loop works

' + '
    ' + '
  1. You and your co-researcher resolve disagreements in the Agreement tab
  2. ' + '
  3. Agent 2 analyses patterns across resolved disagreements
  4. ' + '
  5. Agent 2 proposes boundary clarifications, disambiguation rules, ' + 'or marker refinements
  6. ' + '
  7. You review and approve/reject each rule — rules are ' + 'inactive until approved
  8. ' + '
  9. Approved rules are added to Tier 2 and immediately affect ' + 'Agent 1b\'s coding in future sessions
  10. ' + '
' + '

' + '⚠ Agent 2 requires at least 3 validated sessions and 90 segments ' + 'before proposing rules *(Bujang & Baharum 2017 — power analysis)*.

' + '
' + ) + + 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( + "Select a rule, enter your ID, and provide a note. " + "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.Column(scale=1, min_width=200): + with gr.Accordion("Research Basis", open=True): + gr.HTML(RESEARCH_INFO["rules"]) + with gr.Accordion("What Agent 2 can write", open=False): + gr.Markdown( + "**Boundary clarification** — where episode boundaries fall \n" + "**Disambiguation rule** — how to distinguish two similar dimensions \n" + "**Marker refinement** — context-specific sharpening of a behavioral marker \n\n" + "Agent 2 **cannot** redefine a dimension's core meaning or contradict Tier 1." + ) # ===================================================================== # OUTPUT LISTS # ===================================================================== CODING_OUTPUTS = [ - coding_progress_html_comp, + coding_progress_comp, segment_jump, - turns_display_md, - uncertainty_html_comp, - proposal_md_comp, + turns_html_comp, + uncertainty_comp, + proposal_comp, dim_radio, - dim_desc_html_comp, + dim_desc_comp, comment_box, next_section_btn, ] - NEXT_SECTION_OUTPUTS = [ + NEXT_SECTION_OUTS = [ state, pipeline_html, sections_overview_html, @@ -1545,93 +1802,82 @@ with gr.Blocks(title="CollabCode", css=CSS, theme=gr.themes.Soft()) as demo: parse_btn.click( fn=fn_parse, inputs=[transcript_file, session_id_box, researcher_id_box, state], - outputs=[state, pipeline_html, parse_status, col_agent0], + outputs=[state, pipeline_html, parse_status, col_agent0, sidebar_log], ).then(fn=lambda: gr.update(visible=True), outputs=[parse_status]) + # Update info sidebar to sections step after parse + parse_btn.click( + fn=lambda: RESEARCH_INFO["parse"], + outputs=[pipeline_info], + ) + agent0_btn.click( fn=fn_run_agent0, inputs=[state], - outputs=[state, pipeline_html, col_sections, sections_display_md, sections_labels_box], - ) + outputs=[state, pipeline_html, col_sections, sections_display_md, + sections_labels_box, sidebar_log], + ).then(fn=lambda: RESEARCH_INFO["sections"], outputs=[pipeline_info]) confirm_sections_btn.click( fn=fn_confirm_sections, inputs=[sections_labels_box, state], - outputs=[ - state, pipeline_html, sections_overview_html, - section_header_md, col_section_work, - col_boundary_btn, col_boundary_review, col_coding, - ], - ) + outputs=[state, pipeline_html, sections_overview_html, + section_header_md, col_section_work, + col_boundary_btn, col_boundary_review, col_coding], + ).then(fn=lambda: RESEARCH_INFO["boundaries"], outputs=[pipeline_info]) propose_btn.click( fn=fn_propose_boundaries, inputs=[state], outputs=[state, boundary_status, col_boundary_review, - boundary_display_html, boundary_ids_box], + boundary_display_html, boundary_ids_box, sidebar_log], ) confirm_boundaries_btn.click( fn=fn_confirm_and_code, inputs=[boundary_ids_box, state], - outputs=[state, code_status, col_coding] + CODING_OUTPUTS, - ) + outputs=[state, code_status, col_coding] + CODING_OUTPUTS + [sidebar_log], + ).then(fn=lambda: RESEARCH_INFO["coding"], outputs=[pipeline_info]) next_btn.click( fn=lambda d, c, s: fn_navigate(+1, d, c, s), inputs=[dim_radio, comment_box, state], outputs=[state] + CODING_OUTPUTS, ) - prev_btn.click( fn=lambda d, c, s: fn_navigate(-1, d, c, s), inputs=[dim_radio, comment_box, state], outputs=[state] + CODING_OUTPUTS, ) - segment_jump.change( - fn=fn_jump_to_segment, + fn=fn_jump, inputs=[segment_jump, state], outputs=[state] + CODING_OUTPUTS, ) - - reveal_btn.click( - fn=fn_reveal_proposal, - inputs=[state], - outputs=[proposal_md_comp], - ) - - dim_radio.change( - fn=fn_update_dim_desc, - inputs=[dim_radio], - outputs=[dim_desc_html_comp], - ) + reveal_btn.click(fn=fn_reveal, inputs=[state], outputs=[proposal_comp]) + dim_radio.change(fn=fn_dim_desc, inputs=[dim_radio], outputs=[dim_desc_comp]) next_section_btn.click( fn=fn_next_section, inputs=[dim_radio, comment_box, state], - outputs=NEXT_SECTION_OUTPUTS, + outputs=NEXT_SECTION_OUTS, ) - download_btn.click( - fn=fn_download, - inputs=[state], - outputs=[download_file], - ).then(fn=lambda: gr.update(visible=True), outputs=[download_file]) + download_btn.click(fn=fn_download, inputs=[state], outputs=[download_file]).then( + fn=lambda: gr.update(visible=True), outputs=[download_file] + ) # Agreement tab kappa_btn.click( fn=fn_calculate_kappa, inputs=[r2_upload, state], - outputs=[state, kappa_html_comp, disagreements_md, col_disagreements], + outputs=[state, kappa_html_comp, disagreements_md, col_disagreements, kappa_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], @@ -1639,21 +1885,12 @@ with gr.Blocks(title="CollabCode", css=CSS, theme=gr.themes.Soft()) as demo: ) # Rule review tab - load_rules_btn.click( - fn=fn_load_rules, - outputs=[rules_html_comp, rule_selector], - ) - + load_rules_btn.click(fn=fn_load_rules, outputs=[rules_html_comp, rule_selector]) approve_rule_btn.click( - fn=fn_approve_rule, - inputs=[rule_selector, rule_researcher_id, rule_note], - outputs=[rule_status], + fn=fn_approve, inputs=[rule_selector, rule_rid, rule_note], outputs=[rule_status] ) - reject_rule_btn.click( - fn=fn_reject_rule, - inputs=[rule_selector, rule_researcher_id, rule_note], - outputs=[rule_status], + fn=fn_reject, inputs=[rule_selector, rule_rid, rule_note], outputs=[rule_status] )