Spaces:
Sleeping

script / agent0_sectioner.py
Lara Monteagudo Tubau
Add local heuristic fallback for Agent 0 sectioning
ec3ff21
Raw History Blame Contribute Delete
16 kB
"""
agent0_sectioner.py
-------------------
Agent 0: The Structural Segmenter.
Identifies topical sections / activity phases in a Zoom transcript BEFORE
any behavioral coding takes place. This mirrors how experienced qualitative
coders 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 researcher
MUST confirm (or edit) sections before Agent 1a processes any section.
This human checkpoint prevents the "hour-long transcript overload" problem
by decomposing the session into reviewable units that match natural
conversational structure β€” not arbitrary character counts.
Agent 0 does NOT assign dimension codes. It only identifies where coherent
activity phases begin and end.
"""
from __future__ import annotations
import json
import os
import re
from collections import Counter
from pathlib import Path
from 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 = 30
MIN_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
# ---------------------------------------------------------------------------
_MEDIUM_THRESHOLD = 200 # turns; 60-char truncation above this
_LARGE_THRESHOLD = 400 # turns; 40-char truncation + sampling above this
_XLARGE_THRESHOLD = 600 # turns; 30-char truncation + 2Γ— sampling above this
def _format_turns_compact(turns: list[dict]) -> str:
"""
Adaptive prompt compression for Agent 0.
Agent 0 only needs topic-shift signals to place section boundaries β€”
it does NOT need full turn text. Aggressive truncation cuts token count
while preserving boundary-relevant information (speaker identity,
time, first few words of each turn).
Tier | Threshold | Max chars | Sampling | Est. tokens
--------|-----------|-----------|------------|-------------
Short | ≀ 200 | 120 | every turn | ~5,000
Medium | ≀ 400 | 60 | every turn | ~6,000
Large | ≀ 600 | 40 | every turn | ~8,000
X-Large | > 600 | 30 | every 2nd | ~5,500
For x-large transcripts, we sample every 2nd turn. Adjacent turns
from the same speaker are structurally redundant for section detection;
skipping them preserves all speaker-change signals while halving tokens.
A sentinel line marks each skipped block so the LLM knows turns exist.
"""
n = len(turns)
if n > _XLARGE_THRESHOLD:
maxlen, step = 30, 2
elif n > _LARGE_THRESHOLD:
maxlen, step = 40, 1
elif n > _MEDIUM_THRESHOLD:
maxlen, step = 60, 1
else:
maxlen, step = 120, 1
lines = []
i = 0
while i < len(turns):
t = turns[i]
text = t["text"][:maxlen] + "…" if len(t["text"]) > maxlen else t["text"]
lines.append(f"[{t['turn_id']:>4}] {t['start_time']} {t['speaker']}: {text}")
if step == 2 and i + 1 < len(turns):
skipped = turns[i + 1]
lines.append(
f"[{skipped['turn_id']:>4}] {skipped['start_time']} "
f"{skipped['speaker']}: (…)"
)
i += step
if step > 1:
lines.append(
f"\n[NOTE: {n} turns total; every other turn shown for brevity. "
f"Turn IDs are sequential β€” all turns exist between shown IDs.]"
)
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
# ---------------------------------------------------------------------------
# Heuristic fallback
# ---------------------------------------------------------------------------
_BOUNDARY_PATTERNS = [
re.compile(r"\b(ok|okay|right|so|well)\b.*\b(move on|next|now|let's)\b", re.I),
re.compile(r"\b(now|next|then|after that|at the same time)\b", re.I),
re.compile(r"\b(let's|we should|we need to|we have to)\b", re.I),
re.compile(r"\b(debug|fix|test|check|review|plan|summary|wrap up|finish)\b", re.I),
]
def _turn_text(turn: dict) -> str:
return f"{turn.get('speaker', '')} {turn.get('text', '')}".strip()
def _boundary_score(turn: dict) -> int:
text = _turn_text(turn)
score = 0
for pat in _BOUNDARY_PATTERNS:
if pat.search(text):
score += 1
if len(text) < 20:
score += 1
return score
def _heuristic_sections(turns: list[dict]) -> dict:
"""Simple local segmentation when the remote LLM is unavailable."""
n = len(turns)
if n == 0:
return {"sections": [], "session_overview": ""}
target = TARGET_TURNS_PER_SECTION
min_size = MIN_TURNS_PER_SECTION
sections = []
start_idx = 0
section_num = 1
while start_idx < n:
remaining = n - start_idx
if remaining <= target + 5:
end_idx = n - 1
else:
candidate = min(start_idx + target - 1, n - 1)
window_start = max(start_idx + min_size - 1, candidate - 5)
window_end = min(n - min_size, candidate + 5)
best_idx = candidate
best_score = -1
for idx in range(window_start, window_end + 1):
score = _boundary_score(turns[idx])
if score > best_score:
best_score = score
best_idx = idx
end_idx = best_idx
seg_turns = turns[start_idx : end_idx + 1]
label = f"Phase {section_num}"
texts = " ".join(t.get("text", "") for t in seg_turns).lower()
if any(k in texts for k in ["plan", "planning", "organize", "setup"]):
label = f"Planning Phase {section_num}"
elif any(k in texts for k in ["debug", "fix", "error", "bug", "issue"]):
label = f"Debugging Phase {section_num}"
elif any(k in texts for k in ["test", "testing", "try", "check"]):
label = f"Testing Phase {section_num}"
elif any(k in texts for k in ["review", "reflect", "summary", "wrap up"]):
label = f"Review Phase {section_num}"
sections.append(
{
"section_id": f"s{section_num:02d}",
"label": label,
"summary": (
f"Heuristic local segment covering {len(seg_turns)} turns. "
f"Use this as a draft when remote sectioning is unavailable."
),
"start_turn_id": seg_turns[0]["turn_id"],
"end_turn_id": seg_turns[-1]["turn_id"],
"start_time": seg_turns[0].get("start_time", ""),
"end_time": seg_turns[-1].get("end_time", ""),
}
)
start_idx = end_idx + 1
section_num += 1
overview = f"Local heuristic segmentation created {len(sections)} sections because the remote LLM was unavailable."
return {"sections": sections, "session_overview": overview}
# ---------------------------------------------------------------------------
# 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)
fallback_requested = os.environ.get("LOCAL_SECTIONING", "").strip().lower() in {"1", "true", "yes", "on"}
if fallback_requested:
print("[Agent 0] LOCAL_SECTIONING enabled β€” using heuristic fallback.")
result = _heuristic_sections(turns)
else:
try:
raw = call_llm(system_prompt, user_prompt, max_tokens=MAX_TOKENS)
result = _parse_response(raw)
except Exception as exc:
msg = str(exc).lower()
billing_error = any(token in msg for token in ["prepaid", "credit", "billing", "payment", "quota", "insufficient"])
if billing_error:
print("[Agent 0] Remote LLM billing issue detected β€” using heuristic fallback.")
result = _heuristic_sections(turns)
else:
raise
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}")