File size: 4,857 Bytes
4c582d7 |
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 |
#!/usr/bin/env python3
"""
submission_checker for sampling challenge.
Usage:
python validate_submission.py submission.zip
"""
import argparse
import json
import os
import re
import sys
import tempfile
import zipfile
from pathlib import Path
from typing import List, Tuple
from PIL import Image
EXPECTED_NUM_IMAGES = 250
EXPECTED_SIZE = (512, 512) # width, height
REQUIRED_README_KEYS = [
"method",
"team",
"authors",
"e-mail",
"institution",
"country",
]
class ValidationError(Exception):
"""Raised when one or more hard errors are detected."""
def _fail(msg: str, problems: List[str]) -> None:
problems.append(msg)
print(f"[ERROR] {msg}")
def _warn(msg: str) -> None:
print(f"[WARN] {msg}")
def _check_readme(readme_path: Path, problems: List[str]) -> None:
"""Verify README.txt format and fields."""
if not readme_path.is_file():
_fail("README.txt missing", problems)
return
txt = readme_path.read_text(encoding="utf-8").strip()
relaxed = re.sub(r"'", '"', txt)
relaxed = re.sub(r",\s*}", "}", relaxed)
try:
meta = json.loads(relaxed)
except json.JSONDecodeError as e:
_fail(f"README.txt is not valid JSON‑like: {e}", problems)
return
for key in REQUIRED_README_KEYS:
if key not in meta:
_fail(f"README.txt missing field: {key}", problems)
def _check_image(img_path: Path, problems: List[str]) -> None:
"""Open PNG and verify dimensions & mode."""
if img_path.stat().st_size == 0:
_fail(f"{img_path.name} is empty (0 bytes)", problems)
return
try:
with Image.open(img_path) as im:
im.verify() # basic integrity check
except Exception as e:
_fail(f"{img_path.name} is not a valid PNG: {e}", problems)
return
with Image.open(img_path) as im:
if im.format != "PNG":
_fail(f"{img_path.name}: not a PNG file", problems)
if im.mode != "RGB":
_fail(f"{img_path.name}: mode {im.mode}, expected RGB", problems)
if im.size != EXPECTED_SIZE:
_fail(
f"{img_path.name}: size {im.size}, expected {EXPECTED_SIZE}",
problems,
)
def validate(zip_path: str) -> Tuple[bool, List[str]]:
problems: List[str] = []
if not Path(zip_path).is_file():
raise FileNotFoundError(zip_path)
if Path(zip_path).name != "submission.zip":
_warn("Zip should be named 'submission.zip' — continuing anyway.")
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir = Path(tmpdir)
with zipfile.ZipFile(zip_path) as zf:
zf.extractall(tmpdir)
# Warn about nested directories
if any(p.is_dir() for p in tmpdir.iterdir()):
_warn("Detected sub‑directories; the evaluator expects a flat layout.")
# File listing
files = [p for p in tmpdir.iterdir() if p.is_file()]
png_files = [p for p in files if p.suffix.lower() == ".png"]
readme_path = tmpdir / "README.txt"
# Check README
_check_readme(readme_path, problems)
# Check image count
if len(png_files) != EXPECTED_NUM_IMAGES:
_fail(
f"Expected {EXPECTED_NUM_IMAGES} PNGs, found {len(png_files)}",
problems,
)
# Expected names: 0.png … 249.png
expected_names = {f"{i}.png" for i in range(EXPECTED_NUM_IMAGES)}
actual_names = {p.name for p in png_files}
missing = expected_names - actual_names
extra = actual_names - expected_names
if missing:
_fail(f"Missing PNG files: {', '.join(sorted(missing))}", problems)
if extra:
_fail(f"Unexpected files present: {', '.join(sorted(extra))}", problems)
# Image‑level checks
for img_path in sorted(png_files, key=lambda p: int(p.stem) if p.stem.isdigit() else p.stem):
_check_image(img_path, problems)
# Warn about stray non‑PNG files
stray = [p for p in files if p.suffix.lower() != ".png" and p.name != "README.txt"]
if stray:
_warn(
f"Found non‑PNG files that will be ignored by the evaluator: "
+ ", ".join(p.name for p in stray)
)
return len(problems) == 0, problems
def main() -> None:
parser = argparse.ArgumentParser(description="Validate competition submission zip file.")
parser.add_argument("zip", help="Path to submission.zip")
args = parser.parse_args()
ok, probs = validate(args.zip)
if ok:
print("\nAll checks passed. Good luck on the leaderboard!")
sys.exit(0)
print("\nFound problems:")
for p in probs:
print(" •", p)
sys.exit(1)
if __name__ == "__main__":
main()
|