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'{desc}
' - f'Evidence: {rat}
' - f' for expand-to-read-content — no JS required.
- Each section is collapsed by default (researcher sees the label and size at a glance)
- and can be expanded to read the AI summary + first 8 turns of actual transcript.
+def _score_to_color(score: float, excluded: bool) -> tuple[str, str]:
+ """Returns (background, text-color) for a turn score badge."""
+ if excluded:
+ return "#f1f5f9", "#94a3b8"
+ if score >= 0.8:
+ return "#dcfce7", "#15803d"
+ if score >= 0.55:
+ return "#d1fae5", "#065f46"
+ if score >= 0.40:
+ return "#fef9c3", "#854d0e"
+ if score >= 0.2:
+ return "#eff6ff", "#1d4ed8"
+ return "#f8fafc", "#94a3b8"
- Label format in the textarea is "s01: Label" so the mapping is unambiguous.
- """
- if not sections:
- return 'No sections detected.
'
-
- avg = n_turns // len(sections) if sections else 0
- total = n_turns
-
- # ── 1. Agent completion card ─────────────────────────────────────────────
- agent_card = (
- f''
- f''
- f''
- f''
- f'✓'
- f'Agent 0 — Structural Segmenter'
- f'completed in {agent0_rt:.1f}s'
- f''
- f''
- f'{total} turns · {n_speakers} speaker(s) → '
- f'{len(sections)} sections detected '
- f'(avg {avg} turns/section)
'
- f'Basis: lexical cohesion (Hearst 1997) · topic modelling (Purver et al. 2006) '
- f'· activity phases (Stahl 2006; Roschelle & Teasley 1995)'
- f''
- f''
- f''
- f'Qwen2.5-72B · T=0.1'
- f''
- f''
- )
- # ── 2. Expandable section list ───────────────────────────────────────────
- palette = [
- ("#4338ca", "#eef2ff"), # indigo
- ("#b45309", "#fffbeb"), # amber
- ("#065f46", "#f0fdf4"), # emerald
- ("#9a3412", "#fff7ed"), # orange
- ("#6b21a8", "#faf5ff"), # purple
- ("#0e7490", "#ecfeff"), # cyan
- ("#be123c", "#fff1f2"), # rose
- ]
+def _screener_summary_html(result_dict: dict) -> str:
+ total = result_dict.get("total_turns", 0)
+ flagged = result_dict.get("flagged_turns", 0)
+ windows = len(result_dict.get("candidate_windows", []))
+ savings = result_dict.get("estimated_llm_savings", 0)
- warnings = []
- detail_items = []
+ return (
+ f''
+ + _stat_chip(str(total), "Total turns", "#4338ca", "#eef2ff")
+ + _stat_chip(str(flagged), "Flagged turns", "#065f46", "#dcfce7")
+ + _stat_chip(str(windows), "Candidate windows", "#b45309", "#fffbeb")
+ + _stat_chip(f"{savings:.0%}", "LLM savings", "#be123c", "#fef2f2")
+ + f''
+ )
- for i, s in enumerate(sections):
- col, bg = palette[i % len(palette)]
- n = s["end_turn_id"] - s["start_turn_id"] + 1
- pct = round(n / total * 100) if total else 0
- if pct > 30 and len(sections) > 2:
- warnings.append(
- f'{_h(s["label"])} ({n} turns, {pct}%) is unusually large. '
- f'Expand it below to check if it contains distinct sub-topics.'
- )
+def _stat_chip(value: str, label: str, tc: str, bg: str) -> str:
+ return (
+ f''
+ f'{_h(value)}'
+ f'{_h(label)}'
+ f''
+ )
- # ── Bar ──
- bar = (
- f''
- f''
- f''
- )
- # ── Transcript excerpt ──
- excerpt_html = ""
- if all_turns:
- sec_turns = [
- t for t in all_turns
- if s["start_turn_id"] <= t["turn_id"] <= s["end_turn_id"]
- ]
- shown = sec_turns[:8]
- rows = []
- for t in shown:
- sp = _h(t.get("speaker", "?"))
- ts = _h(t.get("start_time", ""))
- txt = t.get("text", "")
- if len(txt) > 180:
- txt = txt[:180] + "…"
- rows.append(
- f''
- f''
- f'{sp}'
- f'{ts}'
- f'{_h(txt)}'
- f''
- )
- if len(sec_turns) > 8:
- rows.append(
- f'⋯ {len(sec_turns)-8} more turns'
- )
- excerpt_html = (
- f''
- f''
- f'Transcript excerpt (first {len(shown)} of {n} turns)'
- f'{"".join(rows)}'
- f''
+def _screener_turns_html(result_dict: dict, speaker_map: dict,
+ max_turns: int = 300) -> str:
+ turn_scores = result_dict.get("turn_scores", [])
+ if not turn_scores:
+ return 'Run the screener first.
'
+
+ parts = []
+ parts.append(
+ ''
+ ''
+ '#SpeakerScoreTextTriggers'
+ ''
+ )
+
+ shown = 0
+ for ts in turn_scores:
+ if shown >= max_turns:
+ remaining = len(turn_scores) - max_turns
+ parts.append(
+ f'{remaining} more turns — use the search filter'
+ )
+ break
+ shown += 1
+
+ excluded = bool(ts.get("excluded_reason"))
+ flagged = ts.get("flagged", False)
+ score = ts.get("composite", 0)
+ sp = ts.get("speaker", "?")
+ text = ts.get("text", "")
+ tid = ts.get("turn_id", "")
+ stime = ts.get("start_time", "")
+ hits = ts.get("hits", [])
+ signals = ts.get("signals", [])
+
+ entry = speaker_map.get(sp, {"color": "#64748b", "initials_bg": "#e2e8f0"})
+ sbg, stc = _score_to_color(score, excluded)
+
+ # Highlight matched terms in text
+ display_text = _h(text[:140] + ("…" if len(text) > 140 else ""))
+
+ # Trigger chips
+ trigger_chips = ""
+ for hit in hits[:3]:
+ ph = hit.get("phase", "")
+ lbl = hit.get("category_label", "")
+ tier = hit.get("tier", 1)
+ tchip_bg = {"planning": "#eff6ff", "monitoring": "#f0fdf4",
+ "evaluating": "#fff7ed", "ssrl": "#faf5ff"}.get(ph, "#f8fafc")
+ tchip_c = {"planning": "#1d4ed8", "monitoring": "#15803d",
+ "evaluating": "#c2410c", "ssrl": "#7c3aed"}.get(ph, "#64748b")
+ tier_mark = "⟨2⟩" if tier == 2 else "⟨3?⟩" if tier == 3 else ""
+ trigger_chips += (
+ f''
+ f'{_h(lbl[:25])}{tier_mark} '
+ )
+ for sig in signals[:2]:
+ trigger_chips += (
+ f''
+ f'⚡{_h(sig)} '
+ )
+ if excluded:
+ trigger_chips = (
+ f'small talk'
)
- summary_text = _h(s.get("summary", "No summary provided."))
-
- detail_items.append(
- f''
-
- # ── Collapsed header (always visible) ──────────────────────────
- f''
- f''
- f'{_h(s["section_id"])}'
- f''
- f'{_h(s["label"])}'
- f'{_h(s["start_time"])}–{_h(s["end_time"])}'
- f''
- f' {n} turns ({pct}%)'
- f'{bar}'
- f'▼ read'
- f'
'
-
- # ── Expanded content ────────────────────────────────────────────
- f''
- f''
- f'AI summary: {summary_text}
'
- f'{excerpt_html}'
+ row_bg = "#fffbeb" if flagged else ("#f8fafc" if excluded else "white")
+ flag_icon = "🟢" if flagged else ("⬜" if not excluded else "🔘")
+
+ parts.append(
+ f''
+
+ # Turn ID
+ f'{flag_icon} {_h(str(tid))}'
+
+ # Speaker
+ f''
+ f'{_h(sp[:10])}'
+
+ # Score badge
+ f''
+ f'{score:.2f}'
+ f'{_h(stime)}'
f''
- f''
- )
- section_list = f'{"".join(detail_items)}'
-
- # ── 3. Warnings ──────────────────────────────────────────────────────────
- warn_html = ""
- if warnings:
- items = "".join(f"{w} " for w in warnings)
- warn_html = (
- f''
- f'⚠ Size note'
- f'{items}
'
+ # Text
+ f''
+ f'{display_text}'
+
+ # Triggers
+ f'{trigger_chips}'
+
f''
)
- # ── 4. Label editor instruction ──────────────────────────────────────────
- instr = (
- f''
- f'Rename sections below — each line follows the format '
- f''
- f's01: Your Label. '
- f'Edit the text after the colon only; the s01: prefix keeps the order clear. '
- f'Turn boundaries are fixed — only labels change. '
- f'Expand any section above to read its content before renaming.'
- f''
- )
-
- return agent_card + section_list + warn_html + instr
+ parts.append('')
+ return "".join(parts)
-def _episode_dialogue_html(segments: list[dict], boundaries: list[dict],
- speaker_map: dict) -> str:
- """
- Render each proposed episode with its actual dialogue turns + boundary markers.
+def _candidate_windows_html(result_dict: dict) -> str:
+ wins = result_dict.get("candidate_windows", [])
+ if not wins:
+ return 'No candidate windows found.
'
- Design goal: the researcher must be able to READ the transcript before
- deciding whether to accept the AI's proposed boundary positions.
- Showing only turn-ID tables (the old approach) is opaque.
+ parts = ['']
+ for i, w in enumerate(wins, 1):
+ tids = w.get("turn_ids", [])
+ score = w.get("score", 0)
+ summary = w.get("trigger_summary", "")
+ n = w.get("turn_count", len(tids))
+ start = tids[0] if tids else "?"
+ end = tids[-1] if tids else "?"
+ sbg, stc = _score_to_color(score, False)
- Rules:
- - Up to 5 turns shown per episode; truncation indicated clearly
- - Speaker avatars + timestamps match the coding canvas
- - Boundary markers show signal type, confidence, and AI rationale
- - Entire view is scrollable so the page does not grow unbounded
- """
- if not segments:
- return (
- ''
- 'No episode data yet.
'
+ parts.append(
+ f''
+ f''
+ f'{i:02d}'
+ f''
+ f''
+ f'Turns {_h(str(start))}–{_h(str(end))} '
+ f'({n} turns)'
+ f''
+ f'{_h(summary)}'
+ f''
+ f'score {score:.2f}'
+ f''
)
+ parts.append('')
+ return "".join(parts)
+
- bmap: dict[int, dict] = {}
- for b in boundaries:
- bmap[b.get("after_turn_id", -1)] = b
+# ──────────────────────────────────────────────────────────────────────────────
+# Lexicon render helpers
+# ──────────────────────────────────────────────────────────────────────────────
- conf_colors = {
- "high": ("#065f46", "#f0fdf4", "#86efac"),
- "medium": ("#92400e", "#fffbeb", "#fde68a"),
- "low": ("#991b1b", "#fef2f2", "#fca5a5"),
+def _lexicon_tier1_html(tier1_data: dict) -> str:
+ cats = tier1_data.get("categories", [])
+ if not cats:
+ return 'Lexicon file not found.
'
+
+ phase_colors = {
+ "planning": ("#1d4ed8", "#eff6ff", "#dbeafe"),
+ "monitoring": ("#15803d", "#f0fdf4", "#dcfce7"),
+ "evaluating": ("#c2410c", "#fff7ed", "#fed7aa"),
+ "ssrl": ("#7c3aed", "#faf5ff", "#e9d5ff"),
}
- parts: list[str] = []
- for i, seg in enumerate(segments):
- turns = seg.get("turns", [])
- ep_id = seg.get("segment_id", f"ep{i+1:02d}")
- ep_num = ep_id.split("_ep")[-1] if "_ep" in ep_id else str(i + 1)
- n_turns = len(turns)
+ parts = [
+ ''
+ ''
+ '🔒 Tier 1 is research-locked. To add custom terms, use the Tier 2 tab.'
+ ]
+
+ for cat in cats:
+ phase = cat.get("phase", "monitoring")
+ tc, bg, border = phase_colors.get(phase, ("#475569", "#f8fafc", "#e2e8f0"))
+ label = _h(cat.get("label", ""))
+ cat_id = _h(cat.get("id", ""))
+ weight = cat.get("weight", 0)
+ source = _h(cat.get("source", ""))
+ terms = cat.get("terms", [])
+
+ term_chips = " ".join(
+ f''
+ f'{_h(t)}'
+ for t in terms
+ )
- # Episode header strip
parts.append(
- f''
- f'Episode {ep_num}'
- f'{n_turns} turns'
- + (f''
- f'{_h(seg.get("rationale","")[:80])}{"…" if len(seg.get("rationale",""))>80 else ""}'
- f'' if seg.get("rationale") else '')
- + ''
+ f''
+ f''
+ f'{cat_id}'
+ f'{label}'
+ f''
+ f'w={weight} · {_h(phase)}'
+ f''
+ f''
+ f'Source: {source}'
+ f'{term_chips}'
+ f''
)
+ parts.append('')
+ return "".join(parts)
- # Show up to 5 turns
- shown = turns[:5]
- for t in shown:
- sp = t.get("speaker", "?")
- entry = speaker_map.get(
- sp, {"color": "#64748b", "bg": "#f8fafc", "initials_bg": "#e2e8f0"}
- )
- avatar = _speaker_avatar(sp, entry)
- text = t.get("text", "")
- if len(text) > 220:
- text = text[:220] + "…"
- ts = _h(t.get("start_time", ""))
- parts.append(
- f''
- f'{avatar}'
- f''
- f''
- f''
- f'{_h(sp)}'
- f'{ts}'
- f''
- f'#{t.get("turn_id","")}'
- f''
- f'{_h(text)}'
- f''
- )
- if n_turns > 5:
- parts.append(
- f''
- f'⋯ {n_turns - 5} more turn{"s" if n_turns-5>1 else ""} in this episode'
- )
+def _lexicon_tier2_html(tier2_data: dict) -> str:
+ entries = tier2_data.get("entries", [])
+ if not entries:
+ return (
+ ''
+ '📝'
+ 'No validated terms yet.'
+ ''
+ 'Use the form below to add researcher-validated terms.'
+ )
- # Boundary marker before the next episode
- if i < len(segments) - 1 and turns:
- last_tid = turns[-1].get("turn_id", -1)
- b = bmap.get(last_tid, {})
- sig = b.get("boundary_signal", "boundary")
- conf = b.get("confidence", "medium")
- rat = b.get("rationale", "")
- tc, bg, bc = conf_colors.get(conf, conf_colors["medium"])
- parts.append(
- f''
- f'━ boundary'
- f'{_h(sig)}'
- f'{conf} confidence'
- + (f''
- f'— {_h(rat[:100])}{"…" if len(rat)>100 else ""}' if rat else '')
- + f'after #{last_tid}'
- f''
- )
+ parts = ['']
+ for e in entries:
+ active = e.get("active", True)
+ bg = "white" if active else "#f8fafc"
+ tc = "#1e293b" if active else "#94a3b8"
+ badge = ("🟢 Active" if active else "⬜ Inactive")
+ label = _h(e.get("label", ""))
+ cat_id = _h(e.get("category_id", ""))
+ terms = e.get("terms", [])
+ note = _h(e.get("note", ""))
+ added = _h(e.get("added_by", ""))
+
+ term_chips = " ".join(
+ f'{_h(t)}'
+ for t in terms
+ )
- return (
- f''
- + "".join(parts)
- + ''
- )
+ parts.append(
+ f''
+ f''
+ f'{badge}'
+ f'{label}'
+ f'{cat_id}'
+ f'by {added}'
+ f''
+ f'{term_chips}'
+ f'{f"{note}" if note else ""}'
+ f''
+ )
+ parts.append('')
+ return "".join(parts)
-def _agent_log_html(logs: list[dict]) -> str:
- if not logs:
+def _lexicon_tier3_html(tier3_data: dict) -> str:
+ candidates = [c for c in tier3_data.get("candidates", [])
+ if not c.get("approved") and not c.get("rejected")]
+ if not candidates:
return (
- ''
- 'No agents have run yet.
'
+ ''
+ '✅'
+ 'No pending candidates.'
+ ''
+ 'Candidates appear here when the system proposes new terms from coded segments.'
+ ''
)
- 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 = ['']
+ for c in candidates:
+ terms = c.get("terms", [])
+ label = _h(c.get("label", ""))
+ ctx = _h(c.get("context", "")[:200])
+ session = _h(c.get("session_id", ""))
+
+ term_chips = " ".join(
+ f'{_h(t)}'
+ for t in terms
)
+
parts.append(
- f''
- f''
- f'{agent}'
- f'{ts} · {runtime}s'
+ f''
+ f''
+ f'⏳ Pending'
+ f'{label}'
+ f'{session}'
f''
- f'model: {model}'
- f'{extra_lines}'
+ f'{term_chips}'
+ f'{f"“{ctx}”" if ctx else ""}'
f''
)
+ parts.append('')
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,
+# ──────────────────────────────────────────────────────────────────────────────
+# Segment review helpers (enhanced for inline editing)
+# ──────────────────────────────────────────────────────────────────────────────
+
+def _dim_badge(did: str) -> str:
+ colors = {
+ "D1": ("#4338ca","#eef2ff"), "D2": ("#0e7490","#ecfeff"),
+ "D3": ("#065f46","#ecfdf5"), "D4": ("#b45309","#fffbeb"),
+ "D5": ("#6b21a8","#faf5ff"), "D6": ("#9a3412","#fff7ed"),
+ "D7": ("#1e40af","#dbeafe"), "D8": ("#be123c","#fef2f2"),
+ "D9": ("#374151","#f3f4f6"), "NS": ("#78716c","#f5f5f4"),
+ "NA": ("#94a3b8","#f8fafc"),
}
+ tc, bg = colors.get(did, ("#64748b","#f8fafc"))
+ return (
+ f''
+ f'{_h(did)}'
+ )
-def _coding_progress_html(state: dict) -> str:
- sections = state.get("sections", [])
- idx = state.get("section_idx", 0)
- segs = _current_section_segments(state)
- codings = state.get("codings", {})
- cidx = state.get("coding_idx", 0)
- if not segs:
+def _ssrl_badge(phase_id: str) -> str:
+ if not phase_id or phase_id == "NONE":
return ""
- coded = sum(1 for s in segs if codings.get(s["segment_id"], {}).get("dimension_id"))
- total = len(segs)
- pct = int(coded / total * 100) if total else 0
- sec = sections[idx] if idx < len(sections) else {}
- ep_num = min(cidx, total - 1) + 1
- # Total across all sections
- all_coded = sum(1 for v in codings.values() if v.get("dimension_id"))
- all_segs = sum(
- len(state.get("section_segments_coded", {}).get(s["section_id"], []))
- for s in sections
- )
+ tc, bg = SSRL_COLOR_FROM_ID.get(phase_id, ("#64748b","#f8fafc"))
+ label = next((l for p, l, _, _ in SSRL_PHASES if p == phase_id), phase_id)
return (
- f''
- f''
- f''
- f'Section {idx+1}/{len(sections)} — {_h(sec.get("label",""))}'
- f'Episode {ep_num} of {total}'
- f''
- f''
- f''
- f''
- f'{coded}/{total} episodes coded this section'
- f'{all_coded}/{all_segs} total'
- f''
- f''
+ f''
+ f'⟡ {_h(label)}'
)
-# ===========================================================================
-# STATE
-# ===========================================================================
-
-def _empty_state() -> dict:
- return {
- "session_id": "",
- "researcher_id": "",
- "turns": [],
- "speakers": {},
- "sections": [],
- "section_idx": 0,
- "section_stages": {},
- "section_boundaries": {},
- "section_segments": {},
- "section_segments_coded": {},
- "coding_idx": 0,
- "codings": {},
- "stage": "upload",
- "kappa_report": None,
- "agent_logs": [],
- }
-
-
-def _auto_session_id(researcher_id: str = "", source_name: str = "") -> str:
- stamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
- base = (Path(source_name).stem or "drive").replace(" ", "_")
- rid = (researcher_id or "R").strip().replace(" ", "_")
- return f"{rid}_{base}_{stamp}"
+def _segment_review_html(seg: dict, codings: dict, ssrl_codings: dict,
+ speaker_map: dict, screener_hit: bool = False) -> str:
+ sid = seg["segment_id"]
+ existing = codings.get(sid, {})
+ dim_id = existing.get("dimension_id") or seg.get("dimension_id") or "?"
+ ssrl_id = ssrl_codings.get(sid, "NONE")
+ rationale = _h(seg.get("rationale", ""))
+ uncertain = seg.get("uncertain", False)
+ conf = seg.get("confident", False)
+ unote = _h(seg.get("uncertainty_note", ""))
+ n_turns = (seg.get("end_turn_id", 0) - seg.get("start_turn_id", 0) + 1)
+ stime = _h(seg.get("start_time", ""))
+ etime = _h(seg.get("end_time", ""))
+
+ screener_tag = ""
+ if screener_hit:
+ screener_tag = (
+ ''
+ '🔍 screener hit'
+ )
+ uncertain_tag = ""
+ if uncertain:
+ uncertain_tag = (
+ f'⚠ AI uncertain — {unote}'
+ )
-def _loading_card(title: str, subtitle: str = "Please wait…", spin: str = "◐") -> str:
return (
- ''
- ''
- f'{spin}'
- f'{_h(title)}'
- f'{_h(subtitle)}'
- ''
+ f''
+ f''
+ f'{_h(sid)}'
+ f'{_dim_badge(dim_id)}'
+ f'{_ssrl_badge(ssrl_id)}'
+ f'{screener_tag}'
+ f''
+ f'{stime}–{etime} · {n_turns} turns'
+ f''
+ f''
+ f'{rationale or "No rationale."}'
+ f'{uncertain_tag}'
+ f''
)
-def _session_dir(state: dict) -> Path:
- return SESSIONS_ROOT / state["session_id"]
-
-
-def _current_section(state: dict) -> dict | None:
- secs = state.get("sections", [])
- idx = state.get("section_idx", 0)
- return secs[idx] if secs and idx < len(secs) else None
-
+def _all_segments_review_html(state: dict) -> str:
+ all_segs = []
+ codings = state.get("codings", {})
+ ssrl = state.get("ssrl_codings", {})
+ speaker_map = state.get("speakers", {})
+ screener = state.get("screener_result")
+ flagged_wins = set()
+ if screener:
+ for w in screener.get("candidate_windows", []):
+ flagged_wins.update(w.get("turn_ids", []))
-def _current_section_segments(state: dict) -> list[dict]:
- sec = _current_section(state)
- return state["section_segments_coded"].get(sec["section_id"], []) if sec else []
+ for sec in state.get("sections", []):
+ segs = state.get("section_segments_coded", {}).get(sec["section_id"], [])
+ for seg in segs:
+ start = seg.get("start_turn_id", 0)
+ end = seg.get("end_turn_id", 0)
+ hit = any(t in flagged_wins for t in range(start, end + 1))
+ all_segs.append((seg, hit))
+
+ if not all_segs:
+ return 'No coded segments yet.
'
+
+ coded = sum(1 for s, _ in all_segs if codings.get(s["segment_id"], {}).get("dimension_id"))
+ total = len(all_segs)
+ ssrl_ct = sum(1 for s, _ in all_segs if ssrl.get(s["segment_id"], "NONE") != "NONE")
+
+ header = (
+ f''
+ + _stat_chip(str(total), "Segments", "#4338ca", "#eef2ff")
+ + _stat_chip(str(coded), "D1-D9 coded", "#065f46", "#dcfce7")
+ + _stat_chip(str(ssrl_ct), "SSRL tagged", "#7c3aed", "#faf5ff")
+ + f''
+ )
+ rows = "".join(
+ _segment_review_html(seg, codings, ssrl, speaker_map, hit)
+ for seg, hit in all_segs
+ )
+ return header + rows
-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"]]
+# ──────────────────────────────────────────────────────────────────────────────
+# Section display helpers (from v4, kept intact)
+# ──────────────────────────────────────────────────────────────────────────────
-def _persist(state: dict) -> None:
- try:
- d = _session_dir(state)
- d.mkdir(parents=True, exist_ok=True)
- skip = {"turns", "kappa_report"}
- (d / "app_state.json").write_text(
- json.dumps({k: v for k, v in state.items() if k not in skip},
- indent=2, ensure_ascii=False),
- encoding="utf-8",
+def _sections_html(sections: list[dict], n_turns: int, elapsed: float,
+ n_speakers: int, all_turns: list[dict] | None = None) -> str:
+ if not sections:
+ return ""
+ cards = []
+ for s in sections:
+ n = s["end_turn_id"] - s["start_turn_id"] + 1
+ pct = round(n / max(n_turns, 1) * 100)
+ cards.append(
+ f''
+ f''
+ f'{_h(s["label"])}'
+ f'{_h(s["start_time"])}–{_h(s["end_time"])}'
+ f'Turns {s["start_turn_id"]}–'
+ f'{s["end_turn_id"]} ({n} turns · {pct}%)'
+ f''
+ f''
+ f''
+ f''
)
- except Exception:
- pass
-
-
-def _seconds_to_hms(s: float) -> str:
- return str(timedelta(seconds=int(s)))
-
-
-def _push_log(state: dict, entry: dict) -> dict:
- logs = list(state.get("agent_logs", []))
- logs.append(entry)
- state["agent_logs"] = logs[-10:]
- return state
-
+ return (
+ f''
+ f''
+ + _stat_chip(str(n_turns), "Turns", "#4338ca", "#eef2ff")
+ + _stat_chip(str(len(sections)), "Sections", "#065f46", "#dcfce7")
+ + _stat_chip(str(n_speakers), "Speakers", "#b45309", "#fffbeb")
+ + _stat_chip(f"{elapsed}s", "Agent 0", "#7c3aed", "#faf5ff")
+ + f''
+ f'{"".join(cards)}'
+ f''
+ )
-# ===========================================================================
-# CODING RENDER HELPERS
-# ===========================================================================
def _segment_label(seg: dict, codings: dict) -> str:
sid = seg["segment_id"]
- ep = sid.split("_ep")[-1] if "_ep" in sid else sid[-4:]
c = codings.get(sid, {})
did = c.get("dimension_id") or seg.get("dimension_id") or "?"
- sec = c.get("secondary_dimension_id")
coded = "✓" if c.get("dimension_id") else "○"
flag = " ⚠" if seg.get("uncertain") else ""
- multi = f"+{sec}" if sec else ""
- return f"{coded} ep{ep} [{did}{multi}]{flag}"
+ return f"{coded} [{did}]{flag} — {sid[-12:]}"
def _proposal_md(seg: dict) -> str:
@@ -1087,500 +1015,503 @@ def _proposal_md(seg: dict) -> str:
if seg.get("confident"):
tags.append("✅ Confident")
if seg.get("uncertain"):
- tags.append(f"⚠️ Uncertain — {seg.get('uncertainty_note', '')}")
+ tags.append(f"⚠️ Uncertain — {seg.get('uncertainty_note','')}")
if sec_did:
- tags.append(f"🔗 Multi-dimensional: {did} + {sec_did}")
+ tags.append(f"🔗 Multi-dim: {did} + {sec_did}")
return ("\n\n".join(lines) + ("\n\n" + " ".join(tags) if tags else "")).strip()
-CODING_EMPTY = (
- "",
- gr.update(choices=[], value=None),
- "",
- "",
- gr.update(value="", visible=False),
- gr.update(choices=DIM_CHOICES, value=None),
- "",
- gr.update(choices=SEC_DIM_CHOICES, value=SEC_NONE),
- "",
- gr.update(visible=False),
-)
-
-
-def _render_coding(state: dict) -> tuple:
- segs = _current_section_segments(state)
- codings = state.get("codings", {})
- cidx = state.get("coding_idx", 0)
- speaker_map = state.get("speakers", {})
-
- if not segs:
- return CODING_EMPTY
-
- seg = segs[min(cidx, len(segs) - 1)]
- sid = seg["segment_id"]
- existing = codings.get(sid, {})
- saved = existing.get("dimension_id", "")
- choice = next((c for c in DIM_CHOICES if c.startswith(saved)), None)
-
- saved_sec = existing.get("secondary_dimension_id")
- sec_choice = (
- next((c for c in DIM_CHOICES if c.startswith(saved_sec)), SEC_NONE)
- if saved_sec else SEC_NONE
+def _uncertainty_html(seg: dict) -> str:
+ if not seg.get("uncertain"):
+ return ""
+ note = _h(seg.get("uncertainty_note") or "")
+ return (
+ f''
+ f'⚠'
+ f'AI flagged uncertain'
+ f' — {note}'
+ f''
)
- all_done = len(codings) >= len(segs) and all(
- codings.get(s["segment_id"], {}).get("dimension_id") for s in segs
- )
- labels = [_segment_label(s, codings) for s in segs]
+def _dim_desc_html(choice: str) -> str:
+ if not choice:
+ return ""
+ did = DIM_ID_FROM_CHOICE.get(choice, "")
+ desc = DIM_DESC_FROM_ID.get(did, "")
+ if not desc:
+ return ""
return (
- _coding_progress_html(state),
- 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 ""),
- gr.update(choices=SEC_DIM_CHOICES, value=sec_choice),
- existing.get("comment", ""),
- gr.update(visible=all_done),
+ f'{_h(desc)}'
)
-# ===========================================================================
-# PAGE NAVIGATION HELPER
-# ===========================================================================
-
-_PAGE_NAMES = ["welcome", "setup", "sections", "pipeline", "done", "agreement", "library"]
+def _coding_progress_html(state: dict) -> str:
+ sections = state.get("sections", [])
+ idx = state.get("section_idx", 0)
+ segs = _current_section_segments(state)
+ codings = state.get("codings", {})
+ cidx = state.get("coding_idx", 0)
+ if not segs:
+ return ""
+ coded = sum(1 for s in segs if codings.get(s["segment_id"], {}).get("dimension_id"))
+ total = len(segs)
+ pct = int(coded / total * 100) if total else 0
+ sec = sections[idx] if idx < len(sections) else {}
+ all_coded = sum(1 for v in codings.values() if v.get("dimension_id"))
+ all_segs = sum(
+ len(state.get("section_segments_coded", {}).get(s["section_id"], []))
+ for s in sections
+ )
+ return (
+ f''
+ f''
+ f''
+ f'Section {idx+1}/{len(sections)} — {_h(sec.get("label",""))}'
+ f'Episode {min(cidx,total-1)+1} of {total}'
+ f''
+ f''
+ f''
+ f''
+ f''
+ f'{coded}/{total} coded this section'
+ f'{all_coded}/{all_segs} total'
+ f''
+ )
-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]
+CODING_EMPTY = (
+ "", gr.update(choices=[], value=None), "", "",
+ gr.update(value="", visible=False),
+ gr.update(choices=DIM_CHOICES, value=None), "",
+ gr.update(choices=SEC_DIM_CHOICES, value=SEC_NONE), "",
+ gr.update(visible=False),
+)
-# ===========================================================================
-# CALLBACKS
-# ===========================================================================
-# ── Process: Parse + Agent 0 combined ────────────────────────────────────────
+def _render_coding(state: dict) -> tuple:
+ segs = _current_section_segments(state)
+ codings = state.get("codings", {})
+ cidx = state.get("coding_idx", 0)
+ speaker_map = state.get("speakers", {})
+ if not segs:
+ return CODING_EMPTY
+ seg = segs[min(cidx, len(segs) - 1)]
+ sid = seg["segment_id"]
+ existing = codings.get(sid, {})
+ saved = existing.get("dimension_id", "")
+ choice = next((c for c in DIM_CHOICES if c.startswith(saved)), None)
+ saved_sec = existing.get("secondary_dimension_id")
+ sec_choice = (
+ next((c for c in DIM_CHOICES if c.startswith(saved_sec)), SEC_NONE)
+ if saved_sec else SEC_NONE
+ )
+ return (
+ _coding_progress_html(state),
+ gr.update(choices=[_segment_label(s, codings) for s in segs],
+ value=_segment_label(seg, codings)),
+ _format_turns_html(seg, speaker_map),
+ _proposal_md(seg),
+ gr.update(value=_uncertainty_html(seg), visible=seg.get("uncertain", False)),
+ gr.update(choices=DIM_CHOICES, value=choice),
+ _dim_desc_html(choice or ""),
+ gr.update(choices=SEC_DIM_CHOICES, value=sec_choice),
+ "",
+ gr.update(visible=True),
+ )
-def _parse_drive_choice(choice: str) -> tuple[str, str]:
- if not choice or "::" not in choice:
- raise gr.Error("Pick a transcript from Drive first.")
- file_id, file_name = choice.split("::", 1)
- return file_id, file_name
+# ──────────────────────────────────────────────────────────────────────────────
+# Agreement helpers (from v4)
+# ──────────────────────────────────────────────────────────────────────────────
-def fn_refresh_drive_transcripts(researcher_id: str):
- rid = (researcher_id or "").strip()
- if not rid:
- return (
- gr.update(choices=[], value=None, interactive=False),
- _status_card("Enter Researcher ID first, then refresh Drive files.", "warning"),
+def _kappa_summary_html(report: dict) -> str:
+ ac1 = report.get("ac1", 0)
+ kappa = report.get("kappa", 0)
+ ci = report.get("ac1_ci_95", [0, 0])
+ gate = report.get("gate_passed", False)
+ nseg = report.get("n_segments", 0)
+ color = "#15803d" if gate else "#be123c"
+ bg = "#dcfce7" if gate else "#fef2f2"
+ label = "Gate PASSED ✓" if gate else "Gate FAILED ✗"
+ return (
+ f''
+ f''
+ f'{label}'
+ f''
+ f'Gwet AC1: '
+ f'{ac1:.3f}'
+ f'95% CI: '
+ f'[{ci[0]:.3f}, {ci[1]:.3f}]'
+ f'Cohen κ: '
+ f'{kappa:.3f}'
+ f'Segments: '
+ f'{nseg}'
+ f''
+ )
+
+
+def _disagreement_html(report: dict, all_segs: list[dict]) -> str:
+ disags = report.get("disagreements", [])
+ disags = [d for d in disags if d.get("resolution_status", "unresolved") == "unresolved"]
+ if not disags:
+ return 'All disagreements resolved ✓'
+
+ seg_map = {s["segment_id"]: s for s in all_segs}
+ parts = [f''
+ f''
+ f'{len(disags)} unresolved disagreements']
+
+ for d in disags:
+ sid = d["segment_id"]
+ r1 = _h(d.get("r1_code", "?"))
+ r2 = _h(d.get("r2_code", "?"))
+ seg = seg_map.get(sid, {})
+ rat = _h(seg.get("rationale", ""))
+ parts.append(
+ f''
+ f''
+ f'{_h(sid)}'
+ f'R1: {r1}'
+ f'vs'
+ f'R2: {r2}'
+ f''
+ f'{rat}'
+ f''
)
+ parts.append('')
+ return "".join(parts)
+
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Drive / session handlers (from v4)
+# ──────────────────────────────────────────────────────────────────────────────
- register_researcher(rid)
+def fn_refresh_drive_transcripts(researcher_id: str, state: dict):
+ rid = (researcher_id or "").strip()
+ if not rid:
+ return gr.update(choices=[], value=None, interactive=False), \
+ _status_card("Enter Researcher ID first.", "warning")
try:
service = get_drive_service(rid)
if not service:
- return (
- gr.update(choices=[], value=None, interactive=False),
- _status_card(
- "Google Drive is not configured yet.",
- "warning",
- {
- "Needed secret": "GOOGLE_SERVICE_ACCOUNT_JSON",
- "Folder ID": "GOOGLE_DRIVE_FOLDER_ID",
- "Tip": "Copy the DRIVE DEBUG block from the logs if this should already be working.",
- },
- ),
- )
-
+ return gr.update(choices=[], value=None, interactive=False), \
+ _status_card("Google Drive not configured.", "warning")
files = list_transcripts(service)
if not files:
- return (
- gr.update(choices=[], value=None, interactive=False),
- _status_card(
- "No transcript files found in the configured Drive folder.",
- "warning",
- {"Tip": "If this is unexpected, copy the DRIVE DEBUG block from the logs."},
- ),
- )
-
+ return gr.update(choices=[], value=None, interactive=False), \
+ _status_card("No transcript files found.", "warning")
choices = [
- (f"{f['name']} · {f.get('modified_time', '')[:10]}", f"{f['id']}::{f['name']}")
+ (f"{f['name']} · {f.get('modified_time','')[:10]}", f"{f['id']}::{f['name']}")
for f in files
]
- return (
- gr.update(choices=choices, value=choices[0][1], interactive=True),
- _status_card("Drive connected. Select a transcript and click Process.", "success", {"Files": len(choices)}),
- )
+ return gr.update(choices=choices, value=choices[0][1], interactive=True), \
+ _status_card("Drive connected.", "success", {"Files": len(choices)})
except Exception as e:
- diag = format_drive_diagnostic("refresh_drive_transcripts", researcher_id=rid, error=e)
- print(diag, file=_sys.stderr)
- return (
- gr.update(choices=[], value=None, interactive=False),
- _status_card(
- "Drive check failed.",
- "error",
- {"Tip": "Copy the DRIVE DEBUG block below and send it with the issue."},
- diag,
- ),
- )
+ diag = format_drive_diagnostic("refresh", researcher_id=rid, error=e)
+ return gr.update(choices=[], interactive=False), \
+ _status_card("Drive failed.", "error", error_msg=diag)
def fn_load_previous_session(researcher_id: str, state: dict):
rid = (researcher_id or "").strip()
if not rid:
- return state, gr.update(), _status_card("Enter Researcher ID first.", "warning")
-
+ return state, _status_card("Enter Researcher ID first.", "warning")
try:
service = get_drive_service(rid)
if not service:
- return state, gr.update(), _status_card(
- "Drive not configured yet.",
- "warning",
- {"Tip": "Copy the DRIVE DEBUG block from the logs if this should already work."},
- )
-
+ return state, _status_card("Drive not configured.", "warning")
loaded = load_session_from_drive(service, rid)
if not loaded:
- return state, gr.update(), _status_card(
- "No previous Drive session found for this researcher.",
- "warning",
- {"Tip": "If you expected one, copy the DRIVE DEBUG block from the logs."},
- )
-
+ return state, _status_card("No previous session found.", "warning")
new_state = _empty_state()
new_state.update(loaded)
new_state["researcher_id"] = rid
- sid = new_state.get("session_id", "") or _auto_session_id(rid, "restored_session")
+ sid = new_state.get("session_id") or _auto_session_id(rid, "restored")
new_state["session_id"] = sid
+ return new_state, _status_card("Session loaded from Drive.", "success", {"Session": sid})
+ except Exception as e:
+ return state, _status_card("Load failed.", "error",
+ error_msg=format_drive_diagnostic("load", researcher_id=rid, error=e))
+
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Screener handlers
+# ──────────────────────────────────────────────────────────────────────────────
+
+def fn_run_screener(state: dict):
+ turns = state.get("turns", [])
+ if not turns:
+ return (state,
+ _status_card("No transcript loaded. Upload a transcript first.", "warning"),
+ "", "")
+
+ try:
+ result = screen_transcript(turns)
+ result_dict = result_to_dict(result)
+ state["screener_result"] = result_dict
+ state["stage"] = "screened"
+ _persist(state)
+
+ speaker_map = state.get("speakers", {})
+ summary_html = _screener_summary_html(result_dict)
+ turns_html = _screener_turns_html(result_dict, speaker_map)
+ windows_html = _candidate_windows_html(result_dict)
return (
- new_state,
- _status_card("Previous session loaded from Drive.", "success", {"Session ID": sid}),
+ state,
+ _status_card(
+ f"Screener complete — {result.flagged_turns} turns flagged, "
+ f"{len(result.candidate_windows)} candidate windows, "
+ f"~{result.estimated_llm_savings:.0%} estimated LLM savings.",
+ "success",
+ {"Total turns": result.total_turns,
+ "Flagged": result.flagged_turns,
+ "Windows": len(result.candidate_windows)},
+ ),
+ summary_html + turns_html,
+ windows_html,
)
except Exception as e:
- diag = format_drive_diagnostic("load_previous_session", researcher_id=rid, error=e)
- print(diag, file=_sys.stderr)
- return state, _status_card(
- "Could not load the Drive session.",
- "error",
- {"Tip": "Copy the DRIVE DEBUG block below and send it with the issue."},
- diag,
- )
+ return state, _status_card(f"Screener failed: {e}", "error"), "", ""
-def fn_process_with_source(drive_choice: str, researcher_id: str, state: dict):
- """Wrapper: Drive-only transcript selection with automatic session IDs."""
- temp_path: Path | None = None
- service = None
- rid = (researcher_id or "").strip()
- if not rid:
- raise gr.Error("Enter your Researcher ID first.")
- if not drive_choice:
- raise gr.Error("Choose a transcript from Drive first.")
+# ──────────────────────────────────────────────────────────────────────────────
+# Lexicon handlers
+# ──────────────────────────────────────────────────────────────────────────────
+def fn_load_lexicon_view():
try:
- service = get_drive_service(rid)
- if not service:
- diag = format_drive_diagnostic("process_drive_file", researcher_id=rid)
- print(diag, file=_sys.stderr)
- raise gr.Error("Drive is not configured. Copy the DRIVE DEBUG block from the logs.")
-
- file_id, file_name = _parse_drive_choice(drive_choice)
- session_id = _auto_session_id(rid, file_name)
- text = read_file_from_drive(service, file_id)
- suffix = Path(file_name).suffix or ".txt"
- temp_path = Path(tempfile.mktemp(prefix="drive_transcript_", suffix=suffix))
- temp_path.write_text(text, encoding="utf-8")
-
- effective_file = type("DriveFile", (), {"name": str(temp_path)})()
- except gr.Error:
- raise
- except Exception as e:
- file_id, file_name = ("", "")
- try:
- file_id, file_name = _parse_drive_choice(drive_choice)
- except Exception:
- pass
- diag = format_drive_diagnostic(
- "process_drive_file",
- researcher_id=rid,
- file_id=file_id,
- file_name=file_name,
- error=e,
+ data = load_full_lexicon()
+ t1_html = _lexicon_tier1_html(data["tier1"])
+ t2_html = _lexicon_tier2_html(data["tier2"])
+ t3_html = _lexicon_tier3_html(data["tier3"])
+ n_t1 = sum(len(c.get("terms", [])) for c in data["tier1"].get("categories", []))
+ n_t2 = sum(len(e.get("terms", [])) for e in data["tier2"].get("entries", []))
+ n_t3 = sum(1 for c in data["tier3"].get("candidates", [])
+ if not c.get("approved") and not c.get("rejected"))
+ return (
+ t1_html, t2_html, t3_html,
+ _status_card(
+ "Lexicon loaded.",
+ "success",
+ {"Tier 1 terms": n_t1, "Tier 2 validated": n_t2, "Tier 3 pending": n_t3},
+ ),
)
- print(diag, file=_sys.stderr)
- raise gr.Error("Drive file could not be read. Copy the DRIVE DEBUG block from the logs.")
+ except Exception as e:
+ return "", "", "", _status_card(f"Could not load lexicon: {e}", "error")
+
- final_state: dict | None = None
+def fn_add_tier2(category_id: str, label: str, phase: str,
+ terms_text: str, weight: float, researcher_id: str, note: str):
+ terms = [t.strip() for t in terms_text.replace(",", "\n").splitlines() if t.strip()]
+ if not terms:
+ return _status_card("Enter at least one term.", "warning"), "", ""
try:
- for out in fn_process(effective_file, session_id, researcher_id, state):
- if isinstance(out, tuple) and out and isinstance(out[0], dict):
- final_state = out[0]
- yield out
- finally:
- if temp_path and temp_path.exists():
- try:
- temp_path.unlink()
- except Exception:
- pass
-
- # Persist lightweight state snapshot to Drive for resume.
- if final_state and (service or get_drive_service(rid)):
- try:
- svc = service or get_drive_service(rid)
- if svc:
- slim = {k: v for k, v in final_state.items() if k not in {"turns", "kappa_report"}}
- write_session_to_drive(
- svc,
- final_state.get("researcher_id", rid),
- final_state.get("session_id", session_id),
- slim,
- )
- except Exception:
- pass
+ add_tier2_term(
+ terms=terms, category_id=category_id or "TIER2_custom",
+ label=label or "Custom term", phase=phase or "monitoring",
+ weight=float(weight), added_by=researcher_id or "researcher", note=note,
+ )
+ data = load_full_lexicon()
+ t2_html = _lexicon_tier2_html(data["tier2"])
+ return (
+ _status_card(f"Added {len(terms)} term(s) to Tier 2.", "success",
+ {"Terms": ", ".join(terms[:5])}),
+ t2_html, "",
+ )
+ except Exception as e:
+ return _status_card(f"Failed: {e}", "error"), "", ""
-def fn_process(file_obj, session_id: str, researcher_id: str, state: dict):
- """Generator: parse transcript then run Agent 0. Navigates to sections page."""
- if file_obj is None:
- raise gr.Error("Choose a transcript from Drive first.")
- if not researcher_id.strip():
- raise gr.Error("Enter your Researcher ID (e.g. R1).")
- session_id = session_id.strip() or _auto_session_id(researcher_id, getattr(file_obj, "name", "drive_transcript"))
+def fn_approve_candidate(term: str, researcher_id: str):
+ if not term.strip():
+ return _status_card("Enter a term to approve.", "warning"), ""
+ try:
+ approve_tier3_candidate(term.strip(), approved_by=researcher_id or "researcher")
+ data = load_full_lexicon()
+ return (
+ _status_card(f"'{term}' approved and moved to Tier 2.", "success"),
+ _lexicon_tier3_html(data["tier3"]),
+ )
+ except Exception as e:
+ return _status_card(f"Failed: {e}", "error"), ""
- _BTN_BUSY = gr.update(interactive=False, value="⏳ Processing…")
- _BTN_FREE = gr.update(interactive=True, value="⚡ Process Transcript →")
- def _setup_yield(msg, status="processing", details=None, btn=None):
+def fn_reject_candidate(term: str, researcher_id: str, note: str):
+ if not term.strip():
+ return _status_card("Enter a term to reject.", "warning"), ""
+ try:
+ reject_tier3_candidate(term.strip(), rejected_by=researcher_id or "researcher", note=note)
+ data = load_full_lexicon()
return (
- state,
- _status_card(msg, status, details),
- *_show("setup"),
- "", # sections_display_html
- "", # sections_labels_box
- _agent_log_html(state.get("agent_logs", [])),
- btn if btn is not None else _BTN_BUSY,
+ _status_card(f"'{term}' rejected.", "success"),
+ _lexicon_tier3_html(data["tier3"]),
)
+ except Exception as e:
+ return _status_card(f"Failed: {e}", "error"), ""
+
+
+# ──────────────────────────────────────────────────────────────────────────────
+# SSRL tagging handler (for Review tab)
+# ──────────────────────────────────────────────────────────────────────────────
+
+def fn_save_ssrl_tag(seg_label: str, ssrl_choice: str, state: dict):
+ segs = _current_section_segments(state)
+ codings = state.get("codings", {})
+ cidx = state.get("coding_idx", 0)
+ if not segs:
+ return state, ""
+ seg = segs[min(cidx, len(segs) - 1)]
+ sid = seg["segment_id"]
+ phase = SSRL_ID_FROM_CHOICE.get(ssrl_choice, "NONE")
+ ssrl = dict(state.get("ssrl_codings", {}))
+ ssrl[sid] = phase
+ state["ssrl_codings"] = ssrl
+ _persist(state)
+ return state, _status_card(f"SSRL tag '{phase}' saved for {sid}.", "success")
- # Immediately disable the button to prevent double-submission
- yield _setup_yield("Loading transcript from Drive…")
- t0 = time.perf_counter()
+# ──────────────────────────────────────────────────────────────────────────────
+# Transcript processing (from v4, generator)
+# ─────────────────────────────────────────────────────────────────────────���────
+
+def fn_process_local(file, researcher_id: str, state: dict):
+ """Process an uploaded local transcript file."""
+ rid = (researcher_id or "").strip()
+ if not file:
+ yield state, _status_card("No file selected.", "warning"), _pipeline_status_html(state)
+ return
try:
- yield _setup_yield("Parsing transcript…", details={"Session": session_id})
- turns = parse_transcript(file_obj.name)
+ path = Path(file.name) if hasattr(file, "name") else Path(str(file))
+ text = path.read_text(encoding="utf-8", errors="replace")
+ turns = parse_transcript(text)
except Exception as e:
- raise gr.Error(f"Could not parse transcript: {e}") from e
+ yield state, _status_card(f"Parse failed: {e}", "error"), _pipeline_status_html(state)
+ return
- if len(turns) < 5:
- 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())
+ if not turns:
+ yield state, _status_card("No turns found in transcript.", "error"), _pipeline_status_html(state)
+ return
+
+ sid = _auto_session_id(rid, path.name)
+ speakers = _assign_speakers(turns)
+ new_state = _empty_state()
+ new_state.update({"session_id": sid, "researcher_id": rid,
+ "turns": turns, "speakers": speakers, "stage": "upload"})
+ (SESSIONS_ROOT / sid).mkdir(parents=True, exist_ok=True)
+ (SESSIONS_ROOT / sid / "turns.json").write_text(
+ json.dumps(turns, indent=2, ensure_ascii=False), encoding="utf-8"
+ )
+ _persist(new_state)
- new_state = _empty_state()
- new_state.update({
- "session_id": session_id.strip(),
- "researcher_id": researcher_id.strip(),
- "turns": turns,
- "speakers": speaker_map,
- "stage": "parsed",
- })
- log_entry = _make_log_entry(
- "Transcript Parser", rt,
- turns=len(turns), speakers=len(speakers),
- system_prompt_preview="(rule-based parser — no LLM call)",
+ yield (
+ new_state,
+ _status_card("Transcript loaded.", "success",
+ {"Turns": len(turns), "Speakers": len(speakers), "Session": sid}),
+ _pipeline_status_html(new_state),
)
- new_state = _push_log(new_state, log_entry)
- d = SESSIONS_ROOT / session_id.strip()
- d.mkdir(parents=True, exist_ok=True)
- (d / "parsed_turns.json").write_text(
+
+def fn_process_with_source(drive_choice: str, researcher_id: str, state: dict):
+ rid = (researcher_id or "").strip()
+ if not drive_choice:
+ yield state, _status_card("Select a transcript first.", "warning"), _pipeline_status_html(state)
+ return
+ try:
+ file_id, file_name = drive_choice.split("::", 1)
+ service = get_drive_service(rid)
+ text = read_file_from_drive(service, file_id)
+ turns = parse_transcript(text)
+ except Exception as e:
+ yield state, _status_card(f"Drive load failed: {e}", "error"), _pipeline_status_html(state)
+ return
+
+ sid = _auto_session_id(rid, file_name)
+ speakers = _assign_speakers(turns)
+ new_state = _empty_state()
+ new_state.update({"session_id": sid, "researcher_id": rid,
+ "turns": turns, "speakers": speakers, "stage": "upload"})
+ (SESSIONS_ROOT / sid).mkdir(parents=True, exist_ok=True)
+ (SESSIONS_ROOT / sid / "turns.json").write_text(
json.dumps(turns, indent=2, ensure_ascii=False), encoding="utf-8"
)
- duration = _seconds_to_hms(turns[-1]["start_seconds"] - turns[0]["start_seconds"])
-
- # Confirm parse before starting LLM work
- yield _setup_yield(
- f"Parsed {len(turns)} turns from {len(speakers)} speaker(s). Preparing Agent 0…",
- "processing",
- {"Turns": len(turns), "Speakers": ", ".join(speakers), "Duration": duration},
+ _persist(new_state)
+ yield (
+ new_state,
+ _status_card("Drive transcript loaded.", "success",
+ {"Turns": len(turns), "Speakers": len(speakers), "Session": sid}),
+ _pipeline_status_html(new_state),
)
- # ── Estimate LLM cost BEFORE the call (no extra network hit) ─────────────
- # Mirrors agent0_sectioner._format_turns_compact() tiers:
- # > 600 turns → every other turn shown (×0.5), 30 chars → ~9 tok/turn
- # > 400 turns → every turn, 40 chars → ~12 tok/turn
- # > 200 turns → every turn, 60 chars → ~16 tok/turn
- # ≤ 200 turns → every turn, 120 chars → ~22 tok/turn
- n_t = len(turns)
- if n_t > 600:
- tok_per_turn = 9; effective_turns = n_t // 2
- elif n_t > 400:
- tok_per_turn = 12; effective_turns = n_t
- elif n_t > 200:
- tok_per_turn = 16; effective_turns = n_t
- else:
- tok_per_turn = 22; effective_turns = n_t
- est_in_tok = effective_turns * tok_per_turn + 700 # +700 for system prompt
- est_out_tok = 900 # sections JSON is typically 500–1200 tokens
- # 35 tok/s observed throughput on HF shared inference; 20s network buffer
- est_timeout = max(45, int((est_in_tok + est_out_tok) / 35 + 20))
-
- # First heartbeat — LLM call starting
- def _hb(elapsed: int, spin_i: int):
- return (
- new_state,
- _llm_progress_html(
- f"Agent 0 — Structural Segmenter: analysing {len(turns)} turns…",
- elapsed, est_timeout, est_in_tok, circuit_state(), spin_i,
- ),
- *_show("setup"),
- "", # sections_display_html (empty while processing)
- "", # sections_labels_box
- _agent_log_html(new_state["agent_logs"]),
- _BTN_BUSY,
- )
- yield _hb(0, 0)
+# ──────────────────────────────────────────────────────────────────────────────
+# Agent 0 — sectioning (generator)
+# ──────────────────────────────────────────────────────────────────────────────
- # ── Run Agent 0 in a daemon thread so Gradio stays responsive ────────────
- result_q: _queue.Queue = _queue.Queue()
+def fn_run_agent0(state: dict):
+ turns = state.get("turns", [])
+ if not turns:
+ yield state, _status_card("Load a transcript first.", "warning"), _pipeline_status_html(state)
+ return
- def _run_agent0():
- try:
- res = run_sectioning(turns=new_state["turns"],
- session_id=new_state["session_id"])
- result_q.put(("ok", res))
- except Exception as exc:
- result_q.put(("err", exc))
-
- thread = threading.Thread(target=_run_agent0, daemon=True)
- thread.start()
- t_llm = time.perf_counter()
- spin_i = 1
-
- # Heartbeat: yield progress every 2 s while the LLM call is in flight
- while thread.is_alive():
- time.sleep(2)
- elapsed = int(time.perf_counter() - t_llm)
- yield _hb(elapsed, spin_i)
- spin_i += 1
+ yield (state,
+ _loading_card("Agent 0 — detecting structural sections…",
+ f"Processing {len(turns)} turns"),
+ _pipeline_status_html(state))
- # ── Collect result ────────────────────────────────────────────────────────
- outcome, payload = result_q.get()
- if outcome == "err":
- raise gr.Error(f"Section detection failed: {payload}") from payload
+ t0 = time.time()
+ try:
+ result = run_sectioning(turns, state.get("session_id", ""))
+ except Exception as e:
+ yield state, _status_card(f"Agent 0 failed: {e}", "error"), _pipeline_status_html(state)
+ return
- result = payload
- sections = result["sections"]
- if not sections:
- raise gr.Error("Agent 0 returned no sections — try again.")
-
- from agent0_sectioner import build_system_prompt, load_dimension_labels
- sys_prev = build_system_prompt(load_dimension_labels())[:120]
- agent0_rt = round(time.perf_counter() - t_llm, 1)
-
- new_state = dict(new_state)
- new_state.update({
- "sections": sections,
- "section_stages": {s["section_id"]: "pending" for s in sections},
- "stage": "sectioned",
- "_agent0_overview": result.get("session_overview", ""),
- })
- log2 = _make_log_entry(
- "Agent 0 — Structural Segmenter", agent0_rt,
- sections_proposed=len(sections),
- warnings=len(result.get("warnings", [])),
- system_prompt_preview=sys_prev,
- )
- new_state = _push_log(new_state, log2)
+ sections = result.get("sections", [])
+ elapsed = round(time.time() - t0, 1)
+ speakers = state.get("speakers", {})
+ new_state = dict(state)
+ new_state["sections"] = sections
+ new_state["stage"] = "sectioned"
+ d = _session_dir(new_state)
+ d.mkdir(parents=True, exist_ok=True)
(d / "sections_proposed.json").write_text(
json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8"
)
+ new_state = _push_log(new_state, _make_log_entry(
+ "Agent 0", elapsed, sections=len(sections), turns=len(turns)
+ ))
+ _persist(new_state)
- overview = result.get("session_overview", "")
- sections_md = (
- "| # | Label | Turns | Time |\n|---|---|---|---|\n"
- + "\n".join(
- f"| {s['section_id']} | **{s['label']}** | "
- f"{s['start_turn_id']}–{s['end_turn_id']} | "
- f"{s['start_time']}–{s['end_time']} |"
- for s in sections
- )
- + (f"\n\n*{overview}*" if overview else "")
- )
- # Pre-fill with "s01: Label" format so the mapping is unambiguous
- labels_txt = "\n".join(f"{s['section_id']}: {s['label']}" for s in sections)
-
- if result.get("warnings"):
- gr.Warning("Coverage warnings — check the section table.")
- gr.Info(f"Ready: {len(turns)} turns · {len(sections)} sections detected in {agent0_rt}s.")
-
- # Build the rich sections HTML — pass turns so sections are expandable
- sec_html = _sections_html(sections, len(turns), agent0_rt, len(speakers),
- all_turns=turns)
-
+ sec_html = _sections_html(sections, len(turns), elapsed, len(speakers), turns)
yield (
new_state,
- _status_card( # shown briefly, then page switches
- "Agent 0 done — review sections.", "success",
- {"Turns": len(turns), "Sections": len(sections), "Time": f"{agent0_rt}s"},
- ),
- *_show("sections"), # ← navigate to sections page
- sec_html, # rich HTML card + visual grid
- labels_txt, # pre-fill the label editor
- _agent_log_html(new_state["agent_logs"]),
- _BTN_FREE, # re-enable process button
+ _status_card("Agent 0 done.", "success",
+ {"Turns": len(turns), "Sections": len(sections), "Time": f"{elapsed}s"}),
+ _pipeline_status_html(new_state),
)
-# ── Confirm sections ──────────────────────────────────────────────────────────
-
def fn_confirm_sections(labels_text: str, state: dict):
- """
- Generator: immediately shows a 'confirming' state (so the user knows
- their click registered), then navigates to the pipeline page.
- """
sections = state.get("sections", [])
if not sections:
- raise gr.Error("No sections to confirm — process a transcript first.")
-
- _BUSY_HTML = (
- ''
- ''
- '◑'
- 'Saving section labels and loading pipeline…'
- ''
- ''
- 'Please wait — this takes only a moment.'
- ''
- )
+ return state, _status_card("No sections to confirm.", "warning"), _pipeline_status_html(state)
- # ── Yield 1: immediate feedback, stay on sections page ────────────────────
- yield (
- state,
- *_show("sections"),
- gr.update(value=_BUSY_HTML), # sections_display_html
- gr.update(interactive=False, value="⏳ Saving…"), # confirm_sections_btn
- gr.update(visible=True), # col_run_all_boundaries (Column — visible only)
- gr.update(visible=False), # col_boundary_review
- gr.update(visible=False), # col_coding
- )
-
- # ── Process (fast: no LLM, just in-memory + disk) ─────────────────────────
- # Parse "s01: My Label" or plain "My Label" (both accepted)
raw_lines = [l.strip() for l in labels_text.strip().splitlines() if l.strip()]
labels = []
for line in raw_lines:
- # Strip "sXX: " or "sXX:" prefix if present
if ":" in line:
prefix, _, rest = line.partition(":")
if prefix.strip().lower().startswith("s") and prefix.strip()[1:].isdigit():
@@ -1591,1547 +1522,737 @@ def fn_confirm_sections(labels_text: str, state: dict):
confirmed = [dict(s, label=labels[i] if i < len(labels) else s["label"])
for i, s in enumerate(sections)]
- if len(labels) != len(sections):
- gr.Warning(
- f"Label count mismatch ({len(labels)} labels for {len(sections)} sections) — "
- f"AI labels used for any extras."
- )
-
new_state = dict(state)
- new_state.update({
- "sections": confirmed,
- "section_idx": 0,
- "section_stages": {s["section_id"]: "pending" for s in confirmed},
- "section_a1a_results": {},
- "stage": "coding",
- })
-
+ new_state["sections"] = confirmed
+ new_state["section_idx"] = 0
+ new_state["section_stages"] = {s["section_id"]: "pending" for s in confirmed}
d = _session_dir(new_state)
+ d.mkdir(parents=True, exist_ok=True)
(d / "sections_confirmed.json").write_text(
- json.dumps(confirmed, indent=2, ensure_ascii=False), encoding="utf-8"
+ json.dumps({"sections": confirmed}, indent=2, ensure_ascii=False), encoding="utf-8"
)
_persist(new_state)
- gr.Info(f"{len(confirmed)} sections confirmed. Click 'Detect Episode Boundaries' to continue.")
- print(f"[Confirm Sections] {len(confirmed)} sections saved for session {new_state['session_id']}")
-
- # ── Yield 2: navigate to pipeline page ────────────────────────────────────
- yield (
- new_state,
- *_show("pipeline"),
- gr.update(value=""), # sections_display_html (leaving)
- gr.update(interactive=True, value="Confirm Sections →"), # reset button for if user navigates back
- gr.update(visible=True), # col_run_all_boundaries
- gr.update(visible=False), # col_boundary_review
- gr.update(visible=False), # col_coding
- )
+ labels_txt = "\n".join(f"{s['section_id']}: {s['label']}" for s in confirmed)
+ return (new_state,
+ _status_card("Sections confirmed.", "success", {"Count": len(confirmed)}),
+ _pipeline_status_html(new_state))
-# ── Agent 1a — parallel boundary detection ───────────────────────────────────
+# ──────────────────────────────────────────────────────────────────────────────
+# Pipeline — boundaries + coding (generator)
+# ──────────────────────────────────────────────────────────────────────────────
-def fn_run_all_boundaries(state: dict):
+def fn_run_pipeline(state: dict):
sections = state.get("sections", [])
- if not sections:
- raise gr.Error("Confirm sections first.")
- if not state.get("turns"):
- raise gr.Error("No parsed turns — parse the transcript first.")
-
- n = len(sections)
- session_overview = state.get("_agent0_overview", "")
- collected = {}
- pipeline_stats_html = ""
-
- def _a1a_banner(done: int, total: int, status: str = "running") -> str:
- pct = int(done / total * 100) if total else 0
- color = "#4338ca" if status == "running" else "#065f46" if status == "done" else "#be123c"
- icon = "⏳" if status == "running" else "✓" if status == "done" else "✗"
- return (
- f''
- f''
- f'{icon}'
- f'Agent 1a — Boundary Detector'
- f''
- f'{done}/{total} sections · {pct}%'
- f''
- f''
- f''
- f''
- f'Parallel map pattern (Dean & Ghemawat 2004) · '
- f'Basis: Schegloff (2007) adjacency pairs · '
- f'Krippendorff (2004) unitising precedes categorising'
- f''
- )
-
- # Initial yield — show banner immediately
- yield (
- state,
- f"⏳ Running Agent 1a on {n} section(s) (max 3 concurrent)…",
- "",
- gr.update(visible=False),
- gr.update(visible=False, value=""),
- gr.update(visible=False, value=""),
- "",
- _agent_log_html(state.get("agent_logs", [])),
- _a1a_banner(0, n, "running"),
- gr.update(value=""), # episode_dialogue_html — clear while processing
- )
-
- pstats = PipelineStats(agent_name="Agent 1a — Boundary Detector", n_sections=n)
-
- try:
- for sr, pstats in run_boundaries_parallel(
- sections=sections,
- all_turns=state["turns"],
- session_id=state["session_id"],
- session_overview=session_overview,
- ):
- if sr.success:
- collected[sr.section_id] = sr.result
- else:
- gr.Warning(f"Section {sr.section_id} failed: {sr.error}")
-
- processed = len(pstats.results)
- failed_sids = {x.section_id for x in pstats.results if not x.success}
- prog_lines = []
- for s in sections:
- sid = s["section_id"]
- res = collected.get(sid)
- failed = sid in failed_sids
- if res:
- b = len(res.get("boundaries", []))
- e = len(res.get("segments", []))
- prog_lines.append(f"✓ **{sid}** {s['label']} — {b} boundaries → {e} episodes")
- elif failed:
- prog_lines.append(f"✗ **{sid}** {s['label']} — ERROR")
- else:
- prog_lines.append(f"⏳ **{sid}** {s['label']}…")
-
- status_md = f"**{processed}/{n} sections complete**\n\n" + "\n\n".join(prog_lines)
- pipeline_stats_html = render_pipeline_stats_html(pstats)
-
- yield (
- state,
- status_md,
- pipeline_stats_html,
- gr.update(visible=False),
- gr.update(visible=False, value=""),
- gr.update(visible=False, value=""),
- "",
- _agent_log_html(state.get("agent_logs", [])),
- _a1a_banner(processed, n, "running"),
- gr.update(value=""), # episode_dialogue_html — still processing
- )
+ turns = state.get("turns", [])
+ if not sections or not turns:
+ yield state, _status_card("Confirm sections first.", "warning"), _pipeline_status_html(state)
+ return
- except Exception as e:
- raise gr.Error(f"Parallel boundary detection failed: {e}") from e
-
- # All done — update state
- state = dict(state)
- n_success = len(collected)
- n_error = n - n_success
-
- for sec in sections:
- sid = sec["section_id"]
- result = collected.get(sid)
- if result:
- state["section_boundaries"][sid] = result["boundaries"]
- state["section_segments"][sid] = result["segments"]
- state["section_stages"][sid] = "boundaries"
- state.setdefault("section_a1a_results", {})[sid] = result
- else:
- state["section_stages"][sid] = "error"
-
- log = _make_log_entry(
- "Agent 1a — Boundary Detector (parallel)", round(pstats.parallel_wall_s, 1),
- sections_ok=n_success, sections_error=n_error,
- speedup=f"{pstats.speedup:.1f}x",
- total_est_tokens=pstats.total_estimated_tokens,
- )
- state = _push_log(state, log)
- _persist(state)
-
- sec = sections[0]
- turns = _turns_for_section(state["turns"], sec)
- result = collected.get(sec["section_id"], {})
- bounds = result.get("boundaries", [])
- ids_txt = ", ".join(str(b["after_turn_id"]) for b in bounds)
-
- status_final = (
- f"✓ {n_success}/{n} sections analysed "
- f"({pstats.parallel_wall_s:.0f}s parallel · {pstats.speedup:.1f}× speedup).\n\n"
- f"Review boundaries for each section below, then confirm to start coding."
- )
- if n_error:
- status_final += f"\n\n⚠ {n_error} section(s) failed — enter boundary turn IDs manually."
-
- gr.Info(f"Parallel analysis complete: {n_success}/{n} sections OK.")
- print(f"[Agent 1a] Complete: {n_success}/{n} OK in {pstats.parallel_wall_s:.1f}s "
- f"({pstats.speedup:.1f}× speedup)")
-
- # Build dialogue view for the first section to review
- first_result = collected.get(sec["section_id"], {})
- first_segs = first_result.get("segments", [])
- ep_dial_html = _episode_dialogue_html(first_segs, bounds, state["speakers"])
-
- yield (
- state,
- status_final,
- pipeline_stats_html,
- gr.update(visible=True),
- gr.update(visible=True, value=_episode_table_html(turns, bounds)),
- gr.update(visible=True, value=ids_txt),
- f"### Reviewing: {sec['label']} ({sec['section_id']})",
- _agent_log_html(state["agent_logs"]),
- _a1a_banner(n_success, n, "done" if n_error == 0 else "error"),
- ep_dial_html, # full dialogue view — researcher reads this before confirming
- )
-
-
-# ── Confirm boundaries + run Agent 1b ────────────────────────────────────────
-
-def fn_confirm_and_code(boundary_ids_text: str, state: dict):
- sec = _current_section(state)
- if not sec:
- raise gr.Error("No section loaded.")
-
- session_id = state.get("session_id") or _auto_session_id(state.get("researcher_id", ""), sec.get("label", "section"))
- state = dict(state)
- state["session_id"] = session_id
-
- turns = _turns_for_section(state["turns"], sec)
- valid_ids = {t["turn_id"] for t in turns}
- boundaries: list[dict] = []
+ q = _queue.Queue()
+ new_state = dict(state)
+ t0 = time.time()
+ done = threading.Event()
- for tok in boundary_ids_text.split(","):
- tok = tok.strip()
- if not tok:
- continue
+ def _worker():
try:
- tid = int(tok)
- except ValueError:
- raise gr.Error(f"'{tok}' is not a valid turn ID.")
- if tid not in valid_ids:
- raise gr.Error(
- f"Turn {tid} is outside this section "
- f"(valid: {min(valid_ids)}–{max(valid_ids)})."
+ result = run_coding_with_context(
+ turns=turns, sections=sections,
+ session_id=new_state.get("session_id", ""),
+ progress_queue=q,
)
- boundaries.append({"boundary_id": f"r_{tid}", "after_turn_id": tid,
- "confidence": "high", "boundary_signal": "researcher_defined",
- "rationale": "Set by researcher."})
- boundaries.sort(key=lambda b: b["after_turn_id"])
- segments = boundaries_to_segments(sec, turns, boundaries, session_id)
-
- if not segments:
- raise gr.Error("No segments produced — check your boundary turn IDs.")
-
- state["section_boundaries"][sec["section_id"]] = boundaries
- state["section_segments"][sec["section_id"]] = segments
-
- yield (
- state,
- _loading_card("Loading coding stage…", f"Agent 1b is preparing {len(segments)} episode(s) for coding."),
- gr.update(visible=False),
- *CODING_EMPTY,
- "",
- )
-
- agent1a_result = state.get("section_a1a_results", {}).get(sec["section_id"])
- t0 = time.perf_counter()
- try:
- coded, llm_stats = run_coding_with_context(
- section=sec,
- segments=segments,
- agent1a_result=agent1a_result,
- )
- except Exception as e:
- raise gr.Error(f"Agent 1b failed: {e}") from e
-
- rt = round(time.perf_counter() - t0, 1)
- n_uncertain = sum(1 for s in coded if s.get("uncertain"))
- state["section_segments_coded"][sec["section_id"]] = coded
- state["section_stages"][sec["section_id"]] = "coding"
- state["coding_idx"] = 0
- log = _make_log_entry(
- "Agent 1b — Dimension Coder", rt,
- segments_coded=len(coded),
- uncertain_flagged=n_uncertain,
- system_prompt_preview=f"Context chain: section={sec['label']}",
- user_prompt_preview=f"Code {len(segments)} segments",
- )
- state = _push_log(state, log)
-
- d = _session_dir(state)
- (d / f"segments_{sec['section_id']}.json").write_text(
- json.dumps(coded, indent=2, ensure_ascii=False), encoding="utf-8"
- )
-
- msg = f"✓ {len(coded)} segments coded ({rt}s)."
- if n_uncertain:
- msg += f" **{n_uncertain} flagged ⚠ — review these first.**"
- gr.Info(f"{len(coded)} segments coded. {n_uncertain} uncertain.")
-
- yield state, msg, gr.update(visible=True), *_render_coding(state), _agent_log_html(state["agent_logs"])
-
-
-# ── Navigate segments ─────────────────────────────────────────────────────────
-
-def fn_navigate(direction: int, dim_choice: str, sec_choice: str, comment: str, state: dict):
- segs = _current_section_segments(state)
- if not segs:
- return state, *_render_coding(state)
- idx = state.get("coding_idx", 0)
- codings = dict(state.get("codings", {}))
- sid = segs[idx]["segment_id"]
- if dim_choice:
- codings[sid] = {
- "dimension_id": DIM_ID_FROM_CHOICE[dim_choice],
- "secondary_dimension_id":SEC_ID_FROM_CHOICE.get(sec_choice or SEC_NONE),
- "comment": comment.strip(),
- }
- state = dict(state)
- state["codings"] = codings
- state["coding_idx"] = max(0, min(idx + direction, len(segs) - 1))
- return state, *_render_coding(state)
-
-
-def fn_jump(label: str, state: dict):
- segs = _current_section_segments(state)
- if not segs or not label:
- return state, *_render_coding(state)
- codings = state.get("codings", {})
- labels = [_segment_label(s, codings) for s in segs]
- state = dict(state)
- if label in labels:
- state["coding_idx"] = labels.index(label)
- return state, *_render_coding(state)
-
-
-def fn_reveal(state: dict):
- segs = _current_section_segments(state)
- if not segs:
- return gr.update(visible=False)
- seg = segs[min(state.get("coding_idx", 0), len(segs) - 1)]
- return gr.update(value=_proposal_md(seg), visible=True)
-
-
-def fn_dim_desc(choice: str):
- return _dim_desc_html(choice or "")
-
-
-# ── Next section / finish ─────────────────────────────────────────────────────
-
-def fn_next_section(dim_choice: str, sec_choice: str, comment: str, state: dict):
- segs = _current_section_segments(state)
- codings = dict(state.get("codings", {}))
- idx = state.get("coding_idx", 0)
- if segs and dim_choice:
- sid = segs[min(idx, len(segs) - 1)]["segment_id"]
- codings[sid] = {
- "dimension_id": DIM_ID_FROM_CHOICE[dim_choice],
- "secondary_dimension_id":SEC_ID_FROM_CHOICE.get(sec_choice or SEC_NONE),
- "comment": comment.strip(),
- }
-
- new_state = dict(state)
- new_state["codings"] = codings
- sections = new_state.get("sections", [])
- sec_idx = new_state.get("section_idx", 0)
- cur_id = sections[sec_idx]["section_id"]
- new_state["section_stages"][cur_id] = "done"
- next_idx = sec_idx + 1
-
- if next_idx >= len(sections):
- # All done — navigate to done page
- new_state["stage"] = "complete"
- _write_coding_file(new_state)
- _persist(new_state)
- gr.Info("All sections coded! Download your coding file.")
- print(f"[Done] All {len(sections)} sections coded for session {new_state['session_id']}")
- return (
+ q.put({"type": "done", "result": result})
+ except Exception as e:
+ q.put({"type": "error", "msg": str(e)})
+ finally:
+ done.set()
+
+ threading.Thread(target=_worker, daemon=True).start()
+
+ spin_i = 0
+ while not done.is_set():
+ time.sleep(1.5)
+ elapsed = int(time.time() - t0)
+ circ = circuit_state()
+ yield (
new_state,
- *_show("done"),
- _section_cards_html(sections, new_state["section_stages"], sec_idx),
- "", # section_header_md
- gr.update(visible=False), # col_boundary_review
- gr.update(visible=False), # col_coding
- gr.update(value=""), # boundary_display_html
- gr.update(value=""), # boundary_ids_box
- gr.update(value=""), # episode_dialogue_html
+ _llm_progress_html("Running pipeline (boundaries + coding)…",
+ elapsed, 180, len(turns) * 500, circ, spin_i),
+ _pipeline_status_html(new_state),
)
+ spin_i += 1
- # More sections remain — populate boundary review for the next section
- new_state["section_idx"] = next_idx
- new_state["coding_idx"] = 0
- next_sec = sections[next_idx]
- n = next_sec["end_turn_id"] - next_sec["start_turn_id"] + 1
- hdr = (
- f"### Section {next_idx+1} of {len(sections)}: {next_sec['label']}\n"
- f"*{next_sec.get('summary','')}* · "
- f"turns {next_sec['start_turn_id']}–{next_sec['end_turn_id']} ({n} turns)"
+ try:
+ msg = q.get_nowait()
+ except _queue.Empty:
+ msg = {"type": "error", "msg": "Queue empty after done signal."}
+
+ if msg.get("type") == "error":
+ yield new_state, _status_card(f"Pipeline failed: {msg['msg']}", "error"), \
+ _pipeline_status_html(new_state)
+ return
+
+ result = msg["result"]
+ elapsed = round(time.time() - t0, 1)
+ coded_map = result.get("section_segments_coded", {})
+ n_segs = sum(len(v) for v in coded_map.values())
+
+ new_state["section_segments_coded"] = coded_map
+ new_state["codings"] = result.get("codings", {})
+ new_state["stage"] = "coded"
+ new_state = _push_log(new_state, _make_log_entry(
+ "Pipeline", elapsed, segments=n_segs, sections=len(sections)
+ ))
+ d = _session_dir(new_state)
+ d.mkdir(parents=True, exist_ok=True)
+ (d / "codings.json").write_text(
+ json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8"
)
_persist(new_state)
- result = new_state.get("section_a1a_results", {}).get(next_sec["section_id"], {})
- bounds = result.get("boundaries", [])
- next_segs = result.get("segments", [])
- turns = _turns_for_section(new_state["turns"], next_sec)
- ids_txt = ", ".join(str(b["after_turn_id"]) for b in bounds)
- ep_html = _episode_dialogue_html(next_segs, bounds, new_state["speakers"])
-
- gr.Info(f"Section {next_idx+1} of {len(sections)}: {next_sec['label']}")
- print(f"[Next Section] Moving to section {next_idx+1}: {next_sec['label']}")
- return (
+ yield (
new_state,
- *_show("pipeline"),
- _section_cards_html(sections, new_state["section_stages"], next_idx),
- hdr,
- gr.update(visible=True), # col_boundary_review
- gr.update(visible=False), # col_coding
- gr.update(value=_episode_table_html(turns, bounds)), # boundary_display_html
- gr.update(value=ids_txt), # boundary_ids_box
- ep_html, # episode_dialogue_html
+ _status_card("Pipeline complete.", "success",
+ {"Segments": n_segs, "Sections": len(sections), "Time": f"{elapsed}s"}),
+ _pipeline_status_html(new_state),
)
-# ── Download ──────────────────────────────────────────────────────────────────
+# ──────────────────────────────────────────────────────────────────────────────
+# Segment coding (manual, per-episode)
+# ──────────────────────────────────────────────���───────────────────────────────
-def _write_coding_file(state: dict) -> Path:
- all_segs: list[dict] = []
- for sec in state.get("sections", []):
- all_segs.extend(state["section_segments_coded"].get(sec["section_id"], []))
+def fn_save_coding(dim_choice: str, sec_choice: str, note: str, state: dict):
+ segs = _current_section_segments(state)
codings = state.get("codings", {})
- output = {
- "session_id": state["session_id"],
- "researcher_id": state["researcher_id"],
- "codings": [
- {
- "segment_id": s["segment_id"],
- "section_id": s.get("section_id", ""),
- "dimension_id": codings.get(s["segment_id"], {}).get("dimension_id", ""),
- "secondary_dimension_id":codings.get(s["segment_id"], {}).get("secondary_dimension_id"),
- "comment": codings.get(s["segment_id"], {}).get("comment", ""),
- }
- for s in all_segs
- ],
- }
- segs_all = {"segments": [{k: v for k, v in s.items() if k != "turns"} for s in all_segs]}
- d = _session_dir(state)
- (d / "segments_all.json").write_text(
- json.dumps(segs_all, indent=2, ensure_ascii=False), encoding="utf-8"
- )
- out = d / f"coding_{state['researcher_id']}.json"
- out.write_text(json.dumps(output, indent=2, ensure_ascii=False), encoding="utf-8")
- return out
-
-
-def fn_download(state: dict):
- if not state.get("sections"):
- raise gr.Error("No coding to download yet.")
- path = _write_coding_file(state)
- tmp = Path(tempfile.mktemp(suffix=f"_{path.name}"))
- tmp.write_bytes(path.read_bytes())
- return str(tmp)
+ cidx = state.get("coding_idx", 0)
+ if not segs or not dim_choice:
+ return state, "", _pipeline_status_html(state)
+ seg = segs[min(cidx, len(segs) - 1)]
+ sid = seg["segment_id"]
+ did = DIM_ID_FROM_CHOICE.get(dim_choice, "")
+ sec_id = SEC_ID_FROM_CHOICE.get(sec_choice or SEC_NONE)
+ codings = dict(codings)
+ codings[sid] = {"dimension_id": did, "secondary_dimension_id": sec_id,
+ "note": note, "coded_by": state.get("researcher_id", "")}
+ state["codings"] = codings
+ _persist(state)
+ return state, _status_card(f"Saved {did} for {sid}.", "success"), _pipeline_status_html(state)
-# ── Agreement ─────────────────────────────────────────────────────────────────
+def fn_nav_segment(direction: str, state: dict):
+ segs = _current_section_segments(state)
+ cidx = state.get("coding_idx", 0)
+ if not segs:
+ return state
+ if direction == "next":
+ cidx = min(cidx + 1, len(segs) - 1)
+ else:
+ cidx = max(cidx - 1, 0)
+ state["coding_idx"] = cidx
+ return state
-def fn_calculate_kappa(r2_file, state: dict):
- if r2_file is None:
- raise gr.Error("Upload your co-researcher's coding file first.")
- if not state.get("session_id"):
- raise gr.Error("Complete the Pipeline first — session ID not set.")
- d = _session_dir(state)
- r1_path = d / f"coding_{state['researcher_id']}.json"
- segs_path = d / "segments_all.json"
+def fn_nav_section(direction: str, state: dict):
+ secs = state.get("sections", [])
+ idx = state.get("section_idx", 0)
+ if direction == "next":
+ idx = min(idx + 1, len(secs) - 1)
+ else:
+ idx = max(idx - 1, 0)
+ state["section_idx"] = idx
+ state["coding_idx"] = 0
+ return state
- if not r1_path.exists():
- raise gr.Error("Your own coding file not found — download it from the Pipeline first.")
- if not segs_path.exists():
- raise gr.Error("Segments file not found — complete the coding pipeline first.")
- r2_path = d / "coding_R2.json"
- r2_path.write_bytes(Path(r2_file.name).read_bytes())
+# ──────────────────────────────────────────────────────────────────────────────
+# Agreement handlers
+# ──────────────────────────────────────────────────────────────────────────────
- t0 = time.perf_counter()
+def fn_calculate_kappa(r1_file, r2_file, state: dict):
+ if not r1_file or not r2_file:
+ return state, _status_card("Upload both R1 and R2 coding files.", "warning"), \
+ _pipeline_status_html(state)
try:
- report = calculate_kappa_report(
- session_id=state["session_id"],
- coding_r1_path=r1_path,
- coding_r2_path=r2_path,
- proposed_segments_path=segs_path,
- output_path=d / "kappa_report.json",
+ r1 = json.loads(Path(r1_file.name).read_text(encoding="utf-8"))
+ r2 = json.loads(Path(r2_file.name).read_text(encoding="utf-8"))
+ all_segs = []
+ for sec_segs in state.get("section_segments_coded", {}).values():
+ all_segs.extend(sec_segs)
+ report = calculate_kappa_report(r1, r2, all_segs)
+ state["kappa_report"] = report
+ state["stage"] = "agreed"
+ _persist(state)
+ d = _session_dir(state)
+ d.mkdir(parents=True, exist_ok=True)
+ (d / "kappa_report.json").write_text(
+ json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8"
)
+ summary = _kappa_summary_html(report)
+ disag_h = _disagreement_html(report, all_segs)
+ return state, _status_card("Kappa calculated.", "success"), _pipeline_status_html(state)
except Exception as e:
- raise gr.Error(f"Kappa calculation failed: {e}") from e
-
- rt = round(time.perf_counter() - t0, 1)
- gate = report.get("gate_passed", False)
- n_dis = len(report.get("segments_in_disagreement", []))
-
- state = dict(state)
- state["kappa_report"] = report
- log = _make_log_entry("Kappa Calculator", rt,
- kappa=round(report.get("overall_kappa", 0), 3),
- gate_passed=gate, disagreements=n_dis)
- state = _push_log(state, log)
+ return state, _status_card(f"Kappa failed: {e}", "error"), _pipeline_status_html(state)
- if gate:
- gr.Info(f"κ={report['overall_kappa']:.3f} — gate passed! {n_dis} disagreements to resolve.")
- else:
- gr.Warning(f"κ={report['overall_kappa']:.3f} — below 0.70 threshold.")
-
- dis_md = ""
- if n_dis:
- dis = report.get("segments_in_disagreement", [])
- rows = "| Segment | R1 | R2 | Agent 1b |\n|---|---|---|---|\n"
- for di in dis[:20]:
- rows += (
- f"| `{di['segment_id']}` "
- f"| {di.get('r1_dimension','?')} "
- f"| {di.get('r2_dimension','?')} "
- f"| {di.get('agent_dimension','?')} |\n"
- )
- if len(dis) > 20:
- rows += f"| *…{len(dis)-20} more* | | | |\n"
- dis_md = f"### Disagreements ({n_dis})\n\n{rows}"
- return (
- state,
- _kappa_html(report),
- dis_md,
- gr.update(visible=bool(n_dis)),
- _agent_log_html(state["agent_logs"]),
- )
+# ──────────────────────────────────────────────────────────────────────────────
+# Learning (Agent 2) handlers
+# ──────────────────────────────────────────────────────────────────────────────
-
-def fn_run_sequence_analysis(rater_choice: str, state: dict):
- if not state.get("session_id"):
- raise gr.Error("No session loaded — complete the Pipeline first.")
-
- d = _session_dir(state)
+def fn_load_pending_rules():
try:
- path = d / "coding_R2.json" if "R2" in rater_choice else d / f"coding_{state['researcher_id']}.json"
- if not path.exists():
- raise gr.Error(f"Coding file not found: {path.name}.")
- analysis = load_and_analyse(path, max_lag=3)
- except gr.Error:
- raise
+ rules = list_pending_rules()
+ if not rules:
+ return 'No pending rules.
'
+ parts = ['']
+ for r in rules:
+ rid = _h(r.get("rule_id", ""))
+ desc = _h(r.get("description", ""))
+ src = _h(r.get("source_sessions", ""))
+ parts.append(
+ f''
+ f'{rid}'
+ f'{desc}'
+ f''
+ f'From sessions: {src}'
+ f''
+ )
+ parts.append('')
+ return "".join(parts)
except Exception as e:
- raise gr.Error(f"Sequence analysis failed: {e}") from e
-
- if "error" in analysis:
- raise gr.Error(analysis["error"])
-
- stat = analysis.get("statistics", {})
- n_ep = stat.get("n_episodes", 0)
- n_tr = stat.get("n_transitions", 0)
- cats = stat.get("categories_used", [])
- entropy = stat.get("transition_entropy", 0.0)
- ent_max = stat.get("entropy_max", 0.0)
- sig_pos = stat.get("significant_pos", [])
- sig_neg = stat.get("significant_neg", [])
-
- ent_note = (
- f"**{entropy:.3f}** bits / max {ent_max:.3f} — "
- + ("high entropy: no strong sequential pattern"
- if ent_max > 0 and entropy / ent_max > 0.80
- else "moderate entropy: some transitions dominate"
- if ent_max > 0 and entropy / ent_max > 0.50
- else "low entropy: a few transitions strongly dominate")
- )
-
- warnings = analysis.get("sparse_warnings", [])
- warn_md = ""
- if warnings:
- warn_md = (
- f"\n\n*⚠ {len(warnings)} sparse cell(s): "
- f"{'; '.join(warnings[:3])}{'…' if len(warnings) > 3 else ''}*"
- )
+ return f'Error: {_h(str(e))}
'
- summary_md = (
- f"**{n_ep}** episodes · **{n_tr}** transitions · "
- f"**{len(cats)}** dimensions: `{'`, `'.join(cats)}` \n"
- f"Entropy: {ent_note} \n"
- f"**{len(sig_pos)}** significantly common · **{len(sig_neg)}** significantly rare"
- f"{warn_md}"
- )
- gr.Info(f"Sequence analysis: {n_ep} episodes, {len(sig_pos)} significant transitions.")
- return summary_md, render_transition_matrix_html(analysis), render_significant_transitions_html(analysis), gr.update(visible=True)
-
-
-def fn_download_seq_csv(rater_choice: str, state: dict):
- if not state.get("session_id"):
- raise gr.Error("No session loaded.")
- d = _session_dir(state)
- path = d / ("coding_R2.json" if "R2" in rater_choice else f"coding_{state['researcher_id']}.json")
- if not path.exists():
- raise gr.Error(f"Coding file not found: {path.name}")
- analysis = load_and_analyse(path)
- if "error" in analysis:
- raise gr.Error(analysis["error"])
- csv_str = seq_to_csv(analysis)
- tmp = Path(tempfile.mktemp(suffix=f"_transitions_{state['session_id']}.csv"))
- tmp.write_text(csv_str, encoding="utf-8")
- return str(tmp)
-
-
-def fn_resolve(seg_id: str, dim_choice: str, note: str, state: dict):
- if not seg_id.strip():
- raise gr.Error("Enter the segment ID.")
- if not dim_choice:
- raise gr.Error("Select the resolved dimension.")
- resolved = DIM_ID_FROM_CHOICE.get(dim_choice, dim_choice)
+def fn_approve_rule_action(rule_id: str):
+ if not rule_id.strip():
+ return _status_card("Enter a rule ID.", "warning"), fn_load_pending_rules()
try:
- resolve_disagreement(
- report_path=_session_dir(state) / "kappa_report.json",
- segment_id=seg_id.strip(), resolved_dimension=resolved,
- resolution_note=note.strip(),
- )
+ approve_rule(rule_id.strip())
+ return _status_card(f"Rule '{rule_id}' approved.", "success"), fn_load_pending_rules()
except Exception as e:
- raise gr.Error(f"Could not resolve: {e}") from e
- gr.Info(f"Resolved {seg_id.strip()} → {resolved}")
- return state, f"✓ `{seg_id.strip()}` → **{resolved}**"
+ return _status_card(f"Failed: {e}", "error"), fn_load_pending_rules()
-def fn_discard(seg_id: str, note: str, state: dict):
- if not seg_id.strip():
- raise gr.Error("Enter the segment ID.")
+def fn_reject_rule_action(rule_id: str, note: str):
+ if not rule_id.strip():
+ return _status_card("Enter a rule ID.", "warning"), fn_load_pending_rules()
try:
- discard_disagreement(
- report_path=_session_dir(state) / "kappa_report.json",
- segment_id=seg_id.strip(), discard_note=note.strip(),
- )
+ reject_rule(rule_id.strip(), note)
+ return _status_card(f"Rule '{rule_id}' rejected.", "success"), fn_load_pending_rules()
except Exception as e:
- raise gr.Error(f"Could not discard: {e}") from e
- gr.Info(f"Discarded {seg_id.strip()}")
- return state, f"Discarded `{seg_id.strip()}`"
+ return _status_card(f"Failed: {e}", "error"), fn_load_pending_rules()
-# ── Rules ─────────────────────────────────────────────────────────────────────
-
-def fn_load_rules():
- pending = list_pending_rules()
- choices = [f"{r['rule_id']}: {r['description'][:55]}…" for r in pending]
- return _rules_html(pending), choices
-
-
-def fn_approve(choice: str, researcher: str, note: str):
- if not choice:
- raise gr.Error("Select a rule.")
- if not researcher.strip():
- raise gr.Error("Enter your Researcher ID.")
- rid = choice.split(":")[0].strip()
- approve_rule(rid, researcher.strip(), note.strip())
- gr.Info(f"Rule {rid} approved.")
- return f"✓ Rule **{rid}** approved — now active for Agent 1b."
-
-
-def fn_reject(choice: str, researcher: str, note: str):
- if not choice:
- raise gr.Error("Select a rule.")
- if not researcher.strip():
- raise gr.Error("Enter your Researcher ID.")
- if not note.strip():
- raise gr.Error("Provide a rejection reason — Agent 2 learns from it.")
- rid = choice.split(":")[0].strip()
- reject_rule(rid, researcher.strip(), note.strip())
- gr.Info(f"Rule {rid} rejected.")
- return f"✗ Rule **{rid}** rejected."
-
-
-# ===========================================================================
-# CSS
-# ===========================================================================
-
-EXTRA_CSS = """
-.gradio-container {
- max-width: 1200px !important;
- margin: 0 auto !important;
- background: #ececee !important;
- font-family: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Arial, sans-serif !important;
-}
-footer { display: none !important; }
+# ──────────────────────────────────────────────────────────────────────────────
+# GRADIO UI
+# ──────────────────────────────────────────────────────────────────────────────
+CUSTOM_CSS = """
:root {
- --cc-bg: #ececee;
- --cc-surface: #f6f6f7;
- --cc-paper: #ffffff;
- --cc-ink: #111217;
- --cc-muted: #6b6f76;
- --cc-border: #d8dade;
- --cc-accent: #ff5a3d;
- --cc-accent-deep: #ea4425;
-}
-
-:focus-visible { outline: 2px solid var(--cc-accent) !important; outline-offset: 2px; }
-:focus { outline: none; }
-
-/* Primary button */
-.gradio-container button.primary {
- background: var(--cc-accent) !important;
- border-color: var(--cc-accent) !important;
- color: #fff !important;
- font-weight: 700 !important;
-}
-.gradio-container button.primary:hover {
- background: var(--cc-accent-deep) !important;
- border-color: var(--cc-accent-deep) !important;
-}
-.gradio-container button.secondary,
-.gradio-container button:not(.primary) {
- border-color: #c9cdd3 !important;
-}
-
-/* ── Welcome ── */
-.cc-hero {
- text-align: center;
- padding: 56px 24px 40px;
-}
-.cc-hero-title {
- font-size: clamp(3.5rem, 10vw, 7rem);
- font-weight: 900;
- letter-spacing: -0.06em;
- color: var(--cc-ink);
- line-height: 0.88;
- margin: 0 0 16px;
-}
-.cc-hero-sub {
- font-size: 1rem;
- color: var(--cc-muted);
- max-width: 44ch;
- margin: 0 auto 48px;
- line-height: 1.55;
-}
-.cc-entry-card {
- background: var(--cc-paper);
- border: 1px solid var(--cc-border);
- border-radius: 16px;
- padding: 24px;
- min-height: 190px;
- position: relative;
- overflow: hidden;
-}
-.cc-entry-card::after {
- content: "";
- position: absolute;
- right: -24px; bottom: -24px;
- width: 96px; height: 96px;
- border-radius: 999px;
- background: rgba(255,90,61,0.1);
-}
-.cc-entry-kicker {
- font-size: 0.7rem;
- font-weight: 800;
- text-transform: uppercase;
- letter-spacing: 0.1em;
- color: var(--cc-accent-deep);
- margin-bottom: 10px;
- display: block;
-}
-.cc-entry-title {
- font-size: 1.28rem;
- font-weight: 800;
- letter-spacing: -0.025em;
- color: var(--cc-ink);
- margin: 0 0 8px;
- line-height: 1.1;
-}
-.cc-entry-desc {
- font-size: 0.87rem;
- color: #434852;
- line-height: 1.55;
- max-width: 32ch;
-}
-
-/* ── Page nav bar ── */
-.cc-page-nav {
- display: flex;
- align-items: center;
- gap: 12px;
- padding: 16px 0 14px;
- border-bottom: 2px solid var(--cc-border);
- margin-bottom: 24px;
-}
-.cc-page-label {
- font-size: 0.68rem;
- font-weight: 800;
- text-transform: uppercase;
- letter-spacing: 0.12em;
- color: var(--cc-accent-deep);
-}
-.cc-page-title {
- font-size: 1.5rem;
- font-weight: 800;
- letter-spacing: -0.03em;
- color: var(--cc-ink);
- margin: 0;
+ --primary: #4338ca;
+ --primary-light: #eef2ff;
+ --surface: #ffffff;
+ --border: #e2e8f0;
+ --text: #1e293b;
+ --muted: #64748b;
}
-.cc-page-meta {
- font-size: 0.78rem;
- color: var(--cc-muted);
- margin-left: auto;
- font-family: monospace;
-}
-
-/* ── Step indicator ── */
-.cc-steps {
- display: flex;
- gap: 6px;
- align-items: center;
- flex-wrap: wrap;
- margin-bottom: 20px;
-}
-.cc-step-done { color:#065f46;background:#f0fdf4;border:1px solid #86efac;border-radius:999px;padding:4px 12px;font-size:0.76rem;font-weight:700; }
-.cc-step-active { color:#4338ca;background:#eef2ff;border:1px solid #818cf8;border-radius:999px;padding:4px 12px;font-size:0.76rem;font-weight:700; }
-.cc-step-next { color:#94a3b8;background:transparent;border:1px solid #e2e8f0;border-radius:999px;padding:4px 12px;font-size:0.76rem;font-weight:500; }
-.cc-step-sep { color:#d1d5db;font-size:0.7rem; }
-
-/* ── Setup page ── */
-.cc-setup-box {
- background: var(--cc-paper);
- border: 1px solid var(--cc-border);
- border-radius: 12px;
- padding: 24px;
- margin-bottom: 16px;
-}
-
-/* ── Pipeline page ── */
-.cc-section-header {
- background: #eff6ff;
- border: 1px solid #93c5fd;
- border-left: 4px solid #3b82f6;
- border-radius: 0 8px 8px 0;
- padding: 10px 16px;
- margin: 12px 0;
- font-size:0.92em;
- color: #1e3a8a;
-}
-
-/* ── Coding canvas ── */
-.cc-coding-transcript {
- background: var(--cc-paper);
- border: 1px solid var(--cc-border);
- border-radius: 10px;
- padding: 16px;
- max-height: 62vh;
- overflow-y: auto;
-}
-.cc-coding-controls {
- background: var(--cc-paper);
- border: 1px solid var(--cc-border);
- border-radius: 10px;
- padding: 16px;
-}
-.cc-coding-footer {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 12px;
- padding: 12px 0 0;
- border-top: 1px solid var(--cc-border);
- margin-top: 12px;
-}
-
-/* ── Done page ── */
-.cc-done-card {
- background: #f0fdf4;
- border: 2px solid #86efac;
- border-radius: 16px;
- padding: 32px;
- text-align: center;
- margin: 24px 0;
-}
-.cc-done-title {
- font-size: 2rem;
- font-weight: 800;
- color: #065f46;
- margin: 0 0 8px;
-}
-.cc-done-sub {
- color: #14532d;
- font-size: 0.95rem;
- max-width: 50ch;
- margin: 0 auto;
- line-height: 1.6;
-}
-
-/* ── Info callout ── */
-.cc-callout {
- background: #eff6ff;
- border: 1px solid #93c5fd;
- border-radius: 10px;
- padding: 16px 20px;
- margin-bottom: 16px;
- font-size: 0.88em;
- color: #1e3a8a;
- line-height: 1.7;
-}
-"""
-
-CSS = _load_css() + EXTRA_CSS
-
-# ===========================================================================
-# UI — page-based (no tabs)
-# ===========================================================================
-
-with gr.Blocks(title="CollabCode") as demo:
+body { font-family: system-ui, -apple-system, sans-serif; }
+.gr-box { border-radius: 10px !important; }
+.pipeline-header { position: sticky; top: 0; z-index: 100; }
+.tab-nav button { font-weight: 600 !important; }
+.screener-table { overflow-x: auto; }
+""" + _load_css()
+
+
+def build_ui():
+ with gr.Blocks(
+ title="CollabCode v5",
+ css=CUSTOM_CSS,
+ theme=gr.themes.Soft(primary_hue="indigo", neutral_hue="slate"),
+ ) as demo:
+
+ state = gr.State(_empty_state())
+
+ # ── Persistent pipeline header ────────────────────────────────────────
+ with gr.Row(elem_classes=["pipeline-header"]):
+ pipeline_header = gr.HTML(value=_pipeline_status_html(_empty_state()))
+
+ # ── Main tabs ─────────────────────────────────────────────────────────
+ with gr.Tabs():
+
+ # ================================================================
+ # TAB 1 — SESSION
+ # ================================================================
+ with gr.Tab("📋 Session"):
+ gr.Markdown("## Session Setup\nLoad a transcript and identify yourself as a researcher.")
+ with gr.Row():
+ with gr.Column(scale=1):
+ researcher_id = gr.Textbox(
+ label="Researcher ID",
+ placeholder="e.g. R1_Lara",
+ info="Used to namespace your codings and Drive sessions."
+ )
+ gr.Markdown("### Upload transcript (local file)")
+ local_file = gr.File(
+ label="Upload .txt or .vtt transcript",
+ file_types=[".txt", ".vtt", ".srt"],
+ )
+ upload_btn = gr.Button("⬆ Load local file", variant="primary")
+
+ with gr.Column(scale=1):
+ gr.Markdown("### Or load from Google Drive")
+ refresh_drive_btn = gr.Button("🔄 Connect to Drive")
+ drive_dropdown = gr.Dropdown(
+ label="Select transcript from Drive",
+ choices=[], interactive=False,
+ )
+ drive_load_btn = gr.Button("⬇ Load from Drive")
+ load_session_btn = gr.Button("📂 Restore previous session")
- state = gr.State(_empty_state())
+ session_status = gr.HTML()
- # ─────────────────────────────────────────────────────────────────────
- # 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
'
- 'Choose a Zoom transcript from Drive, let AI detect '
- 'sections and episode boundaries, then code each segment '
- 'against the D1–D9 collaborative learning dimensions.
'
- ''
+ upload_btn.click(
+ fn_process_local,
+ inputs=[local_file, researcher_id, state],
+ outputs=[state, session_status, pipeline_header],
)
- start_btn = gr.Button("Start Coding →", variant="primary", size="lg")
-
- with gr.Column(scale=1):
- gr.HTML(
- ''
- 'After coding'
- 'Check Agreement
'
- 'Upload both coders\' files, '
- 'compute Gwet\'s AC1 and Cohen\'s κ, resolve disagreements.
'
- ''
+ refresh_drive_btn.click(
+ fn_refresh_drive_transcripts,
+ inputs=[researcher_id, state],
+ outputs=[drive_dropdown, session_status],
)
- 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.
'
- ''
+ drive_load_btn.click(
+ fn_process_with_source,
+ inputs=[drive_dropdown, researcher_id, state],
+ outputs=[state, session_status, pipeline_header],
+ )
+ load_session_btn.click(
+ fn_load_previous_session,
+ inputs=[researcher_id, state],
+ outputs=[state, session_status],
)
- 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'
- ''
- )
-
- gr.HTML(
- ''
- ''
- 'Choose a transcript from Google Drive, then start coding. '
- 'Session IDs are generated automatically and saved for you.'
- '
'
- ''
- )
- with gr.Row():
- researcher_id_box = gr.Textbox(label="Researcher ID", placeholder="e.g. R1", scale=1)
+ # ================================================================
+ # TAB 2 — SCREENER
+ # ================================================================
+ with gr.Tab("🔍 Screener"):
+ gr.Markdown(
+ "## Metacognitive Talk Screener\n"
+ "Scans every turn with the research-backed trigger lexicon before any LLM call. "
+ "Green rows → candidate windows sent to LLM. Grey rows → small talk, skipped. "
+ "Yellow → structural signal (question mark, interruption, rapid exchange)."
+ )
+ with gr.Row():
+ run_screener_btn = gr.Button("▶ Run Screener", variant="primary", scale=2)
+ screener_info = gr.HTML(scale=3)
- with gr.Row():
- drive_refresh_btn = gr.Button("🔄 Refresh Drive transcripts", variant="secondary")
- load_prev_btn = gr.Button("↺ Load previous session", variant="secondary")
+ screener_status = gr.HTML()
- drive_file_dropdown = gr.Dropdown(
- label="Google Drive transcript",
- choices=[],
- interactive=False,
- )
- drive_status_html = gr.HTML()
-
- gr.HTML(
- ''
- 'Drive-only workflow: refresh the list, select one transcript, '
- 'and click Process Transcript. '
- 'The app will create a session ID automatically and show loading screens as it moves '
- 'through parsing, section detection, boundary review, and coding.'
- ''
- )
+ with gr.Tabs():
+ with gr.Tab("Turn-by-turn view"):
+ gr.Markdown(
+ "*Color key:* 🟢 Flagged (score ≥ 0.40) | ⬛ Low score | 🔘 Small talk excluded"
+ )
+ screener_turns_html = gr.HTML()
+ with gr.Tab("Candidate windows"):
+ gr.Markdown(
+ "These windows will be sent to the LLM for SSRL coding. "
+ "Each window = a flagged turn ± 3 turns context."
+ )
+ screener_windows_html = gr.HTML()
- process_btn = gr.Button("⚡ Process Transcript →", variant="primary")
- process_status = gr.HTML()
- process_log = gr.HTML()
+ run_screener_btn.click(
+ fn_run_screener,
+ inputs=[state],
+ outputs=[state, screener_status, screener_turns_html, screener_windows_html],
+ )
- back_setup_btn = gr.Button("← Back to Home", size="sm")
+ # ================================================================
+ # TAB 3 — SECTIONS
+ # ================================================================
+ with gr.Tab("🏗 Sections"):
+ gr.Markdown(
+ "## Structural Sections (Agent 0)\n"
+ "Agent 0 detects the high-level structure of the session "
+ "(e.g. warm-up, main task, wrap-up). Review and edit labels before coding."
+ )
+ with gr.Row():
+ run_agent0_btn = gr.Button("▶ Run Agent 0 — Detect sections", variant="primary")
+ sections_status = gr.HTML()
+ sections_display = gr.HTML()
+
+ gr.Markdown("### Edit section labels")
+ gr.Markdown(
+ "One label per line. Prefix `s01: ` is optional. "
+ "Labels here become the section headers throughout the app."
+ )
+ sections_labels = gr.Textbox(
+ label="Section labels (one per line)",
+ lines=6, placeholder="Introduction\nMain Task\nWrap-up"
+ )
+ with gr.Row():
+ confirm_sections_btn = gr.Button("✓ Confirm sections", variant="primary")
+ sections_confirm_status = gr.HTML()
+
+ run_agent0_btn.click(
+ fn_run_agent0,
+ inputs=[state],
+ outputs=[state, sections_status, pipeline_header],
+ )
+ confirm_sections_btn.click(
+ fn_confirm_sections,
+ inputs=[sections_labels, state],
+ outputs=[state, sections_confirm_status, pipeline_header],
+ )
- # ─────────────────────────────────────────────────────────────────────
- # 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'
- ''
- )
+ # ================================================================
+ # TAB 4 — PIPELINE
+ # ================================================================
+ with gr.Tab("⚙ Pipeline"):
+ gr.Markdown(
+ "## Coding Pipeline (Agent 1a + 1b)\n"
+ "Runs boundary detection and dimension coding on all confirmed sections. "
+ "Uses screener windows to focus LLM calls on metacognitive candidate turns."
+ )
+ with gr.Row():
+ run_pipeline_btn = gr.Button("▶ Run full pipeline", variant="primary", scale=2)
+ pipeline_info = gr.HTML(scale=3)
- sections_display_html = gr.HTML()
+ pipeline_status_out = gr.HTML()
+ pipeline_log = gr.HTML(label="Agent log")
- gr.Markdown("**Rename sections** — edit the text after the colon, keep the `s01:` prefix:")
- sections_labels_box = gr.Textbox(
- lines=10, show_label=False,
- placeholder="s01: Introduction\ns02: Main Discussion\n…",
- )
- confirm_sections_btn = gr.Button("Confirm Sections →", variant="primary")
- back_sections_btn = gr.Button("← Back to Setup", size="sm")
-
- # ─────────────────────────────────────────────────────────────────────
- # PAGE 3: Pipeline — boundaries + coding (per section)
- # ─────────────────────────────────────────────────────────────────────
- with gr.Column(visible=False) as pg_pipeline:
- gr.HTML(
- ''
- 'Step 3 of 4'
- 'Detect Episodes & Code
'
- ''
- ''
- '✓ Setup'
- '›'
- '✓ Sections'
- '›'
- '3 Code'
- '›'
- '4 Done'
- ''
- )
+ with gr.Accordion("Manual episode-by-episode coding", open=False):
+ gr.Markdown(
+ "Use this if you want to code or override one episode at a time "
+ "rather than running the full automatic pipeline."
+ )
+ with gr.Row():
+ prev_sec_btn = gr.Button("◀ Prev section")
+ next_sec_btn = gr.Button("Next section ▶")
+ with gr.Row():
+ prev_ep_btn = gr.Button("◀ Prev episode")
+ next_ep_btn = gr.Button("Next episode ▶")
+
+ coding_progress = gr.HTML()
+ episode_dropdown = gr.Dropdown(label="Episode", choices=[])
+ turns_display = gr.HTML(label="Turns in episode")
+ proposal_md = gr.Markdown()
+ uncertainty_display = gr.HTML(visible=False)
+ dim_dropdown = gr.Dropdown(label="Dimension (D1-D9)", choices=DIM_CHOICES)
+ dim_desc_display = gr.HTML()
+ sec_dropdown = gr.Dropdown(label="Secondary dimension (optional)",
+ choices=SEC_DIM_CHOICES, value=SEC_NONE)
+ coding_note = gr.Textbox(label="Note (optional)", lines=2)
+ save_btn = gr.Button("💾 Save coding", variant="primary")
+ save_status_out = gr.HTML()
+ manual_btn_visible = gr.Column(visible=False)
+
+ run_pipeline_btn.click(
+ fn_run_pipeline,
+ inputs=[state],
+ outputs=[state, pipeline_status_out, pipeline_header],
+ )
+ save_btn.click(
+ fn_save_coding,
+ inputs=[dim_dropdown, sec_dropdown, coding_note, state],
+ outputs=[state, save_status_out, pipeline_header],
+ )
+ dim_dropdown.change(
+ lambda c: _dim_desc_html(c),
+ inputs=[dim_dropdown], outputs=[dim_desc_display],
+ )
- sections_overview_html = gr.HTML()
+ def _nav_and_render(direction, is_section, state):
+ if is_section:
+ state = fn_nav_section(direction, state)
+ else:
+ state = fn_nav_segment(direction, state)
+ return (state,) + _render_coding(state)
+
+ for btn, dirn, is_sec in [
+ (prev_ep_btn, "prev", False), (next_ep_btn, "next", False),
+ (prev_sec_btn, "prev", True), (next_sec_btn, "next", True),
+ ]:
+ btn.click(
+ lambda d=dirn, s=is_sec: _nav_and_render(d, s, state),
+ inputs=[state],
+ outputs=[state, coding_progress, episode_dropdown, turns_display,
+ proposal_md, uncertainty_display, dim_dropdown,
+ dim_desc_display, sec_dropdown, coding_note, manual_btn_visible],
+ )
- # Live agent-activity banner — updated by callbacks to show what is running
- agent_activity_html = gr.HTML(
- ''
- 'No agent running. Click Detect Episode Boundaries to start.'
- )
+ # ================================================================
+ # TAB 5 — REVIEW
+ # ================================================================
+ with gr.Tab("📊 Review"):
+ gr.Markdown(
+ "## Segment Review & Editing\n"
+ "All coded segments. Green 🔍 badge = screener flagged this segment "
+ "as metacognitive. Use the SSRL phase dropdown to add a metacognitive tag."
+ )
- # Sub-step A: Parallel boundary detection
- with gr.Column(visible=True) as col_run_all_boundaries:
- gr.HTML(
- ''
- 'Agent 1a — Boundary Detector runs in parallel on all sections '
- 'simultaneously. Processing time scales with the longest section, not '
- 'total transcript length. '
- '(Dean & Ghemawat 2004 — parallel map; Schegloff 2007 — episode boundaries; '
- 'Krippendorff 2004 — unitising precedes categorising)'
- ''
- )
- run_all_btn = gr.Button("⚡ Detect Episode Boundaries (All Sections)", variant="primary")
- parallel_status_md = gr.Markdown()
- parallel_stats_html = gr.HTML()
-
- section_header_md = gr.Markdown()
-
- # Sub-step B: Per-section boundary review
- with gr.Column(visible=False) as col_boundary_review:
- # Agent 1b will run here — show what principles it uses
- gr.HTML(
- ''
- 'Agent 1b — Dimension Coder will run after you confirm these boundaries. '
- 'It uses: D1–D9 framework (Meier, Spada & Rummel 2007) · '
- 'Tier 1 hard rules (R01–R08) · Tier 2 learned rules · '
- 'Uncertainty sampling (Settles 2012) to flag hard cases for your review.'
- ''
- )
+ with gr.Row():
+ refresh_review_btn = gr.Button("↺ Refresh view", scale=1)
+ review_info = gr.HTML(scale=4)
- # Episode count summary (compact table)
- boundary_display_html = gr.HTML()
+ review_display = gr.HTML()
- # Full dialogue view — the key UX improvement
- gr.HTML(
- ''
- 'Read the dialogue — verify each episode boundary'
- )
- episode_dialogue_html = gr.HTML()
-
- # Edit controls
- gr.HTML(
- ''
- 'Adjust if needed: enter the turn ID after which '
- 'each new episode begins. Leave empty for a single undivided episode. '
- 'The AI proposal is pre-filled — edit only where you disagree.'
- ''
- )
- with gr.Row():
- boundary_ids_box = gr.Textbox(
- label="Boundary turn IDs (comma-separated)",
- placeholder="e.g. 12, 28, 35",
- lines=1, scale=3,
+ gr.Markdown("### Add SSRL metacognitive phase tag to current episode")
+ gr.Markdown(
+ "This tags the current episode (shown in Pipeline tab) with a "
+ "Socially Shared Regulation of Learning phase. "
+ "These tags are stored separately from D1-D9 codings."
)
- confirm_boundaries_btn = gr.Button("Confirm & Run Agent 1b →",
- variant="primary", scale=1)
- code_status = gr.Markdown()
-
- # Sub-step C: Coding canvas
- with gr.Column(visible=False) as col_coding:
- coding_progress_comp = gr.HTML()
-
- with gr.Row(equal_height=False):
- # Left: transcript
- with gr.Column(scale=3, elem_classes=["cc-coding-transcript"]):
- uncertainty_comp = gr.HTML()
- turns_html_comp = gr.HTML()
- with gr.Row():
- reveal_btn = gr.Button("▶ Reveal AI proposal", variant="secondary", size="sm")
- gr.HTML(
- ''
- 'Code independently first — reveal only if unsure '
- '(Settles 2012)
'
- )
- proposal_comp = gr.Markdown(visible=False)
-
- # Right: coding controls
- with gr.Column(scale=2, elem_classes=["cc-coding-controls"]):
- gr.Markdown("#### Dimension")
- dim_radio = gr.Radio(choices=DIM_CHOICES, label="Primary", value=None)
- dim_desc_comp = gr.HTML()
-
- secondary_dim_drop = gr.Dropdown(
- choices=SEC_DIM_CHOICES,
- value=SEC_NONE,
- label="Secondary dimension (optional)",
- info="Only when a second dimension is clearly sustained throughout. Strijbos et al. (2006).",
- interactive=True,
- )
- comment_box = gr.Textbox(
- label="Note (optional)", lines=2,
- placeholder="Ambiguity, competing codes…"
+ with gr.Row():
+ ssrl_dropdown = gr.Dropdown(
+ label="SSRL metacognitive phase",
+ choices=SSRL_CHOICES,
+ value=SSRL_CHOICES[-1], # NONE
)
- with gr.Row():
- prev_btn = gr.Button("← Previous", size="sm")
- next_btn = gr.Button("Next →", variant="primary", size="sm")
-
- 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.Accordion("Agent Activity Log", open=False):
- pipeline_log = gr.HTML(_agent_log_html([]))
+ save_ssrl_btn = gr.Button("💾 Save SSRL tag", variant="secondary")
+ ssrl_status = gr.HTML()
- back_pipeline_btn = gr.Button("← Back to Sections", size="sm")
+ refresh_review_btn.click(
+ lambda s: _all_segments_review_html(s),
+ inputs=[state], outputs=[review_display],
+ )
+ save_ssrl_btn.click(
+ fn_save_ssrl_tag,
+ inputs=[episode_dropdown, ssrl_dropdown, state],
+ outputs=[state, ssrl_status],
+ )
- # ─────────────────────────────────────────────────────────────────────
- # 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'
- ''
- )
+ # ================================================================
+ # TAB 6 — AGREEMENT
+ # ================================================================
+ with gr.Tab("🤝 Agreement"):
+ gr.Markdown(
+ "## Inter-Rater Reliability\n"
+ "Upload coding files from both researchers. "
+ "The system calculates Gwet's AC1 (primary) and Cohen's κ (secondary) "
+ "with 95% bootstrap CIs (B=1000). Gate: AC1 ≥ 0.70."
+ )
+ with gr.Row():
+ r1_file = gr.File(label="R1 codings (.json)", file_types=[".json"])
+ r2_file = gr.File(label="R2 codings (.json)", file_types=[".json"])
+
+ calc_kappa_btn = gr.Button("📐 Calculate agreement", variant="primary")
+ kappa_status_out = gr.HTML()
+ kappa_summary_out = gr.HTML()
+ disagreement_out = gr.HTML()
+
+ with gr.Accordion("Resolve disagreement", open=False):
+ gr.Markdown(
+ "Enter the segment ID and the agreed resolution. "
+ "Resolved disagreements are written to Tier 3 as training candidates."
+ )
+ resolve_seg_id = gr.Textbox(label="Segment ID")
+ resolve_dim = gr.Dropdown(label="Resolved dimension", choices=DIM_CHOICES)
+ resolve_note = gr.Textbox(label="Resolution note", lines=2)
+ resolve_btn = gr.Button("✓ Resolve")
+ discard_btn = gr.Button("✗ Discard (irresolvable)")
+ resolve_status = gr.HTML()
+
+ calc_kappa_btn.click(
+ fn_calculate_kappa,
+ inputs=[r1_file, r2_file, state],
+ outputs=[state, kappa_status_out, pipeline_header],
+ )
- 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.'
- '
'
- ''
- )
+ def _resolve(seg_id, dim_choice, note, state):
+ report = state.get("kappa_report")
+ if not report:
+ return state, _status_card("Run agreement calculation first.", "warning")
+ try:
+ d = _session_dir(state)
+ report_path = d / "kappa_report.json"
+ did = DIM_ID_FROM_CHOICE.get(dim_choice, "")
+ resolve_disagreement(report_path, seg_id, did, note)
+ return state, _status_card(f"Resolved: {seg_id} → {did}.", "success")
+ except Exception as e:
+ return state, _status_card(f"Failed: {e}", "error")
+
+ def _discard(seg_id, note, state):
+ report = state.get("kappa_report")
+ if not report:
+ return state, _status_card("Run agreement calculation first.", "warning")
+ try:
+ d = _session_dir(state)
+ report_path = d / "kappa_report.json"
+ discard_disagreement(report_path, seg_id, note or "irresolvable")
+ return state, _status_card(f"Discarded: {seg_id}.", "success")
+ except Exception as e:
+ return state, _status_card(f"Failed: {e}", "error")
+
+ resolve_btn.click(
+ _resolve,
+ inputs=[resolve_seg_id, resolve_dim, resolve_note, state],
+ outputs=[state, resolve_status],
+ )
+ discard_btn.click(
+ _discard,
+ inputs=[resolve_seg_id, resolve_note, state],
+ outputs=[state, resolve_status],
+ )
- 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
'
- ''
- )
+ # ================================================================
+ # TAB 7 — LEXICON
+ # ================================================================
+ with gr.Tab("📚 Lexicon"):
+ gr.Markdown(
+ "## Trigger Word Lexicon\n"
+ "The research-backed vocabulary used to screen turns before LLM coding. "
+ "Tier 1 is locked (from published research). "
+ "Tier 2 is your validated additions. "
+ "Tier 3 holds candidates proposed by the system — review and approve or reject them."
+ )
+ with gr.Row():
+ load_lexicon_btn = gr.Button("🔄 Load / refresh lexicon", variant="primary")
+ lexicon_status = gr.HTML()
+
+ with gr.Tabs():
+ with gr.Tab("🔒 Tier 1 — Research-locked"):
+ gr.Markdown(
+ "Source: Halmo et al. 2022, Zimmerman SRL model, "
+ "Järvelä & Hadwin SSRL, LIWC cognitive categories, "
+ "Schegloff et al. conversation analysis."
+ )
+ tier1_html = gr.HTML()
- gr.HTML(
- ''
- 'How it works:'
- ''
- '- You complete the pipeline → download
coding_R1.json '
- '- Your co-researcher runs the same pipeline independently → downloads their file
'
- '- Upload their file here to compute Gwet\'s AC1 and Cohen\'s κ
'
- '- Gate: AC1 ≥ 0.70 (Landis & Koch 1977)
'
- '- Resolve remaining disagreements — they feed Agent 2\'s learning cycle
'
- '
'
- ''
- )
+ with gr.Tab("✏ Tier 2 — Your validated terms"):
+ gr.Markdown(
+ "Terms you've validated in your specific participant population. "
+ "These are used at full weight by the screener."
+ )
+ tier2_html = gr.HTML()
+
+ gr.Markdown("### Add new validated terms")
+ with gr.Row():
+ t2_category = gr.Textbox(
+ label="Category ID",
+ placeholder="MON_custom_01",
+ info="Use existing category IDs to extend them, or create new ones."
+ )
+ t2_label = gr.Textbox(label="Label", placeholder="My custom category")
+ with gr.Row():
+ t2_phase = gr.Dropdown(
+ label="SRL Phase",
+ choices=["planning", "monitoring", "evaluating", "ssrl"],
+ value="monitoring",
+ )
+ t2_weight = gr.Slider(
+ label="Weight (0.3 = weak, 1.0 = strong)",
+ minimum=0.3, maximum=1.0, step=0.05, value=0.7,
+ )
+ t2_terms = gr.Textbox(
+ label="Terms (one per line, or comma-separated)",
+ lines=4,
+ placeholder="what do you mean\ncan you clarify\nhow did you get that",
+ )
+ t2_note = gr.Textbox(label="Note / source", lines=2,
+ placeholder="Observed in Session 3 and 4.")
+ add_t2_btn = gr.Button("➕ Add to Tier 2", variant="primary")
+ add_t2_status = gr.HTML()
+
+ with gr.Tab("⏳ Tier 3 — Candidates (system-proposed)"):
+ gr.Markdown(
+ "Words that appeared in LLM-coded metacognitive segments but "
+ "aren't in Tier 1 or 2 yet. Review each one: approve to move to Tier 2, "
+ "or reject with a note."
+ )
+ tier3_html = gr.HTML()
+
+ gr.Markdown("### Approve or reject a candidate")
+ with gr.Row():
+ t3_term = gr.Textbox(label="Term to approve/reject")
+ t3_note = gr.Textbox(label="Rejection note (optional)")
+ with gr.Row():
+ approve_t3_btn = gr.Button("✓ Approve", variant="primary")
+ reject_t3_btn = gr.Button("✗ Reject")
+ t3_action_status = gr.HTML()
+
+ load_lexicon_btn.click(
+ fn_load_lexicon_view,
+ outputs=[tier1_html, tier2_html, tier3_html, lexicon_status],
+ )
+ add_t2_btn.click(
+ fn_add_tier2,
+ inputs=[t2_category, t2_label, t2_phase, t2_terms,
+ t2_weight, researcher_id, t2_note],
+ outputs=[add_t2_status, tier2_html, t2_terms],
+ )
+ approve_t3_btn.click(
+ fn_approve_candidate,
+ inputs=[t3_term, researcher_id],
+ outputs=[t3_action_status, tier3_html],
+ )
+ reject_t3_btn.click(
+ fn_reject_candidate,
+ inputs=[t3_term, researcher_id, t3_note],
+ outputs=[t3_action_status, tier3_html],
+ )
- with gr.Row():
- r2_upload = gr.File(
- label="Co-researcher coding file (.json)",
- file_types=[".json"], scale=2
- )
- kappa_btn = gr.Button("Calculate Agreement", variant="primary", scale=1)
-
- kappa_html_comp = gr.HTML()
- disagreements_md = gr.Markdown()
-
- with gr.Column(visible=False) as col_disagreements:
- gr.HTML(
- ''
- 'Disagreement Resolution'
- 'For each disagreement: enter the '
- 'segment ID, select the consensus dimension, add a rationale. '
- 'Resolved segments become training data for Agent 2.
'
- ''
- )
- with gr.Row():
- dis_seg_id = gr.Textbox(label="Segment ID", placeholder="e.g. dyad_01_s01_ep03", scale=2)
- dis_dim = gr.Dropdown(label="Resolved dimension", choices=DIM_CHOICES, scale=2)
- dis_note = gr.Textbox(
- label="Rationale — why this dimension?", lines=2,
- placeholder="After discussion we agreed… because…"
- )
- with gr.Row():
- resolve_btn = gr.Button("Resolve ✓", variant="primary")
- discard_btn = gr.Button("Discard segment", variant="secondary")
- dis_status = gr.Markdown()
-
- with gr.Accordion("Sequence Analysis (optional)", open=False):
- gr.HTML(
- ''
- 'Temporal structure of the coded sequence. '
- 'Frequency counts show how much; sequential analysis shows '
- 'what follows what. '
- 'Bakeman & Gottman (1986)'
- ''
- )
- with gr.Row():
- seq_rater_choice = gr.Dropdown(
- label="Analyse coding from",
- choices=["R1 (you)", "R2 (co-researcher)"],
- value="R1 (you)", scale=2,
+ # ================================================================
+ # TAB 8 — LEARNING
+ # ================================================================
+ with gr.Tab("🧠 Learning"):
+ gr.Markdown(
+ "## Agent 2 — Rule Learning\n"
+ "After sessions accumulate disagreements, Agent 2 proposes coding rules "
+ "based on patterns in researcher corrections. Review and approve rules "
+ "before they become active in Tier 2."
+ )
+ with gr.Row():
+ load_rules_btn = gr.Button("🔄 Load pending rules", variant="primary")
+ learning_status = gr.HTML()
+
+ pending_rules_html = gr.HTML()
+
+ gr.Markdown("### Approve or reject a rule")
+ with gr.Row():
+ rule_id_box = gr.Textbox(label="Rule ID")
+ rule_note_box = gr.Textbox(label="Rejection note (optional)")
+ with gr.Row():
+ approve_rule_btn = gr.Button("✓ Approve rule", variant="primary")
+ reject_rule_btn = gr.Button("✗ Reject rule")
+ rule_action_status = gr.HTML()
+
+ load_rules_btn.click(
+ fn_load_pending_rules,
+ outputs=[pending_rules_html],
+ )
+ approve_rule_btn.click(
+ fn_approve_rule_action,
+ inputs=[rule_id_box],
+ outputs=[rule_action_status, pending_rules_html],
+ )
+ reject_rule_btn.click(
+ fn_reject_rule_action,
+ inputs=[rule_id_box, rule_note_box],
+ outputs=[rule_action_status, pending_rules_html],
)
- seq_run_btn = gr.Button("Run →", variant="primary", scale=1)
-
- seq_summary_md = gr.Markdown()
- seq_matrix_html = gr.HTML()
- seq_sig_html = gr.HTML()
- with gr.Column(visible=False) as col_seq_download:
- seq_dl_btn = gr.Button("Download transition matrix (CSV)", variant="secondary", size="sm")
- seq_dl_file = gr.File(visible=False)
-
- with gr.Accordion("Agent Activity Log", open=False):
- agreement_log = gr.HTML(_agent_log_html([]))
-
- with gr.Row():
- back_agreement_btn = gr.Button("← Back to Done")
- go_library_btn = gr.Button("→ Review AI Rules")
-
- # ─────────────────────────────────────────────────────────────────────
- # PAGE 6: Library
- # ─────────────────────────────────────────────────────────────────────
- with gr.Column(visible=False) as pg_library:
- gr.HTML(
- ''
- 'Advanced'
- 'AI Rule Library
'
- ''
- )
- gr.HTML(
- ''
- 'How the learning loop works: Agent 2 analyses patterns '
- 'across resolved disagreements and proposes rules to improve Agent 1b\'s '
- 'future coding. Rules are inactive until approved here. '
- 'Approved rules enter Tier 2 immediately. '
- '(Amershi et al. 2014; Monarch 2021)'
- '
'
- '⚠ Agent 2 requires ≥ 3 validated sessions and ≥ 90 coded segments '
- 'before proposing rules (Bujang & Baharum 2017).'
- ''
+ # ── Auto-load lexicon on launch ───────────────────────────────────────
+ demo.load(
+ fn_load_lexicon_view,
+ outputs=[tier1_html, tier2_html, tier3_html, lexicon_status],
)
- load_rules_btn = gr.Button("Load Pending Rules", variant="primary")
- rules_html_comp = gr.HTML()
+ return demo
- 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")
-
- # =====================================================================
- # 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
- comment_box, # 8
- next_section_btn, # 9
- ]
-
- # fn_process outputs (13 total — includes process_btn so we can disable it while running)
- PROCESS_OUTPUTS = [state, process_status, *ALL_PAGES,
- sections_display_html, sections_labels_box, process_log, process_btn]
-
- # fn_confirm_sections outputs (13 total — generator; includes button + sections_display)
- CONFIRM_SECTIONS_OUTPUTS = [
- state, *ALL_PAGES,
- sections_display_html, # show busy state on yield-1; clear on yield-2
- confirm_sections_btn, # disable on yield-1; re-enable on yield-2
- col_run_all_boundaries,
- col_boundary_review,
- col_coding,
- ]
-
- # fn_run_all_boundaries outputs (10 total)
- RUN_ALL_OUTPUTS = [
- state,
- parallel_status_md,
- parallel_stats_html,
- col_boundary_review,
- boundary_display_html,
- boundary_ids_box,
- section_header_md,
- pipeline_log,
- agent_activity_html,
- episode_dialogue_html, # NEW — full dialogue view per episode
- ]
-
- # fn_confirm_and_code outputs (14 total)
- CONFIRM_CODE_OUTPUTS = [state, code_status, col_coding] + CODING_OUTPUTS + [pipeline_log]
-
- # fn_next_section outputs (15 total — includes boundary + dialogue update for next section)
- NEXT_SECTION_OUTPUTS = [
- state, *ALL_PAGES,
- sections_overview_html,
- section_header_md,
- col_boundary_review,
- col_coding,
- boundary_display_html, # re-populate for next section
- boundary_ids_box, # re-populate for next section
- episode_dialogue_html, # re-populate for next section
- ]
-
- # =====================================================================
- # WIRING
- # =====================================================================
-
- # Welcome navigation
- start_btn.click(lambda: _show("setup"), outputs=ALL_PAGES)
- agreement_nav_btn.click(lambda: _show("agreement"), outputs=ALL_PAGES)
- library_nav_btn.click(lambda: _show("library"), outputs=ALL_PAGES)
-
- # Back buttons
- back_setup_btn.click(lambda: _show("welcome"), outputs=ALL_PAGES)
- back_sections_btn.click(lambda: _show("setup"), outputs=ALL_PAGES)
- back_pipeline_btn.click(lambda: _show("sections"), outputs=ALL_PAGES)
- back_done_btn.click(lambda: _show("pipeline"), outputs=ALL_PAGES)
- back_agreement_btn.click(lambda: _show("done"), outputs=ALL_PAGES)
- back_library_btn.click(lambda: _show("agreement"), outputs=ALL_PAGES)
- home_from_lib.click(lambda: _show("welcome"), outputs=ALL_PAGES)
-
- # Forward navigation
- go_agreement_btn.click(lambda: _show("agreement"), outputs=ALL_PAGES)
- go_library_btn.click(lambda: _show("library"), outputs=ALL_PAGES)
-
- # Setup: process transcript + detect sections
- drive_refresh_btn.click(
- fn=fn_refresh_drive_transcripts,
- inputs=[researcher_id_box],
- outputs=[drive_file_dropdown, drive_status_html],
- )
-
- load_prev_btn.click(
- fn=fn_load_previous_session,
- inputs=[researcher_id_box, state],
- outputs=[state, process_status],
- )
-
- process_btn.click(
- fn=fn_process_with_source,
- inputs=[drive_file_dropdown, researcher_id_box, state],
- outputs=PROCESS_OUTPUTS,
- )
-
- # Sections: confirm labels
- confirm_sections_btn.click(
- fn=fn_confirm_sections,
- inputs=[sections_labels_box, state],
- outputs=CONFIRM_SECTIONS_OUTPUTS,
- )
-
- # Pipeline: run boundaries in parallel
- run_all_btn.click(
- fn=fn_run_all_boundaries,
- inputs=[state],
- outputs=RUN_ALL_OUTPUTS,
- )
-
- # Pipeline: confirm boundaries + run Agent 1b
- confirm_boundaries_btn.click(
- fn=fn_confirm_and_code,
- inputs=[boundary_ids_box, state],
- outputs=CONFIRM_CODE_OUTPUTS,
- )
-
- # Coding navigation
- next_btn.click(
- fn=lambda d, sec, c, s: fn_navigate(+1, d, sec, c, s),
- inputs=[dim_radio, secondary_dim_drop, comment_box, state],
- outputs=[state] + CODING_OUTPUTS,
- )
- prev_btn.click(
- fn=lambda d, sec, c, s: fn_navigate(-1, d, sec, c, s),
- inputs=[dim_radio, secondary_dim_drop, comment_box, state],
- outputs=[state] + CODING_OUTPUTS,
- )
- segment_jump.change(
- fn=fn_jump,
- inputs=[segment_jump, state],
- outputs=[state] + CODING_OUTPUTS,
- )
- reveal_btn.click(fn=fn_reveal, inputs=[state], outputs=[proposal_comp])
- dim_radio.change(fn=fn_dim_desc, inputs=[dim_radio], outputs=[dim_desc_comp])
-
- # Finish section / go to done
- next_section_btn.click(
- fn=fn_next_section,
- inputs=[dim_radio, secondary_dim_drop, comment_box, state],
- outputs=NEXT_SECTION_OUTPUTS,
- )
-
- # Download
- download_btn.click(fn=fn_download, inputs=[state], outputs=[download_file]).then(
- fn=lambda: gr.update(visible=True), outputs=[download_file]
- )
-
- # Agreement
- kappa_btn.click(
- fn=fn_calculate_kappa,
- inputs=[r2_upload, state],
- outputs=[state, kappa_html_comp, disagreements_md, col_disagreements, agreement_log],
- )
- resolve_btn.click(
- fn=fn_resolve,
- inputs=[dis_seg_id, dis_dim, dis_note, state],
- outputs=[state, dis_status],
- )
- discard_btn.click(
- fn=fn_discard,
- inputs=[dis_seg_id, dis_note, state],
- outputs=[state, dis_status],
- )
-
- # Sequence analysis
- seq_run_btn.click(
- fn=fn_run_sequence_analysis,
- inputs=[seq_rater_choice, state],
- outputs=[seq_summary_md, seq_matrix_html, seq_sig_html, col_seq_download],
- )
- seq_dl_btn.click(
- fn=fn_download_seq_csv,
- inputs=[seq_rater_choice, state],
- outputs=[seq_dl_file],
- ).then(fn=lambda: gr.update(visible=True), outputs=[seq_dl_file])
-
- # Library
- load_rules_btn.click(fn=fn_load_rules, outputs=[rules_html_comp, rule_selector])
- approve_rule_btn.click(
- fn=fn_approve, inputs=[rule_selector, rule_rid, rule_note], outputs=[rule_status]
- )
- reject_rule_btn.click(
- fn=fn_reject, inputs=[rule_selector, rule_rid, rule_note], outputs=[rule_status]
- )
+# ──────────────────────────────────────────────────────────────────────────────
+# Entry point
+# ──────────────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
- demo.launch(css=CSS, theme=gr.themes.Soft(), ssr_mode=False)
+ app = build_ui()
+ app.launch(
+ server_name="0.0.0.0",
+ server_port=7860,
+ share=False,
+ show_error=True,
+ )
' - f'Basis: lexical cohesion (Hearst 1997) · topic modelling (Purver et al. 2006) ' - f'· activity phases (Stahl 2006; Roschelle & Teasley 1995)' - f'
' - f'' - f'{_h(s["section_id"])}' - f'' - f'{_h(s["label"])}' - f'{_h(s["start_time"])}–{_h(s["end_time"])}' - f'' - f' {n} turns ({pct}%)' - f'{bar}' - f'▼ read' - f'
' - - # ── Expanded content ──────────────────────────────────────────── - f'' - f'AI summary: {summary_text}
' - f'{excerpt_html}' + row_bg = "#fffbeb" if flagged else ("#f8fafc" if excluded else "white") + flag_icon = "🟢" if flagged else ("⬜" if not excluded else "🔘") + + parts.append( + f'- {items}
'
- f's01: Your Label. '
- f'Edit the text after the colon only; the s01: prefix keeps the order clear. '
- f'Turn boundaries are fixed — only labels change. '
- f'Expand any section above to read its content before renaming.'
- f'No candidate windows found.
' - Design goal: the researcher must be able to READ the transcript before - deciding whether to accept the AI's proposed boundary positions. - Showing only turn-ID tables (the old approach) is opaque. + parts = ['' - 'No episode data yet.
' + parts.append( + f'Lexicon file not found.
' + + phase_colors = { + "planning": ("#1d4ed8", "#eff6ff", "#dbeafe"), + "monitoring": ("#15803d", "#f0fdf4", "#dcfce7"), + "evaluating": ("#c2410c", "#fff7ed", "#fed7aa"), + "ssrl": ("#7c3aed", "#faf5ff", "#e9d5ff"), } - parts: list[str] = [] - for i, seg in enumerate(segments): - turns = seg.get("turns", []) - ep_id = seg.get("segment_id", f"ep{i+1:02d}") - ep_num = ep_id.split("_ep")[-1] if "_ep" in ep_id else str(i + 1) - n_turns = len(turns) + parts = [ + '' - 'No agents have run yet.
' + 'No coded segments yet.
' + + coded = sum(1 for s, _ in all_segs if codings.get(s["segment_id"], {}).get("dimension_id")) + total = len(all_segs) + ssrl_ct = sum(1 for s, _ in all_segs if ssrl.get(s["segment_id"], "NONE") != "NONE") + + header = ( + f'No pending rules.
' + parts = ['Error: {_h(str(e))}
' - summary_md = ( - f"**{n_ep}** episodes · **{n_tr}** transitions · " - f"**{len(cats)}** dimensions: `{'`, `'.join(cats)}` \n" - f"Entropy: {ent_note} \n" - f"**{len(sig_pos)}** significantly common · **{len(sig_neg)}** significantly rare" - f"{warn_md}" - ) - gr.Info(f"Sequence analysis: {n_ep} episodes, {len(sig_pos)} significant transitions.") - return summary_md, render_transition_matrix_html(analysis), render_significant_transitions_html(analysis), gr.update(visible=True) - - -def fn_download_seq_csv(rater_choice: str, state: dict): - if not state.get("session_id"): - raise gr.Error("No session loaded.") - d = _session_dir(state) - path = d / ("coding_R2.json" if "R2" in rater_choice else f"coding_{state['researcher_id']}.json") - if not path.exists(): - raise gr.Error(f"Coding file not found: {path.name}") - analysis = load_and_analyse(path) - if "error" in analysis: - raise gr.Error(analysis["error"]) - csv_str = seq_to_csv(analysis) - tmp = Path(tempfile.mktemp(suffix=f"_transitions_{state['session_id']}.csv")) - tmp.write_text(csv_str, encoding="utf-8") - return str(tmp) - - -def fn_resolve(seg_id: str, dim_choice: str, note: str, state: dict): - if not seg_id.strip(): - raise gr.Error("Enter the segment ID.") - if not dim_choice: - raise gr.Error("Select the resolved dimension.") - resolved = DIM_ID_FROM_CHOICE.get(dim_choice, dim_choice) +def fn_approve_rule_action(rule_id: str): + if not rule_id.strip(): + return _status_card("Enter a rule ID.", "warning"), fn_load_pending_rules() try: - resolve_disagreement( - report_path=_session_dir(state) / "kappa_report.json", - segment_id=seg_id.strip(), resolved_dimension=resolved, - resolution_note=note.strip(), - ) + approve_rule(rule_id.strip()) + return _status_card(f"Rule '{rule_id}' approved.", "success"), fn_load_pending_rules() except Exception as e: - raise gr.Error(f"Could not resolve: {e}") from e - gr.Info(f"Resolved {seg_id.strip()} → {resolved}") - return state, f"✓ `{seg_id.strip()}` → **{resolved}**" + return _status_card(f"Failed: {e}", "error"), fn_load_pending_rules() -def fn_discard(seg_id: str, note: str, state: dict): - if not seg_id.strip(): - raise gr.Error("Enter the segment ID.") +def fn_reject_rule_action(rule_id: str, note: str): + if not rule_id.strip(): + return _status_card("Enter a rule ID.", "warning"), fn_load_pending_rules() try: - discard_disagreement( - report_path=_session_dir(state) / "kappa_report.json", - segment_id=seg_id.strip(), discard_note=note.strip(), - ) + reject_rule(rule_id.strip(), note) + return _status_card(f"Rule '{rule_id}' rejected.", "success"), fn_load_pending_rules() except Exception as e: - raise gr.Error(f"Could not discard: {e}") from e - gr.Info(f"Discarded {seg_id.strip()}") - return state, f"Discarded `{seg_id.strip()}`" + return _status_card(f"Failed: {e}", "error"), fn_load_pending_rules() -# ── Rules ───────────────────────────────────────────────────────────────────── - -def fn_load_rules(): - pending = list_pending_rules() - choices = [f"{r['rule_id']}: {r['description'][:55]}…" for r in pending] - return _rules_html(pending), choices - - -def fn_approve(choice: str, researcher: str, note: str): - if not choice: - raise gr.Error("Select a rule.") - if not researcher.strip(): - raise gr.Error("Enter your Researcher ID.") - rid = choice.split(":")[0].strip() - approve_rule(rid, researcher.strip(), note.strip()) - gr.Info(f"Rule {rid} approved.") - return f"✓ Rule **{rid}** approved — now active for Agent 1b." - - -def fn_reject(choice: str, researcher: str, note: str): - if not choice: - raise gr.Error("Select a rule.") - if not researcher.strip(): - raise gr.Error("Enter your Researcher ID.") - if not note.strip(): - raise gr.Error("Provide a rejection reason — Agent 2 learns from it.") - rid = choice.split(":")[0].strip() - reject_rule(rid, researcher.strip(), note.strip()) - gr.Info(f"Rule {rid} rejected.") - return f"✗ Rule **{rid}** rejected." - - -# =========================================================================== -# CSS -# =========================================================================== - -EXTRA_CSS = """ -.gradio-container { - max-width: 1200px !important; - margin: 0 auto !important; - background: #ececee !important; - font-family: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Arial, sans-serif !important; -} -footer { display: none !important; } +# ────────────────────────────────────────────────────────────────────────────── +# GRADIO UI +# ────────────────────────────────────────────────────────────────────────────── +CUSTOM_CSS = """ :root { - --cc-bg: #ececee; - --cc-surface: #f6f6f7; - --cc-paper: #ffffff; - --cc-ink: #111217; - --cc-muted: #6b6f76; - --cc-border: #d8dade; - --cc-accent: #ff5a3d; - --cc-accent-deep: #ea4425; -} - -:focus-visible { outline: 2px solid var(--cc-accent) !important; outline-offset: 2px; } -:focus { outline: none; } - -/* Primary button */ -.gradio-container button.primary { - background: var(--cc-accent) !important; - border-color: var(--cc-accent) !important; - color: #fff !important; - font-weight: 700 !important; -} -.gradio-container button.primary:hover { - background: var(--cc-accent-deep) !important; - border-color: var(--cc-accent-deep) !important; -} -.gradio-container button.secondary, -.gradio-container button:not(.primary) { - border-color: #c9cdd3 !important; -} - -/* ── Welcome ── */ -.cc-hero { - text-align: center; - padding: 56px 24px 40px; -} -.cc-hero-title { - font-size: clamp(3.5rem, 10vw, 7rem); - font-weight: 900; - letter-spacing: -0.06em; - color: var(--cc-ink); - line-height: 0.88; - margin: 0 0 16px; -} -.cc-hero-sub { - font-size: 1rem; - color: var(--cc-muted); - max-width: 44ch; - margin: 0 auto 48px; - line-height: 1.55; -} -.cc-entry-card { - background: var(--cc-paper); - border: 1px solid var(--cc-border); - border-radius: 16px; - padding: 24px; - min-height: 190px; - position: relative; - overflow: hidden; -} -.cc-entry-card::after { - content: ""; - position: absolute; - right: -24px; bottom: -24px; - width: 96px; height: 96px; - border-radius: 999px; - background: rgba(255,90,61,0.1); -} -.cc-entry-kicker { - font-size: 0.7rem; - font-weight: 800; - text-transform: uppercase; - letter-spacing: 0.1em; - color: var(--cc-accent-deep); - margin-bottom: 10px; - display: block; -} -.cc-entry-title { - font-size: 1.28rem; - font-weight: 800; - letter-spacing: -0.025em; - color: var(--cc-ink); - margin: 0 0 8px; - line-height: 1.1; -} -.cc-entry-desc { - font-size: 0.87rem; - color: #434852; - line-height: 1.55; - max-width: 32ch; -} - -/* ── Page nav bar ── */ -.cc-page-nav { - display: flex; - align-items: center; - gap: 12px; - padding: 16px 0 14px; - border-bottom: 2px solid var(--cc-border); - margin-bottom: 24px; -} -.cc-page-label { - font-size: 0.68rem; - font-weight: 800; - text-transform: uppercase; - letter-spacing: 0.12em; - color: var(--cc-accent-deep); -} -.cc-page-title { - font-size: 1.5rem; - font-weight: 800; - letter-spacing: -0.03em; - color: var(--cc-ink); - margin: 0; + --primary: #4338ca; + --primary-light: #eef2ff; + --surface: #ffffff; + --border: #e2e8f0; + --text: #1e293b; + --muted: #64748b; } -.cc-page-meta { - font-size: 0.78rem; - color: var(--cc-muted); - margin-left: auto; - font-family: monospace; -} - -/* ── Step indicator ── */ -.cc-steps { - display: flex; - gap: 6px; - align-items: center; - flex-wrap: wrap; - margin-bottom: 20px; -} -.cc-step-done { color:#065f46;background:#f0fdf4;border:1px solid #86efac;border-radius:999px;padding:4px 12px;font-size:0.76rem;font-weight:700; } -.cc-step-active { color:#4338ca;background:#eef2ff;border:1px solid #818cf8;border-radius:999px;padding:4px 12px;font-size:0.76rem;font-weight:700; } -.cc-step-next { color:#94a3b8;background:transparent;border:1px solid #e2e8f0;border-radius:999px;padding:4px 12px;font-size:0.76rem;font-weight:500; } -.cc-step-sep { color:#d1d5db;font-size:0.7rem; } - -/* ── Setup page ── */ -.cc-setup-box { - background: var(--cc-paper); - border: 1px solid var(--cc-border); - border-radius: 12px; - padding: 24px; - margin-bottom: 16px; -} - -/* ── Pipeline page ── */ -.cc-section-header { - background: #eff6ff; - border: 1px solid #93c5fd; - border-left: 4px solid #3b82f6; - border-radius: 0 8px 8px 0; - padding: 10px 16px; - margin: 12px 0; - font-size:0.92em; - color: #1e3a8a; -} - -/* ── Coding canvas ── */ -.cc-coding-transcript { - background: var(--cc-paper); - border: 1px solid var(--cc-border); - border-radius: 10px; - padding: 16px; - max-height: 62vh; - overflow-y: auto; -} -.cc-coding-controls { - background: var(--cc-paper); - border: 1px solid var(--cc-border); - border-radius: 10px; - padding: 16px; -} -.cc-coding-footer { - display: flex; - align-items: center; - justify-content: space-between; - gap: 12px; - padding: 12px 0 0; - border-top: 1px solid var(--cc-border); - margin-top: 12px; -} - -/* ── Done page ── */ -.cc-done-card { - background: #f0fdf4; - border: 2px solid #86efac; - border-radius: 16px; - padding: 32px; - text-align: center; - margin: 24px 0; -} -.cc-done-title { - font-size: 2rem; - font-weight: 800; - color: #065f46; - margin: 0 0 8px; -} -.cc-done-sub { - color: #14532d; - font-size: 0.95rem; - max-width: 50ch; - margin: 0 auto; - line-height: 1.6; -} - -/* ── Info callout ── */ -.cc-callout { - background: #eff6ff; - border: 1px solid #93c5fd; - border-radius: 10px; - padding: 16px 20px; - margin-bottom: 16px; - font-size: 0.88em; - color: #1e3a8a; - line-height: 1.7; -} -""" - -CSS = _load_css() + EXTRA_CSS - -# =========================================================================== -# UI — page-based (no tabs) -# =========================================================================== - -with gr.Blocks(title="CollabCode") as demo: +body { font-family: system-ui, -apple-system, sans-serif; } +.gr-box { border-radius: 10px !important; } +.pipeline-header { position: sticky; top: 0; z-index: 100; } +.tab-nav button { font-weight: 600 !important; } +.screener-table { overflow-x: auto; } +""" + _load_css() + + +def build_ui(): + with gr.Blocks( + title="CollabCode v5", + css=CUSTOM_CSS, + theme=gr.themes.Soft(primary_hue="indigo", neutral_hue="slate"), + ) as demo: + + state = gr.State(_empty_state()) + + # ── Persistent pipeline header ──────────────────────────────────────── + with gr.Row(elem_classes=["pipeline-header"]): + pipeline_header = gr.HTML(value=_pipeline_status_html(_empty_state())) + + # ── Main tabs ───────────────────────────────────────────────────────── + with gr.Tabs(): + + # ================================================================ + # TAB 1 — SESSION + # ================================================================ + with gr.Tab("📋 Session"): + gr.Markdown("## Session Setup\nLoad a transcript and identify yourself as a researcher.") + with gr.Row(): + with gr.Column(scale=1): + researcher_id = gr.Textbox( + label="Researcher ID", + placeholder="e.g. R1_Lara", + info="Used to namespace your codings and Drive sessions." + ) + gr.Markdown("### Upload transcript (local file)") + local_file = gr.File( + label="Upload .txt or .vtt transcript", + file_types=[".txt", ".vtt", ".srt"], + ) + upload_btn = gr.Button("⬆ Load local file", variant="primary") + + with gr.Column(scale=1): + gr.Markdown("### Or load from Google Drive") + refresh_drive_btn = gr.Button("🔄 Connect to Drive") + drive_dropdown = gr.Dropdown( + label="Select transcript from Drive", + choices=[], interactive=False, + ) + drive_load_btn = gr.Button("⬇ Load from Drive") + load_session_btn = gr.Button("📂 Restore previous session") - state = gr.State(_empty_state()) + session_status = gr.HTML() - # ───────────────────────────────────────────────────────────────────── - # PAGE 0: Welcome - # ───────────────────────────────────────────────────────────────────── - with gr.Column(visible=True) as pg_welcome: - gr.HTML( - 'CollabCode
' - 'Human-in-the-loop qualitative coding ' - 'for collaborative learning research
' - 'Code a Transcript
' - 'Choose a Zoom transcript from Drive, let AI detect ' - 'sections and episode boundaries, then code each segment ' - 'against the D1–D9 collaborative learning dimensions.
' - 'Check Agreement
' - 'Upload both coders\' files, ' - 'compute Gwet\'s AC1 and Cohen\'s κ, resolve disagreements.
' - 'Review AI Rules
' - 'Approve or reject Agent 2\'s proposed ' - 'coding rules before they enter the validated library.
' - 'Session Setup
' - '' - 'Choose a transcript from Google Drive, then start coding. ' - 'Session IDs are generated automatically and saved for you.' - '
' - 'Review Sections
' - 'Detect Episodes & Code
' - '' - 'Code independently first — reveal only if unsure ' - '(Settles 2012)
' - ) - proposal_comp = gr.Markdown(visible=False) - - # Right: coding controls - with gr.Column(scale=2, elem_classes=["cc-coding-controls"]): - gr.Markdown("#### Dimension") - dim_radio = gr.Radio(choices=DIM_CHOICES, label="Primary", value=None) - dim_desc_comp = gr.HTML() - - secondary_dim_drop = gr.Dropdown( - choices=SEC_DIM_CHOICES, - value=SEC_NONE, - label="Secondary dimension (optional)", - info="Only when a second dimension is clearly sustained throughout. Strijbos et al. (2006).", - interactive=True, - ) - comment_box = gr.Textbox( - label="Note (optional)", lines=2, - placeholder="Ambiguity, competing codes…" + with gr.Row(): + ssrl_dropdown = gr.Dropdown( + label="SSRL metacognitive phase", + choices=SSRL_CHOICES, + value=SSRL_CHOICES[-1], # NONE ) - with gr.Row(): - prev_btn = gr.Button("← Previous", size="sm") - next_btn = gr.Button("Next →", variant="primary", size="sm") - - 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.Accordion("Agent Activity Log", open=False): - pipeline_log = gr.HTML(_agent_log_html([])) + save_ssrl_btn = gr.Button("💾 Save SSRL tag", variant="secondary") + ssrl_status = gr.HTML() - back_pipeline_btn = gr.Button("← Back to Sections", size="sm") + refresh_review_btn.click( + lambda s: _all_segments_review_html(s), + inputs=[state], outputs=[review_display], + ) + save_ssrl_btn.click( + fn_save_ssrl_tag, + inputs=[episode_dropdown, ssrl_dropdown, state], + outputs=[state, ssrl_status], + ) - # ───────────────────────────────────────────────────────────────────── - # PAGE 4: Done - # ───────────────────────────────────────────────────────────────────── - with gr.Column(visible=False) as pg_done: - gr.HTML( - 'All Sections Coded
' - '' - '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.' - '
' - 'Agreement Check
' - '- '
- '
- You complete the pipeline → download
coding_R1.json'
- ' - Your co-researcher runs the same pipeline independently → downloads their file ' - '
- Upload their file here to compute Gwet\'s AC1 and Cohen\'s κ ' - '
- Gate: AC1 ≥ 0.70 (Landis & Koch 1977) ' - '
- Resolve remaining disagreements — they feed Agent 2\'s learning cycle ' - '
For each disagreement: enter the ' - 'segment ID, select the consensus dimension, add a rationale. ' - 'Resolved segments become training data for Agent 2.
' - 'AI Rule Library
' - '' - '⚠ Agent 2 requires ≥ 3 validated sessions and ≥ 90 coded segments ' - 'before proposing rules (Bujang & Baharum 2017).' - '