File size: 6,862 Bytes
ef987bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import csv
import json
import math
import os
import pathlib
import re
import shutil
import subprocess
import sys
import tempfile


ROOT = pathlib.Path.cwd()
SKIP_PARTS = {"tests", "logs", "__pycache__", ".git", "node_modules"}
NUMBER_RE = re.compile(r"(?<![\w.])[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?(?![\w.])")


def _rows(csv_path):
    with csv_path.open(encoding="utf-8-sig", newline="") as handle:
        rows = list(csv.DictReader(handle))
    assert rows and {"url", "score", "label"} <= set(rows[0]), "CSV must have url, score, label columns"
    return rows


def _f1(rows, threshold):
    tp = fp = fn = 0
    for row in rows:
        predicted_clear = float(row["score"]) >= threshold
        actual_clear = row["label"].strip().lower() == "clear"
        tp += int(predicted_clear and actual_clear)
        fp += int(predicted_clear and not actual_clear)
        fn += int(not predicted_clear and actual_clear)
    return 2 * tp / (2 * tp + fp + fn) if (2 * tp + fp + fn) else 0.0


def _assert_optimal_report(workspace):
    rows = _rows(workspace / "test.csv")
    text = (workspace / "threshold_report.txt").read_text(encoding="utf-8", errors="ignore")
    metrics = json.loads((workspace / "threshold_metrics.json").read_text(encoding="utf-8"))
    threshold, reported_f1 = metrics["threshold"], metrics["f1"]
    assert type(threshold) in (int, float) and math.isfinite(threshold), "JSON threshold must be finite numeric"
    assert type(reported_f1) in (int, float) and math.isfinite(reported_f1), "JSON f1 must be finite numeric"
    values = [float(value) for value in NUMBER_RE.findall(text)]
    assert values, "threshold_report.txt contains no numeric threshold/F1 values"
    candidates = sorted({float(row["score"]) for row in rows})
    best_f1 = max(_f1(rows, threshold) for threshold in candidates)
    assert threshold in candidates, "JSON threshold is not a score candidate"
    assert math.isclose(_f1(rows, threshold), best_f1, abs_tol=1e-12), "JSON threshold is not optimal"
    assert math.isclose(reported_f1, best_f1, abs_tol=1e-12), "JSON f1 is not the optimum"
    number = r'([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)'
    threshold_match = re.search(r'threshold\s*[:=]\s*' + number, text, re.I)
    f1_match = re.search(r'f1(?:\s*score)?\s*[:=]\s*' + number, text, re.I)
    assert threshold_match and abs(float(threshold_match.group(1)) - threshold) <= max(0.0005, abs(threshold) * 1e-6), 'report threshold field disagrees with JSON'
    assert f1_match and abs(float(f1_match.group(1)) - best_f1) <= 0.0005, 'report F1 field disagrees with JSON'


def _copy_candidate(destination):
    for source in ROOT.iterdir():
        if source.name in SKIP_PARTS:
            continue
        target = destination / source.name
        if source.is_dir():
            shutil.copytree(source, target, ignore=shutil.ignore_patterns(*SKIP_PARTS))
        else:
            shutil.copy2(source, target)


def _offline_env(workspace):
    guard = workspace / ".test_guard"
    guard.mkdir(exist_ok=True)
    (guard / "sitecustomize.py").write_text(
        "import random, socket\n"
        "random.seed(0)\n"
        "def blocked(*args, **kwargs): raise RuntimeError('network disabled by validator')\n"
        "socket.create_connection = blocked\n"
        "socket.socket.connect = blocked\n"
        "socket.socket.connect_ex = blocked\n",
        encoding="utf-8",
    )
    env = os.environ.copy()
    env.update({"PYTHONHASHSEED": "0", "PYTHONPATH": str(guard), "HF_DATASETS_OFFLINE": "1", "TRANSFORMERS_OFFLINE": "1"})
    return env


def _run_with_rows(rows):
    holder = tempfile.TemporaryDirectory(prefix="task051-enhanced-")
    workspace = pathlib.Path(holder.name)
    _copy_candidate(workspace)
    with (workspace / "test.csv").open("w", encoding="utf-8", newline="") as handle:
        writer = csv.DictWriter(handle, fieldnames=["url", "score", "label"])
        writer.writeheader()
        writer.writerows(rows)
    script = workspace / "solve.py"
    assert script.is_file(), "missing public solve.py entrypoint"
    (workspace / "threshold_report.txt").unlink(missing_ok=True)
    (workspace / "threshold_metrics.json").unlink(missing_ok=True)
    proc = subprocess.run(
        [sys.executable, str(script)], cwd=workspace, env=_offline_env(workspace),
        capture_output=True, text=True, timeout=60,
    )
    if proc.returncode == 0 and (workspace / "threshold_report.txt").is_file() and (workspace / "threshold_metrics.json").is_file():
        return holder, workspace
    holder.cleanup()
    raise AssertionError(f"solve.py failed or did not generate outputs: rc={proc.returncode} stderr={proc.stderr[-500:]}")


# ENHANCED_CASE_1: the reported threshold must actually attain the fixture's maximum F1.
def case_1_fixture_optimum_is_real() -> None:
    _assert_optimal_report(ROOT)


# ENHANCED_CASE_2: a different valid score ordering must produce its own optimum, not a fixture constant.
def case_2_alternate_score_distribution() -> None:
    rows = [
        {"url": "a.jpg", "score": "0.91", "label": "clear"},
        {"url": "b.jpg", "score": "0.80", "label": "blurry"},
        {"url": "c.jpg", "score": "0.67", "label": "clear"},
        {"url": "d.jpg", "score": "0.45", "label": "blurry"},
    ]
    holder, workspace = _run_with_rows(rows)
    try:
        _assert_optimal_report(workspace)
    finally:
        holder.cleanup()


# ENHANCED_CASE_3: duplicate scores with conflicting labels are a legal threshold boundary case.
def case_3_tied_scores_are_evaluated_together() -> None:
    rows = [
        {"url": "tie-a.jpg", "score": "0.90", "label": "clear"},
        {"url": "tie-b.jpg", "score": "0.50", "label": "clear"},
        {"url": "tie-c.jpg", "score": "0.50", "label": "blurry"},
        {"url": "tie-d.jpg", "score": "0.10", "label": "blurry"},
    ]
    holder, workspace = _run_with_rows(rows)
    try:
        _assert_optimal_report(workspace)
    finally:
        holder.cleanup()


def case_4_all_negative_and_non_normalized_scores() -> None:
    rows = [
        {"url": "a.jpg", "score": "-3.25", "label": "blurry"},
        {"url": "b.jpg", "score": "10.5", "label": "blurry"},
        {"url": "c.jpg", "score": "10.5", "label": "blurry"},
    ]
    holder, workspace = _run_with_rows(rows)
    try:
        _assert_optimal_report(workspace)
    finally:
        holder.cleanup()


failures = []
for case in (case_1_fixture_optimum_is_real, case_2_alternate_score_distribution, case_3_tied_scores_are_evaluated_together, case_4_all_negative_and_non_normalized_scores):
    try:
        case()
        print(f"{case.__name__}: PASS")
    except Exception as error:
        failures.append(f"{case.__name__}: {error}")
        print(f"{case.__name__}: FAIL: {error}")
if failures:
    raise AssertionError("enhanced cases failed:\n" + "\n".join(failures))