#!/usr/bin/env python3 """Checks that the candidates in a folder follow the submission format in README.md: file names, JSON shape, types, lengths and ranges, and the size limit. It computes no ratio. usage: python3 tools/check_format.py routes/ (or one .json file) """ import json import math import pathlib import sys from fractions import Fraction MAX_STEPS = 131072 MAX_BITS = 1 << 24 def errors(candidate): values = candidate.get("heights") if not isinstance(values, list) or not 1 <= len(values) <= MAX_STEPS: return [f'"heights" must be a list of 1 to {MAX_STEPS} heights'] out, hs = [], [] for i, v in enumerate(values): if isinstance(v, bool) or not isinstance(v, (int, float, str)) or (isinstance(v, float) and not math.isfinite(v)): out.append(f"height {i}: {v!r} is not a finite number or a string") continue try: x = Fraction(v) except (ValueError, ZeroDivisionError): out.append(f"height {i}: unreadable {v!r}") continue if x < 0: out.append(f"height {i}: {v} is negative") hs.append(x) if out: return out if not any(hs): return ["all heights are 0"] q = math.lcm(*(x.denominator for x in hs)) bits = max(x.numerator * (q // x.denominator) for x in hs).bit_length() if len(hs) * bits > MAX_BITS: return [f"too fine: {len(hs)} heights of {bits} bits over their common denominator; N times the bits may be at most {MAX_BITS}"] return [] 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 "heights" not in candidate: print(f'{path}: not a candidate (no "heights" key); ignored') continue found += 1 problems = errors(candidate) print(f"{path}: {'; '.join(problems[:5])}" if problems else f"{path}: ok ({len(candidate['heights'])} steps)") bad += bool(problems) print(f"{found} candidates, {bad} files with format errors") sys.exit(1 if bad else 0)