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:
agent 2026-11-12 20:55:35 +00:00
parent fcfb2bcd87
commit 3980fbd62b
16 changed files with 16805 additions and 0 deletions

View file

@ -0,0 +1,39 @@
#!/usr/bin/env python3
"""Split data/catalog.json into per-region research assignments.
Usage: python3 -I scripts/make_assignments.py
Writes research/assignments/<group>.json - one file per research agent.
Grouping by region lets one researcher reuse city/country context.
"""
import json
from collections import Counter
GROUPS = {
"germany": ["Germany"],
"alps-benelux": ["Austria", "Switzerland", "Belgium", "Netherlands"],
"france": ["France"],
"nordic-atlantic": ["Sweden", "Norway", "Denmark", "Finland", "Iceland", "Ireland"],
"central-east-europe": ["Croatia", "Slovenia", "Slovakia", "Hungary", "Poland", "Romania",
"Bulgaria", "Ukraine", "Estonia", "Lithuania"],
"south-europe": ["Spain", "Italy", "Portugal", "Greece", "Türkiye"],
"korea": ["Korea (the Republic of)"],
"taiwan-china": ["Taiwan", "China"],
"asia-other": ["Japan", "Singapore", "Thailand", "Viet Nam", "Indonesia", "India"],
"anglo-overseas": ["United States of America", "Canada", "Australia"],
"latin-america": ["Mexico", "Brazil", "Argentina", "Chile", "Colombia", "Costa Rica",
"Peru", "Uruguay", "Venezuela"],
}
catalog = json.load(open("data/catalog.json", encoding="utf-8"))
by_country = {c: g for g, cs in GROUPS.items() for c in cs}
missing = {s["country"] for s in catalog["schools"]} - set(by_country)
assert not missing, f"countries without a group: {missing}"
counts = Counter()
for group in GROUPS:
schools = [s for s in catalog["schools"] if by_country[s["country"]] == group]
counts[group] = len(schools)
with open(f"research/assignments/{group}.json", "w", encoding="utf-8") as f:
json.dump({"group": group, "schools": schools}, f, ensure_ascii=False, indent=1)
f.write("\n")
print(dict(counts), "total", sum(counts.values()))

118
scripts/parse_catalog.py Normal file
View file

@ -0,0 +1,118 @@
#!/usr/bin/env python3
"""Parse a SingleFile save of the CTU Mobility "Catalog of agreements" page.
Usage: python3 -I scripts/parse_catalog.py <saved-catalog.html> data/catalog.json
The saved page is a rendered Vue table. Every agreement is one
<tr class="row-headline"> with cells identified by data-testid. School names
are truncated in the table ("Instituto Tecnológico de B..."), so the research
step resolves full names from the web/QS links kept here.
Output: {"source": {...}, "agreements": [...], "schools": [...]}
agreements - one entry per table row (186 for FEL / Master / 2027)
schools - agreements merged by school code (one card per school)
"""
import html
import json
import re
import sys
from collections import OrderedDict
ISCED = {
"00": "Generic programmes (any field)", "0000": "Generic programmes (any field)",
"0533": "Physics", "0541": "Mathematics",
"061": "ICT", "0610": "ICT (general)", "0611": "Computer use", "0619": "ICT (other)",
"071": "Engineering", "0710": "Engineering (general)", "0713": "Electricity & energy",
"0714": "Electronics & automation", "0715": "Mechanics & metal trades",
"0716": "Motor vehicles, ships & aircraft", "0730": "Architecture & construction",
}
def text(fragment: str) -> str:
t = re.sub(r"<[^>]+>", " ", fragment)
return re.sub(r"\s+", " ", html.unescape(t)).strip()
def cell(row: str, testid: str) -> str:
m = re.search(r"data-testid=%s>(.*?)(?=<td|$)" % re.escape(testid), row, flags=re.S)
return text(m.group(1)) if m else ""
def parse_languages(raw: str):
"""'de (B2) en (B2)' -> [{'lang': 'de', 'level': 'B2'}, ...] (deduplicated)."""
seen, out = set(), []
for lang, level in re.findall(r"([a-z]{2})\s*\(([ABC][12])\)", raw):
if (lang, level) not in seen:
seen.add((lang, level))
out.append({"lang": lang, "level": level})
return out
def main(src_path: str, out_path: str) -> None:
src = open(src_path, encoding="utf-8").read()
meta_url = re.search(r"url:\s*(\S+)", src)
meta_date = re.search(r"saved date:\s*([^\n]+)", src)
src = re.sub(r"<style[^>]*>.*?</style>", " ", src, flags=re.S | re.I)
src = re.sub(r"<svg[^>]*>.*?</svg>", "", src, flags=re.S | re.I)
agreements = []
for chunk in re.split(r'<tr class="row-headline', src)[1:]:
row = chunk.split('<tr class="row-details')[0]
links = {label.strip(): html.unescape(href.strip('"'))
for href, label in re.findall(r'<a[^>]*href=("[^"]*"|\S+)[^>]*>([^<]*)</a>', row)}
lat = lon = None
m = re.search(r"x=([-\d.]+)&y=([-\d.]+)", links.get("Maps", ""))
if m:
lon, lat = float(m.group(1)), float(m.group(2))
places_raw = cell(row, "places")
isced = cell(row, "specialization").split()
agreements.append({
"code": cell(row, "code"),
"catalogName": cell(row, "name"),
"country": cell(row, "country"),
# "FEE" = Faculty of Electrical Engineering (FEL) agreement; blank = CTU-wide
"scope": "FEL" if cell(row, "faculty") == "FEE" else "CTU-wide",
"places": int(places_raw) if places_raw.isdigit() else None,
"isced": isced,
"iscedLabels": [ISCED.get(c, c) for c in isced],
"levels": cell(row, "studyType").split(),
"languages": parse_languages(cell(row, "language")),
"web": links.get("Web"),
"factsheet": links.get("Factsheet"),
"qs": links.get("QS"),
"lat": lat, "lon": lon,
})
schools = OrderedDict()
for a in agreements:
s = schools.setdefault(a["code"], {
"code": a["code"],
"slug": re.sub(r"[^A-Za-z0-9]+", "_", a["code"]).strip("_"),
"catalogName": a["catalogName"], "country": a["country"],
"web": a["web"], "qs": a["qs"], "lat": a["lat"], "lon": a["lon"],
"agreements": [],
})
s["agreements"].append({k: a[k] for k in
("scope", "places", "isced", "iscedLabels", "levels", "languages", "factsheet")})
for k in ("web", "qs", "lat", "lon"):
s[k] = s[k] or a[k]
out = {
"source": {
"url": meta_url.group(1) if meta_url else None,
"savedAt": meta_date.group(1).strip() if meta_date else None,
"academicYear": "2027/2028", "faculty": "FEL (13000)", "studyLevel": "Master (N)",
},
"agreements": agreements,
"schools": list(schools.values()),
}
with open(out_path, "w", encoding="utf-8") as f:
json.dump(out, f, ensure_ascii=False, indent=1)
f.write("\n")
print(f"{len(agreements)} agreements, {len(schools)} schools -> {out_path}")
if __name__ == "__main__":
if len(sys.argv) != 3:
sys.exit(__doc__)
main(sys.argv[1], sys.argv[2])

View 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:]))