#!/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. It computes no inner products. usage: python3 tools/check_format.py routes/ (or one .json file) """ import json import pathlib import sys from fractions import Fraction DIMS = (5, 7, 9, 10) MAX_VECTORS = 1000 def errors(candidate): d = candidate.get("d") if type(d) is not int or d not in DIMS: return [f'"d" must be {" or ".join(map(str, DIMS))}'] vs = candidate.get("vectors") if not isinstance(vs, list) or not 1 <= len(vs) <= MAX_VECTORS: return [f'"vectors" must be a list of 1 to {MAX_VECTORS} vectors'] out = [] for i, v in enumerate(vs): if not isinstance(v, list) or len(v) != d: out.append(f"vector {i} is not a list of {d} entries") continue for e in v: if isinstance(e, bool) or not isinstance(e, (int, str)): out.append(f"vector {i}: entry {e!r} is not an integer or a string") continue try: Fraction(e) except (ValueError, ZeroDivisionError): out.append(f"vector {i}: unreadable entry {e!r}") 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 "vectors" not in candidate: print(f'{path}: not a candidate (no "vectors" key); ignored') continue found += 1 problems = errors(candidate) print(f"{path}: {'; '.join(problems[:5])}" if problems else f"{path}: ok (d={candidate['d']}, {len(candidate['vectors'])} vectors)") bad += bool(problems) print(f"{found} candidates, {bad} files with format errors") sys.exit(1 if bad else 0)