File size: 3,833 Bytes
ee84736
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Score a system's answers on PDF-Integrity-Bench. Standard library only.

    python3 score.py answers/milliframe-doc-forensics.jsonl
    python3 score.py my-tool.jsonl --truth truth.jsonl

An answers file is JSON Lines, one line a file of the pack:

    {"key": "<the SHA-256 of the file>", "flagged": true}

A line may name its file by "path" instead (a file of the pack is named by its SHA-256), and may
say "rejected": true for a file the system refused to read. Every other field is ignored.

A file is counted as the system left it: flagged when the system said so, and against the system
when it gave no line for the file or refused it (a miss on an altered file, a false alarm on an
untouched one).

It prints one JSON object:

- for each kind of alteration, the share of altered files that were flagged;
- for each kind of untouched file, the false alarms per 1,000 files;
- the evasion audit apart: files altered in ways that leave nothing in the file to find. No
  figure above counts them.
"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path


def lines(path: Path) -> list[dict]:
    return [json.loads(line) for line in path.read_text(encoding="utf-8").split("\n") if line.strip()]


def score(truth: list[dict], answers: list[dict]) -> dict:
    given: dict[str, dict] = {}
    for row in answers:
        key = row.get("key") or Path(str(row.get("path", ""))).stem
        if key in given:
            raise SystemExit(f"the file {key[:12]} is answered twice")
        given[key] = row
    unknown = sorted(set(given) - {row["key"] for row in truth})
    if unknown:
        raise SystemExit(f"{len(unknown)} answer(s) name no file of the pack (e.g. {unknown[0][:12]})")
    out: dict[str, float | int | None] = {}
    counted: dict[tuple[str, str], list[bool]] = {}
    missing = rejected = 0
    for row in truth:
        answer = given.get(row["key"])
        refused = bool(answer and answer.get("rejected", False))
        missing += answer is None
        rejected += refused
        if row["label"] == "attack":  # found only when the system answered and flagged it
            flagged = bool(answer and answer.get("flagged") is True and not refused)
            group = ("evasion_audit", "") if row["slice"] == "evasion_audit" else ("attack", row["attack_class"])
        else:  # a refusal or a missing line on an untouched file is a false alarm
            flagged = answer is None or refused or answer.get("flagged") is True
            group = ("benign", row["slice"])
        counted.setdefault(group, []).append(flagged)
    for (kind, name), flags in sorted(counted.items()):
        if kind == "attack":
            out[f"flag_recall_{name}"] = round(sum(flags) / len(flags), 6)
            out[f"documents_{name}"] = len(flags)
        elif kind == "benign":
            out[f"false_alarms_per_1000_{name}"] = round(1000.0 * sum(flags) / len(flags), 6)
            out[f"documents_{name}"] = len(flags)
        else:
            out["evasion_audit_flag_recall"] = round(sum(flags) / len(flags), 6)
            out["evasion_audit_documents"] = len(flags)
    return out | {"missing_outputs": missing, "rejected_inputs": rejected, "documents": len(truth)}


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("answers", type=Path, help="one JSON line a file: its key (or path) and whether it was flagged")
    parser.add_argument("--truth", type=Path, default=Path(__file__).resolve().parent / "truth.jsonl", help="the pack's truth.jsonl (default: beside this script)")
    args = parser.parse_args()
    print(json.dumps(score(lines(args.truth), lines(args.answers)), indent=2, sort_keys=True))
    return 0


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