Spaces:
Running on Zero
Running on Zero
| #!/usr/bin/env python3 | |
| """Self-host the web fonts so the app makes NO Google Fonts call at runtime (fully | |
| local). Downloads the LATIN subset (U+0000-00FF) of each weight used by the UI into | |
| ui/public/fonts/ and writes ui/public/fonts.css. Run once (or to refresh), then | |
| `npm run build`. Devanagari (हेर) uses the OS font, as before — these display fonts | |
| don't ship Devanagari glyphs either way. | |
| python3 scripts/build_fonts.py | |
| """ | |
| from __future__ import annotations | |
| import os | |
| import re | |
| import urllib.request | |
| UA = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 " | |
| "(KHTML, like Gecko) Chrome/124.0 Safari/537.36"} | |
| CSS_URL = ("https://fonts.googleapis.com/css2?family=Chakra+Petch:wght@500;600;700" | |
| "&family=IBM+Plex+Sans:wght@400;500;600&family=JetBrains+Mono:wght@400;500;600&display=swap") | |
| HERE = os.path.dirname(os.path.abspath(__file__)) | |
| PUB = os.path.join(os.path.dirname(HERE), "ui", "public") | |
| FONTS = os.path.join(PUB, "fonts") | |
| def _get(url: str) -> bytes: | |
| return urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=30).read() | |
| def main() -> int: | |
| os.makedirs(FONTS, exist_ok=True) | |
| css = _get(CSS_URL).decode("utf-8") | |
| out, picked = [], set() | |
| for b in re.findall(r"@font-face\s*\{([^}]*)\}", css): | |
| fam = re.search(r"font-family:\s*'([^']+)'", b) | |
| wght = re.search(r"font-weight:\s*(\d+)", b) | |
| url = re.search(r"url\((https://[^)]+\.woff2)\)", b) | |
| ur = re.search(r"unicode-range:\s*([^;]+);", b) | |
| if not (fam and wght and url and ur): | |
| continue | |
| if "U+0000-00FF" not in ur.group(1).upper().replace(" ", ""): # latin subset only | |
| continue | |
| fam, wght, url = fam.group(1), wght.group(1), url.group(1) | |
| if (fam, wght) in picked: | |
| continue | |
| picked.add((fam, wght)) | |
| fn = fam.lower().replace(" ", "") + "-" + wght + ".woff2" | |
| open(os.path.join(FONTS, fn), "wb").write(_get(url)) | |
| out.append(f"@font-face{{font-family:'{fam}';font-style:normal;font-weight:{wght};" | |
| f"font-display:swap;src:url('/fonts/{fn}') format('woff2');}}") | |
| print(f" {fam} {wght} -> {fn}") | |
| open(os.path.join(PUB, "fonts.css"), "w").write("\n".join(out) + "\n") | |
| print(f"wrote ui/public/fonts.css ({len(out)} faces)") | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |