Download task_030/tests/validate_enhancements.py from Lego-X/UXInteract: direct link, hf CLI and curl.
- Browser
- Download file 5.25 kB
-
https://huggingface.co/datasets/Lego-X/UXInteract/resolve/main/task_030/tests/validate_enhancements.py
- Command line
-
hf download hf://datasets/Lego-X/UXInteract/task_030/tests/validate_enhancements.py
-
curl -L -o validate_enhancements.py https://huggingface.co/datasets/Lego-X/UXInteract/resolve/main/task_030/tests/validate_enhancements.py
5.25 kB
| import csv | |
| import math | |
| import os | |
| import pathlib | |
| import struct | |
| import subprocess | |
| import sys | |
| root = pathlib.Path.cwd() | |
| ARTIFACTS = ("anomalies.csv", "cluster_centers.csv", "anomaly_grid.png", "report.html") | |
| def clean_environment(): | |
| env = os.environ.copy() | |
| for name in ( | |
| "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", | |
| "http_proxy", "https_proxy", "all_proxy", "no_proxy", | |
| ): | |
| env.pop(name, None) | |
| env["PYTHONHASHSEED"] = "0" | |
| return env | |
| def run_candidate() -> None: | |
| scripts = [root / 'solve.py'] | |
| assert scripts, "missing candidate Python source" | |
| scripts.sort(key=lambda p: ("cifar" not in p.name.lower(), "anomal" not in p.name.lower(), str(p))) | |
| failures = [] | |
| for script in scripts[:3]: | |
| proc = subprocess.run( | |
| [sys.executable, str(script)], cwd=root, capture_output=True, | |
| text=True, timeout=60, env=clean_environment(), | |
| ) | |
| if proc.returncode == 0 and all( | |
| (root / name).is_file() | |
| for name in ARTIFACTS | |
| ): | |
| return | |
| failures.append(f"{script}: rc={proc.returncode}: {proc.stderr[-300:]}") | |
| raise AssertionError("candidate did not produce required artifacts: " + " | ".join(failures)) | |
| def read_csv(name: str): | |
| with (root / name).open(encoding="utf-8-sig", newline="") as handle: | |
| return list(csv.DictReader(handle)) | |
| def case_1_top_five_percent_contract() -> None: | |
| # ENHANCED_CASE_1: the anomaly file represents exactly the farthest 5% population. | |
| source_rows = read_csv("cifar_tiny.csv") | |
| anomaly_rows = read_csv("anomalies.csv") | |
| required = max(1, math.ceil(len(source_rows) * 0.05)) | |
| assert len(anomaly_rows) == required, ( | |
| f"expected {required} anomaly rows for {len(source_rows)} inputs, got {len(anomaly_rows)}" | |
| ) | |
| source_ids = {row["image_id"] for row in source_rows} | |
| result_ids = [row.get("image_id") for row in anomaly_rows] | |
| assert len(set(result_ids)) == len(result_ids), "anomaly image ids must be unique" | |
| assert set(result_ids) <= source_ids, "anomalies.csv contains an id absent from the fixture" | |
| for row in anomaly_rows: | |
| distance = float(row["distance"]) | |
| assert math.isfinite(distance) and distance >= 0, "anomaly distances must be finite and non-negative" | |
| def case_2_center_table_is_well_formed() -> None: | |
| # ENHANCED_CASE_2: the chosen K and reported RGB centers form a usable center table. | |
| source_rows = read_csv("cifar_tiny.csv") | |
| centers = read_csv("cluster_centers.csv") | |
| assert 2 <= len(centers) < len(source_rows), "chosen K must be non-trivial and smaller than sample count" | |
| required_columns = {"cluster", "r", "g", "b"} | |
| assert required_columns <= set(centers[0]), "center table must contain cluster,r,g,b columns" | |
| cluster_ids = [row["cluster"] for row in centers] | |
| assert len(set(cluster_ids)) == len(cluster_ids), "cluster identifiers must be unique" | |
| center_values = [] | |
| for index, center in enumerate(centers): | |
| point = [] | |
| for channel in ("r", "g", "b"): | |
| value = float(center[channel]) | |
| assert math.isfinite(value), f"center {index} {channel} is not finite" | |
| assert 0 <= value <= 255, f"center {index} {channel}={value} is outside the RGB domain" | |
| point.append(value) | |
| center_values.append(tuple(point)) | |
| assert len(set(center_values)) == len(center_values), "reported centers must not be duplicates" | |
| # A well-shaped arbitrary palette is not a fitted K-Means model. At a | |
| # converged Lloyd solution, each non-empty center is its assigned mean. | |
| groups = [[] for _ in center_values] | |
| for row in source_rows: | |
| point = tuple(float(row[channel]) for channel in ('r', 'g', 'b')) | |
| nearest = min(range(len(center_values)), key=lambda i: (math.dist(point, center_values[i]), i)) | |
| groups[nearest].append(point) | |
| for center, group in zip(center_values, groups): | |
| assert group, 'reported cluster must contain at least one source image' | |
| mean = tuple(sum(point[j] for point in group) / len(group) for j in range(3)) | |
| assert math.dist(center, mean) <= 0.01, 'center is not the mean of its nearest-assigned images' | |
| def png_size(path: pathlib.Path) -> tuple[int, int]: | |
| data = path.read_bytes() | |
| assert data[:8] == b"\x89PNG\r\n\x1a\n", "anomaly_grid.png is not a PNG" | |
| assert data[12:16] == b"IHDR" and len(data) >= 24, "PNG has no valid IHDR" | |
| return struct.unpack(">II", data[16:24]) | |
| def case_3_visualization_is_concrete() -> None: | |
| # ENHANCED_CASE_3: the saved PNG has a concrete canvas. | |
| width, height = png_size(root / "anomaly_grid.png") | |
| assert width > 0 and height > 0, "anomaly visualization must have a non-empty canvas" | |
| run_candidate() | |
| cases = [ | |
| ("ENHANCED_CASE_1", case_1_top_five_percent_contract), | |
| ("ENHANCED_CASE_2", case_2_center_table_is_well_formed), | |
| ("ENHANCED_CASE_3", case_3_visualization_is_concrete), | |
| ] | |
| failed = [] | |
| for case_id, validator in cases: | |
| try: | |
| validator() | |
| print(f"{case_id}: PASS") | |
| except Exception as exc: | |
| failed.append(case_id) | |
| print(f"{case_id}: FAIL: {exc}", file=sys.stderr) | |
| if failed: | |
| raise SystemExit(1) | |