elorasmus/scripts/build_data.py
agent 2e29248fd6 Add more school research; document podman-compose recreate
build_data.py no longer writes __pycache__. README/AGENTS: podman-compose needs
--force-recreate to replace a running container after a rebuild.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HA82gXkMmmRRKLSnY6vQN3
2026-11-12 20:56:59 +00:00

171 lines
8.5 KiB
Python

#!/usr/bin/env python3
"""Build public/data/schools.json, the single file the app loads.
Usage: python3 -I scripts/build_data.py [--strict]
Merges:
data/catalog.json agreements from the CTU catalog (scripts/parse_catalog.py)
research/raw/schools/<slug>.json per-school research (research/BRIEF.md)
research/raw/funding.json grant rates, FX, selection rules
research/raw/countries.json stability, visa, advisories (optional until researched)
Research files that fail scripts/validate_research.py are left out (with the errors printed),
so one bad file never breaks the app. --strict exits non-zero instead.
"""
import datetime as dt
import glob
import json
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
sys.path.insert(0, HERE) # -I drops the script dir from sys.path; we need our own validator
sys.dont_write_bytecode = True # no __pycache__ in scripts/
import validate_research # noqa: E402
# catalog country name -> (display name, ISO 3166 alpha-2, region)
COUNTRY_META = {
"Argentina": ("Argentina", "AR", "Latin America"), "Australia": ("Australia", "AU", "Oceania"),
"Austria": ("Austria", "AT", "Europe"), "Belgium": ("Belgium", "BE", "Europe"),
"Brazil": ("Brazil", "BR", "Latin America"), "Bulgaria": ("Bulgaria", "BG", "Europe"),
"Canada": ("Canada", "CA", "North America"), "Chile": ("Chile", "CL", "Latin America"),
"China": ("China", "CN", "Asia"), "Colombia": ("Colombia", "CO", "Latin America"),
"Costa Rica": ("Costa Rica", "CR", "Latin America"), "Croatia": ("Croatia", "HR", "Europe"),
"Denmark": ("Denmark", "DK", "Europe"), "Estonia": ("Estonia", "EE", "Europe"),
"Finland": ("Finland", "FI", "Europe"), "France": ("France", "FR", "Europe"),
"Germany": ("Germany", "DE", "Europe"), "Greece": ("Greece", "GR", "Europe"),
"Hungary": ("Hungary", "HU", "Europe"), "Iceland": ("Iceland", "IS", "Europe"),
"India": ("India", "IN", "Asia"), "Indonesia": ("Indonesia", "ID", "Asia"),
"Ireland": ("Ireland", "IE", "Europe"), "Italy": ("Italy", "IT", "Europe"),
"Japan": ("Japan", "JP", "Asia"), "Korea (the Republic of)": ("South Korea", "KR", "Asia"),
"Lithuania": ("Lithuania", "LT", "Europe"), "Mexico": ("Mexico", "MX", "Latin America"),
"Netherlands": ("Netherlands", "NL", "Europe"), "Norway": ("Norway", "NO", "Europe"),
"Peru": ("Peru", "PE", "Latin America"), "Poland": ("Poland", "PL", "Europe"),
"Portugal": ("Portugal", "PT", "Europe"), "Romania": ("Romania", "RO", "Europe"),
"Singapore": ("Singapore", "SG", "Asia"), "Slovakia": ("Slovakia", "SK", "Europe"),
"Slovenia": ("Slovenia", "SI", "Europe"), "Spain": ("Spain", "ES", "Europe"),
"Sweden": ("Sweden", "SE", "Europe"), "Switzerland": ("Switzerland", "CH", "Europe"),
"Taiwan": ("Taiwan", "TW", "Asia"), "Thailand": ("Thailand", "TH", "Asia"),
"Türkiye": ("Türkiye", "TR", "Europe"), "Ukraine": ("Ukraine", "UA", "Europe"),
"United States of America": ("USA", "US", "North America"), "Uruguay": ("Uruguay", "UY", "Latin America"),
"Venezuela": ("Venezuela", "VE", "Latin America"), "Viet Nam": ("Vietnam", "VN", "Asia"),
}
# Erasmus+ programme countries present in the catalog (EU27 + IS/LI/NO/TR/RS/MK).
ERASMUS = {"Austria", "Belgium", "Bulgaria", "Croatia", "Denmark", "Estonia", "Finland", "France",
"Germany", "Greece", "Hungary", "Iceland", "Ireland", "Italy", "Lithuania", "Netherlands",
"Norway", "Poland", "Portugal", "Romania", "Slovakia", "Slovenia", "Spain", "Sweden", "Türkiye"}
NAME_ALIASES = {"Turkey": "Türkiye"} # funding.json spells some countries differently
# CTU's non-European stipend has a higher rate for these destinations (research/raw/funding.json).
MBD_HIGH_RATE = {"United States of America", "Canada", "Australia", "Argentina"}
# Housing-swap agreements: the student pays CTU per semester and gets housing + meals at the host.
HOUSING_SWAP = {"US UTEP", "US UVM"}
HOUSING_SWAP_CZK = 55000
def flag(iso2):
return "".join(chr(0x1F1E6 + ord(c) - ord("A")) for c in iso2)
def load(path, default=None):
full = os.path.join(ROOT, path)
if not os.path.exists(full):
return default
with open(full, encoding="utf-8") as f:
return json.load(f)
def erasmus_group(country, funding):
for group, names in funding["erasmus"]["groups"].items():
if country in {NAME_ALIASES.get(n, n) for n in names}:
return int(group)
return None
def mbd_rate(country, funding):
"""Monthly EUR of CTU's stipend for non-European (MBD) agreements."""
by_dest = funding["ctuWide"].get("byDestination") or {}
high = next((v["EUR"] for k, v in by_dest.items() if "USA" in k), None)
other = next((v["EUR"] for k, v in by_dest.items() if "other" in k.lower()), None)
return (high if country in MBD_HIGH_RATE else other) or funding["ctuWide"].get("monthlyEUR")
def school_funding(s, funding):
country, fx = s["country"], funding["fx"]["EURCZK"]
if country in ERASMUS:
g = erasmus_group(country, funding)
rate = funding["erasmus"]["monthlyEUR"].get(str(g)) if g else None
return {"scheme": "erasmus", "group": g, "monthlyEUR": rate,
"label": f"Erasmus+ group {g}" if g else "Erasmus+",
"note": "Latest official Czech rates (2026/27); 2027/28 rates are not published yet."}
if country == "Switzerland":
return {"scheme": "switzerland", "group": None, "monthlyEUR": funding["switzerland"].get("monthlyEUR"),
"label": "Swiss mobility",
"note": "SEMP or Erasmus+, decided by a Swiss parliament vote in Dec 2026; CTU states 600 EUR/month. Low confidence."}
out = {"scheme": "ctu", "group": None, "monthlyEUR": mbd_rate(country, funding),
"label": "CTU stipend (non-Europe)",
"note": "CTU stipend for non-European agreements; rates last published 2024, paid after a financial agreement."}
if s["code"] in HOUSING_SWAP:
out["extraPerSemesterEUR"] = round(HOUSING_SWAP_CZK / fx)
out["note"] += (f" Housing-swap model: you pay CTU {HOUSING_SWAP_CZK:,} CZK per semester and get housing"
" and meals at the host; it is unclear whether the stipend is paid on top.")
return out
def main(strict):
catalog = load("data/catalog.json")
funding = load("research/raw/funding.json")
countries = load("research/raw/countries.json", {})
if funding is None:
sys.exit("research/raw/funding.json is missing")
problems = []
for f in ("research/raw/funding.json", "research/raw/countries.json"):
if os.path.exists(os.path.join(ROOT, f)):
problems += validate_research.validate(os.path.join(ROOT, f))
schools, researched = [], 0
for s in catalog["schools"]:
name, iso2, region = COUNTRY_META[s["country"]]
research = None
path = os.path.join(ROOT, "research", "raw", "schools", s["slug"] + ".json")
if os.path.exists(path):
errors = validate_research.validate(path)
if errors:
problems += errors
else:
with open(path, encoding="utf-8") as f:
research = json.load(f)
researched += 1
schools.append({**s, "countryShort": name, "iso2": iso2, "flag": flag(iso2), "region": region,
"funding": school_funding(s, funding), "research": research})
keep = ("status", "monthlyEUR", "fewerOpportunitiesTopUpEUR", "greenTravel", "ctuOrFelTopUp", "text", "sources")
out = {
"generatedAt": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"catalog": catalog["source"],
"fx": funding["fx"],
"funding": {
"erasmus": {k: funding["erasmus"].get(k) for k in keep},
"switzerland": funding["switzerland"],
"ctuWide": funding["ctuWide"],
"selection": funding["selection"],
},
"countries": countries,
"schools": schools,
}
dest = os.path.join(ROOT, "public", "data", "schools.json")
os.makedirs(os.path.dirname(dest), exist_ok=True)
with open(dest, "w", encoding="utf-8") as f:
json.dump(out, f, ensure_ascii=False, separators=(",", ":"))
f.write("\n")
for p in problems:
print("invalid:", p)
print(f"{len(schools)} schools, {researched} researched, countries: {len(countries)}, "
f"{len(problems)} validation problem(s) -> {os.path.relpath(dest, ROOT)} ({os.path.getsize(dest) // 1024} KB)")
return 1 if strict and problems else 0
if __name__ == "__main__":
sys.exit(main("--strict" in sys.argv[1:]))