Lara Monteagudo Tubau commited on
Commit ·
5b5a20d
0
Parent(s):
Prepare Script app for Hugging Face Space
Browse filesFiles changed (25)
- .gitignoreAdded+13
- .hfignoreAdded+8
- README.mdAdded+27
- agent0_sectioner.pyAdded+273
- agent1_segmenter.pyAdded+401
- agent1a_boundary.pyAdded+275
- agent1b_coder.pyAdded+317
- agent2_learner.pyAdded+783
- app.pyAdded+1621
- coding_rules.jsonAdded+49
- dimensions.jsonAdded+149
- examples.jsonAdded+36
- kappa_calculator.pyAdded+569
- learned_rules.jsonAdded+9
- library/tier1_core/coding_rules.jsonAdded+49
- library/tier1_core/dimensions.jsonAdded+149
- library/tier1_core/examples.jsonAdded+36
- library/tier2_validated/edge_cases.jsonAdded+7
- library/tier2_validated/learned_rules.jsonAdded+9
- library/tier3_candidate/pending_review.jsonAdded+9
- llm_client.pyAdded+58
- orchestrator.pyAdded+666
- pending_review.jsonAdded+9
- requirements.txtAdded+2
- transcript_parser.pyAdded+310
12345678910111213.venv/__pycache__/*.pyc.DS_Store.claude/
# local / transient artifactsparsed_transcript.json*.log
# optional large local transcriptsmeeting_saved_closed_caption*.txtresearcher_ui (1).html12345678.venv/__pycache__/*.pyc*.pyosessions//tmp/.DS_Storemeeting_saved_closed_caption-groupchat1647.txt123456789101112131415161718192021222324252627---title: CollabCodeemoji: 🔬colorFrom: bluecolorTo: indigosdk: gradiosdk_version: "6.13.0"app_file: app.pypinned: false---
# CollabCode — Researcher Coding Interface
A multi-agent pipeline for analyzing collaborative learning in Zoom transcripts.
## Researcher workflow
1. Run the orchestrator locally to generate a `coding_template_RX.json`2. Upload it here, enter your researcher ID, and click **Load**3. Step through each segment, select a dimension (D1–D9), add an optional comment4. Download your completed `coding_RX.json` when all segments are coded
## Environment variables (for the pipeline backend)
| Variable | Purpose ||---|---|| `HF_TOKEN` | Hugging Face token — used by Agent 1 and Agent 2 to call Mistral Large |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273"""agent0_sectioner.py-------------------Agent 0: The Structural Segmenter.
Identifies topical sections / activity phases in a Zoom transcript BEFOREany behavioral coding takes place. This mirrors how experienced qualitativecoders orient to data: macro-structure first, micro-coding second.
Theoretical basis-----------------Human annotation practice — unitising precedes categorising: Krippendorff, K. (2004). Content analysis: An introduction to its methodology (2nd ed., ch. 7). Sage.
Topic/phase segmentation in spoken discourse: Hearst, M. A. (1997). TextTiling: Segmenting text into multi-paragraph subtopic passages. Computational Linguistics, 23(1), 33–64.
Purver, M., Körding, K., Griffiths, T., & Tenenbaum, J. (2006). Unsupervised topic modelling for multi-party spoken discourse. Proceedings of COLING-ACL, 17–24.
Galley, M., McKeown, K., Hirschberg, J., & Shriberg, E. (2003). Identifying agreement and disagreement in conversational speech. Proceedings of ACL.
Activity phases in collaborative work: Stahl, G. (2006). Group cognition: Computer support for building collaborative knowledge. MIT Press.
Roschelle, J., & Teasley, S. D. (1995). The construction of shared knowledge in collaborative problem solving. In C. O'Malley (Ed.), Computer-supported collaborative learning. Springer.
Cognitive load / working memory rationale for section size: Sweller, J. (1988). Cognitive load during problem solving: Effects on learning. Cognitive Science, 12(2), 257–285. — Analysts hold 15–50 turns comfortably before cognitive overload degrades annotation reliability.
Design rationale----------------Agent 0 runs ONCE per transcript as the first automated step. The researcherMUST confirm (or edit) sections before Agent 1a processes any section.This human checkpoint prevents the "hour-long transcript overload" problemby decomposing the session into reviewable units that match naturalconversational structure — not arbitrary character counts.
Agent 0 does NOT assign dimension codes. It only identifies where coherentactivity phases begin and end."""
import jsonfrom pathlib import Pathfrom typing import Optional
from llm_client import call_llm
LIBRARY_ROOT = Path(__file__).parent / "library"TIER1_PATH = LIBRARY_ROOT / "tier1_core"
MAX_TOKENS = 2000
# Target section size — mirrors human working memory limits for discourse# analysis. Analysts reliably process 15-50 turns per coding pass.# (Sweller 1988; Krippendorff 2004 ch.7)TARGET_TURNS_PER_SECTION = 30MIN_TURNS_PER_SECTION = 10
# ---------------------------------------------------------------------------# Library loader# ---------------------------------------------------------------------------
def load_dimension_labels() -> list[dict]: """Load dimension IDs and labels as naming hints for sections.""" dims = json.loads((TIER1_PATH / "dimensions.json").read_text()) return [{"id": d["id"], "label": d["label"]} for d in dims["dimensions"]]
# ---------------------------------------------------------------------------# Formatters# ---------------------------------------------------------------------------
def _format_turns_compact(turns: list[dict]) -> str: """Compact format: turn_id, time, speaker: text (truncated for long turns).""" lines = [] for t in turns: text = t["text"][:120] + "…" if len(t["text"]) > 120 else t["text"] lines.append(f"[{t['turn_id']:>4}] {t['start_time']} {t['speaker']}: {text}") return "\n".join(lines)
# ---------------------------------------------------------------------------# Prompt builder# ---------------------------------------------------------------------------
def build_system_prompt(dimension_labels: list[dict]) -> str: dim_hint = ", ".join(f"{d['id']} ({d['label']})" for d in dimension_labels) return f"""You are a discourse analyst specialising in computer-supported collaborative learning.Your task is to segment a Zoom transcript into coherent topical sections —natural activity phases where the dyad is engaged in a common focus.
This is STRUCTURAL segmentation, NOT behavioral coding.You are identifying where one activity phase ends and another begins.
Boundary signals to look for (Hearst 1997; Purver et al. 2006): - Explicit transition markers: "OK let's move on", "now we need to", "right so..." - Changes in the primary task (planning → implementation, coding → testing) - Shifts in who is driving vs. supporting - Topic exhaustion followed by a new initiation - Breaks and re-orientation turns
Each section must: - Be large enough to contain multiple behavioral episodes (≥ {MIN_TURNS_PER_SECTION} turns) - Have a descriptive activity label (e.g. "Task Orientation", "Collaborative Coding", "Debugging Session", "Review and Reflection", "Planning Next Steps") - Have a 1–2 sentence summary of what the dyad is doing in that phase
Dimension framework hint (for label context only — do not assign codes):{dim_hint}
Output ONLY valid JSON — no preamble, no explanation outside the JSON:{{ "sections": [ {{ "section_id": "s01", "label": "activity label", "summary": "1–2 sentence description of the dyad's activity in this phase", "start_turn_id": 0, "end_turn_id": 45, "start_time": "HH:MM:SS", "end_time": "HH:MM:SS" }} ], "session_overview": "2–3 sentence summary of the full session arc"}}
The sections must be contiguous and cover every turn in the transcript.Aim for 3–8 sections of roughly equal size."""
def build_user_prompt(turns: list[dict]) -> str: return f"""Please segment the following transcript into topical sections.{len(turns)} turns total (turn IDs {turns[0]['turn_id']} – {turns[-1]['turn_id']}).
=== TRANSCRIPT ==={_format_turns_compact(turns)}
Identify 3–8 sections that reflect the natural activity phases of this session."""
# ---------------------------------------------------------------------------# Response parser and validator# ---------------------------------------------------------------------------
def _parse_response(raw: str) -> dict: cleaned = raw.strip() if cleaned.startswith("```"): cleaned = "\n".join(cleaned.split("\n")[1:]) if cleaned.endswith("```"): cleaned = "\n".join(cleaned.split("\n")[:-1]) cleaned = cleaned.strip() try: return json.loads(cleaned) except json.JSONDecodeError as e: raise ValueError( f"Agent 0 returned invalid JSON.\nError: {e}\nRaw:\n{raw}" ) from e
def _validate_sections(sections: list[dict], turns: list[dict]) -> list[str]: """Check sections are contiguous and cover all turns.""" errors = [] if not sections: errors.append("No sections returned.") return errors
all_turn_ids = {t["turn_id"] for t in turns} covered: set[int] = set()
for s in sections: start = s.get("start_turn_id") end = s.get("end_turn_id") if start is None or end is None: errors.append(f"Section {s.get('section_id')} missing turn range.") continue section_range = set(range(start, end + 1)) overlap = covered & section_range if overlap: errors.append( f"Section {s.get('section_id')} overlaps prior sections " f"at turns {sorted(overlap)[:5]}" ) covered.update(section_range)
missing = all_turn_ids - covered if missing: errors.append( f"{len(missing)} turns not covered by any section: " f"{sorted(missing)[:10]}" )
return errors
# ---------------------------------------------------------------------------# Public API# ---------------------------------------------------------------------------
def run_sectioning( turns: list[dict], session_id: str, library_root: Optional[Path] = None,) -> dict: """ Segment a full transcript into topical sections.
Args: turns: Full list of parsed turn dicts. session_id: Identifier for this session. library_root: Override library path (for testing).
Returns: Dict with: sections (list), session_overview (str), session_id, warnings (list). """ global LIBRARY_ROOT, TIER1_PATH if library_root: LIBRARY_ROOT = library_root TIER1_PATH = library_root / "tier1_core"
if not turns: raise ValueError("No turns provided.")
print(f"[Agent 0] Segmenting {len(turns)} turns into topical sections...")
dimension_labels = load_dimension_labels() system_prompt = build_system_prompt(dimension_labels) user_prompt = build_user_prompt(turns)
raw = call_llm(system_prompt, user_prompt, max_tokens=MAX_TOKENS) result = _parse_response(raw) sections = result.get("sections", []) overview = result.get("session_overview", "") warnings = _validate_sections(sections, turns)
if warnings: print(f"[Agent 0] Validation warnings: {warnings}")
print(f"[Agent 0] Proposed {len(sections)} sections:") for s in sections: n = s["end_turn_id"] - s["start_turn_id"] + 1 print(f" {s['section_id']}: {s['label']} " f"({n} turns, {s['start_time']}–{s['end_time']})")
return { "session_id": session_id, "sections": sections, "session_overview": overview, "warnings": warnings, }
def save_sections(result: dict, output_path: Path) -> None: output_path.parent.mkdir(parents=True, exist_ok=True) output_path.write_text( json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8", ) print(f"[Agent 0] Sections saved to {output_path}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401"""agent1_segmenter.py-------------------Agent 1: The Segmenter.
Responsibilities:- Load Tier 1 library (dimensions, examples, coding rules)- Load Tier 2 validated learnings (if any exist)- Receive a window of transcript turns- Call the Claude API to segment and code each window- Return structured segments with dimension codes, rationale, confidence, uncertainty flags, and open/closed boundary status- Hand back the open segment start position for the next window
Agent 1 must NEVER read Tier 3 (candidate/quarantined learnings)."""
import jsonfrom pathlib import Pathfrom typing import Optional
from llm_client import call_llm
# ---------------------------------------------------------------------------# Constants# ---------------------------------------------------------------------------
LIBRARY_ROOT = Path(__file__).parent / "library"TIER1_PATH = LIBRARY_ROOT / "tier1_core"TIER2_PATH = LIBRARY_ROOT / "tier2_validated"
MAX_TOKENS = 4000# Single-pass limit: transcripts up to ~200 turns fit comfortably.# Beyond this the model takes too long to generate the full JSON response.SINGLE_PASS_CHAR_LIMIT = 20_000# Chunk size in turns for longer transcriptsCHUNK_TURNS = 150
# ---------------------------------------------------------------------------# Library loader# ---------------------------------------------------------------------------
def load_tier1() -> dict: """Load all Tier 1 files. Raises if any file is missing or malformed.""" dimensions = json.loads((TIER1_PATH / "dimensions.json").read_text()) examples = json.loads((TIER1_PATH / "examples.json").read_text()) coding_rules = json.loads((TIER1_PATH / "coding_rules.json").read_text()) return { "dimensions": dimensions["dimensions"], "examples": examples["examples"], "coding_rules": coding_rules["rules"], }
def load_tier2() -> dict: """Load Tier 2 validated learnings. Returns empty structures if not yet populated.""" learned_rules = json.loads((TIER2_PATH / "learned_rules.json").read_text()) edge_cases = json.loads((TIER2_PATH / "edge_cases.json").read_text()) return { "learned_rules": learned_rules.get("learned_rules", []), "edge_cases": edge_cases.get("edge_cases", []), }
# ---------------------------------------------------------------------------# Prompt builder# ---------------------------------------------------------------------------
def _format_dimensions(dimensions: list[dict]) -> str: lines = [] for d in dimensions: lines.append(f"[{d['id']}] {d['label']}") lines.append(f" Summary: {d['summary']}") lines.append(f" Key behavioral markers:") for marker in d["key_behavioral_markers"]: lines.append(f" - {marker}") lines.append("") return "\n".join(lines)
def _format_examples(examples: list[dict]) -> str: lines = [] for ex in examples: lines.append(f"Dimension: {ex['dimension_id']} ({ex['type'].upper()})") lines.append(f"Label: {ex['label']}") for turn in ex["exchange"]: lines.append(f" {turn['speaker']}: {turn['text']}") lines.append(f"Note: {ex['annotation_note']}") lines.append("") return "\n".join(lines)
def _format_rules(rules: list[dict]) -> str: return "\n".join( f"[{r['rule_id']}] {r['label']}: {r['description']}" for r in rules )
def _format_learned(tier2: dict) -> str: rules = tier2.get("learned_rules", []) cases = tier2.get("edge_cases", []) if not rules and not cases: return "None yet." lines = [] for r in rules: lines.append(f"- LEARNED RULE: {r.get('description', '')}") for c in cases: lines.append(f"- EDGE CASE: {c.get('description', '')}") return "\n".join(lines)
def _format_turns(turns: list[dict]) -> str: lines = [] for t in turns: lines.append( f"[turn_{t['turn_id']}] [{t['start_time']}] {t['speaker']}: {t['text']}" ) return "\n".join(lines)
def build_system_prompt(tier1: dict, tier2: dict) -> str: return f"""You are a behavioral coding assistant trained in collaborative learning research.Your task is to segment a transcript excerpt into episodes and assign each episodea dimension code from a theory-driven coding framework.
You must follow all coding rules exactly. You may not infer beyond what isobservable in the transcript text.
=== DIMENSION DEFINITIONS ==={_format_dimensions(tier1['dimensions'])}
=== ANCHOR EXAMPLES ==={_format_examples(tier1['examples'])}
=== CODING RULES (MANDATORY) ==={_format_rules(tier1['coding_rules'])}
=== VALIDATED LEARNINGS FROM PRIOR CODING SESSIONS ==={_format_learned(tier2)}
=== OUTPUT FORMAT ===You must respond ONLY with a valid JSON object. No preamble, no explanation outside the JSON.
The JSON must follow this exact structure:{{ "segments": [ {{ "segment_id": "string — use format seg_001, seg_002 etc.", "start_turn_id": integer, "end_turn_id": integer, "start_time": "HH:MM:SS", "end_time": "HH:MM:SS", "dimension_id": "D1 to D9", "dimension_label": "string", "boundary_status": "closed or open", "confident": true or false, "uncertain": true or false, "uncertainty_note": "string or null — name competing dimension and why if uncertain", "rationale": "1-2 sentences citing specific observable behaviors from the turns" }} ], "window_summary": {{ "total_turns_processed": integer, "total_segments_found": integer, "last_segment_status": "closed or open", "next_window_start_turn_id": integer or null }}}}
If the last segment is OPEN, set next_window_start_turn_id to the start_turn_idof that open segment. The next window will begin from there.If the last segment is CLOSED, set next_window_start_turn_id to null."""
def build_user_prompt(turns: list[dict]) -> str: return f"""Please segment and code the following transcript excerpt.
=== TRANSCRIPT TURNS ==={_format_turns(turns)}
Remember:- Assign exactly one dimension per segment- Flag uncertainty if two dimensions are competing- Mark the last segment as OPEN if the episode is not behaviorally complete- Base your rationale only on observable turn content"""
# ---------------------------------------------------------------------------# API call# ---------------------------------------------------------------------------
def _call_claude(system_prompt: str, user_prompt: str) -> str: return call_llm(system_prompt, user_prompt, max_tokens=MAX_TOKENS)
# ---------------------------------------------------------------------------# Response parser# ---------------------------------------------------------------------------
def _parse_response(raw: str) -> dict: """ Parse Claude's JSON response. Strips markdown fences if present. Raises ValueError with details if the response is malformed. """ cleaned = raw.strip() if cleaned.startswith("```"): cleaned = "\n".join(cleaned.split("\n")[1:]) if cleaned.endswith("```"): cleaned = "\n".join(cleaned.split("\n")[:-1]) cleaned = cleaned.strip()
try: parsed = json.loads(cleaned) except json.JSONDecodeError as e: raise ValueError( f"Agent 1 returned invalid JSON.\nError: {e}\nRaw response:\n{raw}" ) from e
# Basic validation if "segments" not in parsed: raise ValueError(f"Response missing 'segments' key.\nRaw:\n{raw}") if "window_summary" not in parsed: raise ValueError(f"Response missing 'window_summary' key.\nRaw:\n{raw}")
return parsed
# ---------------------------------------------------------------------------# Public API# ---------------------------------------------------------------------------
def segment_window( turns: list[dict], session_id: str, window_index: int, library_root: Optional[Path] = None,) -> dict: """ Segment a window of transcript turns.
Args: turns: List of turn dicts from transcript_parser.parse_transcript() session_id: Identifier for this transcript/dyad session window_index: Which window this is (0-indexed), used for segment ID namespacing library_root: Override for library path (useful for testing)
Returns: Dict with keys: segments, window_summary, session_id, window_index """ global LIBRARY_ROOT, TIER1_PATH, TIER2_PATH if library_root: LIBRARY_ROOT = library_root TIER1_PATH = library_root / "tier1_core" TIER2_PATH = library_root / "tier2_validated"
if not turns: raise ValueError("No turns provided to segment_window.")
# Load library — Tier 1 always, Tier 2 always, Tier 3 NEVER tier1 = load_tier1() tier2 = load_tier2()
# Build prompts system_prompt = build_system_prompt(tier1, tier2) user_prompt = build_user_prompt(turns)
# Call API raw_response = _call_claude(system_prompt, user_prompt)
# Parse and validate result = _parse_response(raw_response)
# Namespace segment IDs to avoid collisions across windows prefix = f"w{window_index:02d}" for seg in result["segments"]: seg["segment_id"] = f"{session_id}_{prefix}_{seg['segment_id']}"
result["session_id"] = session_id result["window_index"] = window_index
return result
def _call_single_pass( turns: list[dict], session_id: str, chunk_index: int, system_prompt: str,) -> list[dict]: """Send one batch of turns to the LLM and return namespaced segments.""" user_prompt = build_user_prompt(turns) raw = _call_claude(system_prompt, user_prompt) result = _parse_response(raw)
prefix = f"c{chunk_index:02d}" for seg in result["segments"]: seg["segment_id"] = f"{session_id}_{prefix}_{seg['segment_id']}"
print(f"[Agent 1] Chunk {chunk_index}: {len(result['segments'])} segments " f"(turns {turns[0]['turn_id']}–{turns[-1]['turn_id']})") return result["segments"]
def run_full_transcript( turns: list[dict], session_id: str, library_root: Optional[Path] = None,) -> list[dict]: """ Segment an entire transcript.
Strategy: - Load library once. - If the formatted transcript fits within SINGLE_PASS_CHAR_LIMIT, send it in a single LLM call (best context, fewest calls). - If it exceeds the limit, split into CHUNK_TURNS-turn chunks with a small overlap so episodes that straddle a boundary are not lost.
Returns: List of all segments across all chunks, in order. """ global LIBRARY_ROOT, TIER1_PATH, TIER2_PATH if library_root: LIBRARY_ROOT = library_root TIER1_PATH = library_root / "tier1_core" TIER2_PATH = library_root / "tier2_validated"
if not turns: raise ValueError("No turns provided.")
# Load library once tier1 = load_tier1() tier2 = load_tier2() system_prompt = build_system_prompt(tier1, tier2)
formatted = _format_turns(turns)
# ── Single pass ────────────────────────────────────────────────────────── if len(formatted) <= SINGLE_PASS_CHAR_LIMIT: print(f"[Agent 1] Single-pass mode ({len(turns)} turns, " f"{len(formatted):,} chars)") return _call_single_pass(turns, session_id, 0, system_prompt)
# ── Chunked fallback ───────────────────────────────────────────────────── overlap = CHUNK_TURNS // 10 # 10 % overlap between chunks step = CHUNK_TURNS - overlap chunks = [turns[i:i + CHUNK_TURNS] for i in range(0, len(turns), step)]
print(f"[Agent 1] Chunked mode ({len(turns)} turns → {len(chunks)} chunks " f"of ~{CHUNK_TURNS} with {overlap}-turn overlap)")
all_segments: list[dict] = [] seen_ids: set[str] = set()
for idx, chunk in enumerate(chunks): segs = _call_single_pass(chunk, session_id, idx, system_prompt) for seg in segs: if seg["segment_id"] not in seen_ids: seen_ids.add(seg["segment_id"]) all_segments.append(seg)
print(f"[Agent 1] Complete. Total segments: {len(all_segments)}") return all_segments
# ---------------------------------------------------------------------------# Save output# ---------------------------------------------------------------------------
def save_segments(segments: list[dict], output_path: Path) -> None: output_path.parent.mkdir(parents=True, exist_ok=True) output_path.write_text( json.dumps({"segments": segments}, indent=2, ensure_ascii=False), encoding="utf-8", ) print(f"[Agent 1] Segments saved to {output_path}")
# ---------------------------------------------------------------------------# CLI# ---------------------------------------------------------------------------
if __name__ == "__main__": import sys
if len(sys.argv) < 3: print("Usage: python agent1_segmenter.py <parsed_turns.json> <session_id> [output.json]") sys.exit(1)
turns_file = Path(sys.argv[1]) session_id = sys.argv[2] output_file = Path(sys.argv[3]) if len(sys.argv) > 3 else Path(f"sessions/{session_id}/segments_proposed.json")
turns = json.loads(turns_file.read_text()) segments = run_full_transcript(turns, session_id) save_segments(segments, output_file)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275"""agent1a_boundary.py-------------------Agent 1a: The Boundary Detector.
Given a confirmed topical section, proposes episode boundaries — the turnpositions where one behavioral episode ends and another begins. This is apurely structural task; dimension coding is delegated entirely to Agent 1b.
Why separate boundary detection from coding?--------------------------------------------Krippendorff (2004, ch. 7) establishes that unitising (defining segmentboundaries) should precede categorisation. Mixing the two tasks in oneprompt conflates structurally distinct cognitive operations and reducesreliability in both. Annotation research consistently shows thathuman coders perform better when these tasks are separated:
Krippendorff, K. (2004). Content analysis: An introduction to its methodology (2nd ed., ch. 7 "Unitizing"). Sage.
MacWhinney, B. (2000). The CHILDES Project: Tools for analyzing talk (3rd ed.). Lawrence Erlbaum. — CLAN/ELAN annotation workflows define utterance units before assigning any tier labels.
Pustejovsky, J., & Stubbs, A. (2012). Natural Language Annotation for Machine Learning (ch. 4). O'Reilly. — "Unit definition is logically and procedurally prior to labelling."
Episode boundary signals------------------------Based on conversation analysis (Schegloff 2007) and pragmatics (Levinson 1983):
Schegloff, E. A. (2007). Sequence organization in interaction (vol. 1). Cambridge University Press. — Adjacency pairs, sequence completion, transition relevance points.
Levinson, S. C. (1983). Pragmatics (ch. 6). Cambridge University Press. — Turn-taking machinery and episode closure.
Jefferson, G. (1984). On the organization of laughter in talk about troubles. In J. M. Atkinson & J. Heritage (Eds.), Structures of social action. Cambridge University Press. — Completion signals in interaction.
Stivers, T., & Robinson, J. D. (2006). A preference for progressivity in interaction. Language in Society, 35(3), 367–392. — Topic shift as an interactional resource.
Agent 1a reads NO library tiers (no Tier 1/2/3).Agent 1a NEVER assigns dimension codes."""
import jsonfrom pathlib import Path
from llm_client import call_llm
MAX_TOKENS = 1500
# ---------------------------------------------------------------------------# Formatters# ---------------------------------------------------------------------------
def _format_turns(turns: list[dict]) -> str: lines = [] for t in turns: lines.append( f"[{t['turn_id']:>4}] {t['start_time']} {t['speaker']}: {t['text']}" ) return "\n".join(lines)
# ---------------------------------------------------------------------------# Prompt builder# ---------------------------------------------------------------------------
def build_system_prompt() -> str: return """You are a discourse analyst. Your task is to identify episode boundarieswithin a section of a collaborative work transcript.
An episode boundary marks where one coherent behavioral unit ends and another begins.You are NOT assigning dimension codes — only marking transition points.
Boundary signals (Schegloff 2007; Levinson 1983): explicit_transition — turn-initial markers: "OK", "right", "so", "now let's", "moving on", "anyway", or speaker explicitly closes topic sequence_completion — an adjacency pair completes (Q answered, request fulfilled) and neither speaker continues on that thread activity_change — the dyad shifts from one type of action to another (e.g. reading aloud → discussing → coding → reviewing) topic_exhaustion — topic reaches a natural close before a new one opens, marked by silence, acknowledgement tokens, or reformulation
Confidence levels: high — clear boundary signal present in the transcript text medium — likely boundary but signal is ambiguous or implicit low — possible boundary; human reviewer should check carefully
Output ONLY valid JSON — no preamble, no explanation outside the JSON:{ "section_id": "s01", "boundaries": [ { "boundary_id": "b_s01_01", "after_turn_id": 12, "confidence": "high | medium | low", "boundary_signal": "explicit_transition | sequence_completion | activity_change | topic_exhaustion", "rationale": "1 sentence citing the specific observable signal at this turn" } ], "n_episodes": 4}
If the entire section is one coherent episode, return an empty boundaries listand set n_episodes to 1."""
def build_user_prompt(section: dict, turns: list[dict]) -> str: return f"""Section: {section['section_id']} — {section['label']}Summary: {section.get('summary', '')}Turns: {turns[0]['turn_id']} – {turns[-1]['turn_id']} ({len(turns)} total)
=== TRANSCRIPT ==={_format_turns(turns)}
Identify episode boundaries within this section."""
# ---------------------------------------------------------------------------# Response parser# ---------------------------------------------------------------------------
def _parse_response(raw: str, section_id: str) -> dict: cleaned = raw.strip() if cleaned.startswith("```"): cleaned = "\n".join(cleaned.split("\n")[1:]) if cleaned.endswith("```"): cleaned = "\n".join(cleaned.split("\n")[:-1]) cleaned = cleaned.strip() try: result = json.loads(cleaned) except json.JSONDecodeError as e: raise ValueError( f"Agent 1a returned invalid JSON for {section_id}.\n" f"Error: {e}\nRaw:\n{raw}" ) from e if "boundaries" not in result: raise ValueError( f"Agent 1a response missing 'boundaries' key for {section_id}." ) return result
# ---------------------------------------------------------------------------# Boundary → segment converter# ---------------------------------------------------------------------------
def boundaries_to_segments( section: dict, turns: list[dict], boundaries: list[dict], session_id: str,) -> list[dict]: """ Convert a boundary list into uncoded segment dicts (turn ranges only).
Each segment spans from one boundary to the next. The first segment starts at the section's first turn; the last ends at the section's last turn. Dimension fields are left as None for Agent 1b to fill. """ if not turns: return []
turn_ids = sorted(t["turn_id"] for t in turns) turn_map = {t["turn_id"]: t for t in turns}
# Cut points: start of section + one cut per boundary cut_starts = [turn_ids[0]] for b in sorted(boundaries, key=lambda x: x["after_turn_id"]): after = b["after_turn_id"] if after in turn_ids: idx = turn_ids.index(after) if idx < len(turn_ids) - 1: cut_starts.append(turn_ids[idx + 1])
segments = [] for i, start in enumerate(cut_starts): if i + 1 < len(cut_starts): end_idx = turn_ids.index(cut_starts[i + 1]) - 1 end = turn_ids[end_idx] else: end = turn_ids[-1]
seg_turns = [t for t in turns if start <= t["turn_id"] <= end] if not seg_turns: continue
ep_num = i + 1 seg_id = f"{session_id}_{section['section_id']}_ep{ep_num:02d}"
segments.append({ "segment_id": seg_id, "section_id": section["section_id"], "start_turn_id": start, "end_turn_id": end, "start_time": turn_map[start]["start_time"], "end_time": turn_map[end]["start_time"], "turns": seg_turns, # Filled by Agent 1b "dimension_id": None, "dimension_label": None, "rationale": None, "confident": None, "uncertain": None, "uncertainty_note": None, })
return segments
# ---------------------------------------------------------------------------# Public API# ---------------------------------------------------------------------------
def propose_boundaries( section: dict, turns: list[dict], session_id: str,) -> dict: """ Propose episode boundaries for one confirmed topical section.
Args: section: Confirmed section dict (section_id, label, summary, turn range). turns: The turns belonging to this section. session_id: Session identifier (used in segment ID namespacing).
Returns: Dict with: section_id, boundaries, n_episodes, segments (uncoded). """ print( f"[Agent 1a] Proposing boundaries for {section['section_id']} " f"— {section['label']} ({len(turns)} turns)..." )
system_prompt = build_system_prompt() user_prompt = build_user_prompt(section, turns) raw = call_llm(system_prompt, user_prompt, max_tokens=MAX_TOKENS) result = _parse_response(raw, section["section_id"])
boundaries = result.get("boundaries", []) segments = boundaries_to_segments(section, turns, boundaries, session_id)
# Attach boundary metadata to each segment for UI display boundary_map: dict[int, dict] = {} for b in boundaries: boundary_map[b["after_turn_id"]] = b
for seg in segments: prev_end = seg["start_turn_id"] - 1 seg["_boundary_before"] = boundary_map.get(prev_end)
print( f"[Agent 1a] {section['section_id']}: " f"{len(boundaries)} boundaries → {len(segments)} episodes" )
return { "section_id": section["section_id"], "boundaries": boundaries, "n_episodes": result.get("n_episodes", len(segments)), "segments": segments, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317"""agent1b_coder.py----------------Agent 1b: The Dimension Coder.
Given segments with confirmed boundaries (from Agent 1a + human review),assigns each segment a dimension code from the D1–D9 framework. Operateson one topical section at a time, using section context to inform coding.
Rationale for separating coding from segmentation--------------------------------------------------See agent1a_boundary.py for the full argument. In brief:
Krippendorff, K. (2004). Content analysis (ch. 7). Sage. — Unitising and categorising are distinct cognitive operations. Interleaving them in one prompt inflates apparent agreement by constraining where boundaries can fall to match preferred codes.
Pustejovsky, J., & Stubbs, A. (2012). Natural Language Annotation for Machine Learning (ch. 4). O'Reilly.
Section context window----------------------Providing Agent 1b with the section label and summary (from Agent 0) actsas a form of "discourse context" shown to improve coding reliability in:
Reidsma, D., & Carletta, J. (2008). Reliability measurement without limits. Computational Linguistics, 34(3), 319–326. — Annotators with shared discourse context show higher kappa.
Uncertainty-first routing (active learning)-------------------------------------------Agent 1b flags segments as uncertain, enabling researchers to prioritisereview of those cases — the core insight from uncertainty sampling:
Settles, B. (2012). Active learning. Synthesis Lectures on Artificial Intelligence and Machine Learning, 6(1), 1–114. Morgan & Claypool.
Monarch, R. (2021). Human-in-the-loop machine learning (ch. 3). Manning. — Confidence-based routing to human review.
Collaborative learning dimension framework------------------------------------------The D1–D9 coding scheme implemented here follows the multi-dimensionalquality rating approach established in:
Meier, A., Spada, H., & Rummel, N. (2007). A rating scheme for assessing the quality of computer-supported collaboration processes. International Journal of Computer-Supported Collaborative Learning, 2(1), 63–86.
Rummel, N., & Spada, H. (2005). Learning to collaborate: An instructional approach to promoting collaborative problem solving in computer-mediated settings. Journal of the Learning Sciences, 14(2), 201–241.
Agent 1b reads Tier 1 (core definitions) and Tier 2 (validated learnings).Agent 1b NEVER reads Tier 3 (candidate corrections — reserved for Agent 2)."""
import jsonfrom pathlib import Pathfrom typing import Optional
from llm_client import call_llm
LIBRARY_ROOT = Path(__file__).parent / "library"TIER1_PATH = LIBRARY_ROOT / "tier1_core"TIER2_PATH = LIBRARY_ROOT / "tier2_validated"
MAX_TOKENS = 3000MAX_SEGS_PER_CALL = 8 # batch ceiling — prevents context overflow on large sections
# ---------------------------------------------------------------------------# Library loaders# ---------------------------------------------------------------------------
def load_tier1() -> dict: dimensions = json.loads((TIER1_PATH / "dimensions.json").read_text()) examples = json.loads((TIER1_PATH / "examples.json").read_text()) coding_rules = json.loads((TIER1_PATH / "coding_rules.json").read_text()) return { "dimensions": dimensions["dimensions"], "examples": examples["examples"], "coding_rules": coding_rules["rules"], }
def load_tier2() -> dict: learned_rules = json.loads((TIER2_PATH / "learned_rules.json").read_text()) edge_cases = json.loads((TIER2_PATH / "edge_cases.json").read_text()) return { # Only active (approved) rules reach Agent 1b "learned_rules": [ r for r in learned_rules.get("learned_rules", []) if r.get("active") ], "edge_cases": edge_cases.get("edge_cases", []), }
# ---------------------------------------------------------------------------# Formatters# ---------------------------------------------------------------------------
def _format_dimensions(dimensions: list[dict]) -> str: lines = [] for d in dimensions: lines.append(f"[{d['id']}] {d['label']}") lines.append(f" Summary: {d['summary']}") lines.append(f" Key behavioral markers:") for marker in d["key_behavioral_markers"]: lines.append(f" - {marker}") lines.append("") return "\n".join(lines)
def _format_examples(examples: list[dict]) -> str: lines = [] for ex in examples: lines.append(f"Dimension: {ex['dimension_id']} ({ex['type'].upper()})") lines.append(f"Label: {ex['label']}") for turn in ex["exchange"]: lines.append(f" {turn['speaker']}: {turn['text']}") lines.append(f"Note: {ex['annotation_note']}") lines.append("") return "\n".join(lines)
def _format_rules(rules: list[dict]) -> str: return "\n".join( f"[{r['rule_id']}] {r['label']}: {r['description']}" for r in rules )
def _format_learned(tier2: dict) -> str: rules = tier2.get("learned_rules", []) cases = tier2.get("edge_cases", []) if not rules and not cases: return "None yet." lines = [] for r in rules: lines.append( f"- LEARNED RULE [{r.get('rule_type')}]: {r.get('description', '')}" ) for c in cases: lines.append(f"- EDGE CASE: {c.get('description', '')}") return "\n".join(lines)
def _format_segment(seg: dict) -> str: turns = seg.get("turns", []) lines = [ f"Segment ID: {seg['segment_id']} " f"({seg.get('start_time', '?')} – {seg.get('end_time', '?')})" ] for t in turns: lines.append(f" [{t['turn_id']}] {t['speaker']}: {t['text']}") return "\n".join(lines)
# ---------------------------------------------------------------------------# Prompt builders# ---------------------------------------------------------------------------
def build_system_prompt(tier1: dict, tier2: dict, section: dict) -> str: return f"""You are a behavioral coding assistant trained in collaborative learning research.You are coding segments from one section of a Zoom transcript.
Section context: {section['label']} — {section.get('summary', '')}Use this context to inform your interpretation, but base your final decisionsolely on observable turn content.
=== DIMENSION DEFINITIONS ==={_format_dimensions(tier1['dimensions'])}
=== ANCHOR EXAMPLES ==={_format_examples(tier1['examples'])}
=== CODING RULES (MANDATORY) ==={_format_rules(tier1['coding_rules'])}
=== VALIDATED LEARNINGS FROM PRIOR SESSIONS ==={_format_learned(tier2)}
=== OUTPUT FORMAT ===Respond ONLY with valid JSON. Code ALL segments provided.{{ "coded_segments": [ {{ "segment_id": "must match input segment_id exactly", "dimension_id": "D1 to D9", "dimension_label": "string", "confident": true or false, "uncertain": true or false, "uncertainty_note": "competing dimension and why, or null", "rationale": "1–2 sentences citing specific observable behaviors" }} ]}}"""
def build_user_prompt(segments: list[dict]) -> str: seg_text = "\n\n".join(_format_segment(s) for s in segments) return ( f"Please assign a dimension code to each of the following " f"{len(segments)} segment(s).\n\n{seg_text}\n\n" "Base rationale only on observable turn content." )
# ---------------------------------------------------------------------------# Response parser# ---------------------------------------------------------------------------
def _parse_response(raw: str) -> list[dict]: cleaned = raw.strip() if cleaned.startswith("```"): cleaned = "\n".join(cleaned.split("\n")[1:]) if cleaned.endswith("```"): cleaned = "\n".join(cleaned.split("\n")[:-1]) cleaned = cleaned.strip() try: result = json.loads(cleaned) except json.JSONDecodeError as e: raise ValueError( f"Agent 1b returned invalid JSON.\nError: {e}\nRaw:\n{raw}" ) from e if "coded_segments" not in result: raise ValueError("Agent 1b response missing 'coded_segments' key.") return result["coded_segments"]
# ---------------------------------------------------------------------------# Public API# ---------------------------------------------------------------------------
def code_section( section: dict, segments: list[dict], library_root: Optional[Path] = None,) -> list[dict]: """ Assign dimension codes to all segments in one confirmed section.
Batches the LLM call if the section has more than MAX_SEGS_PER_CALL segments, to avoid context overflow with many long turns.
Args: section: Confirmed section dict (for context window). segments: Uncoded segment dicts from Agent 1a (boundaries confirmed by the researcher). library_root: Override library path (for testing).
Returns: List of segment dicts with dimension_id, rationale, confident, and uncertain fields filled. The 'turns' key is preserved for the UI. """ global LIBRARY_ROOT, TIER1_PATH, TIER2_PATH if library_root: LIBRARY_ROOT = library_root TIER1_PATH = library_root / "tier1_core" TIER2_PATH = library_root / "tier2_validated"
if not segments: return []
print( f"[Agent 1b] Coding {len(segments)} segments in " f"{section['section_id']} — {section['label']}..." )
tier1 = load_tier1() tier2 = load_tier2() system_prompt = build_system_prompt(tier1, tier2, section)
# Batch into groups to respect context limits batches = [ segments[i:i + MAX_SEGS_PER_CALL] for i in range(0, len(segments), MAX_SEGS_PER_CALL) ]
all_coded: dict[str, dict] = {} for batch_idx, batch in enumerate(batches): user_prompt = build_user_prompt(batch) raw = call_llm(system_prompt, user_prompt, max_tokens=MAX_TOKENS) coded_batch = _parse_response(raw) for c in coded_batch: all_coded[c["segment_id"]] = c if len(batches) > 1: print( f"[Agent 1b] Batch {batch_idx + 1}/{len(batches)} complete " f"({len(coded_batch)} segments)" )
# Merge coded fields back into original segment dicts (preserving 'turns') result = [] for seg in segments: code = all_coded.get(seg["segment_id"], {}) result.append({ **seg, "dimension_id": code.get("dimension_id", ""), "dimension_label": code.get("dimension_label", ""), "confident": code.get("confident", False), "uncertain": code.get("uncertain", False), "uncertainty_note": code.get("uncertainty_note"), "rationale": code.get("rationale", ""), })
n_uncertain = sum(1 for s in result if s.get("uncertain")) print( f"[Agent 1b] {section['section_id']}: {len(result)} segments coded, " f"{n_uncertain} flagged uncertain — route to researcher review." ) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783"""agent2_learner.py-----------------Agent 2: The Learner.
Responsibilities:- Only activates after kappa gate is passed AND all disagreements are resolved/discarded- Reads Tier 3 candidate corrections (NEVER Tier 1 or Tier 2 directly)- Reads validated kappa reports to understand agreement patterns- Extracts three types of rules: boundary clarifications, disambiguation rules, behavioral marker refinements- Writes candidate rules to Tier 2 with status: pending_review- Rules only become active for Agent 1 after a human researcher approves them- Never rewrites or contradicts Tier 1- Never operates below the minimum segment threshold
Sample size rationale (encoded as constants): With 9 dimensions and a target kappa >= 0.70, power analysis indicates: - Statistical floor: ~85 segments for 80% power (PMC12935580) - Safe zone: 90-120 segments, accounting for unbalanced category distributions across 9 dimensions (some like D6, D7 are naturally sparse in collaboration corpora, inflating variance and requiring larger N for stable per-dim kappa) - Reference: Bujang & Baharum (2017), Guidelines for minimum sample size requirements for Cohen's Kappa. Epidemiology, Biostatistics and Public Health.
Rule types Agent 2 is allowed to write: Type 1 — Boundary clarification Type 2 — Disambiguation rule (between two specific dimensions) Type 3 — Behavioral marker refinement (context-specific sharpening)
What Agent 2 can NEVER write: - A redefinition of a dimension's core meaning - A rule that contradicts Tier 1 - A rule from sessions where discarded segments exceed 20% - A rule without human approval before it goes live for Agent 1"""
import jsonimport uuidfrom pathlib import Pathfrom datetime import datetime, timezonefrom typing import Optional
from llm_client import call_llm
# ---------------------------------------------------------------------------# Constants# ---------------------------------------------------------------------------
LIBRARY_ROOT = Path(__file__).parent / "library"TIER1_PATH = LIBRARY_ROOT / "tier1_core"TIER2_PATH = LIBRARY_ROOT / "tier2_validated"TIER3_PATH = LIBRARY_ROOT / "tier3_candidate"
MAX_TOKENS = 2000
# Sample size thresholds — see module docstring for statistical rationaleMIN_SEGMENTS_FOR_LEARNING = 90 # statistical floor (80% power, κ=0.70, 9 dims)RECOMMENDED_SEGMENTS = 120 # safe zone for unbalanced 9-dim distributionsMAX_DISCARD_RATE = 0.20 # max proportion of discarded segments allowedMIN_SESSIONS_BEFORE_WRITING = 3 # minimum validated sessions before first rule
RULE_TYPES = [ "boundary_clarification", "disambiguation_rule", "behavioral_marker_refinement",]
# ---------------------------------------------------------------------------# Session accumulator — tracks how many validated segments exist so far# ---------------------------------------------------------------------------
def count_validated_segments(sessions_root: Path) -> tuple[int, int]: """ Count total validated segments across all sessions that: - Passed the kappa gate - Have status ready_for_agent2 - Have a discard rate <= MAX_DISCARD_RATE
Returns (n_valid_sessions, n_valid_segments). """ n_sessions = 0 n_segments = 0
if not sessions_root.exists(): return 0, 0
for session_dir in sessions_root.iterdir(): if not session_dir.is_dir(): continue report_path = session_dir / "kappa_report.json" if not report_path.exists(): continue
try: report = json.loads(report_path.read_text(encoding="utf-8")) except Exception: continue
if report.get("status") != "ready_for_agent2": continue if not report.get("gate_passed"): continue
# Check discard rate total = report.get("n_segments_total", 0) discarded = sum( 1 for d in report.get("disagreements", []) if d.get("resolution_status") == "discarded" ) if total > 0 and discarded / total > MAX_DISCARD_RATE: continue
n_sessions += 1 n_segments += total
return n_sessions, n_segments
# ---------------------------------------------------------------------------# Tier 3 loader — the ONLY library tier Agent 2 reads# ---------------------------------------------------------------------------
def load_tier3_candidates() -> list[dict]: """Load all pending candidate corrections from Tier 3.""" pending_path = TIER3_PATH / "pending_review.json" if not pending_path.exists(): return [] data = json.loads(pending_path.read_text(encoding="utf-8")) return data.get("pending_review", [])
def load_tier1_dimension_ids() -> list[str]: """ Load ONLY the dimension IDs and labels from Tier 1 — just enough for Agent 2 to validate that its rules reference real dimensions. Agent 2 does NOT read full Tier 1 definitions. """ dims = json.loads((TIER1_PATH / "dimensions.json").read_text()) return [{"id": d["id"], "label": d["label"]} for d in dims["dimensions"]]
def load_existing_tier2_rules() -> list[dict]: """Load existing validated rules so Agent 2 doesn't duplicate them.""" rules_path = TIER2_PATH / "learned_rules.json" if not rules_path.exists(): return [] data = json.loads(rules_path.read_text(encoding="utf-8")) return data.get("learned_rules", [])
# ---------------------------------------------------------------------------# Kappa report loader for context# ---------------------------------------------------------------------------
def load_ready_reports(sessions_root: Path) -> list[dict]: """Load all kappa reports that are ready for Agent 2.""" reports = [] if not sessions_root.exists(): return reports
for session_dir in sessions_root.iterdir(): if not session_dir.is_dir(): continue report_path = session_dir / "kappa_report.json" if not report_path.exists(): continue try: report = json.loads(report_path.read_text(encoding="utf-8")) if report.get("status") == "ready_for_agent2": reports.append(report) except Exception: continue
return reports
# ---------------------------------------------------------------------------# Prompt builder# ---------------------------------------------------------------------------
def _format_candidates(candidates: list[dict]) -> str: if not candidates: return "No candidate corrections in Tier 3 yet." lines = [] for c in candidates: lines.append(f"Candidate ID: {c.get('candidate_id', 'unknown')}") lines.append(f" Session: {c.get('session_id')}") lines.append(f" Segment: {c.get('segment_id')}") lines.append(f" Agent 1 assigned: {c.get('agent1_dimension')}") lines.append(f" R1 coded: {c.get('r1_dimension')} | Comment: {c.get('r1_comment', '')}") lines.append(f" R2 coded: {c.get('r2_dimension')} | Comment: {c.get('r2_comment', '')}") lines.append(f" Resolved to: {c.get('resolved_dimension', 'unresolved')}") lines.append(f" Resolution note: {c.get('resolution_note', '')}") lines.append(f" Agent 1 rationale: {c.get('agent1_rationale', '')}") lines.append("") return "\n".join(lines)
def _format_kappa_summary(reports: list[dict]) -> str: if not reports: return "No session reports available." lines = [] for r in reports: lines.append(f"Session: {r['session_id']} | Kappa: {r['overall_kappa']} | " f"Segments: {r['n_segments_total']} | Disagreed: {r['n_segments_disagreed']}") dim_kappas = r.get("kappa_per_dimension", {}) low_dims = [f"{d}={k:.2f}" for d, k in dim_kappas.items() if k is not None and k < 0.70] if low_dims: lines.append(f" Low-agreement dimensions: {', '.join(low_dims)}") return "\n".join(lines)
def _format_existing_rules(rules: list[dict]) -> str: if not rules: return "No rules written yet." lines = [] for r in rules: lines.append(f"- [{r.get('rule_type')}] {r.get('description')} " f"(approved: {r.get('approved', False)})") return "\n".join(lines)
def _format_dimension_ids(dims: list[dict]) -> str: return ", ".join(f"{d['id']} ({d['label']})" for d in dims)
def build_system_prompt( dimension_ids: list[dict], existing_rules: list[dict],) -> str: return f"""You are a methodology assistant for a qualitative research coding project.Your task is to extract generalizable rules from researcher corrections to improvea behavioral coding agent (Agent 1).
You operate under STRICT constraints. Read them carefully.
=== DIMENSIONS (for reference only — do NOT redefine these) ==={_format_dimension_ids(dimension_ids)}
=== EXISTING TIER 2 RULES (do not duplicate these) ==={_format_existing_rules(existing_rules)}
=== RULE TYPES YOU ARE ALLOWED TO WRITE ===1. boundary_clarification When: You see a pattern in WHERE boundaries are placed incorrectly Format: "When [behavioral pattern X] transitions to [behavioral pattern Y], the boundary falls after [specific observable signal Z]"
2. disambiguation_rule Between two specific dimensions that researchers consistently confuse. Format: "When [D_X] and [D_Y] appear to co-occur, assign [D_X] if [condition A], assign [D_Y] if [condition B]"
3. behavioral_marker_refinement A context-specific sharpening of an existing behavioral marker. Format: "In this corpus, [observable behavior] is a marker of [D_X], not [D_Y], because [observable reason]"
=== CONSTRAINTS YOU MUST NEVER VIOLATE ===- Never redefine a dimension's core meaning- Never contradict the dimension definitions- Only write rules that are clearly supported by MULTIPLE corrections (not a single case)- Every rule must cite the candidate IDs it was derived from- Never invent examples — only use what the corrections show- If the corrections are too sparse or inconsistent to support a rule, return an empty list- Rules about boundary placement must reference observable turn-level behaviors, not inferences
=== OUTPUT FORMAT ===Respond ONLY with valid JSON. No preamble, no explanation outside the JSON.
{{ "proposed_rules": [ {{ "rule_type": "boundary_clarification | disambiguation_rule | behavioral_marker_refinement", "dimensions_involved": ["D1", "D2"], "description": "Full rule text as specified above", "rationale": "Why this rule is supported by the corrections — cite candidate_ids", "derived_from_candidates": ["candidate_id_1", "candidate_id_2"], "confidence": "high | medium | low", "agent2_note": "Any caveats or conditions the reviewing researcher should consider" }} ], "learning_summary": {{ "candidates_reviewed": integer, "rules_proposed": integer, "patterns_too_sparse": ["description of pattern seen but not actionable yet"], "recommendation": "brief note to researchers on what to watch for in future sessions" }}}}
If no rules can be reliably derived, return proposed_rules as an empty listand explain in learning_summary why."""
def build_user_prompt( candidates: list[dict], reports: list[dict],) -> str: return f"""Please review the following researcher corrections and kappa reports.Extract generalizable rules where the pattern is clear and consistent.
=== TIER 3 CANDIDATE CORRECTIONS ==={_format_candidates(candidates)}
=== KAPPA REPORT SUMMARIES ==={_format_kappa_summary(reports)}
Remember:- Only propose rules supported by multiple consistent corrections- Cite candidate IDs in your rationale- If in doubt, return an empty list — a sparse rule is worse than no rule"""
# ---------------------------------------------------------------------------# API call# ---------------------------------------------------------------------------
def _call_claude(system_prompt: str, user_prompt: str) -> str: return call_llm(system_prompt, user_prompt, max_tokens=MAX_TOKENS)
# ---------------------------------------------------------------------------# Response parser# ---------------------------------------------------------------------------
def _parse_response(raw: str) -> dict: cleaned = raw.strip() if cleaned.startswith("```"): cleaned = "\n".join(cleaned.split("\n")[1:]) if cleaned.endswith("```"): cleaned = "\n".join(cleaned.split("\n")[:-1]) cleaned = cleaned.strip()
try: return json.loads(cleaned) except json.JSONDecodeError as e: raise ValueError( f"Agent 2 returned invalid JSON.\nError: {e}\nRaw:\n{raw}" ) from e
# ---------------------------------------------------------------------------# Tier 2 writer — writes rules with pending_review status# ---------------------------------------------------------------------------
def write_rules_to_tier2( proposed_rules: list[dict], sessions_contributing: list[str], n_segments_contributing: int,) -> list[dict]: """ Write proposed rules to Tier 2 with status pending_review. Rules are NOT active for Agent 1 until approved = True.
Returns the list of written rule records. """ rules_path = TIER2_PATH / "learned_rules.json" data = json.loads(rules_path.read_text(encoding="utf-8"))
written = [] for rule in proposed_rules: record = { "rule_id": str(uuid.uuid4())[:8], "rule_type": rule.get("rule_type"), "dimensions_involved": rule.get("dimensions_involved", []), "description": rule.get("description"), "rationale": rule.get("rationale"), "derived_from_candidates": rule.get("derived_from_candidates", []), "sessions_contributing": sessions_contributing, "n_segments_contributing": n_segments_contributing, "confidence": rule.get("confidence"), "agent2_note": rule.get("agent2_note", ""), "approved": False, # MUST be reviewed by human "approved_by": None, "approved_at": None, "approval_note": "", "created_at": datetime.now(timezone.utc).isoformat(), "active": False, # only True after approval } data["learned_rules"].append(record) written.append(record)
data["_meta"]["last_updated"] = datetime.now(timezone.utc).isoformat() data["_meta"]["total_entries"] = len(data["learned_rules"])
rules_path.write_text( json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8", )
return written
# ---------------------------------------------------------------------------# Rule approval — called by researcher# ---------------------------------------------------------------------------
def approve_rule( rule_id: str, approved_by: str, approval_note: str = "",) -> dict: """ Approve a pending rule. Sets approved=True and active=True. Only after this does Agent 1 see the rule.
Args: rule_id: The rule_id to approve approved_by: Researcher ID approving the rule approval_note: Optional note on why this rule was approved
Returns updated rule record. """ rules_path = TIER2_PATH / "learned_rules.json" data = json.loads(rules_path.read_text(encoding="utf-8"))
updated = None for rule in data["learned_rules"]: if rule["rule_id"] == rule_id: rule["approved"] = True rule["active"] = True rule["approved_by"] = approved_by rule["approved_at"] = datetime.now(timezone.utc).isoformat() rule["approval_note"] = approval_note updated = rule break
if updated is None: raise ValueError(f"Rule {rule_id} not found in Tier 2.")
rules_path.write_text( json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8", ) print(f"[Agent 2] Rule {rule_id} approved by {approved_by} → now active for Agent 1") return updated
def reject_rule( rule_id: str, rejected_by: str, rejection_note: str,) -> dict: """ Reject a pending rule. Marks it as rejected so it is never shown to Agent 1. The record is kept for audit purposes. """ rules_path = TIER2_PATH / "learned_rules.json" data = json.loads(rules_path.read_text(encoding="utf-8"))
updated = None for rule in data["learned_rules"]: if rule["rule_id"] == rule_id: rule["approved"] = False rule["active"] = False rule["approved_by"] = rejected_by rule["approved_at"] = datetime.now(timezone.utc).isoformat() rule["approval_note"] = f"REJECTED: {rejection_note}" updated = rule break
if updated is None: raise ValueError(f"Rule {rule_id} not found in Tier 2.")
rules_path.write_text( json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8", ) print(f"[Agent 2] Rule {rule_id} rejected by {rejected_by}") return updated
# ---------------------------------------------------------------------------# Tier 3 writer — called by kappa_calculator when disagreements are resolved# ---------------------------------------------------------------------------
def add_to_tier3( session_id: str, segment_id: str, agent1_dimension: str, agent1_rationale: str, r1_dimension: str, r1_comment: str, r2_dimension: str, r2_comment: str, resolved_dimension: str, resolution_note: str,) -> str: """ Add a resolved disagreement to Tier 3 for Agent 2 to review later. Returns the candidate_id of the new entry. """ pending_path = TIER3_PATH / "pending_review.json" data = json.loads(pending_path.read_text(encoding="utf-8"))
candidate_id = str(uuid.uuid4())[:8] entry = { "candidate_id": candidate_id, "session_id": session_id, "segment_id": segment_id, "added_at": datetime.now(timezone.utc).isoformat(), "agent1_dimension": agent1_dimension, "agent1_rationale": agent1_rationale, "r1_dimension": r1_dimension, "r1_comment": r1_comment, "r2_dimension": r2_dimension, "r2_comment": r2_comment, "resolved_dimension": resolved_dimension, "resolution_note": resolution_note, "consumed": False, # flipped to True after Agent 2 processes it }
data["pending_review"].append(entry) data["_meta"]["last_updated"] = datetime.now(timezone.utc).isoformat() data["_meta"]["total_entries"] = len(data["pending_review"])
pending_path.write_text( json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8", )
print(f"[Tier 3] Added candidate {candidate_id} from session {session_id}") return candidate_id
# ---------------------------------------------------------------------------# Main learning run# ---------------------------------------------------------------------------
def run_learning_cycle( sessions_root: Path, library_root: Optional[Path] = None, dry_run: bool = False,) -> dict: """ Run a full Agent 2 learning cycle.
Args: sessions_root: Path to the sessions directory library_root: Override library path (for testing) dry_run: If True, extract rules but do not write to Tier 2
Returns: Dict with proposed rules, learning summary, and gate status. """ global LIBRARY_ROOT, TIER1_PATH, TIER2_PATH, TIER3_PATH if library_root: LIBRARY_ROOT = library_root TIER1_PATH = library_root / "tier1_core" TIER2_PATH = library_root / "tier2_validated" TIER3_PATH = library_root / "tier3_candidate"
print("\n[Agent 2] Starting learning cycle...")
# ── Gate 1: minimum sessions ────────────────────────────────────────── n_sessions, n_segments = count_validated_segments(sessions_root) print(f"[Agent 2] Validated sessions: {n_sessions} | Segments: {n_segments}")
if n_sessions < MIN_SESSIONS_BEFORE_WRITING: print(f"[Agent 2] BLOCKED — minimum {MIN_SESSIONS_BEFORE_WRITING} sessions required " f"({n_sessions} available). Learning cycle skipped.") return { "status": "blocked_insufficient_sessions", "n_sessions": n_sessions, "n_segments": n_segments, "required_sessions": MIN_SESSIONS_BEFORE_WRITING, "proposed_rules": [], }
# ── Gate 2: minimum segments ────────────────────────────────────────── if n_segments < MIN_SEGMENTS_FOR_LEARNING: print(f"[Agent 2] WARNING — below statistical floor of {MIN_SEGMENTS_FOR_LEARNING} " f"segments ({n_segments} available). Rules will be low-confidence.")
if n_segments >= RECOMMENDED_SEGMENTS: print(f"[Agent 2] Segment count ({n_segments}) in safe zone (≥{RECOMMENDED_SEGMENTS}).") elif n_segments >= MIN_SEGMENTS_FOR_LEARNING: print(f"[Agent 2] Segment count ({n_segments}) above floor but below safe zone " f"({RECOMMENDED_SEGMENTS}). Proceeding with caution flag.")
# ── Load inputs ─────────────────────────────────────────────────────── candidates = [c for c in load_tier3_candidates() if not c.get("consumed")] dimension_ids = load_tier1_dimension_ids() existing_rules = load_existing_tier2_rules() reports = load_ready_reports(sessions_root)
if not candidates: print("[Agent 2] No unconsumed candidates in Tier 3. Nothing to learn from.") return { "status": "no_candidates", "proposed_rules": [], "learning_summary": { "candidates_reviewed": 0, "rules_proposed": 0, } }
print(f"[Agent 2] Reviewing {len(candidates)} unconsumed candidates from Tier 3...")
# ── Build prompts and call API ──────────────────────────────────────── system_prompt = build_system_prompt(dimension_ids, existing_rules) user_prompt = build_user_prompt(candidates, reports) raw = _call_claude(system_prompt, user_prompt) result = _parse_response(raw)
proposed_rules = result.get("proposed_rules", []) learning_summary = result.get("learning_summary", {})
print(f"[Agent 2] Proposed {len(proposed_rules)} rule(s).")
# ── Validate rules don't exceed allowed types ───────────────────────── valid_rules = [] for rule in proposed_rules: if rule.get("rule_type") not in RULE_TYPES: print(f"[Agent 2] REJECTED rule with invalid type: {rule.get('rule_type')}") continue dims = rule.get("dimensions_involved", []) valid_dims = [d["id"] for d in dimension_ids] if not all(d in valid_dims for d in dims): print(f"[Agent 2] REJECTED rule referencing unknown dimensions: {dims}") continue valid_rules.append(rule)
print(f"[Agent 2] {len(valid_rules)} rule(s) passed validation.")
# ── Write to Tier 2 (pending_review, not yet active) ───────────────── written_rules = [] if valid_rules and not dry_run: session_ids = [r["session_id"] for r in reports] written_rules = write_rules_to_tier2(valid_rules, session_ids, n_segments)
# Mark candidates as consumed _mark_candidates_consumed([c["candidate_id"] for c in candidates])
print(f"[Agent 2] {len(written_rules)} rule(s) written to Tier 2 with " f"status=pending_review. Awaiting human approval before Agent 1 sees them.") elif dry_run: print("[Agent 2] DRY RUN — rules not written to disk.")
# ── Print summary ───────────────────────────────────────────────────── _print_learning_summary(learning_summary, valid_rules, n_segments)
return { "status": "complete", "n_sessions": n_sessions, "n_segments": n_segments, "candidates_reviewed": len(candidates), "proposed_rules": valid_rules, "written_rules": written_rules, "learning_summary": learning_summary, "below_safe_zone": n_segments < RECOMMENDED_SEGMENTS, }
# ---------------------------------------------------------------------------# Helpers# ---------------------------------------------------------------------------
def _mark_candidates_consumed(candidate_ids: list[str]) -> None: """Mark Tier 3 candidates as consumed so they are not reprocessed.""" pending_path = TIER3_PATH / "pending_review.json" data = json.loads(pending_path.read_text(encoding="utf-8"))
for entry in data["pending_review"]: if entry["candidate_id"] in candidate_ids: entry["consumed"] = True
pending_path.write_text( json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8", )
def _print_learning_summary( summary: dict, rules: list[dict], n_segments: int,) -> None: print("\n" + "═" * 52) print(" AGENT 2 LEARNING SUMMARY") print("═" * 52) print(f" Candidates reviewed : {summary.get('candidates_reviewed', 0)}") print(f" Rules proposed : {len(rules)}") print(f" Total segments : {n_segments}") print(f" Safe zone (≥{RECOMMENDED_SEGMENTS}) : {'Yes' if n_segments >= RECOMMENDED_SEGMENTS else 'No — treat rules as provisional'}") if rules: print("\n Proposed rules:") for r in rules: print(f" [{r['rule_type']}] {r['description'][:80]}...") print(f" Confidence: {r.get('confidence')} | " f"Dims: {r.get('dimensions_involved')}") sparse = summary.get("patterns_too_sparse", []) if sparse: print("\n Patterns seen but not yet actionable:") for p in sparse: print(f" · {p}") rec = summary.get("recommendation", "") if rec: print(f"\n Recommendation: {rec}") print("═" * 52 + "\n")
# ---------------------------------------------------------------------------# List pending rules for researcher review# ---------------------------------------------------------------------------
def list_pending_rules() -> list[dict]: """Return all rules awaiting human approval.""" rules_path = TIER2_PATH / "learned_rules.json" if not rules_path.exists(): return [] data = json.loads(rules_path.read_text(encoding="utf-8")) return [r for r in data.get("learned_rules", []) if not r.get("approved")]
def print_pending_rules() -> None: pending = list_pending_rules() if not pending: print("[Agent 2] No rules pending review.") return print(f"\n[Agent 2] {len(pending)} rule(s) pending human review:\n") for r in pending: print(f" Rule ID : {r['rule_id']}") print(f" Type : {r['rule_type']}") print(f" Dimensions: {r['dimensions_involved']}") print(f" Rule : {r['description']}") print(f" Rationale : {r['rationale']}") print(f" Confidence: {r['confidence']}") print(f" Note : {r.get('agent2_note', '')}") print(f" Created : {r['created_at']}") print()
# ---------------------------------------------------------------------------# CLI# ---------------------------------------------------------------------------
if __name__ == "__main__": import sys
if len(sys.argv) < 2: print("Usage:") print(" Run learning cycle:") print(" python agent2_learner.py learn <sessions_dir> [--dry-run]") print(" List pending rules:") print(" python agent2_learner.py pending") print(" Approve a rule:") print(" python agent2_learner.py approve <rule_id> <researcher_id> [note]") print(" Reject a rule:") print(" python agent2_learner.py reject <rule_id> <researcher_id> <note>") sys.exit(1)
command = sys.argv[1]
if command == "learn": sessions_dir = Path(sys.argv[2]) dry = "--dry-run" in sys.argv run_learning_cycle(sessions_dir, dry_run=dry)
elif command == "pending": print_pending_rules()
elif command == "approve": rule_id = sys.argv[2] researcher = sys.argv[3] note = sys.argv[4] if len(sys.argv) > 4 else "" approve_rule(rule_id, researcher, note)
elif command == "reject": rule_id = sys.argv[2] researcher = sys.argv[3] note = sys.argv[4] if len(sys.argv) > 4 else "No reason given" reject_rule(rule_id, researcher, note)
else: print(f"Unknown command: {command}") sys.exit(1)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621"""app.py (v2)-----------CollabCode — Researcher Interface (redesigned).
Four-agent, human-in-the-loop pipeline for qualitative coding ofcollaborative learning transcripts. All stages in one Gradio application.
Pipeline-------- 1. Parse Upload transcript → confirm structure [human confirms] 2. Agent 0 Topical section detection → researcher edits [human edits] 3. Agent 1a Episode boundary detection → researcher adjusts [human adjusts] 4. Agent 1b Dimension coding per section → researcher codes [human codes] 5. Agreement Upload R2 coding → kappa gate → disagreements [human resolves] 6. Rules Agent 2 proposals → approve / reject [human decides]
References----------Settles, B. (2012). Active learning. Morgan & Claypool.Amershi et al. (2014). Power to the people. IEEE Intelligent Systems, 29(4).Monarch, R. (2021). Human-in-the-loop machine learning. Manning.Krippendorff, K. (2004). Content analysis (ch. 7). Sage.Cohen, J. (1960). Educational and Psychological Measurement, 20(1), 37-46.Landis & Koch (1977). Biometrics, 33(1), 159-174.Meier, Spada & Rummel (2007). IJCSCL, 2(1), 63-86.Rummel & Spada (2005). Journal of the Learning Sciences, 14(2)."""
import jsonimport html as html_libimport tempfilefrom pathlib import Pathfrom datetime import timedelta
import gradio as gr
from transcript_parser import parse_transcriptfrom agent0_sectioner import run_sectioningfrom agent1a_boundary import propose_boundaries, boundaries_to_segmentsfrom agent1b_coder import code_sectionfrom kappa_calculator import ( calculate_kappa_report, resolve_disagreement, discard_disagreement,)from agent2_learner import list_pending_rules, approve_rule, reject_rule
SESSIONS_ROOT = Path("sessions")
# ---------------------------------------------------------------------------# Visual design constants# ---------------------------------------------------------------------------
CSS = """/* ── Layout ─────────────────────────────────────────────────────────── */.gradio-container { max-width: 1160px !important; margin: 0 auto !important; }footer { display: none !important; }
/* ── Pipeline stepper ────────────────────────────────────────────────── */.pipeline-bar { display: flex; align-items: center; gap: 0; background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 10px; padding: 12px 20px; margin-bottom: 8px;}.step-done { color: #16a34a; font-weight: 600; font-size: 0.9em; }.step-active { color: #2563eb; font-weight: 700; font-size: 0.9em; }.step-pending { color: #94a3b8; font-size: 0.9em; }.step-sep { color: #cbd5e1; margin: 0 10px; }
/* ── Section cards ───────────────────────────────────────────────────── */.section-cards { display: flex; gap: 8px; flex-wrap: wrap; margin: 10px 0 6px 0; }.sec-card { flex: 1; min-width: 140px; border-radius: 8px; padding: 10px 14px; border: 1px solid #e2e8f0;}.sec-done { background: #f0fdf4; border-color: #86efac !important; }.sec-active { background: #eff6ff; border-color: #93c5fd !important; border-width: 2px !important; }.sec-pending { background: #f8fafc; border-color: #e2e8f0 !important; }
/* ── Status banners ──────────────────────────────────────────────────── */.banner { border-radius: 8px; padding: 12px 16px; margin: 8px 0; font-size: 0.93em; line-height: 1.5;}.banner-warn { background: #fffbeb; border: 1px solid #fbbf24; color: #92400e; }.banner-error { background: #fef2f2; border: 1px solid #fca5a5; color: #991b1b; }.banner-success { background: #f0fdf4; border: 1px solid #86efac; color: #14532d; }.banner-info { background: #eff6ff; border: 1px solid #93c5fd; color: #1e3a8a; }
/* ── Cards ───────────────────────────────────────────────────────────── */.card { background: white; border: 1px solid #e2e8f0; border-radius: 10px; padding: 16px 20px; margin: 8px 0;}.card-header { font-size: 0.8em; font-weight: 700; letter-spacing: 0.08em; color: #64748b; text-transform: uppercase; margin-bottom: 8px;}
/* ── Episode table ───────────────────────────────────────────────────── */.ep-table { border-collapse: collapse; width: 100%; font-size: 0.88em; }.ep-table th { background: #f1f5f9; padding: 7px 10px; text-align: left; font-weight: 600; color: #475569;}.ep-table td { padding: 6px 10px; border-top: 1px solid #f1f5f9; }.ep-table .boundary-row td { background: #fefce8; color: #78350f; font-size: 0.83em; border-top: 1px dashed #fde68a;}
/* ── Kappa visualization ─────────────────────────────────────────────── */.kappa-score { font-size: 2.8em; font-weight: 800; letter-spacing: -0.02em; }.kappa-bar { height: 8px; background: #e2e8f0; border-radius: 4px; margin: 8px 0; overflow: hidden;}.kappa-bar-fill { height: 100%; border-radius: 4px; transition: width 0.4s; }.dim-bar { height: 6px; background: #e2e8f0; border-radius: 3px; display: inline-block; width: 100px; vertical-align: middle;}.dim-bar-fill { height: 100%; border-radius: 3px; }
/* ── Rule cards ──────────────────────────────────────────────────────── */.rule-card { border: 1px solid #e2e8f0; border-radius: 10px; padding: 16px 20px; margin: 10px 0; background: white;}.rule-type-badge { display: inline-block; font-size: 0.75em; font-weight: 700; letter-spacing: 0.06em; text-transform: uppercase; border-radius: 4px; padding: 2px 8px; margin-bottom: 8px;}.badge-boundary { background: #dbeafe; color: #1d4ed8; }.badge-disambiguation { background: #fce7f3; color: #9d174d; }.badge-marker { background: #dcfce7; color: #15803d; }
/* ── Coding UI ───────────────────────────────────────────────────────── */.progress-mini { height: 6px; background: #e2e8f0; border-radius: 3px; margin: 6px 0 10px 0; overflow: hidden;}.progress-mini-fill { height: 100%; background: #3b82f6; border-radius: 3px; }"""
# ---------------------------------------------------------------------------# Dimension registry# ---------------------------------------------------------------------------
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"{did} — {label}" for did, label, _ in DIMENSIONS]DIM_ID_FROM_CHOICE = {f"{did} — {label}": did for did, label, _ in DIMENSIONS}DIM_DESC_FROM_ID = {did: desc for did, _, desc in DIMENSIONS}DIM_BADGE_COLOR = { "D1": "#dbeafe", "D2": "#e0f2fe", "D3": "#dcfce7", "D4": "#fef9c3", "D5": "#fce7f3", "D6": "#ede9fe", "D7": "#ffedd5", "D8": "#f0fdf4", "D9": "#fef2f2", "NS": "#f1f5f9", "NA": "#f8fafc",}
# ===========================================================================# HTML GENERATION HELPERS# ===========================================================================
def _h(text: str) -> str: """HTML-escape a string.""" return html_lib.escape(str(text))
def _pipeline_html(stage: str) -> str: """Render the pipeline progress stepper as HTML.""" stages = [ ("upload", "1 · Parse"), ("parsed", "2 · Sections"), ("sectioned", "3 · Review"), ("coding", "4 · Code"), ("complete", "5 · Done"), ] order = [s[0] for s in stages] cur = order.index(stage) if stage in order else 0
parts = [] for i, (s, label) in enumerate(stages): if i < cur: cls = "step-done" prefix = "✓ " elif i == cur: cls = "step-active" prefix = "▶ " else: cls = "step-pending" prefix = "" parts.append(f'<span class="{cls}">{prefix}{_h(label)}</span>')
inner = '<span class="step-sep">→</span>'.join(parts) return ( f'<div class="pipeline-bar">' f'<span style="font-size:0.78em;font-weight:700;letter-spacing:0.1em;' f'color:#94a3b8;margin-right:16px">PIPELINE</span>' f'{inner}</div>' )
def _section_cards_html(sections: list[dict], stages: dict, current_idx: int) -> str: """Render section status cards as HTML.""" if not sections: return ""
cards = [] for i, s in enumerate(sections): stage = stages.get(s["section_id"], "pending") if stage == "done": cls, icon, color = "sec-done", "✓", "#16a34a" elif i == current_idx: cls, icon, color = "sec-active", "◑", "#2563eb" else: cls, icon, color = "sec-pending", "○", "#94a3b8"
n = s["end_turn_id"] - s["start_turn_id"] + 1 cards.append( f'<div class="sec-card {cls}">' f'<div style="font-weight:700;color:{color};font-size:0.9em">' f'{icon} {_h(s["label"])}</div>' f'<div style="color:#94a3b8;font-size:0.78em;margin-top:3px">' f'{_h(s["start_time"])}–{_h(s["end_time"])} · {n} turns</div>' f'</div>' )
return f'<div class="section-cards">{"".join(cards)}</div>'
def _episode_table_html(turns: list[dict], boundaries: list[dict]) -> str: """Render proposed episodes and boundaries as an HTML table.""" if not turns: return "<p><em>No turns loaded.</em></p>"
turn_ids = sorted(t["turn_id"] for t in turns) bmap = {b["after_turn_id"]: b for b in boundaries}
cut_starts = [turn_ids[0]] for b in sorted(boundaries, key=lambda x: x["after_turn_id"]): after = b["after_turn_id"] if after in turn_ids: idx = turn_ids.index(after) if idx < len(turn_ids) - 1: cut_starts.append(turn_ids[idx + 1])
rows = ( "<tr>" "<th class='ep-table'>Episode</th>" "<th class='ep-table'>Turns</th>" "<th class='ep-table'>Count</th>" "</tr>" ) for i, start in enumerate(cut_starts): if i + 1 < len(cut_starts): end = turn_ids[turn_ids.index(cut_starts[i + 1]) - 1] else: end = turn_ids[-1] n = end - start + 1 bg = "#f8fafc" if i % 2 else "white" rows += ( f'<tr style="background:{bg}">' f'<td style="font-weight:600">ep{i+1:02d}</td>' f'<td>turns {start}–{end}</td>' f'<td style="color:#64748b">{n}</td>' f'</tr>' ) if i < len(cut_starts) - 1: after_turn = cut_starts[i + 1] - 1 b = bmap.get(after_turn, {}) sig = _h(b.get("boundary_signal", "boundary")) conf = b.get("confidence", "?") rat = _h(b.get("rationale", "")) conf_color = {"high": "#16a34a", "medium": "#d97706", "low": "#dc2626"}.get(conf, "#64748b") rows += ( f'<tr class="boundary-row">' f'<td colspan="3">' f'─── after turn {after_turn} · <em>{sig}</em> · ' f'<strong style="color:{conf_color}">{conf}</strong> — {rat}' f'</td></tr>' )
n_eps = len(cut_starts) n_bounds = len(boundaries) return ( f'<div class="card-header">{n_bounds} boundary{"" if n_bounds == 1 else "ies"}' f' → {n_eps} episode{"" if n_eps == 1 else "s"}</div>' f'<div style="overflow-x:auto">' f'<table class="ep-table" style="width:100%;border-collapse:collapse">' f'{rows}</table></div>' )
def _uncertainty_html(seg: dict) -> str: """Render an uncertainty warning banner, or empty string if not uncertain.""" if not seg.get("uncertain"): return "" note = _h(seg.get("uncertainty_note") or "") return ( f'<div class="banner banner-warn">' f'<strong>⚠ AI flagged uncertain</strong> — {note}' f'</div>' )
def _dim_desc_html(choice: str) -> str: """Render a description box for the currently selected dimension.""" if not choice: return "" did = DIM_ID_FROM_CHOICE.get(choice, "") desc = DIM_DESC_FROM_ID.get(did, "") if not desc: return "" bg = DIM_BADGE_COLOR.get(did, "#f8fafc") return ( f'<div style="background:{bg};border-left:3px solid #3b82f6;' f'border-radius:0 6px 6px 0;padding:8px 12px;font-size:0.88em;color:#1e40af">' f'{_h(desc)}</div>' )
def _kappa_html(report: dict) -> str: """Render a visual kappa report card.""" kappa = report.get("overall_kappa", 0.0) interp = report.get("kappa_interpretation", "") gate = report.get("gate_passed", False) n_segs = report.get("n_segments_total", 0) n_dis = len(report.get("segments_in_disagreement", []))
color = "#16a34a" if gate else "#dc2626" icon = "✓" if gate else "✗" pct = int(min(max(kappa, 0) * 100, 100))
# Threshold marker at 70 % threshold_left = 70
# Per-dimension rows dim_rows = "" for dim, k in sorted((report.get("kappa_per_dimension") or {}).items()): if k is None: continue k_pct = int(min(max(k, 0) * 100, 100)) k_color = "#16a34a" if k >= 0.70 else "#f59e0b" if k >= 0.50 else "#dc2626" dim_rows += ( f'<tr>' f'<td style="padding:4px 8px;font-weight:600;width:40px">{_h(dim)}</td>' f'<td style="padding:4px 8px">' f'<div class="dim-bar"><div class="dim-bar-fill" ' f'style="width:{k_pct}%;background:{k_color}"></div></div>' f'</td>' f'<td style="padding:4px 8px;color:{k_color};font-weight:600">{k:.3f}</td>' f'</tr>' )
if not dim_rows: dim_rows = '<tr><td colspan="3" style="color:#94a3b8;padding:4px 8px">No per-dimension data.</td></tr>'
return ( f'<div class="card">' f'<div style="display:flex;align-items:baseline;gap:16px;margin-bottom:6px">' f'<span class="kappa-score" style="color:{color}">{kappa:.3f}</span>' f'<div>' f'<div style="font-weight:700;color:{color};font-size:1.05em">{icon} {_h(interp)}</div>' f'<div style="color:#64748b;font-size:0.82em">threshold κ=0.70 — Landis & Koch (1977)</div>' f'</div></div>' # bar with threshold marker 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:{color};border-radius:5px"></div>' f'<div style="position:absolute;left:{threshold_left}%;top:-3px;height:16px;' f'width:2px;background:#64748b"></div>' f'</div>' f'<div style="color:#64748b;font-size:0.85em;margin-bottom:14px">' f'{n_segs} segments · {n_dis} disagreement{"s" if n_dis != 1 else ""}' f'</div>' f'<div class="card-header">Per-Dimension Agreement</div>' f'<table style="border-collapse:collapse;font-size:0.88em">' f'<tr style="background:#f8fafc">' f'<th style="padding:4px 8px;text-align:left">Dim</th>' f'<th style="padding:4px 8px;text-align:left">Agreement</th>' f'<th style="padding:4px 8px;text-align:left">κ</th>' f'</tr>' f'{dim_rows}</table></div>' )
def _rules_html(rules: list[dict]) -> str: """Render pending rules as styled cards.""" if not rules: return '<div class="banner banner-success">No rules pending review.</div>'
TYPE_BADGE = { "boundary_clarification": ("badge-boundary", "Boundary Clarification"), "disambiguation_rule": ("badge-disambiguation", "Disambiguation Rule"), "behavioral_marker_refinement": ("badge-marker", "Marker Refinement"), }
cards = [] for r in rules: rule_type = r.get("rule_type", "unknown") badge_cls, badge_label = TYPE_BADGE.get(rule_type, ("badge-marker", rule_type)) dims = ", ".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'<div class="rule-card">' f'<div style="display:flex;justify-content:space-between;align-items:flex-start">' f'<div>' f'<span class="rule-type-badge {badge_cls}">{badge_label}</span>' f'<span style="margin-left:8px;color:#94a3b8;font-size:0.8em">' f'{rid} · {created}</span>' f'</div>' f'<span style="font-size:0.82em;color:#64748b">dims: {_h(dims)}</span>' f'</div>' f'<p style="font-size:0.95em;margin:10px 0 6px 0">{desc}</p>' f'<p style="font-size:0.85em;color:#475569;margin:0 0 4px 0">' f'<strong>Rationale:</strong> {rat}</p>' f'<div style="display:flex;gap:16px;font-size:0.83em;color:#64748b">' f'<span>Confidence: <strong>{conf}</strong></span>' + (f'<span>Note: {note}</span>' if note else '') + f'</div>' f'</div>' )
return "".join(cards)
def _coding_progress_html(state: dict) -> str: """Render coding progress as an HTML progress block.""" sections = state.get("sections", []) idx = state.get("section_idx", 0) segs = _current_section_segments(state) codings = state.get("codings", {}) cidx = state.get("coding_idx", 0)
if not segs: return ""
coded = sum(1 for s in segs if codings.get(s["segment_id"], {}).get("dimension_id")) total = len(segs) pct = int(coded / total * 100) if total else 0 sec = sections[idx] if idx < len(sections) else {} ep_num = min(cidx, total - 1) + 1
return ( f'<div>' f'<div style="font-size:0.82em;color:#64748b;margin-bottom:2px">' f'Section {idx + 1} of {len(sections)} — ' f'<strong style="color:#1e293b">{_h(sec.get("label", ""))}</strong>' f' · Episode {ep_num} of {total}' f'</div>' f'<div class="progress-mini">' f'<div class="progress-mini-fill" style="width:{pct}%"></div>' f'</div>' f'<div style="font-size:0.78em;color:#94a3b8">{coded} of {total} coded ({pct}%)</div>' f'</div>' )
# ===========================================================================# STATE HELPERS# ===========================================================================
def _empty_state() -> dict: return { "session_id": "", "researcher_id": "", "turns": [], "sections": [], "section_idx": 0, "section_stages": {}, "section_boundaries": {}, "section_segments": {}, "section_segments_coded": {}, "coding_idx": 0, "codings": {}, "stage": "upload", "kappa_report": None, "_last_error": None, }
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) if not sec: return [] return state["section_segments_coded"].get(sec["section_id"], [])
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 )
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")} (d / "app_state.json").write_text( json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8" ) except Exception: pass
def _seconds_to_hms(s: float) -> str: return str(timedelta(seconds=int(s)))
# ===========================================================================# CODING UI 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 "" 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", "") tags = [] if seg.get("confident"): 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()
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)
def _render_coding(state: dict) -> tuple: segs = _current_section_segments(state) codings = state.get("codings", {}) cidx = state.get("coding_idx", 0)
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( codings.get(s["segment_id"], {}).get("dimension_id") for s in segs ) jump_choices = [_segment_dropdown_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), _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), )
# ===========================================================================# BACKEND CALLBACKS# ===========================================================================
# ── 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.") if not researcher_id.strip(): raise gr.Error("Enter your researcher ID.")
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.")
new_state = _empty_state() new_state.update({ "session_id": session_id.strip(), "researcher_id": researcher_id.strip(), "turns": turns, "stage": "parsed", })
d = SESSIONS_ROOT / session_id.strip() d.mkdir(parents=True, exist_ok=True) (d / "parsed_turns.json").write_text( 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" f"| | |\n|---|---|\n" f"| Turns | {len(turns)} |\n" f"| Speakers | {', '.join(speakers)} |\n" f"| Duration | {duration} |\n" )
gr.Info(f"Parsed {len(turns)} turns. Review the summary, then detect sections.") return ( new_state, _pipeline_html("parsed"), summary_md, gr.update(visible=True), # col_agent0 )
# ── Stage 2: Agent 0 section detection ───────────────────────────────────
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), "", "", )
try: 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
sections = result["sections"] if not sections: raise gr.Error("Agent 0 returned no sections. Try again or check the transcript.")
warnings = result.get("warnings", []) if warnings: gr.Warning("Section coverage warnings detected — check the transcript range.")
state = dict(state) state["sections"] = sections state["section_stages"] = {s["section_id"]: "pending" for s in sections} state["stage"] = "sectioned"
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", "") sections_md = ( "| # | Label | Turns | Time |\n|---|---|---|---|\n" + "\n".join( f"| {s['section_id']} | {s['label']} | " f"{s['start_turn_id']}–{s['end_turn_id']} | " f"{s['start_time']}–{s['end_time']} |" for s in sections ) ) labels_txt = "\n".join(s["label"] for s in sections)
gr.Info(f"{len(sections)} sections detected. Review and edit labels, then confirm.") yield ( state, _pipeline_html("sectioned"), gr.update(visible=True), # col_sections sections_md + (f"\n\n*{overview}*" if overview else ""), labels_txt, )
# ── 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." )
confirmed = [] for i, s in enumerate(sections): updated = dict(s) if i < len(labels): updated["label"] = labels[i] confirmed.append(updated)
state = dict(state) state["sections"] = confirmed state["section_idx"] = 0 state["section_stages"] = {s["section_id"]: "pending" for s in confirmed} state["stage"] = "coding"
d = _session_dir(state) (d / "sections_confirmed.json").write_text( json.dumps(confirmed, indent=2, ensure_ascii=False), encoding="utf-8" ) _persist(state)
sec = confirmed[0] n = sec["end_turn_id"] - sec["start_turn_id"] + 1 hdr = ( f"### Section 1 of {len(confirmed)}: {sec['label']}\n" 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.") 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 )
# ── Stage 3a: Agent 1a boundary detection ────────────────────────────────
def fn_propose_boundaries(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 found for section {sec['section_id']}.")
yield (state, "⏳ Detecting episode boundaries…", gr.update(visible=False), "", "")
try: 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
boundaries = result["boundaries"] 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.")
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"
ids_text = ", ".join(str(b["after_turn_id"]) for b in boundaries)
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." )
yield ( state, status, gr.update(visible=True), _episode_table_html(turns, boundaries), ids_text, )
# ── Stage 3b: 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.")
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 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. Enter integers only.") 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.", }) 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.")
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, )
try: coded = code_section(section=sec, segments=segments) except Exception as e: raise gr.Error(f"Agent 1b failed: {e}") from e
state["section_segments_coded"][sec["section_id"]] = coded state["section_stages"][sec["section_id"]] = "coding" state["coding_idx"] = 0
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." if n_uncertain: msg += f" **{n_uncertain} flagged uncertain** — check ⚠ markers." msg += " AI proposals hidden — code independently, then reveal if needed."
gr.Info(f"{len(coded)} segments ready for coding.") yield ( state, msg, gr.update(visible=True), *_render_coding(state), )
# ── Stage 3c: Navigate segments ──────────────────────────────────────────
def fn_navigate(direction: int, dim_choice: str, comment: str, state: dict): segs = _current_section_segments(state) if not segs: return state, *_render_coding(state)
idx = state.get("coding_idx", 0) codings = dict(state.get("codings", {})) sid = segs[idx]["segment_id"]
if dim_choice: codings[sid] = { "dimension_id": DIM_ID_FROM_CHOICE[dim_choice], "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): 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] state = dict(state) if label in labels: state["coding_idx"] = labels.index(label) return state, *_render_coding(state)
def fn_reveal_proposal(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)] return gr.update(value=_proposal_md(seg), visible=True)
def fn_update_dim_desc(choice: str): return _dim_desc_html(choice or "")
# ── Stage 3d: 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(), }
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"
next_idx = sec_idx + 1
if next_idx >= len(sections): # All done state["stage"] = "complete" _write_coding_file(state) _persist(state) gr.Info("All sections coded! Download your coding file.") return ( state, _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 )
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"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']}") 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 )
# ── Download coding file ──────────────────────────────────────────────────
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)
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", ""), } for s in all_segs ], }
segments_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" ) 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
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
# ── Agreement tab ─────────────────────────────────────────────────────────
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.")
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." ) if not segs_path.exists(): raise gr.Error( "Segments file not found. Make sure you completed the coding pipeline." )
r2_path = d / "coding_R2.json" r2_path.write_bytes(Path(r2_file.name).read_bytes())
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
state = dict(state) state["kappa_report"] = report
gate = report.get("gate_passed", False) n_dis = len(report.get("segments_in_disagreement", []))
if gate: gr.Info(f"Kappa gate passed! {n_dis} disagreement(s) to resolve.") else: gr.Warning("Kappa below 0.70 threshold — review and re-code before proceeding.")
dis_md = "" if n_dis: dis = report.get("segments_in_disagreement", []) rows = "| Segment | R1 | R2 | Agent |\n|---|---|---|---|\n" for di in dis[:15]: rows += ( f"| `{di['segment_id']}` " 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}"
return ( state, _kappa_html(report), dis_md, gr.update(visible=bool(n_dis)), )
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.") 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) try: resolve_disagreement( report_path=d / "kappa_report.json", segment_id=seg_id.strip(), resolved_dimension=resolved_dim, 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}**"
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) try: discard_disagreement( report_path=d / "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()}`"
# ── Rule review tab ───────────────────────────────────────────────────────
def fn_load_rules(): try: pending = list_pending_rules() except Exception as e: raise gr.Error(f"Could not load rules: {e}") from e 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): 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()}."
def fn_reject_rule(choice: str, researcher_id: 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.") 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."
# ===========================================================================# UI DEFINITION# ===========================================================================
with gr.Blocks(title="CollabCode", css=CSS, theme=gr.themes.Soft()) as demo:
state = gr.State(_empty_state())
# ── Header ─────────────────────────────────────────────────────────── gr.HTML( '<div style="padding:20px 0 8px 0">' '<h1 style="font-size:1.6em;font-weight:800;color:#1e293b;margin:0">' 'CollabCode</h1>' '<p style="color:#64748b;margin:2px 0 0 0;font-size:0.92em">' 'Human-in-the-loop pipeline for collaborative learning transcript analysis' '</p></div>' )
# ── Pipeline progress stepper (dynamic) ────────────────────────────── pipeline_html = gr.HTML(_pipeline_html("upload"))
with gr.Tabs():
# ================================================================== # TAB 1: 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('<hr style="margin:8px 0;border-color:#e2e8f0">') 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('<hr style="margin:8px 0;border-color:#e2e8f0">') 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('<hr style="margin:8px 0;border-color:#e2e8f0">') 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('<div class="card" style="margin:8px 0">' '<div class="card-header">Episode Structure</div>') boundary_display_html = gr.HTML() gr.HTML('</div>') 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.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, ) dim_desc_html_comp = gr.HTML() comment_box = gr.Textbox( label="Comment (optional)", lines=2, placeholder="Notes for disagreement review…" ) reveal_btn = gr.Button( "Reveal AI proposal", variant="secondary", size="sm" ) gr.Markdown( '<span style="color:#94a3b8;font-size:0.8em">' 'AI proposal hidden by default — code independently first ' '(Settles 2012)</span>' ) 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( '<div class="banner banner-success" style="margin:16px 0">' '<strong>All sections coded!</strong> Download your file and share it ' 'with your co-researcher for agreement calculation.' '</div>' ) download_btn = gr.Button("Download Coding File", variant="primary") download_file = gr.File(visible=False)
# ================================================================== # TAB 2: Agreement & Kappa # ================================================================== 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('<div class="banner banner-info">Resolve each disagreement below. ' 'Resolved segments go to Tier 3 for Agent 2 to learn from.</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="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()
# ================================================================== # TAB 3: Rule 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()
# ===================================================================== # OUTPUT LISTS # =====================================================================
CODING_OUTPUTS = [ coding_progress_html_comp, segment_jump, turns_display_md, uncertainty_html_comp, proposal_md_comp, dim_radio, dim_desc_html_comp, comment_box, next_section_btn, ]
NEXT_SECTION_OUTPUTS = [ state, pipeline_html, sections_overview_html, section_header_md, col_boundary_btn, col_boundary_review, col_coding, col_complete, ]
# ===================================================================== # CALLBACK WIRING # =====================================================================
parse_btn.click( fn=fn_parse, inputs=[transcript_file, session_id_box, researcher_id_box, state], outputs=[state, pipeline_html, parse_status, col_agent0], ).then(fn=lambda: gr.update(visible=True), outputs=[parse_status])
agent0_btn.click( fn=fn_run_agent0, inputs=[state], outputs=[state, pipeline_html, col_sections, sections_display_md, sections_labels_box], )
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, ], )
propose_btn.click( fn=fn_propose_boundaries, inputs=[state], outputs=[state, boundary_status, col_boundary_review, boundary_display_html, boundary_ids_box], )
confirm_boundaries_btn.click( fn=fn_confirm_and_code, inputs=[boundary_ids_box, state], outputs=[state, code_status, col_coding] + CODING_OUTPUTS, )
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, 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], )
next_section_btn.click( fn=fn_next_section, inputs=[dim_radio, comment_box, state], outputs=NEXT_SECTION_OUTPUTS, )
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], )
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], )
# Rule review tab 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], )
reject_rule_btn.click( fn=fn_reject_rule, inputs=[rule_selector, rule_researcher_id, rule_note], outputs=[rule_status], )
if __name__ == "__main__": demo.launch(theme=gr.themes.Soft())12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849{ "_meta": { "version": "1.0", "locked": true, "description": "Hard coding rules that Agent 1 must always follow. These are never modified by Agent 2." }, "rules": [ { "rule_id": "R01", "label": "One dimension per segment", "description": "Each segment must be assigned exactly one dimension code. If multiple dimensions are observable, assign the most dominant one and flag the segment as uncertain with a note on the competing dimension." }, { "rule_id": "R02", "label": "Segments are behaviorally defined", "description": "A segment boundary is determined by a shift in the TYPE of collaborative behavior, not by topic change in the conversational sense. Ask: has the behavioral function of the exchange changed?" }, { "rule_id": "R03", "label": "Minimum segment length", "description": "A segment must contain at least 2 speaker turns. A single utterance is not sufficient to establish a behavioral episode unless it is a clear, unambiguous closing act (e.g. a consensus statement)." }, { "rule_id": "R04", "label": "Open flag on window boundary", "description": "If at the end of a processing window the current segment has not reached a natural behavioral close, the segment must be flagged as OPEN. The next window must begin from the first turn of the open segment, not from where the window ended." }, { "rule_id": "R05", "label": "Uncertainty flag", "description": "If Agent 1 is uncertain between two dimensions, it must still assign one dimension (the most likely), set uncertain=true, and name the competing dimension in the uncertainty_note field." }, { "rule_id": "R06", "label": "Rationale required", "description": "Every segment must include a rationale of 1-2 sentences citing specific observable behaviors from the turns that justify the dimension assignment." }, { "rule_id": "R07", "label": "No inference beyond the text", "description": "Agent 1 must only code what is observable in the transcript. It must not infer mental states, intentions, or off-transcript behavior. If something is ambiguous, use the uncertainty flag." }, { "rule_id": "R08", "label": "Negative episodes are valid", "description": "A dimension can be coded even when the behavior is absent or performed poorly. For example, failed dialogue management (overlapping speech) is still coded as D2. The quality of the behavior is for the researcher to evaluate." } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149{ "_meta": { "version": "1.0", "locked": true, "description": "Core dimension definitions for collaborative coding. This file is authored by the research team and must never be modified by Agent 2. These definitions are the ground truth of the coding framework.", "total_dimensions": 9 }, "dimensions": [ { "id": "D1", "code": "mutual_understanding", "label": "Sustaining Mutual Understanding", "summary": "Speakers ensure their contributions are understood and actively seek and give evidence of comprehension.", "full_definition": "Speakers make their contributions understandable for their collaboration partner, e.g., by avoiding or explaining technical terms from their domain of expertise or by paraphrasing longer passages of text from their materials, rather than reading them aloud to their partner. They make sure they have been understood by eliciting feedback from their partner. Listeners focus their attention on what the speaker is saying and give verbal feedback on their understanding (backchannels, paraphrases), demonstrate their understanding in an appropriate response, or ask for clarification.", "key_behavioral_markers": [ "Speaker explains or avoids domain-specific jargon", "Speaker paraphrases material rather than reading aloud", "Speaker explicitly checks for comprehension (e.g. 'Did you understand?')", "Listener gives backchannel feedback (e.g. 'Mhm', 'I see')", "Listener paraphrases back what was said", "Listener asks for clarification", "Speaker confirms or corrects listener's paraphrase" ] }, { "id": "D2", "code": "dialogue_management", "label": "Dialogue Management", "summary": "A smooth conversational flow is maintained with clear turn-taking and minimal overlap or confusion.", "full_definition": "A smooth flow of communication is maintained in which little time is lost due to overlaps in speech or confusion about whose turn it is to talk. Turn-taking is often facilitated by means of questions or explicit handovers. Speakers avoid redundant phrases and fillers at the end of a turn, thus signalling they are done and the partner may now speak. To the observer it is always clear who is talking and who is listening. Before partners start a new conversation after a phase of parallel individual work, they make sure they have their partner's attention.", "key_behavioral_markers": [ "Explicit turn handover (e.g. 'What do you think?', 'You go!')", "Attention-getting before speaking (e.g. calling partner's name)", "Meta-statements to initiate conversation (e.g. 'Can I ask you something?')", "Overlapping speech causing confusion", "Unclear who holds the floor", "Excessive fillers or redundant phrases signalling incomplete turn", "Partner interrupts without acknowledgement" ] }, { "id": "D3", "code": "information_pooling", "label": "Information Pooling", "summary": "Partners actively share, elaborate, and elicit domain-specific information relevant to the joint task.", "full_definition": "Partners try to gather as many solution-relevant pieces of information as possible. New information is introduced in an elaborated way, for example by relating it to facts that have already been established, or by pointing out its relevance for the solution. Participants elicit domain-specific knowledge from their partner, using their expertise as a resource. At the same time they make sure that the aspects that are important from the perspective of their own domain are taken into account and they take on the task of clarifying any information needs that relate to their domain of expertise.", "key_behavioral_markers": [ "Partner introduces new information and explains its relevance", "Partner connects new information to already established facts", "Partner explicitly elicits domain knowledge from the other (e.g. 'What does your field say about this?')", "Partner shares discipline-specific diagnostic criteria or knowledge", "Partner asks clarifying questions about the other's domain", "Partner ensures their own domain perspective is included" ] }, { "id": "D4", "code": "reaching_consensus", "label": "Reaching Consensus", "summary": "Partners critically evaluate options and arguments before reaching a clearly identifiable joint decision.", "full_definition": "Decisions for alternatives on the way to a final solution stand at the end of a critical discussion in which partners have collected and evaluated arguments for and against the available options. If partners initially prefer different options, they exchange arguments until a consensus is reached that can be grounded in facts. Even if partners agree from the start, they still evaluate their shared preference critically and search for supporting as well as challenging facts. The point at which a final decision is reached is clearly identifiable.", "key_behavioral_markers": [ "Partners explicitly state and compare different options", "Partners exchange arguments for and against an option", "Partners ground their preference in case facts or evidence", "Critical evaluation even when initial agreement is present", "A clear moment of joint decision or agreement", "Agreed decision is not revisited without new information" ] }, { "id": "D5", "code": "task_division", "label": "Task Division", "summary": "The task is systematically divided into subtasks with clear individual and joint work phases.", "full_definition": "The task is divided into subtasks. Partners proceed systematically, taking on one step toward the solution at a time with a clear goal or question guiding each work phase. Individual as well as joint phases of work are established, either in a plan set up at the beginning or in short-term arrangements agreed upon as they go. Partners define and take on individual subtasks that match their expertise and resources. The work is divided equally so neither collaborator has to wait idly.", "key_behavioral_markers": [ "Partners explicitly propose or agree on a plan or structure", "Partners assign subtasks to individuals", "Partners initiate or close an individual work phase", "Partners initiate or close a joint work phase", "Partners refer to a previously established plan", "One partner waits while the other completes a task (negative marker)", "Subtask assignments match each partner's expertise" ] }, { "id": "D6", "code": "time_management", "label": "Time Management", "summary": "Partners actively monitor time and adjust their work pace to ensure task completion within the allotted period.", "full_definition": "Partners monitor the remaining time throughout their cooperation and make sure to finish the current subtask or topic with enough time to complete the remaining subtasks. They check whether the current topic is important enough to spend more time on, and remind one another of the time remaining. They might also set up and monitor adherence to a time schedule in which each subtask is allotted a realistic amount of time.", "key_behavioral_markers": [ "Partner explicitly mentions remaining time", "Partner suggests moving on due to time pressure", "Partner proposes or references a time schedule", "Partner checks whether current topic warrants more time", "Partner reminds the other of a time constraint", "Rushing or skipping steps due to time running out (negative marker)" ] }, { "id": "D7", "code": "technical_coordination", "label": "Technical Coordination", "summary": "Partners manage the use of shared technical tools effectively, including editor access and application switching.", "full_definition": "Partners master the basic technical skills that allow them to use the technical tools to their advantage. Collaborators arrange who may write into the shared editor at which time. At least one partner makes use of their individual text editor, allowing for phases of parallel writing.", "key_behavioral_markers": [ "Partner negotiates who writes in the shared editor", "Partner switches between applications or tools", "Partner uses copy-paste or other basic technical functions", "Partner uses their individual editor for parallel work", "Technical difficulty or confusion about tool use (negative marker)", "Conflict over simultaneous editing (negative marker)" ] }, { "id": "D8", "code": "reciprocal_interaction", "label": "Reciprocal Interaction", "summary": "Partners interact as equals, with mutual respect, constructive criticism, and balanced contribution.", "full_definition": "Partners treat each other with respect and encourage one another to contribute their opinions and perspectives. Critical remarks are constructive and factual, never personal. Partners interact as equals, and decisions are made cooperatively. Since both partners hold equal amounts of unique task-relevant knowledge, they should contribute equally toward the problem solution; the solution process is not dominated by one partner.", "key_behavioral_markers": [ "Partner explicitly invites the other's opinion or perspective", "Critical feedback is framed as task-oriented, not personal", "Decisions are made jointly, not unilaterally", "Both partners contribute roughly equally to the discussion", "One partner dominates or dismisses the other (negative marker)", "Personal or dismissive criticism (negative marker)", "Partner encourages or affirms the other's contribution" ] }, { "id": "D9", "code": "individual_task_orientation", "label": "Individual Task Orientation", "summary": "Each participant actively engages with the task, brings their knowledge and skills to bear, and avoids distraction.", "full_definition": "Each participant actively engages in finding a good solution to the problem, bringing their knowledge and skills to bear. They focus attention on the task and on task-relevant information, avoid distractions, and strive to mobilize their own as well as the partner's skills and resources. The participant shows interest in the task or enjoyment of the work, for example by expressing a wish to help the patient, a general interest in the subject domains, or pride in work considered well done.", "key_behavioral_markers": [ "Partner expresses motivation or interest in the task", "Partner actively contributes task-relevant knowledge", "Partner redirects attention back to the task", "Partner expresses care about the quality of the solution", "Partner is distracted or disengaged (negative marker)", "Partner expresses enjoyment or pride in their work" ] } ]}123456789101112131415161718192021222324252627282930313233343536{ "_meta": { "version": "1.0", "locked": true, "description": "Anchor examples per dimension. These are research-team-authored examples that ground the LLM's interpretation. Agent 2 must never modify this file. New examples may only be added by the research team." }, "examples": [ { "dimension_id": "D1", "type": "positive", "label": "Successful comprehension check and paraphrase", "source": "Study 1, translated", "exchange": [ {"speaker": "Psychology Student (P)", "text": "Did you understand what I just said?"}, {"speaker": "Medical Student (M)", "text": "U-hum. That is, you mean, whether now there is a psychotic component in addition to the depression and the multiple sclerosis?"}, {"speaker": "Psychology Student (P)", "text": "Exactly!"} ], "annotation_note": "P elicits comprehension check. M paraphrases back accurately. P confirms. Classic D1 positive episode." }, { "dimension_id": "D2", "type": "negative", "label": "Overlapping speech causing communication breakdown", "source": "Study 1, translated", "exchange": [ {"speaker": "P", "text": "[It's certainly a depression]"}, {"speaker": "M", "text": "[...has always been]"}, {"speaker": "M", "text": "[Mhm, that's] sure"}, {"speaker": "P", "text": "[I don't understand you]"}, {"speaker": "M", "text": "[But schizophrenia... schizophrenia] I can't read that."}, {"speaker": "P", "text": "[It's certainly a depression... Sorry?]"} ], "annotation_note": "Brackets indicate simultaneous speech. Repeated overlaps, confusion about the floor, neither partner can complete a thought. Classic D2 negative episode." } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569"""kappa_calculator.py-------------------Calculates Cohen's Kappa between two researcher codings of the sameproposed segments from Agent 1.
Assumptions (prototype):- Both researchers accept Agent 1's segment boundaries- Only the dimension label (D1-D9) is the unit of agreement- Boundary concerns are captured as free-text comments, not in the metric- Kappa gate threshold: 0.70
Outputs a structured kappa_report.json to the session folder."""
import jsonfrom pathlib import Pathfrom datetime import datetime, timezonefrom collections import defaultdictfrom typing import Optional
# ---------------------------------------------------------------------------# Constants# ---------------------------------------------------------------------------
KAPPA_THRESHOLD = 0.70DIMENSIONS = ["D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "NS", "NA"]
# ---------------------------------------------------------------------------# Data loaders# ---------------------------------------------------------------------------
def load_coding(filepath: Path) -> dict: """ Load a researcher coding file. Expected structure: { "researcher_id": "R1", "session_id": "dyad_12", "codings": [ { "segment_id": "...", "dimension_id": "D1", "comment": "optional free text" }, ... ] } """ data = json.loads(filepath.read_text(encoding="utf-8")) if "codings" not in data: raise ValueError(f"Coding file missing 'codings' key: {filepath}") if "researcher_id" not in data: raise ValueError(f"Coding file missing 'researcher_id': {filepath}") return data
def load_proposed_segments(filepath: Path) -> dict: """Load the proposed segments from Agent 1 output.""" data = json.loads(filepath.read_text(encoding="utf-8")) if "segments" not in data: raise ValueError(f"Segments file missing 'segments' key: {filepath}") return {seg["segment_id"]: seg for seg in data["segments"]}
# ---------------------------------------------------------------------------# Validation# ---------------------------------------------------------------------------
def validate_codings( coding_r1: dict, coding_r2: dict, proposed_segments: dict,) -> list[str]: """ Check that both codings cover exactly the same segments. Returns a list of error strings (empty = all good). """ errors = []
ids_r1 = {c["segment_id"] for c in coding_r1["codings"]} ids_r2 = {c["segment_id"] for c in coding_r2["codings"]} ids_proposed = set(proposed_segments.keys())
missing_r1 = ids_proposed - ids_r1 missing_r2 = ids_proposed - ids_r2 extra_r1 = ids_r1 - ids_proposed extra_r2 = ids_r2 - ids_proposed
if missing_r1: errors.append(f"{coding_r1['researcher_id']} has not coded: {sorted(missing_r1)}") if missing_r2: errors.append(f"{coding_r2['researcher_id']} has not coded: {sorted(missing_r2)}") if extra_r1: errors.append(f"{coding_r1['researcher_id']} coded unknown segments: {sorted(extra_r1)}") if extra_r2: errors.append(f"{coding_r2['researcher_id']} coded unknown segments: {sorted(extra_r2)}")
# Check all dimension IDs are valid for coding in [coding_r1, coding_r2]: for c in coding["codings"]: if c["dimension_id"] not in DIMENSIONS: errors.append( f"{coding['researcher_id']} used unknown dimension " f"'{c['dimension_id']}' for segment {c['segment_id']}" )
return errors
# ---------------------------------------------------------------------------# Cohen's Kappa# ---------------------------------------------------------------------------
def _build_aligned_labels( coding_r1: dict, coding_r2: dict,) -> tuple[list[str], list[str], list[str]]: """ Align the two codings by segment_id. Returns (segment_ids, labels_r1, labels_r2) in the same order. """ map_r1 = {c["segment_id"]: c["dimension_id"] for c in coding_r1["codings"]} map_r2 = {c["segment_id"]: c["dimension_id"] for c in coding_r2["codings"]}
# Use only segments present in both (validation already flagged gaps) shared = sorted(set(map_r1.keys()) & set(map_r2.keys()))
labels_r1 = [map_r1[sid] for sid in shared] labels_r2 = [map_r2[sid] for sid in shared]
return shared, labels_r1, labels_r2
def _cohen_kappa(labels_a: list[str], labels_b: list[str]) -> float: """ Calculate Cohen's Kappa for two aligned label lists. Returns float in [-1, 1]. Returns 0.0 if calculation is undefined. """ n = len(labels_a) if n == 0: return 0.0
# Observed agreement p_o = sum(a == b for a, b in zip(labels_a, labels_b)) / n
# Expected agreement categories = set(labels_a) | set(labels_b) p_e = 0.0 for cat in categories: prop_a = labels_a.count(cat) / n prop_b = labels_b.count(cat) / n p_e += prop_a * prop_b
if p_e == 1.0: # Perfect expected agreement — kappa undefined, treat as 1.0 if also perfect observed return 1.0 if p_o == 1.0 else 0.0
return (p_o - p_e) / (1.0 - p_e)
def calculate_overall_kappa( coding_r1: dict, coding_r2: dict,) -> tuple[float, list[str], list[str], list[str]]: """ Calculate overall Cohen's Kappa across all segments. Returns (kappa, segment_ids, labels_r1, labels_r2). """ segment_ids, labels_r1, labels_r2 = _build_aligned_labels(coding_r1, coding_r2) kappa = _cohen_kappa(labels_r1, labels_r2) return kappa, segment_ids, labels_r1, labels_r2
def calculate_per_dimension_kappa( segment_ids: list[str], labels_r1: list[str], labels_r2: list[str],) -> dict[str, Optional[float]]: """ Calculate Kappa restricted to segments where at least one rater assigned a given dimension. This reveals where agreement breaks down.
Returns dict: {"D1": 0.82, "D2": 0.61, ...} Dimensions with fewer than 2 observations return None (insufficient data). """ per_dim = {} for dim in DIMENSIONS: # Include segments where R1 or R2 assigned this dimension indices = [ i for i, (a, b) in enumerate(zip(labels_r1, labels_r2)) if a == dim or b == dim ] if len(indices) < 2: per_dim[dim] = None continue
sub_r1 = [labels_r1[i] for i in indices] sub_r2 = [labels_r2[i] for i in indices] per_dim[dim] = round(_cohen_kappa(sub_r1, sub_r2), 4)
return per_dim
# ---------------------------------------------------------------------------# Disagreement analysis# ---------------------------------------------------------------------------
def identify_disagreements( segment_ids: list[str], labels_r1: list[str], labels_r2: list[str], coding_r1: dict, coding_r2: dict, proposed_segments: dict,) -> list[dict]: """ Build a structured list of all disagreeing segments with context. """ map_comments_r1 = { c["segment_id"]: c.get("comment", "") for c in coding_r1["codings"] } map_comments_r2 = { c["segment_id"]: c.get("comment", "") for c in coding_r2["codings"] }
disagreements = [] for sid, d1, d2 in zip(segment_ids, labels_r1, labels_r2): if d1 != d2: seg = proposed_segments.get(sid, {}) disagreements.append({ "segment_id": sid, "start_time": seg.get("start_time"), "end_time": seg.get("end_time"), "agent1_dimension": seg.get("dimension_id"), "agent1_rationale": seg.get("rationale"), f"{coding_r1['researcher_id']}_dimension": d1, f"{coding_r1['researcher_id']}_comment": map_comments_r1.get(sid, ""), f"{coding_r2['researcher_id']}_dimension": d2, f"{coding_r2['researcher_id']}_comment": map_comments_r2.get(sid, ""), "resolution_status": "pending", "resolved_dimension": None, "resolution_note": "", })
return disagreements
# ---------------------------------------------------------------------------# Kappa interpretation# ---------------------------------------------------------------------------
def interpret_kappa(kappa: float) -> str: if kappa < 0: return "poor — worse than chance" elif kappa < 0.20: return "slight" elif kappa < 0.40: return "fair" elif kappa < 0.60: return "moderate" elif kappa < 0.70: return "substantial — below gate threshold" elif kappa < 0.80: return "substantial — gate passed" elif kappa < 0.90: return "strong" else: return "near-perfect"
# ---------------------------------------------------------------------------# Main report builder# ---------------------------------------------------------------------------
def calculate_kappa_report( session_id: str, coding_r1_path: Path, coding_r2_path: Path, proposed_segments_path: Path, output_path: Optional[Path] = None,) -> dict: """ Full kappa report for a session.
Args: session_id: Identifier for this dyad/transcript session coding_r1_path: Path to Researcher 1 coding JSON coding_r2_path: Path to Researcher 2 coding JSON proposed_segments_path: Path to Agent 1 segments_proposed.json output_path: Where to save the report (optional)
Returns: Full kappa report dict. """ # Load coding_r1 = load_coding(coding_r1_path) coding_r2 = load_coding(coding_r2_path) proposed_segments = load_proposed_segments(proposed_segments_path)
# Validate completeness errors = validate_codings(coding_r1, coding_r2, proposed_segments) if errors: raise ValueError( "Coding validation failed — cannot calculate kappa:\n" + "\n".join(f" - {e}" for e in errors) )
# Overall kappa overall_kappa, segment_ids, labels_r1, labels_r2 = calculate_overall_kappa( coding_r1, coding_r2 )
# Per-dimension kappa per_dim_kappa = calculate_per_dimension_kappa(segment_ids, labels_r1, labels_r2)
# Disagreements disagreements = identify_disagreements( segment_ids, labels_r1, labels_r2, coding_r1, coding_r2, proposed_segments, )
# Gate gate_passed = overall_kappa >= KAPPA_THRESHOLD
# Agreement breakdown n_total = len(segment_ids) n_agree = sum(a == b for a, b in zip(labels_r1, labels_r2)) n_disagree = n_total - n_agree
report = { "session_id": session_id, "timestamp": datetime.now(timezone.utc).isoformat(), "researcher_1": coding_r1["researcher_id"], "researcher_2": coding_r2["researcher_id"], "n_segments_total": n_total, "n_segments_agreed": n_agree, "n_segments_disagreed": n_disagree, "overall_kappa": round(overall_kappa, 4), "kappa_interpretation": interpret_kappa(overall_kappa), "gate_threshold": KAPPA_THRESHOLD, "gate_passed": gate_passed, "kappa_per_dimension": per_dim_kappa, "segments_in_disagreement": [d["segment_id"] for d in disagreements], "disagreements": disagreements, "status": ( "ready_for_agent2" if gate_passed and not disagreements else "pending_disagreement_review" if gate_passed else "below_threshold_review_required" ), }
# Save if output_path: output_path.parent.mkdir(parents=True, exist_ok=True) output_path.write_text( json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8", ) print(f"[Kappa] Report saved to {output_path}")
# Print summary _print_summary(report)
return report
# ---------------------------------------------------------------------------# Disagreement resolution (called after human review)# ---------------------------------------------------------------------------
def resolve_disagreement( report_path: Path, segment_id: str, resolved_dimension: str, resolution_note: str,) -> dict: """ Record a human resolution for a specific disagreement. Updates the report file in place.
Args: report_path: Path to the kappa_report.json segment_id: Which segment was resolved resolved_dimension: The agreed-upon dimension code resolution_note: Why this dimension was chosen
Returns: Updated report dict. """ report = json.loads(report_path.read_text(encoding="utf-8"))
resolved_count = 0 for d in report["disagreements"]: if d["segment_id"] == segment_id: d["resolution_status"] = "resolved" d["resolved_dimension"] = resolved_dimension d["resolution_note"] = resolution_note resolved_count += 1
if resolved_count == 0: raise ValueError(f"Segment {segment_id} not found in disagreements.")
# Check if all disagreements are now handled (resolved or discarded) all_handled = all( d["resolution_status"] in ("resolved", "discarded") for d in report["disagreements"] )
if all_handled and report["gate_passed"]: report["status"] = "ready_for_agent2"
report_path.write_text( json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8", ) print(f"[Kappa] Resolved disagreement for {segment_id} → {resolved_dimension}") return report
def discard_disagreement( report_path: Path, segment_id: str, discard_note: str,) -> dict: """ Mark a disagreement as discarded (unresolvable). Discarded segments are excluded from Agent 2 learning. """ report = json.loads(report_path.read_text(encoding="utf-8"))
for d in report["disagreements"]: if d["segment_id"] == segment_id: d["resolution_status"] = "discarded" d["resolved_dimension"] = None d["resolution_note"] = discard_note
# Check if remaining disagreements are all handled all_handled = all( d["resolution_status"] in ("resolved", "discarded") for d in report["disagreements"] )
if all_handled and report["gate_passed"]: report["status"] = "ready_for_agent2"
report_path.write_text( json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8", ) print(f"[Kappa] Discarded disagreement for {segment_id}") return report
# ---------------------------------------------------------------------------# Console summary# ---------------------------------------------------------------------------
def _print_summary(report: dict) -> None: print("\n" + "═" * 52) print(f" KAPPA REPORT — {report['session_id']}") print("═" * 52) print(f" Researchers : {report['researcher_1']} vs {report['researcher_2']}") print(f" Segments : {report['n_segments_total']} total") print(f" Agreed : {report['n_segments_agreed']}") print(f" Disagreed : {report['n_segments_disagreed']}") print(f" Kappa : {report['overall_kappa']:.4f} ({report['kappa_interpretation']})") print(f" Gate (≥0.70) : {'✓ PASSED' if report['gate_passed'] else '✗ FAILED'}") print(f" Status : {report['status']}") print("\n Per-dimension kappa:") for dim, k in report["kappa_per_dimension"].items(): if k is not None: bar = "▓" * int(k * 20) print(f" {dim} {k:.2f} {bar}") else: print(f" {dim} — (insufficient data)") if report["segments_in_disagreement"]: print(f"\n Disagreeing segments:") for sid in report["segments_in_disagreement"]: print(f" · {sid}") print("═" * 52 + "\n")
# ---------------------------------------------------------------------------# Coding file template generator# ---------------------------------------------------------------------------
def generate_coding_template( proposed_segments_path: Path, researcher_id: str, session_id: str, output_path: Path,) -> None: """ Generate a blank coding template for a researcher to fill in. Each segment has an empty dimension_id and comment field. """ proposed = json.loads(proposed_segments_path.read_text(encoding="utf-8"))
template = { "researcher_id": researcher_id, "session_id": session_id, "instructions": ( "Fill in dimension_id for each segment (D1–D9, NS=Not Sure, NA=Not Applicable). " "Use the comment field for boundary concerns or ambiguity notes. " "Do not change segment_id values." ), "codings": [ { "segment_id": seg["segment_id"], "start_time": seg.get("start_time"), "end_time": seg.get("end_time"), "agent1_label": seg.get("dimension_id"), "agent1_rationale": seg.get("rationale"), "dimension_id": "", "comment": "", } for seg in proposed["segments"] ] }
output_path.parent.mkdir(parents=True, exist_ok=True) output_path.write_text( json.dumps(template, indent=2, ensure_ascii=False), encoding="utf-8", ) print(f"[Kappa] Coding template for {researcher_id} saved to {output_path}")
# ---------------------------------------------------------------------------# CLI# ---------------------------------------------------------------------------
if __name__ == "__main__": import sys
if len(sys.argv) < 2: print("Usage:") print(" Calculate kappa:") print(" python kappa_calculator.py calc <session_id> <r1.json> <r2.json> <segments.json> [report.json]") print(" Generate coding template:") print(" python kappa_calculator.py template <segments.json> <researcher_id> <session_id> <output.json>") sys.exit(1)
command = sys.argv[1]
if command == "calc": session_id = sys.argv[2] r1_path = Path(sys.argv[3]) r2_path = Path(sys.argv[4]) segments_path = Path(sys.argv[5]) output = Path(sys.argv[6]) if len(sys.argv) > 6 else \ Path(f"sessions/{session_id}/kappa_report.json")
calculate_kappa_report(session_id, r1_path, r2_path, segments_path, output)
elif command == "template": segments_path = Path(sys.argv[2]) researcher_id = sys.argv[3] session_id = sys.argv[4] output = Path(sys.argv[5])
generate_coding_template(segments_path, researcher_id, session_id, output)
else: print(f"Unknown command: {command}") sys.exit(1)123456789{ "_meta": { "version": "1.0", "description": "Validated learnings written by Agent 2 after high-kappa human agreement. Read by Agent 1 during segmentation. Each entry must have been derived from at least 3 coded sessions with kappa >= 0.70.", "last_updated": null, "total_entries": 0 }, "learned_rules": []}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849{ "_meta": { "version": "1.0", "locked": true, "description": "Hard coding rules that Agent 1 must always follow. These are never modified by Agent 2." }, "rules": [ { "rule_id": "R01", "label": "One dimension per segment", "description": "Each segment must be assigned exactly one dimension code. If multiple dimensions are observable, assign the most dominant one and flag the segment as uncertain with a note on the competing dimension." }, { "rule_id": "R02", "label": "Segments are behaviorally defined", "description": "A segment boundary is determined by a shift in the TYPE of collaborative behavior, not by topic change in the conversational sense. Ask: has the behavioral function of the exchange changed?" }, { "rule_id": "R03", "label": "Minimum segment length", "description": "A segment must contain at least 2 speaker turns. A single utterance is not sufficient to establish a behavioral episode unless it is a clear, unambiguous closing act (e.g. a consensus statement)." }, { "rule_id": "R04", "label": "Open flag on window boundary", "description": "If at the end of a processing window the current segment has not reached a natural behavioral close, the segment must be flagged as OPEN. The next window must begin from the first turn of the open segment, not from where the window ended." }, { "rule_id": "R05", "label": "Uncertainty flag", "description": "If Agent 1 is uncertain between two dimensions, it must still assign one dimension (the most likely), set uncertain=true, and name the competing dimension in the uncertainty_note field." }, { "rule_id": "R06", "label": "Rationale required", "description": "Every segment must include a rationale of 1-2 sentences citing specific observable behaviors from the turns that justify the dimension assignment." }, { "rule_id": "R07", "label": "No inference beyond the text", "description": "Agent 1 must only code what is observable in the transcript. It must not infer mental states, intentions, or off-transcript behavior. If something is ambiguous, use the uncertainty flag." }, { "rule_id": "R08", "label": "Negative episodes are valid", "description": "A dimension can be coded even when the behavior is absent or performed poorly. For example, failed dialogue management (overlapping speech) is still coded as D2. The quality of the behavior is for the researcher to evaluate." } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149{ "_meta": { "version": "1.0", "locked": true, "description": "Core dimension definitions for collaborative coding. This file is authored by the research team and must never be modified by Agent 2. These definitions are the ground truth of the coding framework.", "total_dimensions": 9 }, "dimensions": [ { "id": "D1", "code": "mutual_understanding", "label": "Sustaining Mutual Understanding", "summary": "Speakers ensure their contributions are understood and actively seek and give evidence of comprehension.", "full_definition": "Speakers make their contributions understandable for their collaboration partner, e.g., by avoiding or explaining technical terms from their domain of expertise or by paraphrasing longer passages of text from their materials, rather than reading them aloud to their partner. They make sure they have been understood by eliciting feedback from their partner. Listeners focus their attention on what the speaker is saying and give verbal feedback on their understanding (backchannels, paraphrases), demonstrate their understanding in an appropriate response, or ask for clarification.", "key_behavioral_markers": [ "Speaker explains or avoids domain-specific jargon", "Speaker paraphrases material rather than reading aloud", "Speaker explicitly checks for comprehension (e.g. 'Did you understand?')", "Listener gives backchannel feedback (e.g. 'Mhm', 'I see')", "Listener paraphrases back what was said", "Listener asks for clarification", "Speaker confirms or corrects listener's paraphrase" ] }, { "id": "D2", "code": "dialogue_management", "label": "Dialogue Management", "summary": "A smooth conversational flow is maintained with clear turn-taking and minimal overlap or confusion.", "full_definition": "A smooth flow of communication is maintained in which little time is lost due to overlaps in speech or confusion about whose turn it is to talk. Turn-taking is often facilitated by means of questions or explicit handovers. Speakers avoid redundant phrases and fillers at the end of a turn, thus signalling they are done and the partner may now speak. To the observer it is always clear who is talking and who is listening. Before partners start a new conversation after a phase of parallel individual work, they make sure they have their partner's attention.", "key_behavioral_markers": [ "Explicit turn handover (e.g. 'What do you think?', 'You go!')", "Attention-getting before speaking (e.g. calling partner's name)", "Meta-statements to initiate conversation (e.g. 'Can I ask you something?')", "Overlapping speech causing confusion", "Unclear who holds the floor", "Excessive fillers or redundant phrases signalling incomplete turn", "Partner interrupts without acknowledgement" ] }, { "id": "D3", "code": "information_pooling", "label": "Information Pooling", "summary": "Partners actively share, elaborate, and elicit domain-specific information relevant to the joint task.", "full_definition": "Partners try to gather as many solution-relevant pieces of information as possible. New information is introduced in an elaborated way, for example by relating it to facts that have already been established, or by pointing out its relevance for the solution. Participants elicit domain-specific knowledge from their partner, using their expertise as a resource. At the same time they make sure that the aspects that are important from the perspective of their own domain are taken into account and they take on the task of clarifying any information needs that relate to their domain of expertise.", "key_behavioral_markers": [ "Partner introduces new information and explains its relevance", "Partner connects new information to already established facts", "Partner explicitly elicits domain knowledge from the other (e.g. 'What does your field say about this?')", "Partner shares discipline-specific diagnostic criteria or knowledge", "Partner asks clarifying questions about the other's domain", "Partner ensures their own domain perspective is included" ] }, { "id": "D4", "code": "reaching_consensus", "label": "Reaching Consensus", "summary": "Partners critically evaluate options and arguments before reaching a clearly identifiable joint decision.", "full_definition": "Decisions for alternatives on the way to a final solution stand at the end of a critical discussion in which partners have collected and evaluated arguments for and against the available options. If partners initially prefer different options, they exchange arguments until a consensus is reached that can be grounded in facts. Even if partners agree from the start, they still evaluate their shared preference critically and search for supporting as well as challenging facts. The point at which a final decision is reached is clearly identifiable.", "key_behavioral_markers": [ "Partners explicitly state and compare different options", "Partners exchange arguments for and against an option", "Partners ground their preference in case facts or evidence", "Critical evaluation even when initial agreement is present", "A clear moment of joint decision or agreement", "Agreed decision is not revisited without new information" ] }, { "id": "D5", "code": "task_division", "label": "Task Division", "summary": "The task is systematically divided into subtasks with clear individual and joint work phases.", "full_definition": "The task is divided into subtasks. Partners proceed systematically, taking on one step toward the solution at a time with a clear goal or question guiding each work phase. Individual as well as joint phases of work are established, either in a plan set up at the beginning or in short-term arrangements agreed upon as they go. Partners define and take on individual subtasks that match their expertise and resources. The work is divided equally so neither collaborator has to wait idly.", "key_behavioral_markers": [ "Partners explicitly propose or agree on a plan or structure", "Partners assign subtasks to individuals", "Partners initiate or close an individual work phase", "Partners initiate or close a joint work phase", "Partners refer to a previously established plan", "One partner waits while the other completes a task (negative marker)", "Subtask assignments match each partner's expertise" ] }, { "id": "D6", "code": "time_management", "label": "Time Management", "summary": "Partners actively monitor time and adjust their work pace to ensure task completion within the allotted period.", "full_definition": "Partners monitor the remaining time throughout their cooperation and make sure to finish the current subtask or topic with enough time to complete the remaining subtasks. They check whether the current topic is important enough to spend more time on, and remind one another of the time remaining. They might also set up and monitor adherence to a time schedule in which each subtask is allotted a realistic amount of time.", "key_behavioral_markers": [ "Partner explicitly mentions remaining time", "Partner suggests moving on due to time pressure", "Partner proposes or references a time schedule", "Partner checks whether current topic warrants more time", "Partner reminds the other of a time constraint", "Rushing or skipping steps due to time running out (negative marker)" ] }, { "id": "D7", "code": "technical_coordination", "label": "Technical Coordination", "summary": "Partners manage the use of shared technical tools effectively, including editor access and application switching.", "full_definition": "Partners master the basic technical skills that allow them to use the technical tools to their advantage. Collaborators arrange who may write into the shared editor at which time. At least one partner makes use of their individual text editor, allowing for phases of parallel writing.", "key_behavioral_markers": [ "Partner negotiates who writes in the shared editor", "Partner switches between applications or tools", "Partner uses copy-paste or other basic technical functions", "Partner uses their individual editor for parallel work", "Technical difficulty or confusion about tool use (negative marker)", "Conflict over simultaneous editing (negative marker)" ] }, { "id": "D8", "code": "reciprocal_interaction", "label": "Reciprocal Interaction", "summary": "Partners interact as equals, with mutual respect, constructive criticism, and balanced contribution.", "full_definition": "Partners treat each other with respect and encourage one another to contribute their opinions and perspectives. Critical remarks are constructive and factual, never personal. Partners interact as equals, and decisions are made cooperatively. Since both partners hold equal amounts of unique task-relevant knowledge, they should contribute equally toward the problem solution; the solution process is not dominated by one partner.", "key_behavioral_markers": [ "Partner explicitly invites the other's opinion or perspective", "Critical feedback is framed as task-oriented, not personal", "Decisions are made jointly, not unilaterally", "Both partners contribute roughly equally to the discussion", "One partner dominates or dismisses the other (negative marker)", "Personal or dismissive criticism (negative marker)", "Partner encourages or affirms the other's contribution" ] }, { "id": "D9", "code": "individual_task_orientation", "label": "Individual Task Orientation", "summary": "Each participant actively engages with the task, brings their knowledge and skills to bear, and avoids distraction.", "full_definition": "Each participant actively engages in finding a good solution to the problem, bringing their knowledge and skills to bear. They focus attention on the task and on task-relevant information, avoid distractions, and strive to mobilize their own as well as the partner's skills and resources. The participant shows interest in the task or enjoyment of the work, for example by expressing a wish to help the patient, a general interest in the subject domains, or pride in work considered well done.", "key_behavioral_markers": [ "Partner expresses motivation or interest in the task", "Partner actively contributes task-relevant knowledge", "Partner redirects attention back to the task", "Partner expresses care about the quality of the solution", "Partner is distracted or disengaged (negative marker)", "Partner expresses enjoyment or pride in their work" ] } ]}123456789101112131415161718192021222324252627282930313233343536{ "_meta": { "version": "1.0", "locked": true, "description": "Anchor examples per dimension. These are research-team-authored examples that ground the LLM's interpretation. Agent 2 must never modify this file. New examples may only be added by the research team." }, "examples": [ { "dimension_id": "D1", "type": "positive", "label": "Successful comprehension check and paraphrase", "source": "Study 1, translated", "exchange": [ {"speaker": "Psychology Student (P)", "text": "Did you understand what I just said?"}, {"speaker": "Medical Student (M)", "text": "U-hum. That is, you mean, whether now there is a psychotic component in addition to the depression and the multiple sclerosis?"}, {"speaker": "Psychology Student (P)", "text": "Exactly!"} ], "annotation_note": "P elicits comprehension check. M paraphrases back accurately. P confirms. Classic D1 positive episode." }, { "dimension_id": "D2", "type": "negative", "label": "Overlapping speech causing communication breakdown", "source": "Study 1, translated", "exchange": [ {"speaker": "P", "text": "[It's certainly a depression]"}, {"speaker": "M", "text": "[...has always been]"}, {"speaker": "M", "text": "[Mhm, that's] sure"}, {"speaker": "P", "text": "[I don't understand you]"}, {"speaker": "M", "text": "[But schizophrenia... schizophrenia] I can't read that."}, {"speaker": "P", "text": "[It's certainly a depression... Sorry?]"} ], "annotation_note": "Brackets indicate simultaneous speech. Repeated overlaps, confusion about the floor, neither partner can complete a thought. Classic D2 negative episode." } ]}1234567{ "_meta": { "description": "Validated edge cases that clarify boundary decisions for Agent 1. Written by Agent 2 after human approval. Never modified directly.", "locked": false }, "edge_cases": []}123456789{ "_meta": { "version": "1.0", "description": "Validated learnings written by Agent 2 after high-kappa human agreement. Read by Agent 1 during segmentation. Each entry must have been derived from at least 3 coded sessions with kappa >= 0.70.", "last_updated": null, "total_entries": 0 }, "learned_rules": []}123456789{ "_meta": { "version": "1.0", "description": "Quarantined candidate learnings. These are corrections or patterns observed during coding that have NOT yet been validated by two researchers with kappa >= 0.70. Agent 1 must NEVER read this file. Only Agent 2 reads this file during the learning step.", "last_updated": null, "total_entries": 0 }, "pending_review": []}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758"""llm_client.py-------------Shared LLM client for Agent 1 and Agent 2.Uses Qwen 2.5 72B via the Hugging Face Inference API.Chosen for strong Japanese language understanding and reliable JSON output.
Requires HF_TOKEN environment variable (huggingface.co/settings/tokens)."""
import osimport timefrom huggingface_hub import InferenceClient
MODEL = "Qwen/Qwen2.5-72B-Instruct"_client: InferenceClient | None = None
TIMEOUT_SECS = 180 # generous for large chunks on a 72B model
def _get_client() -> InferenceClient: global _client if _client is None: token = os.environ.get("HF_TOKEN") if not token: raise RuntimeError("HF_TOKEN environment variable is not set.") _client = InferenceClient(model=MODEL, token=token, timeout=TIMEOUT_SECS) return _client
def call_llm(system_prompt: str, user_prompt: str, max_tokens: int = 4000) -> str: """ Send a system + user prompt to Qwen 2.5 72B and return the response text. Retries up to 3 times with backoff on transient errors (504, 503, etc). """ client = _get_client() messages = [ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}, ]
for attempt in range(3): try: response = client.chat.completions.create( messages=messages, max_tokens=max_tokens, temperature=0.1, ) return response.choices[0].message.content except Exception as e: is_transient = any(code in str(e) for code in ("504", "503", "502", "429")) if attempt < 2 and is_transient: wait = 5 * (attempt + 1) print(f"[LLM] Transient error (attempt {attempt+1}), retrying in {wait}s…") time.sleep(wait) continue raise RuntimeError(f"LLM API error: {e}") from e123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666"""orchestrator.py---------------Session Orchestrator with file watcher.
Manages the full pipeline lifecycle for each session:
CREATED → PARSED (transcript parsed into turns) → SEGMENTED (Agent 1 proposed segments) → AWAITING_R1 (coding template generated, waiting for Researcher 1) → AWAITING_R2 (R1 received, waiting for Researcher 2) → CALCULATING_KAPPA → BELOW_THRESHOLD (kappa < 0.70 — researchers must review) → DISAGREEMENT_REVIEW (kappa passed but disagreements remain) → READY_FOR_AGENT2 → LEARNING (Agent 2 running) → COMPLETE
The file watcher monitors the sessions directory. When a researcherdrops a completed coding file into the session folder, the orchestratordetects it and automatically advances the session to the next state.
Usage: # Start a new session python orchestrator.py new <transcript_file> <session_id>
# Watch all sessions (runs continuously) python orchestrator.py watch <sessions_root>
# Advance a specific session manually python orchestrator.py advance <session_id> <sessions_root>
# Show status of all sessions python orchestrator.py status <sessions_root>
# Approve a learned rule python orchestrator.py approve-rule <rule_id> <researcher_id> <sessions_root>"""
import jsonimport timeimport shutilimport tracebackfrom pathlib import Pathfrom datetime import datetime, timezonefrom typing import Optional
# Import our pipeline modulesimport syssys.path.insert(0, str(Path(__file__).parent))
from transcript_parser import parse_transcript, save_parsedfrom agent1_segmenter import run_full_transcript, save_segmentsfrom kappa_calculator import ( calculate_kappa_report, generate_coding_template, resolve_disagreement, discard_disagreement,)from agent2_learner import ( run_learning_cycle, add_to_tier3, approve_rule, reject_rule, list_pending_rules,)
# ---------------------------------------------------------------------------# Constants# ---------------------------------------------------------------------------
WATCH_INTERVAL_SECS = 10 # how often the watcher pollsLIBRARY_ROOT = Path(__file__).parent / "library"
# Expected filenames within a session directoryF_STATE = "session_state.json"F_TURNS = "parsed_turns.json"F_SEGMENTS = "segments_proposed.json"F_TEMPLATE_R1 = "coding_template_R1.json"F_TEMPLATE_R2 = "coding_template_R2.json"F_CODING_R1 = "coding_R1.json"F_CODING_R2 = "coding_R2.json"F_KAPPA_REPORT = "kappa_report.json"
# ---------------------------------------------------------------------------# State management# ---------------------------------------------------------------------------
VALID_STATES = [ "CREATED", "PARSED", "SEGMENTED", "AWAITING_R1", "AWAITING_R2", "CALCULATING_KAPPA", "BELOW_THRESHOLD", "DISAGREEMENT_REVIEW", "READY_FOR_AGENT2", "LEARNING", "COMPLETE", "ERROR",]
def read_state(session_dir: Path) -> dict: state_file = session_dir / F_STATE if not state_file.exists(): return {} return json.loads(state_file.read_text(encoding="utf-8"))
def write_state(session_dir: Path, state: str, extra: Optional[dict] = None) -> dict: existing = read_state(session_dir) record = { **existing, "state": state, "updated_at": datetime.now(timezone.utc).isoformat(), } if extra: record.update(extra)
# Append to history history = record.get("history", []) history.append({"state": state, "at": record["updated_at"]}) record["history"] = history
(session_dir / F_STATE).write_text( json.dumps(record, indent=2, ensure_ascii=False), encoding="utf-8", ) return record
def get_state(session_dir: Path) -> str: return read_state(session_dir).get("state", "UNKNOWN")
# ---------------------------------------------------------------------------# Session creation# ---------------------------------------------------------------------------
def create_session( transcript_path: Path, session_id: str, sessions_root: Path, researcher_ids: Optional[list[str]] = None,) -> Path: """ Create a new session directory and copy the transcript in.
Args: transcript_path: Path to the raw Zoom transcript session_id: Unique identifier for this session/dyad sessions_root: Root directory for all sessions researcher_ids: e.g. ["R1", "R2"] — used for template naming
Returns: Path to the created session directory. """ session_dir = sessions_root / session_id session_dir.mkdir(parents=True, exist_ok=True)
# Copy transcript in dest = session_dir / f"transcript{transcript_path.suffix}" shutil.copy2(transcript_path, dest)
write_state(session_dir, "CREATED", { "session_id": session_id, "transcript_file": dest.name, "researcher_ids": researcher_ids or ["R1", "R2"], "created_at": datetime.now(timezone.utc).isoformat(), })
print(f"[Orchestrator] Session {session_id} created at {session_dir}") return session_dir
# ---------------------------------------------------------------------------# Pipeline steps# ---------------------------------------------------------------------------
def step_parse(session_dir: Path) -> bool: """Parse the transcript into turns.""" state = read_state(session_dir) transcript_file = session_dir / state["transcript_file"]
print(f"[Orchestrator] [{state['session_id']}] Parsing transcript...") turns = parse_transcript(transcript_file) save_parsed(turns, session_dir / F_TURNS) write_state(session_dir, "PARSED", {"n_turns": len(turns)}) print(f"[Orchestrator] [{state['session_id']}] Parsed {len(turns)} turns.") return True
def step_segment(session_dir: Path) -> bool: """Run Agent 1 across the full transcript.""" state = read_state(session_dir) sid = state["session_id"] turns = json.loads((session_dir / F_TURNS).read_text(encoding="utf-8"))
print(f"[Orchestrator] [{sid}] Running Agent 1 segmentation...") segments = run_full_transcript( turns=turns, session_id=sid, library_root=LIBRARY_ROOT, ) save_segments(segments, session_dir / F_SEGMENTS) write_state(session_dir, "SEGMENTED", {"n_segments": len(segments)}) print(f"[Orchestrator] [{sid}] Agent 1 produced {len(segments)} segments.") return True
def step_generate_templates(session_dir: Path) -> bool: """Generate coding templates for both researchers.""" state = read_state(session_dir) sid = state["session_id"] researcher_ids = state.get("researcher_ids", ["R1", "R2"]) segments_path = session_dir / F_SEGMENTS
for rid in researcher_ids: template_path = session_dir / f"coding_template_{rid}.json" generate_coding_template( proposed_segments_path=segments_path, researcher_id=rid, session_id=sid, output_path=template_path, ) print(f"[Orchestrator] [{sid}] Coding template generated for {rid}.")
write_state(session_dir, "AWAITING_R1") print(f"[Orchestrator] [{sid}] Waiting for researchers to submit codings.") print(f"[Orchestrator] [{sid}] Researchers: drop completed coding files as " f"coding_R1.json and coding_R2.json into {session_dir}") return True
def step_check_codings(session_dir: Path) -> Optional[str]: """ Check which coding files have arrived. Returns the new state string, or None if nothing changed. """ state = read_state(session_dir) sid = state["session_id"] has_r1 = (session_dir / F_CODING_R1).exists() has_r2 = (session_dir / F_CODING_R2).exists() current = state.get("state")
if has_r1 and has_r2: if current != "CALCULATING_KAPPA": print(f"[Orchestrator] [{sid}] Both codings received. Advancing to kappa calculation.") write_state(session_dir, "CALCULATING_KAPPA") return "CALCULATING_KAPPA"
elif has_r1 and current == "AWAITING_R1": print(f"[Orchestrator] [{sid}] R1 coding received. Waiting for R2.") write_state(session_dir, "AWAITING_R2") return "AWAITING_R2"
elif has_r2 and current == "AWAITING_R1": print(f"[Orchestrator] [{sid}] R2 coding received first. Waiting for R1.") write_state(session_dir, "AWAITING_R2") return "AWAITING_R2"
return None
def step_calculate_kappa(session_dir: Path) -> bool: """Run the kappa calculator and route based on result.""" state = read_state(session_dir) sid = state["session_id"]
print(f"[Orchestrator] [{sid}] Calculating Cohen's Kappa...") report = calculate_kappa_report( session_id=sid, coding_r1_path=session_dir / F_CODING_R1, coding_r2_path=session_dir / F_CODING_R2, proposed_segments_path=session_dir / F_SEGMENTS, output_path=session_dir / F_KAPPA_REPORT, )
# Push resolved disagreements to Tier 3 # (at this point they're not yet resolved — just flagged) # Tier 3 population happens after disagreement review (see resolve/discard helpers)
if not report["gate_passed"]: write_state(session_dir, "BELOW_THRESHOLD", { "kappa": report["overall_kappa"], "kappa_interpretation": report["kappa_interpretation"], }) print(f"[Orchestrator] [{sid}] Kappa {report['overall_kappa']:.4f} — " f"BELOW THRESHOLD. Researchers must review and re-code.") return True
if report["segments_in_disagreement"]: write_state(session_dir, "DISAGREEMENT_REVIEW", { "kappa": report["overall_kappa"], "n_disagreements": len(report["segments_in_disagreement"]), }) print(f"[Orchestrator] [{sid}] Kappa passed. " f"{len(report['segments_in_disagreement'])} disagreements to resolve.") return True
# Kappa passed and no disagreements write_state(session_dir, "READY_FOR_AGENT2", { "kappa": report["overall_kappa"], }) print(f"[Orchestrator] [{sid}] Kappa passed with no disagreements. " f"Ready for Agent 2.") return True
def step_run_agent2(session_dir: Path, sessions_root: Path) -> bool: """Run Agent 2 learning cycle.""" state = read_state(session_dir) sid = state["session_id"]
write_state(session_dir, "LEARNING") print(f"[Orchestrator] [{sid}] Running Agent 2 learning cycle...")
result = run_learning_cycle( sessions_root=sessions_root, library_root=LIBRARY_ROOT, )
write_state(session_dir, "COMPLETE", { "learning_result": { "status": result.get("status"), "rules_proposed": len(result.get("proposed_rules", [])), "below_safe_zone": result.get("below_safe_zone", False), } })
print(f"[Orchestrator] [{sid}] Session complete.") return True
# ---------------------------------------------------------------------------# Disagreement helpers (called by researchers after DISAGREEMENT_REVIEW)# ---------------------------------------------------------------------------
def resolve_session_disagreement( session_id: str, sessions_root: Path, segment_id: str, resolved_dimension: str, resolution_note: str,) -> None: """ Resolve a specific disagreement and push it to Tier 3. After all disagreements are resolved/discarded, advances the session. """ session_dir = sessions_root / session_id report_path = session_dir / F_KAPPA_REPORT state = read_state(session_dir) segments = json.loads((session_dir / F_SEGMENTS).read_text()) seg_map = {s["segment_id"]: s for s in segments["segments"]}
# Update the kappa report report = resolve_disagreement( report_path=report_path, segment_id=segment_id, resolved_dimension=resolved_dimension, resolution_note=resolution_note, )
# Push to Tier 3 seg = seg_map.get(segment_id, {}) codings_r1 = json.loads((session_dir / F_CODING_R1).read_text()) codings_r2 = json.loads((session_dir / F_CODING_R2).read_text()) map_r1 = {c["segment_id"]: c for c in codings_r1["codings"]} map_r2 = {c["segment_id"]: c for c in codings_r2["codings"]}
add_to_tier3( session_id=session_id, segment_id=segment_id, agent1_dimension=seg.get("dimension_id", ""), agent1_rationale=seg.get("rationale", ""), r1_dimension=map_r1.get(segment_id, {}).get("dimension_id", ""), r1_comment=map_r1.get(segment_id, {}).get("comment", ""), r2_dimension=map_r2.get(segment_id, {}).get("dimension_id", ""), r2_comment=map_r2.get(segment_id, {}).get("comment", ""), resolved_dimension=resolved_dimension, resolution_note=resolution_note, )
# Check if all disagreements handled → advance if report.get("status") == "ready_for_agent2": write_state(session_dir, "READY_FOR_AGENT2", {"kappa": report["overall_kappa"]}) print(f"[Orchestrator] [{session_id}] All disagreements resolved. " f"Ready for Agent 2.")
def discard_session_disagreement( session_id: str, sessions_root: Path, segment_id: str, discard_note: str,) -> None: """Discard an unresolvable disagreement and advance if all are handled.""" session_dir = sessions_root / session_id report_path = session_dir / F_KAPPA_REPORT
report = discard_disagreement( report_path=report_path, segment_id=segment_id, discard_note=discard_note, )
if report.get("status") == "ready_for_agent2": write_state(session_dir, "READY_FOR_AGENT2", {"kappa": report["overall_kappa"]}) print(f"[Orchestrator] [{session_id}] All disagreements handled. " f"Ready for Agent 2.")
# ---------------------------------------------------------------------------# Advance — single step forward for a session# ---------------------------------------------------------------------------
def advance_session(session_dir: Path, sessions_root: Path) -> str: """ Advance a session by one step based on its current state. Returns the new state string. """ state_str = get_state(session_dir)
try: if state_str == "CREATED": step_parse(session_dir)
elif state_str == "PARSED": step_segment(session_dir)
elif state_str == "SEGMENTED": step_generate_templates(session_dir)
elif state_str in ("AWAITING_R1", "AWAITING_R2"): new_state = step_check_codings(session_dir) if new_state == "CALCULATING_KAPPA": step_calculate_kappa(session_dir)
elif state_str == "CALCULATING_KAPPA": step_calculate_kappa(session_dir)
elif state_str == "READY_FOR_AGENT2": step_run_agent2(session_dir, sessions_root)
elif state_str in ("COMPLETE", "ERROR", "BELOW_THRESHOLD", "DISAGREEMENT_REVIEW"): pass # these states require human intervention
except Exception as e: error_msg = traceback.format_exc() write_state(session_dir, "ERROR", { "error": str(e), "traceback": error_msg, }) print(f"[Orchestrator] ERROR in session {session_dir.name}:\n{error_msg}")
return get_state(session_dir)
# ---------------------------------------------------------------------------# File watcher# ---------------------------------------------------------------------------
class SessionWatcher: """ Watches the sessions root directory for file changes. When a coding file is detected, automatically advances the session. """
def __init__(self, sessions_root: Path): self.sessions_root = sessions_root self.sessions_root.mkdir(parents=True, exist_ok=True) self._last_seen: dict[str, set[str]] = {} # session_id → set of filenames
def _scan_session(self, session_dir: Path) -> set[str]: """Return set of filenames currently in the session directory.""" return {f.name for f in session_dir.iterdir() if f.is_file()}
def _detect_new_files(self, session_id: str, current_files: set[str]) -> set[str]: """Return files that appeared since last scan.""" previous = self._last_seen.get(session_id, set()) return current_files - previous
def tick(self) -> None: """One scan cycle — check all sessions for changes.""" for session_dir in sorted(self.sessions_root.iterdir()): if not session_dir.is_dir(): continue
session_id = session_dir.name state_str = get_state(session_dir) current_files = self._scan_session(session_dir) new_files = self._detect_new_files(session_id, current_files)
self._last_seen[session_id] = current_files
# Always advance newly created sessions through automated steps if state_str in ("CREATED", "PARSED", "SEGMENTED"): advance_session(session_dir, self.sessions_root)
# Advance when both codings arrive elif state_str in ("AWAITING_R1", "AWAITING_R2"): coding_files = {F_CODING_R1, F_CODING_R2} if new_files & coding_files: print(f"[Watcher] New coding file(s) detected in {session_id}: " f"{new_files & coding_files}") advance_session(session_dir, self.sessions_root)
# Advance when ready for Agent 2 elif state_str == "READY_FOR_AGENT2": advance_session(session_dir, self.sessions_root)
def run(self) -> None: """Run the watcher loop indefinitely.""" print(f"[Watcher] Watching {self.sessions_root} every {WATCH_INTERVAL_SECS}s...") print(f"[Watcher] Press Ctrl+C to stop.\n")
# Initial scan to populate _last_seen without triggering false positives for session_dir in self.sessions_root.iterdir(): if session_dir.is_dir(): self._last_seen[session_dir.name] = self._scan_session(session_dir)
while True: try: self.tick() except KeyboardInterrupt: print("\n[Watcher] Stopped.") break except Exception as e: print(f"[Watcher] Unexpected error: {e}") traceback.print_exc() time.sleep(WATCH_INTERVAL_SECS)
# ---------------------------------------------------------------------------# Status display# ---------------------------------------------------------------------------
def print_all_status(sessions_root: Path) -> None: """Print a summary of all sessions and their current states.""" sessions = sorted(sessions_root.iterdir()) if sessions_root.exists() else []
if not sessions: print("[Orchestrator] No sessions found.") return
print(f"\n{'═' * 70}") print(f" SESSION STATUS — {sessions_root}") print(f"{'═' * 70}") print(f" {'SESSION':<20} {'STATE':<25} {'KAPPA':<8} {'SEGMENTS':<10} UPDATED") print(f" {'-'*20} {'-'*25} {'-'*8} {'-'*10} {'-'*20}")
for session_dir in sessions: if not session_dir.is_dir(): continue state = read_state(session_dir) if not state: continue
sid = state.get("session_id", session_dir.name) s = state.get("state", "UNKNOWN") kappa = f"{state.get('kappa', '—'):.3f}" if isinstance(state.get("kappa"), float) else "—" n_segs = str(state.get("n_segments", "—")) updated = state.get("updated_at", "")[:16].replace("T", " ")
# Colour-code state marker = { "COMPLETE": "✓", "ERROR": "✗", "BELOW_THRESHOLD": "!", "DISAGREEMENT_REVIEW":"?", "READY_FOR_AGENT2": "→", "LEARNING": "⟳", }.get(s, " ")
print(f" {sid:<20} {marker} {s:<23} {kappa:<8} {n_segs:<10} {updated}")
# Pending rules pending = list_pending_rules() if pending: print(f"\n ⚠ {len(pending)} learned rule(s) pending human approval.") print(f" Run: python orchestrator.py approve-rule <rule_id> <researcher_id>")
print(f"{'═' * 70}\n")
# ---------------------------------------------------------------------------# CLI# ---------------------------------------------------------------------------
if __name__ == "__main__": import sys
if len(sys.argv) < 2: print(__doc__) sys.exit(1)
command = sys.argv[1]
if command == "new": if len(sys.argv) < 4: print("Usage: python orchestrator.py new <transcript_file> <session_id> [sessions_root]") sys.exit(1) transcript = Path(sys.argv[2]) session_id = sys.argv[3] root = Path(sys.argv[4]) if len(sys.argv) > 4 else Path("sessions") session_dir = create_session(transcript, session_id, root) # Immediately start automated steps watcher = SessionWatcher(root) watcher.tick()
elif command == "watch": root = Path(sys.argv[2]) if len(sys.argv) > 2 else Path("sessions") SessionWatcher(root).run()
elif command == "advance": if len(sys.argv) < 3: print("Usage: python orchestrator.py advance <session_id> [sessions_root]") sys.exit(1) session_id = sys.argv[2] root = Path(sys.argv[3]) if len(sys.argv) > 3 else Path("sessions") session_dir = root / session_id new_state = advance_session(session_dir, root) print(f"[Orchestrator] Session {session_id} → {new_state}")
elif command == "status": root = Path(sys.argv[2]) if len(sys.argv) > 2 else Path("sessions") print_all_status(root)
elif command == "resolve": # python orchestrator.py resolve <session_id> <segment_id> <dimension> <note> [sessions_root] session_id = sys.argv[2] segment_id = sys.argv[3] dimension = sys.argv[4] note = sys.argv[5] root = Path(sys.argv[6]) if len(sys.argv) > 6 else Path("sessions") resolve_session_disagreement(session_id, root, segment_id, dimension, note)
elif command == "discard": # python orchestrator.py discard <session_id> <segment_id> <note> [sessions_root] session_id = sys.argv[2] segment_id = sys.argv[3] note = sys.argv[4] root = Path(sys.argv[5]) if len(sys.argv) > 5 else Path("sessions") discard_session_disagreement(session_id, root, segment_id, note)
elif command == "approve-rule": rule_id = sys.argv[2] researcher = sys.argv[3] note = sys.argv[4] if len(sys.argv) > 4 else "" approve_rule(rule_id, researcher, note)
elif command == "reject-rule": rule_id = sys.argv[2] researcher = sys.argv[3] note = sys.argv[4] if len(sys.argv) > 4 else "No reason given" reject_rule(rule_id, researcher, note)
else: print(f"Unknown command: {command}") print(__doc__) sys.exit(1)123456789{ "_meta": { "version": "1.0", "description": "Quarantined candidate learnings. These are corrections or patterns observed during coding that have NOT yet been validated by two researchers with kappa >= 0.70. Agent 1 must NEVER read this file. Only Agent 2 reads this file during the learning step.", "last_updated": null, "total_entries": 0 }, "pending_review": []}12gradio>=6.0.0huggingface_hub>=1.8.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310"""transcript_parser.py--------------------Parses Zoom transcripts (TXT or VTT format) into structured speaker turns.Each turn is the atomic unit for downstream segmentation by Agent 1.
Supported formats: - Zoom TXT export: "Speaker Name\tHH:MM:SS\nUtterance text\n" - Zoom VTT export: WebVTT with timestamp blocks and speaker labels
Output: List of Turn dicts, ready to be saved as parsed JSON."""
import reimport jsonfrom pathlib import Pathfrom dataclasses import dataclass, asdictfrom typing import Optional, Union
# ---------------------------------------------------------------------------# Data structure# ---------------------------------------------------------------------------
@dataclassclass Turn: turn_id: int # sequential index across the transcript speaker: str # normalised speaker name start_time: str # HH:MM:SS end_time: Optional[str] # HH:MM:SS — available in VTT, None in TXT start_seconds: float # for windowing arithmetic end_seconds: Optional[float] text: str # cleaned utterance
# ---------------------------------------------------------------------------# Helpers# ---------------------------------------------------------------------------
def _hhmmss_to_seconds(ts: str) -> float: """Convert HH:MM:SS or HH:MM:SS.mmm to total seconds.""" ts = ts.strip() # strip milliseconds if present (VTT uses HH:MM:SS.mmm) ts = ts.split(".")[0] parts = ts.split(":") try: if len(parts) == 3: h, m, s = parts return int(h) * 3600 + int(m) * 60 + int(s) elif len(parts) == 2: m, s = parts return int(m) * 60 + int(s) except ValueError: pass return 0.0
def _seconds_to_hhmmss(seconds: float) -> str: seconds = int(seconds) h = seconds // 3600 m = (seconds % 3600) // 60 s = seconds % 60 return f"{h:02d}:{m:02d}:{s:02d}"
def _clean_text(text: str) -> str: """Strip VTT positioning tags, extra whitespace, and common artefacts.""" text = re.sub(r"<[^>]+>", "", text) # remove <00:00:00.000> tags text = re.sub(r"\[.*?\]", "", text) # remove [Music] [Applause] etc text = re.sub(r"\s+", " ", text) # collapse whitespace return text.strip()
# ---------------------------------------------------------------------------# TXT parser# ---------------------------------------------------------------------------# Zoom TXT export format:## Speaker Name\tHH:MM:SS# Utterance text (may span multiple lines until next speaker block)## Some exports use a tab separator, others a newline between name+time and text.# We handle both.
_TXT_HEADER_RE = re.compile( r"^(?P<speaker>.+?)\t(?P<time>\d{1,2}:\d{2}:\d{2})\s*$")
# Alternative format: "HH:MM:SS Speaker Name"_TXT_HEADER_ALT_RE = re.compile( r"^(?P<time>\d{1,2}:\d{2}:\d{2})\s{2,}(?P<speaker>.+?)\s*$")
# Format: "[Speaker Name] HH:MM:SS"_TXT_HEADER_BRACKET_RE = re.compile( r"^\[(?P<speaker>[^\]]+)\]\s+(?P<time>\d{1,2}:\d{2}:\d{2})\s*$")
def _parse_txt(lines: list[str]) -> list[Turn]: turns = [] turn_id = 0 current_speaker = None current_time = None current_lines = []
def _flush(): nonlocal turn_id if current_speaker and current_lines: text = _clean_text(" ".join(current_lines)) if text: turns.append(Turn( turn_id=turn_id, speaker=current_speaker, start_time=current_time, end_time=None, start_seconds=_hhmmss_to_seconds(current_time), end_seconds=None, text=text, )) turn_id += 1
for line in lines: m = _TXT_HEADER_RE.match(line) or _TXT_HEADER_ALT_RE.match(line) or _TXT_HEADER_BRACKET_RE.match(line) if m: _flush() current_speaker = m.group("speaker").strip() current_time = m.group("time").strip() current_lines = [] else: stripped = line.strip() if stripped: current_lines.append(stripped)
_flush()
# Back-fill end times from next turn's start for i in range(len(turns) - 1): turns[i].end_time = turns[i + 1].start_time turns[i].end_seconds = turns[i + 1].start_seconds
return turns
# ---------------------------------------------------------------------------# VTT parser# ---------------------------------------------------------------------------# WebVTT format:## WEBVTT## 00:00:01.000 --> 00:00:04.000# <v Speaker Name>Utterance text## Speaker may also appear as a plain line before the text.
_VTT_TIMESTAMP_RE = re.compile( r"^(?P<start>\d{2}:\d{2}:\d{2}[\.,]\d{3})\s+-->\s+(?P<end>\d{2}:\d{2}:\d{2}[\.,]\d{3})")_VTT_VOICE_TAG_RE = re.compile(r"^<v\s+(?P<speaker>[^>]+)>(?P<text>.*)$")
def _parse_vtt(lines: list[str]) -> list[Turn]: turns = [] turn_id = 0 i = 0
while i < len(lines): line = lines[i].strip()
m_ts = _VTT_TIMESTAMP_RE.match(line) if m_ts: start_raw = m_ts.group("start").replace(",", ".") end_raw = m_ts.group("end").replace(",", ".") start_time = start_raw[:8] # HH:MM:SS end_time = end_raw[:8]
# Collect text lines for this block text_lines = [] speaker = "Unknown" i += 1 while i < len(lines) and lines[i].strip(): tline = lines[i].strip() m_v = _VTT_VOICE_TAG_RE.match(tline) if m_v: speaker = m_v.group("speaker").strip() tline = m_v.group("text") text_lines.append(tline) i += 1
text = _clean_text(" ".join(text_lines)) if text: turns.append(Turn( turn_id=turn_id, speaker=speaker, start_time=start_time, end_time=end_time, start_seconds=_hhmmss_to_seconds(start_time), end_seconds=_hhmmss_to_seconds(end_time), text=text, )) turn_id += 1 else: i += 1
return turns
# ---------------------------------------------------------------------------# Public API# ---------------------------------------------------------------------------
def detect_format(content: str) -> str: """Detect whether a transcript is VTT or TXT format.""" first_lines = content.strip().splitlines()[:5] for line in first_lines: if line.strip().upper() == "WEBVTT": return "vtt" # Check for TXT header pattern in first 20 lines for line in content.splitlines()[:20]: if _TXT_HEADER_RE.match(line) or _TXT_HEADER_ALT_RE.match(line) or _TXT_HEADER_BRACKET_RE.match(line): return "txt" return "txt" # default assumption
def parse_transcript(filepath: Union[str, Path]) -> list[dict]: """ Parse a Zoom transcript file (TXT or VTT) into a list of Turn dicts.
Args: filepath: Path to the .txt or .vtt transcript file.
Returns: List of dicts with keys: turn_id, speaker, start_time, end_time, start_seconds, end_seconds, text. """ path = Path(filepath) if not path.exists(): raise FileNotFoundError(f"Transcript not found: {filepath}")
content = path.read_text(encoding="utf-8", errors="replace") fmt = detect_format(content) lines = content.splitlines()
if fmt == "vtt": turns = _parse_vtt(lines) else: turns = _parse_txt(lines)
if not turns: raise ValueError( f"No speaker turns extracted from {filepath}. " "Check that the file matches Zoom TXT or VTT export format." )
return [asdict(t) for t in turns]
def extract_window( turns: list[dict], start_seconds: float, duration_seconds: float = 600, # 10 minutes default) -> list[dict]: """ Return all turns that begin within [start_seconds, start_seconds + duration]. Used by Agent 1 to feed the sliding window. """ end_seconds = start_seconds + duration_seconds return [ t for t in turns if start_seconds <= t["start_seconds"] < end_seconds ]
def save_parsed(turns: list[dict], output_path: Union[str, Path]) -> None: """Save parsed turns to JSON.""" Path(output_path).write_text( json.dumps(turns, indent=2, ensure_ascii=False), encoding="utf-8", ) print(f"Saved {len(turns)} turns to {output_path}")
# ---------------------------------------------------------------------------# CLI usage# ---------------------------------------------------------------------------
if __name__ == "__main__": import sys
if len(sys.argv) < 2: print("Usage: python transcript_parser.py <transcript_file> [output.json]") sys.exit(1)
input_file = sys.argv[1] output_file = sys.argv[2] if len(sys.argv) > 2 else "parsed_transcript.json"
turns = parse_transcript(input_file) save_parsed(turns, output_file)
# Print summary total_seconds = turns[-1]["start_seconds"] if turns else 0 print(f"\nSummary:") print(f" Format detected : {detect_format(Path(input_file).read_text())}") print(f" Total turns : {len(turns)}") print(f" Speakers : {sorted(set(t['speaker'] for t in turns))}") print(f" Duration : {_seconds_to_hhmmss(total_seconds)}") print(f"\nFirst 3 turns:") for t in turns[:3]: print(f" [{t['start_time']}] {t['speaker']}: {t['text'][:80]}...").gitignoreAdded+13
.hfignoreAdded+8
README.mdAdded+27
agent0_sectioner.pyAdded+273
agent1_segmenter.pyAdded+401
agent1a_boundary.pyAdded+275
agent1b_coder.pyAdded+317
agent2_learner.pyAdded+783
app.pyAdded+1621
coding_rules.jsonAdded+49
dimensions.jsonAdded+149
examples.jsonAdded+36
kappa_calculator.pyAdded+569
learned_rules.jsonAdded+9
library/tier1_core/coding_rules.jsonAdded+49
library/tier1_core/dimensions.jsonAdded+149
library/tier1_core/examples.jsonAdded+36
library/tier2_validated/edge_cases.jsonAdded+7
library/tier2_validated/learned_rules.jsonAdded+9
library/tier3_candidate/pending_review.jsonAdded+9
llm_client.pyAdded+58
orchestrator.pyAdded+666
pending_review.jsonAdded+9
requirements.txtAdded+2
transcript_parser.pyAdded+310