File size: 12,363 Bytes
e091e85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
#!/usr/bin/env python3
"""Score CausalMedBench prediction JSONL files.

The script downloads only benchmark metadata when images are not accessed.
Predictions are joined by stable ``record_id`` values, so file order is ignored.
"""

from __future__ import annotations

import argparse
import json
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any, Iterable

from datasets import load_dataset


REPO_ID = "leaf0932/CausalMedBench"
VIEWS = (
    "forged_original",
    "authentic_source",
    "local_restored",
    "local_forged_only",
    "authentic_nuisance",
)
EXPECTED_REASONING = {
    "forged_original": (
        "fake",
        {"mixed"},
        {"mixed", "local_bbox"},
    ),
    "authentic_source": ("real", {"none"}, {"none"}),
    "local_restored": ("fake", {"global_forensic"}, {"global_or_outside"}),
    "local_forged_only": (
        "fake",
        {"local_medical", "local_forensic", "local_medical_and_local_forensic"},
        {"local_bbox"},
    ),
    "authentic_nuisance": ("real", {"none"}, {"none"}),
}


def read_jsonl(path: Path) -> Iterable[dict[str, Any]]:
    with path.open("r", encoding="utf-8") as stream:
        for line_number, line in enumerate(stream, start=1):
            if not line.strip():
                continue
            try:
                value = json.loads(line)
            except json.JSONDecodeError as error:
                raise ValueError(f"Invalid JSON at {path}:{line_number}: {error}") from error
            if not isinstance(value, dict):
                raise ValueError(f"Expected an object at {path}:{line_number}")
            yield value


def normalize_label(value: Any) -> str | None:
    label = str(value or "").strip().lower()
    if label.startswith("verdict:"):
        label = label.split(":", 1)[1].strip()
    return label if label in {"real", "fake"} else None


def prediction_index(path: Path) -> dict[str, dict[str, Any]]:
    result: dict[str, dict[str, Any]] = {}
    for row in read_jsonl(path):
        record_id = str(row.get("record_id") or "").strip()
        if not record_id:
            raise ValueError(f"Missing record_id in {path}")
        if record_id in result:
            raise ValueError(f"Duplicate record_id in {path}: {record_id}")
        label = normalize_label(row.get("verdict", row.get("label")))
        result[record_id] = {**row, "label": label}
    return result


def ground_truth_rows(dataset: Any) -> list[dict[str, Any]]:
    columns = [name for name in dataset.column_names if name != "image"]
    return [{name: row[name] for name in columns} for row in dataset]


def merge_predictions(
    truth: list[dict[str, Any]],
    predictions: dict[str, dict[str, Any]],
    *,
    strict: bool,
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
    truth_ids = {str(row["record_id"]) for row in truth}
    unknown = sorted(set(predictions) - truth_ids)
    if unknown:
        raise ValueError(f"Predictions contain {len(unknown)} unknown record_id values; first: {unknown[0]}")
    merged = []
    missing = []
    for row in truth:
        record_id = str(row["record_id"])
        prediction = predictions.get(record_id)
        if prediction is None:
            missing.append(record_id)
            prediction = {"label": None}
        merged.append({**row, "prediction": prediction})
    if strict and missing:
        raise ValueError(f"Missing {len(missing)} predictions; first: {missing[0]}")
    return merged, {
        "expected": len(truth),
        "submitted": len(predictions),
        "matched": len(truth) - len(missing),
        "missing": len(missing),
        "coverage": (len(truth) - len(missing)) / len(truth) if truth else 0.0,
    }


def binary_metrics(rows: list[dict[str, Any]]) -> dict[str, Any]:
    matrix: Counter[tuple[str, str]] = Counter()
    parsed = 0
    for row in rows:
        target = str(row["target_label"]).lower()
        predicted = row["prediction"].get("label")
        if predicted in {"real", "fake"}:
            parsed += 1
            matrix[(target, predicted)] += 1
    tp = matrix[("fake", "fake")]
    tn = matrix[("real", "real")]
    fp = matrix[("real", "fake")]
    fn = matrix[("fake", "real")]
    fake_precision = tp / (tp + fp) if tp + fp else 0.0
    fake_recall = tp / (tp + fn) if tp + fn else 0.0
    fake_f1 = (
        2 * fake_precision * fake_recall / (fake_precision + fake_recall)
        if fake_precision + fake_recall
        else 0.0
    )
    real_precision = tn / (tn + fn) if tn + fn else 0.0
    real_recall = tn / (tn + fp) if tn + fp else 0.0
    real_f1 = (
        2 * real_precision * real_recall / (real_precision + real_recall)
        if real_precision + real_recall
        else 0.0
    )
    n = len(rows)
    return {
        "n": n,
        "parsed": parsed,
        "coverage": parsed / n if n else 0.0,
        "accuracy": (tp + tn) / n if n else 0.0,
        "fake_precision": fake_precision,
        "fake_recall": fake_recall,
        "fake_f1": fake_f1,
        "macro_f1": (fake_f1 + real_f1) / 2,
        "confusion": {"tp_fake": tp, "tn_real": tn, "fp_fake": fp, "fn_fake": fn},
    }


def grouped_metrics(rows: list[dict[str, Any]], field: str) -> dict[str, Any]:
    groups: dict[str, list[dict[str, Any]]] = defaultdict(list)
    for row in rows:
        groups[str(row.get(field) or "unknown")].append(row)
    return {key: binary_metrics(values) for key, values in sorted(groups.items())}


def five_view_metrics(rows: list[dict[str, Any]]) -> dict[str, Any]:
    by_view: dict[str, list[dict[str, Any]]] = defaultdict(list)
    by_group: dict[str, dict[str, dict[str, Any]]] = defaultdict(dict)
    for row in rows:
        by_view[str(row["view_id"])].append(row)
        by_group[str(row["group_id"])][str(row["view_id"])] = row
    complete = 0
    all_correct = 0
    contrast = Counter()
    for views in by_group.values():
        if not set(VIEWS).issubset(views):
            continue
        complete += 1
        labels = {view: views[view]["prediction"].get("label") for view in VIEWS}
        contrast["authentic_recovery"] += int(
            labels["forged_original"] == "fake" and labels["authentic_source"] == "real"
        )
        contrast["global_evidence_sufficiency"] += int(
            labels["forged_original"] == "fake" and labels["local_restored"] == "fake"
        )
        contrast["local_evidence_sufficiency"] += int(
            labels["authentic_source"] == "real" and labels["local_forged_only"] == "fake"
        )
        contrast["benign_nuisance_invariance"] += int(
            labels["authentic_source"] == "real" and labels["authentic_nuisance"] == "real"
        )
        targets = {view: ("real" if view in {"authentic_source", "authentic_nuisance"} else "fake") for view in VIEWS}
        all_correct += int(all(labels[view] == targets[view] for view in VIEWS))
    return {
        "overall": binary_metrics(rows),
        "by_view": {key: binary_metrics(values) for key, values in sorted(by_view.items())},
        "complete_groups": complete,
        "five_view_consistency": all_correct / complete if complete else 0.0,
        "paired_contrasts": {
            key: value / complete if complete else 0.0 for key, value in sorted(contrast.items())
        },
        "by_modality": grouped_metrics(rows, "modality"),
        "by_forgery_type": grouped_metrics(rows, "forgery_type"),
        "by_generator": grouped_metrics(rows, "generator"),
    }


def reasoning_metrics(rows: list[dict[str, Any]]) -> dict[str, Any]:
    totals = Counter()
    by_view: dict[str, Counter[str]] = defaultdict(Counter)
    group_checks: dict[str, list[bool]] = defaultdict(list)
    failures = []
    for row in rows:
        view = str(row["view_id"])
        expected_label, expected_types, expected_locations = EXPECTED_REASONING[view]
        prediction = row["prediction"]
        evidence_type = str(prediction.get("evidence_type") or "").strip().lower()
        location = str(prediction.get("evidence_location") or "").strip().lower()
        label_ok = prediction.get("label") == expected_label
        type_ok = evidence_type in expected_types
        location_ok = location in expected_locations
        joint = label_ok and type_ok and location_ok
        values = {
            "n": 1,
            "verdict_ok": int(label_ok),
            "evidence_type_ok": int(type_ok),
            "evidence_location_ok": int(location_ok),
            "joint_alignment": int(joint),
        }
        totals.update(values)
        by_view[view].update(values)
        group_checks[str(row["group_id"])].append(joint)
        if not joint and len(failures) < 20:
            failures.append({
                "record_id": row["record_id"],
                "expected": {
                    "verdict": expected_label,
                    "evidence_type": sorted(expected_types),
                    "evidence_location": sorted(expected_locations),
                },
                "prediction": prediction,
            })

    def rates(values: Counter[str]) -> dict[str, float | int]:
        n = values["n"]
        return {key: (value if key == "n" else value / n if n else 0.0) for key, value in values.items()}

    return {
        "overall": rates(totals),
        "by_view": {key: rates(values) for key, values in sorted(by_view.items())},
        "five_view_strict_alignment": (
            sum(len(values) == len(VIEWS) and all(values) for values in group_checks.values())
            / len(group_checks)
            if group_checks
            else 0.0
        ),
        "failure_examples": failures,
    }


def load_truth(repo_id: str, cache_dir: str | None) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
    ordinary = load_dataset(repo_id, "ordinary", split="test", cache_dir=cache_dir)
    five_view = load_dataset(repo_id, "five_view", split="test", cache_dir=cache_dir)
    return ground_truth_rows(ordinary), ground_truth_rows(five_view)


def main() -> None:
    parser = argparse.ArgumentParser(description="Score a CausalMedBench submission")
    parser.add_argument("--ordinary-predictions", type=Path)
    parser.add_argument("--five-view-predictions", type=Path)
    parser.add_argument("--reasoning-predictions", type=Path)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--repo-id", default=REPO_ID)
    parser.add_argument("--cache-dir")
    parser.add_argument("--allow-partial", action="store_true")
    args = parser.parse_args()
    if not any((args.ordinary_predictions, args.five_view_predictions, args.reasoning_predictions)):
        parser.error("provide at least one prediction file")

    ordinary_truth, five_view_truth = load_truth(args.repo_id, args.cache_dir)
    report: dict[str, Any] = {
        "schema_version": "causalmedbench-score-v1.0",
        "repo_id": args.repo_id,
    }
    strict = not args.allow_partial
    if args.ordinary_predictions:
        rows, coverage = merge_predictions(
            ordinary_truth, prediction_index(args.ordinary_predictions), strict=strict
        )
        report["ordinary_submission"] = coverage
        report["ordinary_task"] = {
            "overall": binary_metrics(rows),
            "by_modality": grouped_metrics(rows, "modality"),
            "by_forgery_type": grouped_metrics(rows, "forgery_type"),
            "by_generator": grouped_metrics(rows, "generator"),
        }
    if args.five_view_predictions:
        rows, coverage = merge_predictions(
            five_view_truth, prediction_index(args.five_view_predictions), strict=strict
        )
        report["five_view_submission"] = coverage
        report["five_view"] = five_view_metrics(rows)
    if args.reasoning_predictions:
        reasoning_truth = [row for row in five_view_truth if row.get("is_reasoning_subset")]
        rows, coverage = merge_predictions(
            reasoning_truth, prediction_index(args.reasoning_predictions), strict=strict
        )
        report["reasoning_submission"] = coverage
        report["explanation_alignment"] = reasoning_metrics(rows)

    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps(report, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()