From f158f1d485d153972287166190af7a9d5fe2ecf7 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:39:48 +0100 Subject: [PATCH] refactor: move the site image tools into sitegen --- scripts/fetch_site_images.py | 210 +--------------------------- scripts/make_og_cards.py | 111 ++------------- scripts/make_site_icons.py | 158 +-------------------- scripts/sitegen/brand.py | 165 ++++++++++++++++++++++ scripts/sitegen/chromium.py | 15 ++ scripts/sitegen/imagefetch.py | 123 ++++++++++++++++ scripts/sitegen/imagenormalize.py | 105 ++++++++++++++ scripts/sitegen/ogcards.py | 115 +++++++++++++++ tests/sources.py | 3 + tests/test_layers.py | 4 +- tests/test_optional_dependencies.py | 5 +- tests/test_site_components.py | 4 +- tests/test_site_inputs.py | 7 +- tests/test_site_systems.py | 13 +- 14 files changed, 561 insertions(+), 477 deletions(-) create mode 100644 scripts/sitegen/brand.py create mode 100644 scripts/sitegen/chromium.py create mode 100644 scripts/sitegen/imagefetch.py create mode 100644 scripts/sitegen/imagenormalize.py create mode 100644 scripts/sitegen/ogcards.py diff --git a/scripts/fetch_site_images.py b/scripts/fetch_site_images.py index c213294fd..73e481b9c 100644 --- a/scripts/fetch_site_images.py +++ b/scripts/fetch_site_images.py @@ -6,7 +6,7 @@ The site served these from other hosts: GitHub avatars and files on the in silence, and every page view hit third-party hosts. This tool copies them into ``docs_assets/logos/`` and ``docs_assets/system-icons/``, which are committed, and records where each came from in a ``sources.json`` beside -them. The site build only reads those copies (``sitediagrams.localize_images``). +them. The site build only reads those copies (``sitegen.diagrams.localize_images``). Raster logos are normalised to an 80 px square WebP, twice the 40 px they are shown at, and system icons to a 48 px PNG, so every tile has the same @@ -23,208 +23,8 @@ and PyYAML. from __future__ import annotations import argparse -import base64 -import io -import json -import re -import subprocess -import sys -import urllib.parse -from pathlib import Path -from model.registry import load_platform_registry -from core.paths import DB_FILE, PLATFORMS_DIR, REPO_ROOT -from scraper.base_scraper import FetchError, fetch_bytes - -sys.path.insert(0, str(REPO_ROOT / "scripts")) - -LOGO_DIR = REPO_ROOT / "docs_assets" / "logos" -ICON_DIR = REPO_ROOT / "docs_assets" / "system-icons" -LOGO_SIZE = 80 -ICON_SIZE = 48 -AVATAR_HOST = "avatars.githubusercontent.com" -USER_AGENT = "retrobios-site-images" - -def fetch(url: str) -> bytes: - """A GET retried on a rate limit or a dropped connection: one 429 - midway left icons rewritten under a sources.json of the previous run.""" - return fetch_bytes(url, {"User-Agent": USER_AGENT}, timeout=60) - - -def square_image(data: bytes, size: int, kind: str = "PNG", flip: bool = False, - trim: bool = False) -> bytes: - """*flip* mirrors the image top to bottom, for a boot logo stored in the - row order a device's screen reads (MinUI's). *trim* cuts the plain - background around the mark, the corner pixel's colour, and keeps that - colour around it: a 640 x 480 boot screen became a dot.""" - try: - from PIL import Image, ImageChops - except ImportError as exc: - raise SystemExit("Pillow is needed to normalise raster images: pip install Pillow") from exc - image = Image.open(io.BytesIO(data)).convert("RGBA") - if flip: - image = image.transpose(Image.Transpose.FLIP_TOP_BOTTOM) - background = (0, 0, 0, 0) - if trim: - background = image.getpixel((0, 0)) - # Faint noise in the background is no part of the mark. - box = (ImageChops.difference(image, Image.new("RGBA", image.size, background)) - .convert("L").point(lambda value: 255 if value > 48 else 0).getbbox()) - if box: - image = image.crop(box) - side = round(max(image.size) * 1.2) - framed = Image.new("RGBA", (side, side), background) - framed.paste(image, ((side - image.width) // 2, (side - image.height) // 2)) - image = framed - image.thumbnail((size, size), Image.LANCZOS) - tile = Image.new("RGBA", (size, size), background) - tile.paste(image, ((size - image.width) // 2, (size - image.height) // 2), image) - out = io.BytesIO() - if kind == "WEBP": - # Quality 90: half the bytes of lossless, edges still clean at 40 px. - tile.save(out, "WEBP", quality=90, method=6) - else: - tile.save(out, "PNG", optimize=True) - return out.getvalue() - - -def is_svg(data: bytes) -> bool: - head = data[:512].lstrip().lower() - return head.startswith((b" bytes: - lowered = data.lower() - for token in (b" bytes: - """Each raster an SVG embeds, at most LOGO_SIZE pixels on its longest side.""" - - def shrink(match: re.Match[bytes]) -> bytes: - try: - from PIL import Image - except ImportError as exc: - raise SystemExit("Pillow is needed to normalise raster images: pip install Pillow") from exc - image = Image.open(io.BytesIO(base64.b64decode(re.sub(rb"\s", b"", match.group(1))))).convert("RGBA") - if max(image.size) <= LOGO_SIZE: - return match.group(0) - image.thumbnail((LOGO_SIZE, LOGO_SIZE), Image.LANCZOS) - out = io.BytesIO() - image.save(out, "PNG", optimize=True) - return b"data:image/png;base64," + base64.b64encode(out.getvalue()) - - return EMBEDDED_RASTER.sub(shrink, data) - - -# Editor markup (Inkscape's namedview, sodipodi attributes, metadata) was -# most of the bytes of two logos. svgo comes with the site's packages. -SVGO = REPO_ROOT / "website" / "node_modules" / ".bin" / "svgo" - - -def minify_svg(data: bytes) -> bytes: - if not SVGO.is_file(): - raise SystemExit("svgo is needed to minify SVG logos: npm ci --prefix website") - result = subprocess.run([str(SVGO), "--multipass", "-i", "-", "-o", "-"], - input=data, capture_output=True, check=True) - return result.stdout - - -def write_manifest(directory: Path, note: str, entries: list[dict]) -> None: - entries.sort(key=lambda entry: entry["file"]) - document = {"note": note, "images": entries} - (directory / "sources.json").write_text( - json.dumps(document, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" - ) - - -def fetch_logos() -> None: - from model.guides import GROUP_TILES, GUIDES - - platforms = load_platform_registry(REPO_ROOT / PLATFORMS_DIR, required=True) - LOGO_DIR.mkdir(parents=True, exist_ok=True) - entries = [] - # The tiles of a kind of device (Android handhelds) beside the setups - # carry a logo too, named after the tile. - sources = [(name, entry.get("logo"), entry, GUIDES.get(name)) - for name, entry in sorted(platforms.items())] - sources += [(re.sub(r"[^a-z0-9]+", "-", tile.name.lower()).strip("-"), tile.logo, {}, tile) - for tiles in GROUP_TILES.values() for tile in tiles] - for name, url, entry, guide in sources: - if not url: - # No logo of its own: the tile shows initials, and an old copy - # would still be served. - for stale in LOGO_DIR.glob(f"{name}.*"): - stale.unlink() - continue - download = f"{url}?s={LOGO_SIZE * 2}" if AVATAR_HOST in url else url - data = fetch(download) - if is_svg(data): - file_name, payload = f"{name}.svg", minify_svg(shrink_embedded(safe_svg(data, url))) - else: - file_name, payload = f"{name}.webp", square_image( - data, LOGO_SIZE, "WEBP", flip=bool(entry.get("logo_flip")), - trim=bool(entry.get("logo_trim"))) - for stale in LOGO_DIR.glob(f"{name}.*"): - if stale.name != file_name: - stale.unlink() - (LOGO_DIR / file_name).write_bytes(payload) - # Who owns each mark: logo_owner and logo_licence in the guides. - owner = (guide and guide.logo_owner) or name - licence = (guide and guide.logo_licence) or "ownership not recorded" - entries.append({ - "file": file_name, "platform": name, "source": url, - "owner": owner, "licence": licence, - }) - print(f" {file_name} from {url}") - write_manifest( - LOGO_DIR, - "Each platform's own logo, owned by its project and shown only to name that " - "platform. Copied once by scripts/fetch_site_images.py.", - entries, - ) - - -def fetch_icons() -> None: - from model.database import load_database - from model.collection import group_by_manufacturer - from sitegen.render import SYSTEM_ICON_BASE, console_icon_name - - db = load_database(str(REPO_ROOT / DB_FILE)) - names = sorted({ - console_icon_name(manufacturer, console) - for manufacturer, consoles in group_by_manufacturer(db).items() - for console in consoles - }) - ICON_DIR.mkdir(parents=True, exist_ok=True) - entries = [] - for name in names: - url = f"{SYSTEM_ICON_BASE}/{urllib.parse.quote(name)}.png" - try: - data = fetch(url) - except FetchError as exc: - if exc.status == 404: - continue - raise - file_name = f"{name}.png" - (ICON_DIR / file_name).write_bytes(square_image(data, ICON_SIZE)) - entries.append({"file": file_name, "source": url}) - print(f" {file_name}") - write_manifest( - ICON_DIR, - "System icons from libretro/retroarch-assets (xmb/systematic), " - "licensed CC-BY-4.0 by the libretro team. Resized to 48 px.", - entries, - ) +from sitegen.imagefetch import fetch_icons, fetch_logos def main() -> None: @@ -233,10 +33,12 @@ def main() -> None: args = parser.parse_args() if args.only in (None, "logos"): print("Platform logos:") - fetch_logos() + for file_name, url in fetch_logos(): + print(f" {file_name} from {url}") if args.only in (None, "icons"): print("System icons:") - fetch_icons() + for file_name in fetch_icons(): + print(f" {file_name}") if __name__ == "__main__": diff --git a/scripts/make_og_cards.py b/scripts/make_og_cards.py index a91fe01d3..854dd68dc 100644 --- a/scripts/make_og_cards.py +++ b/scripts/make_og_cards.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """Render the sharing cards (Open Graph images) to PNG, once. -Each card is an SVG written by ``sitediagrams.og_card_svg`` from the +Each card is an SVG written by ``sitegen.diagrams.og_card_svg`` from the registry, rasterised by a headless Chromium through Playwright, then committed under ``docs_assets/og/``. The site build copies the PNG files and never runs this script, so it adds nothing to the build's dependencies. @@ -20,86 +20,10 @@ consoles (``og/systems/.png``), the other pages their section's. from __future__ import annotations import argparse -import sys -from pathlib import Path -sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) - -from core.text import series -from model.registry import list_registered_platforms -from model.platforms import load_platform_config -from sitegen.diagrams import OG_SECTIONS, og_card_svg, wrap - -ROOT = Path(__file__).resolve().parent.parent - -OUT = ROOT / "docs_assets" / "og" -LOGO = ROOT / "docs_assets" / "brand" / "logo.svg" -PLATFORM_TAGLINE = "Which BIOS files it needs, and where each one goes" -# The tagline's box on the card: og_card_svg wraps it at this width and -# size, and three lines fit above the address. -TAGLINE_WIDTH, TAGLINE_SIZE, TAGLINE_LINES = 1000, 34, 3 - - -def platform_cards() -> dict[str, tuple[str, str]]: - """Each platform page's card, by its path under og/, with its title.""" - platforms = ROOT / "platforms" - return { - f"platforms/{name}": (load_platform_config(name, str(platforms))["platform"], - PLATFORM_TAGLINE) - for name in list_registered_platforms(str(platforms)) - } - - -def consoles_tagline(consoles: list[str], lead: str = "BIOS files for") -> str: - """"BIOS files for PlayStation, PlayStation 2 and 5 more": as many - names as the card's three lines hold, the rest counted.""" - names = sorted(consoles, key=str.casefold) - for shown in range(len(names), 0, -1): - rest = len(names) - shown - listed = names[:shown] - if rest: - text = f"{lead} {', '.join(listed)} and {rest} more" - else: - text = f"{lead} {series(listed)}" - if len(wrap(text, TAGLINE_WIDTH, TAGLINE_SIZE)) <= TAGLINE_LINES: - return text - return f"{lead} {len(names)} sections" - - -def system_cards() -> dict[str, tuple[str, str]]: - """Each manufacturer page's card under og/systems/, titled with the - manufacturer and listing its consoles. Read from the same grouping the - system pages are written from.""" - from model.composition import GAME_DATA_TOPS - from model.database import load_database - from model.collection import group_by_manufacturer, manufacturer_slug - - def lead(manufacturer: str) -> str: - # Other holds one folder per emulator, a game publisher's page its - # games' data: neither is a list of consoles. - if manufacturer in GAME_DATA_TOPS: - return "Game data for" - return "Files kept for the emulators" if manufacturer == "Other" else "BIOS files for" - - manufacturers = group_by_manufacturer(load_database(str(ROOT / "database.json"))) - return { - f"systems/{manufacturer_slug(manufacturer)}": ( - manufacturer, consoles_tagline(list(consoles), lead(manufacturer))) - for manufacturer, consoles in sorted(manufacturers.items()) - } - - -def card_svg(key: str, logo: str, titles: dict[str, tuple[str, str]]) -> str: - if key in OG_SECTIONS: - return og_card_svg(key, logo) - # A page card is a section card with the page's own title and tagline. - # The tagline is a format string there: braces in a name stay text. - title, tagline = titles[key] - OG_SECTIONS[key] = (title, tagline.replace("{", "{{").replace("}", "}}")) - try: - return og_card_svg(key, logo) - finally: - del OG_SECTIONS[key] +from core.paths import REPO_ROOT +from sitegen.chromium import require_playwright +from sitegen.ogcards import card_keys, card_titles, render_cards def main() -> None: @@ -108,29 +32,10 @@ def main() -> None: parser.add_argument("--only", choices=("sections", "platforms", "systems"), help="render one kind of card (default: all)") args = parser.parse_args() - try: - from playwright.sync_api import sync_playwright - except ImportError as exc: - raise SystemExit("Playwright with Chromium is needed: pip install playwright") from exc - titles: dict[str, tuple[str, str]] = {} - if args.only in (None, "platforms"): - titles.update(platform_cards()) - if args.only in (None, "systems"): - titles.update(system_cards()) - keys = [*(OG_SECTIONS if args.only in (None, "sections") else []), *titles] - logo = LOGO.read_text(encoding="utf-8") - with sync_playwright() as playwright: - browser = playwright.chromium.launch() - page = browser.new_page(viewport={"width": 1200, "height": 630}) - for key in keys: - page.set_content( - '' + card_svg(key, logo, titles) + "" - ) - path = OUT / f"{key}.png" - path.parent.mkdir(parents=True, exist_ok=True) - page.screenshot(path=str(path), clip={"x": 0, "y": 0, "width": 1200, "height": 630}) - print(path.relative_to(ROOT)) - browser.close() + sync_playwright = require_playwright() + titles = card_titles(args.only) + for path in render_cards(sync_playwright, card_keys(args.only, titles), titles): + print(path.relative_to(REPO_ROOT)) if __name__ == "__main__": diff --git a/scripts/make_site_icons.py b/scripts/make_site_icons.py index 5c2a6467e..624316184 100644 --- a/scripts/make_site_icons.py +++ b/scripts/make_site_icons.py @@ -29,164 +29,14 @@ The repository's own images come from the same shapes, in ``.github/assets/``: from __future__ import annotations from core.paths import REPO_ROOT - -OUT = REPO_ROOT / "docs_assets" / "brand" -PROJECT = REPO_ROOT / ".github" / "assets" - -HEADER = "#3b3f7a" -GLYPH = "#8be0f7" -GLYPH_DIM = "#4fa3c4" -# The site title: the light scheme's accent, the dark scheme's accent. -TITLE = {"light": "#273c8f", "dark": "#aebcff"} -# The mark beside it: the header logo in each scheme (website/src/assets). -MARK = {"light": HEADER, "dark": "#fff"} -# The sharing cards' background (sitediagrams.og_card_svg). -CARD = "#2b2e5c" -FONT = "system-ui, -apple-system, 'Segoe UI', 'Noto Sans', Helvetica, Arial, sans-serif" - -# (column, row, dim) on the 4 by 4 grid, read from the project logo. -PIXELS = [ - (0, 0, False), (1, 0, False), (2, 0, True), - (1, 1, False), (3, 1, True), - (0, 2, False), (3, 2, False), - (1, 3, True), (2, 3, False), (3, 3, False), -] - -BODY = (8, 8, 32, 4) # x, y, size, corner radius in a 48 unit box -PIN_CENTRES = (13.5, 20.5, 27.5, 34.5) -PIN_WIDTH = 3.4 -PIN_LENGTH = 5.5 -CELL = 5.0 -GAP = 1.6 - - -def _pins(fill: str) -> str: - half = PIN_WIDTH / 2 - rects = [] - for centre in PIN_CENTRES: - start = centre - half - rects += [ - (start, 8 - PIN_LENGTH, PIN_WIDTH, PIN_LENGTH), - (start, 40, PIN_WIDTH, PIN_LENGTH), - (8 - PIN_LENGTH, start, PIN_LENGTH, PIN_WIDTH), - (40, start, PIN_LENGTH, PIN_WIDTH), - ] - return "".join( - f'' - for x, y, w, h in rects - ) - - -def _glyph(bright: str, dim: str) -> str: - span = 4 * CELL + 3 * GAP - origin = BODY[0] + (BODY[2] - span) / 2 - return "".join( - f'' - for c, r, is_dim in PIXELS - ) - - -def _body(fill: str, extra: str = "") -> str: - x, y, size, radius = BODY - return f'' - - -def _mark(fill: str) -> str: - """The chip in one colour, glyph cut out so what is behind shows through.""" - return ('' + _body("#fff") + _glyph("#000", "#5a5a5a") + "" - + _pins(fill) + _body(fill, ' mask="url(#glyph)"')) - - -def logo_svg() -> str: - """White chip, glyph cut out: the header colour shows through it.""" - return ('' + _mark("#fff") + "") - - -def project_logo_svg() -> str: - """The chip in colour, on any background.""" - return ('' + _pins(HEADER) + _body(HEADER) + _glyph(GLYPH, GLYPH_DIM) - + "") - - -def banner_svg(scheme: str) -> str: - """The mark and the name as the site header sets them: system-ui at 600, - the mark about twice the height of the capitals.""" - return ('' + _mark(MARK[scheme]) + "" - f'RetroBIOS') - - -def social_preview_html() -> str: - """The white mark and the name on the sharing cards' indigo, centred.""" - return (f'' - '' - + _mark("#fff") + "" - f'' - "RetroBIOS") - - -def favicon_svg() -> str: - return ( - '' - "" - + _pins(HEADER).replace(f'fill="{HEADER}"', 'class="c"') - + _body(HEADER).replace(f'fill="{HEADER}"', 'class="c"') - + _glyph(GLYPH, GLYPH_DIM) + "" - ) - - -def touch_icon_svg() -> str: - """Opaque square: iOS fills transparency with black.""" - return ( - '' - f'' - + logo_svg().split(">", 1)[1].rsplit("", 1)[0] + "" - ) +from sitegen.brand import write_brand +from sitegen.chromium import require_playwright def main() -> None: - try: - from playwright.sync_api import sync_playwright - except ImportError as exc: - raise SystemExit("Playwright with Chromium is needed: pip install playwright") from exc - OUT.mkdir(parents=True, exist_ok=True) - vectors = ( - (OUT / "logo.svg", logo_svg()), (OUT / "favicon.svg", favicon_svg()), - (PROJECT / "logo.svg", project_logo_svg()), - (PROJECT / "banner-light.svg", banner_svg("light")), - (PROJECT / "banner-dark.svg", banner_svg("dark")), - ) - for path, text in vectors: - path.write_text(text + "\n", encoding="utf-8") + sync_playwright = require_playwright() + for path in write_brand(sync_playwright): print(path.relative_to(REPO_ROOT)) - favicon = favicon_svg().replace("@media (prefers-color-scheme: dark)", "@media not all") - rasters = ( - (OUT / "favicon-32.png", 32, favicon), - (OUT / "apple-touch-icon.png", 180, touch_icon_svg()), - (PROJECT / "favicon.png", 32, favicon), - (PROJECT / "logo.png", 256, project_logo_svg()), - ) - with sync_playwright() as playwright: - browser = playwright.chromium.launch() - for path, size, text in rasters: - page = browser.new_page(viewport={"width": size, "height": size}) - sized = text.replace("{sized}') - page.screenshot(path=str(path), omit_background=True, clip={"x": 0, "y": 0, "width": size, "height": size}) - page.close() - print(path.relative_to(REPO_ROOT)) - page = browser.new_page(viewport={"width": 1280, "height": 640}) - page.set_content(social_preview_html()) - page.screenshot(path=str(PROJECT / "social-preview.png"), - clip={"x": 0, "y": 0, "width": 1280, "height": 640}) - print((PROJECT / "social-preview.png").relative_to(REPO_ROOT)) - browser.close() if __name__ == "__main__": diff --git a/scripts/sitegen/brand.py b/scripts/sitegen/brand.py new file mode 100644 index 000000000..42aadf579 --- /dev/null +++ b/scripts/sitegen/brand.py @@ -0,0 +1,165 @@ +"""The project's mark as vector shapes, and the icon and logo files drawn from it.""" + +from __future__ import annotations + +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +from core.paths import REPO_ROOT + +OUT = REPO_ROOT / "docs_assets" / "brand" +PROJECT = REPO_ROOT / ".github" / "assets" + +HEADER = "#3b3f7a" +GLYPH = "#8be0f7" +GLYPH_DIM = "#4fa3c4" +# The site title: the light scheme's accent, the dark scheme's accent. +TITLE = {"light": "#273c8f", "dark": "#aebcff"} +# The mark beside it: the header logo in each scheme (website/src/assets). +MARK = {"light": HEADER, "dark": "#fff"} +# The sharing cards' background (sitegen.diagrams.og_card_svg). +CARD = "#2b2e5c" +FONT = "system-ui, -apple-system, 'Segoe UI', 'Noto Sans', Helvetica, Arial, sans-serif" + +# (column, row, dim) on the 4 by 4 grid, read from the project logo. +PIXELS = [ + (0, 0, False), (1, 0, False), (2, 0, True), + (1, 1, False), (3, 1, True), + (0, 2, False), (3, 2, False), + (1, 3, True), (2, 3, False), (3, 3, False), +] + +BODY = (8, 8, 32, 4) # x, y, size, corner radius in a 48 unit box +PIN_CENTRES = (13.5, 20.5, 27.5, 34.5) +PIN_WIDTH = 3.4 +PIN_LENGTH = 5.5 +CELL = 5.0 +GAP = 1.6 + + +def _pins(fill: str) -> str: + half = PIN_WIDTH / 2 + rects = [] + for centre in PIN_CENTRES: + start = centre - half + rects += [ + (start, 8 - PIN_LENGTH, PIN_WIDTH, PIN_LENGTH), + (start, 40, PIN_WIDTH, PIN_LENGTH), + (8 - PIN_LENGTH, start, PIN_LENGTH, PIN_WIDTH), + (40, start, PIN_LENGTH, PIN_WIDTH), + ] + return "".join( + f'' + for x, y, w, h in rects + ) + + +def _glyph(bright: str, dim: str) -> str: + span = 4 * CELL + 3 * GAP + origin = BODY[0] + (BODY[2] - span) / 2 + return "".join( + f'' + for c, r, is_dim in PIXELS + ) + + +def _body(fill: str, extra: str = "") -> str: + x, y, size, radius = BODY + return f'' + + +def _mark(fill: str) -> str: + """The chip in one colour, glyph cut out so what is behind shows through.""" + return ('' + _body("#fff") + _glyph("#000", "#5a5a5a") + "" + + _pins(fill) + _body(fill, ' mask="url(#glyph)"')) + + +def logo_svg() -> str: + """White chip, glyph cut out: the header colour shows through it.""" + return ('' + _mark("#fff") + "") + + +def project_logo_svg() -> str: + """The chip in colour, on any background.""" + return ('' + _pins(HEADER) + _body(HEADER) + _glyph(GLYPH, GLYPH_DIM) + + "") + + +def banner_svg(scheme: str) -> str: + """The mark and the name as the site header sets them: system-ui at 600, + the mark about twice the height of the capitals.""" + return ('' + _mark(MARK[scheme]) + "" + f'RetroBIOS') + + +def social_preview_html() -> str: + """The white mark and the name on the sharing cards' indigo, centred.""" + return (f'' + '' + + _mark("#fff") + "" + f'' + "RetroBIOS") + + +def favicon_svg() -> str: + return ( + '' + "" + + _pins(HEADER).replace(f'fill="{HEADER}"', 'class="c"') + + _body(HEADER).replace(f'fill="{HEADER}"', 'class="c"') + + _glyph(GLYPH, GLYPH_DIM) + "" + ) + + +def touch_icon_svg() -> str: + """Opaque square: iOS fills transparency with black.""" + return ( + '' + f'' + + logo_svg().split(">", 1)[1].rsplit("", 1)[0] + "" + ) + + +def write_brand(sync_playwright: Any) -> Iterator[Path]: + """Each file of the mark as it is written: the vectors, then the rasters + a headless Chromium draws from them.""" + OUT.mkdir(parents=True, exist_ok=True) + vectors = ( + (OUT / "logo.svg", logo_svg()), (OUT / "favicon.svg", favicon_svg()), + (PROJECT / "logo.svg", project_logo_svg()), + (PROJECT / "banner-light.svg", banner_svg("light")), + (PROJECT / "banner-dark.svg", banner_svg("dark")), + ) + for path, text in vectors: + path.write_text(text + "\n", encoding="utf-8") + yield path + favicon = favicon_svg().replace("@media (prefers-color-scheme: dark)", "@media not all") + rasters = ( + (OUT / "favicon-32.png", 32, favicon), + (OUT / "apple-touch-icon.png", 180, touch_icon_svg()), + (PROJECT / "favicon.png", 32, favicon), + (PROJECT / "logo.png", 256, project_logo_svg()), + ) + with sync_playwright() as playwright: + browser = playwright.chromium.launch() + for path, size, text in rasters: + page = browser.new_page(viewport={"width": size, "height": size}) + sized = text.replace("{sized}') + page.screenshot(path=str(path), omit_background=True, clip={"x": 0, "y": 0, "width": size, "height": size}) + page.close() + yield path + page = browser.new_page(viewport={"width": 1280, "height": 640}) + page.set_content(social_preview_html()) + page.screenshot(path=str(PROJECT / "social-preview.png"), + clip={"x": 0, "y": 0, "width": 1280, "height": 640}) + yield PROJECT / "social-preview.png" + browser.close() diff --git a/scripts/sitegen/chromium.py b/scripts/sitegen/chromium.py new file mode 100644 index 000000000..e154b7cbe --- /dev/null +++ b/scripts/sitegen/chromium.py @@ -0,0 +1,15 @@ +"""The headless Chromium that rasterises the committed icons and sharing cards.""" + +from __future__ import annotations + +from typing import Any + + +def require_playwright() -> Any: + """Playwright's sync_playwright, or an exit naming what to install: the + image tools need it, the site build never does.""" + try: + from playwright.sync_api import sync_playwright + except ImportError as exc: + raise SystemExit("Playwright with Chromium is needed: pip install playwright") from exc + return sync_playwright diff --git a/scripts/sitegen/imagefetch.py b/scripts/sitegen/imagefetch.py new file mode 100644 index 000000000..51700b158 --- /dev/null +++ b/scripts/sitegen/imagefetch.py @@ -0,0 +1,123 @@ +"""The platform logos and system icons the site shows, copied once into docs_assets/.""" + +from __future__ import annotations + +import json +import re +import urllib.parse +from collections.abc import Iterator +from pathlib import Path + +from core.paths import DB_FILE, PLATFORMS_DIR, REPO_ROOT +from model.collection import group_by_manufacturer +from model.database import load_database +from model.guides import GROUP_TILES, GUIDES +from model.registry import load_platform_registry +from scraper.base_scraper import FetchError, fetch_bytes +from sitegen.imagenormalize import ( + ICON_SIZE, + LOGO_SIZE, + is_svg, + minify_svg, + safe_svg, + shrink_embedded, + square_image, +) +from sitegen.render import SYSTEM_ICON_BASE, console_icon_name + +LOGO_DIR = REPO_ROOT / "docs_assets" / "logos" +ICON_DIR = REPO_ROOT / "docs_assets" / "system-icons" +AVATAR_HOST = "avatars.githubusercontent.com" +USER_AGENT = "retrobios-site-images" + + +def fetch(url: str) -> bytes: + """A GET retried on a rate limit or a dropped connection: one 429 + midway left icons rewritten under a sources.json of the previous run.""" + return fetch_bytes(url, {"User-Agent": USER_AGENT}, timeout=60) + + +def write_manifest(directory: Path, note: str, entries: list[dict]) -> None: + entries.sort(key=lambda entry: entry["file"]) + document = {"note": note, "images": entries} + (directory / "sources.json").write_text( + json.dumps(document, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" + ) + + +def fetch_logos() -> Iterator[tuple[str, str]]: + """Each logo as it is written, (file name, source URL). sources.json is + written after the last one.""" + platforms = load_platform_registry(REPO_ROOT / PLATFORMS_DIR, required=True) + LOGO_DIR.mkdir(parents=True, exist_ok=True) + entries = [] + # The tiles of a kind of device (Android handhelds) beside the setups + # carry a logo too, named after the tile. + sources = [(name, entry.get("logo"), entry, GUIDES.get(name)) + for name, entry in sorted(platforms.items())] + sources += [(re.sub(r"[^a-z0-9]+", "-", tile.name.lower()).strip("-"), tile.logo, {}, tile) + for tiles in GROUP_TILES.values() for tile in tiles] + for name, url, entry, guide in sources: + if not url: + # No logo of its own: the tile shows initials, and an old copy + # would still be served. + for stale in LOGO_DIR.glob(f"{name}.*"): + stale.unlink() + continue + download = f"{url}?s={LOGO_SIZE * 2}" if AVATAR_HOST in url else url + data = fetch(download) + if is_svg(data): + file_name, payload = f"{name}.svg", minify_svg(shrink_embedded(safe_svg(data, url))) + else: + file_name, payload = f"{name}.webp", square_image( + data, LOGO_SIZE, "WEBP", flip=bool(entry.get("logo_flip")), + trim=bool(entry.get("logo_trim"))) + for stale in LOGO_DIR.glob(f"{name}.*"): + if stale.name != file_name: + stale.unlink() + (LOGO_DIR / file_name).write_bytes(payload) + # Who owns each mark: logo_owner and logo_licence in the guides. + owner = (guide and guide.logo_owner) or name + licence = (guide and guide.logo_licence) or "ownership not recorded" + entries.append({ + "file": file_name, "platform": name, "source": url, + "owner": owner, "licence": licence, + }) + yield file_name, url + write_manifest( + LOGO_DIR, + "Each platform's own logo, owned by its project and shown only to name that " + "platform. Copied once by scripts/fetch_site_images.py.", + entries, + ) + + +def fetch_icons() -> Iterator[str]: + """Each icon's file name as it is written, the systems libretro draws no + icon for skipped. sources.json is written after the last one.""" + db = load_database(str(REPO_ROOT / DB_FILE)) + names = sorted({ + console_icon_name(manufacturer, console) + for manufacturer, consoles in group_by_manufacturer(db).items() + for console in consoles + }) + ICON_DIR.mkdir(parents=True, exist_ok=True) + entries = [] + for name in names: + url = f"{SYSTEM_ICON_BASE}/{urllib.parse.quote(name)}.png" + try: + data = fetch(url) + except FetchError as exc: + if exc.status == 404: + continue + raise + file_name = f"{name}.png" + (ICON_DIR / file_name).write_bytes(square_image(data, ICON_SIZE)) + entries.append({"file": file_name, "source": url}) + yield file_name + write_manifest( + ICON_DIR, + "System icons from libretro/retroarch-assets (xmb/systematic), " + "licensed CC-BY-4.0 by the libretro team. Resized to 48 px.", + entries, + ) diff --git a/scripts/sitegen/imagenormalize.py b/scripts/sitegen/imagenormalize.py new file mode 100644 index 000000000..d9064f160 --- /dev/null +++ b/scripts/sitegen/imagenormalize.py @@ -0,0 +1,105 @@ +"""Logos and icons brought to one tile size: rasters squared, SVG checked and minified.""" + +from __future__ import annotations + +import base64 +import io +import re +import subprocess +from typing import Any + +from core.paths import REPO_ROOT + +LOGO_SIZE = 80 +ICON_SIZE = 48 + + +def _pillow() -> Any: + """Pillow's Image and ImageChops, or an exit naming what to install.""" + try: + from PIL import Image, ImageChops + except ImportError as exc: + raise SystemExit("Pillow is needed to normalise raster images: pip install Pillow") from exc + return Image, ImageChops + + +def square_image(data: bytes, size: int, kind: str = "PNG", flip: bool = False, + trim: bool = False) -> bytes: + """*flip* mirrors the image top to bottom, for a boot logo stored in the + row order a device's screen reads (MinUI's). *trim* cuts the plain + background around the mark, the corner pixel's colour, and keeps that + colour around it: a 640 x 480 boot screen became a dot.""" + Image, ImageChops = _pillow() + image = Image.open(io.BytesIO(data)).convert("RGBA") + if flip: + image = image.transpose(Image.Transpose.FLIP_TOP_BOTTOM) + background = (0, 0, 0, 0) + if trim: + background = image.getpixel((0, 0)) + # Faint noise in the background is no part of the mark. + box = (ImageChops.difference(image, Image.new("RGBA", image.size, background)) + .convert("L").point(lambda value: 255 if value > 48 else 0).getbbox()) + if box: + image = image.crop(box) + side = round(max(image.size) * 1.2) + framed = Image.new("RGBA", (side, side), background) + framed.paste(image, ((side - image.width) // 2, (side - image.height) // 2)) + image = framed + image.thumbnail((size, size), Image.LANCZOS) + tile = Image.new("RGBA", (size, size), background) + tile.paste(image, ((size - image.width) // 2, (size - image.height) // 2), image) + out = io.BytesIO() + if kind == "WEBP": + # Quality 90: half the bytes of lossless, edges still clean at 40 px. + tile.save(out, "WEBP", quality=90, method=6) + else: + tile.save(out, "PNG", optimize=True) + return out.getvalue() + + +def is_svg(data: bytes) -> bool: + head = data[:512].lstrip().lower() + return head.startswith((b" bytes: + lowered = data.lower() + for token in (b" bytes: + """Each raster an SVG embeds, at most LOGO_SIZE pixels on its longest side.""" + + def shrink(match: re.Match[bytes]) -> bytes: + Image, _ = _pillow() + image = Image.open(io.BytesIO(base64.b64decode(re.sub(rb"\s", b"", match.group(1))))).convert("RGBA") + if max(image.size) <= LOGO_SIZE: + return match.group(0) + image.thumbnail((LOGO_SIZE, LOGO_SIZE), Image.LANCZOS) + out = io.BytesIO() + image.save(out, "PNG", optimize=True) + return b"data:image/png;base64," + base64.b64encode(out.getvalue()) + + return EMBEDDED_RASTER.sub(shrink, data) + + +# Editor markup (Inkscape's namedview, sodipodi attributes, metadata) was +# most of the bytes of two logos. svgo comes with the site's packages. +SVGO = REPO_ROOT / "website" / "node_modules" / ".bin" / "svgo" + + +def minify_svg(data: bytes) -> bytes: + if not SVGO.is_file(): + raise SystemExit("svgo is needed to minify SVG logos: npm ci --prefix website") + result = subprocess.run([str(SVGO), "--multipass", "-i", "-", "-o", "-"], + input=data, capture_output=True, check=True) + return result.stdout diff --git a/scripts/sitegen/ogcards.py b/scripts/sitegen/ogcards.py new file mode 100644 index 000000000..08a30593c --- /dev/null +++ b/scripts/sitegen/ogcards.py @@ -0,0 +1,115 @@ +"""The sharing cards (Open Graph images): each page's title and tagline, rendered to PNG.""" + +from __future__ import annotations + +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +from core.paths import DB_FILE, PLATFORMS_DIR, REPO_ROOT +from core.text import series +from model.collection import group_by_manufacturer, manufacturer_slug +from model.composition import GAME_DATA_TOPS +from model.database import load_database +from model.platforms import load_platform_config +from model.registry import list_registered_platforms +from sitegen.diagrams import OG_SECTIONS, og_card_svg, wrap + +OUT = REPO_ROOT / "docs_assets" / "og" +LOGO = REPO_ROOT / "docs_assets" / "brand" / "logo.svg" +PLATFORM_TAGLINE = "Which BIOS files it needs, and where each one goes" +# The tagline's box on the card: og_card_svg wraps it at this width and +# size, and three lines fit above the address. +TAGLINE_WIDTH, TAGLINE_SIZE, TAGLINE_LINES = 1000, 34, 3 + + +def platform_cards() -> dict[str, tuple[str, str]]: + """Each platform page's card, by its path under og/, with its title.""" + platforms = REPO_ROOT / PLATFORMS_DIR + return { + f"platforms/{name}": (load_platform_config(name, str(platforms))["platform"], + PLATFORM_TAGLINE) + for name in list_registered_platforms(str(platforms)) + } + + +def consoles_tagline(consoles: list[str], lead: str = "BIOS files for") -> str: + """"BIOS files for PlayStation, PlayStation 2 and 5 more": as many + names as the card's three lines hold, the rest counted.""" + names = sorted(consoles, key=str.casefold) + for shown in range(len(names), 0, -1): + rest = len(names) - shown + listed = names[:shown] + if rest: + text = f"{lead} {', '.join(listed)} and {rest} more" + else: + text = f"{lead} {series(listed)}" + if len(wrap(text, TAGLINE_WIDTH, TAGLINE_SIZE)) <= TAGLINE_LINES: + return text + return f"{lead} {len(names)} sections" + + +def _manufacturer_lead(manufacturer: str) -> str: + # Other holds one folder per emulator, a game publisher's page its + # games' data: neither is a list of consoles. + if manufacturer in GAME_DATA_TOPS: + return "Game data for" + return "Files kept for the emulators" if manufacturer == "Other" else "BIOS files for" + + +def system_cards() -> dict[str, tuple[str, str]]: + """Each manufacturer page's card under og/systems/, titled with the + manufacturer and listing its consoles. Read from the same grouping the + system pages are written from.""" + manufacturers = group_by_manufacturer(load_database(str(REPO_ROOT / DB_FILE))) + return { + f"systems/{manufacturer_slug(manufacturer)}": ( + manufacturer, consoles_tagline(list(consoles), _manufacturer_lead(manufacturer))) + for manufacturer, consoles in sorted(manufacturers.items()) + } + + +def card_titles(only: str | None) -> dict[str, tuple[str, str]]: + """The page cards of the kind *only* names (every kind when None), by key.""" + titles: dict[str, tuple[str, str]] = {} + if only in (None, "platforms"): + titles.update(platform_cards()) + if only in (None, "systems"): + titles.update(system_cards()) + return titles + + +def card_keys(only: str | None, titles: dict[str, tuple[str, str]]) -> list[str]: + """The section cards, unless *only* names another kind, then the page cards.""" + return [*(OG_SECTIONS if only in (None, "sections") else []), *titles] + + +def card_svg(key: str, logo: str, titles: dict[str, tuple[str, str]]) -> str: + if key in OG_SECTIONS: + return og_card_svg(key, logo) + # A page card is a section card with the page's own title and tagline. + # The tagline is a format string there: braces in a name stay text. + title, tagline = titles[key] + OG_SECTIONS[key] = (title, tagline.replace("{", "{{").replace("}", "}}")) + try: + return og_card_svg(key, logo) + finally: + del OG_SECTIONS[key] + + +def render_cards(sync_playwright: Any, keys: list[str], + titles: dict[str, tuple[str, str]]) -> Iterator[Path]: + """Each card's PNG as it is written under og/, drawn by a headless Chromium.""" + logo = LOGO.read_text(encoding="utf-8") + with sync_playwright() as playwright: + browser = playwright.chromium.launch() + page = browser.new_page(viewport={"width": 1200, "height": 630}) + for key in keys: + page.set_content( + '' + card_svg(key, logo, titles) + "" + ) + path = OUT / f"{key}.png" + path.parent.mkdir(parents=True, exist_ok=True) + page.screenshot(path=str(path), clip={"x": 0, "y": 0, "width": 1200, "height": 630}) + yield path + browser.close() diff --git a/tests/sources.py b/tests/sources.py index c2e5f85dd..49e9e9df3 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -121,6 +121,9 @@ COMMANDS = { "schemas/romfolders.py", "schemas/games.py", "schemas/run.py", ), "site_insights.py": ("sitegen/insights.py",), + "fetch_site_images.py": ("sitegen/imagefetch.py", "sitegen/imagenormalize.py"), + "make_site_icons.py": ("sitegen/brand.py", "sitegen/chromium.py"), + "make_og_cards.py": ("sitegen/ogcards.py", "sitegen/chromium.py"), "generate_readme.py": ("sitegen/readme.py",), "make_demo.py": ( "sitegen/demovariants.py", "sitegen/democard.py", "sitegen/demosession.py", diff --git a/tests/test_layers.py b/tests/test_layers.py index a6a4c7272..18d8cd055 100644 --- a/tests/test_layers.py +++ b/tests/test_layers.py @@ -39,8 +39,8 @@ SIBLING_IMPORTS: dict[str, frozenset[str]] = { "romrecipes": frozenset(), # The site prints the recipe counts and the dump-catalog coverage report # those two packages compute, serves the handheld launchers and prints the - # CI checks. - "sitegen": frozenset({"acquire", "packs", "romrecipes", "installer_build", "devtools"}), + # CI checks. The logo copier downloads through the scrapers' fetch_bytes. + "sitegen": frozenset({"acquire", "packs", "romrecipes", "installer_build", "devtools", "scraper"}), # The record names its packs as the pack builder does. "release": frozenset({"packs"}), # The launcher archives are written by the pack member writer. diff --git a/tests/test_optional_dependencies.py b/tests/test_optional_dependencies.py index c2b771814..b5f187da4 100644 --- a/tests/test_optional_dependencies.py +++ b/tests/test_optional_dependencies.py @@ -65,9 +65,8 @@ class SuiteWithoutJsonschema(unittest.TestCase): # is committed under docs_assets/ and the build only reads it, so the build # keeps to the standard library and pyyaml. MAINTENANCE_TOOLS = { - "fetch_site_images.py": "PIL", - "make_og_cards.py": "playwright", - "make_site_icons.py": "playwright", + "imagenormalize.py": "PIL", + "chromium.py": "playwright", } diff --git a/tests/test_site_components.py b/tests/test_site_components.py index a473d1771..fd9985470 100644 --- a/tests/test_site_components.py +++ b/tests/test_site_components.py @@ -721,7 +721,7 @@ class LogosAtTheirDisplaySize(unittest.TestCase): if path.suffix == ".webp": self.assertEqual(_webp_size(path.read_bytes()), (LOGO_PIXELS, LOGO_PIXELS)) self.assertEqual(sorted(p.name for p in LOGOS.glob("*.png")), []) - script = _read(REPO_ROOT / "scripts" / "fetch_site_images.py") + script = script_source("fetch_site_images.py") self.assertIn(f"LOGO_SIZE = {LOGO_PIXELS}", script) self.assertIn('square_image(\n data, LOGO_SIZE, "WEBP"', script) @@ -1069,7 +1069,7 @@ class LogosAtTheirWeight(unittest.TestCase): self.assertLessEqual(max(width, height), 80) def test_the_fetcher_writes_them_so(self): - script = _read(REPO_ROOT / "scripts" / "fetch_site_images.py") + script = script_source("fetch_site_images.py") self.assertIn('minify_svg(shrink_embedded(safe_svg(data, url)))', script) diff --git a/tests/test_site_inputs.py b/tests/test_site_inputs.py index 71a8ff311..d99134cc6 100644 --- a/tests/test_site_inputs.py +++ b/tests/test_site_inputs.py @@ -121,9 +121,10 @@ class TheCollectionDoesNotDependOnTheWorkingDirectory(unittest.TestCase): self.assertEqual(siteinputs.bios_dir({"bios_dir": "/abs/bios"}), Path("/abs/bios")) def test_the_image_tools_do_not_load_the_page_generator(self) -> None: - for module in ("make_og_cards.py", "fetch_site_images.py", "sitegen/render.py"): - with self.subTest(module=module): - source = (REPO_ROOT / "scripts" / module).read_text(encoding="utf-8") + tools = ("make_og_cards.py", "fetch_site_images.py", "make_site_icons.py") + for path in (*(p for tool in tools for p in script_paths(tool)), SCRIPTS / "sitegen" / "render.py"): + with self.subTest(module=path.name): + source = path.read_text(encoding="utf-8") self.assertNotIn("from generate_site import", source) diff --git a/tests/test_site_systems.py b/tests/test_site_systems.py index ae316a145..7555d7de7 100644 --- a/tests/test_site_systems.py +++ b/tests/test_site_systems.py @@ -54,7 +54,8 @@ from sitegen import systemsindex from sitegen import render as siterender from model import systemnames from packs.crossref import FileConsumers -import make_og_cards +from sitegen import ogcards +from sitegen.diagrams import wrap from core.anchors import toc_slug REPO_ROOT = Path(__file__).resolve().parents[1] @@ -585,15 +586,15 @@ class ArcadeIsItsOwnGroup(unittest.TestCase): class EachManufacturerHasItsCard(unittest.TestCase): def test_a_tagline_holds_three_lines_and_counts_the_rest(self) -> None: names = [f"Console number {n}" for n in range(40)] - text = make_og_cards.consoles_tagline(names) + text = ogcards.consoles_tagline(names) self.assertRegex(text, r" and \d+ more$") - lines = make_og_cards.wrap(text, make_og_cards.TAGLINE_WIDTH, make_og_cards.TAGLINE_SIZE) - self.assertLessEqual(len(lines), make_og_cards.TAGLINE_LINES) - self.assertEqual(make_og_cards.consoles_tagline(["Saturn", "Dreamcast"]), + lines = wrap(text, ogcards.TAGLINE_WIDTH, ogcards.TAGLINE_SIZE) + self.assertLessEqual(len(lines), ogcards.TAGLINE_LINES) + self.assertEqual(ogcards.consoles_tagline(["Saturn", "Dreamcast"]), "BIOS files for Dreamcast and Saturn") def test_every_manufacturer_page_has_a_committed_card(self) -> None: - cards = make_og_cards.system_cards() + cards = ogcards.system_cards() missing = [key for key in cards if not (REPO_ROOT / "docs_assets" / "og" / f"{key}.png").is_file()] self.assertEqual(missing, [], "run python scripts/make_og_cards.py --only systems")