jmonas commited on
Commit
4c582d7
·
verified ·
1 Parent(s): 267ccec

Create validate_submission.py

Browse files
Files changed (1) hide show
  1. test_v2.0/validate_submission.py +171 -0
test_v2.0/validate_submission.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ submission_checker for sampling challenge.
4
+
5
+ Usage:
6
+ python validate_submission.py submission.zip
7
+
8
+ """
9
+
10
+ import argparse
11
+ import json
12
+ import os
13
+ import re
14
+ import sys
15
+ import tempfile
16
+ import zipfile
17
+ from pathlib import Path
18
+ from typing import List, Tuple
19
+
20
+ from PIL import Image
21
+
22
+ EXPECTED_NUM_IMAGES = 250
23
+ EXPECTED_SIZE = (512, 512) # width, height
24
+ REQUIRED_README_KEYS = [
25
+ "method",
26
+ "team",
27
+ "authors",
28
+ "e-mail",
29
+ "institution",
30
+ "country",
31
+ ]
32
+
33
+
34
+ class ValidationError(Exception):
35
+ """Raised when one or more hard errors are detected."""
36
+
37
+
38
+
39
+ def _fail(msg: str, problems: List[str]) -> None:
40
+ problems.append(msg)
41
+ print(f"[ERROR] {msg}")
42
+
43
+
44
+ def _warn(msg: str) -> None:
45
+ print(f"[WARN] {msg}")
46
+
47
+
48
+ def _check_readme(readme_path: Path, problems: List[str]) -> None:
49
+ """Verify README.txt format and fields."""
50
+ if not readme_path.is_file():
51
+ _fail("README.txt missing", problems)
52
+ return
53
+
54
+ txt = readme_path.read_text(encoding="utf-8").strip()
55
+
56
+ # Relaxed JSON: convert single quotes → double quotes, drop trailing commas before }
57
+ relaxed = re.sub(r"'", '"', txt)
58
+ relaxed = re.sub(r",\s*}", "}", relaxed)
59
+
60
+ try:
61
+ meta = json.loads(relaxed)
62
+ except json.JSONDecodeError as e:
63
+ _fail(f"README.txt is not valid JSON‑like: {e}", problems)
64
+ return
65
+
66
+ for key in REQUIRED_README_KEYS:
67
+ if key not in meta:
68
+ _fail(f"README.txt missing field: {key}", problems)
69
+
70
+
71
+ def _check_image(img_path: Path, problems: List[str]) -> None:
72
+ """Open PNG and verify dimensions & mode."""
73
+ if img_path.stat().st_size == 0:
74
+ _fail(f"{img_path.name} is empty (0 bytes)", problems)
75
+ return
76
+
77
+ try:
78
+ with Image.open(img_path) as im:
79
+ im.verify() # basic integrity check
80
+ except Exception as e:
81
+ _fail(f"{img_path.name} is not a valid PNG: {e}", problems)
82
+ return
83
+
84
+ with Image.open(img_path) as im:
85
+ if im.format != "PNG":
86
+ _fail(f"{img_path.name}: not a PNG file", problems)
87
+ if im.mode != "RGB":
88
+ _fail(f"{img_path.name}: mode {im.mode}, expected RGB", problems)
89
+ if im.size != EXPECTED_SIZE:
90
+ _fail(
91
+ f"{img_path.name}: size {im.size}, expected {EXPECTED_SIZE}",
92
+ problems,
93
+ )
94
+
95
+
96
+ def validate(zip_path: str) -> Tuple[bool, List[str]]:
97
+ problems: List[str] = []
98
+
99
+ if not Path(zip_path).is_file():
100
+ raise FileNotFoundError(zip_path)
101
+
102
+ if Path(zip_path).name != "submission.zip":
103
+ _warn("Zip should be named 'submission.zip' — continuing anyway.")
104
+
105
+ with tempfile.TemporaryDirectory() as tmpdir:
106
+ tmpdir = Path(tmpdir)
107
+ with zipfile.ZipFile(zip_path) as zf:
108
+ zf.extractall(tmpdir)
109
+
110
+ # Warn about nested directories
111
+ if any(p.is_dir() for p in tmpdir.iterdir()):
112
+ _warn("Detected sub‑directories; the evaluator expects a flat layout.")
113
+
114
+ # File listing
115
+ files = [p for p in tmpdir.iterdir() if p.is_file()]
116
+ png_files = [p for p in files if p.suffix.lower() == ".png"]
117
+ readme_path = tmpdir / "README.txt"
118
+
119
+ # Check README
120
+ _check_readme(readme_path, problems)
121
+
122
+ # Check image count
123
+ if len(png_files) != EXPECTED_NUM_IMAGES:
124
+ _fail(
125
+ f"Expected {EXPECTED_NUM_IMAGES} PNGs, found {len(png_files)}",
126
+ problems,
127
+ )
128
+
129
+ # Expected names: 0.png … 249.png
130
+ expected_names = {f"{i}.png" for i in range(EXPECTED_NUM_IMAGES)}
131
+ actual_names = {p.name for p in png_files}
132
+ missing = expected_names - actual_names
133
+ extra = actual_names - expected_names
134
+ if missing:
135
+ _fail(f"Missing PNG files: {', '.join(sorted(missing))}", problems)
136
+ if extra:
137
+ _fail(f"Unexpected files present: {', '.join(sorted(extra))}", problems)
138
+
139
+ # Image‑level checks
140
+ for img_path in sorted(png_files, key=lambda p: int(p.stem) if p.stem.isdigit() else p.stem):
141
+ _check_image(img_path, problems)
142
+
143
+ # Warn about stray non‑PNG files
144
+ stray = [p for p in files if p.suffix.lower() != ".png" and p.name != "README.txt"]
145
+ if stray:
146
+ _warn(
147
+ f"Found non‑PNG files that will be ignored by the evaluator: "
148
+ + ", ".join(p.name for p in stray)
149
+ )
150
+
151
+ return len(problems) == 0, problems
152
+
153
+
154
+ def main() -> None:
155
+ parser = argparse.ArgumentParser(description="Validate competition submission zip file.")
156
+ parser.add_argument("zip", help="Path to submission.zip")
157
+ args = parser.parse_args()
158
+
159
+ ok, probs = validate(args.zip)
160
+ if ok:
161
+ print("\nAll checks passed. Good luck on the leaderboard!")
162
+ sys.exit(0)
163
+
164
+ print("\nFound problems:")
165
+ for p in probs:
166
+ print(" •", p)
167
+ sys.exit(1)
168
+
169
+
170
+ if __name__ == "__main__":
171
+ main()