Add CTU catalogue parser and research contract
parse_catalog.py turns a saved copy of the CTU Mobility catalogue (FEL, Master, 2027/28) into data/catalog.json: 186 agreements merged into 170 schools. research/BRIEF.md is the contract for per-school research (JSON shape, scoring anchors, source rules); validate_research.py enforces its structure. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HA82gXkMmmRRKLSnY6vQN3
This commit is contained in:
parent
fcfb2bcd87
commit
3980fbd62b
16 changed files with 16805 additions and 0 deletions
305
scripts/validate_research.py
Normal file
305
scripts/validate_research.py
Normal file
|
|
@ -0,0 +1,305 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Validate research files against the contract in research/BRIEF.md.
|
||||
|
||||
Usage:
|
||||
python3 -I scripts/validate_research.py # everything in research/raw/
|
||||
python3 -I scripts/validate_research.py research/raw/schools/A_GRAZ02.json [...]
|
||||
|
||||
Exit code 0 = all valid. Errors are printed as "<file>: <path>: <problem>".
|
||||
The checks are structural (types, ranges, enums, lengths), not factual.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
CATALOG = json.load(open(os.path.join(ROOT, "data", "catalog.json"), encoding="utf-8"))
|
||||
CODES_BY_SLUG = {s["slug"]: s["code"] for s in CATALOG["schools"]}
|
||||
COUNTRIES = sorted({s["country"] for s in CATALOG["schools"]})
|
||||
|
||||
CONF = {"high", "medium", "low"}
|
||||
SHORT, TEXT, LONG = 160, 900, 1400 # max characters per kind of string
|
||||
|
||||
|
||||
class Checker:
|
||||
def __init__(self, name):
|
||||
self.name, self.errors = name, []
|
||||
|
||||
def err(self, path, msg):
|
||||
self.errors.append(f"{self.name}: {path}: {msg}")
|
||||
|
||||
def obj(self, v, path, keys):
|
||||
if not isinstance(v, dict):
|
||||
self.err(path, "must be an object")
|
||||
return False
|
||||
for k in keys:
|
||||
if k not in v:
|
||||
self.err(path, f"missing key '{k}'")
|
||||
return True
|
||||
|
||||
def string(self, v, path, maxlen=TEXT, allow_empty=False, nullable=False):
|
||||
if v is None and nullable:
|
||||
return
|
||||
if not isinstance(v, str):
|
||||
self.err(path, "must be a string" + (" or null" if nullable else ""))
|
||||
elif not allow_empty and not v.strip():
|
||||
self.err(path, "must not be empty")
|
||||
elif len(v) > maxlen:
|
||||
self.err(path, f"too long ({len(v)} > {maxlen} chars)")
|
||||
|
||||
def score(self, v, path):
|
||||
if not isinstance(v, (int, float)) or isinstance(v, bool) or not 0 <= v <= 10:
|
||||
self.err(path, "score must be a number 0-10")
|
||||
|
||||
def number(self, v, path, nullable=True, lo=0, hi=1e7):
|
||||
if v is None and nullable:
|
||||
return
|
||||
if not isinstance(v, (int, float)) or isinstance(v, bool) or not lo <= v <= hi:
|
||||
self.err(path, f"must be a number {lo}..{hi}" + (" or null" if nullable else ""))
|
||||
|
||||
def range_(self, v, path, hi=1e6):
|
||||
if v is None:
|
||||
return
|
||||
if (not isinstance(v, list) or len(v) != 2
|
||||
or not all(isinstance(x, (int, float)) and not isinstance(x, bool) for x in v)):
|
||||
self.err(path, "must be [low, high] numbers or null")
|
||||
elif not 0 <= v[0] <= v[1] <= hi:
|
||||
self.err(path, f"need 0 <= low <= high <= {hi}")
|
||||
|
||||
def enum(self, v, path, allowed):
|
||||
if v not in allowed:
|
||||
self.err(path, f"must be one of {sorted(allowed)}")
|
||||
|
||||
def str_list(self, v, path, max_items=12):
|
||||
if not isinstance(v, list):
|
||||
self.err(path, "must be a list of strings")
|
||||
return
|
||||
if len(v) > max_items:
|
||||
self.err(path, f"at most {max_items} items")
|
||||
for i, x in enumerate(v):
|
||||
self.string(x, f"{path}[{i}]", SHORT)
|
||||
|
||||
def sources(self, v, path, minimum):
|
||||
if not isinstance(v, list) or len(v) < minimum:
|
||||
self.err(path, f"need a list of at least {minimum} sources")
|
||||
return
|
||||
for i, s in enumerate(v):
|
||||
if self.obj(s, f"{path}[{i}]", ["label", "url"]):
|
||||
self.string(s.get("label"), f"{path}[{i}].label", SHORT)
|
||||
if not isinstance(s.get("url"), str) or not re.match(r"^https?://[^\s]+$", s["url"]):
|
||||
self.err(f"{path}[{i}].url", "must be an http(s) URL")
|
||||
|
||||
|
||||
def scored(c, v, path):
|
||||
if c.obj(v, path, ["score", "text"]):
|
||||
c.score(v.get("score"), path + ".score")
|
||||
c.string(v.get("text"), path + ".text")
|
||||
|
||||
|
||||
def check_school(c, d, slug):
|
||||
top = ["code", "name", "shortName", "city", "country", "summary", "highlights", "watchouts",
|
||||
"aiRobotics", "language", "living", "fees", "travel", "social", "solitude", "nature",
|
||||
"safety", "calendar", "application", "sources", "confidence", "researchedAt"]
|
||||
if not c.obj(d, "$", top):
|
||||
return
|
||||
expected = CODES_BY_SLUG.get(slug)
|
||||
if expected is None:
|
||||
c.err("$", f"file name slug '{slug}' is not a school in data/catalog.json")
|
||||
elif d.get("code") != expected:
|
||||
c.err("$.code", f"must be exactly '{expected}'")
|
||||
for k in ("name", "shortName", "city", "country"):
|
||||
c.string(d.get(k), f"$.{k}", SHORT)
|
||||
c.string(d.get("summary"), "$.summary", 700)
|
||||
c.str_list(d.get("highlights"), "$.highlights", 6)
|
||||
c.str_list(d.get("watchouts"), "$.watchouts", 6)
|
||||
|
||||
ai = d.get("aiRobotics")
|
||||
if c.obj(ai, "$.aiRobotics", ["academic", "practical", "access", "rankings", "labs", "courses", "teams"]):
|
||||
for k in ("academic", "practical", "access"):
|
||||
scored(c, ai.get(k), f"$.aiRobotics.{k}")
|
||||
r = ai.get("rankings")
|
||||
if c.obj(r, "$.aiRobotics.rankings", ["qsWorld", "qsCS", "csrankings", "other"]):
|
||||
for k in ("qsWorld", "qsCS", "csrankings", "other"):
|
||||
c.string(r.get(k), f"$.aiRobotics.rankings.{k}", 300, nullable=True)
|
||||
c.str_list(ai.get("labs"), "$.aiRobotics.labs", 8)
|
||||
c.str_list(ai.get("courses"), "$.aiRobotics.courses", 12)
|
||||
c.str_list(ai.get("teams"), "$.aiRobotics.teams", 8)
|
||||
|
||||
lang = d.get("language")
|
||||
if c.obj(lang, "$.language", ["teaching", "proof", "localNeed", "text"]):
|
||||
c.string(lang.get("teaching"), "$.language.teaching")
|
||||
c.string(lang.get("proof"), "$.language.proof")
|
||||
c.score(lang.get("localNeed"), "$.language.localNeed")
|
||||
c.string(lang.get("text"), "$.language.text")
|
||||
|
||||
liv = d.get("living")
|
||||
if c.obj(liv, "$.living", ["rentEUR", "foodEUR", "transportEUR", "otherEUR", "totalEUR", "housing", "text"]):
|
||||
for k in ("rentEUR", "foodEUR", "transportEUR", "otherEUR"):
|
||||
c.range_(liv.get(k), f"$.living.{k}", 5000)
|
||||
if liv.get("totalEUR") is None:
|
||||
c.err("$.living.totalEUR", "required: best estimate [low, high] EUR per month")
|
||||
c.range_(liv.get("totalEUR"), "$.living.totalEUR", 8000)
|
||||
c.string(liv.get("housing"), "$.living.housing")
|
||||
c.string(liv.get("text"), "$.living.text")
|
||||
|
||||
fees = d.get("fees")
|
||||
if c.obj(fees, "$.fees", ["mandatoryEUR", "text", "hostFunding"]):
|
||||
c.number(fees.get("mandatoryEUR"), "$.fees.mandatoryEUR", hi=20000)
|
||||
c.string(fees.get("text"), "$.fees.text")
|
||||
hf = fees.get("hostFunding")
|
||||
if c.obj(hf, "$.fees.hostFunding", ["monthlyEUR", "text"]):
|
||||
c.number(hf.get("monthlyEUR"), "$.fees.hostFunding.monthlyEUR", hi=5000)
|
||||
c.string(hf.get("text"), "$.fees.hostFunding.text")
|
||||
|
||||
tr = d.get("travel")
|
||||
if c.obj(tr, "$.travel", ["mode", "duration", "roundTripEUR", "text"]):
|
||||
c.enum(tr.get("mode"), "$.travel.mode", {"train", "bus", "flight", "car"})
|
||||
c.string(tr.get("duration"), "$.travel.duration", SHORT)
|
||||
if tr.get("roundTripEUR") is None:
|
||||
c.err("$.travel.roundTripEUR", "required: best estimate [low, high] EUR")
|
||||
c.range_(tr.get("roundTripEUR"), "$.travel.roundTripEUR", 10000)
|
||||
c.string(tr.get("text"), "$.travel.text")
|
||||
|
||||
soc = d.get("social")
|
||||
if c.obj(soc, "$.social", ["score", "esn", "internationals", "text"]):
|
||||
c.score(soc.get("score"), "$.social.score")
|
||||
c.string(soc.get("esn"), "$.social.esn", SHORT, nullable=True)
|
||||
c.string(soc.get("internationals"), "$.social.internationals", 300, nullable=True)
|
||||
c.string(soc.get("text"), "$.social.text")
|
||||
scored(c, d.get("solitude"), "$.solitude")
|
||||
|
||||
nat = d.get("nature")
|
||||
if c.obj(nat, "$.nature", ["climbing", "hiking", "ocean", "skiing", "climate"]):
|
||||
for k in ("climbing", "hiking", "ocean", "skiing"):
|
||||
scored(c, nat.get(k), f"$.nature.{k}")
|
||||
c.string(nat.get("climate"), "$.nature.climate")
|
||||
|
||||
saf = d.get("safety")
|
||||
if c.obj(saf, "$.safety", ["score", "hazards", "text"]):
|
||||
c.score(saf.get("score"), "$.safety.score")
|
||||
c.string(saf.get("hazards"), "$.safety.hazards", 400)
|
||||
c.string(saf.get("text"), "$.safety.text")
|
||||
|
||||
cal = d.get("calendar")
|
||||
if c.obj(cal, "$.calendar", ["term", "fit", "fullYear", "text"]):
|
||||
c.string(cal.get("term"), "$.calendar.term", 300)
|
||||
c.enum(cal.get("fit"), "$.calendar.fit", {"good", "ok", "poor"})
|
||||
c.enum(cal.get("fullYear"), "$.calendar.fullYear", {"possible", "unclear", "no"})
|
||||
c.string(cal.get("text"), "$.calendar.text")
|
||||
|
||||
app = d.get("application")
|
||||
if c.obj(app, "$.application", ["nominationDeadline", "text"]):
|
||||
c.string(app.get("nominationDeadline"), "$.application.nominationDeadline", 300, nullable=True)
|
||||
c.string(app.get("text"), "$.application.text")
|
||||
|
||||
c.sources(d.get("sources"), "$.sources", 4)
|
||||
conf = d.get("confidence")
|
||||
keys = ["aiRobotics", "language", "living", "travel", "social", "nature", "safety", "calendar", "overall"]
|
||||
if c.obj(conf, "$.confidence", keys):
|
||||
for k in keys:
|
||||
c.enum(conf.get(k), f"$.confidence.{k}", CONF)
|
||||
if not isinstance(d.get("researchedAt"), str) or not re.match(r"^\d{4}-\d{2}-\d{2}$", d["researchedAt"]):
|
||||
c.err("$.researchedAt", "must be YYYY-MM-DD")
|
||||
|
||||
|
||||
def check_countries(c, d):
|
||||
if not isinstance(d, dict):
|
||||
return c.err("$", "must be an object keyed by country name")
|
||||
for name in COUNTRIES:
|
||||
if name not in d:
|
||||
c.err("$", f"missing country '{name}' (use the catalog spelling)")
|
||||
for name, v in d.items():
|
||||
p = f"$['{name}']"
|
||||
keys = ["erasmusProgramme", "erasmusGroup", "wgiPoliticalStability", "gpi", "mfaAdvisory",
|
||||
"visa", "health", "currency", "stabilityScore", "text", "sources"]
|
||||
if not c.obj(v, p, keys):
|
||||
continue
|
||||
if not isinstance(v.get("erasmusProgramme"), bool):
|
||||
c.err(p + ".erasmusProgramme", "must be true/false")
|
||||
if v.get("erasmusGroup") not in (1, 2, 3, None):
|
||||
c.err(p + ".erasmusGroup", "must be 1, 2, 3 or null")
|
||||
w = v.get("wgiPoliticalStability")
|
||||
if c.obj(w, p + ".wgiPoliticalStability", ["percentile", "year"]):
|
||||
c.number(w.get("percentile"), p + ".wgiPoliticalStability.percentile", hi=100)
|
||||
g = v.get("gpi")
|
||||
if c.obj(g, p + ".gpi", ["rank", "year"]):
|
||||
c.number(g.get("rank"), p + ".gpi.rank", hi=200)
|
||||
m = v.get("mfaAdvisory")
|
||||
if c.obj(m, p + ".mfaAdvisory", ["level", "text"]):
|
||||
c.enum(m.get("level"), p + ".mfaAdvisory.level", {"none", "caution", "partial-avoid", "avoid"})
|
||||
c.string(m.get("text"), p + ".mfaAdvisory.text")
|
||||
vi = v.get("visa")
|
||||
if c.obj(vi, p + ".visa", ["required", "type", "costEUR", "text"]):
|
||||
if not isinstance(vi.get("required"), bool):
|
||||
c.err(p + ".visa.required", "must be true/false")
|
||||
c.string(vi.get("type"), p + ".visa.type", SHORT, allow_empty=True)
|
||||
c.number(vi.get("costEUR"), p + ".visa.costEUR", hi=5000)
|
||||
c.string(vi.get("text"), p + ".visa.text")
|
||||
h = v.get("health")
|
||||
if c.obj(h, p + ".health", ["ehic", "text"]):
|
||||
if not isinstance(h.get("ehic"), bool):
|
||||
c.err(p + ".health.ehic", "must be true/false")
|
||||
c.string(h.get("text"), p + ".health.text")
|
||||
cur = v.get("currency")
|
||||
if c.obj(cur, p + ".currency", ["code", "perEUR"]):
|
||||
c.string(cur.get("code"), p + ".currency.code", 3)
|
||||
c.number(cur.get("perEUR"), p + ".currency.perEUR", nullable=False, hi=1e6)
|
||||
c.score(v.get("stabilityScore"), p + ".stabilityScore")
|
||||
c.string(v.get("text"), p + ".text", LONG)
|
||||
c.sources(v.get("sources"), p + ".sources", 2)
|
||||
|
||||
|
||||
def check_funding(c, d):
|
||||
if not c.obj(d, "$", ["fx", "erasmus", "switzerland", "ctuWide", "ka171", "selection", "sources"]):
|
||||
return
|
||||
fx = d.get("fx")
|
||||
if c.obj(fx, "$.fx", ["EURCZK", "date", "source"]):
|
||||
c.number(fx.get("EURCZK"), "$.fx.EURCZK", nullable=False, lo=10, hi=50)
|
||||
e = d.get("erasmus")
|
||||
if c.obj(e, "$.erasmus", ["status", "monthlyEUR", "groups", "greenTravel", "fewerOpportunitiesTopUpEUR",
|
||||
"ctuOrFelTopUp", "text", "sources"]):
|
||||
mo = e.get("monthlyEUR")
|
||||
if c.obj(mo, "$.erasmus.monthlyEUR", ["1", "2", "3"]):
|
||||
for k in ("1", "2", "3"):
|
||||
c.number(mo.get(k), f"$.erasmus.monthlyEUR.{k}", nullable=False, hi=3000)
|
||||
c.sources(e.get("sources"), "$.erasmus.sources", 2)
|
||||
for k in ("switzerland", "ctuWide", "ka171", "selection"):
|
||||
v = d.get(k)
|
||||
if c.obj(v, f"$.{k}", ["text", "sources"]):
|
||||
c.string(v.get("text"), f"$.{k}.text", 2500)
|
||||
c.sources(v.get("sources"), f"$.{k}.sources", 1)
|
||||
|
||||
|
||||
def validate(path):
|
||||
c = Checker(os.path.relpath(path, ROOT))
|
||||
try:
|
||||
d = json.load(open(path, encoding="utf-8"))
|
||||
except (OSError, ValueError) as e:
|
||||
c.err("$", f"not readable JSON: {e}")
|
||||
return c.errors
|
||||
base = os.path.basename(path)
|
||||
if base == "countries.json":
|
||||
check_countries(c, d)
|
||||
elif base == "funding.json":
|
||||
check_funding(c, d)
|
||||
else:
|
||||
check_school(c, d, base[:-5] if base.endswith(".json") else base)
|
||||
return c.errors
|
||||
|
||||
|
||||
def main(paths):
|
||||
if not paths:
|
||||
raw = os.path.join(ROOT, "research", "raw")
|
||||
paths = [os.path.join(raw, f) for f in ("funding.json", "countries.json") if os.path.exists(os.path.join(raw, f))]
|
||||
sd = os.path.join(raw, "schools")
|
||||
paths += sorted(os.path.join(sd, f) for f in os.listdir(sd) if f.endswith(".json"))
|
||||
errors = [e for p in paths for e in validate(p)]
|
||||
for e in errors:
|
||||
print(e)
|
||||
print(f"{len(paths)} file(s) checked, {len(errors)} error(s)")
|
||||
return 1 if errors else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
Loading…
Add table
Add a link
Reference in a new issue