File size: 10,036 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
293
294
295
296
297
298
299
300
"""Grader — match agent findings to ground-truth eval categories and compute
precision/recall.

Public API
----------
EVAL_MAPPING : dict[str, list[str]]
    Mapping from rubric_category → list[eval_category].  This is the ONLY
    place that mapping lives; ``calibrate.py`` and ``report.py`` import it
    from here for display purposes.

EVAL_CATEGORIES : list[str]
    The 6 fixed pass-bar eval categories.

project_findings(findings: list[FindingLike], slide_n: int) -> set[str]
    Return the set of eval categories covered by *findings* on *slide_n*
    after projecting through EVAL_MAPPING.

GradeResult
    Dataclass holding per-eval-category and per-slide stats.

grade(
    agent_findings: dict[int, list[FindingLike]],
    ground_truth: dict[int, set[str]],
) -> GradeResult
    Top-level grading entry point.
"""
from __future__ import annotations

from dataclasses import dataclass, field
from typing import Protocol, runtime_checkable


# ---------------------------------------------------------------------------
# The 6 fixed eval categories
# ---------------------------------------------------------------------------

EVAL_CATEGORIES: list[str] = [
    "confidentiality_statement",
    "slide_title_position",
    "table_labeling",
    "key_vs_legend",
    "spacing",
    "terminology",
]

PASS_BAR_MIN: int = 4  # ≥4 of 6 eval categories must have ≥1 true-positive


# ---------------------------------------------------------------------------
# EVAL_MAPPING (rubric_category → eval_category[])
# Locked per Carmack-reviewed spec.  Edit here only.
# ---------------------------------------------------------------------------

EVAL_MAPPING: dict[str, list[str]] = {
    "title_slide":               ["slide_title_position"],
    "slide_title":               ["slide_title_position"],
    "confidentiality_statement": ["confidentiality_statement"],
    "bullets":                   ["spacing", "terminology"],
    "tables_overall":            ["table_labeling", "spacing"],
    "table_title":               ["table_labeling"],
    "table_header":              ["table_labeling"],
    "table_body":                ["spacing"],
    "statistics_row":            ["table_labeling"],
    "client_row":                ["table_labeling"],
    "chart_title":               ["spacing"],
    "chart_content":             ["key_vs_legend"],
    "chart_source_notes":        ["spacing"],
    "shapes":                    ["spacing"],
    "footnotes":                 ["terminology"],
    "emphasis_annotations":      [],
    "writing_style":             ["terminology"],
    "terminology":               ["terminology", "table_labeling"],
    "color_palette":             [],
    "section_header":            [],
}


# ---------------------------------------------------------------------------
# Minimal structural protocol — avoids importing the Pydantic Finding model
# so grader.py can be unit-tested with lightweight dicts/namedtuples.
# ---------------------------------------------------------------------------


@runtime_checkable
class FindingLike(Protocol):
    """Anything with a ``category`` string attribute is a FindingLike."""

    @property
    def category(self) -> str: ...  # noqa: E704


# ---------------------------------------------------------------------------
# Projection
# ---------------------------------------------------------------------------


def project_findings(findings: list[FindingLike], slide_n: int | None = None) -> set[str]:
    """Return eval categories covered by *findings* after EVAL_MAPPING projection.

    Parameters
    ----------
    findings:
        Agent findings for a single slide (or any collection).  Each must
        expose a ``.category`` attribute matching a key in EVAL_MAPPING.
    slide_n:
        Ignored; retained for call-site readability.

    Returns
    -------
    set[str]
        Union of all eval categories the findings map to.  Unknown rubric
        categories (not in EVAL_MAPPING) are silently ignored.
    """
    result: set[str] = set()
    for f in findings:
        for ec in EVAL_MAPPING.get(f.category, []):
            result.add(ec)
    return result


# ---------------------------------------------------------------------------
# Data classes for grading output
# ---------------------------------------------------------------------------


@dataclass
class EvalCategoryStats:
    """Per-eval-category precision/recall numbers."""

    eval_category: str
    # Ground-truth: number of slides that have this category in GT
    gt_count: int = 0
    # True positives: slides where both agent and GT have this category
    tp_count: int = 0
    # False positives: slides where agent has this category but GT does not
    fp_count: int = 0
    # False negatives: slides where GT has this category but agent does not
    fn_count: int = 0

    @property
    def precision(self) -> float | None:
        """Precision = TP / (TP + FP).  None if no agent predictions."""
        denom = self.tp_count + self.fp_count
        return self.tp_count / denom if denom > 0 else None

    @property
    def recall(self) -> float | None:
        """Recall = TP / (TP + FN).  None if no ground-truth items."""
        return self.tp_count / self.gt_count if self.gt_count > 0 else None

    @property
    def has_tp(self) -> bool:
        return self.tp_count > 0


@dataclass
class SlideResult:
    """Per-slide grading summary."""

    slide_n: int
    gt_categories: set[str]
    agent_categories: set[str]
    hit: bool  # True if any overlap between gt and agent


@dataclass
class GradeResult:
    """Top-level result returned by :func:`grade`."""

    total_slides: int = 0
    slides_with_gt: int = 0  # slides that have ≥1 GT eval category
    slides_with_agent: int = 0  # slides that have ≥1 agent finding
    total_gt_issues: int = 0  # sum of |GT categories| over all slides
    total_agent_findings: int = 0  # total number of agent findings (raw)

    per_category: dict[str, EvalCategoryStats] = field(default_factory=dict)
    per_slide: list[SlideResult] = field(default_factory=list)

    # Pass-bar
    pass_bar: bool = False  # True if ≥PASS_BAR_MIN eval categories have ≥1 TP
    categories_with_tp: int = 0

    @property
    def deck_recall(self) -> float | None:
        """Deck-level recall = slides_with_hit / slides_with_gt."""
        if self.slides_with_gt == 0:
            return None
        hits = sum(1 for s in self.per_slide if s.hit)
        return hits / self.slides_with_gt

    @property
    def deck_precision(self) -> float | None:
        """Deck-level precision = slides_with_hit / slides_with_agent."""
        if self.slides_with_agent == 0:
            return None
        hits = sum(1 for s in self.per_slide if s.hit)
        return hits / self.slides_with_agent


# ---------------------------------------------------------------------------
# Main grading entry point
# ---------------------------------------------------------------------------


def grade(
    agent_findings: dict[int, list[FindingLike]],
    ground_truth: dict[int, set[str]],
    *,
    total_slides: int | None = None,
) -> GradeResult:
    """Compute precision/recall of agent findings against ground-truth.

    Parameters
    ----------
    agent_findings:
        ``{slide_n: [Finding, ...]}`` — agent findings indexed by 1-based
        slide number.  Each finding must expose ``.category``.
    ground_truth:
        ``{slide_n: set[eval_category]}`` — from
        :func:`scripts.ground_truth.classify_notes`.
    total_slides:
        Total slide count in the deck.  If omitted, inferred from the union
        of keys in *agent_findings* and *ground_truth*.

    Returns
    -------
    GradeResult
    """
    # Determine slide universe.
    all_slides = set(agent_findings.keys()) | set(ground_truth.keys())
    if total_slides is not None:
        all_slides = all_slides | set(range(1, total_slides + 1))
    n_total = total_slides if total_slides is not None else (max(all_slides) if all_slides else 0)

    # Initialise per-category stats.
    per_cat: dict[str, EvalCategoryStats] = {
        ec: EvalCategoryStats(eval_category=ec) for ec in EVAL_CATEGORIES
    }

    per_slide: list[SlideResult] = []
    total_gt_issues = 0
    total_agent_raw = sum(len(v) for v in agent_findings.values())
    slides_with_gt = 0
    slides_with_agent = 0

    for slide_n in sorted(all_slides):
        findings = agent_findings.get(slide_n, [])
        gt_cats = ground_truth.get(slide_n, set())

        agent_cats = project_findings(findings, slide_n)

        if gt_cats:
            slides_with_gt += 1
            total_gt_issues += len(gt_cats)
        if agent_cats:
            slides_with_agent += 1

        # Slide-level hit: any overlap between agent eval cats and GT eval cats.
        hit = bool(agent_cats & gt_cats)

        per_slide.append(
            SlideResult(
                slide_n=slide_n,
                gt_categories=gt_cats,
                agent_categories=agent_cats,
                hit=hit,
            )
        )

        # Per-category accounting.
        for ec in EVAL_CATEGORIES:
            stats = per_cat[ec]
            in_gt = ec in gt_cats
            in_agent = ec in agent_cats

            if in_gt:
                stats.gt_count += 1
            if in_gt and in_agent:
                stats.tp_count += 1
            if in_agent and not in_gt:
                stats.fp_count += 1
            if in_gt and not in_agent:
                stats.fn_count += 1

    # Pass-bar.
    cats_with_tp = sum(1 for s in per_cat.values() if s.has_tp)
    pass_bar = cats_with_tp >= PASS_BAR_MIN

    return GradeResult(
        total_slides=n_total,
        slides_with_gt=slides_with_gt,
        slides_with_agent=slides_with_agent,
        total_gt_issues=total_gt_issues,
        total_agent_findings=total_agent_raw,
        per_category=per_cat,
        per_slide=per_slide,
        pass_bar=pass_bar,
        categories_with_tp=cats_with_tp,
    )