File size: 9,974 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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
"""Calibration harness CLI for the Farient brand-review agentic system.

Usage
-----
    cd apps/api
    uv run python -m scripts.calibrate \\
        --deck "../../Doc Reference/Annotated_20260511 IDEXX Peer Group Assessment - DRAFT 20260330 (3).pptx" \\
        --out calibration_report.md \\
        --json calibration_report.json \\
        [--cached]

Options
-------
--deck PATH     Path to the annotated IDEXX .pptx file.
--out PATH      Output path for the Markdown report.  [default: calibration_report.md]
--json PATH     Output path for the JSON report.      [default: calibration_report.json]
--cached        Re-use the most recent cached agent run from calibration_runs/<ts>/
                instead of calling OpenAI.  Critical for re-grading without re-paying.

Caching
-------
Each live run writes its FinalAuditResult JSON to:
    calibration_runs/<ISO-timestamp>/final.json

Pass --cached to load the latest directory.  You can also seed
    calibration_runs/synthetic/final.json
with hand-crafted data for smoke-testing without any OpenAI calls.
"""
from __future__ import annotations

import argparse
import asyncio
import json
import logging
import os
import sys
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path

# Load apps/api/.env (gitignored) so the CLI picks up OPENAI_API_KEY without
# requiring a shell export. Real shell env still wins (override=False).
from dotenv import load_dotenv as _load_dotenv
_load_dotenv(Path(__file__).resolve().parent.parent / ".env", override=True)

# ---- ensure apps/api is on sys.path when run as -m scripts.calibrate -------
_HERE = Path(__file__).resolve().parent          # apps/api/scripts/
_API_ROOT = _HERE.parent                          # apps/api/
if str(_API_ROOT) not in sys.path:
    sys.path.insert(0, str(_API_ROOT))

from agents.output_schemas import FinalAuditResult  # noqa: E402
from scripts.grader import grade  # noqa: E402
from scripts.ground_truth import extract_ground_truth  # noqa: E402
from scripts.report import write_report  # noqa: E402


logger = logging.getLogger(__name__)
logging.basicConfig(
    level=logging.INFO,
    format="%(levelname)s  %(name)s  %(message)s",
)


# ---------------------------------------------------------------------------
# Cache helpers
# ---------------------------------------------------------------------------

_RUNS_DIR = _API_ROOT / "calibration_runs"


def _list_cached_runs() -> list[Path]:
    """Return calibration_runs/* dirs sorted oldest→newest."""
    if not _RUNS_DIR.exists():
        return []
    return sorted(
        [d for d in _RUNS_DIR.iterdir() if d.is_dir() and (d / "final.json").exists()]
    )


def _latest_cached_run() -> Path | None:
    runs = _list_cached_runs()
    return runs[-1] if runs else None


def _save_run(result: FinalAuditResult) -> Path:
    """Write FinalAuditResult JSON to calibration_runs/<timestamp>/final.json."""
    ts = datetime.now(tz=timezone.utc).strftime("%Y%m%dT%H%M%SZ")
    run_dir = _RUNS_DIR / ts
    run_dir.mkdir(parents=True, exist_ok=True)
    out = run_dir / "final.json"
    out.write_text(
        json.dumps(result.model_dump(), indent=2, ensure_ascii=False),
        encoding="utf-8",
    )
    logger.info("Agent output cached → %s", out)
    return run_dir


def _load_cached_run(run_dir: Path) -> FinalAuditResult:
    """Load and validate a cached FinalAuditResult from *run_dir/final.json*."""
    payload = json.loads((run_dir / "final.json").read_text(encoding="utf-8"))
    return FinalAuditResult.model_validate(payload)


# ---------------------------------------------------------------------------
# FindingLike adapter (wraps FinalAuditResult findings for grader)
# ---------------------------------------------------------------------------


@dataclass
class _FindingAdapter:
    """Thin wrapper so agent Finding fields satisfy grader.FindingLike."""

    category: str


def _build_agent_findings(
    result: FinalAuditResult,
) -> dict[int, list[_FindingAdapter]]:
    """Extract ``{slide_n: [FindingAdapter, ...]}`` from a FinalAuditResult."""
    out: dict[int, list[_FindingAdapter]] = {}
    for slide_env in result.slides:
        adapters = [_FindingAdapter(category=f.category) for f in slide_env.findings]
        if adapters:
            out[slide_env.slide_number] = adapters
    return out


# ---------------------------------------------------------------------------
# Live agent run
# ---------------------------------------------------------------------------


async def _run_live(deck_path: Path, job_id: str) -> FinalAuditResult:
    """Run the full agent pipeline against *deck_path* and return the result."""
    # Import here to avoid loading the agent stack when running --cached.
    from agents.runner import run_audit  # noqa: PLC0415
    from agents.context import AuditContext  # noqa: PLC0415
    from rubric.loader import load_rubric  # noqa: PLC0415
    from services.parser import parse_deck  # noqa: PLC0415
    from services.renderer import render_deck  # noqa: PLC0415

    logger.info("Parsing deck: %s", deck_path)
    parsed = parse_deck(deck_path)

    logger.info("Rendering deck (%d slides)…", parsed.slide_count)
    render_result = render_deck(deck_path, out_dir=_API_ROOT / "tmp" / job_id)

    logger.info("Loading rubric…")
    rubric = load_rubric()

    ctx = AuditContext(
        parsed_deck=parsed,
        render_result=render_result,
        rubric=rubric,
        out_dir=_API_ROOT / "tmp" / job_id,
    )

    logger.info("Running agentic audit (this may take a few minutes)…")
    result = await run_audit(ctx, job_id, file_name=deck_path.name)
    return result


# ---------------------------------------------------------------------------
# CLI entry point
# ---------------------------------------------------------------------------


def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        prog="scripts.calibrate",
        description=(
            "Calibration harness: run the agentic review on an annotated IDEXX deck "
            "and produce a precision/recall report."
        ),
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=__doc__,
    )
    parser.add_argument(
        "--deck",
        required=True,
        metavar="PATH",
        help="Path to the annotated IDEXX .pptx file.",
    )
    parser.add_argument(
        "--out",
        default="calibration_report.md",
        metavar="PATH",
        help="Output path for the Markdown report. [default: calibration_report.md]",
    )
    parser.add_argument(
        "--json",
        default="calibration_report.json",
        metavar="PATH",
        dest="json_out",
        help="Output path for the JSON report. [default: calibration_report.json]",
    )
    parser.add_argument(
        "--cached",
        action="store_true",
        help=(
            "Re-use the most recent cached agent output instead of calling OpenAI. "
            "Looks for calibration_runs/<latest>/final.json."
        ),
    )
    return parser.parse_args(argv)


def main(argv: list[str] | None = None) -> int:
    args = _parse_args(argv)

    deck_path = Path(args.deck).resolve()
    if not deck_path.exists():
        logger.error("Deck not found: %s", deck_path)
        return 1

    out_md = Path(args.out)
    out_json = Path(args.json_out)

    # ---- Obtain agent result (cached or live) --------------------------------
    run_id: str | None = None
    if args.cached:
        run_dir = _latest_cached_run()
        if run_dir is None:
            logger.error(
                "--cached specified but no calibration_runs/ directory found. "
                "Run without --cached first, or seed calibration_runs/synthetic/final.json."
            )
            return 1
        logger.info("Loading cached run: %s", run_dir)
        result = _load_cached_run(run_dir)
        run_id = run_dir.name
    else:
        job_id = f"calib_{datetime.now(tz=timezone.utc).strftime('%Y%m%dT%H%M%SZ')}"
        result = asyncio.run(_run_live(deck_path, job_id))
        run_dir = _save_run(result)
        run_id = run_dir.name

    # ---- Extract ground truth -----------------------------------------------
    logger.info("Extracting ground-truth notes from deck…")
    raw_notes, ground_truth = extract_ground_truth(deck_path)
    logger.info(
        "Ground truth: %d slides with annotated eval categories",
        len(ground_truth),
    )

    # ---- Build agent findings dict ------------------------------------------
    agent_findings = _build_agent_findings(result)
    logger.info(
        "Agent findings: %d slides with findings",
        len(agent_findings),
    )

    # ---- Grade ---------------------------------------------------------------
    grade_result = grade(
        agent_findings,
        ground_truth,
        total_slides=result.slide_count,
    )

    # ---- Report --------------------------------------------------------------
    trace_url_base = os.environ.get("OPENAI_TRACE_URL_BASE", "")
    write_report(
        grade_result,
        raw_notes,
        deck_path,
        out_md=out_md,
        out_json=out_json,
        run_id=run_id,
        trace_url_base=trace_url_base or None,
    )

    # ---- Print summary -------------------------------------------------------
    status = "PASS" if grade_result.pass_bar else "FAIL"
    print(f"\nCalibration complete — pass-bar: {status}")
    print(f"  Eval categories with ≥1 TP: {grade_result.categories_with_tp}/6")
    print(f"  Deck recall:    {_fmt_pct(grade_result.deck_recall)}")
    print(f"  Deck precision: {_fmt_pct(grade_result.deck_precision)}")
    print(f"  Report:  {out_md}")
    print(f"  JSON:    {out_json}")

    return 0


def _fmt_pct(v: float | None) -> str:
    return f"{v * 100:.1f}%" if v is not None else "N/A"


if __name__ == "__main__":
    sys.exit(main())