File size: 5,265 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
import contextlib
import os
import pathlib
import shutil
import struct
import subprocess
import sys
import tempfile
from html.parser import HTMLParser

ROOT = pathlib.Path.cwd()
SKIP_PARTS = {"tests", "logs", "__pycache__", ".git", "node_modules"}


class _TextOnly(HTMLParser):
    def __init__(self):
        super().__init__()
        self.parts = []

    def handle_data(self, data):
        self.parts.append(data)


def _copy_candidate(destination: pathlib.Path) -> None:
    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: pathlib.Path):
    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):\n"
        "    raise RuntimeError('network disabled by deterministic 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",
        "WANDB_MODE": "offline",
    })
    return env


def _run_candidate(workspace: pathlib.Path) -> None:
    scripts = [workspace / 'solve.py']
    assert scripts, "missing candidate Python source"
    failures = []
    for script in scripts:
        for output in ("mnist_samples.png", "report.html"):
            (workspace / output).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 all((workspace / p).is_file() for p in ("mnist_samples.png", "report.html")):
            return
        failures.append(f"{script.name}: rc={proc.returncode} stderr={proc.stderr[-500:]}")
    raise AssertionError("no candidate script generated both outputs: " + " | ".join(failures))


@contextlib.contextmanager
def _generated_workspace():
    with tempfile.TemporaryDirectory(prefix="task049-enhanced-") as tmp:
        workspace = pathlib.Path(tmp)
        _copy_candidate(workspace)
        _run_candidate(workspace)
        yield workspace


def _visible_report_text(workspace: pathlib.Path) -> str:
    report = workspace / "report.html"
    assert report.is_file() and report.stat().st_size > 0, "missing report.html"
    parser = _TextOnly()
    parser.feed(report.read_text(encoding="utf-8", errors="ignore"))
    return " ".join(parser.parts).lower()


# ENHANCED_CASE_1: running the candidate must create the requested PNG MNIST sample display.
def case_1_generates_png_sample_display() -> None:
    with _generated_workspace() as workspace:
        path = workspace / "mnist_samples.png"
        assert path.is_file() and path.stat().st_size > 0, "missing mnist_samples.png"
        payload = path.read_bytes()
        assert payload.startswith(b"\x89PNG\r\n\x1a\n"), "mnist_samples.png lacks the PNG signature"
        assert len(payload) >= 24 and payload[12:16] == b"IHDR", "mnist_samples.png lacks an IHDR chunk"
        width, height = struct.unpack(">II", payload[16:24])
        image_header = (workspace / "train-images-idx3-ubyte").read_bytes()[:16]
        _, _, rows, cols = struct.unpack(">IIII", image_header)
        assert width >= cols and height >= rows, "sample display is smaller than one source image"


# ENHANCED_CASE_2: the report must explain the explicitly required split and transforms.
def case_2_report_explains_split_and_transforms() -> None:
    with _generated_workspace() as workspace:
        text = _visible_report_text(workspace)
        assert "80" in text and "20" in text, "report does not explain the 80%/20% split"
        transform_terms = ("transform", "normalize", "normalization", "flip", "变换", "归一化", "翻转")
        assert any(word in text for word in transform_terms), "report omits transforms"


# ENHANCED_CASE_3: the report must identify the requested MNIST classification network.
def case_3_report_identifies_mnist_network() -> None:
    with _generated_workspace() as workspace:
        text = _visible_report_text(workspace)
        assert "mnist" in text, "report does not identify the MNIST dataset"
        assert any(word in text for word in ("mlp", "network", "neural", "网络")), "report omits the MLP/network"


failures = []
for case in (
    case_1_generates_png_sample_display,
    case_2_report_explains_split_and_transforms,
    case_3_report_identifies_mnist_network,
):
    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))