File size: 8,411 Bytes
fdfe81a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
"""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"
    )