diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -1,15 +1,8 @@ """ -app.py (v3) — CollabCode Researcher Interface +app.py (v4) — 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). +Page-based flow: Welcome → Setup → Sections → Pipeline → Done → Agreement → Library +No tabs. One task per screen. """ from __future__ import annotations @@ -55,10 +48,6 @@ _STYLES_DIR = Path(__file__).parent / "static" / "styles" MODEL_ID = "Qwen/Qwen2.5-72B-Instruct" TEMPERATURE = 0.1 -# --------------------------------------------------------------------------- -# Startup diagnostics — printed once to the server log so the research team -# can quickly verify the environment is configured correctly. -# --------------------------------------------------------------------------- import sys as _sys, importlib.metadata as _meta def _startup_log() -> None: @@ -69,7 +58,7 @@ def _startup_log() -> None: hf_ver = "unknown" hf_tok = "SET" if __import__("os").environ.get("HF_TOKEN") else "MISSING ⚠" print("=" * 60) - print(" CollabCode — startup") + print(" CollabCode v4 — startup") print("=" * 60) print(f" Python : {_sys.version.split()[0]}") print(f" Gradio : {_gr.__version__}") @@ -77,30 +66,12 @@ def _startup_log() -> None: print(f" HF_TOKEN : {hf_tok}") print(f" Sessions root: {SESSIONS_ROOT.resolve()}") print(f" Model : {MODEL_ID}") - print(f" Temperature : {TEMPERATURE}") print("=" * 60) _startup_log() -# --------------------------------------------------------------------------- -# CSS loading -# -# Priority order: -# 1. Dart Sass CLI (`sass` command) — full @use/@forward support -# 2. Pre-compiled static/styles/main.css (committed artifact) -# 3. Inline fallback — covers the most critical Gradio overrides -# -# The SCSS design system uses Dart Sass @use syntax (requires Dart Sass ≥ 1.23). -# libsass does not support @use. Install Dart Sass: -# npm install -g sass # Node.js -# brew install sass/sass/sass # macOS -# choco install sass # Windows -# Then run: python static/build.py -# --------------------------------------------------------------------------- - def _load_css() -> str: - # 1. Try Dart Sass CLI scss_entry = _STYLES_DIR / "main.scss" if scss_entry.exists(): try: @@ -113,21 +84,13 @@ def _load_css() -> str: if result.returncode == 0 and result.stdout: css = result.stdout (_STYLES_DIR / "main.css").write_text(css, encoding="utf-8") - print("[CollabCode] SCSS compiled via Dart Sass CLI.") return css except (FileNotFoundError, subprocess.TimeoutExpired): - pass # sass CLI not available - - # 2. Pre-compiled CSS + pass compiled = _STYLES_DIR / "main.css" if compiled.exists(): - print("[CollabCode] Using pre-compiled main.css.") return compiled.read_text(encoding="utf-8") - - # 3. Inline fallback — no external dependency required - print("[CollabCode] No compiled CSS found. Using inline fallback. " - "Install Dart Sass and run `python static/build.py` for full styling.") - return "" # EXTRA_CSS below covers essential Gradio overrides + return "" # --------------------------------------------------------------------------- @@ -162,30 +125,26 @@ 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} -# Secondary dimension choices — "None" is explicit and default SEC_NONE = "None — single dimension only" SEC_DIM_CHOICES = [SEC_NONE] + DIM_CHOICES SEC_ID_FROM_CHOICE = {SEC_NONE: None, **DIM_ID_FROM_CHOICE} # --------------------------------------------------------------------------- -# Speaker palette — 6 perceptually distinct colours (deuteranopia-safe pair -# tested via Coblis simulator). Each entry: text colour, light bg, initials bg. +# Speaker palette # --------------------------------------------------------------------------- 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 + ("#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: - """Map speaker name → palette entry dict.""" seen: dict[str, dict] = {} for t in turns: sp = t.get("speaker", "?") @@ -200,7 +159,7 @@ def _assign_speakers(turns: list[dict]) -> dict: def _speaker_avatar(name: str, entry: dict) -> str: initials = "".join(w[0] for w in name.split()[:2]).upper() or "?" return ( - f' str: 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.

' @@ -230,10 +188,8 @@ def _format_turns_html(seg: dict, speaker_map: dict) -> str: f'
' f'' f'{_h(sp)}' - f'' - f'{ts}' - f'' - f'#{turn_id}' + f'{ts}' + f'#{turn_id}' f'
' f'
{text}
' f'' @@ -241,260 +197,10 @@ def _format_turns_html(seg: dict, speaker_map: dict) -> str: 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.

-
""", -} - - -# --------------------------------------------------------------------------- -# Agent activity log -# --------------------------------------------------------------------------- - -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' - 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: - stages = [ - ("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 - - parts = [ - '
', - 'PIPELINE', - ] - for i, (_, label) in enumerate(stages): - if i < cur: - bg, col, fw = "#ecfdf5", "#065f46", "600" - prefix = "✓ " - elif i == cur: - bg, col, fw = "#eef2ff", "#4338ca", "700" - prefix = "▶ " - else: - bg, col, fw = "transparent", "#94a3b8", "400" - prefix = "" - parts.append( - f'{prefix}{label}' - ) - parts.append('
') - return "".join(parts) - - def _section_cards_html(sections: list[dict], stages: dict, current_idx: int) -> str: if not sections: return "" @@ -504,7 +210,7 @@ def _section_cards_html(sections: list[dict], stages: dict, current_idx: int) -> if stage == "done": bc, fc, icon = "#86efac", "#065f46", "✓" elif i == current_idx: - bc, fc, icon = "#93c5fd", "#1d4ed8", "◑" + bc, fc, icon = "#93c5fd", "#1d4ed8", "▶" else: bc, fc, icon = "#e2e8f0", "#94a3b8", "○" n = s["end_turn_id"] - s["start_turn_id"] + 1 @@ -533,12 +239,9 @@ def _episode_table_html(turns: list[dict], boundaries: list[dict]) -> str: rows = ( "" - "Episode" - "Turns" - "Count" + "Episode" + "Turns" + "Count" "" ) for i, start in enumerate(cuts): @@ -554,12 +257,10 @@ def _episode_table_html(turns: list[dict], boundaries: list[dict]) -> str: 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") + 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'' + f'⚠' f'
AI flagged uncertain' f' — {note}
' f'' @@ -610,61 +311,37 @@ def _dim_desc_html(choice: str) -> str: f'color:#1e40af;margin-top:6px">{_h(desc)}' ) -def _status_card( - title: str, - status: str = "success", # "success", "error", "warning", "processing" - details: dict | None = None, - processing_time_sec: float | None = None, - error_msg: str | None = None, -) -> str: - """ - Create a visual status card for process feedback. - Replaces pop-ups with inline, contextual reporting. - - status: success/error/warning/processing - details: dict of key-value pairs to display - processing_time_sec: if provided, show "X.Xs processing" - error_msg: if provided, show error details - """ + +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", "❌"), + "error": ("#fef2f2", "#991b1b", "#fca5a5", "✗"), "warning": ("#fffbeb", "#78350f", "#fbbf24", "⚠"), "processing": ("#eff6ff", "#1e40af", "#93c5fd", "⏳"), } - bg, title_color, border_color, icon = colors.get(status, colors["success"]) - + bg, tc, bc, icon = colors.get(status, colors["success"]) detail_html = "" if details: - detail_html = ( - f'
' - ) + detail_html = '
' for k, v in details.items(): - detail_html += f'
{_h(k)}: {_h(str(v))}
' + detail_html += ( + f'
{_h(k)}: ' + f'{_h(str(v))}
' + ) detail_html += '
' - - time_html = ( - f'
' - f'⏱ {processing_time_sec:.1f}s processing time
' - if processing_time_sec is not None else "" - ) - error_html = ( f'
{_h(error_msg)}
' + f'font-family:monospace;font-size:0.78em;margin-top:8px;' + f'white-space:pre-wrap;word-break:break-all">{_h(error_msg)}
' if error_msg else "" ) - return ( - f'
' - f'
' + f'
' + f'
' f'{icon} {_h(title)}
' - f'{detail_html}' - f'{time_html}' - f'{error_html}' + f'{detail_html}{error_html}' f'
' ) @@ -690,14 +367,6 @@ def _speaker_legend_html(speaker_map: dict) -> str: def _kappa_html(report: dict) -> str: - """ - Render the full reliability report card. - - Shows Gwet's AC1 as primary (gate metric) and Cohen's κ as secondary - reference. Flags the divergence when prevalence bias is making κ - misleadingly low (Byrt, Bishop & Carlin 1993). - """ - # Primary: AC1 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]) @@ -705,23 +374,18 @@ def _kappa_html(report: dict) -> str: col = "#065f46" if gate else "#be123c" icon = "✓" if gate else "✗" pct = int(min(max(ac1, 0) * 100, 100)) - - # Secondary: κ 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", [])) - n_segs = report.get("n_segments_total", 0) - n_dis = len(report.get("segments_in_disagreement", [])) - - # Confidence interval text ci_text = "" if ac1_ci[0] is not None: ci_text = f' 95% CI [{ac1_ci[0]:.3f}, {ac1_ci[1]:.3f}]' - # Prevalence warning banner prev_banner = "" if prev_warn: dominant = max( @@ -732,37 +396,29 @@ def _kappa_html(report: dict) -> str: f'
' f'⚠ Prevalence bias detected: {_h(dominant[0])} accounts for ' - f'{dominant[1]:.0%} of codings. Cohen\'s κ is artificially depressed — ' - f'AC1 is the appropriate metric here. ' - f'(Byrt, Bishop & Carlin 1993)' - f'
' + f'{dominant[1]:.0%} of codings. AC1 is the appropriate metric here.
' ) - # κ vs AC1 divergence note - div_note = "" + kc = "#065f46" if kappa >= 0.70 else "#be123c" if div_flag: - kc = "#065f46" if kappa >= 0.70 else "#be123c" 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}' - f' (prevalence bias in κ)' + f' · |AC1 − κ| = {divergence:.3f} (prevalence bias)' f'
' ) else: - kc = "#065f46" if kappa >= 0.70 else "#be123c" 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 only — Gwet 2008 primary)
' + f' (reference — Gwet 2008 primary)
' ) - # Per-dimension AC1 rows (primary) — fall back to κ if new report not available - dim_src = report.get("ac1_per_dimension") or report.get("kappa_per_dimension") or {} + 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 = "" + 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: @@ -776,10 +432,6 @@ def _kappa_html(report: dict) -> str: continue vp = int(min(max(v, 0) * 100, 100)) vc = "#065f46" if v >= 0.70 else "#b45309" if v >= 0.50 else "#be123c" - gate_pip = ( - f'' - f'{"✓" if v >= 0.70 else "·"}' - ) dim_rows += ( f'
' @@ -788,38 +440,30 @@ def _kappa_html(report: dict) -> str: f'
' f'' f'{v:.3f}' - f'{gate_pip}' f'' ) return ( f'
' f'{prev_banner}' - # Primary score f'
' f'{ac1:.3f}' f'
' f'
{icon} {_h(ac1_interp)}
' - f'
' - f'Gwet\'s AC1 · gate ≥ 0.70 · Gwet (2008); Landis & Koch (1977)' - f'
' + f'
Gwet\'s AC1 · gate ≥ 0.70
' f'
' f'{ci_text}' - # Progress bar with 0.70 threshold marker f'
' f'
' f'
' f'
0.70
' f'
' - # Counts + secondary metric f'
' - f'{n_segs} segments · {n_dis} disagreement{"s" if n_dis!=1 else ""}' - f'
' + f'{n_segs} segments · {n_dis} disagreement{"s" if n_dis!=1 else ""}
' f'{div_note}' - # Per-dimension f'
Per-Dimension {dim_label} (one-vs-rest)
' + f'letter-spacing:0.07em;color:#94a3b8;margin:14px 0 6px">Per-Dimension {dim_label}' f'{dim_rows}' f'' ) @@ -849,28 +493,70 @@ def _rules_html(rules: list[dict]) -> str: cards.append( f'
' - f'
' + f'
' f'
' f'{label}' - f'' - f'{rid} · {created}' + f'padding:2px 10px;font-size:0.72em;font-weight:700;text-transform:uppercase">{label}' + f'{rid} · {created}' f'
' f'dims: {dims}' f'
' f'

{desc}

' - f'

' - f'Evidence: {rat}

' - f'
' - f'Confidence: {conf}' - + (f'Note: {note}' if note else '') + + f'

Evidence: {rat}

' + f'
' + f'Confidence: {conf}' + + (f' · Note: {note}' if note else '') + f'
' ) return "".join(cards) +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) @@ -884,16 +570,29 @@ def _coding_progress_html(state: dict) -> str: 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'Section {idx+1}/{len(sections)} — ' - f'{_h(sec.get("label",""))} · Episode {ep_num}/{total}' + 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} coded ({pct}%)
' + f'
' + f'{coded}/{total} episodes coded this section' + f'{all_coded}/{all_segs} total' + f'
' f'
' ) @@ -907,7 +606,7 @@ def _empty_state() -> dict: "session_id": "", "researcher_id": "", "turns": [], - "speakers": {}, # name → palette entry + "speakers": {}, "sections": [], "section_idx": 0, "section_stages": {}, @@ -918,7 +617,7 @@ def _empty_state() -> dict: "codings": {}, "stage": "upload", "kappa_report": None, - "agent_logs": [], # list of log entry dicts + "agent_logs": [], } @@ -972,14 +671,14 @@ def _push_log(state: dict, entry: dict) -> dict: # =========================================================================== 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 "" + 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}" @@ -988,14 +687,9 @@ def _proposal_md(seg: dict) -> str: rat = seg.get("rationale", "") sec_did = seg.get("secondary_dimension_id") sec_rat = seg.get("secondary_rationale", "") - - lines = [f"> **AI primary: {did}** \n> {rat}"] + lines = [f"> **AI primary: {did}** \n> {rat}"] if sec_did: - lines.append( - f"> **AI secondary: {sec_did}** \n" - f"> _{sec_rat or 'co-occurring dimension'}_" - ) - + lines.append(f"> **AI secondary: {sec_did}** \n> _{sec_rat or 'co-occurring dimension'}_") tags = [] if seg.get("confident"): tags.append("✅ Confident") @@ -1003,21 +697,20 @@ def _proposal_md(seg: dict) -> str: 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 progress html - gr.update(choices=[], value=None), # 1 segment_jump - "", # 2 turns_display_html - "", # 3 uncertainty_html - gr.update(value="", visible=False), # 4 proposal_md - gr.update(choices=DIM_CHOICES, value=None), # 5 dim_radio - "", # 6 dim_desc_html - 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=[], value=None), + "", + "", + gr.update(value="", visible=False), + gr.update(choices=DIM_CHOICES, value=None), + "", + gr.update(choices=SEC_DIM_CHOICES, value=SEC_NONE), + "", + gr.update(visible=False), ) @@ -1036,8 +729,8 @@ def _render_coding(state: dict) -> tuple: 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 = ( + 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 ) @@ -1061,13 +754,25 @@ def _render_coding(state: dict) -> tuple: ) +# =========================================================================== +# PAGE NAVIGATION HELPER +# =========================================================================== + +_PAGE_NAMES = ["welcome", "setup", "sections", "pipeline", "done", "agreement", "library"] + +def _show(page: str) -> list: + """Return 7 gr.update(visible=...) items, one per page.""" + return [gr.update(visible=(p == page)) for p in _PAGE_NAMES] + + # =========================================================================== # CALLBACKS # =========================================================================== -# ── Stage 1: Parse ─────────────────────────────────────────────────────────── +# ── Process: Parse + Agent 0 combined ──────────────────────────────────────── -def fn_parse(file_obj, session_id: str, researcher_id: str, state: dict): +def fn_process(file_obj, session_id: str, researcher_id: str, state: dict): + """Generator: parse transcript then run Agent 0. Navigates to sections page.""" if file_obj is None: raise gr.Error("Upload a transcript file first.") if not session_id.strip(): @@ -1075,6 +780,18 @@ def fn_parse(file_obj, session_id: str, researcher_id: str, state: dict): if not researcher_id.strip(): raise gr.Error("Enter your Researcher ID (e.g. R1).") + def _setup_yield(msg, status="processing", details=None): + return ( + state, + _status_card(msg, status, details), + *_show("setup"), + "", # sections_display_md + "", # sections_labels_box + _agent_log_html(state.get("agent_logs", [])), + ) + + yield _setup_yield("Parsing transcript…") + t0 = time.perf_counter() try: turns = parse_transcript(file_obj.name) @@ -1099,7 +816,7 @@ def fn_parse(file_obj, session_id: str, researcher_id: str, state: dict): log_entry = _make_log_entry( "Transcript Parser", rt, turns=len(turns), speakers=len(speakers), - system_prompt_preview="(no LLM call — rule-based parser)", + system_prompt_preview="(rule-based parser — no LLM call)", ) new_state = _push_log(new_state, log_entry) @@ -1108,75 +825,57 @@ def fn_parse(file_obj, session_id: str, researcher_id: str, state: dict): (d / "parsed_turns.json").write_text( json.dumps(turns, indent=2, ensure_ascii=False), encoding="utf-8" ) - duration = _seconds_to_hms(turns[-1]["start_seconds"] - turns[0]["start_seconds"]) - legend = _speaker_legend_html(speaker_map) - summary = ( - f"{legend}" - f"| | |\n|---|---|\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 from {len(speakers)} speaker(s).") - return ( + yield ( new_state, - _pipeline_html("parsed"), - summary, - gr.update(visible=True), # col_agent0 + _status_card( + f"Parsed {len(turns)} turns — detecting sections…", "processing", + {"Turns": len(turns), "Speakers": len(speakers), "Duration": duration}, + ), + *_show("setup"), + "", + "", _agent_log_html(new_state["agent_logs"]), ) - -# ── 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), "", "", "" - - t0 = time.perf_counter() + # Run Agent 0 try: - result = run_sectioning(turns=state["turns"], session_id=state["session_id"]) + result = run_sectioning(turns=new_state["turns"], session_id=new_state["session_id"]) except Exception as e: - raise gr.Error(f"Agent 0 failed: {e}") from e + raise gr.Error(f"Section detection 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.") + raise gr.Error("Agent 0 returned no sections — try again.") from agent0_sectioner import build_system_prompt, load_dimension_labels - sys_prev = build_system_prompt(load_dimension_labels())[:120] - user_prev = f"Segment {len(state['turns'])} turns into topical sections." + sys_prev = build_system_prompt(load_dimension_labels())[:120] - state = dict(state) - state["sections"] = sections - state["section_stages"] = {s["section_id"]: "pending" for s in sections} - state["stage"] = "sectioned" - state["_agent0_overview"] = result.get("session_overview", "") # passed to Agent 1a context chain - log = _make_log_entry( - "Agent 0 — Structural Segmenter", rt, + new_state = dict(new_state) + new_state.update({ + "sections": sections, + "section_stages": {s["section_id"]: "pending" for s in sections}, + "stage": "sectioned", + "_agent0_overview": result.get("session_overview", ""), + }) + log2 = _make_log_entry( + "Agent 0 — Structural Segmenter", round(time.perf_counter() - t0, 1), sections_proposed=len(sections), warnings=len(result.get("warnings", [])), system_prompt_preview=sys_prev, - user_prompt_preview=user_prev, ) - state = _push_log(state, log) + new_state = _push_log(new_state, log2) - 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( - f"| {s['section_id']} | {s['label']} | " + f"| {s['section_id']} | **{s['label']}** | " f"{s['start_turn_id']}–{s['end_turn_id']} | " f"{s['start_time']}–{s['end_time']} |" for s in sections @@ -1186,103 +885,92 @@ def fn_run_agent0(state: dict): labels_txt = "\n".join(s["label"] for s in sections) if result.get("warnings"): - gr.Warning("Coverage warnings detected — check the section table.") - gr.Info(f"{len(sections)} sections detected in {rt}s.") + gr.Warning("Coverage warnings — check the section table.") + gr.Info(f"Ready: {len(turns)} turns · {len(sections)} sections detected.") yield ( - state, - _pipeline_html("sectioned"), - gr.update(visible=True), + new_state, + _status_card( + "Transcript processed — review sections below.", "success", + {"Turns": len(turns), "Speakers": len(speakers), + "Sections": len(sections), "Duration": duration}, + ), + *_show("sections"), # ← navigate to sections page sections_md, labels_txt, - _agent_log_html(state["agent_logs"]), + _agent_log_html(new_state["agent_logs"]), ) -# ── Stage 2b: Confirm sections ──────────────────────────���───────────────────── +# ── 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.") + raise gr.Error("No sections to confirm — process a transcript first.") 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)] if len(labels) != len(sections): - gr.Warning(f"Label count mismatch ({len(labels)} vs {len(sections)}).") + gr.Warning(f"Label count mismatch ({len(labels)} vs {len(sections)}) — using AI labels for extras.") - state = dict(state) - state.update({ - "sections": confirmed, - "section_idx": 0, - "section_stages": {s["section_id"]: "pending" for s in confirmed}, - "section_a1a_results":{}, # section_id → Agent 1a result dict (pre-fetched) - "stage": "coding", + 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(state) + d = _session_dir(new_state) (d / "sections_confirmed.json").write_text( json.dumps(confirmed, indent=2, ensure_ascii=False), encoding="utf-8" ) - _persist(state) + _persist(new_state) - n = confirmed[0]["end_turn_id"] - confirmed[0]["start_turn_id"] + 1 - gr.Info( - f"{len(confirmed)} sections confirmed. " - f"Click 'Analyse All Boundaries' to run Agent 1a in parallel on all sections." - ) + gr.Info(f"{len(confirmed)} sections confirmed. Detect episode boundaries next.") + + # Navigate to pipeline page; reset subcolumn visibility for clean state return ( - state, - _pipeline_html("coding"), - _section_cards_html(confirmed, state["section_stages"], 0), - gr.update(visible=True), # col_section_work + new_state, + *_show("pipeline"), + _section_cards_html(confirmed, new_state["section_stages"], 0), gr.update(visible=True), # col_run_all_boundaries gr.update(visible=False), # col_boundary_review gr.update(visible=False), # col_coding - "", # parallel_status_html ) -# ── Stage 3a: Agent 1a — PARALLEL for all sections ─────────────────────────── +# ── Agent 1a — parallel boundary detection ─────────────────────────────────── def fn_run_all_boundaries(state: dict): - """ - Generator: run Agent 1a on ALL confirmed sections in parallel. - - Yields one progress update per section as it completes (Dean & Ghemawat 2004 - map-reduce pattern; Nielsen 1994 — feedback within 10s). - Final yield shows the complete stats table and transitions to per-section review. - """ sections = state.get("sections", []) if not sections: raise gr.Error("Confirm sections first.") if not state.get("turns"): - raise gr.Error("No parsed turns found. Parse the transcript first.") + raise gr.Error("No parsed turns — parse the transcript first.") - n = len(sections) - session_overview = state.get("_agent0_overview", "") - collected_results = {} + n = len(sections) + session_overview = state.get("_agent0_overview", "") + collected = {} pipeline_stats_html = "" - # Initial streaming update + # Initial yield yield ( state, - f"⏳ Running Agent 1a in parallel on {n} section(s) (max {min(n, 3)} concurrent workers)…", + f"⏳ Running Agent 1a on {n} section(s) (max 3 concurrent)…", "", - gr.update(visible=False, value=""), - gr.update(visible=False, value=""), + gr.update(visible=False), # col_boundary_review + gr.update(visible=False, value=""), # boundary_display_html + gr.update(visible=False, value=""), # boundary_ids_box "", _agent_log_html(state.get("agent_logs", [])), ) - # Initialise pstats before the loop so references after the try block are - # always safe even if run_boundaries_parallel raises before its first yield. - pstats = PipelineStats( - agent_name="Agent 1a — Boundary Detector", - n_sections=n, - ) + pstats = PipelineStats(agent_name="Agent 1a — Boundary Detector", n_sections=n) try: for sr, pstats in run_boundaries_parallel( @@ -1292,16 +980,15 @@ def fn_run_all_boundaries(state: dict): session_overview=session_overview, ): if sr.success: - collected_results[sr.section_id] = sr.result + collected[sr.section_id] = sr.result else: gr.Warning(f"Section {sr.section_id} failed: {sr.error}") - # Build live progress table processed = len(pstats.results) prog_lines = [] for s in sections: sid = s["section_id"] - res = collected_results.get(sid) + res = collected.get(sid) failed = any((not x.success) and x.section_id == sid for x in pstats.results) if res: b = len(res.get("boundaries", [])) @@ -1319,6 +1006,7 @@ def fn_run_all_boundaries(state: dict): state, status_md, pipeline_stats_html, + gr.update(visible=False), gr.update(visible=False, value=""), gr.update(visible=False, value=""), "", @@ -1330,12 +1018,12 @@ def fn_run_all_boundaries(state: dict): # All done — update state state = dict(state) - n_success = len(collected_results) + n_success = len(collected) n_error = n - n_success for sec in sections: sid = sec["section_id"] - result = collected_results.get(sid) + result = collected.get(sid) if result: state["section_boundaries"][sid] = result["boundaries"] state["section_segments"][sid] = result["segments"] @@ -1344,10 +1032,6 @@ def fn_run_all_boundaries(state: dict): else: state["section_stages"][sid] = "error" - # Log to agent activity - total_rt = sum( - (r.wall_time_s for r in pstats.results if r.success), 0.0 - ) log = _make_log_entry( "Agent 1a — Boundary Detector (parallel)", round(pstats.parallel_wall_s, 1), sections_ok=n_success, sections_error=n_error, @@ -1357,22 +1041,19 @@ def fn_run_all_boundaries(state: dict): state = _push_log(state, log) _persist(state) - # Transition: show section-by-section boundary review for section 0 sec = sections[0] turns = _turns_for_section(state["turns"], sec) - result = collected_results.get(sec["section_id"], {}) + 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"✓ All {n_success} sections analysed " - f"({pstats.parallel_wall_s:.0f}s parallel vs ~{pstats.sequential_est_s:.0f}s serial — " - f"{pstats.speedup:.1f}× speedup).\n\n" - f"Now review section boundaries one by one and confirm before coding begins." + 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 — their boundaries need manual entry." + 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.") @@ -1380,15 +1061,15 @@ def fn_run_all_boundaries(state: dict): state, status_final, pipeline_stats_html, - gr.update(visible=True, - value=_episode_table_html(turns, bounds)), # boundary_display_html - gr.update(visible=True, value=ids_txt), # boundary_ids_box + gr.update(visible=True), # col_boundary_review ← now visible + 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"]), ) -# ── Stage 3b: Confirm boundaries + run Agent 1b ─────────────────────────────── +# ── Confirm boundaries + run Agent 1b ──────────────────────────────────────── def fn_confirm_and_code(boundary_ids_text: str, state: dict): sec = _current_section(state) @@ -1427,7 +1108,6 @@ def fn_confirm_and_code(boundary_ids_text: str, state: dict): yield state, f"⏳ Agent 1b coding {len(segments)} episode(s)…", gr.update(visible=False), *CODING_EMPTY, "" - # Pass Agent 1a's result as context for Agent 1b (context chain) agent1a_result = state.get("section_a1a_results", {}).get(sec["section_id"]) t0 = time.perf_counter() try: @@ -1439,10 +1119,7 @@ def fn_confirm_and_code(boundary_ids_text: str, state: dict): except Exception as e: raise gr.Error(f"Agent 1b failed: {e}") from e - rt = round(time.perf_counter() - t0, 1) - sys_prev = f"Context chain: section={sec['label']}, boundary_ctx={'yes' if agent1a_result else 'no'}" - user_prev = f"Code {len(segments)} segments in section: {sec['label']}" - + 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" @@ -1451,8 +1128,8 @@ def fn_confirm_and_code(boundary_ids_text: str, state: dict): "Agent 1b — Dimension Coder", rt, segments_coded=len(coded), uncertain_flagged=n_uncertain, - system_prompt_preview=sys_prev, - user_prompt_preview=user_prev, + system_prompt_preview=f"Context chain: section={sec['label']}", + user_prompt_preview=f"Code {len(segments)} segments", ) state = _push_log(state, log) @@ -1461,9 +1138,9 @@ def fn_confirm_and_code(boundary_ids_text: str, state: dict): json.dumps(coded, indent=2, ensure_ascii=False), encoding="utf-8" ) - msg = f"✓ {len(coded)} segments coded in {rt}s." + msg = f"✓ {len(coded)} segments coded ({rt}s)." if n_uncertain: - msg += f" **{n_uncertain} flagged ⚠ uncertain** — review those first." + 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"]) @@ -1514,7 +1191,7 @@ def fn_dim_desc(choice: str): return _dim_desc_html(choice or "") -# ── Next section ────────────────────────────────────────────────────────────── +# ── Next section / finish ───────────────────────────────────────────────────── def fn_next_section(dim_choice: str, sec_choice: str, comment: str, state: dict): segs = _current_section_segments(state) @@ -1528,50 +1205,55 @@ def fn_next_section(dim_choice: str, sec_choice: str, comment: str, state: dict) "comment": comment.strip(), } - state = dict(state) - state["codings"] = codings - sections = state.get("sections", []) - sec_idx = state.get("section_idx", 0) + 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"] - state["section_stages"][cur_id] = "done" - + new_state["section_stages"][cur_id] = "done" next_idx = sec_idx + 1 + if next_idx >= len(sections): - state["stage"] = "complete" - _write_coding_file(state) - _persist(state) + # 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.") return ( - state, - _pipeline_html("complete"), - _section_cards_html(sections, state["section_stages"], sec_idx), + new_state, + *_show("done"), + _section_cards_html(sections, new_state["section_stages"], sec_idx), "", - gr.update(visible=False), - gr.update(visible=False), - gr.update(visible=False), - gr.update(visible=True), + gr.update(visible=False), # col_boundary_review + gr.update(visible=False), # col_coding ) - state["section_idx"] = next_idx - state["coding_idx"] = 0 - next_sec = sections[next_idx] + # More sections remain — stay on pipeline page, show next section's boundary review + 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(state) + _persist(new_state) + + # Load boundary review for next section + result = new_state.get("section_a1a_results", {}).get(next_sec["section_id"], {}) + bounds = result.get("boundaries", []) + turns = _turns_for_section(new_state["turns"], next_sec) + ids_txt = ", ".join(str(b["after_turn_id"]) for b in bounds) + gr.Info(f"Section {next_idx+1}: {next_sec['label']}") return ( - state, - _pipeline_html("coding"), - _section_cards_html(sections, state["section_stages"], next_idx), + new_state, + *_show("pipeline"), + _section_cards_html(sections, new_state["section_stages"], next_idx), hdr, - gr.update(visible=True), - gr.update(visible=False), - gr.update(visible=False), - gr.update(visible=False), + gr.update(visible=True), # col_boundary_review + gr.update(visible=False), # col_coding ) @@ -1628,7 +1310,7 @@ def fn_calculate_kappa(r2_file, state: dict): 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 tab first.") + 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.") @@ -1653,23 +1335,20 @@ def fn_calculate_kappa(r2_file, state: dict): 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, - ) + 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. Review and re-code.") + 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" + dis = report.get("segments_in_disagreement", []) + rows = "| Segment | R1 | R2 | Agent 1b |\n|---|---|---|---|\n" for di in dis[:20]: rows += ( f"| `{di['segment_id']}` " @@ -1691,31 +1370,14 @@ def fn_calculate_kappa(r2_file, state: dict): def fn_run_sequence_analysis(rater_choice: str, state: dict): - """ - Run sequential analysis on one rater's coding file. - - Sequential analysis (Bakeman & Gottman 1986; Bakeman & Quera 2011) - reveals temporal patterns invisible in frequency counts: - which dimension transitions occur more or less often than chance? - - Args: - rater_choice: "R1 (you)" or "R2 (co-researcher)" or "Both (merged)" - state: app state (used to locate the session folder) - """ if not state.get("session_id"): - raise gr.Error("No session loaded — complete the Pipeline tab first.") + raise gr.Error("No session loaded — complete the Pipeline first.") d = _session_dir(state) - try: - if "R2" in rater_choice: - path = d / "coding_R2.json" - else: - path = d / f"coding_{state['researcher_id']}.json" - + 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}. Download your coding first.") - + raise gr.Error(f"Coding file not found: {path.name}.") analysis = load_and_analyse(path, max_lag=3) except gr.Error: raise @@ -1725,57 +1387,49 @@ def fn_run_sequence_analysis(rater_choice: str, state: dict): 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", []) + 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", []) - # Summary markdown ent_note = ( f"**{entropy:.3f}** bits / max {ent_max:.3f} — " - + ("high entropy: transitions are distributed; no strong sequential pattern" + + ("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 the sequence") + 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) — residuals unreliable: " + 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 used: `{'`, `'.join(cats)}` \n" - f"Transition entropy: {ent_note} \n" + 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} \n\n" - f"*Adjusted residuals — Bakeman & Quera (2011). " - f"|z| > 1.96 = p < .05 · |z| > 2.58 = p < .01*" + f"{warn_md}" ) - matrix_html = render_transition_matrix_html(analysis) - sig_html = render_significant_transitions_html(analysis) - - gr.Info(f"Sequence analysis complete: {n_ep} episodes, {len(sig_pos)} significant transitions.") - return summary_md, matrix_html, sig_html, gr.update(visible=True) + 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): - """Download transition matrix as CSV for R/Python/SPSS.""" 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") + 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) @@ -1834,8 +1488,8 @@ def fn_approve(choice: str, researcher: str, note: str): 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." + 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): @@ -1852,742 +1506,771 @@ def fn_reject(choice: str, researcher: str, note: str): # =========================================================================== -# EXTRA CSS +# CSS # =========================================================================== EXTRA_CSS = """ .gradio-container { - max-width: 1240px !important; + 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; } -/* Global visual language */ :root { - --cc-bg: #ececee; - --cc-surface: #f6f6f7; - --cc-paper: #ffffff; - --cc-ink: #111217; - --cc-muted: #6b6f76; - --cc-border: #d8dade; - --cc-accent: #ff5a3d; + --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; } -.cc-app-header { - display: flex; - align-items: flex-end; - justify-content: space-between; - padding: 20px 0 12px; - border-bottom: 1px solid var(--cc-border); - margin-bottom: 14px; -} - -.cc-app-title { - margin: 0; - font-size: clamp(2rem, 4vw, 3.5rem); - line-height: 0.95; - letter-spacing: -0.05em; - font-weight: 900; - color: var(--cc-ink); -} - -.cc-app-subtitle { - margin: 8px 0 0; - font-size: 0.85rem; - color: var(--cc-muted); - max-width: 52ch; -} - -.cc-app-meta { - text-align: right; - font-size: 0.72rem; - color: var(--cc-muted); - text-transform: uppercase; - letter-spacing: 0.08em; -} - -/* Top nav / tabs */ -.tab-nav { - border-bottom: 1px solid var(--cc-border) !important; - margin-bottom: 12px !important; -} +:focus-visible { outline: 2px solid var(--cc-accent) !important; outline-offset: 2px; } +:focus { outline: none; } -.tab-nav button { +/* Primary button */ +.gradio-container button.primary { + background: var(--cc-accent) !important; + border-color: var(--cc-accent) !important; + color: #fff !important; font-weight: 700 !important; - font-size: 0.82rem !important; - text-transform: uppercase; - letter-spacing: 0.06em; - color: #4a4e56 !important; } - -.tab-nav button.selected { - color: var(--cc-ink) !important; - border-bottom-color: var(--cc-accent) !important; - border-bottom-width: 3px !important; +.gradio-container button.primary:hover { + background: var(--cc-accent-deep) !important; + border-color: var(--cc-accent-deep) !important; } - -/* Home dashboard */ -.cc-dashboard-intro { - background: linear-gradient(180deg, #f6f6f7 0%, #f1f1f3 100%); - border: 1px solid var(--cc-border); - border-radius: 14px; - padding: 18px 20px; - margin-bottom: 14px; +.gradio-container button.secondary, +.gradio-container button:not(.primary) { + border-color: #c9cdd3 !important; } -.cc-dashboard-intro h3 { - margin: 0 0 4px; - font-size: 1.35rem; - letter-spacing: -0.02em; +/* ── 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-dashboard-intro p { - margin: 0; +.cc-hero-sub { + font-size: 1rem; color: var(--cc-muted); - font-size: 0.92rem; + max-width: 44ch; + margin: 0 auto 48px; + line-height: 1.55; } - -.cc-workspace-card { - position: relative; +.cc-entry-card { background: var(--cc-paper); border: 1px solid var(--cc-border); - border-radius: 14px; - padding: 18px; - min-height: 196px; + border-radius: 16px; + padding: 24px; + min-height: 190px; + position: relative; overflow: hidden; } - -.cc-workspace-card::after { +.cc-entry-card::after { content: ""; position: absolute; - right: -28px; - bottom: -28px; - width: 112px; - height: 112px; + right: -24px; bottom: -24px; + width: 96px; height: 96px; border-radius: 999px; - background: rgba(255, 90, 61, 0.12); + background: rgba(255,90,61,0.1); } - -.cc-workspace-kicker { - display: inline-block; - font-size: 0.72rem; +.cc-entry-kicker { + font-size: 0.7rem; font-weight: 800; text-transform: uppercase; - letter-spacing: 0.08em; + letter-spacing: 0.1em; color: var(--cc-accent-deep); margin-bottom: 10px; + display: block; } - -.cc-workspace-title { - margin: 0 0 8px; +.cc-entry-title { font-size: 1.28rem; - line-height: 1.1; + font-weight: 800; letter-spacing: -0.025em; color: var(--cc-ink); - font-weight: 800; + margin: 0 0 8px; + line-height: 1.1; } - -.cc-workspace-copy { - margin: 0; +.cc-entry-desc { + font-size: 0.87rem; color: #434852; - font-size: 0.88rem; line-height: 1.55; - max-width: 34ch; + max-width: 32ch; } -/* Focus rings */ -:focus-visible { outline: 2px solid var(--cc-accent) !important; outline-offset: 2px; } -:focus { outline: none; } +/* ── 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; +} -/* Buttons */ -.gradio-container button.primary { - background: var(--cc-accent) !important; - border-color: var(--cc-accent) !important; - color: #fff !important; - font-weight: 700 !important; +/* ── Step indicator ── */ +.cc-steps { + display: flex; + gap: 6px; + align-items: center; + flex-wrap: wrap; + margin-bottom: 20px; } +.cc-step-done { color:#065f46;background:#f0fdf4;border:1px solid #86efac;border-radius:999px;padding:4px 12px;font-size:0.76rem;font-weight:700; } +.cc-step-active { color:#4338ca;background:#eef2ff;border:1px solid #818cf8;border-radius:999px;padding:4px 12px;font-size:0.76rem;font-weight:700; } +.cc-step-next { color:#94a3b8;background:transparent;border:1px solid #e2e8f0;border-radius:999px;padding:4px 12px;font-size:0.76rem;font-weight:500; } +.cc-step-sep { color:#d1d5db;font-size:0.7rem; } -.gradio-container button.primary:hover { - background: var(--cc-accent-deep) !important; - border-color: var(--cc-accent-deep) !important; +/* ── Setup page ── */ +.cc-setup-box { + background: var(--cc-paper); + border: 1px solid var(--cc-border); + border-radius: 12px; + padding: 24px; + margin-bottom: 16px; } -.gradio-container button.secondary, -.gradio-container button:not(.primary) { - border-color: #c9cdd3 !important; +/* ── Pipeline page ── */ +.cc-section-header { + background: #eff6ff; + border: 1px solid #93c5fd; + border-left: 4px solid #3b82f6; + border-radius: 0 8px 8px 0; + padding: 10px 16px; + margin: 12px 0; + font-size:0.92em; + color: #1e3a8a; } -/* Page progress strips */ -.cc-page-strip { - background: #f7f7f8; +/* ── Coding canvas ── */ +.cc-coding-transcript { + background: var(--cc-paper); border: 1px solid var(--cc-border); - border-left: 4px solid var(--cc-accent); border-radius: 10px; - padding: 10px 14px; - font-size: 0.84rem; - color: #2a2e34; + 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; } """ +CSS = _load_css() + EXTRA_CSS # =========================================================================== -# UI +# UI — page-based (no tabs) # =========================================================================== -CSS = _load_css() + EXTRA_CSS - -with gr.Blocks(title="CollabCode") as demo: +with gr.Blocks(css=CSS, title="CollabCode") as demo: state = gr.State(_empty_state()) - # ── App header ──────────────────────────────────────────────────────── - gr.HTML( - '
' - '
' - '

CollabCode

' - '

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

' - '
' - '
' - f'Model: {MODEL_ID.split("/")[-1]}' - f'
Temperature: {TEMPERATURE}' - '
' - '
' - ) + # ───────────────────────────────────────────────────────────────────── + # PAGE 0: Welcome + # ───────────────────────────────────────────────────────────────────── + with gr.Column(visible=True) as pg_welcome: + gr.HTML( + '
' + '

CollabCode

' + '

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

' + '
' + ) + with gr.Row(equal_height=True): + with gr.Column(scale=2): + gr.HTML( + '
' + 'Primary workflow' + '

Code a Transcript

' + '

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

' + '
' + ) + start_btn = gr.Button("Start Coding →", variant="primary", size="lg") - # ── Pipeline stepper (always visible) ──────────────────────────────── - pipeline_html = gr.HTML(_pipeline_html("upload")) + with gr.Column(scale=1): + gr.HTML( + '
' + 'After coding' + '

Check Agreement

' + '

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

' + '
' + ) + agreement_nav_btn = gr.Button("Open Agreement →") + + with gr.Column(scale=1): + gr.HTML( + '
' + 'Advanced' + '

Review AI Rules

' + '

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

' + '
' + ) + library_nav_btn = gr.Button("Open Library →") + + gr.HTML( + '
' + f'Model: {MODEL_ID.split("/")[-1]} · ' + f'Temperature: {TEMPERATURE} · ' + 'Framework: Meier, Spada & Rummel (2007)' + '
' + ) + + # ───────────────────────────────────────────────────────────────────── + # PAGE 1: Setup + # ───────────────────────────────────────────────────────────────────── + with gr.Column(visible=False) as pg_setup: + gr.HTML( + '
' + 'Step 1 of 4' + '

Session Setup

' + '
' + '
' + '1 Setup' + '›' + '2 Sections' + '›' + '3 Code' + '›' + '4 Done' + '
' + ) - # ── Quick help (modal-style guidance, collapsible) ─────────────────── - with gr.Accordion("Quick Help", open=False): gr.HTML( - '
' - 'Recommended flow: Home → Transcript Pipeline → Intercoder Agreement → AI Library Review.' - '
    ' - '
  • Use the page buttons at the top of each workspace for step-by-step navigation.
  • ' - '
  • Validation issues are shown inline in red boxes (no disruptive popups).
  • ' - '
  • Each completed operation returns a small processing report with timing.
  • ' - '
' + '
' + '

' + 'Both researchers should run the full pipeline independently on the ' + 'same transcript file. ' + 'Use the same Session ID so your files can be compared in the Agreement check.' + '

' '
' ) - # ── Agent activity log (shared across all tabs) ─────────────────────── - agent_log_html = gr.HTML(_agent_log_html([])) + with gr.Row(): + session_id_box = gr.Textbox(label="Session ID", placeholder="e.g. dyad_01", scale=1) + researcher_id_box = gr.Textbox(label="Researcher ID", placeholder="e.g. R1", scale=1) + + transcript_file = gr.File( + label="Transcript file (.txt or .vtt Zoom export)", + file_types=[".txt", ".vtt"], + ) + + process_btn = gr.Button("⚡ Process Transcript →", variant="primary") + process_status = gr.HTML() + process_log = gr.HTML() + + back_setup_btn = gr.Button("← Back to Home", size="sm") + + # ───────────────────────────────────────────────────────────────────── + # PAGE 2: 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' + '
' + ) + + gr.HTML( + '
' + 'AI detected topical sections using lexical cohesion signals ' + '(Hearst 1997; Purver et al. 2006). ' + 'Edit the labels below to match your theoretical framing. ' + 'Turn boundaries are fixed — only labels can be changed.' + '
' + ) - with gr.Tabs(selected="home") as main_tabs: + sections_display_md = gr.Markdown() - # ================================================================== - # TAB 0 — Home Dashboard (app-style entry) - # ================================================================== - with gr.Tab("Home", id="home"): + gr.Markdown("**Edit section labels** (one per line):") + sections_labels_box = gr.Textbox(lines=8, show_label=False, + placeholder="One label per line…") + 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() + + # Sub-step A: Parallel boundary detection + with gr.Column(visible=True) as col_run_all_boundaries: gr.HTML( - '
' - '

Choose a workspace

' - '

' - 'Each workspace is a dedicated page, so you can focus on one task at a time.' - '

' + '
' + 'Agent 1a runs in parallel on all sections simultaneously — ' + 'processing time scales with the longest section, not total length. ' + '(Dean & Ghemawat 2004 — parallel map pattern)' '
' ) - with gr.Row(equal_height=True): - with gr.Column(scale=1): - gr.HTML( - '
' - '
Transcript
' - '

Pipeline Workspace

' - '

' - 'Upload transcript, detect sections, review boundaries, and code episodes.' - '

' - '
' - ) - go_pipeline_btn = gr.Button("Open Transcript Workspace", variant="primary") - - with gr.Column(scale=1): - gr.HTML( - '
' - '
Intercoder
' - '

Agreement Workspace

' - '

' - 'Compare two coder files, compute reliability, and resolve disagreements.' - '

' - '
' - ) - go_agreement_btn = gr.Button("Open Intercoder Workspace") - - with gr.Column(scale=1): - gr.HTML( - '
' - '
AI Library
' - '

Learning Review Workspace

' - '

' - 'Review and approve/reject Agent 2 proposed rules for the validated library.' - '

' - '
' - ) - go_rules_btn = gr.Button("Open AI Library Workspace") + run_all_btn = gr.Button("⚡ Detect Episode Boundaries (All Sections)", variant="primary") + parallel_status_md = gr.Markdown() + parallel_stats_html = gr.HTML() - # ================================================================== - # TAB 1 — Research Pipeline - # ================================================================== - with gr.Tab("Transcript Pipeline", id="pipeline"): + section_header_md = gr.Markdown() + # Sub-step B: Per-section boundary review + with gr.Column(visible=False) as col_boundary_review: + gr.HTML( + '
' + '
Episode Structure
' + ) + boundary_display_html = gr.HTML() + gr.HTML('
') + + gr.Markdown( + "**Review boundaries above.** Edit the turn IDs below to adjust. " + "Leave empty for a single undivided episode." + ) with gr.Row(): - gr.HTML( - '
' - 'Page 1 of 3: Transcript processing and coding workflow.' - '
' + boundary_ids_box = gr.Textbox( + label="Boundary turn IDs (comma-separated) — turn after which each new episode begins", + placeholder="e.g. 12, 28, 35", + lines=1, scale=3, ) - to_agreement_btn = gr.Button("Next Page: Intercoder →", size="sm") + confirm_boundaries_btn = gr.Button("Confirm & Code →", variant="primary", scale=1) + code_status = gr.Markdown() - with gr.Row(equal_height=False): + # Sub-step C: Coding canvas + with gr.Column(visible=False) as col_coding: + coding_progress_comp = gr.HTML() - # ── 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): - 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." - ) - 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 — Boundary Analysis + Coding") - sections_overview_html = gr.HTML() - - # 3a: Parallel Agent 1a for ALL sections - with gr.Column() as col_run_all_boundaries: - gr.HTML( - '
' - 'Agent 1a runs in parallel on all sections simultaneously.' - ' Processing time scales with the longest section, not the total ' - 'transcript length. *(Dean & Ghemawat 2004 — parallel map pattern)*' - '
' - ) - run_all_btn = gr.Button( - "⚡ Analyse All Boundaries in Parallel (Agent 1a)", - variant="primary", - ) - parallel_status_md = gr.Markdown() - parallel_stats_html = gr.HTML() - - # Current section review header - section_header_md = gr.Markdown() - - # 3b: Per-section boundary review (after parallel run) - with gr.Column(visible=False) as col_boundary_review: - gr.HTML( - '
' - '
Episode Structure
' - ) - boundary_display_html = gr.HTML() - gr.HTML('
') - gr.Markdown( - "**Review boundaries above.** Edit the turn IDs below " - "to adjust, add, or remove boundaries. " - "Leave empty for a single undivided episode." - ) - with gr.Row(): - 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() - gr.Markdown("**Transcript**", elem_classes=["label-md"]) - turns_html_comp = gr.HTML() - 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="Primary dimension", value=None - ) - dim_desc_comp = gr.HTML() - secondary_dim_drop = gr.Dropdown( - choices=SEC_DIM_CHOICES, - value=SEC_NONE, - label="Secondary dimension (optional)", - info="Use only when a second dimension is clearly sustained throughout the episode. Strijbos et al. (2006); Suthers & Rosen (2011).", - interactive=True, - ) - 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 - ) - - # Step 4: Complete - with gr.Column(visible=False) as col_complete: + 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( - '
' - '

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.

' - '
' + '

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

' ) - 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 — Inter-Rater Agreement - # ================================================================== - with gr.Tab("Intercoder Agreement", id="agreement"): - with gr.Row(): - back_to_pipeline_btn = gr.Button("← Back to Transcript", size="sm") - gr.HTML( - '
' - 'Page 2 of 3: Reliability and disagreement resolution.' - '
' - ) - to_rules_btn = gr.Button("Next Page: AI Library →", size="sm") - 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. ' - '
' - '
' + proposal_comp = gr.Markdown(visible=False) + + # Right: coding controls + with gr.Column(scale=2, elem_classes=["cc-coding-controls"]): + gr.Markdown("#### Dimension") + dim_radio = gr.Radio(choices=DIM_CHOICES, label="Primary", value=None) + dim_desc_comp = gr.HTML() + + secondary_dim_drop = gr.Dropdown( + choices=SEC_DIM_CHOICES, + value=SEC_NONE, + label="Secondary dimension (optional)", + info="Only when a second dimension is clearly sustained throughout. Strijbos et al. (2006).", + interactive=True, + ) + comment_box = gr.Textbox( + label="Note (optional)", lines=2, + placeholder="Ambiguity, competing codes…" ) - - 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) + prev_btn = gr.Button("← Previous", size="sm") + next_btn = gr.Button("Next →", variant="primary", size="sm") - kappa_html_comp = gr.HTML() - disagreements_md = gr.Markdown() + segment_jump = gr.Dropdown( + label="Jump to segment", choices=[], value=None, interactive=True + ) + next_section_btn = gr.Button( + "→ Finish Section & Continue", variant="secondary", visible=False + ) - 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.Accordion("Agent Activity Log", open=False): + pipeline_log = gr.HTML(_agent_log_html([])) - # ── Sequence Analysis ────────────────────────────── - with gr.Accordion("Sequence Analysis", open=False) as accord_seq: - gr.HTML( - '
' - 'Temporal structure of the coded sequence. ' - 'Frequency counts tell you how much of each dimension; ' - 'sequential analysis tells you what follows what. ' - 'Bakeman & Gottman (1986); Bakeman & Quera (2011)' - '
' - ) - 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 for R/Python/SPSS)", - variant="secondary", size="sm", - ) - seq_dl_file = gr.File(visible=False) - - 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 — AI Learning Review - # ================================================================== - with gr.Tab("AI Library Review", id="library"): + 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(): - back_to_agreement_btn = gr.Button("← Back to Intercoder", size="sm") - gr.HTML( - '
' - 'Page 3 of 3: Validate and curate AI learning rules.' - '
' + 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, ) - home_btn = gr.Button("Return Home", size="sm") - 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)*.

' - '
' - ) + 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

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

' + '⚠ Agent 2 requires ≥ 3 validated sessions and ≥ 90 coded segments ' + 'before proposing rules (Bujang & Baharum 2017).' + '
' + ) - 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." - ) + 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") # ===================================================================== - # OUTPUT LISTS + # ALL PAGES list (order must match _PAGE_NAMES) # ===================================================================== + ALL_PAGES = [pg_welcome, pg_setup, pg_sections, pg_pipeline, pg_done, pg_agreement, pg_library] 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 ← NEW - comment_box, # 8 - next_section_btn, # 9 + 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 ] - NEXT_SECTION_OUTS = [ + # fn_process outputs (12 total) + PROCESS_OUTPUTS = [state, process_status, *ALL_PAGES, sections_display_md, sections_labels_box, process_log] + + # fn_confirm_sections outputs (12 total) + CONFIRM_SECTIONS_OUTPUTS = [ + state, *ALL_PAGES, + sections_overview_html, + col_run_all_boundaries, # reset to visible + col_boundary_review, # reset to hidden + col_coding, # reset to hidden + ] + + # fn_run_all_boundaries outputs (8 total) + RUN_ALL_OUTPUTS = [ state, - pipeline_html, + parallel_status_md, + parallel_stats_html, + col_boundary_review, # show/hide + boundary_display_html, + boundary_ids_box, + section_header_md, + pipeline_log, + ] + + # fn_confirm_and_code outputs (14 total) + CONFIRM_CODE_OUTPUTS = [state, code_status, col_coding] + CODING_OUTPUTS + [pipeline_log] + + # fn_next_section outputs (12 total) + NEXT_SECTION_OUTPUTS = [ + state, *ALL_PAGES, sections_overview_html, section_header_md, - col_run_all_boundaries, col_boundary_review, col_coding, - col_complete, ] # ===================================================================== - # CALLBACK WIRING + # WIRING # ===================================================================== - # App-style page navigation - go_pipeline_btn.click(fn=lambda: gr.update(selected="pipeline"), outputs=[main_tabs]) - go_agreement_btn.click(fn=lambda: gr.update(selected="agreement"), outputs=[main_tabs]) - go_rules_btn.click(fn=lambda: gr.update(selected="library"), outputs=[main_tabs]) - - to_agreement_btn.click(fn=lambda: gr.update(selected="agreement"), outputs=[main_tabs]) - back_to_pipeline_btn.click(fn=lambda: gr.update(selected="pipeline"), outputs=[main_tabs]) - to_rules_btn.click(fn=lambda: gr.update(selected="library"), outputs=[main_tabs]) - back_to_agreement_btn.click(fn=lambda: gr.update(selected="agreement"), outputs=[main_tabs]) - home_btn.click(fn=lambda: gr.update(selected="home"), outputs=[main_tabs]) - - parse_btn.click( - fn=fn_parse, + # Welcome navigation + start_btn.click(lambda: _show("setup"), outputs=ALL_PAGES) + agreement_nav_btn.click(lambda: _show("agreement"), outputs=ALL_PAGES) + library_nav_btn.click(lambda: _show("library"), outputs=ALL_PAGES) + + # Back buttons + back_setup_btn.click(lambda: _show("welcome"), outputs=ALL_PAGES) + back_sections_btn.click(lambda: _show("setup"), outputs=ALL_PAGES) + back_pipeline_btn.click(lambda: _show("sections"), outputs=ALL_PAGES) + back_done_btn.click(lambda: _show("pipeline"), outputs=ALL_PAGES) + back_agreement_btn.click(lambda: _show("done"), outputs=ALL_PAGES) + back_library_btn.click(lambda: _show("agreement"), outputs=ALL_PAGES) + home_from_lib.click(lambda: _show("welcome"), outputs=ALL_PAGES) + + # Forward navigation + go_agreement_btn.click(lambda: _show("agreement"), outputs=ALL_PAGES) + go_library_btn.click(lambda: _show("library"), outputs=ALL_PAGES) + + # Setup: process transcript + detect sections + process_btn.click( + fn=fn_process, inputs=[transcript_file, session_id_box, researcher_id_box, state], - outputs=[state, pipeline_html, parse_status, col_agent0], + outputs=PROCESS_OUTPUTS, ) - # 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, sidebar_log], - ).then(fn=lambda: RESEARCH_INFO["sections"], outputs=[pipeline_info]) - + # Sections: confirm labels confirm_sections_btn.click( fn=fn_confirm_sections, inputs=[sections_labels_box, state], - outputs=[ - state, pipeline_html, sections_overview_html, - col_section_work, - col_run_all_boundaries, col_boundary_review, col_coding, - parallel_stats_html, - ], - ).then(fn=lambda: RESEARCH_INFO["boundaries"], outputs=[pipeline_info]) + outputs=CONFIRM_SECTIONS_OUTPUTS, + ) + # Pipeline: run boundaries in parallel run_all_btn.click( fn=fn_run_all_boundaries, inputs=[state], - outputs=[ - state, - parallel_status_md, - parallel_stats_html, - boundary_display_html, - boundary_ids_box, - section_header_md, - sidebar_log, - ], - ).then(fn=lambda: RESEARCH_INFO["boundaries"], outputs=[pipeline_info]) + 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=[state, code_status, col_coding] + CODING_OUTPUTS + [sidebar_log], - ).then(fn=lambda: RESEARCH_INFO["coding"], outputs=[pipeline_info]) + outputs=CONFIRM_CODE_OUTPUTS, + ) + # Coding navigation next_btn.click( fn=lambda d, sec, c, s: fn_navigate(+1, d, sec, c, s), inputs=[dim_radio, secondary_dim_drop, comment_box, state], @@ -2606,21 +2289,23 @@ with gr.Blocks(title="CollabCode") as demo: reveal_btn.click(fn=fn_reveal, inputs=[state], outputs=[proposal_comp]) dim_radio.change(fn=fn_dim_desc, inputs=[dim_radio], outputs=[dim_desc_comp]) + # Finish section / go to done next_section_btn.click( fn=fn_next_section, inputs=[dim_radio, secondary_dim_drop, comment_box, state], - outputs=NEXT_SECTION_OUTS, + 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 tab + # Agreement kappa_btn.click( fn=fn_calculate_kappa, inputs=[r2_upload, state], - outputs=[state, kappa_html_comp, disagreements_md, col_disagreements, kappa_log], + outputs=[state, kappa_html_comp, disagreements_md, col_disagreements, agreement_log], ) resolve_btn.click( fn=fn_resolve, @@ -2645,7 +2330,7 @@ with gr.Blocks(title="CollabCode") as demo: outputs=[seq_dl_file], ).then(fn=lambda: gr.update(visible=True), outputs=[seq_dl_file]) - # Rule review tab + # 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]