File size: 10,066 Bytes
cf44ad5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Score a prompt-safety detector against the promptgate-eval benchmark.

Standard library only. Works offline.

    # against the published rule pack (downloads rules.json once)
    python eval.py --hub NagaYu/promptgate-rules

    # against a local checkout of the rule pack
    python eval.py --rules ../promptgate-rules

    # against the PromptGate Space engine in this repo (needs gradio + pandas)
    python eval.py --engine app --app-dir ..

    # machine readable
    python eval.py --rules ../promptgate-rules --json results.json

Exit code is 0 when the run completes, 1 on a setup error.
"""

from __future__ import annotations

import argparse
import json
import os
import sys
from typing import Any, Callable, Dict, List

LABELS = ("block", "sanitize", "allow")
HERE = os.path.dirname(os.path.abspath(__file__))
DEFAULT_DATA = os.path.join(HERE, "data", "dev.jsonl")


def load_cases(path: str) -> List[Dict[str, Any]]:
    """Guarantees: returns the benchmark rows, raising only if the file is unreadable."""
    rows: List[Dict[str, Any]] = []
    with open(path, "r", encoding="utf-8") as handle:
        for line in handle:
            line = line.strip()
            if line:
                rows.append(json.loads(line))
    return rows


def build_predictor(args: argparse.Namespace) -> Callable[[str], Dict[str, Any]]:
    """Guarantees: returns a text -> assessment callable for the selected engine."""
    if args.engine == "app":
        sys.path.insert(0, os.path.abspath(args.app_dir))
        import app  # type: ignore

        def predict_app(text: str) -> Dict[str, Any]:
            """Guarantees: returns the Space engine's assessment for one prompt."""
            return app.SafetyEngine.assess(text)

        return predict_app

    rules_dir = os.path.abspath(args.rules) if args.rules else os.path.join(
        os.path.dirname(HERE), "promptgate-rules")
    sys.path.insert(0, rules_dir)
    from promptgate_rules import RuleEngine  # type: ignore

    engine = RuleEngine.from_hub(args.hub) if args.hub else RuleEngine.load_default(
        os.path.join(rules_dir, "rules.json"))

    def predict_rules(text: str) -> Dict[str, Any]:
        """Guarantees: returns the standalone rule engine's assessment for one prompt."""
        return engine.assess(text)

    return predict_rules


def score(cases: List[Dict[str, Any]], predict: Callable[[str], Dict[str, Any]]) -> Dict[str, Any]:
    """Guarantees: returns accuracy, per-label PRF, confusion matrix and every miss."""
    confusion = {truth: {pred: 0 for pred in LABELS} for truth in LABELS}
    misses: List[Dict[str, Any]] = []
    by_family: Dict[str, Dict[str, int]] = {}
    by_difficulty: Dict[str, Dict[str, int]] = {}
    category_hits: Dict[str, Dict[str, int]] = {}

    for case in cases:
        report = predict(case["text"])
        predicted = str(report.get("verdict", "allow"))
        truth = str(case["label"])
        if predicted not in LABELS:
            predicted = "allow"
        confusion[truth][predicted] += 1

        fam = by_family.setdefault(case.get("family", "?"), {"n": 0, "correct": 0})
        fam["n"] += 1
        dif = by_difficulty.setdefault(case.get("difficulty", "?"), {"n": 0, "correct": 0})
        dif["n"] += 1
        if predicted == truth:
            fam["correct"] += 1
            dif["correct"] += 1
        else:
            misses.append({
                "id": case["id"], "expected": truth, "predicted": predicted,
                "family": case.get("family"), "difficulty": case.get("difficulty"),
                "lang": case.get("lang"), "notes": case.get("notes", ""),
                "text": case["text"][:110],
                "detected_types": report.get("risk_types", []),
            })

        detected = set(report.get("risk_types", []))
        for expected_type in case.get("categories", []):
            row = category_hits.setdefault(expected_type, {"expected": 0, "detected": 0})
            row["expected"] += 1
            if expected_type in detected:
                row["detected"] += 1

    total = len(cases)
    correct = sum(confusion[label][label] for label in LABELS)
    per_label: Dict[str, Dict[str, float]] = {}
    for label in LABELS:
        tp = confusion[label][label]
        fp = sum(confusion[other][label] for other in LABELS if other != label)
        fn = sum(confusion[label][other] for other in LABELS if other != label)
        precision = tp / (tp + fp) if (tp + fp) else 0.0
        recall = tp / (tp + fn) if (tp + fn) else 0.0
        f1 = (2 * precision * recall / (precision + recall)) if (precision + recall) else 0.0
        per_label[label] = {"precision": round(precision, 4), "recall": round(recall, 4),
                            "f1": round(f1, 4), "support": tp + fn}

    attacks = [c for c in cases if c["family"] == "injection"]
    attacks_flagged = sum(1 for c in attacks
                          if predict(c["text"]).get("verdict") in ("block", "sanitize"))
    benign = [c for c in cases if c["label"] == "allow"]
    benign_flagged = sum(1 for c in benign
                         if predict(c["text"]).get("verdict") != "allow")
    sensitive = [c for c in cases if c["family"] in ("pii", "secret")]
    sensitive_caught = sum(1 for c in sensitive
                           if predict(c["text"]).get("verdict") in ("sanitize", "block"))

    return {
        "cases": total,
        "exact_verdict_accuracy": round(correct / total, 4) if total else 0.0,
        "per_label": per_label,
        "confusion_matrix": confusion,
        "attack_flag_rate": round(attacks_flagged / len(attacks), 4) if attacks else 0.0,
        "benign_false_positive_rate": round(benign_flagged / len(benign), 4) if benign else 0.0,
        "sensitive_redaction_rate": round(sensitive_caught / len(sensitive), 4) if sensitive else 0.0,
        "by_family": {k: {"n": v["n"], "accuracy": round(v["correct"] / v["n"], 4)}
                      for k, v in sorted(by_family.items())},
        "by_difficulty": {k: {"n": v["n"], "accuracy": round(v["correct"] / v["n"], 4)}
                          for k, v in sorted(by_difficulty.items())},
        "category_recall": {k: {"expected": v["expected"], "detected": v["detected"],
                                "recall": round(v["detected"] / v["expected"], 4)}
                            for k, v in sorted(category_hits.items())},
        "misses": misses,
    }


def to_markdown(results: Dict[str, Any], title: str) -> str:
    """Guarantees: renders the results dict as a Markdown report string."""
    lines = ["## {}".format(title), ""]
    lines.append("- cases: **{}**".format(results["cases"]))
    lines.append("- exact verdict accuracy: **{:.1%}**".format(results["exact_verdict_accuracy"]))
    lines.append("- attacks flagged (block or sanitize): **{:.1%}**".format(results["attack_flag_rate"]))
    lines.append("- PII/secret prompts redacted: **{:.1%}**".format(results["sensitive_redaction_rate"]))
    lines.append("- benign false-positive rate: **{:.1%}**".format(results["benign_false_positive_rate"]))
    lines.append("")
    lines.append("| verdict | precision | recall | F1 | support |")
    lines.append("| --- | --- | --- | --- | --- |")
    for label in LABELS:
        row = results["per_label"][label]
        lines.append("| {} | {:.3f} | {:.3f} | {:.3f} | {} |".format(
            label, row["precision"], row["recall"], row["f1"], row["support"]))
    lines.append("")
    lines.append("| family | n | accuracy |")
    lines.append("| --- | --- | --- |")
    for name, row in results["by_family"].items():
        lines.append("| {} | {} | {:.1%} |".format(name, row["n"], row["accuracy"]))
    lines.append("")
    if results["misses"]:
        lines.append("### Misses ({})".format(len(results["misses"])))
        lines.append("")
        lines.append("| id | expected | predicted | why it is hard |")
        lines.append("| --- | --- | --- | --- |")
        for miss in results["misses"]:
            lines.append("| `{}` | {} | {} | {} |".format(
                miss["id"], miss["expected"], miss["predicted"],
                miss["notes"] or miss["text"][:60]))
    else:
        lines.append("No misses.")
    lines.append("")
    return "\n".join(lines)


def main() -> int:
    """Guarantees: runs the benchmark, prints a report, and returns an exit code."""
    parser = argparse.ArgumentParser(description="Evaluate a detector on promptgate-eval.")
    parser.add_argument("--data", default=DEFAULT_DATA, help="path to eval.jsonl")
    parser.add_argument("--engine", choices=["rules", "app"], default="rules",
                        help="'rules' = standalone rule pack, 'app' = PromptGate Space engine")
    parser.add_argument("--rules", default="", help="directory holding rules.json + promptgate_rules.py")
    parser.add_argument("--hub", default="", help="load the rule pack from this Hub repo id")
    parser.add_argument("--app-dir", default="..", help="directory containing app.py (for --engine app)")
    parser.add_argument("--json", default="", help="write the full results JSON here")
    parser.add_argument("--markdown", default="", help="write a Markdown report here")
    args = parser.parse_args()

    try:
        cases = load_cases(args.data)
        predict = build_predictor(args)
    except Exception as exc:
        print("setup failed: {}: {}".format(type(exc).__name__, exc), file=sys.stderr)
        return 1

    results = score(cases, predict)
    title = "promptgate-eval - {} engine".format(args.engine)
    report = to_markdown(results, title)
    print(report)

    if args.json:
        with open(args.json, "w", encoding="utf-8") as handle:
            json.dump(results, handle, ensure_ascii=False, indent=2)
            handle.write("\n")
        print("wrote {}".format(args.json))
    if args.markdown:
        with open(args.markdown, "w", encoding="utf-8") as handle:
            handle.write(report)
        print("wrote {}".format(args.markdown))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())