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"""
|
| 3 |
+
submission_checker for compression challenge.
|
| 4 |
+
|
| 5 |
+
Usage:
|
| 6 |
+
python validate_submission.py submission.zip
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
import json
|
| 11 |
+
import os
|
| 12 |
+
import re
|
| 13 |
+
import sys
|
| 14 |
+
import tempfile
|
| 15 |
+
import zipfile
|
| 16 |
+
from typing import List, Tuple
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
EXPECTED_SHAPE = (3, 32, 32, 500)
|
| 22 |
+
CODEBOOK_SIZE = 64_000
|
| 23 |
+
EXPECTED_DTYPES = {"indices": np.int32, "values": np.float32}
|
| 24 |
+
DEFAULT_NUM_SAMPLES = 450 # .npz files expected
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class ValidationError(Exception):
|
| 28 |
+
"""Raised when one or more hard errors are detected."""
|
| 29 |
+
|
| 30 |
+
def _fail(msg: str, problems: List[str]):
|
| 31 |
+
problems.append(msg)
|
| 32 |
+
print(f"[ERROR] {msg}")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _check_readme(readme_path: str, problems: List[str]):
|
| 36 |
+
"""Parse and sanity‑check README.txt.
|
| 37 |
+
|
| 38 |
+
* Must exist.
|
| 39 |
+
* Must be JSON (we allow single quotes + trailing commas, which we normalise).
|
| 40 |
+
* Must contain the six required keys.
|
| 41 |
+
"""
|
| 42 |
+
if not os.path.isfile(readme_path):
|
| 43 |
+
_fail("README.txt missing", problems)
|
| 44 |
+
return None
|
| 45 |
+
|
| 46 |
+
with open(readme_path, "r", encoding="utf‑8") as f:
|
| 47 |
+
txt = f.read().strip()
|
| 48 |
+
|
| 49 |
+
# Make a permissive JSON pass: swap single -> double quotes and drop any trailing
|
| 50 |
+
# comma before the closing brace. **DO NOT** apply a regex that matches the empty
|
| 51 |
+
# string, or the text becomes garbage. (We had a bug here earlier.)
|
| 52 |
+
relaxed = re.sub(r"'", '"', txt)
|
| 53 |
+
relaxed = re.sub(r",\s*}" , "}", relaxed) # trailing comma
|
| 54 |
+
|
| 55 |
+
try:
|
| 56 |
+
meta = json.loads(relaxed)
|
| 57 |
+
except json.JSONDecodeError as e:
|
| 58 |
+
_fail(f"README.txt is not valid JSON‑like: {e}", problems)
|
| 59 |
+
meta = None
|
| 60 |
+
|
| 61 |
+
required = ["method", "team", "authors", "e-mail", "institution", "country"]
|
| 62 |
+
for field in required:
|
| 63 |
+
if meta is None or field not in meta:
|
| 64 |
+
_fail(f"README.txt missing field: {field}", problems)
|
| 65 |
+
|
| 66 |
+
return meta
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _check_npz_file(path: str, problems: List[str]):
|
| 70 |
+
"""Verify one <ID>.npz obeys all rules."""
|
| 71 |
+
try:
|
| 72 |
+
data = np.load(path)
|
| 73 |
+
except Exception as e:
|
| 74 |
+
_fail(f"Could not read {os.path.basename(path)}: {e}", problems)
|
| 75 |
+
return
|
| 76 |
+
|
| 77 |
+
# required arrays
|
| 78 |
+
for key in ("indices", "values"):
|
| 79 |
+
if key not in data:
|
| 80 |
+
_fail(f"{os.path.basename(path)} missing array '{key}'", problems)
|
| 81 |
+
return
|
| 82 |
+
|
| 83 |
+
idx, val = data["indices"], data["values"]
|
| 84 |
+
|
| 85 |
+
if idx.shape != EXPECTED_SHAPE:
|
| 86 |
+
_fail(f"{os.path.basename(path)}: indices shape {idx.shape} != {EXPECTED_SHAPE}", problems)
|
| 87 |
+
if val.shape != EXPECTED_SHAPE:
|
| 88 |
+
_fail(f"{os.path.basename(path)}: values shape {val.shape} != {EXPECTED_SHAPE}", problems)
|
| 89 |
+
|
| 90 |
+
if idx.dtype != EXPECTED_DTYPES["indices"]:
|
| 91 |
+
_fail(f"{os.path.basename(path)}: indices dtype {idx.dtype}, expected {EXPECTED_DTYPES['indices']}", problems)
|
| 92 |
+
if val.dtype != EXPECTED_DTYPES["values"]:
|
| 93 |
+
_fail(f"{os.path.basename(path)}: values dtype {val.dtype}, expected {EXPECTED_DTYPES['values']}", problems)
|
| 94 |
+
|
| 95 |
+
if idx.min() < 0 or idx.max() >= CODEBOOK_SIZE:
|
| 96 |
+
_fail(
|
| 97 |
+
f"{os.path.basename(path)}: indices out of range [0, {CODEBOOK_SIZE‑1}] (min={idx.min()}, max={idx.max()})",
|
| 98 |
+
problems,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def validate(zip_path: str, expected_samples: int = DEFAULT_NUM_SAMPLES) -> Tuple[bool, List[str]]:
|
| 104 |
+
problems: List[str] = []
|
| 105 |
+
|
| 106 |
+
if not os.path.isfile(zip_path):
|
| 107 |
+
raise FileNotFoundError(zip_path)
|
| 108 |
+
|
| 109 |
+
if os.path.basename(zip_path) != "submission.zip":
|
| 110 |
+
print("[WARN] Zip should be named 'submission.zip' — continuing anyway.")
|
| 111 |
+
|
| 112 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 113 |
+
with zipfile.ZipFile(zip_path) as zf:
|
| 114 |
+
zf.extractall(tmp)
|
| 115 |
+
|
| 116 |
+
# Warn about nested dirs, but keep going.
|
| 117 |
+
if any(os.path.isdir(os.path.join(tmp, x)) for x in os.listdir(tmp)):
|
| 118 |
+
print("[WARN] Detected sub‑directories; the evaluator expects a flat layout.")
|
| 119 |
+
|
| 120 |
+
_check_readme(os.path.join(tmp, "README.txt"), problems)
|
| 121 |
+
|
| 122 |
+
npz_files = [f for f in os.listdir(tmp) if f.endswith(".npz")]
|
| 123 |
+
if len(npz_files) != expected_samples:
|
| 124 |
+
_fail(f"Expected {expected_samples} .npz files, found {len(npz_files)}.", problems)
|
| 125 |
+
|
| 126 |
+
for fname in sorted(npz_files):
|
| 127 |
+
_check_npz_file(os.path.join(tmp, fname), problems)
|
| 128 |
+
|
| 129 |
+
return len(problems) == 0, problems
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def main():
|
| 134 |
+
ap = argparse.ArgumentParser(description="Validate competition submission zip file.")
|
| 135 |
+
ap.add_argument("zip", help="Path to submission.zip")
|
| 136 |
+
ap.add_argument("--num-samples", type=int, default=DEFAULT_NUM_SAMPLES,
|
| 137 |
+
help=f"Number of test samples (default {DEFAULT_NUM_SAMPLES})")
|
| 138 |
+
args = ap.parse_args()
|
| 139 |
+
|
| 140 |
+
ok, probs = validate(args.zip, args.num_samples)
|
| 141 |
+
if ok:
|
| 142 |
+
print("\nAll checks passed. Good luck in the leaderboard!")
|
| 143 |
+
sys.exit(0)
|
| 144 |
+
|
| 145 |
+
print("\nFound problems:")
|
| 146 |
+
for p in probs:
|
| 147 |
+
print(" •", p)
|
| 148 |
+
sys.exit(1)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
if __name__ == "__main__":
|
| 152 |
+
main()
|