UXInteract / task_034 /tests /validate_enhanced.py
DojiSum's picture
Publish the current 141-task UXInteract release
ef987bb verified
Raw History Blame Contribute Delete
6.18 kB
import os
import pathlib
import shutil
import subprocess
import sys
import tempfile
import numpy as np
from PIL import Image
ROOT = pathlib.Path.cwd()
SKIP_PARTS = {"tests", "logs", "__pycache__", ".git", "node_modules"}
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_candidate(workspace):
scripts = [workspace / 'solve.py']
assert scripts, "missing candidate Python source"
failures = []
for script in scripts:
(workspace / "transformed_image.png").unlink(missing_ok=True)
(workspace / "transform_report.txt").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 / "transformed_image.png").is_file():
return
failures.append(f"{script.name}: rc={proc.returncode} stderr={proc.stderr[-500:]}")
raise AssertionError("no candidate script produced transformed_image.png: " + " | ".join(failures))
# ENHANCED_CASE_1: CenterCrop(height=4, width=4) fixes the observable output size.
def case_1_center_crop_dimensions() -> None:
with Image.open(ROOT / "transformed_image.png") as image:
image.verify()
with Image.open(ROOT / "transformed_image.png") as image:
assert image.size == (4, 4), f"CenterCrop output must be 4x4, got {image.size}"
# ENHANCED_CASE_2: ToGray must make every RGB channel equal while preserving image data.
def case_2_grayscale_output() -> None:
with Image.open(ROOT / "transformed_image.png") as image:
pixels = np.array(image.convert("RGB"))
assert np.array_equal(pixels[:, :, 0], pixels[:, :, 1]), "red and green channels differ after grayscale"
assert np.array_equal(pixels[:, :, 1], pixels[:, :, 2]), "green and blue channels differ after grayscale"
assert np.unique(pixels[:, :, 0]).size > 1, "transformed output is a uniform placeholder"
# ENHANCED_CASE_3: an asymmetric legal input must be observably flipped without fixing blur internals.
def case_3_horizontal_flip_on_asymmetric_input() -> None:
with tempfile.TemporaryDirectory(prefix="task050-enhanced-") as tmp:
workspace = pathlib.Path(tmp)
_copy_candidate(workspace)
# The four center columns increase sharply left-to-right. Every normal
# 3x3 blur preserves that direction, so the required p=1 flip reverses
# it without tying the test to an OpenCV border mode or gray formula.
columns = np.array([250, 250, 20, 60, 120, 200, 0, 0], dtype=np.uint8)
source = np.repeat(columns[None, :, None], 8, axis=0)
source = np.repeat(source, 3, axis=2)
Image.fromarray(source, "RGB").save(workspace / "input.ppm")
_run_candidate(workspace)
with Image.open(workspace / "transformed_image.png") as image:
actual = np.array(image.convert("RGB"))
assert actual.shape == (4, 4, 3), f"variant output has wrong shape: {actual.shape}"
profile = actual[:, :, 0].astype(np.float64).mean(axis=0)
assert np.all(np.diff(profile) <= 0), f"output does not have the flipped right-to-left profile: {profile.tolist()}"
assert profile[0] - profile[-1] >= 40, f"flip signal was lost or output is a placeholder: {profile.tolist()}"
def case_4_changed_geometry_and_color():
with tempfile.TemporaryDirectory(prefix='task050-geometry-') as directory:
workspace = pathlib.Path(directory)
_copy_candidate(workspace)
source = np.fromfunction(lambda y, x, c: (37*y + 53*x + 79*c + 11*x*y) % 256, (9, 11, 3), dtype=int).astype(np.uint8)
Image.fromarray(source, 'RGB').save(workspace / 'input.ppm')
_run_candidate(workspace)
top, left = (source.shape[0] - 4) // 2, (source.shape[1] - 4) // 2
crop = source[top:top+4, left:left+4][:, ::-1].astype(float)
expected = np.zeros((4, 4))
for y in range(4):
for x in range(4):
samples = [crop[min(3, max(0, y+dy)), min(3, max(0, x+dx))]
for dy in (-1, 0, 1) for dx in (-1, 0, 1)]
rgb = np.rint(np.mean(samples, axis=0))
expected[y, x] = np.rint(np.dot(rgb, [0.299, 0.587, 0.114]))
with Image.open(workspace / 'transformed_image.png') as image:
actual = np.array(image.convert('RGB')).astype(float)
assert actual.shape == (4, 4, 3)
assert np.max(np.abs(actual - expected[:, :, None])) <= 3, 'changed-size/color input must follow the full crop, flip, blur and grayscale pipeline'
failures = []
for case in (case_1_center_crop_dimensions, case_2_grayscale_output, case_3_horizontal_flip_on_asymmetric_input, case_4_changed_geometry_and_color):
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))
visual = pathlib.Path('/logs/verifier/visual-audit')
visual.mkdir(parents=True, exist_ok=True)
shutil.copyfile(ROOT / 'transformed_image.png', visual / 'transformed-image.png')