'
- f'Section {idx + 1} of {len(sections)} — '
- f'
{_h(sec.get("label", ""))}'
- f' · Episode {ep_num} of {total}'
+ f'
'
+ f'
'
+ f'Section {idx+1}/{len(sections)} — '
+ f'{_h(sec.get("label",""))} · Episode {ep_num}/{total}'
f'
'
- f'
'
- f'
{coded} of {total} coded ({pct}%)
'
+ f'
'
+ f'
{coded}/{total} coded ({pct}%)
'
f'
'
)
# ===========================================================================
-# STATE HELPERS
+# STATE
# ===========================================================================
def _empty_state() -> dict:
@@ -538,6 +688,7 @@ def _empty_state() -> dict:
"session_id": "",
"researcher_id": "",
"turns": [],
+ "speakers": {}, # name → palette entry
"sections": [],
"section_idx": 0,
"section_stages": {},
@@ -548,7 +699,7 @@ def _empty_state() -> dict:
"codings": {},
"stage": "upload",
"kappa_report": None,
- "_last_error": None,
+ "agent_logs": [], # list of log entry dicts
}
@@ -564,33 +715,23 @@ def _current_section(state: dict) -> dict | None:
def _current_section_segments(state: dict) -> list[dict]:
sec = _current_section(state)
- if not sec:
- return []
- return state["section_segments_coded"].get(sec["section_id"], [])
+ return state["section_segments_coded"].get(sec["section_id"], []) if sec else []
def _turns_for_section(turns: list[dict], section: dict) -> list[dict]:
- return [
- t for t in turns
- if section["start_turn_id"] <= t["turn_id"] <= section["end_turn_id"]
- ]
-
-
-def _all_sections_done(state: dict) -> bool:
- stages = state.get("section_stages", {})
- secs = state.get("sections", [])
- return bool(secs) and all(
- stages.get(s["section_id"]) == "done" for s in secs
- )
+ return [t for t in turns
+ if section["start_turn_id"] <= t["turn_id"] <= section["end_turn_id"]]
def _persist(state: dict) -> None:
try:
d = _session_dir(state)
d.mkdir(parents=True, exist_ok=True)
- payload = {k: v for k, v in state.items() if k not in ("turns", "kappa_report")}
+ skip = {"turns", "kappa_report"}
(d / "app_state.json").write_text(
- json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8"
+ json.dumps({k: v for k, v in state.items() if k not in skip},
+ indent=2, ensure_ascii=False),
+ encoding="utf-8",
)
except Exception:
pass
@@ -600,34 +741,26 @@ def _seconds_to_hms(s: float) -> str:
return str(timedelta(seconds=int(s)))
+def _push_log(state: dict, entry: dict) -> dict:
+ logs = list(state.get("agent_logs", []))
+ logs.append(entry)
+ state["agent_logs"] = logs[-10:]
+ return state
+
+
# ===========================================================================
-# CODING UI HELPERS
+# CODING RENDER HELPERS
# ===========================================================================
-def _segment_dropdown_label(seg: dict, codings: dict) -> str:
- sid = seg["segment_id"]
- ep = sid.split("_ep")[-1] if "_ep" in sid else sid[-4:]
- did = seg.get("dimension_id") or "?"
- coded = "✓" if codings.get(sid, {}).get("dimension_id") else "○"
- flag = " ⚠" if seg.get("uncertain") else ""
+def _segment_label(seg: dict, codings: dict) -> str:
+ sid = seg["segment_id"]
+ ep = sid.split("_ep")[-1] if "_ep" in sid else sid[-4:]
+ did = seg.get("dimension_id") or "?"
+ coded = "✓" if codings.get(sid, {}).get("dimension_id") else "○"
+ flag = " ⚠" if seg.get("uncertain") else ""
return f"{coded} ep{ep} [{did}]{flag}"
-def _format_turns_md(seg: dict) -> str:
- turns = seg.get("turns", [])
- if not turns:
- return "*No turns in this segment.*"
- speakers = list(dict.fromkeys(t.get("speaker", "") for t in turns))
- lines = []
- for t in turns:
- sp = t.get("speaker", "?")
- time = t.get("start_time", "")
- text = t.get("text", "")
- fmt = f"**{sp}**" if speakers.index(sp) % 2 == 0 else f"_{sp}_"
- lines.append(f"{fmt} `{time}` \n{text}")
- return "\n\n---\n\n".join(lines)
-
-
def _proposal_md(seg: dict) -> str:
did = seg.get("dimension_id", "?")
rat = seg.get("rationale", "")
@@ -636,84 +769,95 @@ def _proposal_md(seg: dict) -> str:
tags.append("✅ Confident")
if seg.get("uncertain"):
tags.append(f"⚠️ Uncertain — {seg.get('uncertainty_note', '')}")
- tag_line = " ".join(tags)
- return f"> **AI proposal: {did}** \n> {rat}\n\n{tag_line}".strip()
+ return f"> **AI proposal: {did}** \n> {rat}\n\n{' '.join(tags)}".strip()
CODING_EMPTY = (
- "", # progress html
- gr.update(choices=[], value=None), # segment_jump
- "*Run Agent 1a and confirm boundaries first.*", # turns_display
- "", # uncertainty_html
- gr.update(value="", visible=False), # proposal_md
- gr.update(choices=DIM_CHOICES, value=None), # dim_radio
- "", # dim_desc_html
- "", # comment_box
- gr.update(visible=False), # next_section_btn
+ "", # progress html
+ gr.update(choices=[], value=None), # segment_jump
+ "", # turns_display_html
+ "", # uncertainty_html
+ gr.update(value="", visible=False), # proposal_md
+ gr.update(choices=DIM_CHOICES, value=None), # dim_radio
+ "", # dim_desc_html
+ "", # comment_box
+ gr.update(visible=False), # next_section_btn
)
def _render_coding(state: dict) -> tuple:
- segs = _current_section_segments(state)
- codings = state.get("codings", {})
- cidx = state.get("coding_idx", 0)
+ segs = _current_section_segments(state)
+ codings = state.get("codings", {})
+ cidx = state.get("coding_idx", 0)
+ speaker_map = state.get("speakers", {})
if not segs:
return CODING_EMPTY
- seg = segs[min(cidx, len(segs) - 1)]
- sid = seg["segment_id"]
- existing = codings.get(sid, {})
- saved_dim = existing.get("dimension_id", "")
- choice = next((c for c in DIM_CHOICES if c.startswith(saved_dim)), None)
-
- all_coded = len(codings) >= len(segs) and all(
+ seg = segs[min(cidx, len(segs) - 1)]
+ sid = seg["segment_id"]
+ existing = codings.get(sid, {})
+ saved = existing.get("dimension_id", "")
+ choice = next((c for c in DIM_CHOICES if c.startswith(saved)), None)
+ all_done = len(codings) >= len(segs) and all(
codings.get(s["segment_id"], {}).get("dimension_id") for s in segs
)
- jump_choices = [_segment_dropdown_label(s, codings) for s in segs]
+ labels = [_segment_label(s, codings) for s in segs]
return (
_coding_progress_html(state),
- gr.update(choices=jump_choices, value=jump_choices[min(cidx, len(segs) - 1)]),
- _format_turns_md(seg),
+ gr.update(choices=labels, value=labels[min(cidx, len(segs) - 1)]),
+ _format_turns_html(seg, speaker_map),
_uncertainty_html(seg),
gr.update(value=_proposal_md(seg), visible=False),
gr.update(choices=DIM_CHOICES, value=choice),
_dim_desc_html(choice or ""),
existing.get("comment", ""),
- gr.update(visible=all_coded),
+ gr.update(visible=all_done),
)
# ===========================================================================
-# BACKEND CALLBACKS
+# CALLBACKS
# ===========================================================================
-# ── Stage 1: Parse ───────────────────────────────────────────────────────
+# ── Stage 1: Parse ───────────────────────────────────────────────────────────
def fn_parse(file_obj, session_id: str, researcher_id: str, state: dict):
if file_obj is None:
raise gr.Error("Upload a transcript file first.")
if not session_id.strip():
- raise gr.Error("Enter a session ID.")
+ raise gr.Error("Enter a Session ID (e.g. dyad_01).")
if not researcher_id.strip():
- raise gr.Error("Enter your researcher ID.")
+ raise gr.Error("Enter your Researcher ID (e.g. R1).")
+ t0 = time.perf_counter()
try:
turns = parse_transcript(file_obj.name)
except Exception as e:
raise gr.Error(f"Could not parse transcript: {e}") from e
if len(turns) < 5:
- raise gr.Error(f"Only {len(turns)} turns found. Check that the transcript format is correct.")
+ raise gr.Error(f"Only {len(turns)} turns found — check the transcript format.")
+
+ rt = round(time.perf_counter() - t0, 1)
+ speaker_map = _assign_speakers(turns)
+ speakers = list(speaker_map.keys())
new_state = _empty_state()
new_state.update({
"session_id": session_id.strip(),
"researcher_id": researcher_id.strip(),
"turns": turns,
+ "speakers": speaker_map,
"stage": "parsed",
})
+ log_entry = _make_log_entry(
+ "Transcript Parser", rt,
+ turns=len(turns), speakers=len(speakers),
+ system_prompt_preview="(no LLM call — rule-based parser)",
+ )
+ new_state = _push_log(new_state, log_entry)
d = SESSIONS_ROOT / session_id.strip()
d.mkdir(parents=True, exist_ok=True)
@@ -721,65 +865,69 @@ def fn_parse(file_obj, session_id: str, researcher_id: str, state: dict):
json.dumps(turns, indent=2, ensure_ascii=False), encoding="utf-8"
)
- speakers = list(dict.fromkeys(t["speaker"] for t in turns))
duration = _seconds_to_hms(turns[-1]["start_seconds"] - turns[0]["start_seconds"])
- summary_md = (
- f"**Session:** `{session_id.strip()}` · **Researcher:** `{researcher_id.strip()}`\n\n"
+ legend = _speaker_legend_html(speaker_map)
+ summary = (
+ f"{legend}"
f"| | |\n|---|---|\n"
- f"| Turns | {len(turns)} |\n"
+ f"| Turns | **{len(turns)}** |\n"
f"| Speakers | {', '.join(speakers)} |\n"
f"| Duration | {duration} |\n"
+ f"| Session | `{session_id.strip()}` |\n"
)
- gr.Info(f"Parsed {len(turns)} turns. Review the summary, then detect sections.")
+ gr.Info(f"Parsed {len(turns)} turns from {len(speakers)} speaker(s).")
return (
new_state,
_pipeline_html("parsed"),
- summary_md,
- gr.update(visible=True), # col_agent0
+ summary,
+ gr.update(visible=True), # col_agent0
+ _agent_log_html(new_state["agent_logs"]),
)
-# ── Stage 2: Agent 0 section detection ───────────────────────────────────
+# ── Stage 2: Agent 0 ─────────────────────────────────────────────────────────
def fn_run_agent0(state: dict):
if not state.get("turns"):
raise gr.Error("Parse a transcript first.")
- yield (
- state,
- _pipeline_html("parsed"),
- gr.update(visible=False),
- "", "",
- )
+ yield state, _pipeline_html("parsed"), gr.update(visible=False), "", "", ""
+ t0 = time.perf_counter()
try:
- result = run_sectioning(
- turns=state["turns"],
- session_id=state["session_id"],
- )
+ result = run_sectioning(turns=state["turns"], session_id=state["session_id"])
except Exception as e:
raise gr.Error(f"Agent 0 failed: {e}") from e
+ rt = round(time.perf_counter() - t0, 1)
sections = result["sections"]
if not sections:
- raise gr.Error("Agent 0 returned no sections. Try again or check the transcript.")
+ raise gr.Error("Agent 0 returned no sections. Try again.")
- warnings = result.get("warnings", [])
- if warnings:
- gr.Warning("Section coverage warnings detected — check the transcript range.")
+ from agent0_sectioner import build_system_prompt, load_dimension_labels
+ sys_prev = build_system_prompt(load_dimension_labels())[:120]
+ user_prev = f"Segment {len(state['turns'])} turns into topical sections."
state = dict(state)
state["sections"] = sections
state["section_stages"] = {s["section_id"]: "pending" for s in sections}
state["stage"] = "sectioned"
+ log = _make_log_entry(
+ "Agent 0 — Structural Segmenter", rt,
+ sections_proposed=len(sections),
+ warnings=len(result.get("warnings", [])),
+ system_prompt_preview=sys_prev,
+ user_prompt_preview=user_prev,
+ )
+ state = _push_log(state, log)
d = _session_dir(state)
(d / "sections_proposed.json").write_text(
json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8"
)
- overview = result.get("session_overview", "")
+ overview = result.get("session_overview", "")
sections_md = (
"| # | Label | Turns | Time |\n|---|---|---|---|\n"
+ "\n".join(
@@ -788,45 +936,45 @@ def fn_run_agent0(state: dict):
f"{s['start_time']}–{s['end_time']} |"
for s in sections
)
+ + (f"\n\n*{overview}*" if overview else "")
)
labels_txt = "\n".join(s["label"] for s in sections)
- gr.Info(f"{len(sections)} sections detected. Review and edit labels, then confirm.")
+ if result.get("warnings"):
+ gr.Warning("Coverage warnings detected — check the section table.")
+ gr.Info(f"{len(sections)} sections detected in {rt}s.")
+
yield (
state,
_pipeline_html("sectioned"),
- gr.update(visible=True), # col_sections
- sections_md + (f"\n\n*{overview}*" if overview else ""),
+ gr.update(visible=True),
+ sections_md,
labels_txt,
+ _agent_log_html(state["agent_logs"]),
)
-# ── Stage 2b: Confirm sections ────────────────────────────────────────────
+# ── Stage 2b: Confirm sections ────────────────────────────────────────────────
def fn_confirm_sections(labels_text: str, state: dict):
sections = state.get("sections", [])
if not sections:
raise gr.Error("No sections to confirm — run Agent 0 first.")
- labels = [l.strip() for l in labels_text.strip().splitlines() if l.strip()]
- if len(labels) != len(sections):
- gr.Warning(
- f"Label count ({len(labels)}) doesn't match section count ({len(sections)}). "
- "Using original labels for unmatched sections."
- )
+ labels = [l.strip() for l in labels_text.strip().splitlines() if l.strip()]
+ confirmed = [dict(s, label=labels[i] if i < len(labels) else s["label"])
+ for i, s in enumerate(sections)]
- confirmed = []
- for i, s in enumerate(sections):
- updated = dict(s)
- if i < len(labels):
- updated["label"] = labels[i]
- confirmed.append(updated)
+ if len(labels) != len(sections):
+ gr.Warning(f"Label count mismatch ({len(labels)} vs {len(sections)}) — unmatched sections keep original labels.")
state = dict(state)
- state["sections"] = confirmed
- state["section_idx"] = 0
- state["section_stages"] = {s["section_id"]: "pending" for s in confirmed}
- state["stage"] = "coding"
+ state.update({
+ "sections": confirmed,
+ "section_idx": 0,
+ "section_stages": {s["section_id"]: "pending" for s in confirmed},
+ "stage": "coding",
+ })
d = _session_dir(state)
(d / "sections_confirmed.json").write_text(
@@ -841,21 +989,20 @@ def fn_confirm_sections(labels_text: str, state: dict):
f"*{sec.get('summary', '')}* · "
f"turns {sec['start_turn_id']}–{sec['end_turn_id']} ({n} turns)"
)
-
- gr.Info(f"{len(confirmed)} sections confirmed. Now detect boundaries for Section 1.")
+ gr.Info(f"{len(confirmed)} sections confirmed. Detect boundaries for Section 1.")
return (
state,
_pipeline_html("coding"),
_section_cards_html(confirmed, state["section_stages"], 0),
hdr,
- gr.update(visible=True), # col_section_work
- gr.update(visible=True), # col_boundary_btn
- gr.update(visible=False), # col_boundary_review
- gr.update(visible=False), # col_coding
+ gr.update(visible=True), # col_section_work
+ gr.update(visible=True), # col_boundary_btn
+ gr.update(visible=False), # col_boundary_review
+ gr.update(visible=False), # col_coding
)
-# ── Stage 3a: Agent 1a boundary detection ────────────────────────────────
+# ── Stage 3a: Agent 1a ────────────────────────────────────────────────────────
def fn_propose_boundaries(state: dict):
sec = _current_section(state)
@@ -866,56 +1013,70 @@ def fn_propose_boundaries(state: dict):
if not turns:
raise gr.Error(f"No turns found for section {sec['section_id']}.")
- yield (state, "⏳ Detecting episode boundaries…", gr.update(visible=False), "", "")
+ yield state, "⏳ Detecting episode boundaries…", gr.update(visible=False), "", "", ""
+ t0 = time.perf_counter()
try:
- result = propose_boundaries(
- section=sec, turns=turns, session_id=state["session_id"]
- )
+ result = propose_boundaries(section=sec, turns=turns,
+ session_id=state["session_id"])
except Exception as e:
raise gr.Error(f"Agent 1a failed: {e}") from e
+ rt = round(time.perf_counter() - t0, 1)
+
+ from agent1a_boundary import build_system_prompt as a1a_sys
+ from agent1a_boundary import build_user_prompt as a1a_user
+ sys_prev = a1a_sys()[:120]
+ user_prev = f"Section: {sec['section_id']} — {sec['label']} ({len(turns)} turns)"
+
boundaries = result["boundaries"]
- n_low = sum(1 for b in boundaries if b.get("confidence") == "low")
+ n_low = sum(1 for b in boundaries if b.get("confidence") == "low")
if n_low:
- gr.Warning(f"{n_low} boundary{'is' if n_low == 1 else 'ies'} have low confidence — review carefully.")
+ gr.Warning(f"{n_low} low-confidence boundary{'ies' if n_low>1 else ''} — review carefully.")
state = dict(state)
state["section_boundaries"][sec["section_id"]] = boundaries
state["section_segments"][sec["section_id"]] = result["segments"]
state["section_stages"][sec["section_id"]] = "boundaries"
+ log = _make_log_entry(
+ "Agent 1a — Boundary Detector", rt,
+ boundaries_proposed=len(boundaries),
+ episodes=len(result["segments"]),
+ low_confidence=n_low,
+ system_prompt_preview=sys_prev,
+ user_prompt_preview=user_prev,
+ )
+ state = _push_log(state, log)
ids_text = ", ".join(str(b["after_turn_id"]) for b in boundaries)
-
- status = (
- f"**{len(boundaries)} boundary{'ies' if len(boundaries) != 1 else ''} proposed "
+ status = (
+ f"**{len(boundaries)} boundary{'ies' if len(boundaries)!=1 else ''} proposed "
f"→ {len(result['segments'])} episodes.** \n"
- f"Review the episode table. Edit turn IDs below if needed, then confirm."
+ f"Review the episode table, edit turn IDs if needed, then confirm."
)
+ gr.Info(f"{len(boundaries)} boundaries detected in {rt}s.")
yield (
state,
status,
gr.update(visible=True),
_episode_table_html(turns, boundaries),
ids_text,
+ _agent_log_html(state["agent_logs"]),
)
-# ── Stage 3b: Confirm boundaries + run Agent 1b ───────────────────────────
+# ── Stage 3b: Confirm + Agent 1b ─────────────────────────────────────────────
def fn_confirm_and_code(boundary_ids_text: str, state: dict):
sec = _current_section(state)
if not sec:
raise gr.Error("No section loaded.")
- turns = _turns_for_section(state["turns"], sec)
- if not turns:
- raise gr.Error(f"No turns for section {sec['section_id']}.")
-
- # Parse researcher-edited boundary IDs
+ turns = _turns_for_section(state["turns"], sec)
valid_ids = {t["turn_id"] for t in turns}
boundaries: list[dict] = []
+
for tok in boundary_ids_text.split(","):
tok = tok.strip()
if not tok:
@@ -923,141 +1084,124 @@ def fn_confirm_and_code(boundary_ids_text: str, state: dict):
try:
tid = int(tok)
except ValueError:
- raise gr.Error(f"'{tok}' is not a valid turn ID. Enter integers only.")
+ raise gr.Error(f"'{tok}' is not a valid turn ID.")
if tid not in valid_ids:
- raise gr.Error(
- f"Turn ID {tid} is not in this section "
- f"(valid range: {min(valid_ids)}–{max(valid_ids)})."
- )
- boundaries.append({
- "boundary_id": f"r_{tid}",
- "after_turn_id": tid,
- "confidence": "high",
- "boundary_signal": "researcher_defined",
- "rationale": "Boundary defined by researcher review.",
- })
+ raise gr.Error(f"Turn {tid} is outside this section (range {min(valid_ids)}–{max(valid_ids)}).")
+ boundaries.append({"boundary_id": f"r_{tid}", "after_turn_id": tid,
+ "confidence": "high", "boundary_signal": "researcher_defined",
+ "rationale": "Set by researcher."})
boundaries.sort(key=lambda b: b["after_turn_id"])
-
segments = boundaries_to_segments(sec, turns, boundaries, state["session_id"])
+
if not segments:
- raise gr.Error("Boundary IDs produced zero segments. Check your turn ID entries.")
+ raise gr.Error("No segments produced — check your boundary turn IDs.")
state = dict(state)
state["section_boundaries"][sec["section_id"]] = boundaries
state["section_segments"][sec["section_id"]] = segments
- n_segs = len(segments)
- yield (
- state,
- f"⏳ Agent 1b coding {n_segs} episode{'s' if n_segs != 1 else ''}…",
- gr.update(visible=False),
- *CODING_EMPTY,
- )
+ yield state, f"⏳ Agent 1b coding {len(segments)} episode(s)…", gr.update(visible=False), *CODING_EMPTY, ""
+ t0 = time.perf_counter()
try:
coded = code_section(section=sec, segments=segments)
except Exception as e:
raise gr.Error(f"Agent 1b failed: {e}") from e
+ rt = round(time.perf_counter() - t0, 1)
+
+ from agent1b_coder import build_system_prompt as a1b_sys, load_tier1, load_tier2
+ tier1 = load_tier1()
+ tier2 = load_tier2()
+ sys_prev = a1b_sys(tier1, tier2, sec)[:120]
+ user_prev = f"Code {len(segments)} segments in section: {sec['label']}"
+
+ n_uncertain = sum(1 for s in coded if s.get("uncertain"))
state["section_segments_coded"][sec["section_id"]] = coded
state["section_stages"][sec["section_id"]] = "coding"
state["coding_idx"] = 0
+ log = _make_log_entry(
+ "Agent 1b — Dimension Coder", rt,
+ segments_coded=len(coded),
+ uncertain_flagged=n_uncertain,
+ system_prompt_preview=sys_prev,
+ user_prompt_preview=user_prev,
+ )
+ state = _push_log(state, log)
d = _session_dir(state)
(d / f"segments_{sec['section_id']}.json").write_text(
json.dumps(coded, indent=2, ensure_ascii=False), encoding="utf-8"
)
- n_uncertain = sum(1 for s in coded if s.get("uncertain"))
- msg = f"✓ {len(coded)} segments coded."
+ msg = f"✓ {len(coded)} segments coded in {rt}s."
if n_uncertain:
- msg += f" **{n_uncertain} flagged uncertain** — check ⚠ markers."
- msg += " AI proposals hidden — code independently, then reveal if needed."
+ msg += f" **{n_uncertain} flagged ⚠ uncertain** — review those first."
+ gr.Info(f"{len(coded)} segments coded. {n_uncertain} uncertain.")
- gr.Info(f"{len(coded)} segments ready for coding.")
- yield (
- state,
- msg,
- gr.update(visible=True),
- *_render_coding(state),
- )
+ yield state, msg, gr.update(visible=True), *_render_coding(state), _agent_log_html(state["agent_logs"])
-# ── Stage 3c: Navigate segments ──────────────────────────────────────────
+# ── Navigate segments ─────────────────────────────────────────────────────────
def fn_navigate(direction: int, dim_choice: str, comment: str, state: dict):
- segs = _current_section_segments(state)
+ segs = _current_section_segments(state)
if not segs:
return state, *_render_coding(state)
-
idx = state.get("coding_idx", 0)
codings = dict(state.get("codings", {}))
sid = segs[idx]["segment_id"]
-
if dim_choice:
- codings[sid] = {
- "dimension_id": DIM_ID_FROM_CHOICE[dim_choice],
- "comment": comment.strip(),
- }
-
- state = dict(state)
- state["codings"] = codings
+ codings[sid] = {"dimension_id": DIM_ID_FROM_CHOICE[dim_choice], "comment": comment.strip()}
+ state = dict(state)
+ state["codings"] = codings
state["coding_idx"] = max(0, min(idx + direction, len(segs) - 1))
return state, *_render_coding(state)
-def fn_jump_to_segment(label: str, state: dict):
+def fn_jump(label: str, state: dict):
segs = _current_section_segments(state)
if not segs or not label:
return state, *_render_coding(state)
codings = state.get("codings", {})
- labels = [_segment_dropdown_label(s, codings) for s in segs]
+ labels = [_segment_label(s, codings) for s in segs]
state = dict(state)
if label in labels:
state["coding_idx"] = labels.index(label)
return state, *_render_coding(state)
-def fn_reveal_proposal(state: dict):
+def fn_reveal(state: dict):
segs = _current_section_segments(state)
if not segs:
return gr.update(visible=False)
- idx = state.get("coding_idx", 0)
- seg = segs[min(idx, len(segs) - 1)]
+ seg = segs[min(state.get("coding_idx", 0), len(segs) - 1)]
return gr.update(value=_proposal_md(seg), visible=True)
-def fn_update_dim_desc(choice: str):
+def fn_dim_desc(choice: str):
return _dim_desc_html(choice or "")
-# ── Stage 3d: Next section ────────────────────────────────────────────────
+# ── Next section ──────────────────────────────────────────────────────────────
def fn_next_section(dim_choice: str, comment: str, state: dict):
segs = _current_section_segments(state)
codings = dict(state.get("codings", {}))
idx = state.get("coding_idx", 0)
-
- # Save last segment's coding if a dimension was selected
if segs and dim_choice:
- sid = segs[min(idx, len(segs) - 1)]["segment_id"]
- codings[sid] = {
- "dimension_id": DIM_ID_FROM_CHOICE[dim_choice],
- "comment": comment.strip(),
- }
+ sid = segs[min(idx, len(segs) - 1)]["segment_id"]
+ codings[sid] = {"dimension_id": DIM_ID_FROM_CHOICE[dim_choice], "comment": comment.strip()}
- state = dict(state)
- state["codings"] = codings
-
- sections = state.get("sections", [])
- sec_idx = state.get("section_idx", 0)
- cur_sec = sections[sec_idx]
- state["section_stages"][cur_sec["section_id"]] = "done"
+ state = dict(state)
+ state["codings"] = codings
+ sections = state.get("sections", [])
+ sec_idx = state.get("section_idx", 0)
+ cur_id = sections[sec_idx]["section_id"]
+ state["section_stages"][cur_id] = "done"
next_idx = sec_idx + 1
-
if next_idx >= len(sections):
- # All done
state["stage"] = "complete"
_write_coding_file(state)
_persist(state)
@@ -1067,110 +1211,92 @@ def fn_next_section(dim_choice: str, comment: str, state: dict):
_pipeline_html("complete"),
_section_cards_html(sections, state["section_stages"], sec_idx),
"",
- gr.update(visible=False), # col_boundary_btn
- gr.update(visible=False), # col_boundary_review
- gr.update(visible=False), # col_coding
- gr.update(visible=True), # col_complete
+ gr.update(visible=False),
+ gr.update(visible=False),
+ gr.update(visible=False),
+ gr.update(visible=True),
)
- state["section_idx"] = next_idx
- state["coding_idx"] = 0
- next_sec = sections[next_idx]
- n = next_sec["end_turn_id"] - next_sec["start_turn_id"] + 1
+ state["section_idx"] = next_idx
+ state["coding_idx"] = 0
+ next_sec = sections[next_idx]
+ n = next_sec["end_turn_id"] - next_sec["start_turn_id"] + 1
hdr = (
- f"### Section {next_idx + 1} of {len(sections)}: {next_sec['label']}\n"
- f"*{next_sec.get('summary', '')}* · "
+ f"### Section {next_idx+1} of {len(sections)}: {next_sec['label']}\n"
+ f"*{next_sec.get('summary','')}* · "
f"turns {next_sec['start_turn_id']}–{next_sec['end_turn_id']} ({n} turns)"
)
_persist(state)
-
- gr.Info(f"Moving to section {next_idx + 1}: {next_sec['label']}")
+ gr.Info(f"Section {next_idx+1}: {next_sec['label']}")
return (
state,
_pipeline_html("coding"),
_section_cards_html(sections, state["section_stages"], next_idx),
hdr,
- gr.update(visible=True), # col_boundary_btn
- gr.update(visible=False), # col_boundary_review
- gr.update(visible=False), # col_coding
- gr.update(visible=False), # col_complete
+ gr.update(visible=True),
+ gr.update(visible=False),
+ gr.update(visible=False),
+ gr.update(visible=False),
)
-# ── Download coding file ──────────────────────────────────────────────────
+# ── Download ──────────────────────────────────────────────────────────────────
def _write_coding_file(state: dict) -> Path:
all_segs: list[dict] = []
for sec in state.get("sections", []):
- coded = state["section_segments_coded"].get(sec["section_id"], [])
- all_segs.extend(coded)
-
+ all_segs.extend(state["section_segments_coded"].get(sec["section_id"], []))
codings = state.get("codings", {})
output = {
"session_id": state["session_id"],
"researcher_id": state["researcher_id"],
"codings": [
- {
- "segment_id": s["segment_id"],
- "section_id": s.get("section_id", ""),
- "dimension_id": codings.get(s["segment_id"], {}).get("dimension_id", ""),
- "comment": codings.get(s["segment_id"], {}).get("comment", ""),
- }
+ {"segment_id": s["segment_id"], "section_id": s.get("section_id", ""),
+ "dimension_id": codings.get(s["segment_id"], {}).get("dimension_id", ""),
+ "comment": codings.get(s["segment_id"], {}).get("comment", "")}
for s in all_segs
],
}
-
- segments_all = {
- "segments": [{k: v for k, v in s.items() if k != "turns"} for s in all_segs]
- }
+ segs_all = {"segments": [{k: v for k, v in s.items() if k != "turns"} for s in all_segs]}
d = _session_dir(state)
(d / "segments_all.json").write_text(
- json.dumps(segments_all, indent=2, ensure_ascii=False), encoding="utf-8"
+ json.dumps(segs_all, indent=2, ensure_ascii=False), encoding="utf-8"
)
- rid = state["researcher_id"]
- out_path = d / f"coding_{rid}.json"
- out_path.write_text(
- json.dumps(output, indent=2, ensure_ascii=False), encoding="utf-8"
- )
- return out_path
+ out = d / f"coding_{state['researcher_id']}.json"
+ out.write_text(json.dumps(output, indent=2, ensure_ascii=False), encoding="utf-8")
+ return out
def fn_download(state: dict):
if not state.get("sections"):
raise gr.Error("No coding to download yet.")
- try:
- path = _write_coding_file(state)
- tmp = Path(tempfile.mktemp(suffix=f"_{path.name}"))
- tmp.write_bytes(path.read_bytes())
- return str(tmp)
- except Exception as e:
- raise gr.Error(f"Download failed: {e}") from e
+ path = _write_coding_file(state)
+ tmp = Path(tempfile.mktemp(suffix=f"_{path.name}"))
+ tmp.write_bytes(path.read_bytes())
+ return str(tmp)
-# ── Agreement tab ─────────────────────────────────────────────────────────
+# ── Agreement ─────────────────────────────────────────────────────────────────
def fn_calculate_kappa(r2_file, state: dict):
if r2_file is None:
raise gr.Error("Upload your co-researcher's coding file first.")
if not state.get("session_id"):
- raise gr.Error("Load a session in the Pipeline tab first.")
+ raise gr.Error("Complete the Pipeline first — session ID not set.")
d = _session_dir(state)
r1_path = d / f"coding_{state['researcher_id']}.json"
segs_path = d / "segments_all.json"
if not r1_path.exists():
- raise gr.Error(
- "Your coding file was not found. Complete and download your coding in the Pipeline tab."
- )
+ raise gr.Error("Your own coding file not found — download it from the Pipeline tab first.")
if not segs_path.exists():
- raise gr.Error(
- "Segments file not found. Make sure you completed the coding pipeline."
- )
+ raise gr.Error("Segments file not found — complete the coding pipeline first.")
r2_path = d / "coding_R2.json"
r2_path.write_bytes(Path(r2_file.name).read_bytes())
+ t0 = time.perf_counter()
try:
report = calculate_kappa_report(
session_id=state["session_id"],
@@ -1182,69 +1308,74 @@ def fn_calculate_kappa(r2_file, state: dict):
except Exception as e:
raise gr.Error(f"Kappa calculation failed: {e}") from e
- state = dict(state)
- state["kappa_report"] = report
-
+ rt = round(time.perf_counter() - t0, 1)
gate = report.get("gate_passed", False)
n_dis = len(report.get("segments_in_disagreement", []))
+ state = dict(state)
+ state["kappa_report"] = report
+ log = _make_log_entry(
+ "Kappa Calculator", rt,
+ kappa=round(report.get("overall_kappa", 0), 3),
+ gate_passed=gate,
+ disagreements=n_dis,
+ )
+ state = _push_log(state, log)
+
if gate:
- gr.Info(f"Kappa gate passed! {n_dis} disagreement(s) to resolve.")
+ gr.Info(f"κ={report['overall_kappa']:.3f} — gate passed! {n_dis} disagreements to resolve.")
else:
- gr.Warning("Kappa below 0.70 threshold — review and re-code before proceeding.")
+ gr.Warning(f"κ={report['overall_kappa']:.3f} — below 0.70 threshold. Review and re-code.")
dis_md = ""
if n_dis:
- dis = report.get("segments_in_disagreement", [])
- rows = "| Segment | R1 | R2 | Agent |\n|---|---|---|---|\n"
- for di in dis[:15]:
+ dis = report.get("segments_in_disagreement", [])
+ rows = "| Segment | R1 | R2 | Agent 1b |\n|---|---|---|---|\n"
+ for di in dis[:20]:
rows += (
f"| `{di['segment_id']}` "
- f"| {di.get('r1_dimension', '?')} "
- f"| {di.get('r2_dimension', '?')} "
- f"| {di.get('agent_dimension', '?')} |\n"
+ f"| {di.get('r1_dimension','?')} "
+ f"| {di.get('r2_dimension','?')} "
+ f"| {di.get('agent_dimension','?')} |\n"
)
- if len(dis) > 15:
- rows += f"| *…{len(dis) - 15} more* | | | |\n"
- dis_md = f"### Disagreements ({n_dis} total)\n\n{rows}"
+ if len(dis) > 20:
+ rows += f"| *…{len(dis)-20} more* | | | |\n"
+ dis_md = f"### Disagreements ({n_dis})\n\n{rows}"
return (
state,
_kappa_html(report),
dis_md,
gr.update(visible=bool(n_dis)),
+ _agent_log_html(state["agent_logs"]),
)
def fn_resolve(seg_id: str, dim_choice: str, note: str, state: dict):
if not seg_id.strip():
- raise gr.Error("Enter the segment ID to resolve.")
+ raise gr.Error("Enter the segment ID.")
if not dim_choice:
raise gr.Error("Select the resolved dimension.")
- d = _session_dir(state)
- resolved_dim = DIM_ID_FROM_CHOICE.get(dim_choice, dim_choice)
+ resolved = DIM_ID_FROM_CHOICE.get(dim_choice, dim_choice)
try:
resolve_disagreement(
- report_path=d / "kappa_report.json",
- segment_id=seg_id.strip(),
- resolved_dimension=resolved_dim,
+ report_path=_session_dir(state) / "kappa_report.json",
+ segment_id=seg_id.strip(), resolved_dimension=resolved,
resolution_note=note.strip(),
)
except Exception as e:
- raise gr.Error(f"Could not resolve disagreement: {e}") from e
- gr.Info(f"Resolved {seg_id.strip()} → {resolved_dim}")
- return state, f"✓ Resolved `{seg_id.strip()}` → **{resolved_dim}**"
+ raise gr.Error(f"Could not resolve: {e}") from e
+ gr.Info(f"Resolved {seg_id.strip()} → {resolved}")
+ return state, f"✓ `{seg_id.strip()}` → **{resolved}**"
def fn_discard(seg_id: str, note: str, state: dict):
if not seg_id.strip():
- raise gr.Error("Enter the segment ID to discard.")
- d = _session_dir(state)
+ raise gr.Error("Enter the segment ID.")
try:
discard_disagreement(
- report_path=d / "kappa_report.json",
- segment_id=seg_id.strip(),
- discard_note=note.strip(),
+ report_path=_session_dir(state) / "kappa_report.json",
+ segment_id=seg_id.strip(), discard_note=note.strip(),
)
except Exception as e:
raise gr.Error(f"Could not discard: {e}") from e
@@ -1252,282 +1383,408 @@ def fn_discard(seg_id: str, note: str, state: dict):
return state, f"Discarded `{seg_id.strip()}`"
-# ── Rule review tab ───────────────────────────────────────────────────────
+# ── Rules ─────────────────────────────────────────────────────────────────────
def fn_load_rules():
- try:
- pending = list_pending_rules()
- except Exception as e:
- raise gr.Error(f"Could not load rules: {e}") from e
+ pending = list_pending_rules()
choices = [f"{r['rule_id']}: {r['description'][:55]}…" for r in pending]
return _rules_html(pending), choices
-def fn_approve_rule(choice: str, researcher_id: str, note: str):
+def fn_approve(choice: str, researcher: str, note: str):
if not choice:
- raise gr.Error("Select a rule to approve.")
- if not researcher_id.strip():
- raise gr.Error("Enter your researcher ID.")
- rule_id = choice.split(":")[0].strip()
- try:
- approve_rule(rule_id, researcher_id.strip(), note.strip())
- except Exception as e:
- raise gr.Error(f"Approval failed: {e}") from e
- gr.Info(f"Rule {rule_id} approved — now active for Agent 1b.")
- return f"✓ Rule **{rule_id}** approved by {researcher_id.strip()}."
+ raise gr.Error("Select a rule.")
+ if not researcher.strip():
+ raise gr.Error("Enter your Researcher ID.")
+ rid = choice.split(":")[0].strip()
+ approve_rule(rid, researcher.strip(), note.strip())
+ gr.Info(f"Rule {rid} approved — now active for Agent 1b.")
+ return f"✓ Rule **{rid}** approved."
-def fn_reject_rule(choice: str, researcher_id: str, note: str):
+def fn_reject(choice: str, researcher: str, note: str):
if not choice:
- raise gr.Error("Select a rule to reject.")
- if not researcher_id.strip():
- raise gr.Error("Enter your researcher ID.")
+ raise gr.Error("Select a rule.")
+ if not researcher.strip():
+ raise gr.Error("Enter your Researcher ID.")
if not note.strip():
- raise gr.Error("Provide a rejection reason so Agent 2 can learn from it.")
- rule_id = choice.split(":")[0].strip()
- try:
- reject_rule(rule_id, researcher_id.strip(), note.strip())
- except Exception as e:
- raise gr.Error(f"Rejection failed: {e}") from e
- gr.Info(f"Rule {rule_id} rejected.")
- return f"✗ Rule **{rule_id}** rejected."
+ raise gr.Error("Provide a rejection reason — Agent 2 learns from it.")
+ rid = choice.split(":")[0].strip()
+ reject_rule(rid, researcher.strip(), note.strip())
+ gr.Info(f"Rule {rid} rejected.")
+ return f"✗ Rule **{rid}** rejected."
+
+
+# ===========================================================================
+# EXTRA CSS
+# ===========================================================================
+
+EXTRA_CSS = """
+.gradio-container { max-width: 1200px !important; margin: 0 auto !important; }
+footer { display: none !important; }
+.info-sidebar { font-size: 0.83em; }
+.info-sidebar h4 { font-size: 0.95em; color: #1e293b; margin: 0 0 8px; }
+/* Gradio tab styling */
+.tab-nav { border-bottom: 2px solid #e2e8f0 !important; }
+.tab-nav button { font-weight: 600 !important; font-size: 0.88em !important; }
+.tab-nav button.selected { color: #4338ca !important; border-bottom-color: #4338ca !important; }
+/* Focus rings */
+:focus-visible { outline: 2px solid #4338ca; outline-offset: 2px; }
+:focus { outline: none; }
+/* Gradio primary button */
+.gradio-container button.primary {
+ background: #4338ca !important; border-color: #4338ca !important;
+}
+.gradio-container button.primary:hover {
+ background: #3730a3 !important; border-color: #3730a3 !important;
+}
+"""
# ===========================================================================
-# UI DEFINITION
+# UI
# ===========================================================================
+CSS = _load_css() + EXTRA_CSS
+
with gr.Blocks(title="CollabCode", css=CSS, theme=gr.themes.Soft()) as demo:
state = gr.State(_empty_state())
- # ── Header ───────────────────────────────────────────────────────────
+ # ── App header ────────────────────────────────────────────────────────
gr.HTML(
- '
'
- '
'
- 'CollabCode
'
- '
'
+ '
'
+ '
'
+ '
CollabCode
'
+ '
'
'Human-in-the-loop pipeline for collaborative learning transcript analysis'
- '
'
+ ''
+ '
'
+ '
'
+ f'Model: {MODEL_ID.split("/")[-1]}'
+ f'
Temperature: {TEMPERATURE}'
+ '
'
+ '
'
)
- # ── Pipeline progress stepper (dynamic) ──────────────────────────────
+ # ── Pipeline stepper (always visible) ────────────────────────────────
pipeline_html = gr.HTML(_pipeline_html("upload"))
+ # ── Agent activity log (shared across all tabs) ───────────────────────
+ agent_log_html = gr.HTML(_agent_log_html([]))
+
with gr.Tabs():
# ==================================================================
- # TAB 1: Pipeline
+ # TAB 1 — Research Pipeline
# ==================================================================
- with gr.Tab("Pipeline"):
-
- # Stage 1: Upload & Parse
- with gr.Group():
- gr.Markdown("### Step 1 — Upload Transcript")
- with gr.Row(equal_height=True):
- transcript_file = gr.File(
- label="Transcript file (.txt / .vtt)",
- file_types=[".txt", ".vtt"],
- scale=2,
- )
- with gr.Column(scale=1):
- session_id_box = gr.Textbox(label="Session ID", placeholder="e.g. dyad_01")
- researcher_id_box = gr.Textbox(label="Researcher ID", placeholder="e.g. R1")
- parse_btn = gr.Button("Parse Transcript →", variant="primary")
- parse_status = gr.Markdown(visible=False)
-
- # Stage 2: Detect sections
- with gr.Column(visible=False) as col_agent0:
- gr.HTML('
')
- gr.Markdown("### Step 2 — Detect Topical Sections (Agent 0)")
- gr.Markdown(
- "Agent 0 segments the transcript into activity phases — not behavioral codes. "
- "You will review and rename sections before coding begins. "
- "*(Hearst 1997; Purver et al. 2006)*"
- )
- agent0_btn = gr.Button("Detect Sections →", variant="primary")
- agent0_status = gr.Markdown()
-
- # Stage 2b: Section review
- with gr.Column(visible=False) as col_sections:
- gr.HTML('
')
- gr.Markdown("### Step 2b — Review Sections")
- sections_display_md = gr.Markdown()
- with gr.Accordion("Edit section labels", open=True):
- gr.Markdown(
- "One label per line. Turn boundaries stay as proposed. "
- "To remove a section, delete its label — remaining labels "
- "will map to sections in order."
- )
- sections_labels_box = gr.Textbox(lines=8, show_label=False)
- confirm_sections_btn = gr.Button("Confirm Sections →", variant="primary")
-
- # Stage 3: Per-section pipeline
- with gr.Column(visible=False) as col_section_work:
- gr.HTML('
')
- gr.Markdown("### Step 3 — Section-by-Section Coding")
- sections_overview_html = gr.HTML()
- section_header_md = gr.Markdown()
-
- # 3a: Propose boundaries
- with gr.Column() as col_boundary_btn:
- propose_btn = gr.Button(
- "Detect Episode Boundaries (Agent 1a) →", variant="primary"
- )
- boundary_status = gr.Markdown()
-
- # 3b: Boundary review + confirm
- with gr.Column(visible=False) as col_boundary_review:
- gr.HTML('
'
- '')
- boundary_display_html = gr.HTML()
- gr.HTML('
')
- with gr.Row():
- with gr.Column(scale=3):
- boundary_ids_box = gr.Textbox(
- label="Boundary turn IDs — comma-separated turns after which a new episode begins",
- placeholder="e.g. 12, 28, 35 (leave empty for one episode)",
- lines=1,
+ with gr.Tab("Research Pipeline"):
+
+ with gr.Row(equal_height=False):
+
+ # ── Main content (4/5) ────────────────────────────────────
+ with gr.Column(scale=4):
+
+ # Step 1: Upload & Parse
+ with gr.Group():
+ gr.Markdown("### Step 1 — Upload Transcript")
+ gr.Markdown(
+ "Upload your Zoom `.txt` or `.vtt` transcript. "
+ "Both researchers should run the full pipeline "
+ "independently on the **same** transcript file.",
+ elem_id="parse-help",
+ )
+ with gr.Row(equal_height=True):
+ transcript_file = gr.File(
+ label="Transcript (.txt / .vtt)", file_types=[".txt", ".vtt"], scale=2
)
- with gr.Column(scale=1):
- confirm_boundaries_btn = gr.Button(
- "Confirm & Code (Agent 1b) →", variant="primary"
- )
- code_status = gr.Markdown()
-
- # 3c: Segment coding
- with gr.Column(visible=False) as col_coding:
- coding_progress_html_comp = gr.HTML()
- segment_jump = gr.Dropdown(
- label="Jump to segment", choices=[], value=None,
- interactive=True, scale=1,
- )
- with gr.Row(equal_height=False):
- # Left: turns display
- with gr.Column(scale=3):
- uncertainty_html_comp = gr.HTML()
- turns_display_md = gr.Markdown(
- label="Transcript segment", show_label=True
- )
- proposal_md_comp = gr.Markdown(visible=False)
-
- # Right: coding controls
- with gr.Column(scale=2):
- gr.Markdown("#### Your coding")
- dim_radio = gr.Radio(
- choices=DIM_CHOICES, label="Dimension",
- value=None, interactive=True,
+ with gr.Column(scale=1):
+ session_id_box = gr.Textbox(label="Session ID", placeholder="e.g. dyad_01")
+ researcher_id_box = gr.Textbox(label="Researcher ID", placeholder="e.g. R1")
+ parse_btn = gr.Button("Parse Transcript →", variant="primary")
+ parse_status = gr.Markdown(visible=False)
+
+ # Step 2: Detect Sections
+ with gr.Column(visible=False) as col_agent0:
+ gr.HTML('
')
+ gr.Markdown("### Step 2 — Detect Topical Sections (Agent 0)")
+ gr.Markdown(
+ "Agent 0 segments the transcript into **activity phases** using "
+ "lexical cohesion signals *(Hearst 1997; Purver et al. 2006)*. "
+ "You will review and rename sections before any coding begins."
+ )
+ agent0_btn = gr.Button("Detect Sections →", variant="primary")
+ agent0_status = gr.Markdown()
+
+ # Step 2b: Review sections
+ with gr.Column(visible=False) as col_sections:
+ gr.HTML('
')
+ gr.Markdown("### Step 2b — Review Sections")
+ sections_display_md = gr.Markdown()
+ with gr.Accordion("Edit section labels (one per line)", open=True):
+ gr.Markdown(
+ "Edit labels to match your theoretical framing. "
+ "**Turn boundaries are fixed** — to merge sections, "
+ "delete the label line and adjust manually."
)
- dim_desc_html_comp = gr.HTML()
- comment_box = gr.Textbox(
- label="Comment (optional)", lines=2, placeholder="Notes for disagreement review…"
+ sections_labels_box = gr.Textbox(lines=8, show_label=False)
+ confirm_sections_btn = gr.Button("Confirm Sections →", variant="primary")
+
+ # Step 3: Per-section coding
+ with gr.Column(visible=False) as col_section_work:
+ gr.HTML('
')
+ gr.Markdown("### Step 3 — Section-by-Section Coding")
+ sections_overview_html = gr.HTML()
+ section_header_md = gr.Markdown()
+
+ # 3a: Boundary detection
+ with gr.Column() as col_boundary_btn:
+ propose_btn = gr.Button(
+ "Detect Episode Boundaries (Agent 1a) →", variant="primary"
)
- reveal_btn = gr.Button(
- "Reveal AI proposal", variant="secondary", size="sm"
+ boundary_status = gr.Markdown()
+
+ # 3b: Boundary review
+ with gr.Column(visible=False) as col_boundary_review:
+ gr.HTML(
+ '
'
+ '
Episode Structure
'
)
+ boundary_display_html = gr.HTML()
+ gr.HTML('
')
gr.Markdown(
- '
'
- 'AI proposal hidden by default — code independently first '
- '(Settles 2012)'
+ "**Review boundaries above.** Edit the turn IDs below "
+ "to adjust, add, or remove boundaries. "
+ "Leave empty for a single undivided episode."
)
with gr.Row():
- prev_btn = gr.Button("← Previous", size="sm")
- next_btn = gr.Button("Next →", variant="primary", size="sm")
- next_section_btn = gr.Button(
- "→ Finish Section & Continue", variant="secondary", visible=False
- )
+ boundary_ids_box = gr.Textbox(
+ label="Boundary turn IDs (comma-separated) — the turn after which each new episode begins",
+ placeholder="e.g. 12, 28, 35",
+ lines=1, scale=3,
+ )
+ confirm_boundaries_btn = gr.Button(
+ "Confirm & Code (Agent 1b) →",
+ variant="primary", scale=1,
+ )
+ code_status = gr.Markdown()
+
+ # 3c: Coding interface
+ with gr.Column(visible=False) as col_coding:
+ coding_progress_comp = gr.HTML()
+ segment_jump = gr.Dropdown(
+ label="Jump to segment", choices=[], value=None, interactive=True
+ )
+ with gr.Row(equal_height=False):
+ # Left: transcript
+ with gr.Column(scale=3):
+ uncertainty_comp = gr.HTML()
+ turns_html_comp = gr.HTML(
+ label="Transcript", show_label=True
+ )
+ proposal_comp = gr.Markdown(visible=False)
+ reveal_btn = gr.Button(
+ "Reveal AI proposal", variant="secondary", size="sm"
+ )
+ gr.HTML(
+ '
'
+ 'AI proposal hidden by default — code independently first '
+ '(Settles 2012 — uncertainty sampling)
'
+ )
+
+ # Right: coding controls
+ with gr.Column(scale=2):
+ gr.Markdown("#### Your Coding")
+ dim_radio = gr.Radio(
+ choices=DIM_CHOICES, label="Dimension", value=None
+ )
+ dim_desc_comp = gr.HTML()
+ comment_box = gr.Textbox(
+ label="Comment (optional)", lines=2,
+ placeholder="Note any ambiguity for the disagreement review…"
+ )
+ with gr.Row():
+ prev_btn = gr.Button("← Previous", size="sm")
+ next_btn = gr.Button("Next →", variant="primary", size="sm")
+
+ next_section_btn = gr.Button(
+ "→ Finish Section & Continue", variant="secondary", visible=False
+ )
- # Stage 4: Complete
- with gr.Column(visible=False) as col_complete:
- gr.HTML(
- '
'
- 'All sections coded! Download your file and share it '
- 'with your co-researcher for agreement calculation.'
- '
'
- )
- download_btn = gr.Button("Download Coding File", variant="primary")
- download_file = gr.File(visible=False)
+ # Step 4: Complete
+ with gr.Column(visible=False) as col_complete:
+ gr.HTML(
+ '
'
+ '
All sections coded ✓
'
+ '
Download your coding file and share it '
+ 'with your co-researcher. They should complete the same pipeline '
+ 'independently, then both files go to the '
+ 'Inter-Rater Agreement tab.
'
+ '
'
+ )
+ download_btn = gr.Button("Download My Coding File", variant="primary")
+ download_file = gr.File(visible=False)
+
+ # ── Info sidebar (1/5) ────────────────────────────────────
+ with gr.Column(scale=1, min_width=200):
+ with gr.Accordion("Research Basis", open=True):
+ pipeline_info = gr.HTML(RESEARCH_INFO["parse"])
+
+ with gr.Accordion("Agent Activity Log", open=True):
+ gr.Markdown(
+ '
'
+ f'Model: {MODEL_ID.split("/")[-1]} · '
+ f'Temperature: {TEMPERATURE}'
+ )
+ sidebar_log = gr.HTML(_agent_log_html([]))
# ==================================================================
- # TAB 2: Agreement & Kappa
+ # TAB 2 — Inter-Rater Agreement
# ==================================================================
- with gr.Tab("Agreement & Kappa"):
- gr.Markdown(
- "## Inter-Rater Agreement\n"
- "Upload your co-researcher's completed `coding_RX.json`. "
- "The system calculates Cohen's κ — gate is **κ ≥ 0.70** "
- "*(Landis & Koch 1977; Bujang & Baharum 2017)*."
- )
- with gr.Row():
- r2_upload = gr.File(
- label="Co-researcher coding (.json)", file_types=[".json"], scale=2
- )
- kappa_btn = gr.Button("Calculate Kappa", variant="primary", scale=1)
-
- kappa_html_comp = gr.HTML()
- disagreements_md = gr.Markdown()
-
- with gr.Column(visible=False) as col_disagreements:
- gr.HTML('
Resolve each disagreement below. '
- 'Resolved segments go to Tier 3 for Agent 2 to learn from.
')
- with gr.Row():
- dis_seg_id = gr.Textbox(label="Segment ID", placeholder="e.g. dyad_01_s01_ep03", scale=2)
- dis_dim = gr.Dropdown(label="Resolved dimension", choices=DIM_CHOICES, scale=2)
- dis_note = gr.Textbox(
- label="Resolution note — explain why this dimension was chosen",
- lines=2, placeholder="Both researchers agreed after discussion that…"
- )
- with gr.Row():
- resolve_btn = gr.Button("Resolve", variant="primary")
- discard_btn = gr.Button("Discard segment", variant="secondary")
- dis_status = gr.Markdown()
+ with gr.Tab("Inter-Rater Agreement"):
+ with gr.Row(equal_height=False):
+ with gr.Column(scale=4):
+
+ # How it works
+ gr.HTML(
+ '
'
+ '
How dual-coding works
'
+ '
'
+ '- You complete the Pipeline tab → download
coding_R1.json '
+ '- Your co-researcher runs the same Pipeline independently on the same transcript → downloads
coding_R2.json '
+ '- Both files are uploaded here to calculate Cohen\'s κ
'
+ '- Gate: κ ≥ 0.70 to proceed *(Landis & Koch 1977)*
'
+ '- Remaining disagreements are resolved below → feed Agent 2\'s learning
'
+ '
'
+ '
'
+ )
+
+ gr.Markdown("### Upload Co-Researcher Coding")
+ with gr.Row():
+ r2_upload = gr.File(
+ label="Co-researcher coding file (.json)", file_types=[".json"], scale=2
+ )
+ kappa_btn = gr.Button("Calculate κ", variant="primary", scale=1)
+
+ kappa_html_comp = gr.HTML()
+ disagreements_md = gr.Markdown()
+
+ with gr.Column(visible=False) as col_disagreements:
+ gr.HTML(
+ '
'
+ '
Disagreement Resolution'
+ '
For each disagreement: '
+ 'enter the segment ID, select the consensus dimension, and add a '
+ 'note explaining your decision. Resolved segments become training '
+ 'data for Agent 2.
'
+ '
'
+ )
+ with gr.Row():
+ dis_seg_id = gr.Textbox(
+ label="Segment ID", placeholder="e.g. dyad_01_s01_ep03", scale=2
+ )
+ dis_dim = gr.Dropdown(
+ label="Resolved dimension", choices=DIM_CHOICES, scale=2
+ )
+ dis_note = gr.Textbox(
+ label="Resolution note — why this dimension?",
+ lines=2,
+ placeholder="After discussion we agreed that… because…"
+ )
+ with gr.Row():
+ resolve_btn = gr.Button("Resolve ✓", variant="primary")
+ discard_btn = gr.Button("Discard segment", variant="secondary")
+ dis_status = gr.Markdown()
+
+ with gr.Column(scale=1, min_width=200):
+ with gr.Accordion("Research Basis", open=True):
+ gr.HTML(RESEARCH_INFO["agreement"])
+ with gr.Accordion("Agent Activity Log", open=False):
+ kappa_log = gr.HTML(_agent_log_html([]))
# ==================================================================
- # TAB 3: Rule Review
+ # TAB 3 — AI Learning Review
# ==================================================================
- with gr.Tab("Rule Review"):
- gr.Markdown(
- "## Agent 2 Rule Proposals\n"
- "Rules proposed by Agent 2 from researcher corrections. "
- "**Inactive until approved here.** "
- "Once approved, they become part of Agent 1b's coding guidelines "
- "and are versioned in Tier 2. *(Settles 2012 — active learning update loop)*"
- )
- load_rules_btn = gr.Button("Load Pending Rules", variant="primary")
- rules_html_comp = gr.HTML()
- with gr.Group():
- gr.Markdown("#### Approve or Reject a Rule")
- rule_selector = gr.Dropdown(label="Select rule", choices=[])
- rule_researcher_id = gr.Textbox(
- label="Your Researcher ID", placeholder="e.g. R1"
- )
- rule_note = gr.Textbox(
- label="Approval note / Rejection reason",
- lines=2,
- placeholder="This rule is consistent with sessions 3 and 4…",
- )
- with gr.Row():
- reject_rule_btn = gr.Button("Reject ✗", variant="secondary")
- approve_rule_btn = gr.Button("Approve ✓", variant="primary")
- rule_status = gr.Markdown()
+ with gr.Tab("AI Learning Review"):
+ with gr.Row(equal_height=False):
+ with gr.Column(scale=4):
+
+ gr.HTML(
+ '
'
+ '
How the learning loop works
'
+ '
'
+ '- You and your co-researcher resolve disagreements in the Agreement tab
'
+ '- Agent 2 analyses patterns across resolved disagreements
'
+ '- Agent 2 proposes boundary clarifications, disambiguation rules, '
+ 'or marker refinements
'
+ '- You review and approve/reject each rule — rules are '
+ 'inactive until approved
'
+ '- Approved rules are added to Tier 2 and immediately affect '
+ 'Agent 1b\'s coding in future sessions
'
+ '
'
+ '
'
+ '⚠ Agent 2 requires at least 3 validated sessions and 90 segments '
+ 'before proposing rules *(Bujang & Baharum 2017 — power analysis)*.
'
+ '
'
+ )
+
+ load_rules_btn = gr.Button("Load Pending Rules", variant="primary")
+ rules_html_comp = gr.HTML()
+
+ with gr.Group():
+ gr.Markdown("#### Approve or Reject a Rule")
+ gr.Markdown(
+ "Select a rule, enter your ID, and provide a note. "
+ "Rejection reasons are logged — Agent 2 learns from them on the next cycle."
+ )
+ rule_selector = gr.Dropdown(label="Select rule", choices=[])
+ rule_rid = gr.Textbox(label="Researcher ID", placeholder="e.g. R1")
+ rule_note = gr.Textbox(
+ label="Note (required for rejection, optional for approval)",
+ lines=2,
+ placeholder="This rule is consistent with sessions 3–5 because…"
+ )
+ with gr.Row():
+ reject_rule_btn = gr.Button("Reject ✗", variant="secondary")
+ approve_rule_btn = gr.Button("Approve ✓", variant="primary")
+ rule_status = gr.Markdown()
+
+ with gr.Column(scale=1, min_width=200):
+ with gr.Accordion("Research Basis", open=True):
+ gr.HTML(RESEARCH_INFO["rules"])
+ with gr.Accordion("What Agent 2 can write", open=False):
+ gr.Markdown(
+ "**Boundary clarification** — where episode boundaries fall \n"
+ "**Disambiguation rule** — how to distinguish two similar dimensions \n"
+ "**Marker refinement** — context-specific sharpening of a behavioral marker \n\n"
+ "Agent 2 **cannot** redefine a dimension's core meaning or contradict Tier 1."
+ )
# =====================================================================
# OUTPUT LISTS
# =====================================================================
CODING_OUTPUTS = [
- coding_progress_html_comp,
+ coding_progress_comp,
segment_jump,
- turns_display_md,
- uncertainty_html_comp,
- proposal_md_comp,
+ turns_html_comp,
+ uncertainty_comp,
+ proposal_comp,
dim_radio,
- dim_desc_html_comp,
+ dim_desc_comp,
comment_box,
next_section_btn,
]
- NEXT_SECTION_OUTPUTS = [
+ NEXT_SECTION_OUTS = [
state,
pipeline_html,
sections_overview_html,
@@ -1545,93 +1802,82 @@ with gr.Blocks(title="CollabCode", css=CSS, theme=gr.themes.Soft()) as demo:
parse_btn.click(
fn=fn_parse,
inputs=[transcript_file, session_id_box, researcher_id_box, state],
- outputs=[state, pipeline_html, parse_status, col_agent0],
+ outputs=[state, pipeline_html, parse_status, col_agent0, sidebar_log],
).then(fn=lambda: gr.update(visible=True), outputs=[parse_status])
+ # Update info sidebar to sections step after parse
+ parse_btn.click(
+ fn=lambda: RESEARCH_INFO["parse"],
+ outputs=[pipeline_info],
+ )
+
agent0_btn.click(
fn=fn_run_agent0,
inputs=[state],
- outputs=[state, pipeline_html, col_sections, sections_display_md, sections_labels_box],
- )
+ outputs=[state, pipeline_html, col_sections, sections_display_md,
+ sections_labels_box, sidebar_log],
+ ).then(fn=lambda: RESEARCH_INFO["sections"], outputs=[pipeline_info])
confirm_sections_btn.click(
fn=fn_confirm_sections,
inputs=[sections_labels_box, state],
- outputs=[
- state, pipeline_html, sections_overview_html,
- section_header_md, col_section_work,
- col_boundary_btn, col_boundary_review, col_coding,
- ],
- )
+ outputs=[state, pipeline_html, sections_overview_html,
+ section_header_md, col_section_work,
+ col_boundary_btn, col_boundary_review, col_coding],
+ ).then(fn=lambda: RESEARCH_INFO["boundaries"], outputs=[pipeline_info])
propose_btn.click(
fn=fn_propose_boundaries,
inputs=[state],
outputs=[state, boundary_status, col_boundary_review,
- boundary_display_html, boundary_ids_box],
+ boundary_display_html, boundary_ids_box, sidebar_log],
)
confirm_boundaries_btn.click(
fn=fn_confirm_and_code,
inputs=[boundary_ids_box, state],
- outputs=[state, code_status, col_coding] + CODING_OUTPUTS,
- )
+ outputs=[state, code_status, col_coding] + CODING_OUTPUTS + [sidebar_log],
+ ).then(fn=lambda: RESEARCH_INFO["coding"], outputs=[pipeline_info])
next_btn.click(
fn=lambda d, c, s: fn_navigate(+1, d, c, s),
inputs=[dim_radio, comment_box, state],
outputs=[state] + CODING_OUTPUTS,
)
-
prev_btn.click(
fn=lambda d, c, s: fn_navigate(-1, d, c, s),
inputs=[dim_radio, comment_box, state],
outputs=[state] + CODING_OUTPUTS,
)
-
segment_jump.change(
- fn=fn_jump_to_segment,
+ fn=fn_jump,
inputs=[segment_jump, state],
outputs=[state] + CODING_OUTPUTS,
)
-
- reveal_btn.click(
- fn=fn_reveal_proposal,
- inputs=[state],
- outputs=[proposal_md_comp],
- )
-
- dim_radio.change(
- fn=fn_update_dim_desc,
- inputs=[dim_radio],
- outputs=[dim_desc_html_comp],
- )
+ reveal_btn.click(fn=fn_reveal, inputs=[state], outputs=[proposal_comp])
+ dim_radio.change(fn=fn_dim_desc, inputs=[dim_radio], outputs=[dim_desc_comp])
next_section_btn.click(
fn=fn_next_section,
inputs=[dim_radio, comment_box, state],
- outputs=NEXT_SECTION_OUTPUTS,
+ outputs=NEXT_SECTION_OUTS,
)
- download_btn.click(
- fn=fn_download,
- inputs=[state],
- outputs=[download_file],
- ).then(fn=lambda: gr.update(visible=True), outputs=[download_file])
+ download_btn.click(fn=fn_download, inputs=[state], outputs=[download_file]).then(
+ fn=lambda: gr.update(visible=True), outputs=[download_file]
+ )
# Agreement tab
kappa_btn.click(
fn=fn_calculate_kappa,
inputs=[r2_upload, state],
- outputs=[state, kappa_html_comp, disagreements_md, col_disagreements],
+ outputs=[state, kappa_html_comp, disagreements_md, col_disagreements, kappa_log],
)
-
resolve_btn.click(
fn=fn_resolve,
inputs=[dis_seg_id, dis_dim, dis_note, state],
outputs=[state, dis_status],
)
-
discard_btn.click(
fn=fn_discard,
inputs=[dis_seg_id, dis_note, state],
@@ -1639,21 +1885,12 @@ with gr.Blocks(title="CollabCode", css=CSS, theme=gr.themes.Soft()) as demo:
)
# Rule review tab
- load_rules_btn.click(
- fn=fn_load_rules,
- outputs=[rules_html_comp, rule_selector],
- )
-
+ load_rules_btn.click(fn=fn_load_rules, outputs=[rules_html_comp, rule_selector])
approve_rule_btn.click(
- fn=fn_approve_rule,
- inputs=[rule_selector, rule_researcher_id, rule_note],
- outputs=[rule_status],
+ fn=fn_approve, inputs=[rule_selector, rule_rid, rule_note], outputs=[rule_status]
)
-
reject_rule_btn.click(
- fn=fn_reject_rule,
- inputs=[rule_selector, rule_researcher_id, rule_note],
- outputs=[rule_status],
+ fn=fn_reject, inputs=[rule_selector, rule_rid, rule_note], outputs=[rule_status]
)