Spaces:
Running on Zero
Running on Zero
File size: 2,430 Bytes
5f43c7d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | #!/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())
|