"""Report writer — render a GradeResult to Markdown + JSON. Public API ---------- write_report( result: GradeResult, raw_notes: dict[int, str], deck_path: Path, out_md: Path, out_json: Path, *, run_id: str | None = None, trace_url_base: str | None = None, ) -> None Write the Markdown and JSON calibration reports. build_markdown( result: GradeResult, raw_notes: dict[int, str], deck_path: Path, *, run_id: str | None = None, trace_url_base: str | None = None, ) -> str Return the Markdown string (for tests / preview). build_json_payload(result: GradeResult, deck_path: Path) -> dict Return the JSON-serialisable payload dict. """ from __future__ import annotations import json import os from pathlib import Path from typing import Any from scripts.grader import EVAL_CATEGORIES, EVAL_MAPPING, GradeResult, PASS_BAR_MIN def _pct(value: float | None) -> str: if value is None: return "N/A" return f"{value * 100:.1f}%" def build_markdown( result: GradeResult, raw_notes: dict[int, str], deck_path: Path, *, run_id: str | None = None, trace_url_base: str | None = None, ) -> str: """Build the full Markdown calibration report string.""" lines: list[str] = [] # ---- Title ---- lines.append("# Farient Brand-Review Calibration Report") lines.append("") lines.append(f"**Deck:** `{deck_path.name}`") if run_id: lines.append(f"**Run ID:** `{run_id}`") lines.append("") # ---- Summary table ---- pass_label = "**PASS**" if result.pass_bar else "**FAIL**" lines.append("## Summary") lines.append("") lines.append("| Metric | Value |") lines.append("|--------|-------|") lines.append(f"| Total slides | {result.total_slides} |") lines.append(f"| Slides with GT issues | {result.slides_with_gt} |") lines.append(f"| Total GT eval-category issues | {result.total_gt_issues} |") lines.append(f"| Total agent findings (raw) | {result.total_agent_findings} |") lines.append(f"| Deck-level recall | {_pct(result.deck_recall)} |") lines.append(f"| Deck-level precision | {_pct(result.deck_precision)} |") lines.append(f"| Eval categories with ≥1 TP | {result.categories_with_tp} / {len(EVAL_CATEGORIES)} |") lines.append(f"| Pass-bar (≥{PASS_BAR_MIN} of {len(EVAL_CATEGORIES)}) | {pass_label} |") lines.append("") # ---- Per-eval-category breakdown ---- lines.append("## Per-Eval-Category Breakdown") lines.append("") lines.append( "| Eval Category | GT Slides | TP | FP | FN | Precision | Recall | Has TP |" ) lines.append( "|---------------|----------:|---:|---:|---:|----------:|-------:|:------:|" ) for ec in EVAL_CATEGORIES: s = result.per_category[ec] has_tp = "✓" if s.has_tp else "✗" lines.append( f"| `{ec}` | {s.gt_count} | {s.tp_count} | {s.fp_count} | {s.fn_count}" f" | {_pct(s.precision)} | {_pct(s.recall)} | {has_tp} |" ) lines.append("") # ---- Per-slide table ---- lines.append("## Per-Slide Detail") lines.append("") lines.append("| Slide | GT Eval Categories | Agent Eval Categories | Hit |") lines.append("|------:|--------------------|----------------------|:---:|") for sr in sorted(result.per_slide, key=lambda x: x.slide_n): gt_str = ", ".join(f"`{c}`" for c in sorted(sr.gt_categories)) or "—" agent_str = ", ".join(f"`{c}`" for c in sorted(sr.agent_categories)) or "—" hit_str = "✓" if sr.hit else ("—" if not sr.gt_categories else "✗") lines.append(f"| {sr.slide_n} | {gt_str} | {agent_str} | {hit_str} |") lines.append("") # ---- EVAL_MAPPING table ---- lines.append("## EVAL_MAPPING (Rubric → Eval Category Projection)") lines.append("") lines.append("_This table is the authoritative projection used by the grader._") lines.append("") lines.append("| Rubric Category | Eval Categories |") lines.append("|-----------------|-----------------|") for rubric_cat, eval_cats in EVAL_MAPPING.items(): eval_str = ", ".join(f"`{e}`" for e in eval_cats) if eval_cats else "_(none)_" lines.append(f"| `{rubric_cat}` | {eval_str} |") lines.append("") # ---- Raw notes (reviewer audit trail) ---- lines.append("## Ground-Truth Notes (Audit Trail)") lines.append("") lines.append( "Raw speaker notes and their classified eval categories, " "for reviewer auditing of the classification rules." ) lines.append("") if raw_notes: for slide_n in sorted(raw_notes.keys()): note_text = raw_notes[slide_n] lines.append(f"### Slide {slide_n}") lines.append("") lines.append("**Raw notes:**") lines.append("") lines.append("```") lines.append(note_text.strip()) lines.append("```") lines.append("") else: lines.append("_(No speaker notes found in the deck.)_") lines.append("") # ---- Trace links (if env set) ---- effective_trace_base = trace_url_base or os.environ.get("OPENAI_TRACE_URL_BASE", "") if effective_trace_base and run_id: lines.append("## Trace Links") lines.append("") lines.append(f"- [Run trace]({effective_trace_base.rstrip('/')}/{run_id})") lines.append("") return "\n".join(lines) def build_json_payload(result: GradeResult, deck_path: Path) -> dict[str, Any]: """Build the JSON-serialisable calibration report payload.""" per_cat_list = [] for ec in EVAL_CATEGORIES: s = result.per_category[ec] per_cat_list.append( { "eval_category": ec, "gt_count": s.gt_count, "tp_count": s.tp_count, "fp_count": s.fp_count, "fn_count": s.fn_count, "precision": s.precision, "recall": s.recall, "has_tp": s.has_tp, } ) per_slide_list = [ { "slide_n": sr.slide_n, "gt_categories": sorted(sr.gt_categories), "agent_categories": sorted(sr.agent_categories), "hit": sr.hit, } for sr in sorted(result.per_slide, key=lambda x: x.slide_n) ] return { "deck": str(deck_path.name), "total_slides": result.total_slides, "slides_with_gt": result.slides_with_gt, "total_gt_issues": result.total_gt_issues, "total_agent_findings": result.total_agent_findings, "deck_recall": result.deck_recall, "deck_precision": result.deck_precision, "categories_with_tp": result.categories_with_tp, "pass_bar": result.pass_bar, "pass_bar_min": PASS_BAR_MIN, "eval_categories": EVAL_CATEGORIES, "per_category": per_cat_list, "per_slide": per_slide_list, } def write_report( result: GradeResult, raw_notes: dict[int, str], deck_path: Path, out_md: Path, out_json: Path, *, run_id: str | None = None, trace_url_base: str | None = None, ) -> None: """Write Markdown and JSON calibration reports to disk. Parameters ---------- result: The :class:`GradeResult` from :func:`grader.grade`. raw_notes: Raw notes text ``{slide_n: text}`` from notes_xml; included in the Markdown for reviewer auditing. deck_path: Path to the source ``.pptx`` (used for display only). out_md: Output path for the Markdown report. out_json: Output path for the JSON report. run_id: Optional run identifier (timestamp or UUID) for trace links. trace_url_base: Optional base URL for OpenAI trace links; if omitted the ``OPENAI_TRACE_URL_BASE`` env var is consulted. """ md_text = build_markdown( result, raw_notes, deck_path, run_id=run_id, trace_url_base=trace_url_base, ) out_md.parent.mkdir(parents=True, exist_ok=True) out_md.write_text(md_text, encoding="utf-8") payload = build_json_payload(result, deck_path) out_json.parent.mkdir(parents=True, exist_ok=True) out_json.write_text( json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8" )