Spaces:
Sleeping

script / orchestrator.py
Lara Monteagudo Tubau
Prepare Script app for Hugging Face Space
5b5a20d
Raw History Blame Contribute Delete
23.7 kB
"""
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 researcher
drops a completed coding file into the session folder, the orchestrator
detects 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 json
import time
import shutil
import traceback
from pathlib import Path
from datetime import datetime, timezone
from typing import Optional
# Import our pipeline modules
import sys
sys.path.insert(0, str(Path(__file__).parent))
from transcript_parser import parse_transcript, save_parsed
from agent1_segmenter import run_full_transcript, save_segments
from 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 polls
LIBRARY_ROOT = Path(__file__).parent / "library"
# Expected filenames within a session directory
F_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)