#!/usr/bin/env python3 """Checks that the candidates in a folder follow the submission format in README.md: JSON shape, container, n, the coordinates' form, and that every point lies in its container (exactly). It computes no areas. usage: python3 tools/check_format.py routes/ (or one .json file) """ import json import pathlib import re import sys from fractions import Fraction SIZES = range(20, 37) DECIMAL = re.compile(r"-?\d{1,6}(\.\d{1,200})?") def errors(candidate): container, n = candidate.get("container"), candidate.get("n") if container not in ("square", "triangle"): return ['"container" must be "square" or "triangle"'] if type(n) is not int or n not in SIZES: return ['"n" must be one of the integers 20 to 36'] pts = candidate.get("points") if not isinstance(pts, list) or len(pts) != n: return [f'"points" must be a list of {n} points'] out = [] for i, p in enumerate(pts): if not isinstance(p, list) or len(p) != 2: out.append(f"point {i} is not a list [x, y]") continue if not all(isinstance(c, str) and DECIMAL.fullmatch(c) for c in p): out.append(f"point {i}: coordinates must be strings holding plain decimals, such as \"0.125\"") continue x, y = map(Fraction, p) if not (0 <= x <= 1 and 0 <= y <= 1 if container == "square" else x >= 0 and y >= 0 and x + y <= 1): out.append(f"point {i} ({p[0]}, {p[1]}) is outside the {container}") return out if len(sys.argv) != 2: sys.exit(__doc__) target = pathlib.Path(sys.argv[1]) if target.is_file() and target.suffix != ".json": sys.exit(f"{target}: candidates are .json files") files = [target] if target.is_file() else sorted(target.rglob("*.json")) found = bad = 0 for path in files: if path.stat().st_size > 1_000_000: print(f"{path}: over 1 MB") bad += 1 continue try: candidate = json.loads(path.read_text()) except Exception as exc: print(f"{path}: not valid JSON ({exc})") bad += 1 continue if not isinstance(candidate, dict) or "points" not in candidate: print(f'{path}: not a candidate (no "points" key); ignored') continue found += 1 problems = errors(candidate) print(f"{path}: {'; '.join(problems[:5])}" if problems else f"{path}: ok ({candidate['container']}-n{candidate['n']})") bad += bool(problems) print(f"{found} candidates, {bad} files with format errors") sys.exit(1 if bad else 0)