Lara Monteagudo Tubau
fix: circuit breaker resilience, Drive save on every persist, remove local upload
7070b94 Download app.py from pylxi/script: direct link, hf CLI and curl.
- Browser
- Download file 178 kB
-
https://huggingface.co/spaces/pylxi/script/resolve/main/app.py
- Command line
-
hf download hf://spaces/pylxi/script/app.py
-
curl -L -o app.py https://huggingface.co/spaces/pylxi/script/resolve/main/app.py
178 kB
"""
app.py (v4) β CollabCode Researcher Interface
==============================================
Page-based flow: Welcome β Setup β Sections β Pipeline β Done β Agreement β Library
No tabs. One task per screen.
"""
from __future__ import annotations
import json
import html as html_lib
import queue as _queue
import tempfile
import threading
import time
from datetime import datetime, timezone, timedelta
from pathlib import Path
import gradio as gr
from transcript_parser import parse_transcript
from agent0_sectioner import run_sectioning
from metacog_screener import (
screen_transcript, result_to_dict,
add_tier2_term, propose_tier3_candidate,
approve_tier3_candidate, reject_tier3_candidate,
load_full_lexicon,
)
from agent1a_boundary import propose_boundaries, boundaries_to_segments
from agent1b_coder import code_section
from drive_utils import (
get_drive_service,
list_transcripts,
read_file_from_drive,
write_session_to_drive,
load_session_from_drive,
register_researcher,
format_drive_diagnostic,
)
from kappa_calculator import (
calculate_kappa_report,
resolve_disagreement,
discard_disagreement,
)
from agent2_learner import list_pending_rules, approve_rule, reject_rule
from pipeline import (
run_boundaries_parallel,
run_coding_with_context,
render_pipeline_stats_html,
PipelineStats,
)
from llm_client import circuit_state, compute_timeout, reset_circuit
from sequential_analysis import (
load_and_analyse,
render_transition_matrix_html,
render_significant_transitions_html,
to_csv as seq_to_csv,
lag_to_csv,
)
SESSIONS_ROOT = Path("sessions")
SESSIONS_ROOT.mkdir(parents=True, exist_ok=True)
_STYLES_DIR = Path(__file__).parent / "static" / "styles"
MODEL_ID = "Qwen/Qwen2.5-72B-Instruct"
TEMPERATURE = 0.1
import sys as _sys, importlib.metadata as _meta
def _startup_log() -> None:
import gradio as _gr
try:
hf_ver = _meta.version("huggingface_hub")
except Exception:
hf_ver = "unknown"
hf_tok = "SET" if __import__("os").environ.get("HF_TOKEN") else "MISSING β "
print("=" * 60)
print(" CollabCode v4 β startup")
print("=" * 60)
print(f" Python : {_sys.version.split()[0]}")
print(f" Gradio : {_gr.__version__}")
print(f" HF hub : {hf_ver}")
print(f" HF_TOKEN : {hf_tok}")
print(f" Sessions root: {SESSIONS_ROOT.resolve()}")
print(f" Model : {MODEL_ID}")
print("=" * 60)
_startup_log()
def _load_css() -> str:
scss_entry = _STYLES_DIR / "main.scss"
if scss_entry.exists():
try:
import subprocess
result = subprocess.run(
["sass", str(scss_entry), "--style=expanded",
"--load-path", str(_STYLES_DIR), "--no-source-map"],
capture_output=True, text=True, timeout=30,
)
if result.returncode == 0 and result.stdout:
css = result.stdout
(_STYLES_DIR / "main.css").write_text(css, encoding="utf-8")
return css
except (FileNotFoundError, subprocess.TimeoutExpired):
pass
compiled = _STYLES_DIR / "main.css"
if compiled.exists():
return compiled.read_text(encoding="utf-8")
return ""
# ---------------------------------------------------------------------------
# Design system β dimensions
# ---------------------------------------------------------------------------
DIMENSIONS = [
("D1", "Sustaining Mutual Understanding",
"Speakers ensure contributions are understood; actively seek comprehension."),
("D2", "Dialogue Management",
"Smooth conversational flow with clear turn-taking and minimal overlap."),
("D3", "Information Pooling",
"Partners share, elaborate, and elicit domain-specific information."),
("D4", "Reaching Consensus",
"Partners critically evaluate options before reaching a joint decision."),
("D5", "Task Division",
"Task is systematically divided into subtasks with clear work phases."),
("D6", "Time Management",
"Partners monitor time and adjust pace to ensure task completion."),
("D7", "Technical Coordination",
"Partners manage shared technical tools effectively."),
("D8", "Reciprocal Interaction",
"Partners interact as equals with mutual respect and balanced contribution."),
("D9", "Individual Task Orientation",
"Each participant actively engages, contributes knowledge, avoids distraction."),
("NS", "Not Sure",
"Cannot confidently assign β competing interpretations remain unresolved."),
("NA", "Not Applicable",
"Doesn't fit any dimension: off-topic, administrative, or technical noise."),
]
DIM_CHOICES = [f"{d} β {l}" for d, l, _ in DIMENSIONS]
DIM_ID_FROM_CHOICE = {f"{d} β {l}": d for d, l, _ in DIMENSIONS}
DIM_DESC_FROM_ID = {d: desc for d, _, desc in DIMENSIONS}
SEC_NONE = "None β single dimension only"
SEC_DIM_CHOICES = [SEC_NONE] + DIM_CHOICES
SEC_ID_FROM_CHOICE = {SEC_NONE: None, **DIM_ID_FROM_CHOICE}
# SSRL phase tagging (Iiskala 2011; JΓ€rvelΓ€ & Hadwin 2013)
SSRL_PHASES = [
("M-MON", "Individual monitoring β one speaker tracks own/others' understanding"),
("M-REG", "Individual regulation β one speaker adjusts plan, strategy or effort"),
("CO-REG", "Co-regulation β one speaker scaffolds another's metacognitive process"),
("SSRL", "Socially shared β group jointly monitors and regulates together"),
]
SSRL_NONE = "None β no metacognitive activity"
SSRL_CHOICES = [SSRL_NONE] + [f"{c} β {l}" for c, l in SSRL_PHASES]
SSRL_ID_FROM_CHOICE = {SSRL_NONE: None, **{f"{c} β {l}": c for c, l in SSRL_PHASES}}
# ---------------------------------------------------------------------------
# Speaker palette
# ---------------------------------------------------------------------------
SPEAKER_PALETTE = [
("#4338ca", "#eef2ff", "#c7d2fe", "π΅"),
("#b45309", "#fffbeb", "#fde68a", "π‘"),
("#065f46", "#ecfdf5", "#a7f3d0", "π’"),
("#9a3412", "#fff7ed", "#fed7aa", "π "),
("#6b21a8", "#faf5ff", "#e9d5ff", "π£"),
("#0e7490", "#ecfeff", "#a5f3fc", "π·"),
]
def _assign_speakers(turns: list[dict]) -> dict:
seen: dict[str, dict] = {}
for t in turns:
sp = t.get("speaker", "?")
if sp not in seen:
i = len(seen) % len(SPEAKER_PALETTE)
c, bg, ibg, emoji = SPEAKER_PALETTE[i]
seen[sp] = {"color": c, "bg": bg, "initials_bg": ibg,
"emoji": emoji, "index": i}
return seen
def _speaker_avatar(name: str, entry: dict) -> str:
initials = "".join(w[0] for w in name.split()[:2]).upper() or "?"
return (
f'<span title="{_h(name)}" style="'
f'display:inline-flex;align-items:center;justify-content:center;'
f'width:30px;height:30px;border-radius:50%;background:{entry["initials_bg"]};'
f'color:{entry["color"]};font-weight:800;font-size:0.72em;flex-shrink:0;'
f'border:1.5px solid {entry["color"]}20">{initials}</span>'
)
_TURN_MERGE_GAP_S = 5 # merge same-speaker turns with gap < this many seconds
def _format_turns_html(seg: dict, speaker_map: dict) -> str:
"""Render episode turns, grouping consecutive same-speaker turns with small gaps."""
turns = seg.get("turns", [])
if not turns:
return '<p style="color:#94a3b8;font-style:italic">No turns in this segment.</p>'
# ββ Group consecutive same-speaker turns with gap < _TURN_MERGE_GAP_S ββββ
groups: list[dict] = []
for t in turns:
sp = t.get("speaker", "?")
cur = t.get("start_seconds", 0)
if (groups
and groups[-1]["speaker"] == sp
and (cur - groups[-1]["last_seconds"]) < _TURN_MERGE_GAP_S):
groups[-1]["texts"].append(t.get("text", ""))
groups[-1]["last_seconds"] = cur
groups[-1]["last_id"] = t.get("turn_id", "")
else:
groups.append({
"speaker": sp,
"texts": [t.get("text", "")],
"start_time": t.get("start_time", ""),
"last_seconds": cur,
"first_id": t.get("turn_id", ""),
"last_id": t.get("turn_id", ""),
})
parts = []
for g in groups:
sp = g["speaker"]
entry = speaker_map.get(sp, {"color": "#64748b", "bg": "#f8fafc",
"initials_bg": "#e2e8f0", "emoji": "β"})
avatar = _speaker_avatar(sp, entry)
ts = _h(g["start_time"])
merged = " ".join(g["texts"])
fid, lid = g["first_id"], g["last_id"]
id_label = f"#{fid}β#{lid}" if fid != lid else f"#{fid}"
# Wrap separate sentences for readability
sentences = [s.strip() for s in merged.replace("β¦", "β¦ ").split(" ") if s.strip()]
body = " ".join(f'<span style="opacity:0.9">{_h(s)}</span>' for s in sentences) or _h(merged)
parts.append(
f'<div style="display:flex;gap:10px;padding:11px 0;'
f'border-bottom:1px solid #f1f5f9;align-items:flex-start">'
f'{avatar}'
f'<div style="flex:1;min-width:0">'
f'<div style="display:flex;align-items:baseline;gap:8px;margin-bottom:4px">'
f'<span style="font-weight:700;color:{entry["color"]};font-size:0.85em">{_h(sp)}</span>'
f'<span style="font-family:monospace;font-size:0.72em;color:#94a3b8">{ts}</span>'
f'<span style="font-family:monospace;font-size:0.65em;color:#cbd5e1">{id_label}</span>'
f'</div>'
f'<div style="line-height:1.7;color:#1e293b;font-size:0.95em">{body}</div>'
f'</div></div>'
)
return f'<div style="font-family:system-ui,sans-serif">{"".join(parts)}</div>'
def _h(s) -> str:
return html_lib.escape(str(s))
def _section_cards_html(sections: list[dict], stages: dict, current_idx: int) -> str:
if not sections:
return ""
cards = []
for i, s in enumerate(sections):
stage = stages.get(s["section_id"], "pending")
if stage == "done":
bc, fc, icon = "#86efac", "#065f46", "β"
elif i == current_idx:
bc, fc, icon = "#93c5fd", "#1d4ed8", "βΆ"
else:
bc, fc, icon = "#e2e8f0", "#94a3b8", "β"
n = s["end_turn_id"] - s["start_turn_id"] + 1
cards.append(
f'<div style="flex:1;min-width:120px;border:2px solid {bc};'
f'border-radius:8px;padding:8px 12px;background:white">'
f'<div style="font-weight:700;color:{fc};font-size:0.85em">'
f'{icon} {_h(s["label"])}</div>'
f'<div style="font-family:monospace;font-size:0.72em;color:#94a3b8;margin-top:2px">'
f'{_h(s["start_time"])}β{_h(s["end_time"])} Β· {n} turns</div>'
f'</div>'
)
return f'<div style="display:flex;gap:8px;flex-wrap:wrap;margin:10px 0">{"".join(cards)}</div>'
def _episode_table_html(turns: list[dict], boundaries: list[dict]) -> str:
if not turns:
return '<p style="color:#94a3b8">No turns.</p>'
turn_ids = sorted(t["turn_id"] for t in turns)
bmap = {b["after_turn_id"]: b for b in boundaries}
cuts = [turn_ids[0]]
for b in sorted(boundaries, key=lambda x: x["after_turn_id"]):
idx = turn_ids.index(b["after_turn_id"]) if b["after_turn_id"] in turn_ids else -1
if idx >= 0 and idx < len(turn_ids) - 1:
cuts.append(turn_ids[idx + 1])
rows = (
"<tr style='background:#f1f5f9'>"
"<th style='padding:6px 10px;text-align:left;font-size:0.8em;font-weight:700;color:#475569'>Episode</th>"
"<th style='padding:6px 10px;text-align:left;font-size:0.8em;font-weight:700;color:#475569'>Turns</th>"
"<th style='padding:6px 10px;text-align:left;font-size:0.8em;font-weight:700;color:#475569'>Count</th>"
"</tr>"
)
for i, start in enumerate(cuts):
end = turn_ids[turn_ids.index(cuts[i + 1]) - 1] if i + 1 < len(cuts) else turn_ids[-1]
bg = "#f8fafc" if i % 2 else "white"
rows += (
f'<tr style="background:{bg}">'
f'<td style="padding:6px 10px;font-family:monospace;font-weight:700">ep{i+1:02d}</td>'
f'<td style="padding:6px 10px;font-family:monospace;color:#475569">{start}β{end}</td>'
f'<td style="padding:6px 10px;color:#94a3b8">{end-start+1}</td>'
f'</tr>'
)
if i < len(cuts) - 1:
after = cuts[i + 1] - 1
b = bmap.get(after, {})
sig = _h(b.get("boundary_signal", "boundary"))
conf = b.get("confidence", "?")
rat = _h(b.get("rationale", ""))
cc = {"high": "#065f46", "medium": "#b45309", "low": "#be123c"}.get(conf, "#64748b")
rows += (
f'<tr style="background:#fffbeb">'
f'<td colspan="3" style="padding:3px 10px;font-size:0.78em;color:#78350f;'
f'border-top:1px dashed #fde68a">'
f'βββ after turn {after} Β· <em>{sig}</em> Β· '
f'<strong style="color:{cc}">{conf}</strong> confidence β {rat}'
f'</td></tr>'
)
n_ep = len(cuts)
n_b = len(boundaries)
return (
f'<div style="font-size:0.8em;font-weight:700;color:#64748b;'
f'text-transform:uppercase;letter-spacing:0.05em;margin-bottom:6px">'
f'{n_b} boundary{"ies" if n_b!=1 else ""} β {n_ep} episode{"s" if n_ep!=1 else ""}'
f'</div>'
f'<div style="overflow-x:auto">'
f'<table style="border-collapse:collapse;width:100%;border:1px solid #e2e8f0;'
f'border-radius:8px;overflow:hidden">{rows}</table></div>'
)
def _uncertainty_html(seg: dict) -> str:
if not seg.get("uncertain"):
return ""
note = _h(seg.get("uncertainty_note") or "")
return (
f'<div role="alert" style="background:#fffbeb;border:1px solid #fbbf24;'
f'border-radius:8px;padding:10px 14px;margin-bottom:10px;display:flex;gap:8px;'
f'align-items:flex-start;font-size:0.88em">'
f'<span style="font-size:1.1em">β </span>'
f'<div><strong style="color:#78350f">AI flagged uncertain</strong>'
f'<span style="color:#92400e"> β {note}</span></div>'
f'</div>'
)
def _dim_desc_html(choice: str) -> str:
if not choice:
return ""
did = DIM_ID_FROM_CHOICE.get(choice, "")
desc = DIM_DESC_FROM_ID.get(did, "")
if not desc:
return ""
return (
f'<div style="background:#eff6ff;border-left:3px solid #4338ca;'
f'border-radius:0 6px 6px 0;padding:7px 12px;font-size:0.85em;'
f'color:#1e40af;margin-top:6px">{_h(desc)}</div>'
)
def _status_card(title: str, status: str = "success",
details: dict | None = None, error_msg: str | None = None) -> str:
colors = {
"success": ("#f0fdf4", "#065f46", "#86efac", "β"),
"error": ("#fef2f2", "#991b1b", "#fca5a5", "β"),
"warning": ("#fffbeb", "#78350f", "#fbbf24", "β "),
"processing": ("#eff6ff", "#1e40af", "#93c5fd", "β³"),
}
bg, tc, bc, icon = colors.get(status, colors["success"])
detail_html = ""
if details:
detail_html = '<div style="display:flex;flex-wrap:wrap;gap:16px;font-size:0.88em;margin-top:10px">'
for k, v in details.items():
detail_html += (
f'<div><span style="color:{tc};opacity:0.7">{_h(k)}:</span> '
f'<strong style="color:{tc}">{_h(str(v))}</strong></div>'
)
detail_html += '</div>'
error_html = (
f'<div style="background:rgba(0,0,0,0.05);border-radius:6px;padding:8px;'
f'font-family:monospace;font-size:0.78em;margin-top:8px;'
f'white-space:pre-wrap;word-break:break-all">{_h(error_msg)}</div>'
if error_msg else ""
)
return (
f'<div style="background:{bg};border:2px solid {bc};'
f'border-radius:10px;padding:14px 18px;margin:8px 0">'
f'<div style="color:{tc};font-weight:700;font-size:0.95em">'
f'{icon} {_h(title)}</div>'
f'{detail_html}{error_html}'
f'</div>'
)
# ---------------------------------------------------------------------------
# LLM progress indicator β shown while a blocking LLM call runs in background.
# Updates every 2 s via heartbeat yields; spinner cycles to signal activity.
# ---------------------------------------------------------------------------
_SPINNERS = ["β", "β", "β", "β"]
def _llm_progress_html(message: str, elapsed: int, est_total: int,
tokens_in: int, circ: str, spin_i: int) -> str:
"""
Rich status card shown during LLM calls.
Never freezes the UI β fn_process calls this from a heartbeat loop
while the actual LLM request runs in a daemon thread.
"""
pct = min(int(elapsed / max(est_total, 1) * 85), 85) # max 85% until done
remaining = max(est_total - elapsed, 0)
spinner = _SPINNERS[spin_i % len(_SPINNERS)]
bar_color = "#4338ca"
circ_color = "#065f46" if circ == "CLOSED" else "#b45309" if circ == "HALF_OPEN" else "#be123c"
circ_icon = "β" if circ == "CLOSED" else "β " if circ == "HALF_OPEN" else "β"
tok_str = f"{tokens_in:,}"
eta_str = f"~{remaining}s" if remaining > 5 else "finishingβ¦"
return (
f'<div style="background:#eff6ff;border:2px solid #93c5fd;'
f'border-radius:12px;padding:16px 20px;font-family:system-ui,sans-serif">'
# ββ Header row ββββββββββββββββββββββββββββββββββββββββββββββββββββ
f'<div style="display:flex;align-items:center;gap:10px;margin-bottom:12px">'
f'<span style="font-size:1.3em;line-height:1">{spinner}</span>'
f'<span style="font-weight:700;color:#1e3a8a;font-size:0.94em">{_h(message)}</span>'
f'<span style="margin-left:auto;font-family:monospace;font-size:0.84em;'
f'background:#dbeafe;padding:3px 9px;border-radius:6px;color:#1e40af;'
f'white-space:nowrap">{elapsed}s elapsed</span>'
f'</div>'
# ββ Progress bar ββββββββββββββββββββββββββββββββββββββββββββββββββ
f'<div style="background:#dbeafe;border-radius:5px;height:9px;'
f'margin-bottom:10px;overflow:hidden;position:relative">'
f'<div style="height:100%;width:{pct}%;background:{bar_color};'
f'border-radius:5px;transition:width 0.4s ease"></div>'
f'<span style="position:absolute;right:6px;top:-1px;font-size:0.7em;'
f'color:#6366f1;font-weight:700">{pct}%</span>'
f'</div>'
# ββ Metrics row βββββββββββββββββββββββββββββββββββββββββββββββββββ
f'<div style="display:flex;flex-wrap:wrap;gap:14px;font-size:0.8em;color:#475569">'
f'<span>β± Est. total: ~{est_total}s</span>'
f'<span>β ETA: {eta_str}</span>'
f'<span>π’ ~{tok_str} tokens in</span>'
f'<span style="color:{circ_color};font-weight:600">'
f'LLM circuit: {circ_icon} {circ}</span>'
f'</div>'
# ββ Note ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
f'<div style="margin-top:8px;font-size:0.75em;color:#94a3b8;font-style:italic">'
f'Processing in background β UI stays responsive. '
f'Typical 250-turn transcript: 45β90 s on HF shared inference.'
f'</div>'
f'</div>'
)
def _speaker_legend_html(speaker_map: dict) -> str:
if not speaker_map:
return ""
chips = []
for name, entry in speaker_map.items():
avatar = _speaker_avatar(name, entry)
chips.append(
f'<span style="display:inline-flex;align-items:center;gap:5px;'
f'padding:3px 8px;border-radius:20px;background:{entry["bg"]};'
f'border:1px solid {entry["initials_bg"]}">'
f'{avatar}'
f'<span style="font-size:0.82em;font-weight:600;color:{entry["color"]}">'
f'{_h(name)}</span></span>'
)
return (
f'<div style="display:flex;flex-wrap:wrap;gap:6px;margin-bottom:12px">'
f'{"".join(chips)}</div>'
)
def _kappa_html(report: dict) -> str:
ac1 = report.get("overall_ac1", report.get("overall_kappa", 0.0))
ac1_interp = report.get("ac1_interpretation", report.get("kappa_interpretation", ""))
ac1_ci = report.get("ac1_ci_95", [None, None])
gate = report.get("gate_passed", False)
col = "#065f46" if gate else "#be123c"
icon = "β" if gate else "β"
pct = int(min(max(ac1, 0) * 100, 100))
kappa = report.get("overall_kappa", 0.0)
kappa_ci = report.get("kappa_ci_95", [None, None])
divergence = report.get("kappa_ac1_divergence", 0.0)
div_flag = report.get("kappa_ac1_divergence_flag", False)
prev_warn = report.get("prevalence_warning", False)
n_segs = report.get("n_segments_total", 0)
n_dis = len(report.get("segments_in_disagreement", []))
ci_text = ""
if ac1_ci[0] is not None:
ci_text = f'<span style="font-size:0.75em;color:#64748b"> 95% CI [{ac1_ci[0]:.3f}, {ac1_ci[1]:.3f}]</span>'
prev_banner = ""
if prev_warn:
dominant = max(
((d, v["prevalence"]) for d, v in (report.get("category_distribution") or {}).items()),
key=lambda x: x[1], default=("?", 0)
)
prev_banner = (
f'<div style="background:#fffbeb;border:1px solid #fbbf24;border-radius:6px;'
f'padding:8px 12px;margin-bottom:10px;font-size:0.82em;color:#78350f">'
f'β <strong>Prevalence bias detected:</strong> {_h(dominant[0])} accounts for '
f'{dominant[1]:.0%} of codings. AC1 is the appropriate metric here.</div>'
)
kc = "#065f46" if kappa >= 0.70 else "#be123c"
if div_flag:
div_note = (
f'<div style="font-size:0.78em;color:#64748b;margin-top:4px">'
f'Cohen\'s ΞΊ = <span style="font-weight:700;color:{kc}">{kappa:.3f}</span>'
+ (f' [{kappa_ci[0]:.3f}, {kappa_ci[1]:.3f}]' if kappa_ci[0] is not None else '') +
f' Β· |AC1 β ΞΊ| = <strong style="color:#d97706">{divergence:.3f}</strong> (prevalence bias)'
f'</div>'
)
else:
div_note = (
f'<div style="font-size:0.78em;color:#94a3b8;margin-top:4px">'
f'Cohen\'s ΞΊ = <span style="color:{kc}">{kappa:.3f}</span>'
+ (f' [{kappa_ci[0]:.3f}, {kappa_ci[1]:.3f}]' if kappa_ci[0] is not None else '') +
f' (reference β Gwet 2008 primary)</div>'
)
dim_src = report.get("ac1_per_dimension") or report.get("kappa_per_dimension") or {}
dim_label = "AC1" if "ac1_per_dimension" in report else "ΞΊ"
dim_rows = ""
for dim in ["D1","D2","D3","D4","D5","D6","D7","D8","D9","NS","NA"]:
v = dim_src.get(dim)
if v is None:
dim_rows += (
f'<div style="display:flex;gap:8px;align-items:center;padding:3px 0;'
f'border-top:1px solid #f1f5f9;opacity:0.4">'
f'<span style="font-weight:700;font-size:0.82em;width:32px">{dim}</span>'
f'<span style="font-size:0.75em;color:#94a3b8;flex:1">insufficient data</span>'
f'</div>'
)
continue
vp = int(min(max(v, 0) * 100, 100))
vc = "#065f46" if v >= 0.70 else "#b45309" if v >= 0.50 else "#be123c"
dim_rows += (
f'<div style="display:flex;gap:8px;align-items:center;padding:4px 0;'
f'border-top:1px solid #f1f5f9">'
f'<span style="font-weight:700;font-size:0.82em;width:32px">{dim}</span>'
f'<div style="flex:1;height:6px;background:#e2e8f0;border-radius:3px;overflow:hidden">'
f'<div style="height:100%;width:{vp}%;background:{vc};border-radius:3px"></div></div>'
f'<span style="font-weight:700;font-size:0.82em;color:{vc};width:40px;text-align:right">'
f'{v:.3f}</span>'
f'</div>'
)
return (
f'<div style="background:white;border:1px solid #e2e8f0;border-radius:12px;padding:20px">'
f'{prev_banner}'
f'<div style="display:flex;align-items:flex-end;gap:14px;margin-bottom:4px">'
f'<span style="font-size:3em;font-weight:800;color:{col};line-height:1">{ac1:.3f}</span>'
f'<div>'
f'<div style="font-weight:700;color:{col};font-size:1em">{icon} {_h(ac1_interp)}</div>'
f'<div style="font-size:0.76em;color:#94a3b8">Gwet\'s AC1 Β· gate β₯ 0.70</div>'
f'</div></div>'
f'{ci_text}'
f'<div style="position:relative;height:10px;background:#e2e8f0;border-radius:5px;margin:10px 0">'
f'<div style="position:absolute;height:100%;width:{pct}%;background:{col};border-radius:5px"></div>'
f'<div style="position:absolute;left:70%;top:-4px;height:18px;width:2px;background:#94a3b8"></div>'
f'<div style="position:absolute;left:70%;top:-16px;font-size:0.68em;color:#94a3b8;'
f'transform:translateX(-50%)">0.70</div>'
f'</div>'
f'<div style="font-size:0.83em;color:#64748b">'
f'{n_segs} segments Β· {n_dis} disagreement{"s" if n_dis!=1 else ""}</div>'
f'{div_note}'
f'<div style="font-size:0.75em;font-weight:700;text-transform:uppercase;'
f'letter-spacing:0.07em;color:#94a3b8;margin:14px 0 6px">Per-Dimension {dim_label}</div>'
f'{dim_rows}'
f'</div>'
)
def _rules_html(rules: list[dict]) -> str:
if not rules:
return (
'<div style="background:#f0fdf4;border:1px solid #86efac;border-radius:8px;'
'padding:12px 16px;color:#065f46;font-size:0.9em">No rules pending review.</div>'
)
TYPE_META = {
"boundary_clarification": ("#dbeafe", "#1e3a8a", "Boundary"),
"disambiguation_rule": ("#fce7f3", "#831843", "Disambiguation"),
"behavioral_marker_refinement": ("#d1fae5", "#064e3b", "Marker Refinement"),
}
cards = []
for r in rules:
bg, tc, label = TYPE_META.get(r.get("rule_type", ""), ("#f1f5f9", "#334155", "Rule"))
dims = _h(", ".join(r.get("dimensions_involved") or []))
desc = _h(r.get("description", ""))
rat = _h(r.get("rationale", ""))
conf = _h(r.get("confidence", ""))
note = _h(r.get("agent2_note", ""))
rid = _h(r.get("rule_id", ""))
created = r.get("created_at", "")[:10]
cards.append(
f'<article style="border:1px solid #e2e8f0;border-radius:10px;'
f'padding:16px 18px;margin-bottom:12px;background:white">'
f'<div style="display:flex;justify-content:space-between;flex-wrap:wrap;gap:6px;margin-bottom:10px">'
f'<div style="display:flex;align-items:center;gap:8px">'
f'<span style="background:{bg};color:{tc};border-radius:20px;'
f'padding:2px 10px;font-size:0.72em;font-weight:700;text-transform:uppercase">{label}</span>'
f'<span style="font-family:monospace;font-size:0.75em;color:#94a3b8">{rid} Β· {created}</span>'
f'</div>'
f'<span style="font-size:0.78em;color:#64748b">dims: <strong>{dims}</strong></span>'
f'</div>'
f'<p style="font-size:0.93em;color:#1e293b;line-height:1.6;margin:0 0 8px">{desc}</p>'
f'<p style="font-size:0.82em;color:#475569;margin:0 0 8px"><strong>Evidence:</strong> {rat}</p>'
f'<div style="font-size:0.78em;color:#64748b">'
f'Confidence: <strong>{conf}</strong>'
+ (f' Β· Note: {note}' if note else '') +
f'</div></article>'
)
return "".join(cards)
def _sections_html(sections: list[dict], n_turns: int,
agent0_rt: float, n_speakers: int,
all_turns: list[dict] | None = None) -> str:
"""
Rich sections display for the Review Sections page.
Uses native HTML <details>/<summary> for expand-to-read-content β no JS required.
Each section is collapsed by default (researcher sees the label and size at a glance)
and can be expanded to read the AI summary + first 8 turns of actual transcript.
Label format in the textarea is "s01: Label" so the mapping is unambiguous.
"""
if not sections:
return '<p style="color:#94a3b8;font-style:italic">No sections detected.</p>'
avg = n_turns // len(sections) if sections else 0
total = n_turns
# ββ 1. Agent completion card βββββββββββββββββββββββββββββββββββββββββββββ
agent_card = (
f'<div style="background:#f0fdf4;border:2px solid #86efac;border-radius:10px;'
f'padding:14px 18px;margin-bottom:14px;font-family:system-ui,sans-serif">'
f'<div style="display:flex;align-items:flex-start;gap:10px;flex-wrap:wrap">'
f'<div style="flex:1;min-width:200px">'
f'<div style="display:flex;align-items:center;gap:8px;margin-bottom:5px">'
f'<span style="font-size:1.1em">β</span>'
f'<strong style="color:#065f46;font-size:0.95em">Agent 0 β Structural Segmenter</strong>'
f'<span style="background:#bbf7d0;color:#14532d;font-size:0.72em;font-weight:700;'
f'padding:2px 8px;border-radius:20px;margin-left:4px">completed in {agent0_rt:.1f}s</span>'
f'</div>'
f'<div style="font-size:0.82em;color:#166534;line-height:1.7">'
f'<strong>{total}</strong> turns Β· <strong>{n_speakers}</strong> speaker(s) β '
f'<strong>{len(sections)}</strong> sections detected '
f'(avg {avg} turns/section)<br>'
f'<em>Basis: lexical cohesion (Hearst 1997) Β· topic modelling (Purver et al. 2006) '
f'Β· activity phases (Stahl 2006; Roschelle & Teasley 1995)</em>'
f'</div>'
f'</div>'
f'<div style="text-align:right;font-family:monospace;font-size:0.78em;color:#6b7280">'
f'Qwen2.5-72B Β· T=0.1</div>'
f'</div>'
f'</div>'
)
# ββ 2. Expandable section list βββββββββββββββββββββββββββββββββββββββββββ
palette = [
("#4338ca", "#eef2ff"), # indigo
("#b45309", "#fffbeb"), # amber
("#065f46", "#f0fdf4"), # emerald
("#9a3412", "#fff7ed"), # orange
("#6b21a8", "#faf5ff"), # purple
("#0e7490", "#ecfeff"), # cyan
("#be123c", "#fff1f2"), # rose
]
warnings = []
detail_items = []
for i, s in enumerate(sections):
col, bg = palette[i % len(palette)]
n = s["end_turn_id"] - s["start_turn_id"] + 1
pct = round(n / total * 100) if total else 0
if pct > 30 and len(sections) > 2:
warnings.append(
f'<strong>{_h(s["label"])}</strong> ({n} turns, {pct}%) is unusually large. '
f'Expand it below to check if it contains distinct sub-topics.'
)
# ββ Bar ββ
bar = (
f'<div style="background:#e2e8f0;border-radius:3px;height:4px;'
f'width:80px;display:inline-block;vertical-align:middle;margin-left:8px">'
f'<div style="height:100%;width:{min(pct,100)}%;background:{col};border-radius:3px">'
f'</div></div>'
)
# ββ 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'<div style="padding:5px 0;border-bottom:1px solid #f1f5f9">'
f'<span style="font-weight:700;font-size:0.82em;color:{col};margin-right:6px">'
f'{sp}</span>'
f'<span style="font-size:0.72em;color:#94a3b8;font-family:monospace;'
f'margin-right:8px">{ts}</span>'
f'<span style="font-size:0.88em;color:#1e293b">{_h(txt)}</span>'
f'</div>'
)
if len(sec_turns) > 8:
rows.append(
f'<div style="font-size:0.75em;color:#94a3b8;padding:4px 0;'
f'font-style:italic">β― {len(sec_turns)-8} more turns</div>'
)
excerpt_html = (
f'<div style="margin-top:10px">'
f'<div style="font-size:0.72em;font-weight:700;text-transform:uppercase;'
f'letter-spacing:0.06em;color:#94a3b8;margin-bottom:6px">'
f'Transcript excerpt (first {len(shown)} of {n} turns)</div>'
f'{"".join(rows)}'
f'</div>'
)
summary_text = _h(s.get("summary", "No summary provided."))
detail_items.append(
f'<details style="border:1px solid {col}40;border-radius:10px;'
f'margin-bottom:8px;overflow:hidden;font-family:system-ui,sans-serif">'
# ββ Collapsed header (always visible) ββββββββββββββββββββββββββ
f'<summary style="cursor:pointer;padding:12px 16px;background:{bg};'
f'border-left:5px solid {col};display:flex;align-items:center;'
f'gap:10px;list-style:none;-webkit-appearance:none">'
f'<span style="font-size:0.7em;font-weight:800;color:{col};'
f'text-transform:uppercase;letter-spacing:0.08em;min-width:28px">'
f'{_h(s["section_id"])}</span>'
f'<span style="font-weight:700;color:#1e293b;flex:1;font-size:0.92em">'
f'{_h(s["label"])}</span>'
f'<span style="font-size:0.72em;color:#64748b;white-space:nowrap;'
f'font-family:monospace">{_h(s["start_time"])}β{_h(s["end_time"])}</span>'
f'<span style="font-size:0.72em;color:{col};font-weight:700;white-space:nowrap">'
f' {n} turns ({pct}%)</span>'
f'{bar}'
f'<span style="color:{col};font-size:0.8em;margin-left:4px">βΌ read</span>'
f'</summary>'
# ββ Expanded content ββββββββββββββββββββββββββββββββββββββββββββ
f'<div style="padding:14px 16px;background:white;'
f'border-top:1px solid {col}20">'
f'<p style="font-size:0.85em;color:#334155;margin:0 0 8px;line-height:1.65">'
f'<strong style="color:{col}">AI summary:</strong> {summary_text}</p>'
f'{excerpt_html}'
f'</div>'
f'</details>'
)
section_list = f'<div style="margin-bottom:12px">{"".join(detail_items)}</div>'
# ββ 3. Warnings ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
warn_html = ""
if warnings:
items = "".join(f"<li style='margin:4px 0'>{w}</li>" for w in warnings)
warn_html = (
f'<div style="background:#fffbeb;border:1px solid #fbbf24;border-radius:8px;'
f'padding:10px 14px;margin-bottom:12px;font-size:0.83em;color:#78350f">'
f'<strong>β Size note</strong>'
f'<ul style="margin:6px 0 0;padding-left:18px">{items}</ul>'
f'</div>'
)
# ββ 4. Label editor instruction ββββββββββββββββββββββββββββββββββββββββββ
instr = (
f'<div style="background:#f8fafc;border:1px solid #e2e8f0;'
f'border-left:4px solid #4338ca;border-radius:0 8px 8px 0;'
f'padding:10px 14px;font-size:0.84em;color:#334155;margin-bottom:4px">'
f'<strong>Rename sections below</strong> β each line follows the format '
f'<code style="background:#e2e8f0;padding:1px 5px;border-radius:3px">'
f's01: Your Label</code>. '
f'Edit the text after the colon only; the <code>s01:</code> 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'</div>'
)
return agent_card + section_list + warn_html + instr
def _episode_dialogue_html(segments: list[dict], boundaries: list[dict],
speaker_map: dict) -> str:
"""
Render each proposed episode with its actual dialogue turns + boundary markers.
Design goal: the researcher must be able to READ the transcript before
deciding whether to accept the AI's proposed boundary positions.
Showing only turn-ID tables (the old approach) is opaque.
Rules:
- Up to 5 turns shown per episode; truncation indicated clearly
- Speaker avatars + timestamps match the coding canvas
- Boundary markers show signal type, confidence, and AI rationale
- Entire view is scrollable so the page does not grow unbounded
"""
if not segments:
return (
'<p style="color:#94a3b8;font-style:italic;padding:12px">'
'No episode data yet.</p>'
)
bmap: dict[int, dict] = {}
for b in boundaries:
bmap[b.get("after_turn_id", -1)] = b
conf_colors = {
"high": ("#065f46", "#f0fdf4", "#86efac"),
"medium": ("#92400e", "#fffbeb", "#fde68a"),
"low": ("#991b1b", "#fef2f2", "#fca5a5"),
}
parts: list[str] = []
for i, seg in enumerate(segments):
turns = seg.get("turns", [])
ep_id = seg.get("segment_id", f"ep{i+1:02d}")
ep_num = ep_id.split("_ep")[-1] if "_ep" in ep_id else str(i + 1)
n_turns = len(turns)
# Episode header strip
parts.append(
f'<div style="background:#f1f5f9;border-left:4px solid #4338ca;'
f'padding:7px 14px;display:flex;align-items:center;gap:10px;'
f'font-family:system-ui,sans-serif">'
f'<span style="font-size:0.72em;font-weight:800;color:#4338ca;'
f'text-transform:uppercase;letter-spacing:0.08em">Episode {ep_num}</span>'
f'<span style="font-size:0.75em;color:#64748b">{n_turns} turns</span>'
+ (f'<span style="font-size:0.75em;color:#94a3b8;font-style:italic">'
f'{_h(seg.get("rationale","")[:80])}{"β¦" if len(seg.get("rationale",""))>80 else ""}'
f'</span>' if seg.get("rationale") else '')
+ '</div>'
)
# 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'<div style="display:flex;gap:9px;padding:8px 14px;'
f'background:white;border-bottom:1px solid #f1f5f9;'
f'align-items:flex-start;font-family:system-ui,sans-serif">'
f'{avatar}'
f'<div style="flex:1;min-width:0">'
f'<div style="display:flex;gap:8px;margin-bottom:2px;align-items:baseline">'
f'<span style="font-weight:700;font-size:0.82em;color:{entry["color"]}">'
f'{_h(sp)}</span>'
f'<span style="font-size:0.7em;color:#94a3b8;font-family:monospace">{ts}</span>'
f'<span style="font-size:0.68em;color:#cbd5e1;font-family:monospace">'
f'#{t.get("turn_id","")}</span>'
f'</div>'
f'<div style="font-size:0.88em;color:#1e293b;line-height:1.6">{_h(text)}</div>'
f'</div></div>'
)
if n_turns > 5:
parts.append(
f'<div style="padding:5px 14px;font-size:0.75em;color:#94a3b8;'
f'background:#fafafa;border-bottom:1px solid #f1f5f9;font-style:italic">'
f'β― {n_turns - 5} more turn{"s" if n_turns-5>1 else ""} in this episode</div>'
)
# 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'<div style="background:{bg};border-top:1px dashed {bc};'
f'border-bottom:1px dashed {bc};padding:6px 14px;'
f'display:flex;align-items:center;gap:8px;flex-wrap:wrap;'
f'font-family:system-ui,sans-serif">'
f'<span style="font-size:0.72em;font-weight:800;color:{tc};'
f'text-transform:uppercase;letter-spacing:0.06em">β boundary</span>'
f'<span style="background:{tc}18;color:{tc};padding:1px 7px;'
f'border-radius:4px;font-size:0.75em;font-weight:700">{_h(sig)}</span>'
f'<span style="font-size:0.72em;color:{tc};font-weight:600">{conf} confidence</span>'
+ (f'<span style="font-size:0.72em;color:#64748b;font-style:italic">'
f'β {_h(rat[:100])}{"β¦" if len(rat)>100 else ""}</span>' if rat else '')
+ f'<span style="margin-left:auto;font-size:0.68em;color:#94a3b8;'
f'font-family:monospace">after #{last_tid}</span>'
f'</div>'
)
return (
f'<div style="border:1px solid #e2e8f0;border-radius:10px;overflow:hidden;'
f'max-height:55vh;overflow-y:auto;font-family:system-ui,sans-serif">'
+ "".join(parts)
+ '</div>'
)
def _agent_log_html(logs: list[dict]) -> str:
if not logs:
return (
'<p style="font-size:0.8em;color:#94a3b8;font-style:italic">'
'No agents have run yet.</p>'
)
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'<div style="display:flex;justify-content:space-between;font-size:0.78em">'
f'<span style="color:#64748b">{_h(str(k))}</span>'
f'<span style="font-weight:600">{_h(str(v))}</span></div>'
for k, v in extras.items()
)
parts.append(
f'<div style="border:1px solid #e2e8f0;border-radius:8px;'
f'padding:10px 12px;margin-bottom:8px;background:white">'
f'<div style="display:flex;justify-content:space-between;margin-bottom:4px">'
f'<span style="font-weight:700;font-size:0.88em;color:#1e293b">{agent}</span>'
f'<span style="font-size:0.72em;color:#94a3b8">{ts} Β· {runtime}s</span>'
f'</div>'
f'<div style="font-size:0.76em;color:#94a3b8">model: <strong style="color:#4338ca">{model}</strong></div>'
f'{extra_lines}'
f'</div>'
)
return "".join(parts)
def _make_log_entry(agent: str, runtime_s: float, **stats) -> dict:
return {
"agent": agent,
"model": MODEL_ID,
"temperature": TEMPERATURE,
"runtime_s": round(runtime_s, 1),
"timestamp": datetime.now(timezone.utc).strftime("%H:%M:%S"),
**stats,
}
def _coding_progress_html(state: dict) -> str:
sections = state.get("sections", [])
idx = state.get("section_idx", 0)
segs = _current_section_segments(state)
codings = state.get("codings", {})
cidx = state.get("coding_idx", 0)
if not segs:
return ""
coded = sum(1 for s in segs if codings.get(s["segment_id"], {}).get("dimension_id"))
total = len(segs)
pct = int(coded / total * 100) if total else 0
sec = sections[idx] if idx < len(sections) else {}
ep_num = min(cidx, total - 1) + 1
# Total across all sections
all_coded = sum(1 for v in codings.values() if v.get("dimension_id"))
all_segs = sum(
len(state.get("section_segments_coded", {}).get(s["section_id"], []))
for s in sections
)
return (
f'<div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:10px;'
f'padding:12px 16px;margin-bottom:12px">'
f'<div style="display:flex;justify-content:space-between;align-items:baseline;'
f'margin-bottom:6px">'
f'<div style="font-size:0.88em;font-weight:700;color:#1e293b">'
f'Section {idx+1}/{len(sections)} β {_h(sec.get("label",""))}</div>'
f'<div style="font-size:0.82em;color:#64748b">Episode {ep_num} of {total}</div>'
f'</div>'
f'<div style="height:6px;background:#e2e8f0;border-radius:3px;overflow:hidden">'
f'<div style="height:100%;width:{pct}%;background:#4338ca;border-radius:3px;'
f'transition:width 0.3s"></div></div>'
f'<div style="display:flex;justify-content:space-between;margin-top:4px;'
f'font-size:0.75em;color:#94a3b8">'
f'<span>{coded}/{total} episodes coded this section</span>'
f'<span>{all_coded}/{all_segs} total</span>'
f'</div>'
f'</div>'
)
# ===========================================================================
# STATE
# ===========================================================================
def _empty_state() -> dict:
return {
"session_id": "",
"researcher_id": "",
"turns": [],
"speakers": {},
"sections": [],
"section_idx": 0,
"section_stages": {},
"section_boundaries": {},
"section_segments": {},
"section_segments_coded": {},
"coding_idx": 0,
"codings": {},
"stage": "upload",
"kappa_report": None,
"agent_logs": [],
"screener_result": None,
"ssrl_codings": {},
}
def _auto_session_id(researcher_id: str = "", source_name: str = "") -> str:
stamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
base = (Path(source_name).stem or "drive").replace(" ", "_")
rid = (researcher_id or "R").strip().replace(" ", "_")
return f"{rid}_{base}_{stamp}"
def _loading_card(title: str, subtitle: str = "Please waitβ¦", spin: str = "β") -> str:
return (
'<div style="background:#eff6ff;border:2px solid #93c5fd;border-radius:12px;'
'padding:18px 20px;margin:10px 0;font-family:system-ui,sans-serif">'
'<div style="display:flex;align-items:center;gap:12px">'
f'<div style="font-size:1.35em;color:#1e3a8a">{spin}</div>'
f'<div><div style="font-weight:800;color:#1e3a8a;font-size:1.02em">{_h(title)}</div>'
f'<div style="margin-top:4px;font-size:0.86em;color:#475569">{_h(subtitle)}</div></div>'
'</div></div>'
)
def _session_dir(state: dict) -> Path:
return SESSIONS_ROOT / state["session_id"]
def _current_section(state: dict) -> dict | None:
secs = state.get("sections", [])
idx = state.get("section_idx", 0)
return secs[idx] if secs and idx < len(secs) else None
def _current_section_segments(state: dict) -> list[dict]:
sec = _current_section(state)
return state["section_segments_coded"].get(sec["section_id"], []) if sec else []
def _turns_for_section(turns: list[dict], section: dict) -> list[dict]:
return [t for t in turns
if section["start_turn_id"] <= t["turn_id"] <= section["end_turn_id"]]
def _persist(state: dict) -> None:
"""Save state to local disk AND Drive (if Drive is configured)."""
skip = {"turns", "kappa_report"}
slim = {k: v for k, v in state.items() if k not in skip}
# Local save (fast, always)
try:
d = _session_dir(state)
d.mkdir(parents=True, exist_ok=True)
(d / "app_state.json").write_text(
json.dumps(slim, indent=2, ensure_ascii=False), encoding="utf-8"
)
except Exception:
pass
# Drive save (async-ish β run in background thread so UI isn't blocked)
rid = state.get("researcher_id", "")
sid = state.get("session_id", "")
if rid and sid:
def _drive_save():
try:
svc = get_drive_service(rid)
if svc:
write_session_to_drive(svc, rid, sid, slim)
except Exception as e:
print(f"[Drive] Background save failed: {e}", file=_sys.stderr)
import threading as _threading
_threading.Thread(target=_drive_save, daemon=True).start()
def _seconds_to_hms(s: float) -> str:
return str(timedelta(seconds=int(s)))
def _push_log(state: dict, entry: dict) -> dict:
logs = list(state.get("agent_logs", []))
logs.append(entry)
state["agent_logs"] = logs[-10:]
return state
# ===========================================================================
# CODING RENDER HELPERS
# ===========================================================================
def _segment_label(seg: dict, codings: dict) -> str:
sid = seg["segment_id"]
ep = sid.split("_ep")[-1] if "_ep" in sid else sid[-4:]
c = codings.get(sid, {})
did = c.get("dimension_id") or seg.get("dimension_id") or "?"
sec = c.get("secondary_dimension_id")
coded = "β" if c.get("dimension_id") else "β"
flag = " β " if seg.get("uncertain") else ""
multi = f"+{sec}" if sec else ""
return f"{coded} ep{ep} [{did}{multi}]{flag}"
def _proposal_md(seg: dict) -> str:
did = seg.get("dimension_id", "?")
rat = seg.get("rationale", "")
sec_did = seg.get("secondary_dimension_id")
sec_rat = seg.get("secondary_rationale", "")
lines = [f"> **AI primary: {did}** \n> {rat}"]
if sec_did:
lines.append(f"> **AI secondary: {sec_did}** \n> _{sec_rat or 'co-occurring dimension'}_")
tags = []
if seg.get("confident"):
tags.append("β
Confident")
if seg.get("uncertain"):
tags.append(f"β οΈ Uncertain β {seg.get('uncertainty_note', '')}")
if sec_did:
tags.append(f"π Multi-dimensional: {did} + {sec_did}")
return ("\n\n".join(lines) + ("\n\n" + " ".join(tags) if tags else "")).strip()
CODING_EMPTY = (
"", # 0 coding_progress_comp
gr.update(choices=[], value=None), # 1 segment_jump
"", # 2 turns_html_comp
"", # 3 uncertainty_comp
gr.update(value="", visible=False), # 4 proposal_comp
gr.update(choices=DIM_CHOICES, value=None), # 5 dim_radio
"", # 6 dim_desc_comp
gr.update(choices=SEC_DIM_CHOICES, value=SEC_NONE), # 7 secondary_dim_drop
"", # 8 comment_box
gr.update(visible=False), # 9 next_section_btn
gr.update(choices=SSRL_CHOICES, value=SSRL_NONE), # 10 ssrl_radio
gr.update(visible=False), # 11 ssrl_col β hidden when no D1-D9
)
def _render_coding(state: dict) -> tuple:
segs = _current_section_segments(state)
codings = state.get("codings", {})
cidx = state.get("coding_idx", 0)
speaker_map = state.get("speakers", {})
if not segs:
return CODING_EMPTY
seg = segs[min(cidx, len(segs) - 1)]
sid = seg["segment_id"]
existing = codings.get(sid, {})
saved = existing.get("dimension_id", "")
choice = next((c for c in DIM_CHOICES if c.startswith(saved)), None)
saved_sec = existing.get("secondary_dimension_id")
sec_choice = (
next((c for c in DIM_CHOICES if c.startswith(saved_sec)), SEC_NONE)
if saved_sec else SEC_NONE
)
saved_ssrl = existing.get("ssrl_phase")
ssrl_choice = (
next((c for c in SSRL_CHOICES if c.startswith(saved_ssrl)), SSRL_NONE)
if saved_ssrl else SSRL_NONE
)
all_done = len(codings) >= len(segs) and all(
codings.get(s["segment_id"], {}).get("dimension_id") for s in segs
)
labels = [_segment_label(s, codings) for s in segs]
_skip_prefixes = ("NS", "NA", "None", "")
show_ssrl = bool(choice) and not any(choice.startswith(p) for p in _skip_prefixes)
return (
_coding_progress_html(state), # 0
gr.update(choices=labels, value=labels[min(cidx, len(segs) - 1)]), # 1
_format_turns_html(seg, speaker_map), # 2
_uncertainty_html(seg), # 3
gr.update(value=_proposal_md(seg), visible=False), # 4
gr.update(choices=DIM_CHOICES, value=choice), # 5
_dim_desc_html(choice or ""), # 6
gr.update(choices=SEC_DIM_CHOICES, value=sec_choice), # 7
existing.get("comment", ""), # 8
gr.update(visible=all_done), # 9
gr.update(choices=SSRL_CHOICES, value=ssrl_choice), # 10
gr.update(visible=show_ssrl), # 11 ssrl_col
)
# ===========================================================================
# PAGE NAVIGATION HELPER
# ===========================================================================
_PAGE_NAMES = ["welcome", "setup", "screener", "sections", "pipeline",
"done", "agreement", "library", "lexicon"]
def _show(page: str) -> list:
"""Return 9 gr.update(visible=...) items, one per page."""
return [gr.update(visible=(p == page)) for p in _PAGE_NAMES]
# ===========================================================================
# CALLBACKS
# ===========================================================================
# ββ Process: Parse + Agent 0 combined ββββββββββββββββββββββββββββββββββββββββ
def _parse_drive_choice(choice: str) -> tuple[str, str]:
if not choice or "::" not in choice:
raise gr.Error("Pick a transcript from Drive first.")
file_id, file_name = choice.split("::", 1)
return file_id, file_name
def fn_refresh_drive_transcripts(researcher_id: str):
rid = (researcher_id or "").strip()
if not rid:
return (
gr.update(choices=[], value=None, interactive=False),
_status_card("Enter Researcher ID first, then refresh Drive files.", "warning"),
)
register_researcher(rid)
try:
service = get_drive_service(rid)
if not service:
return (
gr.update(choices=[], value=None, interactive=False),
_status_card(
"Google Drive is not configured yet.",
"warning",
{
"Needed secret": "GOOGLE_SERVICE_ACCOUNT_JSON",
"Folder ID": "GOOGLE_DRIVE_FOLDER_ID",
"Tip": "Copy the DRIVE DEBUG block from the logs if this should already be working.",
},
),
)
files = list_transcripts(service)
if not files:
return (
gr.update(choices=[], value=None, interactive=False),
_status_card(
"No transcript files found in the configured Drive folder.",
"warning",
{"Tip": "If this is unexpected, copy the DRIVE DEBUG block from the logs."},
),
)
choices = [
(f"{f['name']} Β· {f.get('modified_time', '')[:10]}", f"{f['id']}::{f['name']}")
for f in files
]
return (
gr.update(choices=choices, value=choices[0][1], interactive=True),
_status_card("Drive connected. Select a transcript and click Process.", "success", {"Files": len(choices)}),
)
except Exception as e:
diag = format_drive_diagnostic("refresh_drive_transcripts", researcher_id=rid, error=e)
print(diag, file=_sys.stderr)
return (
gr.update(choices=[], value=None, interactive=False),
_status_card(
"Drive check failed.",
"error",
{"Tip": "Copy the DRIVE DEBUG block below and send it with the issue."},
diag,
),
)
def fn_load_previous_session(researcher_id: str, state: dict):
"""
Generator: load saved session from Drive, re-parse transcript, navigate to screener.
Outputs: PARSE_OUTPUTS (state, pipeline_bar_html, process_status, process_btn,
screener_summary_html, screener_turns_html_c, screener_to_sections_btn, *ALL_PAGES)
"""
rid = (researcher_id or "").strip()
def _bail(msg: str, kind: str = "warning"):
yield (state, _pipeline_bar_html(state),
_status_card(msg, kind), _BTN_FREE,
"", "", gr.update(visible=False), *_show("setup"))
if not rid:
yield from _bail("Enter Researcher ID first.")
return
# ββ Step 1: initial feedback ββββββββββββββββββββββββββββββββββββββββββββββ
yield (state, _pipeline_bar_html(state),
_status_card("Connecting to Driveβ¦", "info"), _BTN_BUSY,
"", "", gr.update(visible=False), *_show("setup"))
try:
service = get_drive_service(rid)
except Exception as e:
yield from _bail(f"Drive connection failed: {e}", "error")
return
if not service:
yield from _bail("Drive not configured β check GOOGLE_CREDENTIALS.", "warning")
return
# ββ Step 2: load saved state ββββββββββββββββββββββββββββββββββββββββββββββ
yield (state, _pipeline_bar_html(state),
_status_card("Loading saved sessionβ¦", "info"), _BTN_BUSY,
"", "", gr.update(visible=False), *_show("setup"))
try:
loaded = load_session_from_drive(service, rid)
except Exception as e:
diag = format_drive_diagnostic("load_previous_session", researcher_id=rid, error=e)
print(diag, file=_sys.stderr)
yield from _bail(f"Could not load Drive session: {e}", "error")
return
if not loaded:
yield from _bail("No previous session found for this researcher ID.", "warning")
return
new_state = _empty_state()
new_state.update(loaded)
new_state["researcher_id"] = rid
sid = new_state.get("session_id") or _auto_session_id(rid, "restored_session")
new_state["session_id"] = sid
# ββ Step 3: re-parse transcript to restore `turns` ββββββββββββββββββββββββ
drive_file_id = new_state.get("_drive_file_id")
source_name = new_state.get("_source_file_name", "transcript.vtt")
if drive_file_id:
yield (new_state, _pipeline_bar_html(new_state),
_status_card(f"Re-parsing '{source_name}' to restore transcriptβ¦", "info"),
_BTN_BUSY, "", "", gr.update(visible=False), *_show("setup"))
try:
text = read_file_from_drive(service, drive_file_id)
suffix = Path(source_name).suffix or ".vtt"
tmp = Path(tempfile.mktemp(suffix=suffix))
tmp.write_text(text, encoding="utf-8")
parsed = parse_transcript(str(tmp))
new_state["turns"] = parsed.get("turns", [])
new_state["speakers"] = parsed.get("speakers", new_state.get("speakers", {}))
try:
tmp.unlink()
except Exception:
pass
except Exception as e:
yield from _bail(
f"Could not re-parse transcript: {e}. "
"Re-upload the file manually to continue.", "warning"
)
return
else:
# No file_id stored (old session or local upload) β warn, turns unavailable
gr.Warning("Transcript not available for re-parsing β turns will be missing. "
"Re-upload the file to restore the full view.")
# ββ Step 4: build resume summary card ββββββββββββββββββββββββββββββββββββ
n_turns = len(new_state.get("turns", []))
n_sections = len(new_state.get("sections", []))
n_codings = len(new_state.get("codings", {}))
stage_map = {
"complete": "All sections coded β",
"coding": "Coding in progress",
"sectioned": "Sections detected, boundaries pending",
"parsed": "Transcript parsed, screener run",
}
stage_label = stage_map.get(new_state.get("stage", ""), "Screener complete")
sum_html = (
'<div style="background:#f0fdf4;border:2px solid #86efac;border-radius:10px;'
'padding:16px;font-family:system-ui,sans-serif">'
'<div style="font-weight:700;color:#166534;font-size:1.05em;margin-bottom:10px">'
'β Session Resumed</div>'
'<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-bottom:10px">'
f'<div style="text-align:center"><div style="font-size:1.7em;font-weight:800;color:#15803d">{n_turns}</div>'
'<div style="font-size:0.75em;color:#4b5563">Turns</div></div>'
f'<div style="text-align:center"><div style="font-size:1.7em;font-weight:800;color:#15803d">{n_sections}</div>'
'<div style="font-size:0.75em;color:#4b5563">Sections</div></div>'
f'<div style="text-align:center"><div style="font-size:1.7em;font-weight:800;color:#15803d">{n_codings}</div>'
'<div style="font-size:0.75em;color:#4b5563">Episodes coded</div></div>'
'</div>'
f'<div style="font-size:0.85em;color:#374151">Stage: <strong>{stage_label}</strong>'
f' Β· Session: <code style="background:#dcfce7;padding:1px 5px;border-radius:3px">{sid}</code></div>'
'<div style="margin-top:8px;font-size:0.78em;color:#6b7280">'
'Click <strong>Detect Sections β</strong> to continue β sections and boundaries '
'are loaded from your saved session (no LLM re-run).</div>'
'</div>'
)
gr.Info(f"Session resumed: {n_sections} sections Β· {n_codings} episodes coded.")
yield (
new_state,
_pipeline_bar_html(new_state),
_status_card(f"Session loaded Β· {n_turns} turns Β· {n_sections} sections Β· {n_codings} coded",
"success", {"Session": sid}),
_BTN_FREE,
sum_html,
"", # screener_turns_html_c (no turn detail on resume)
gr.update(visible=True), # screener_to_sections_btn β clicking uses cached sections
*_show("screener"),
)
def fn_process_with_source(drive_choice: str, researcher_id: str, state: dict):
"""Wrapper: Drive-only transcript selection with automatic session IDs."""
temp_path: Path | None = None
service = None
rid = (researcher_id or "").strip()
if not rid:
raise gr.Error("Enter your Researcher ID first.")
if not drive_choice:
raise gr.Error("Choose a transcript from Drive first.")
try:
service = get_drive_service(rid)
if not service:
diag = format_drive_diagnostic("process_drive_file", researcher_id=rid)
print(diag, file=_sys.stderr)
raise gr.Error("Drive is not configured. Copy the DRIVE DEBUG block from the logs.")
file_id, file_name = _parse_drive_choice(drive_choice)
session_id = _auto_session_id(rid, file_name)
text = read_file_from_drive(service, file_id)
suffix = Path(file_name).suffix or ".txt"
temp_path = Path(tempfile.mktemp(prefix="drive_transcript_", suffix=suffix))
temp_path.write_text(text, encoding="utf-8")
# Store Drive source so we can re-parse on session resume
state = dict(state)
state["_drive_file_id"] = file_id
state["_source_file_name"] = file_name
effective_file = type("DriveFile", (), {"name": str(temp_path)})()
except gr.Error:
raise
except Exception as e:
file_id, file_name = ("", "")
try:
file_id, file_name = _parse_drive_choice(drive_choice)
except Exception:
pass
diag = format_drive_diagnostic(
"process_drive_file",
researcher_id=rid,
file_id=file_id,
file_name=file_name,
error=e,
)
print(diag, file=_sys.stderr)
raise gr.Error("Drive file could not be read. Copy the DRIVE DEBUG block from the logs.")
final_state: dict | None = None
try:
for out in fn_parse_transcript(effective_file, session_id, researcher_id, state):
if isinstance(out, tuple) and out and isinstance(out[0], dict):
final_state = out[0]
yield out
finally:
if temp_path and temp_path.exists():
try:
temp_path.unlink()
except Exception:
pass
# Persist lightweight state snapshot to Drive for resume.
if final_state and (service or get_drive_service(rid)):
try:
svc = service or get_drive_service(rid)
if svc:
slim = {k: v for k, v in final_state.items() if k not in {"turns", "kappa_report"}}
write_session_to_drive(
svc,
final_state.get("researcher_id", rid),
final_state.get("session_id", session_id),
slim,
)
except Exception:
pass
def fn_parse_transcript(file_obj, session_id: str, researcher_id: str, state: dict):
"""
Phase 1 β Generator: parse transcript, auto-run screener, navigate to screener page.
Outputs: state, pipeline_bar_html, process_status, process_btn,
screener_summary_html, screener_turns_html_c, screener_to_sections_btn, *ALL_PAGES
"""
if file_obj is None:
raise gr.Error("Choose a transcript first.")
if not researcher_id.strip():
raise gr.Error("Enter your Researcher ID (e.g. R1).")
session_id = session_id.strip() or _auto_session_id(
researcher_id, getattr(file_obj, "name", "transcript")
)
rid = researcher_id.strip()
_BTN_BUSY = gr.update(interactive=False, value="β³ Processingβ¦")
_BTN_FREE = gr.update(interactive=True, value="Process Drive Transcript β")
def _parse_yield(msg, status="processing", details=None, btn=None, nav="setup"):
return (
state,
_pipeline_bar_html(state),
_status_card(msg, status, details),
btn if btn is not None else _BTN_BUSY,
"", # screener_summary_html
"", # screener_turns_html_c
gr.update(visible=False), # screener_to_sections_btn
*_show(nav),
)
yield _parse_yield("Parsing transcriptβ¦")
try:
turns = parse_transcript(file_obj.name)
except Exception as e:
raise gr.Error(f"Could not parse transcript: {e}") from e
if len(turns) < 5:
raise gr.Error(f"Only {len(turns)} turns found β check the transcript format.")
speaker_map = _assign_speakers(turns)
speakers = list(speaker_map.keys())
duration = _seconds_to_hms(turns[-1]["start_seconds"] - turns[0]["start_seconds"])
new_state = _empty_state()
new_state.update({
"session_id": session_id,
"researcher_id": rid,
"turns": turns,
"speakers": speaker_map,
"stage": "upload",
})
d = SESSIONS_ROOT / session_id
d.mkdir(parents=True, exist_ok=True)
(d / "parsed_turns.json").write_text(
json.dumps(turns, indent=2, ensure_ascii=False), encoding="utf-8"
)
yield _parse_yield(
f"Running pre-screen on {len(turns)} turnsβ¦",
details={"Turns": len(turns), "Speakers": ", ".join(speakers), "Duration": duration},
)
# ββ Auto-run screener (pre-LLM, fast) ββββββββββββββββββββββββββββββββββββ
screener_ok = False
try:
result = screen_transcript(turns)
rd = result_to_dict(result)
new_state["screener_result"] = rd
new_state["stage"] = "screened"
n_wins = len(rd["candidate_windows"])
savings = f"{rd['estimated_llm_savings']:.0%}"
sum_html = _screener_summary_html(rd)
turns_html = _screener_turns_html(rd, speaker_map)
screener_ok = True
except Exception as e:
sum_html = (
f'<div style="background:#fffbeb;border:1px solid #fde68a;border-radius:8px;'
f'padding:14px 16px;color:#92400e;font-size:0.9em">'
f'<strong>Screener could not run automatically.</strong><br>'
f'Error: {html_lib.escape(str(e))}<br>'
f'Click <em>Re-run Screener</em> below to try again, '
f'or click <em>Detect Sections β</em> to continue without screening.</div>'
)
turns_html = ""
yield (
new_state,
_pipeline_bar_html(new_state),
_status_card(
f"Parsed {len(turns)} turns Β· {len(speakers)} speaker(s).",
"success",
{"Session": session_id, "Turns": len(turns), "Speakers": ", ".join(speakers)},
),
_BTN_FREE,
sum_html, # screener_summary_html
turns_html, # screener_turns_html_c
gr.update(visible=True), # screener_to_sections_btn β always show
*_show("screener"),
)
def fn_run_agent0(state: dict):
"""
Phase 2 β Generator: run Agent 0 on parsed turns, navigate to sections.
Triggered by 'Continue to Sections' button on screener page.
Outputs: state, pipeline_bar_html, sections_display_html, sections_labels_box, *ALL_PAGES
"""
reset_circuit() # fresh start β don't carry over failures from a previous run
turns = state.get("turns", [])
if not turns:
raise gr.Error("No transcript loaded β process a file first.")
# ββ Sections cache: if Agent 0 already ran, skip LLM and go to sections β
existing_sections = state.get("sections", [])
if existing_sections:
n_t = len(turns)
speakers = list(state.get("speakers", {}).keys())
sec_html = _sections_html(existing_sections, n_t, 0, len(speakers), all_turns=turns)
labels_txt = "\n".join(f"{s['section_id']}: {s['label']}" for s in existing_sections)
gr.Info(f"Using cached sections ({len(existing_sections)} detected). Re-run via Back if you need fresh detection.")
yield (
state,
_pipeline_bar_html(state),
sec_html,
labels_txt,
*_show("sections"),
)
return
session_id = state.get("session_id", "")
n_t = len(turns)
if n_t > 600:
tok_per_turn = 9; effective_turns = n_t // 2
elif n_t > 400:
tok_per_turn = 12; effective_turns = n_t
elif n_t > 200:
tok_per_turn = 16; effective_turns = n_t
else:
tok_per_turn = 22; effective_turns = n_t
est_in_tok = effective_turns * tok_per_turn + 700
est_out_tok = 900
est_timeout = max(45, int((est_in_tok + est_out_tok) / 35 + 20))
def _hb(elapsed: int, spin_i: int):
return (
state,
_pipeline_bar_html(state),
_llm_progress_html(
f"Agent 0 β Structural Segmenter: analysing {n_t} turnsβ¦",
elapsed, est_timeout, est_in_tok, circuit_state(), spin_i,
),
"", # sections_labels_box
*_show("screener"),
)
yield _hb(0, 0)
result_q: _queue.Queue = _queue.Queue()
def _run_a0():
try:
res = run_sectioning(turns=turns, session_id=session_id)
result_q.put(("ok", res))
except Exception as exc:
result_q.put(("err", exc))
thread = threading.Thread(target=_run_a0, daemon=True)
thread.start()
t_llm = time.perf_counter()
spin_i = 1
while thread.is_alive():
time.sleep(2)
elapsed = int(time.perf_counter() - t_llm)
yield _hb(elapsed, spin_i)
spin_i += 1
outcome, payload = result_q.get()
if outcome == "err":
raise gr.Error(f"Section detection failed: {payload}") from payload
result = payload
sections = result["sections"]
if not sections:
raise gr.Error("Agent 0 returned no sections β try again.")
from agent0_sectioner import build_system_prompt, load_dimension_labels
agent0_rt = round(time.perf_counter() - t_llm, 1)
new_state = dict(state)
new_state.update({
"sections": sections,
"section_stages": {s["section_id"]: "pending" for s in sections},
"stage": "sectioned",
"_agent0_overview": result.get("session_overview", ""),
})
log_entry = _make_log_entry(
"Agent 0 β Structural Segmenter", agent0_rt,
sections_proposed=len(sections),
warnings=len(result.get("warnings", [])),
system_prompt_preview=build_system_prompt(load_dimension_labels())[:120],
)
new_state = _push_log(new_state, log_entry)
d = SESSIONS_ROOT / session_id
d.mkdir(parents=True, exist_ok=True)
(d / "sections_proposed.json").write_text(
json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8"
)
overview = result.get("session_overview", "")
speakers = list(state.get("speakers", {}).keys())
sec_html = _sections_html(sections, n_t, agent0_rt, len(speakers), all_turns=turns)
labels_txt = "\n".join(f"{s['section_id']}: {s['label']}" for s in sections)
if result.get("warnings"):
gr.Warning("Coverage warnings β check the section table.")
gr.Info(f"Ready: {n_t} turns Β· {len(sections)} sections detected in {agent0_rt}s.")
yield (
new_state,
_pipeline_bar_html(new_state),
sec_html,
labels_txt,
*_show("sections"),
)
# ββ Legacy wrapper kept for Drive flow ββββββββββββββββββββββββββββββββββββββββ
def fn_process(file_obj, session_id: str, researcher_id: str, state: dict):
"""Alias β fn_parse_transcript (Drive flow calls this via fn_process_with_source)."""
yield from fn_parse_transcript(file_obj, session_id, researcher_id, state)
# ββ Local file upload (new, no Drive needed) ββββββββββββββββββββββββββββββββββ
def fn_process_local(file, researcher_id: str, state: dict):
"""
Generator: load a local .txt/.vtt/.csv transcript, run screener, navigate to screener.
Outputs match PARSE_OUTPUTS.
"""
rid = (researcher_id or "").strip()
if not file:
raise gr.Error("Select a local transcript file first.")
if not rid:
raise gr.Error("Enter your Researcher ID first.")
path = Path(file.name) if hasattr(file, "name") else Path(str(file))
sid = _auto_session_id(rid, path.stem)
file_mock = type("F", (), {"name": str(path)})()
yield from fn_parse_transcript(file_mock, sid, rid, state)
# ββ Original fn_process body (kept below for Drive fn_process_with_source) βββ
# ββ Confirm sections ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def fn_confirm_sections(labels_text: str, state: dict):
"""
Generator: immediately shows a 'confirming' state (so the user knows
their click registered), then navigates to the pipeline page.
"""
sections = state.get("sections", [])
if not sections:
raise gr.Error("No sections to confirm β process a transcript first.")
_BUSY_HTML = (
'<div style="background:#eff6ff;border:2px solid #93c5fd;border-radius:10px;'
'padding:14px 18px;font-family:system-ui,sans-serif">'
'<div style="display:flex;align-items:center;gap:10px">'
'<span style="font-size:1.2em">β</span>'
'<strong style="color:#1e3a8a">Saving section labels and loading pipelineβ¦</strong>'
'</div>'
'<div style="margin-top:8px;font-size:0.82em;color:#4b5563">'
'Please wait β this takes only a moment.'
'</div></div>'
)
# ββ Yield 1: immediate feedback, stay on sections page ββββββββββββββββββββ
yield (
state,
*_show("sections"),
gr.update(value=_BUSY_HTML), # sections_display_html
gr.update(interactive=False, value="β³ Savingβ¦"), # confirm_sections_btn
gr.update(visible=True), # col_run_all_boundaries (Column β visible only)
gr.update(visible=False), # col_boundary_review
gr.update(visible=False), # col_coding
)
# ββ Process (fast: no LLM, just in-memory + disk) βββββββββββββββββββββββββ
# Parse "s01: My Label" or plain "My Label" (both accepted)
raw_lines = [l.strip() for l in labels_text.strip().splitlines() if l.strip()]
labels = []
for line in raw_lines:
# Strip "sXX: " or "sXX:" prefix if present
if ":" in line:
prefix, _, rest = line.partition(":")
if prefix.strip().lower().startswith("s") and prefix.strip()[1:].isdigit():
labels.append(rest.strip())
continue
labels.append(line)
confirmed = [dict(s, label=labels[i] if i < len(labels) else s["label"])
for i, s in enumerate(sections)]
if len(labels) != len(sections):
gr.Warning(
f"Label count mismatch ({len(labels)} labels for {len(sections)} sections) β "
f"AI labels used for any extras."
)
new_state = dict(state)
new_state.update({
"sections": confirmed,
"section_idx": 0,
"section_stages": {s["section_id"]: "pending" for s in confirmed},
"section_a1a_results": {},
"stage": "coding",
})
d = _session_dir(new_state)
(d / "sections_confirmed.json").write_text(
json.dumps(confirmed, indent=2, ensure_ascii=False), encoding="utf-8"
)
_persist(new_state)
gr.Info(f"{len(confirmed)} sections confirmed. Click 'Detect Episode Boundaries' to continue.")
print(f"[Confirm Sections] {len(confirmed)} sections saved for session {new_state['session_id']}")
# ββ Yield 2: navigate to pipeline page ββββββββββββββββββββββββββββββββββββ
yield (
new_state,
*_show("pipeline"),
gr.update(value=""), # sections_display_html (leaving)
gr.update(interactive=True, value="Confirm Sections β"), # reset button for if user navigates back
gr.update(visible=True), # col_run_all_boundaries
gr.update(visible=False), # col_boundary_review
gr.update(visible=False), # col_coding
)
# ββ Agent 1a β parallel boundary detection βββββββββββββββββββββββββββββββββββ
def fn_run_all_boundaries(state: dict):
reset_circuit() # fresh start for this pipeline step
sections = state.get("sections", [])
if not sections:
raise gr.Error("Confirm sections first.")
if not state.get("turns"):
raise gr.Error("No parsed turns β parse the transcript first.")
# ββ Cache check: if all sections already have boundaries, skip LLM βββββββ
existing = state.get("section_a1a_results", {})
if existing and all(s["section_id"] in existing for s in sections):
collected = {sid: r for sid, r in existing.items()}
# Jump straight to showing first section review
sec = sections[0]
turns = _turns_for_section(state["turns"], sec)
result = collected.get(sec["section_id"], {})
bounds = result.get("boundaries", [])
ids_txt = ", ".join(str(b["after_turn_id"]) for b in bounds)
yield (
state,
"β Episode boundaries already detected β showing cached results.",
"",
gr.update(visible=False),
gr.update(visible=True, value=_episode_table_html(turns, bounds)),
gr.update(visible=True, value=ids_txt),
_section_header_md(sec),
_agent_log_html(state.get("agent_logs", [])),
"",
gr.update(value=_episode_dialogue_html(turns, bounds)),
)
return
n = len(sections)
session_overview = state.get("_agent0_overview", "")
collected = {}
pipeline_stats_html = ""
def _a1a_banner(done: int, total: int, status: str = "running") -> str:
pct = int(done / total * 100) if total else 0
color = "#4338ca" if status == "running" else "#065f46" if status == "done" else "#be123c"
icon = "β³" if status == "running" else "β" if status == "done" else "β"
return (
f'<div style="background:#eff6ff;border:2px solid #93c5fd;border-radius:10px;'
f'padding:12px 16px;font-family:system-ui,sans-serif">'
f'<div style="display:flex;align-items:center;gap:8px;margin-bottom:8px">'
f'<span>{icon}</span>'
f'<strong style="color:#1e3a8a;font-size:0.9em">Agent 1a β Boundary Detector</strong>'
f'<span style="margin-left:auto;font-size:0.78em;color:#6b7280">'
f'{done}/{total} sections Β· {pct}%</span>'
f'</div>'
f'<div style="background:#dbeafe;border-radius:4px;height:7px;overflow:hidden">'
f'<div style="height:100%;width:{pct}%;background:{color};border-radius:4px;'
f'transition:width 0.4s"></div></div>'
f'<div style="margin-top:6px;font-size:0.77em;color:#4b5563">'
f'Parallel map pattern (Dean & Ghemawat 2004) Β· '
f'Basis: Schegloff (2007) adjacency pairs Β· '
f'Krippendorff (2004) unitising precedes categorising'
f'</div></div>'
)
# Initial yield β show banner immediately
yield (
state,
f"β³ Running Agent 1a on {n} section(s) (max 3 concurrent)β¦",
"",
gr.update(visible=False),
gr.update(visible=False, value=""),
gr.update(visible=False, value=""),
"",
_agent_log_html(state.get("agent_logs", [])),
_a1a_banner(0, n, "running"),
gr.update(value=""), # episode_dialogue_html β clear while processing
)
pstats = PipelineStats(agent_name="Agent 1a β Boundary Detector", n_sections=n)
try:
for sr, pstats in run_boundaries_parallel(
sections=sections,
all_turns=state["turns"],
session_id=state["session_id"],
session_overview=session_overview,
):
if sr.success:
collected[sr.section_id] = sr.result
else:
gr.Warning(f"Section {sr.section_id} failed: {sr.error}")
processed = len(pstats.results)
failed_sids = {x.section_id for x in pstats.results if not x.success}
prog_lines = []
for s in sections:
sid = s["section_id"]
res = collected.get(sid)
failed = sid in failed_sids
if res:
b = len(res.get("boundaries", []))
e = len(res.get("segments", []))
prog_lines.append(f"β **{sid}** {s['label']} β {b} boundaries β {e} episodes")
elif failed:
prog_lines.append(f"β **{sid}** {s['label']} β ERROR")
else:
prog_lines.append(f"β³ **{sid}** {s['label']}β¦")
status_md = f"**{processed}/{n} sections complete**\n\n" + "\n\n".join(prog_lines)
pipeline_stats_html = render_pipeline_stats_html(pstats)
yield (
state,
status_md,
pipeline_stats_html,
gr.update(visible=False),
gr.update(visible=False, value=""),
gr.update(visible=False, value=""),
"",
_agent_log_html(state.get("agent_logs", [])),
_a1a_banner(processed, n, "running"),
gr.update(value=""), # episode_dialogue_html β still processing
)
except Exception as e:
raise gr.Error(f"Parallel boundary detection failed: {e}") from e
# All done β update state
state = dict(state)
n_success = len(collected)
n_error = n - n_success
for sec in sections:
sid = sec["section_id"]
result = collected.get(sid)
if result:
state["section_boundaries"][sid] = result["boundaries"]
state["section_segments"][sid] = result["segments"]
state["section_stages"][sid] = "boundaries"
state.setdefault("section_a1a_results", {})[sid] = result
else:
state["section_stages"][sid] = "error"
log = _make_log_entry(
"Agent 1a β Boundary Detector (parallel)", round(pstats.parallel_wall_s, 1),
sections_ok=n_success, sections_error=n_error,
speedup=f"{pstats.speedup:.1f}x",
total_est_tokens=pstats.total_estimated_tokens,
)
state = _push_log(state, log)
_persist(state)
sec = sections[0]
turns = _turns_for_section(state["turns"], sec)
result = collected.get(sec["section_id"], {})
bounds = result.get("boundaries", [])
ids_txt = ", ".join(str(b["after_turn_id"]) for b in bounds)
status_final = (
f"β {n_success}/{n} sections analysed "
f"({pstats.parallel_wall_s:.0f}s parallel Β· {pstats.speedup:.1f}Γ speedup).\n\n"
f"Review boundaries for each section below, then confirm to start coding."
)
if n_error:
status_final += f"\n\nβ {n_error} section(s) failed β enter boundary turn IDs manually."
gr.Info(f"Parallel analysis complete: {n_success}/{n} sections OK.")
print(f"[Agent 1a] Complete: {n_success}/{n} OK in {pstats.parallel_wall_s:.1f}s "
f"({pstats.speedup:.1f}Γ speedup)")
# Build dialogue view for the first section to review
first_result = collected.get(sec["section_id"], {})
first_segs = first_result.get("segments", [])
ep_dial_html = _episode_dialogue_html(first_segs, bounds, state["speakers"])
yield (
state,
status_final,
pipeline_stats_html,
gr.update(visible=True),
gr.update(visible=True, value=_episode_table_html(turns, bounds)),
gr.update(visible=True, value=ids_txt),
f"### Reviewing: {sec['label']} ({sec['section_id']})",
_agent_log_html(state["agent_logs"]),
_a1a_banner(n_success, n, "done" if n_error == 0 else "error"),
ep_dial_html, # full dialogue view β researcher reads this before confirming
)
# ββ Confirm boundaries + run Agent 1b ββββββββββββββββββββββββββββββββββββββββ
def fn_confirm_and_code(boundary_ids_text: str, state: dict):
sec = _current_section(state)
if not sec:
raise gr.Error("No section loaded.")
session_id = state.get("session_id") or _auto_session_id(state.get("researcher_id", ""), sec.get("label", "section"))
state = dict(state)
state["session_id"] = session_id
turns = _turns_for_section(state["turns"], sec)
valid_ids = {t["turn_id"] for t in turns}
boundaries: list[dict] = []
for tok in boundary_ids_text.split(","):
tok = tok.strip()
if not tok:
continue
try:
tid = int(tok)
except ValueError:
raise gr.Error(f"'{tok}' is not a valid turn ID.")
if tid not in valid_ids:
raise gr.Error(
f"Turn {tid} is outside this section "
f"(valid: {min(valid_ids)}β{max(valid_ids)})."
)
boundaries.append({"boundary_id": f"r_{tid}", "after_turn_id": tid,
"confidence": "high", "boundary_signal": "researcher_defined",
"rationale": "Set by researcher."})
boundaries.sort(key=lambda b: b["after_turn_id"])
segments = boundaries_to_segments(sec, turns, boundaries, session_id)
if not segments:
raise gr.Error("No segments produced β check your boundary turn IDs.")
# ββ Min-episode guard: merge segments with < 2 turns into the next one βββ
_MIN_TURNS = 2
merged: list[dict] = []
pending_turns: list = []
for seg in segments:
seg_turns = seg.get("turns", [])
combined = pending_turns + seg_turns
pending_turns = []
if len(combined) < _MIN_TURNS:
pending_turns = combined # carry forward, merge into next
else:
if merged:
seg["turns"] = combined
else:
seg["turns"] = combined
merged.append(seg)
# Any remaining tiny tail β append to last segment
if pending_turns and merged:
merged[-1]["turns"] = merged[-1].get("turns", []) + pending_turns
elif pending_turns:
merged = [{"turns": pending_turns, "segment_id": "s_merged",
"label": "Merged", "section_id": sec["section_id"]}]
segments = merged if merged else segments
if not segments:
raise gr.Error("No segments produced after merging short episodes.")
state["section_boundaries"][sec["section_id"]] = boundaries
state["section_segments"][sec["section_id"]] = segments
# ββ Agent 1b cache: if proposals already exist for this section, skip LLM β
cached_coded = state.get("section_segments_coded", {}).get(sec["section_id"])
if cached_coded:
state["section_stages"][sec["section_id"]] = "coding"
state["coding_idx"] = 0
n_uncertain = sum(1 for s in cached_coded if s.get("uncertain"))
msg = f"β {len(cached_coded)} episodes (cached β no LLM re-run)."
if n_uncertain:
msg += f" **{n_uncertain} flagged β **"
gr.Info(f"Using cached Agent 1b proposals ({len(cached_coded)} episodes).")
yield state, msg, gr.update(visible=True), *_render_coding(state), _agent_log_html(state.get("agent_logs", []))
return
yield (
state,
_loading_card("Loading coding stageβ¦", f"Agent 1b is preparing {len(segments)} episode(s) for coding."),
gr.update(visible=False),
*CODING_EMPTY,
"",
)
agent1a_result = state.get("section_a1a_results", {}).get(sec["section_id"])
t0 = time.perf_counter()
try:
coded, llm_stats = run_coding_with_context(
section=sec,
segments=segments,
agent1a_result=agent1a_result,
)
except Exception as e:
raise gr.Error(f"Agent 1b failed: {e}") from e
rt = round(time.perf_counter() - t0, 1)
n_uncertain = sum(1 for s in coded if s.get("uncertain"))
state["section_segments_coded"][sec["section_id"]] = coded
state["section_stages"][sec["section_id"]] = "coding"
state["coding_idx"] = 0
log = _make_log_entry(
"Agent 1b β Dimension Coder", rt,
segments_coded=len(coded),
uncertain_flagged=n_uncertain,
system_prompt_preview=f"Context chain: section={sec['label']}",
user_prompt_preview=f"Code {len(segments)} segments",
)
state = _push_log(state, log)
d = _session_dir(state)
(d / f"segments_{sec['section_id']}.json").write_text(
json.dumps(coded, indent=2, ensure_ascii=False), encoding="utf-8"
)
msg = f"β {len(coded)} segments coded ({rt}s)."
if n_uncertain:
msg += f" **{n_uncertain} flagged β β review these first.**"
gr.Info(f"{len(coded)} segments coded. {n_uncertain} uncertain.")
yield state, msg, gr.update(visible=True), *_render_coding(state), _agent_log_html(state["agent_logs"])
# ββ Navigate segments βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def fn_navigate(direction: int, dim_choice: str, sec_choice: str, comment: str,
ssrl_choice: str, state: dict):
segs = _current_section_segments(state)
if not segs:
return state, *_render_coding(state)
idx = state.get("coding_idx", 0)
codings = dict(state.get("codings", {}))
sid = segs[idx]["segment_id"]
if dim_choice:
codings[sid] = {
"dimension_id": DIM_ID_FROM_CHOICE[dim_choice],
"secondary_dimension_id":SEC_ID_FROM_CHOICE.get(sec_choice or SEC_NONE),
"comment": comment.strip(),
"ssrl_phase": SSRL_ID_FROM_CHOICE.get(ssrl_choice or SSRL_NONE),
}
state = dict(state)
state["codings"] = codings
state["coding_idx"] = max(0, min(idx + direction, len(segs) - 1))
return state, *_render_coding(state)
def fn_jump(label: str, state: dict):
segs = _current_section_segments(state)
if not segs or not label:
return state, *_render_coding(state)
codings = state.get("codings", {})
labels = [_segment_label(s, codings) for s in segs]
state = dict(state)
if label in labels:
state["coding_idx"] = labels.index(label)
return state, *_render_coding(state)
def fn_reveal(state: dict):
segs = _current_section_segments(state)
if not segs:
return gr.update(visible=False)
seg = segs[min(state.get("coding_idx", 0), len(segs) - 1)]
return gr.update(value=_proposal_md(seg), visible=True)
def fn_dim_desc(choice: str):
"""Return dim description HTML + SSRL visibility update."""
desc = _dim_desc_html(choice or "")
# Show SSRL only when a substantive D1-D9 code is selected (not NS / NA / None)
_skip_prefixes = ("NS", "NA", "None", "")
show_ssrl = bool(choice) and not any(choice.startswith(p) for p in _skip_prefixes)
return desc, gr.update(visible=show_ssrl)
def fn_skip_episode(state: dict):
"""Mark current episode as non-codeable and advance to next."""
idx = state.get("current_index", 0)
segs = state.get("segments", [])
if 0 <= idx < len(segs):
sid = segs[idx].get("segment_id")
state.setdefault("codings", {})[sid] = {
"dimension_id": "SKIP",
"secondary_dim": None,
"ssrl_phase": None,
"comment": "Not codeable β skipped",
}
return fn_navigate(+1, "SKIP", SEC_NONE, "", SSRL_NONE, state)
# ββ Next section / finish βββββββββββββββββββββββββββββββββββββββββββββββββββββ
def fn_next_section(dim_choice: str, sec_choice: str, comment: str,
ssrl_choice: str, state: dict):
segs = _current_section_segments(state)
codings = dict(state.get("codings", {}))
idx = state.get("coding_idx", 0)
if segs and dim_choice:
sid = segs[min(idx, len(segs) - 1)]["segment_id"]
codings[sid] = {
"dimension_id": DIM_ID_FROM_CHOICE[dim_choice],
"secondary_dimension_id":SEC_ID_FROM_CHOICE.get(sec_choice or SEC_NONE),
"comment": comment.strip(),
"ssrl_phase": SSRL_ID_FROM_CHOICE.get(ssrl_choice or SSRL_NONE),
}
new_state = dict(state)
new_state["codings"] = codings
sections = new_state.get("sections", [])
sec_idx = new_state.get("section_idx", 0)
cur_id = sections[sec_idx]["section_id"]
new_state["section_stages"][cur_id] = "done"
next_idx = sec_idx + 1
if next_idx >= len(sections):
# All done β navigate to done page
new_state["stage"] = "complete"
_write_coding_file(new_state)
_persist(new_state)
gr.Info("All sections coded! Download your coding file.")
print(f"[Done] All {len(sections)} sections coded for session {new_state['session_id']}")
return (
new_state,
*_show("done"),
_section_cards_html(sections, new_state["section_stages"], sec_idx),
"", # section_header_md
gr.update(visible=False), # col_boundary_review
gr.update(visible=False), # col_coding
gr.update(value=""), # boundary_display_html
gr.update(value=""), # boundary_ids_box
gr.update(value=""), # episode_dialogue_html
)
# More sections remain β populate boundary review for the next section
new_state["section_idx"] = next_idx
new_state["coding_idx"] = 0
next_sec = sections[next_idx]
n = next_sec["end_turn_id"] - next_sec["start_turn_id"] + 1
hdr = (
f"### Section {next_idx+1} of {len(sections)}: {next_sec['label']}\n"
f"*{next_sec.get('summary','')}* Β· "
f"turns {next_sec['start_turn_id']}β{next_sec['end_turn_id']} ({n} turns)"
)
_persist(new_state)
result = new_state.get("section_a1a_results", {}).get(next_sec["section_id"], {})
bounds = result.get("boundaries", [])
next_segs = result.get("segments", [])
turns = _turns_for_section(new_state["turns"], next_sec)
ids_txt = ", ".join(str(b["after_turn_id"]) for b in bounds)
ep_html = _episode_dialogue_html(next_segs, bounds, new_state["speakers"])
gr.Info(f"Section {next_idx+1} of {len(sections)}: {next_sec['label']}")
print(f"[Next Section] Moving to section {next_idx+1}: {next_sec['label']}")
return (
new_state,
*_show("pipeline"),
_section_cards_html(sections, new_state["section_stages"], next_idx),
hdr,
gr.update(visible=True), # col_boundary_review
gr.update(visible=False), # col_coding
gr.update(value=_episode_table_html(turns, bounds)), # boundary_display_html
gr.update(value=ids_txt), # boundary_ids_box
ep_html, # episode_dialogue_html
)
# ββ Download ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _write_coding_file(state: dict) -> Path:
all_segs: list[dict] = []
for sec in state.get("sections", []):
all_segs.extend(state["section_segments_coded"].get(sec["section_id"], []))
codings = state.get("codings", {})
output = {
"session_id": state["session_id"],
"researcher_id": state["researcher_id"],
"codings": [
{
"segment_id": s["segment_id"],
"section_id": s.get("section_id", ""),
"dimension_id": codings.get(s["segment_id"], {}).get("dimension_id", ""),
"secondary_dimension_id":codings.get(s["segment_id"], {}).get("secondary_dimension_id"),
"ssrl_phase": codings.get(s["segment_id"], {}).get("ssrl_phase"),
"comment": codings.get(s["segment_id"], {}).get("comment", ""),
}
for s in all_segs
],
}
segs_all = {"segments": [{k: v for k, v in s.items() if k != "turns"} for s in all_segs]}
d = _session_dir(state)
(d / "segments_all.json").write_text(
json.dumps(segs_all, indent=2, ensure_ascii=False), encoding="utf-8"
)
out = d / f"coding_{state['researcher_id']}.json"
out.write_text(json.dumps(output, indent=2, ensure_ascii=False), encoding="utf-8")
return out
def fn_download(state: dict):
if not state.get("sections"):
raise gr.Error("No coding to download yet.")
path = _write_coding_file(state)
tmp = Path(tempfile.mktemp(suffix=f"_{path.name}"))
tmp.write_bytes(path.read_bytes())
return str(tmp)
# ββ Agreement βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def fn_calculate_kappa(r2_file, state: dict):
if r2_file is None:
raise gr.Error("Upload your co-researcher's coding file first.")
if not state.get("session_id"):
raise gr.Error("Complete the Pipeline first β session ID not set.")
d = _session_dir(state)
r1_path = d / f"coding_{state['researcher_id']}.json"
segs_path = d / "segments_all.json"
if not r1_path.exists():
raise gr.Error("Your own coding file not found β download it from the Pipeline first.")
if not segs_path.exists():
raise gr.Error("Segments file not found β complete the coding pipeline first.")
r2_path = d / "coding_R2.json"
r2_path.write_bytes(Path(r2_file.name).read_bytes())
t0 = time.perf_counter()
try:
report = calculate_kappa_report(
session_id=state["session_id"],
coding_r1_path=r1_path,
coding_r2_path=r2_path,
proposed_segments_path=segs_path,
output_path=d / "kappa_report.json",
)
except Exception as e:
raise gr.Error(f"Kappa calculation failed: {e}") from e
rt = round(time.perf_counter() - t0, 1)
gate = report.get("gate_passed", False)
n_dis = len(report.get("segments_in_disagreement", []))
state = dict(state)
state["kappa_report"] = report
log = _make_log_entry("Kappa Calculator", rt,
kappa=round(report.get("overall_kappa", 0), 3),
gate_passed=gate, disagreements=n_dis)
state = _push_log(state, log)
if gate:
gr.Info(f"ΞΊ={report['overall_kappa']:.3f} β gate passed! {n_dis} disagreements to resolve.")
else:
gr.Warning(f"ΞΊ={report['overall_kappa']:.3f} β below 0.70 threshold.")
dis_md = ""
if n_dis:
dis = report.get("segments_in_disagreement", [])
rows = "| Segment | R1 | R2 | Agent 1b |\n|---|---|---|---|\n"
for di in dis[:20]:
rows += (
f"| `{di['segment_id']}` "
f"| {di.get('r1_dimension','?')} "
f"| {di.get('r2_dimension','?')} "
f"| {di.get('agent_dimension','?')} |\n"
)
if len(dis) > 20:
rows += f"| *β¦{len(dis)-20} more* | | | |\n"
dis_md = f"### Disagreements ({n_dis})\n\n{rows}"
return (
state,
_kappa_html(report),
dis_md,
gr.update(visible=bool(n_dis)),
_agent_log_html(state["agent_logs"]),
)
def fn_run_sequence_analysis(rater_choice: str, state: dict):
if not state.get("session_id"):
raise gr.Error("No session loaded β complete the Pipeline first.")
d = _session_dir(state)
try:
path = d / "coding_R2.json" if "R2" in rater_choice else d / f"coding_{state['researcher_id']}.json"
if not path.exists():
raise gr.Error(f"Coding file not found: {path.name}.")
analysis = load_and_analyse(path, max_lag=3)
except gr.Error:
raise
except Exception as e:
raise gr.Error(f"Sequence analysis failed: {e}") from e
if "error" in analysis:
raise gr.Error(analysis["error"])
stat = analysis.get("statistics", {})
n_ep = stat.get("n_episodes", 0)
n_tr = stat.get("n_transitions", 0)
cats = stat.get("categories_used", [])
entropy = stat.get("transition_entropy", 0.0)
ent_max = stat.get("entropy_max", 0.0)
sig_pos = stat.get("significant_pos", [])
sig_neg = stat.get("significant_neg", [])
ent_note = (
f"**{entropy:.3f}** bits / max {ent_max:.3f} β "
+ ("high entropy: no strong sequential pattern"
if ent_max > 0 and entropy / ent_max > 0.80
else "moderate entropy: some transitions dominate"
if ent_max > 0 and entropy / ent_max > 0.50
else "low entropy: a few transitions strongly dominate")
)
warnings = analysis.get("sparse_warnings", [])
warn_md = ""
if warnings:
warn_md = (
f"\n\n*β {len(warnings)} sparse cell(s): "
f"{'; '.join(warnings[:3])}{'β¦' if len(warnings) > 3 else ''}*"
)
summary_md = (
f"**{n_ep}** episodes Β· **{n_tr}** transitions Β· "
f"**{len(cats)}** dimensions: `{'`, `'.join(cats)}` \n"
f"Entropy: {ent_note} \n"
f"**{len(sig_pos)}** significantly common Β· **{len(sig_neg)}** significantly rare"
f"{warn_md}"
)
gr.Info(f"Sequence analysis: {n_ep} episodes, {len(sig_pos)} significant transitions.")
return summary_md, render_transition_matrix_html(analysis), render_significant_transitions_html(analysis), gr.update(visible=True)
def fn_download_seq_csv(rater_choice: str, state: dict):
if not state.get("session_id"):
raise gr.Error("No session loaded.")
d = _session_dir(state)
path = d / ("coding_R2.json" if "R2" in rater_choice else f"coding_{state['researcher_id']}.json")
if not path.exists():
raise gr.Error(f"Coding file not found: {path.name}")
analysis = load_and_analyse(path)
if "error" in analysis:
raise gr.Error(analysis["error"])
csv_str = seq_to_csv(analysis)
tmp = Path(tempfile.mktemp(suffix=f"_transitions_{state['session_id']}.csv"))
tmp.write_text(csv_str, encoding="utf-8")
return str(tmp)
def fn_resolve(seg_id: str, dim_choice: str, note: str, state: dict):
if not seg_id.strip():
raise gr.Error("Enter the segment ID.")
if not dim_choice:
raise gr.Error("Select the resolved dimension.")
resolved = DIM_ID_FROM_CHOICE.get(dim_choice, dim_choice)
try:
resolve_disagreement(
report_path=_session_dir(state) / "kappa_report.json",
segment_id=seg_id.strip(), resolved_dimension=resolved,
resolution_note=note.strip(),
)
except Exception as e:
raise gr.Error(f"Could not resolve: {e}") from e
gr.Info(f"Resolved {seg_id.strip()} β {resolved}")
return state, f"β `{seg_id.strip()}` β **{resolved}**"
def fn_discard(seg_id: str, note: str, state: dict):
if not seg_id.strip():
raise gr.Error("Enter the segment ID.")
try:
discard_disagreement(
report_path=_session_dir(state) / "kappa_report.json",
segment_id=seg_id.strip(), discard_note=note.strip(),
)
except Exception as e:
raise gr.Error(f"Could not discard: {e}") from e
gr.Info(f"Discarded {seg_id.strip()}")
return state, f"Discarded `{seg_id.strip()}`"
# ββ Rules βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def fn_load_rules():
pending = list_pending_rules()
choices = [f"{r['rule_id']}: {r['description'][:55]}β¦" for r in pending]
return _rules_html(pending), choices
def fn_approve(choice: str, researcher: str, note: str):
if not choice:
raise gr.Error("Select a rule.")
if not researcher.strip():
raise gr.Error("Enter your Researcher ID.")
rid = choice.split(":")[0].strip()
approve_rule(rid, researcher.strip(), note.strip())
gr.Info(f"Rule {rid} approved.")
return f"β Rule **{rid}** approved β now active for Agent 1b."
def fn_reject(choice: str, researcher: str, note: str):
if not choice:
raise gr.Error("Select a rule.")
if not researcher.strip():
raise gr.Error("Enter your Researcher ID.")
if not note.strip():
raise gr.Error("Provide a rejection reason β Agent 2 learns from it.")
rid = choice.split(":")[0].strip()
reject_rule(rid, researcher.strip(), note.strip())
gr.Info(f"Rule {rid} rejected.")
return f"β Rule **{rid}** rejected."
# ===========================================================================
# CSS
# ===========================================================================
EXTRA_CSS = """
.gradio-container {
max-width: 1200px !important;
margin: 0 auto !important;
background: #ececee !important;
font-family: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Arial, sans-serif !important;
}
footer { display: none !important; }
:root {
--cc-bg: #ececee;
--cc-surface: #f6f6f7;
--cc-paper: #ffffff;
--cc-ink: #111217;
--cc-muted: #6b6f76;
--cc-border: #d8dade;
--cc-accent: #ff5a3d;
--cc-accent-deep: #ea4425;
}
:focus-visible { outline: 2px solid var(--cc-accent) !important; outline-offset: 2px; }
:focus { outline: none; }
/* Primary button */
.gradio-container button.primary {
background: var(--cc-accent) !important;
border-color: var(--cc-accent) !important;
color: #fff !important;
font-weight: 700 !important;
}
.gradio-container button.primary:hover {
background: var(--cc-accent-deep) !important;
border-color: var(--cc-accent-deep) !important;
}
.gradio-container button.secondary,
.gradio-container button:not(.primary) {
border-color: #c9cdd3 !important;
}
/* ββ Welcome ββ */
.cc-hero {
text-align: center;
padding: 56px 24px 40px;
}
.cc-hero-title {
font-size: clamp(3.5rem, 10vw, 7rem);
font-weight: 900;
letter-spacing: -0.06em;
color: var(--cc-ink);
line-height: 0.88;
margin: 0 0 16px;
}
.cc-hero-sub {
font-size: 1rem;
color: var(--cc-muted);
max-width: 44ch;
margin: 0 auto 48px;
line-height: 1.55;
}
.cc-entry-card {
background: var(--cc-paper);
border: 1px solid var(--cc-border);
border-radius: 16px;
padding: 24px;
min-height: 190px;
position: relative;
overflow: hidden;
}
.cc-entry-card::after {
content: "";
position: absolute;
right: -24px; bottom: -24px;
width: 96px; height: 96px;
border-radius: 999px;
background: rgba(255,90,61,0.1);
}
.cc-entry-kicker {
font-size: 0.7rem;
font-weight: 800;
text-transform: uppercase;
letter-spacing: 0.1em;
color: var(--cc-accent-deep);
margin-bottom: 10px;
display: block;
}
.cc-entry-title {
font-size: 1.28rem;
font-weight: 800;
letter-spacing: -0.025em;
color: var(--cc-ink);
margin: 0 0 8px;
line-height: 1.1;
}
.cc-entry-desc {
font-size: 0.87rem;
color: #434852;
line-height: 1.55;
max-width: 32ch;
}
/* ββ Page nav bar ββ */
.cc-page-nav {
display: flex;
align-items: center;
gap: 12px;
padding: 16px 0 14px;
border-bottom: 2px solid var(--cc-border);
margin-bottom: 24px;
}
.cc-page-label {
font-size: 0.68rem;
font-weight: 800;
text-transform: uppercase;
letter-spacing: 0.12em;
color: var(--cc-accent-deep);
}
.cc-page-title {
font-size: 1.5rem;
font-weight: 800;
letter-spacing: -0.03em;
color: var(--cc-ink);
margin: 0;
}
.cc-page-meta {
font-size: 0.78rem;
color: var(--cc-muted);
margin-left: auto;
font-family: monospace;
}
/* ββ Step indicator ββ */
.cc-steps {
display: flex;
gap: 6px;
align-items: center;
flex-wrap: wrap;
margin-bottom: 20px;
}
.cc-step-done { color:#065f46;background:#f0fdf4;border:1px solid #86efac;border-radius:999px;padding:4px 12px;font-size:0.76rem;font-weight:700; }
.cc-step-active { color:#4338ca;background:#eef2ff;border:1px solid #818cf8;border-radius:999px;padding:4px 12px;font-size:0.76rem;font-weight:700; }
.cc-step-next { color:#94a3b8;background:transparent;border:1px solid #e2e8f0;border-radius:999px;padding:4px 12px;font-size:0.76rem;font-weight:500; }
.cc-step-sep { color:#d1d5db;font-size:0.7rem; }
/* ββ Setup page ββ */
.cc-setup-box {
background: var(--cc-paper);
border: 1px solid var(--cc-border);
border-radius: 12px;
padding: 24px;
margin-bottom: 16px;
}
/* ββ Pipeline page ββ */
.cc-section-header {
background: #eff6ff;
border: 1px solid #93c5fd;
border-left: 4px solid #3b82f6;
border-radius: 0 8px 8px 0;
padding: 10px 16px;
margin: 12px 0;
font-size:0.92em;
color: #1e3a8a;
}
/* ββ Coding canvas ββ */
.cc-coding-transcript {
background: var(--cc-paper);
border: 1px solid var(--cc-border);
border-radius: 10px;
padding: 16px;
max-height: 62vh;
overflow-y: auto;
}
.cc-coding-controls {
background: var(--cc-paper);
border: 1px solid var(--cc-border);
border-radius: 10px;
padding: 16px;
}
.cc-coding-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 12px 0 0;
border-top: 1px solid var(--cc-border);
margin-top: 12px;
}
/* ββ Done page ββ */
.cc-done-card {
background: #f0fdf4;
border: 2px solid #86efac;
border-radius: 16px;
padding: 32px;
text-align: center;
margin: 24px 0;
}
.cc-done-title {
font-size: 2rem;
font-weight: 800;
color: #065f46;
margin: 0 0 8px;
}
.cc-done-sub {
color: #14532d;
font-size: 0.95rem;
max-width: 50ch;
margin: 0 auto;
line-height: 1.6;
}
/* ββ Info callout ββ */
.cc-callout {
background: #eff6ff;
border: 1px solid #93c5fd;
border-radius: 10px;
padding: 16px 20px;
margin-bottom: 16px;
font-size: 0.88em;
color: #1e3a8a;
line-height: 1.7;
}
/* ββ Pipeline progress header (always visible) ββ */
.cc-pipeline-bar {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 20px;
background: var(--cc-paper);
border-bottom: 1.5px solid var(--cc-border);
flex-wrap: wrap;
position: sticky;
top: 0;
z-index: 50;
box-shadow: 0 1px 6px rgba(0,0,0,0.05);
}
.cc-pipeline-step {
display: flex;
flex-direction: column;
align-items: center;
gap: 2px;
padding: 5px 12px;
border-radius: 7px;
min-width: 64px;
border: 1.5px solid var(--cc-border);
background: var(--cc-surface);
}
.cc-pipeline-step.done { background: #f0fdf4; border-color: #86efac; }
.cc-pipeline-step.active { background: #fff5f2; border-color: var(--cc-accent); }
.cc-pipeline-step .dot { font-size: 0.82em; color: var(--cc-muted); }
.cc-pipeline-step.done .dot { color: #15803d; }
.cc-pipeline-step.active .dot { color: var(--cc-accent); }
.cc-pipeline-step .lbl {
font-size: 0.66em; font-weight: 800; text-transform: uppercase;
letter-spacing: 0.06em; color: var(--cc-muted);
}
.cc-pipeline-step.done .lbl { color: #15803d; }
.cc-pipeline-step.active .lbl { color: var(--cc-accent-deep); }
/* ββ Screener view ββ */
.cc-screener-row {
display: grid;
grid-template-columns: 36px 80px 64px 1fr 160px;
gap: 8px;
padding: 7px 12px;
border-bottom: 1px solid var(--cc-border);
align-items: start;
font-size: 0.85em;
}
.cc-screener-header {
background: var(--cc-surface);
border-radius: 8px 8px 0 0;
font-size: 0.7em;
font-weight: 800;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--cc-muted);
}
/* ββ Lexicon tier cards ββ */
.cc-tier-card {
border: 1.5px solid var(--cc-border);
border-radius: 10px;
padding: 12px 16px;
margin-bottom: 10px;
background: var(--cc-paper);
}
.cc-tier-kicker {
font-size: 0.68em;
font-weight: 800;
text-transform: uppercase;
letter-spacing: 0.08em;
color: var(--cc-accent-deep);
margin-bottom: 4px;
}
"""
CSS = _load_css() + EXTRA_CSS
# ===========================================================================
# Pipeline header + Screener + Lexicon helpers
# ===========================================================================
_PIPE_STAGES = [
("upload", "Upload"),
("screened", "Screen"),
("sectioned", "Section"),
("coded", "Code"),
("done", "Done"),
("agreed", "Agreement"),
]
_PIPE_ORDER = [s for s, _ in _PIPE_STAGES]
def _pipeline_bar_html(state: dict) -> str:
current = state.get("stage", "upload")
session = html_lib.escape(state.get("session_id", "β") or "β")
turns = len(state.get("turns", []))
sc = state.get("screener_result")
savings = f"{sc['estimated_llm_savings']:.0%}" if sc else "β"
n_wins = len(sc["candidate_windows"]) if sc else "β"
try:
cur_i = _PIPE_ORDER.index(current)
except ValueError:
cur_i = 0
steps = []
for i, (stage, label) in enumerate(_PIPE_STAGES):
cls = "done" if i < cur_i else ("active" if i == cur_i else "")
dot = "β" if i < cur_i else ("βΆ" if i == cur_i else "β")
steps.append(
f'<div class="cc-pipeline-step {cls}">'
f'<span class="dot">{dot}</span>'
f'<span class="lbl">{label}</span>'
f'</div>'
)
return (
f'<div class="cc-pipeline-bar">'
f'<div style="line-height:1.25;margin-right:6px">'
f'<div style="font-weight:800;font-size:0.85em;color:var(--cc-ink)">{session}</div>'
f'<div style="font-size:0.68em;color:var(--cc-muted)">'
f'{turns} turns Β· {n_wins} windows Β· ~{savings} LLM saved</div>'
f'</div>'
+ "".join(steps)
+ f'</div>'
)
def _screener_summary_html(rd: dict) -> str:
total = rd.get("total_turns", 0)
flagged = rd.get("flagged_turns", 0)
windows = len(rd.get("candidate_windows", []))
savings = rd.get("estimated_llm_savings", 0)
def chip(v, lbl, tc, bg):
return (
f'<div style="background:{bg};border-radius:9px;padding:10px 16px;'
f'text-align:center;min-width:80px">'
f'<div style="font-size:1.45em;font-weight:800;color:{tc}">{html_lib.escape(str(v))}</div>'
f'<div style="font-size:0.68em;color:{tc};opacity:.8;font-weight:700;'
f'text-transform:uppercase;letter-spacing:.05em">{lbl}</div></div>'
)
return (
f'<div style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:16px">'
+ chip(total, "Total turns", "#111217", "#f6f6f7")
+ chip(flagged, "Flagged", "#15803d", "#f0fdf4")
+ chip(windows, "LLM windows", "#b45309", "#fffbeb")
+ chip(f"{savings:.0%}", "LLM saved", "#ff5a3d", "#fff5f2")
+ f'</div>'
)
def _screener_turns_html(rd: dict, speaker_map: dict) -> str:
scores = rd.get("turn_scores", [])
if not scores:
return '<p style="color:var(--cc-muted)">No turns scored.</p>'
rows = [
'<div style="border:1px solid var(--cc-border);border-radius:10px;overflow:hidden">'
'<div class="cc-screener-row cc-screener-header" '
'style="padding:6px 12px;background:var(--cc-surface)">'
'<div>#</div><div>Speaker</div><div>Score</div><div>Text</div><div>Triggers</div>'
'</div>'
]
for ts in scores[:250]:
excl = bool(ts.get("excluded_reason"))
flagged = ts.get("flagged", False)
score = ts.get("composite", 0)
sp = ts.get("speaker", "?")
text = html_lib.escape(ts.get("text", "")[:130])
tid = ts.get("turn_id", "")
hits = ts.get("hits", [])
sigs = ts.get("signals", [])
if excl:
sbg, stc = "#f6f6f7", "#a8a29e"
elif score >= 0.8:
sbg, stc = "#f0fdf4", "#15803d"
elif score >= 0.4:
sbg, stc = "#fffbeb", "#b45309"
elif score >= 0.2:
sbg, stc = "#fff5f2", "#ff5a3d"
else:
sbg, stc = "#f6f6f7", "#6b6f76"
chips = ""
for h in hits[:3]:
lbl = html_lib.escape(h.get("category_label", "")[:22])
t = h.get("tier", 1)
mark = "Β²" if t == 2 else "Β³?" if t == 3 else ""
chips += (
f'<span style="background:#fff5f2;color:#ff5a3d;font-size:0.72em;'
f'padding:1px 5px;border-radius:3px;white-space:nowrap">{lbl}{mark}</span> '
)
for sig in sigs[:2]:
chips += (
f'<span style="background:#faf5ff;color:#7c3aed;font-size:0.72em;'
f'padding:1px 5px;border-radius:3px;white-space:nowrap">{html_lib.escape(sig)}</span> '
)
if excl:
chips = '<span style="font-size:0.72em;color:#a8a29e">small talk</span>'
flag = "βΆ" if flagged else ("β" if excl else "Β·")
row_bg = "#fffbeb" if flagged else ("#f6f6f7" if excl else "white")
rows.append(
f'<div class="cc-screener-row" style="background:{row_bg}">'
f'<div style="font-family:monospace;font-size:0.72em;color:var(--cc-muted)">'
f'{flag}{html_lib.escape(str(tid))}</div>'
f'<div style="font-size:0.78em;font-weight:600;color:#111217;'
f'overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{html_lib.escape(sp[:12])}</div>'
f'<div><span style="background:{sbg};color:{stc};font-family:monospace;'
f'font-size:0.8em;font-weight:700;padding:2px 5px;border-radius:4px">'
f'{score:.2f}</span></div>'
f'<div style="font-size:0.85em;color:#111217;line-height:1.45">{text}</div>'
f'<div style="display:flex;flex-direction:column;gap:2px">{chips}</div>'
f'</div>'
)
if len(scores) > 250:
rows.append(
f'<div style="text-align:center;padding:8px;font-size:0.8em;color:var(--cc-muted)">'
f'{len(scores)-250} more turns not shown</div>'
)
rows.append('</div>')
return "".join(rows)
def _lexicon_tier1_html(data: dict) -> str:
cats = data.get("categories", [])
phase_colors = {
"planning": ("#1d4ed8","#eff6ff"),
"monitoring": ("#15803d","#f0fdf4"),
"evaluating": ("#b45309","#fffbeb"),
"ssrl": ("#7c3aed","#faf5ff"),
}
parts = ['<div style="font-size:0.8em;color:var(--cc-muted);margin-bottom:12px;'
'padding:8px 12px;background:var(--cc-surface);border-radius:6px">'
'Tier 1 is research-locked. Add custom terms in Tier 2.</div>']
for cat in cats:
tc, bg = phase_colors.get(cat.get("phase",""), ("#6b6f76","#f6f6f7"))
terms = " ".join(
f'<span style="background:{bg};color:{tc};font-size:0.78em;'
f'padding:2px 7px;border-radius:4px;display:inline-block;margin:2px">'
f'{html_lib.escape(t)}</span>'
for t in cat.get("terms", [])
)
parts.append(
f'<div class="cc-tier-card">'
f'<div class="cc-tier-kicker">{html_lib.escape(cat.get("phase",""))}</div>'
f'<div style="font-weight:800;color:var(--cc-ink);margin-bottom:4px">'
f'{html_lib.escape(cat.get("label",""))}</div>'
f'<div style="font-size:0.72em;color:var(--cc-muted);margin-bottom:8px">'
f'w={cat.get("weight",0)} Β· {html_lib.escape(cat.get("source",""))}</div>'
f'<div style="line-height:2">{terms}</div></div>'
)
return "".join(parts)
def _lexicon_tier2_html(data: dict) -> str:
entries = data.get("entries", [])
if not entries:
return ('<div style="text-align:center;padding:36px;color:var(--cc-muted)">'
'No validated terms yet. Use the form below to add them.</div>')
parts = []
for e in entries:
terms = " ".join(
f'<span style="background:#f0fdf4;color:#15803d;font-size:0.8em;'
f'padding:2px 7px;border-radius:4px">{html_lib.escape(t)}</span>'
for t in e.get("terms", [])
)
note = html_lib.escape(e.get("note",""))
parts.append(
f'<div class="cc-tier-card">'
f'<div style="font-weight:700;color:var(--cc-ink)">{html_lib.escape(e.get("label",""))}</div>'
f'<div style="font-size:0.72em;color:var(--cc-muted);margin-bottom:6px">'
f'by {html_lib.escape(e.get("added_by",""))} Β· {html_lib.escape(e.get("category_id",""))}</div>'
f'<div style="margin-bottom:6px">{terms}</div>'
+ (f'<div style="font-size:0.8em;color:var(--cc-muted)">{note}</div>' if note else "")
+ f'</div>'
)
return "".join(parts)
def _lexicon_tier3_html(data: dict) -> str:
cands = [c for c in data.get("candidates", [])
if not c.get("approved") and not c.get("rejected")]
if not cands:
return ('<div style="text-align:center;padding:36px;color:var(--cc-muted)">'
'No pending candidates.</div>')
parts = []
for c in cands:
terms = " ".join(
f'<span style="background:#fffbeb;color:#b45309;font-size:0.8em;'
f'padding:2px 8px;border-radius:4px;font-weight:600">{html_lib.escape(t)}</span>'
for t in c.get("terms", [])
)
ctx = html_lib.escape(c.get("context","")[:180])
parts.append(
f'<div class="cc-tier-card" style="border-color:#fde68a;background:#fffbeb">'
f'<div class="cc-tier-kicker" style="color:#b45309">Pending review</div>'
f'<div style="font-weight:700;color:var(--cc-ink);margin-bottom:6px">'
f'{html_lib.escape(c.get("label",""))}</div>'
f'<div style="margin-bottom:6px">{terms}</div>'
+ (f'<div style="font-size:0.8em;color:#78350f;font-style:italic">“{ctx}”</div>' if ctx else "")
+ f'</div>'
)
return "".join(parts)
# Screener handler β returns (state, bar, summary_html, turns_html, rerun_btn_update)
def fn_run_screener(state: dict):
turns = state.get("turns", [])
if not turns:
err = ('<div style="background:#fffbeb;border:1px solid #fde68a;border-radius:8px;'
'padding:14px;color:#92400e">No transcript loaded β go back to Upload.</div>')
return state, _pipeline_bar_html(state), err, "", gr.update(visible=True)
try:
result = screen_transcript(turns)
rd = result_to_dict(result)
new_state = dict(state)
new_state["screener_result"] = rd
new_state["stage"] = "screened"
speaker_map = new_state.get("speakers", {})
return (
new_state,
_pipeline_bar_html(new_state),
_screener_summary_html(rd),
_screener_turns_html(rd, speaker_map),
gr.update(visible=False), # hide re-run btn β success
)
except Exception as e:
err = (
f'<div style="background:#fffbeb;border:1px solid #fde68a;border-radius:8px;'
f'padding:14px;color:#92400e"><strong>Screener error:</strong> '
f'{html_lib.escape(str(e))}</div>'
)
return state, _pipeline_bar_html(state), err, "", gr.update(visible=True)
# Lexicon handlers
def fn_load_lexicon():
try:
d = load_full_lexicon()
return _lexicon_tier1_html(d["tier1"]), _lexicon_tier2_html(d["tier2"]), _lexicon_tier3_html(d["tier3"]), ""
except Exception as e:
return "", "", "", f"Error loading lexicon: {e}"
def fn_add_tier2_term(cat_id, label, phase, terms_text, weight, researcher_id, note):
terms = [t.strip() for t in terms_text.replace(",","\n").splitlines() if t.strip()]
if not terms:
return "Enter at least one term.", "", ""
try:
add_tier2_term(terms=terms, category_id=cat_id or "TIER2_custom",
label=label or "Custom", phase=phase or "monitoring",
weight=float(weight), added_by=researcher_id or "researcher", note=note)
d = load_full_lexicon()
return f"Added {len(terms)} term(s) to Tier 2.", _lexicon_tier2_html(d["tier2"]), ""
except Exception as e:
return f"Failed: {e}", "", ""
def fn_approve_t3(term, researcher_id):
if not term.strip():
return "Enter a term.", ""
try:
approve_tier3_candidate(term.strip(), approved_by=researcher_id or "researcher")
d = load_full_lexicon()
return f"'{term}' approved.", _lexicon_tier3_html(d["tier3"])
except Exception as e:
return f"Failed: {e}", ""
def fn_reject_t3(term, researcher_id, note):
if not term.strip():
return "Enter a term.", ""
try:
reject_tier3_candidate(term.strip(), rejected_by=researcher_id or "researcher", note=note)
d = load_full_lexicon()
return f"'{term}' rejected.", _lexicon_tier3_html(d["tier3"])
except Exception as e:
return f"Failed: {e}", ""
# ===========================================================================
# UI β page-based (no tabs)
# ===========================================================================
with gr.Blocks(title="CollabCode") as demo:
state = gr.State(_empty_state())
# Persistent pipeline status bar (hidden on welcome)
pipeline_bar_html = gr.HTML(
value=_pipeline_bar_html(_empty_state()),
visible=False,
elem_id="cc-pipeline-bar-root",
)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PAGE 0: Welcome
# Hidden buttons kept so wiring stays intact
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
with gr.Column(visible=True) as pg_welcome:
# Hidden nav buttons (agreement / library) β wiring requires them to exist
agreement_nav_btn = gr.Button(visible=False)
library_nav_btn = gr.Button(visible=False)
gr.HTML(
'<div class="cc-hero">'
'<h1 class="cc-hero-title">CollabCode</h1>'
'<p class="cc-hero-sub">Human-in-the-loop qualitative coding '
'for collaborative learning research</p>'
'</div>'
)
# ββ Primary entry card ββββββββββββββββββββββββββββββββββββββββββββ
with gr.Row(equal_height=True):
with gr.Column(scale=2):
gr.HTML(
'<div class="cc-entry-card">'
'<span class="cc-entry-kicker">Primary workflow</span>'
'<h3 class="cc-entry-title">Code a Transcript</h3>'
'<p class="cc-entry-desc">Upload a Zoom transcript or load from Drive. '
'AI pre-screens turns for metacognitive signals, detects discussion sections, '
'finds episode boundaries, and proposes D1βD9 codes β '
'you review and confirm every decision.</p>'
'</div>'
)
start_btn = gr.Button("Start Coding β", variant="primary", size="lg")
# ββ About / system logic ββββββββββββββββββββββββββββββββββββββββββ
gr.HTML(
'<div style="margin:36px 0 8px;border-top:1px solid var(--cc-border);'
'padding-top:32px">'
'<div style="font-weight:800;font-size:1.05em;color:var(--cc-ink);'
'margin-bottom:20px;letter-spacing:-0.01em">How CollabCode works</div>'
'</div>'
)
with gr.Row(equal_height=True):
gr.HTML(
'<div class="cc-entry-card" style="border-top:3px solid #ff5a3d">'
'<span class="cc-entry-kicker">Step 1 β Pre-screen</span>'
'<h3 class="cc-entry-title" style="font-size:1em">Metacognitive Screener</h3>'
'<p class="cc-entry-desc">Before any LLM call, every turn is scored against '
'a three-tier lexicon (Iiskala 2011; Schoor & Bannert 2012). '
'Turns with no metacognitive signal are filtered out β typically cutting '
'LLM cost by 40β70 %. Only candidate windows reach Agent 0.</p>'
'</div>'
)
gr.HTML(
'<div class="cc-entry-card" style="border-top:3px solid #f59e0b">'
'<span class="cc-entry-kicker">Step 2 β Structure</span>'
'<h3 class="cc-entry-title" style="font-size:1em">Agent 0 β Sectioner</h3>'
'<p class="cc-entry-desc">Agent 0 reads the full transcript and proposes '
'thematic sections (e.g. "Problem framing", "Solution negotiation"). '
'You rename or merge them before the next stage. '
'Sections give Agent 1a its scope and anchor all downstream analysis.</p>'
'</div>'
)
gr.HTML(
'<div class="cc-entry-card" style="border-top:3px solid #10b981">'
'<span class="cc-entry-kicker">Step 3 β Episodes</span>'
'<h3 class="cc-entry-title" style="font-size:1em">Agent 1a β Boundary Detector</h3>'
'<p class="cc-entry-desc">Within each section, Agent 1a runs in parallel '
'to find episode boundaries β moments where the collaborative activity '
'shifts. Boundary proposals are shown to you for review and adjustment '
'before coding begins.</p>'
'</div>'
)
gr.HTML(
'<div class="cc-entry-card" style="border-top:3px solid #6366f1">'
'<span class="cc-entry-kicker">Step 4 β Code</span>'
'<h3 class="cc-entry-title" style="font-size:1em">Agent 1b + Human</h3>'
'<p class="cc-entry-desc">Agent 1b proposes D1βD9 codes '
'(Meier, Spada & Rummel 2007) and SSRL phases (M-MON, M-REG, CO-REG, SSRL) '
'for each episode. You code independently first, then reveal the AI proposal '
'to resolve ambiguity. All decisions are yours.</p>'
'</div>'
)
with gr.Row(equal_height=True):
gr.HTML(
'<div class="cc-entry-card" style="border-top:3px solid #0ea5e9">'
'<span class="cc-entry-kicker">Step 5 β Agreement</span>'
'<h3 class="cc-entry-title" style="font-size:1em">Inter-rater Reliability</h3>'
'<p class="cc-entry-desc">Upload a second coder\'s file to compute '
'Gwet\'s AC1 (primary) and Cohen\'s ΞΊ (reference) per dimension. '
'Disagreements are listed segment by segment so you can resolve '
'or flag them for discussion.</p>'
'</div>'
)
gr.HTML(
'<div class="cc-entry-card" style="border-top:3px solid #8b5cf6">'
'<span class="cc-entry-kicker">Step 6 β Learn</span>'
'<h3 class="cc-entry-title" style="font-size:1em">Agent 2 β Rule Learner</h3>'
'<p class="cc-entry-desc">After each validated session, Agent 2 induces '
'tentative coding rules from agreed codings. Rules are held in Tier 3 '
'until a researcher promotes them to the validated lexicon β '
'keeping the human firmly in the loop.</p>'
'</div>'
)
gr.HTML(
'<div class="cc-entry-card" style="border-top:3px solid #f43f5e">'
'<span class="cc-entry-kicker">Design principle</span>'
'<h3 class="cc-entry-title" style="font-size:1em">Human-in-the-loop</h3>'
'<p class="cc-entry-desc">Every AI action is a proposal, not a decision. '
'The researcher confirms sections, adjusts boundaries, codes independently, '
'and approves lexicon updates. AI reduces mechanical effort; '
'expert judgment drives all coding outcomes.</p>'
'</div>'
)
gr.HTML(
'<div style="text-align:center;padding:32px 0 16px;font-size:0.75rem;color:#94a3b8">'
f'Model: <strong>{MODEL_ID.split("/")[-1]}</strong> Β· '
f'Temperature: {TEMPERATURE} Β· '
'Framework: Meier, Spada & Rummel (2007) Β· Iiskala (2011)'
'</div>'
)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PAGE 1: Setup
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
with gr.Column(visible=False) as pg_setup:
gr.HTML(
'<div class="cc-page-nav">'
'<span class="cc-page-label">Step 1 of 5 β Upload</span>'
'<h2 class="cc-page-title">Load a Transcript</h2>'
'</div>'
'<div class="cc-steps">'
'<span class="cc-step-active">1 Upload</span>'
'<span class="cc-step-sep">βΊ</span>'
'<span class="cc-step-next">2 Screen</span>'
'<span class="cc-step-sep">βΊ</span>'
'<span class="cc-step-next">3 Sections</span>'
'<span class="cc-step-sep">βΊ</span>'
'<span class="cc-step-next">4 Code</span>'
'<span class="cc-step-sep">βΊ</span>'
'<span class="cc-step-next">5 Done</span>'
'</div>'
)
# ββ Researcher ID βββββββββββββββββββββββββββββββββββββββββββββββββ
gr.HTML(
'<div style="font-weight:700;color:var(--cc-ink);margin:16px 0 4px">Your Researcher ID</div>'
'<div style="font-size:0.82em;color:var(--cc-muted);margin-bottom:8px">'
'A short label used to identify your coding file (e.g. R1, lara, jsmith).</div>'
)
researcher_id_box = gr.Textbox(
label="",
placeholder="e.g. R1",
max_lines=1,
)
# ββ Option A: Google Drive ββββββββββββββββββββββββββββββββββββββββ
gr.HTML(
'<div style="border-top:1px solid var(--cc-border);margin:20px 0 12px"></div>'
'<div style="font-weight:700;color:var(--cc-ink);margin-bottom:4px">Option A β Google Drive</div>'
'<div style="font-size:0.82em;color:var(--cc-muted);margin-bottom:10px">'
'Refresh the list, pick a transcript, then click Load.</div>'
)
with gr.Row():
drive_refresh_btn = gr.Button("Refresh Drive list", variant="secondary", scale=2)
load_prev_btn = gr.Button("Resume session", variant="secondary", scale=1)
drive_file_dropdown = gr.Dropdown(
label="Select transcript",
choices=[],
interactive=False,
)
drive_status_html = gr.HTML()
process_btn = gr.Button("Load from Drive β", variant="primary")
process_status = gr.HTML()
process_log = gr.HTML()
back_setup_btn = gr.Button("β Back to Home", size="sm")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PAGE 2: Screener
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
with gr.Column(visible=False) as pg_screener:
gr.HTML(
'<div class="cc-page-nav">'
'<span class="cc-page-label">Step 2 of 5 β Pre-screen</span>'
'<h2 class="cc-page-title">Metacognitive Screener</h2>'
'</div>'
'<div class="cc-steps">'
'<span class="cc-step-done">β Upload</span>'
'<span class="cc-step-sep">βΊ</span>'
'<span class="cc-step-active">2 Screen</span>'
'<span class="cc-step-sep">βΊ</span>'
'<span class="cc-step-next">3 Sections</span>'
'<span class="cc-step-sep">βΊ</span>'
'<span class="cc-step-next">4 Code</span>'
'<span class="cc-step-sep">βΊ</span>'
'<span class="cc-step-next">5 Done</span>'
'</div>'
)
# Summary chips β auto-populated when the page loads
screener_summary_html = gr.HTML(
value='<div style="padding:20px;text-align:center;color:var(--cc-muted)">'
'Running screenerβ¦</div>'
)
# Primary CTA β shown once screener finishes
screener_to_sections_btn = gr.Button(
"Detect Sections β", variant="primary", size="lg", visible=False
)
# Collapsible turn detail
with gr.Accordion("Turn-by-turn detail", open=False):
gr.HTML(
'<div style="font-size:0.8em;color:var(--cc-muted);padding:6px 0 10px">'
'Turns are colour-coded by composite score. '
'Orange rows are candidate windows passed to Agent 0; '
'grey rows are filtered out.</div>'
)
screener_turns_html_c = gr.HTML()
# Re-run (only needed if auto-run failed)
run_screener_btn = gr.Button(
"Re-run Screener", variant="secondary", size="sm", visible=False
)
back_screener_btn = gr.Button("β Back to Upload", size="sm")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PAGE 3: Sections review
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
with gr.Column(visible=False) as pg_sections:
gr.HTML(
'<div class="cc-page-nav">'
'<span class="cc-page-label">Step 2 of 4</span>'
'<h2 class="cc-page-title">Review Sections</h2>'
'</div>'
'<div class="cc-steps">'
'<span class="cc-step-done">β Setup</span>'
'<span class="cc-step-sep">βΊ</span>'
'<span class="cc-step-active">2 Sections</span>'
'<span class="cc-step-sep">βΊ</span>'
'<span class="cc-step-next">3 Code</span>'
'<span class="cc-step-sep">βΊ</span>'
'<span class="cc-step-next">4 Done</span>'
'</div>'
)
sections_display_html = gr.HTML()
gr.Markdown("**Rename sections** β edit the text after the colon, keep the `s01:` prefix:")
sections_labels_box = gr.Textbox(
lines=10, show_label=False,
placeholder="s01: Introduction\ns02: Main Discussion\nβ¦",
)
confirm_sections_btn = gr.Button("Confirm Sections β", variant="primary")
back_sections_btn = gr.Button("β Back to Setup", size="sm")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PAGE 3: Pipeline β boundaries + coding (per section)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
with gr.Column(visible=False) as pg_pipeline:
gr.HTML(
'<div class="cc-page-nav">'
'<span class="cc-page-label">Step 3 of 4</span>'
'<h2 class="cc-page-title">Detect Episodes & Code</h2>'
'</div>'
'<div class="cc-steps">'
'<span class="cc-step-done">β Setup</span>'
'<span class="cc-step-sep">βΊ</span>'
'<span class="cc-step-done">β Sections</span>'
'<span class="cc-step-sep">βΊ</span>'
'<span class="cc-step-active">3 Code</span>'
'<span class="cc-step-sep">βΊ</span>'
'<span class="cc-step-next">4 Done</span>'
'</div>'
)
sections_overview_html = gr.HTML()
# Live agent-activity banner β updated by callbacks to show what is running
agent_activity_html = gr.HTML(
'<div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:10px;'
'padding:12px 16px;font-size:0.84em;color:#64748b;font-family:system-ui,sans-serif">'
'No agent running. Click <strong>Detect Episode Boundaries</strong> to start.</div>'
)
# Sub-step A: Parallel boundary detection
with gr.Column(visible=True) as col_run_all_boundaries:
gr.HTML(
'<div style="background:#eff6ff;border:1px solid #93c5fd;border-radius:10px;'
'padding:14px 18px;margin-bottom:10px;font-size:0.87em;color:#1e3a8a;line-height:1.6">'
'<strong>Agent 1a β Boundary Detector</strong> runs in parallel on all sections '
'simultaneously. Processing time scales with the <em>longest</em> section, not '
'total transcript length. '
'<em>(Dean & Ghemawat 2004 β parallel map; Schegloff 2007 β episode boundaries; '
'Krippendorff 2004 β unitising precedes categorising)</em>'
'</div>'
)
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(
'<div style="background:#f0fdf4;border:1px solid #86efac;border-radius:10px;'
'padding:10px 16px;margin-bottom:8px;font-size:0.83em;color:#166534">'
'<strong>Agent 1b β Dimension Coder</strong> 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.'
'</div>'
)
# Episode count summary (compact table)
boundary_display_html = gr.HTML()
# Full dialogue view β the key UX improvement
gr.HTML(
'<div style="font-size:0.8em;font-weight:700;color:#475569;'
'text-transform:uppercase;letter-spacing:0.06em;margin:10px 0 6px">'
'Read the dialogue β verify each episode boundary</div>'
)
episode_dialogue_html = gr.HTML()
# Edit controls
gr.HTML(
'<div style="font-size:0.82em;color:#334155;margin:10px 0 4px;'
'padding:8px 12px;background:#f8fafc;border:1px solid #e2e8f0;'
'border-radius:8px">'
'<strong>Adjust if needed:</strong> enter the turn ID <em>after which</em> '
'each new episode begins. Leave empty for a single undivided episode. '
'The AI proposal is pre-filled β edit only where you disagree.'
'</div>'
)
with gr.Row():
boundary_ids_box = gr.Textbox(
label="Boundary turn IDs (comma-separated)",
placeholder="e.g. 12, 28, 35",
lines=1, scale=3,
)
confirm_boundaries_btn = gr.Button("Confirm & Run Agent 1b β",
variant="primary", scale=1)
code_status = gr.Markdown()
# Sub-step C: Coding canvas
with gr.Column(visible=False) as col_coding:
coding_progress_comp = gr.HTML()
# ββ Jump to segment β at the TOP before the transcript ββββββββββ
segment_jump = gr.Dropdown(
label="Jump to segment", choices=[], value=None, interactive=True,
info="Quickly navigate to any episode by ID."
)
with gr.Row(equal_height=False):
# Left: transcript
with gr.Column(scale=3, elem_classes=["cc-coding-transcript"]):
uncertainty_comp = gr.HTML()
turns_html_comp = gr.HTML()
with gr.Row():
reveal_btn = gr.Button("βΆ Reveal AI proposal", variant="secondary", size="sm")
gr.HTML(
'<p style="font-size:0.75em;color:#94a3b8;margin:auto 0;line-height:1.4">'
'Code independently first β reveal only if unsure '
'<em>(Settles 2012)</em></p>'
)
proposal_comp = gr.Markdown(visible=False)
# Right: coding controls
with gr.Column(scale=2, elem_classes=["cc-coding-controls"]):
gr.Markdown("#### D1βD9 Dimension")
dim_radio = gr.Radio(choices=DIM_CHOICES, label="Primary", value=None)
dim_desc_comp = gr.HTML()
secondary_dim_drop = gr.Dropdown(
choices=SEC_DIM_CHOICES,
value=SEC_NONE,
label="Secondary dimension (optional)",
info="Only when a second dimension is clearly sustained throughout. Strijbos et al. (2006).",
interactive=True,
)
# ββ SSRL section β hidden until a D1-D9 code is chosen ββ
with gr.Column(visible=False) as ssrl_col:
gr.HTML(
'<div style="border-top:1px solid var(--cc-border);'
'margin:12px 0 8px;padding-top:10px">'
'<div style="font-weight:700;font-size:0.85em;color:var(--cc-ink);'
'text-transform:uppercase;letter-spacing:.05em;margin-bottom:4px">SSRL Phase</div>'
'<div style="font-size:0.72em;color:var(--cc-muted)">Iiskala (2011) Β· '
'JΓ€rvelΓ€ & Hadwin (2013) β only shown when a D1-D9 code is selected</div></div>'
)
ssrl_radio = gr.Radio(
choices=SSRL_CHOICES,
label="Metacognitive phase",
value=SSRL_NONE,
info="Tag the dominant SSRL phase if metacognition is present.",
)
comment_box = gr.Textbox(
label="Note (optional)", lines=2,
placeholder="Ambiguity, competing codesβ¦"
)
with gr.Row():
prev_btn = gr.Button("β Prev", size="sm")
next_btn = gr.Button("Next β", variant="primary", size="sm")
skip_btn = gr.Button("β Skip", size="sm", variant="secondary")
gr.HTML(
'<p style="font-size:0.72em;color:#94a3b8;margin-top:4px;line-height:1.4">'
'Skip marks the episode as <em>not codeable</em> (small talk, off-topic) and moves on.</p>'
)
next_section_btn = gr.Button(
"β Finish Section & Continue", variant="secondary", visible=False
)
with gr.Accordion("Agent Activity Log", open=False):
pipeline_log = gr.HTML(_agent_log_html([]))
back_pipeline_btn = gr.Button("β Back to Sections", size="sm")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PAGE 4: Done
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
with gr.Column(visible=False) as pg_done:
gr.HTML(
'<div class="cc-page-nav">'
'<span class="cc-page-label">Step 4 of 4</span>'
'<h2 class="cc-page-title">All Sections Coded</h2>'
'</div>'
'<div class="cc-steps">'
'<span class="cc-step-done">β Setup</span>'
'<span class="cc-step-sep">βΊ</span>'
'<span class="cc-step-done">β Sections</span>'
'<span class="cc-step-sep">βΊ</span>'
'<span class="cc-step-done">β Coded</span>'
'<span class="cc-step-sep">βΊ</span>'
'<span class="cc-step-active">4 Done</span>'
'</div>'
)
gr.HTML(
'<div class="cc-done-card">'
'<div class="cc-done-title">Coding complete β</div>'
'<p class="cc-done-sub">'
'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 <strong>Agreement Check</strong>.'
'</p>'
'</div>'
)
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(
'<div class="cc-page-nav">'
'<span class="cc-page-label">Inter-Rater Reliability</span>'
'<h2 class="cc-page-title">Agreement Check</h2>'
'</div>'
)
gr.HTML(
'<div class="cc-callout">'
'<strong>How it works:</strong>'
'<ol style="margin:8px 0 0;padding-left:20px;line-height:1.9">'
'<li>You complete the pipeline β download <code>coding_R1.json</code></li>'
'<li>Your co-researcher runs the same pipeline independently β downloads their file</li>'
'<li>Upload their file here to compute <strong>Gwet\'s AC1</strong> and Cohen\'s ΞΊ</li>'
'<li>Gate: <strong>AC1 β₯ 0.70</strong> <em>(Landis & Koch 1977)</em></li>'
'<li>Resolve remaining disagreements β they feed Agent 2\'s learning cycle</li>'
'</ol>'
'</div>'
)
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(
'<div style="background:#fffbeb;border:1px solid #fbbf24;'
'border-radius:8px;padding:12px 16px;margin:12px 0;font-size:0.88em">'
'<strong style="color:#78350f">Disagreement Resolution</strong>'
'<p style="color:#92400e;margin:4px 0 0">For each disagreement: enter the '
'segment ID, select the consensus dimension, add a rationale. '
'Resolved segments become training data for Agent 2.</p>'
'</div>'
)
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(
'<div style="background:#f0fdf4;border:1px solid #86efac;'
'border-radius:8px;padding:10px 14px;margin-bottom:10px;'
'font-size:0.83em;color:#065f46">'
'<strong>Temporal structure of the coded sequence.</strong> '
'Frequency counts show <em>how much</em>; sequential analysis shows '
'<em>what follows what</em>. '
'<em>Bakeman & Gottman (1986)</em>'
'</div>'
)
with gr.Row():
seq_rater_choice = gr.Dropdown(
label="Analyse coding from",
choices=["R1 (you)", "R2 (co-researcher)"],
value="R1 (you)", scale=2,
)
seq_run_btn = gr.Button("Run β", variant="primary", scale=1)
seq_summary_md = gr.Markdown()
seq_matrix_html = gr.HTML()
seq_sig_html = gr.HTML()
with gr.Column(visible=False) as col_seq_download:
seq_dl_btn = gr.Button("Download transition matrix (CSV)", variant="secondary", size="sm")
seq_dl_file = gr.File(visible=False)
with gr.Accordion("Agent Activity Log", open=False):
agreement_log = gr.HTML(_agent_log_html([]))
with gr.Row():
back_agreement_btn = gr.Button("β Back to Done")
go_library_btn = gr.Button("β Review AI Rules")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PAGE 6: Library
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
with gr.Column(visible=False) as pg_library:
gr.HTML(
'<div class="cc-page-nav">'
'<span class="cc-page-label">Advanced</span>'
'<h2 class="cc-page-title">AI Rule Library</h2>'
'</div>'
)
gr.HTML(
'<div class="cc-callout">'
'<strong>How the learning loop works:</strong> Agent 2 analyses patterns '
'across resolved disagreements and proposes rules to improve Agent 1b\'s '
'future coding. Rules are <em>inactive</em> until approved here. '
'Approved rules enter Tier 2 immediately. '
'<em>(Amershi et al. 2014; Monarch 2021)</em>'
'<br><br>'
'β Agent 2 requires β₯ 3 validated sessions and β₯ 90 coded segments '
'before proposing rules <em>(Bujang & Baharum 2017)</em>.'
'</div>'
)
load_rules_btn = gr.Button("Load Pending Rules", variant="primary")
rules_html_comp = gr.HTML()
with gr.Group():
gr.Markdown("#### Approve or Reject a Rule")
gr.Markdown(
"Rejection reasons are logged β Agent 2 learns from them on the next cycle."
)
rule_selector = gr.Dropdown(label="Select rule", choices=[])
rule_rid = gr.Textbox(label="Researcher ID", placeholder="e.g. R1")
rule_note = gr.Textbox(
label="Note (required for rejection, optional for approval)", lines=2,
placeholder="This rule is consistent with sessions 3β5 becauseβ¦"
)
with gr.Row():
reject_rule_btn = gr.Button("Reject β", variant="secondary")
approve_rule_btn = gr.Button("Approve β", variant="primary")
rule_status = gr.Markdown()
with gr.Row():
back_library_btn = gr.Button("β Back to Agreement")
home_from_lib = gr.Button("Home")
open_lexicon_btn = gr.Button("Open Lexicon β")
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PAGE 8: Lexicon manager
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
with gr.Column(visible=False) as pg_lexicon:
gr.HTML(
'<div class="cc-page-nav">'
'<h2 class="cc-page-title">Lexicon Manager</h2>'
'</div>'
'<div class="cc-callout">'
'Tier 1 is research-locked (Iiskala 2011; Schoor & Bannert 2012). '
'Tier 2 accepts researcher-validated additions. '
'Tier 3 collects candidates found during screening β review and promote them here.'
'</div>'
)
with gr.Tabs():
with gr.Tab("Tier 1 β Core (read-only)"):
tier1_html = gr.HTML()
with gr.Tab("Tier 2 β Validated"):
tier2_html = gr.HTML()
gr.HTML('<div style="margin-top:20px;font-weight:700;margin-bottom:6px">Add term to Tier 2</div>')
with gr.Row():
t2_cat_id = gr.Textbox(label="Category ID", placeholder="MON_custom")
t2_label = gr.Textbox(label="Label", placeholder="Metacognitive hedge")
t2_phase = gr.Dropdown(label="Phase", choices=["planning","monitoring","evaluating","ssrl"], value="monitoring")
t2_weight = gr.Number(label="Weight (0β1)", value=0.5, minimum=0, maximum=1)
t2_terms_box = gr.Textbox(label="Terms (one per line or comma-separated)", lines=3)
with gr.Row():
t2_researcher = gr.Textbox(label="Researcher ID", placeholder="R1")
t2_note = gr.Textbox(label="Note (optional)")
add_t2_btn = gr.Button("Add to Tier 2", variant="primary")
t2_status = gr.HTML()
with gr.Tab("Tier 3 β Candidates"):
tier3_html = gr.HTML()
gr.HTML('<div style="margin-top:16px;font-weight:700">Approve or reject a candidate</div>')
with gr.Row():
t3_term = gr.Textbox(label="Term (exact text)")
t3_researcher = gr.Textbox(label="Researcher ID", placeholder="R1")
t3_note = gr.Textbox(label="Rejection note (optional)")
with gr.Row():
t3_reject_btn = gr.Button("Reject", variant="secondary")
t3_approve_btn = gr.Button("Approve", variant="primary")
t3_status = gr.HTML()
lex_error = gr.HTML()
load_lexicon_btn = gr.Button("Refresh Lexicon", variant="secondary", size="sm")
with gr.Row():
back_lexicon_btn = gr.Button("β Back to Library")
home_from_lex = gr.Button("Home")
# =====================================================================
# ALL PAGES list (order must match _PAGE_NAMES)
# =====================================================================
ALL_PAGES = [pg_welcome, pg_setup, pg_screener, pg_sections, pg_pipeline,
pg_done, pg_agreement, pg_library, pg_lexicon]
CODING_OUTPUTS = [
coding_progress_comp, # 0
segment_jump, # 1
turns_html_comp, # 2
uncertainty_comp, # 3
proposal_comp, # 4
dim_radio, # 5
dim_desc_comp, # 6
secondary_dim_drop, # 7
comment_box, # 8
next_section_btn, # 9
ssrl_radio, # 10 β SSRL phase tag
ssrl_col, # 11 β SSRL section visibility (show only for D1-D9)
]
# fn_parse_transcript / fn_process_with_source outputs
# state, pipeline_bar_html, process_status, process_btn,
# screener_summary_html, screener_turns_html_c, screener_to_sections_btn, *ALL_PAGES
PARSE_OUTPUTS = [
state, pipeline_bar_html, process_status, process_btn,
screener_summary_html, screener_turns_html_c, screener_to_sections_btn,
*ALL_PAGES,
]
# fn_run_agent0 outputs
# state, pipeline_bar_html, sections_display_html, sections_labels_box, *ALL_PAGES
AGENT0_OUTPUTS = [
state, pipeline_bar_html, sections_display_html, sections_labels_box,
*ALL_PAGES,
]
# Legacy alias (used by load_prev_btn and other legacy code paths)
PROCESS_OUTPUTS = PARSE_OUTPUTS
# fn_confirm_sections outputs (13 total β generator; includes button + sections_display)
CONFIRM_SECTIONS_OUTPUTS = [
state, *ALL_PAGES,
sections_display_html, # show busy state on yield-1; clear on yield-2
confirm_sections_btn, # disable on yield-1; re-enable on yield-2
col_run_all_boundaries,
col_boundary_review,
col_coding,
]
# fn_run_all_boundaries outputs (10 total)
RUN_ALL_OUTPUTS = [
state,
parallel_status_md,
parallel_stats_html,
col_boundary_review,
boundary_display_html,
boundary_ids_box,
section_header_md,
pipeline_log,
agent_activity_html,
episode_dialogue_html, # NEW β full dialogue view per episode
]
# fn_confirm_and_code outputs (14 total)
CONFIRM_CODE_OUTPUTS = [state, code_status, col_coding] + CODING_OUTPUTS + [pipeline_log]
# fn_next_section outputs (15 total β includes boundary + dialogue update for next section)
NEXT_SECTION_OUTPUTS = [
state, *ALL_PAGES,
sections_overview_html,
section_header_md,
col_boundary_review,
col_coding,
boundary_display_html, # re-populate for next section
boundary_ids_box, # re-populate for next section
episode_dialogue_html, # re-populate for next section
]
# =====================================================================
# WIRING
# =====================================================================
# Welcome navigation
start_btn.click(lambda: _show("setup"), outputs=ALL_PAGES)
agreement_nav_btn.click(lambda: _show("agreement"), outputs=ALL_PAGES)
library_nav_btn.click(lambda: _show("library"), outputs=ALL_PAGES)
# Back buttons
back_setup_btn.click(lambda: _show("welcome"), outputs=ALL_PAGES)
back_sections_btn.click(
fn=lambda st: _show("screener") if st.get("screener_result") else _show("setup"),
inputs=[state], outputs=ALL_PAGES,
)
back_pipeline_btn.click(lambda: _show("sections"), outputs=ALL_PAGES)
back_done_btn.click(lambda: _show("pipeline"), outputs=ALL_PAGES)
back_agreement_btn.click(lambda: _show("done"), outputs=ALL_PAGES)
back_library_btn.click(lambda: _show("agreement"), outputs=ALL_PAGES)
home_from_lib.click(lambda: _show("welcome"), outputs=ALL_PAGES)
back_screener_btn.click(lambda: _show("setup"), outputs=ALL_PAGES)
# Forward navigation
go_agreement_btn.click(lambda: _show("agreement"), outputs=ALL_PAGES)
go_library_btn.click(lambda: _show("library"), outputs=ALL_PAGES)
# Setup: Drive β Phase 1 (parse + screen)
drive_refresh_btn.click(
fn=fn_refresh_drive_transcripts,
inputs=[researcher_id_box],
outputs=[drive_file_dropdown, drive_status_html],
)
load_prev_btn.click(
fn=fn_load_previous_session,
inputs=[researcher_id_box, state],
outputs=PARSE_OUTPUTS,
)
process_btn.click(
fn=fn_process_with_source,
inputs=[drive_file_dropdown, researcher_id_box, state],
outputs=PARSE_OUTPUTS,
).then(fn=lambda: gr.update(visible=True), outputs=[pipeline_bar_html])
# Screener: manual re-run (only shown when auto-run failed)
run_screener_btn.click(
fn=fn_run_screener,
inputs=[state],
outputs=[state, pipeline_bar_html, screener_summary_html,
screener_turns_html_c, run_screener_btn],
)
# Screener β Sections: Phase 2 (run Agent 0)
screener_to_sections_btn.click(
fn=fn_run_agent0,
inputs=[state],
outputs=AGENT0_OUTPUTS,
)
# Sections: confirm labels
confirm_sections_btn.click(
fn=fn_confirm_sections,
inputs=[sections_labels_box, state],
outputs=CONFIRM_SECTIONS_OUTPUTS,
)
# Pipeline: run boundaries in parallel
run_all_btn.click(
fn=fn_run_all_boundaries,
inputs=[state],
outputs=RUN_ALL_OUTPUTS,
)
# Pipeline: confirm boundaries + run Agent 1b
confirm_boundaries_btn.click(
fn=fn_confirm_and_code,
inputs=[boundary_ids_box, state],
outputs=CONFIRM_CODE_OUTPUTS,
)
# Coding navigation (now includes ssrl_radio)
next_btn.click(
fn=lambda d, sec, c, ssrl, s: fn_navigate(+1, d, sec, c, ssrl, s),
inputs=[dim_radio, secondary_dim_drop, comment_box, ssrl_radio, state],
outputs=[state] + CODING_OUTPUTS,
)
prev_btn.click(
fn=lambda d, sec, c, ssrl, s: fn_navigate(-1, d, sec, c, ssrl, s),
inputs=[dim_radio, secondary_dim_drop, comment_box, ssrl_radio, state],
outputs=[state] + CODING_OUTPUTS,
)
segment_jump.change(
fn=fn_jump,
inputs=[segment_jump, state],
outputs=[state] + CODING_OUTPUTS,
)
reveal_btn.click(fn=fn_reveal, inputs=[state], outputs=[proposal_comp])
# dim_radio controls description AND shows/hides SSRL section
dim_radio.change(
fn=fn_dim_desc,
inputs=[dim_radio],
outputs=[dim_desc_comp, ssrl_col],
)
# Skip episode β mark as not codeable and advance
skip_btn.click(
fn=fn_skip_episode,
inputs=[state],
outputs=[state] + CODING_OUTPUTS,
)
# Finish section / go to done (now includes ssrl_radio)
next_section_btn.click(
fn=fn_next_section,
inputs=[dim_radio, secondary_dim_drop, comment_box, ssrl_radio, state],
outputs=NEXT_SECTION_OUTPUTS,
)
# Download
download_btn.click(fn=fn_download, inputs=[state], outputs=[download_file]).then(
fn=lambda: gr.update(visible=True), outputs=[download_file]
)
# Agreement
kappa_btn.click(
fn=fn_calculate_kappa,
inputs=[r2_upload, state],
outputs=[state, kappa_html_comp, disagreements_md, col_disagreements, agreement_log],
)
resolve_btn.click(
fn=fn_resolve,
inputs=[dis_seg_id, dis_dim, dis_note, state],
outputs=[state, dis_status],
)
discard_btn.click(
fn=fn_discard,
inputs=[dis_seg_id, dis_note, state],
outputs=[state, dis_status],
)
# Sequence analysis
seq_run_btn.click(
fn=fn_run_sequence_analysis,
inputs=[seq_rater_choice, state],
outputs=[seq_summary_md, seq_matrix_html, seq_sig_html, col_seq_download],
)
seq_dl_btn.click(
fn=fn_download_seq_csv,
inputs=[seq_rater_choice, state],
outputs=[seq_dl_file],
).then(fn=lambda: gr.update(visible=True), outputs=[seq_dl_file])
# Library
load_rules_btn.click(fn=fn_load_rules, outputs=[rules_html_comp, rule_selector])
approve_rule_btn.click(
fn=fn_approve, inputs=[rule_selector, rule_rid, rule_note], outputs=[rule_status]
)
reject_rule_btn.click(
fn=fn_reject, inputs=[rule_selector, rule_rid, rule_note], outputs=[rule_status]
)
open_lexicon_btn.click(
fn=fn_load_lexicon,
outputs=[tier1_html, tier2_html, tier3_html, lex_error],
).then(lambda: _show("lexicon"), outputs=ALL_PAGES)
# Lexicon navigation + actions
back_lexicon_btn.click(lambda: _show("library"), outputs=ALL_PAGES)
home_from_lex.click(lambda: _show("welcome"), outputs=ALL_PAGES)
load_lexicon_btn.click(
fn=fn_load_lexicon,
outputs=[tier1_html, tier2_html, tier3_html, lex_error],
)
add_t2_btn.click(
fn=fn_add_tier2_term,
inputs=[t2_cat_id, t2_label, t2_phase, t2_terms_box, t2_weight,
t2_researcher, t2_note],
outputs=[t2_status, tier2_html, lex_error],
)
t3_approve_btn.click(
fn=fn_approve_t3,
inputs=[t3_term, t3_researcher],
outputs=[t3_status, tier3_html],
)
t3_reject_btn.click(
fn=fn_reject_t3,
inputs=[t3_term, t3_researcher, t3_note],
outputs=[t3_status, tier3_html],
)
if __name__ == "__main__":
demo.launch(css=CSS, theme=gr.themes.Soft(), ssr_mode=False)
"""
app.py (v4) β CollabCode Researcher Interface
==============================================
Page-based flow: Welcome β Setup β Sections β Pipeline β Done β Agreement β Library
No tabs. One task per screen.
"""
from __future__ import annotations
import json
import html as html_lib
import queue as _queue
import tempfile
import threading
import time
from datetime import datetime, timezone, timedelta
from pathlib import Path
import gradio as gr
from transcript_parser import parse_transcript
from agent0_sectioner import run_sectioning
from metacog_screener import (
screen_transcript, result_to_dict,
add_tier2_term, propose_tier3_candidate,
approve_tier3_candidate, reject_tier3_candidate,
load_full_lexicon,
)
from agent1a_boundary import propose_boundaries, boundaries_to_segments
from agent1b_coder import code_section
from drive_utils import (
get_drive_service,
list_transcripts,
read_file_from_drive,
write_session_to_drive,
load_session_from_drive,
register_researcher,
format_drive_diagnostic,
)
from kappa_calculator import (
calculate_kappa_report,
resolve_disagreement,
discard_disagreement,
)
from agent2_learner import list_pending_rules, approve_rule, reject_rule
from pipeline import (
run_boundaries_parallel,
run_coding_with_context,
render_pipeline_stats_html,
PipelineStats,
)
from llm_client import circuit_state, compute_timeout, reset_circuit
from sequential_analysis import (
load_and_analyse,
render_transition_matrix_html,
render_significant_transitions_html,
to_csv as seq_to_csv,
lag_to_csv,
)
SESSIONS_ROOT = Path("sessions")
SESSIONS_ROOT.mkdir(parents=True, exist_ok=True)
_STYLES_DIR = Path(__file__).parent / "static" / "styles"
MODEL_ID = "Qwen/Qwen2.5-72B-Instruct"
TEMPERATURE = 0.1
import sys as _sys, importlib.metadata as _meta
def _startup_log() -> None:
import gradio as _gr
try:
hf_ver = _meta.version("huggingface_hub")
except Exception:
hf_ver = "unknown"
hf_tok = "SET" if __import__("os").environ.get("HF_TOKEN") else "MISSING β "
print("=" * 60)
print(" CollabCode v4 β startup")
print("=" * 60)
print(f" Python : {_sys.version.split()[0]}")
print(f" Gradio : {_gr.__version__}")
print(f" HF hub : {hf_ver}")
print(f" HF_TOKEN : {hf_tok}")
print(f" Sessions root: {SESSIONS_ROOT.resolve()}")
print(f" Model : {MODEL_ID}")
print("=" * 60)
_startup_log()
def _load_css() -> str:
scss_entry = _STYLES_DIR / "main.scss"
if scss_entry.exists():
try:
import subprocess
result = subprocess.run(
["sass", str(scss_entry), "--style=expanded",
"--load-path", str(_STYLES_DIR), "--no-source-map"],
capture_output=True, text=True, timeout=30,
)