diff --git a/.gitignore b/.gitignore index bc9e7f2..c1caeeb 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,6 @@ __pycache__/ cache/ .idea/ .venv-site/ +# The poster service's kept layers and finished pictures, when run from here +/layers/ +/posters/ diff --git a/README.md b/README.md index d49d677..2e9e7b0 100644 --- a/README.md +++ b/README.md @@ -24,10 +24,22 @@ How posters are made (sources and their licences, kept layers, options, credits) | `GET /circuits/{country}/{locality}/{circuit}/layout/{layout}/{format}` | the layout's file: `geojson`, `svg` or `png` | | `GET /tracks/{country}/{locality}/{circuit}/year/{year}/{format}` | the layout the circuit used that year | | `GET /grand-prix/{race}/{season}/{format}` | the layout a race ran on, such as `/grand-prix/Qatar Grand Prix/2025/geojson` | -| `GET /posters/race/{race}/{season}.png?bg=…` | a 1000×1500 race poster; `bg` is `aerial` (default), `osm`, `dark`, `light` or `none` | -| `GET /posters/season/{season}.png` | a 1000×1500 season poster | -| `GET /posters/session/{race}/{season}/{session}.png` | a 1920×1080 thumbnail for one session, such as `fp1`, `qualifying`, `sprint` or `race` | +| `GET /posters/race/{race}/{season}.png?…` | a 1000×1500 race poster: the round, the race's name and date and its track over a picture of its circuit | +| `GET /posters/season/{season}.png?…` | a 1000×1500 season poster: the year over a picked photo of that season's cars, or over black | +| `GET /posters/session/{race}/{season}/{session}.png?…` | a 1920×1080 thumbnail for one session, such as `fp1`, `qualifying`, `sprint` or `race` | | `GET /kometa/formula-1-metadata.yml` | [Kometa](https://kometa.wiki/) metadata that sets these posters on a Plex Formula 1 library | +| `GET /licences` | every source a picture may be made from: its licence, its credit and its terms, and how a picture's licence follows from them | + +The three picture routes take the same options as query parameters ([docs/posters.md](docs/posters.md) lists +them): `style` (`classic`, `minimal`), `bg` (`satellite`, its alias `aerial`, `osm`, `dark`, `light`, `none`), +`photo` (`natural`, `bw`), `show` (a comma list of `wordmark`, `round`, `name`, `subtitle`, `date`, `circuit`, +`locality`, `session`), `locator` and `checker` (`on`, `off`), `track` (`off`, or a colour with an optional width, +`#ffffff,6`), `dim` (0 to 1), `accent` (a colour), `width` (200 up to the picture's own) and `format` (`png`, `jpg`, +`webp`). An unknown option or value is answered 422, naming it. `bg=satellite` takes the layout's picked Wikimedia +Commons photo, else the national aerial photo (USGS in the United States, PDOK in the Netherlands, IGN in France), +else EOxCloudless; [circuits/photos.json](circuits/photos.json) holds the picks, and `{"use": "map"}` there makes a +layout draw the dark map instead of EOxCloudless. Every picture carries the credit line of its sources at its +bottom and in `X-Credits`, its licence in `X-License` (it follows its sources), and `Link: ; rel="license"`. A race is named as [Jolpica](https://github.com/jolpica/jolpica-f1) (the Ergast API's successor) names it in its schedule, and its circuit is found by Jolpica's circuit id (`ergastId` in `circuits.json`), never by the @@ -133,18 +145,26 @@ rate limit and kept in `cache/jolpica/`; a throttled or failed fetch is said in ## Caching -What the service fetches or renders is kept in `cache/` (the module's cache volume): race schedules from Jolpica -in `cache/jolpica/` (a season that is over for good, the running one for six hours), and every poster and thumbnail -in `cache/posters/` once every map tile and photo it needs came. A poster is sent with an `ETag` and a day's -`Cache-Control`; one whose map or photo failed is not kept, and is sent with five minutes', so it is rendered again -once its source answers. Map tiles are fetched in parallel, at most six at once from Esri and two from -OpenStreetMap. +Race schedules from Jolpica are kept in `cache/jolpica/` (a season that is over for good, the running one for six +hours). What a picture needs from the network is a layer, kept for good in `layers/` (the module's `layers` directory, +backed up and fetched again if lost): the map picture of one source around a layout, a picked photo cropped to the +picture, the world locator and the track's outline. A layer is kept only whole, when every tile came and they are +not all one picture. Every finished picture is kept in `posters/` under a key of its route, its options and its +layers, at most 2 GB, the least recently used going first; a second season of a circuit draws from the kept layers +and fetches nothing. A picture whose map or photo did not arrive is served without it, kept nowhere, and sent with +five minutes' `Cache-Control` and no `ETag`. + +Clients keep an address that carries the render version (`?v=r3`, as the Kometa file writes it) for good +(`immutable`); any other address a day, then ask again with its `ETag` and get a 304 while it is unchanged. Every +request the service makes carries the User-Agent `f1-circuits/ (+)`. OpenStreetMap tiles +are fetched only when a picture asks for them, at most two at once; Wikimedia Commons is asked one request at a time. ## Checks `merge-check.sh` runs before a change merges: every Python file the service ships must parse, and the tests in `tests/` must pass (every circuit has one unique `ergastId`, a race resolves by it, a failed Jolpica fetch is never -kept, every link in this README leads to a file). +kept, every link in this README leads to a file; a poster's satellite source, +credits and licence, its options, keys and cache headers, and the picture store's cap). ## Acknowledgment @@ -152,8 +172,9 @@ kept, every link in this README leads to a file). [initial data source](https://www.google.com/maps/d/u/0/viewer?mid=1nv6ugq4H67CSzKUauW92-pPstYw&ll=-37.84579005412956%2C144.96881158570557&z=16) and altitudes (from [Highs and lows - which F1 track has the most elevation changes?](https://www.formula1.com/en/latest/features/2016/10/highs-and-lows---which-f1-track-has-the-most-elevation-changes-.html)) are kept in the upstream files. -* Race schedules from [Jolpica](https://github.com/jolpica/jolpica-f1); poster backgrounds from Esri (World Imagery - and the grey canvases) and OpenStreetMap. +* Race schedules from [Jolpica](https://github.com/jolpica/jolpica-f1) (CC BY-NC-SA 4.0); the posters' pictures from + Wikimedia Commons, USGS, PDOK (Beeldmateriaal Nederland), IGN, EOX (EOxCloudless) and OpenStreetMap, each under + its licence and with its credit: `/licences` and [docs/posters.md](docs/posters.md). ## Disclaimer diff --git a/app_info.py b/app_info.py new file mode 100644 index 0000000..b32e13e --- /dev/null +++ b/app_info.py @@ -0,0 +1,17 @@ +"""Who this service is to the outside: its version, its public address and the User-Agent it sends. + +Standard library only: the Jolpica client, the poster sources and the API share it. +""" +import os + +# The API's own version (cdn-api.py's FastAPI app says the same). +APP_VERSION = "1.0.0" + +# The address this service is reached at, which the Kometa metadata links every poster to and every outgoing +# request names. The mesh writes it from the name the route is served under (F1_CIRCUITS_BASE_URL); the fallback +# is the address HAL served it at, so a deployment that sets nothing behaves as before. +PUBLIC_BASE_URL = os.environ.get("F1_CIRCUITS_BASE_URL", "https://f1-circuits.zurag.be").rstrip("/") + +# Every outgoing request carries it (Jolpica, the map and photo sources): the app's name and its public address, +# never a person's address. +USER_AGENT = f"f1-circuits/{APP_VERSION} (+{PUBLIC_BASE_URL})" diff --git a/cdn-api.py b/cdn-api.py index 668d219..201e0e1 100644 --- a/cdn-api.py +++ b/cdn-api.py @@ -1,32 +1,42 @@ -import hashlib - from fastapi import FastAPI, HTTPException, Request, Response -from fastapi.responses import FileResponse, Response as FastAPIResponse, PlainTextResponse +from fastapi.openapi.docs import get_swagger_ui_html +from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, PlainTextResponse from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles from pathlib import Path +from typing import Optional import logging # Import our CircuitService +from app_info import APP_VERSION from circuits_service import CircuitService, Format -from posters_service import PostersService, BackgroundStyle +from posters_service import PostersService, Rendered +import poster_options +import poster_sources from access_log import log_request from models.track_layout import TrackLayout -# Initialize FastAPI app +# The unofficial-use disclaimer for the Formula 1 marks, at the foot of / and /docs (and of the example site). +DISCLAIMER = ("This service is unofficial and is not associated in any way with the Formula 1 companies. F1, FORMULA " + "ONE, FORMULA 1, FIA FORMULA ONE WORLD CHAMPIONSHIP, GRAND PRIX, and related marks are trademarks of " + "Formula One Licensing B.V.") + +# Initialize FastAPI app; /docs is served below, with the disclaimer at its foot app = FastAPI( title="F1 Track Layouts API", description="API serving F1 track layout images, vectors and GeoJSON files", - version="1.0.0" + version=APP_VERSION, + docs_url=None, ) -# Add CORS middleware +# Add CORS middleware. The example pages, opened from another origin, read a picture's credits and licence. app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], + expose_headers=["X-Credits", "X-License", "Link", "ETag"], ) # Configure logging @@ -84,11 +94,29 @@ async def root(): "/posters/season/{season}.png", "/posters/session/{grand_prix_name}/{season}/{session_slug}.png", "/kometa/formula-1-metadata.yml", + "/licences", ], "examples": "/examples/", + "disclaimer": DISCLAIMER, } +@app.get("/docs", include_in_schema=False) +async def docs() -> HTMLResponse: + """The OpenAPI docs, with the disclaimer at their foot.""" + page = get_swagger_ui_html(openapi_url=app.openapi_url, title=f"{app.title} - docs").body.decode() + footer = (f'
{DISCLAIMER}
') + return HTMLResponse(page.replace("", f"{footer}")) + + +@app.get("/licences") +async def get_licences(): + """Every source a picture may be made from: its licence, its credit and its terms' address, and how a picture's + licence follows from them.""" + return poster_sources.licences() + + # The example site: one page per area of the API, each calling the routes above (examples/index.html). app.mount( "/examples", @@ -100,66 +128,76 @@ app.mount( # The poster routes are plain defs, not async: a render fetches map tiles and a schedule and draws for # seconds, so it runs in the threadpool instead of holding up every other request on the event loop. -def poster_response(request: Request, png: bytes, kept: bool) -> Response: - """A stored poster: clients keep it a day, then ask again with its ETag and get a 304 while it is - unchanged, so a poster whose look changed reaches them within a day, not a year. A poster whose map - or photo failed is kept by clients for five minutes, with no ETag, so they ask again soon.""" - if not kept: - return FastAPIResponse(content=png, media_type="image/png", headers={"Cache-Control": "public, max-age=300"}) - etag = '"' + hashlib.sha256(png).hexdigest()[:32] + '"' - headers = {"Cache-Control": "public, max-age=86400", "ETag": etag} - if etag in [tag.strip().removeprefix("W/") for tag in request.headers.get("if-none-match", "").split(",")]: +POSTER_OPTIONS_DOC = """Options are query parameters, the same on every poster route (docs/posters.md); an unknown option + or value is answered 422, naming it: `style` (classic, minimal), `bg` (satellite, its alias aerial, osm, dark, + light, none), `photo` (natural, bw), `show` (a comma list of wordmark, round, name, subtitle, date, circuit, + locality, session), `locator` and `checker` (on, off), `track` (off, or #rrggbb with an optional width: + #ffffff,6), `dim` (0 to 1), `accent` (#rrggbb), `width` (200 up to the frame's), `format` (png, jpg, webp), and + `v`, the render version, which the Kometa file adds so clients keep the picture for good.""" + + +def render_poster(request: Request, kind: str, grand_prix_name: Optional[str] = None, season: Optional[int] = None, + session_slug: Optional[str] = None) -> Response: + """A picture with its credits, its licence and what clients may keep of it. + + An address with the current render version (?v=) is kept for good; any other a day, then asked again with its + ETag (a 304 while it is unchanged); a picture served without its map or photo five minutes, with no ETag.""" + try: + options = poster_options.parse_options(request.query_params.multi_items(), kind) + except poster_options.OptionError as e: + return JSONResponse(status_code=422, content={"detail": str(e)}) + try: + rendered: Optional[Rendered] = posters_service.render(kind, options, grand_prix_name, season, session_slug) + except poster_sources.LicenceClash as e: + logger.error(f"Picture refused, {kind} {grand_prix_name} {season} {session_slug}: {e}") + raise HTTPException(status_code=500, detail=f"Picture refused: {e}") + if rendered is None: + what = " ".join(str(part) for part in (grand_prix_name, season, session_slug) if part is not None) + raise HTTPException(status_code=404, detail=f"No {kind} picture available for {what}") + etag = '"' + rendered.name.split(".")[0][:32] + '"' + headers = poster_options.cache_headers(rendered.kept, options.versioned, etag) + headers.update({"X-Credits": poster_sources.ascii_header(rendered.credit), "X-License": rendered.licence, + "Link": '; rel="license"'}) + if rendered.kept and poster_options.etag_matches(request.headers.get("if-none-match", ""), etag): return Response(status_code=304, headers=headers) - return FastAPIResponse(content=png, media_type="image/png", headers=headers) + return Response(content=rendered.data, media_type=rendered.media_type, headers=headers) -@app.get("/posters/race/{grand_prix_name}/{season}.png") -def get_race_poster(request: Request, grand_prix_name: str, season: int, bg: BackgroundStyle = BackgroundStyle.AERIAL): - """Plex-ready 1000x1500 race poster (PNG). Cached on disk per (race, bg). - - `?bg=` selects the backdrop: - - aerial (default) — Esri World Imagery satellite at the circuit's coords - - osm — OpenStreetMap Carto street-map at the circuit's coords - - dark — Esri Dark Gray Canvas - - light — Esri Light Gray Canvas - - none — plain black background (skip tile fetch) - """ - rendered = posters_service.render_race_poster(grand_prix_name, season, bg=bg) - if not rendered: - raise HTTPException(status_code=404, detail=f"No poster available for {grand_prix_name} {season}") - return poster_response(request, *rendered) +@app.get("/posters/race/{grand_prix_name}/{season}.png", description=POSTER_OPTIONS_DOC) +def get_race_poster(request: Request, grand_prix_name: str, season: int): + """Plex-ready 1000x1500 race poster: the round, the race's name and date and its track over a map or photo of + its circuit.""" + return render_poster(request, "race", grand_prix_name, season) -@app.get("/posters/season/{season}.png") +@app.get("/posters/season/{season}.png", description=POSTER_OPTIONS_DOC) def get_season_poster(request: Request, season: int): - """Plex-ready 1000x1500 season poster (PNG). Cached on disk.""" - return poster_response(request, *posters_service.render_season_poster(season)) + """Plex-ready 1000x1500 season poster: the year over a picked photo of that season's cars, or over black.""" + return render_poster(request, "season", season=season) -@app.get("/posters/session/{grand_prix_name}/{season}/{session_slug}.png") +@app.get("/posters/session/{grand_prix_name}/{season}/{session_slug}.png", description=POSTER_OPTIONS_DOC) def get_session_thumb(request: Request, grand_prix_name: str, season: int, session_slug: str): - """Plex episode-thumb (1920x1080) for a specific session of a race weekend. + """Plex episode-thumb (1920x1080) for one session of a race weekend. `session_slug` is one of: fp1, fp2, fp3, pre-qualifying, qualifying, post-qualifying, pre-race, race, post-race, highlights, pre-sprint, sprint, post-sprint, pre-sprint-qualifying, sprint-qualifying, post-sprint-qualifying, bonus. """ - rendered = posters_service.render_session_thumb(grand_prix_name, season, session_slug) - if not rendered: - raise HTTPException(status_code=404, detail=f"No session thumb for {grand_prix_name} {season} {session_slug}") - return poster_response(request, *rendered) + return render_poster(request, "session", grand_prix_name, season, session_slug) @app.get("/kometa/formula-1-metadata.yml") def get_kometa_metadata(): """Generate a Kometa-compatible metadata YAML for the Formula 1 library. - One entry per F1 season from 1950..current+1. Each entry: + Its first lines say where its data comes from (Jolpica, CC BY-NC-SA 4.0). One entry per F1 season from + 1950..current+1. Each entry: - uses Kometa's f1_season builder for round/episode names - - sets url_poster on the show (per-season hero from files-api) - - sets url_poster on each Plex 'season' (== each F1 round) from the - f1-circuits race poster endpoint + - sets url_poster on the show (the season poster) + - sets url_poster on each Plex 'season' (== each F1 round) from the race poster route, and on each episode + from the session thumbnail route; every address carries ?v= Kometa harmlessly skips shows / seasons that don't exist in the Plex library, so we can emit the full schedule and let Kometa do the matching. diff --git a/circuits/photos.json b/circuits/photos.json new file mode 100644 index 0000000..238ffd5 --- /dev/null +++ b/circuits/photos.json @@ -0,0 +1,3 @@ +{ + "$comment": "The picked Wikimedia Commons aerial photo per layout (docs/posters.md, Picking photos). Key: the layout's path under circuits/ without extension, country/city/circuit/layout, such as \"belgium/spa/circuit-de-spa-francorchamps/1983-\". Value: {\"file\": the Commons title without \"File:\", \"licence\": its LicenseShortName (CC0, public domain, CC BY or CC BY-SA only), \"author\", \"credit\": \"Photo: , , via Wikimedia Commons\", \"date\": YYYY[-MM[-DD]]}; or, instead of a photo, {\"use\": \"map\"}: that layout's bg=satellite then draws the dark OpenStreetMap map instead of EOxCloudless (a photo or a national aerial photo still comes first). Written by the picking tool, read by the poster service; a key starting with \"$\" is a note, not a pick." +} diff --git a/ergast_service.py b/ergast_service.py index 8a1d861..0289c3c 100644 --- a/ergast_service.py +++ b/ergast_service.py @@ -9,6 +9,8 @@ from datetime import date from pathlib import Path from typing import Optional, TYPE_CHECKING +from app_info import USER_AGENT + if TYPE_CHECKING: from circuits_service import CircuitService @@ -112,7 +114,8 @@ class ErgastService: time.sleep(wait) self._last_request = time.monotonic() try: - with urllib.request.urlopen(url, timeout=self.REQUEST_TIMEOUT) as resp: + request = urllib.request.Request(url, headers={'User-Agent': USER_AGENT}) + with urllib.request.urlopen(request, timeout=self.REQUEST_TIMEOUT) as resp: return json.loads(resp.read())['MRData']['RaceTable']['Races'] except urllib.error.HTTPError as e: if e.code != 429 or attempt == self.RETRIES: diff --git a/merge-check.sh b/merge-check.sh index 85c1cce..9d75e6c 100644 --- a/merge-check.sh +++ b/merge-check.sh @@ -11,14 +11,16 @@ # models it imports. Then the tests in tests/, which need the standard library only: every circuit in # circuits/circuits.json carries one unique ergastId, and a race's circuit resolves by that id, never by # its name; a failed Jolpica fetch is never kept, a season that is over is read from disk, a throttled -# request is asked again. +# request is asked again; a poster's options, keys, cache headers and store cap, its satellite source, credits and +# licence (poster_options.py and poster_sources.py, standard library only). # # **Said, never passed silently**: the service's dependencies (service/requirements.txt) are the image's to # install, so the service is not started. set -eu # Parsed, not compiled to files: a check leaves the tree as it found it. -find cdn-api.py access_log.py circuits_service.py ergast_service.py posters_service.py models -name '*.py' -print0 | +find cdn-api.py access_log.py app_info.py circuits_service.py ergast_service.py posters_service.py poster_options.py \ + poster_sources.py models -name '*.py' -print0 | xargs -0 python3 -c 'import ast, sys for f in sys.argv[1:]: ast.parse(open(f, encoding="utf-8").read(), f) diff --git a/module.json b/module.json index e54d78b..704bb1f 100644 --- a/module.json +++ b/module.json @@ -23,7 +23,7 @@ "port": 8000, "protocol": "tcp", "from": "mesh", - "why": "the track-layout CDN, the race posters and the Kometa metadata over http; its public name is a route grant and the proxy reaches it here. Kometa fetches the metadata and every poster by that public name" + "why": "the track-layout CDN, the race posters, their licences and the Kometa metadata over http; its public name is a route grant and the proxy reaches it here. Kometa fetches the metadata and every poster by that public name" } ], "data": { @@ -32,7 +32,19 @@ "id": "cache", "path": "${dir:cache}", "class": "cache", - "why": "the generated track layouts and posters, rebuilt on demand" + "why": "the race schedules asked from Jolpica, asked again when lost" + }, + { + "id": "layers", + "path": "${dir:layers}", + "class": "rebuildable", + "why": "the kept layers of the posters: the map pictures, picked photos, world locators and track outlines, fetched once and kept for good; fetched again if lost" + }, + { + "id": "posters", + "path": "${dir:posters}", + "class": "cache", + "why": "the finished posters and thumbnails, at most 2 GB, drawn again from the layers on demand" } ] }, @@ -48,6 +60,16 @@ "type": "directory", "mode": "0700" }, + { + "id": "layers", + "type": "directory", + "mode": "0700" + }, + { + "id": "posters", + "type": "directory", + "mode": "0700" + }, { "id": "site-env", "type": "file", @@ -67,7 +89,9 @@ "${dir:state}/site.env" ], "volumes": [ - "${dir:cache}:/app/cache" + "${dir:cache}:/app/cache", + "${dir:layers}:/app/layers", + "${dir:posters}:/app/posters" ], "restart-on": [ "site-env" diff --git a/poster_options.py b/poster_options.py new file mode 100644 index 0000000..ef927dd --- /dev/null +++ b/poster_options.py @@ -0,0 +1,223 @@ +"""What a caller may choose on a poster, a season poster or a session thumbnail, how a choice is checked, and the +keys pictures are kept under (docs/posters.md, Options, Layers and Finished images). Standard library only, so the +merge check tests it as it is. +""" +import hashlib +import math +import re +from dataclasses import dataclass +from typing import Iterable, Optional + +# Part of every layer's and every finished picture's key: raised when what a picture looks like changes, so no +# picture made before is served again. r3: licensed sources, kept layers, options and credits. +RENDER_VERSION = "r3" + +# A frame is the picture's own size: a poster (race and season) and a session thumbnail. +FRAMES = {"poster": (1000, 1500), "thumb": (1920, 1080)} +FRAME_OF = {"race": "poster", "season": "poster", "session": "thumb"} + +SHOW_ITEMS = ("wordmark", "round", "name", "subtitle", "date", "circuit", "locality", "session") +BACKGROUNDS = ("satellite", "osm", "dark", "light", "none") +BG_ALIASES = {"aerial": "satellite"} # kept for addresses already in use +PHOTO_TREATMENTS = ("bw", "natural") +FORMATS = {"png": "image/png", "jpg": "image/jpeg", "webp": "image/webp"} +STYLES = ("classic", "minimal") +ON_OFF = {"on": True, "off": False} +TRACK_WIDTHS = (1, 30) +MIN_WIDTH = 200 + +# The accent the classic and minimal styles give the wordmark: F1 red. One place, mirrored by the picker page. +DEFAULT_ACCENT = "#dc1220" +DEFAULT_TRACK = ("#ffffff", 6) + +# The style's values per kind of picture. classic is how each picture looked before options existed (a thumb had +# no checker and no locator); dim is the darkening behind the track, and its shape per kind keeps its proportions. +PRESETS = { + "classic": { + "race": {"show": ("wordmark", "round", "name", "subtitle", "date"), "checker": True, "locator": True, "dim": 0.43}, + "season": {"show": ("wordmark", "name", "subtitle"), "checker": True, "locator": True, "dim": 0.24}, + "session": {"show": ("wordmark", "round", "name", "subtitle", "session"), "checker": False, "locator": False, + "dim": 0.55}, + }, + "minimal": { + "race": {"show": ("name", "date"), "checker": False, "locator": False, "dim": 0.25}, + "season": {"show": ("name", "date"), "checker": False, "locator": False, "dim": 0.25}, + "session": {"show": ("name", "session"), "checker": False, "locator": False, "dim": 0.25}, + }, +} +# The dim each kind's darkening was drawn for: the shape is scaled by dim / CLASSIC_DIM[kind]. +CLASSIC_DIM = {kind: values["dim"] for kind, values in PRESETS["classic"].items()} + +OPTION_NAMES = ("style", "bg", "photo", "show", "locator", "checker", "track", "dim", "accent", "width", "format", "v") +_COLOUR = re.compile(r"^#[0-9a-fA-F]{6}$") + + +class OptionError(ValueError): + """An unknown option or value: answered 422, naming it.""" + + +@dataclass(frozen=True) +class Options: + style: str + bg: str + photo: str + show: frozenset + locator: bool + checker: bool + track: Optional[tuple[str, int]] # None: off + dim: float + accent: str + width: int + format: str + versioned: bool # the address carries the current render version (?v=) + + def canonical(self) -> str: + """The options as they are drawn, the style resolved: two addresses that draw the same picture match.""" + track = f"{self.track[0]},{self.track[1]}" if self.track else "off" + return (f"bg={self.bg};photo={self.photo};show={','.join(sorted(self.show))};" + f"locator={'on' if self.locator else 'off'};checker={'on' if self.checker else 'off'};" + f"track={track};dim={self.dim:g};accent={self.accent};width={self.width};format={self.format}") + + +def _choice(name: str, value: str, allowed: Iterable[str]) -> str: + if value not in allowed: + raise OptionError(f"unknown value {value!r} for option {name!r}; it takes {', '.join(allowed)}") + return value + + +def _colour(name: str, value: str) -> str: + if not _COLOUR.match(value): + raise OptionError(f"unknown value {value!r} for option {name!r}; it takes a colour #rrggbb") + return value.lower() + + +def parse_options(items: Iterable[tuple[str, str]], kind: str) -> Options: + """The query of a picture's address, checked: kind is race, season or session. Any option given overrides the + style's preset; an unknown option, a repeated one or an unknown value raises OptionError.""" + given: dict[str, str] = {} + for name, value in items: + if name not in OPTION_NAMES: + raise OptionError(f"unknown option {name!r}; options are {', '.join(OPTION_NAMES)}") + if name in given: + raise OptionError(f"option {name!r} given more than once") + given[name] = value + + style = _choice("style", given.get("style", "classic"), STYLES) + preset = PRESETS[style][kind] + frame_width = FRAMES[FRAME_OF[kind]][0] + + bg = given.get("bg", "satellite") + bg = _choice("bg", BG_ALIASES.get(bg, bg), BACKGROUNDS + tuple(BG_ALIASES)) + photo = _choice("photo", given.get("photo", "natural"), PHOTO_TREATMENTS) + + if "show" in given: + show = frozenset(item for item in given["show"].split(",") if item) + unknown = sorted(show - set(SHOW_ITEMS)) + if unknown: + raise OptionError(f"unknown value {unknown[0]!r} for option 'show'; it takes a comma list of " + f"{', '.join(SHOW_ITEMS)}") + else: + show = frozenset(preset["show"]) + + locator = ON_OFF[_choice("locator", given["locator"], ON_OFF)] if "locator" in given else preset["locator"] + checker = ON_OFF[_choice("checker", given["checker"], ON_OFF)] if "checker" in given else preset["checker"] + + track: Optional[tuple[str, int]] = DEFAULT_TRACK + if "track" in given: + if given["track"] == "off": + track = None + else: + colour, _, width = given["track"].partition(",") + colour = _colour("track", colour) + if width: + if not width.isdigit() or not TRACK_WIDTHS[0] <= int(width) <= TRACK_WIDTHS[1]: + raise OptionError(f"unknown value {given['track']!r} for option 'track'; it takes off or " + f"#rrggbb with an optional width {TRACK_WIDTHS[0]} to {TRACK_WIDTHS[1]}, #ffffff,6") + track = (colour, int(width)) + else: + track = (colour, DEFAULT_TRACK[1]) + + dim = preset["dim"] + if "dim" in given: + try: + dim = float(given["dim"]) + except ValueError: + dim = math.nan + if not 0 <= dim <= 1: # also refuses nan + raise OptionError(f"unknown value {given['dim']!r} for option 'dim'; it takes a number from 0 to 1") + + accent = _colour("accent", given["accent"]) if "accent" in given else DEFAULT_ACCENT + + width = frame_width + if "width" in given: + if not given["width"].isdigit() or not MIN_WIDTH <= int(given["width"]) <= frame_width: + raise OptionError(f"unknown value {given['width']!r} for option 'width'; it takes {MIN_WIDTH} up to " + f"{frame_width}") + width = int(given["width"]) + + fmt = _choice("format", given.get("format", "png"), tuple(FORMATS)) + return Options(style=style, bg=bg, photo=photo, show=show, locator=locator, checker=checker, track=track, + dim=dim, accent=accent, width=width, format=fmt, versioned=given.get("v") == RENDER_VERSION) + + +# ------------------------------------------------------------------ keys + +def trace_hash(coordinates) -> str: + """A layout's trace, as the layer keys name it: a changed trace makes a new key.""" + return hashlib.sha256(repr(coordinates).encode()).hexdigest()[:16] + + +def map_layer_key(source_key: str, trace: str, frame: str, zoom: int) -> str: + return f"map/{source_key}/{trace}-{frame}-z{zoom}-{RENDER_VERSION}" + + +def photo_layer_key(file: str, sha1: str, frame: str) -> str: + name = hashlib.sha256(file.encode()).hexdigest()[:12] # a Commons title may hold any character + return f"photo/{name}-{sha1}-{frame}-{RENDER_VERSION}" + + +def locator_layer_key(lat: float, lon: float) -> str: + return f"locator/{round(lat, 2):.2f}_{round(lon, 2):.2f}-{RENDER_VERSION}" + + +def outline_layer_key(trace: str, frame: str, zoom: int) -> str: + return f"outline/{trace}-{frame}-z{zoom}" + + +def finished_key(route: str, options: Options, layer_keys: Iterable[str]) -> str: + """A finished picture's name in the store: its route, its options and the keys of the layers it was made from.""" + made_of = "|".join(sorted(layer_keys)) + digest = hashlib.sha256(f"{RENDER_VERSION}\n{route}\n{options.canonical()}\n{made_of}".encode()).hexdigest() + return f"{digest[:40]}.{options.format}" + + +# ------------------------------------------------------------------ what clients keep + +def cache_headers(kept: bool, versioned: bool, etag: str) -> dict[str, str]: + """An address with the current render version is kept for good; any other a day, asked again with its ETag; + a picture served without its layer five minutes, with no ETag.""" + if not kept: + return {"Cache-Control": "public, max-age=300"} + if versioned: + return {"Cache-Control": "public, max-age=31536000, immutable", "ETag": etag} + return {"Cache-Control": "public, max-age=86400", "ETag": etag} + + +def etag_matches(if_none_match: str, etag: str) -> bool: + tags = [tag.strip().removeprefix("W/") for tag in (if_none_match or "").split(",")] + return etag in tags or "*" in tags + + +# ------------------------------------------------------------------ the store's cap + +def evictions(entries: dict[str, tuple[float, int]], cap: int) -> list[str]: + """The stored pictures to remove, least recently used first, until the rest fit the cap. + entries: name → (last used, size in bytes).""" + total = sum(size for _, size in entries.values()) + out = [] + for name, (_, size) in sorted(entries.items(), key=lambda item: item[1][0]): + if total <= cap: + break + out.append(name) + total -= size + return out diff --git a/poster_sources.py b/poster_sources.py new file mode 100644 index 0000000..02c30cb --- /dev/null +++ b/poster_sources.py @@ -0,0 +1,307 @@ +"""Where every poster picture comes from, under which licence, and the credit each source asks for (docs/posters.md, +Sources). Standard library only, so the merge check tests it as it is. + +The satellite chain takes, per layout, the first source that has it: the layout's picked Wikimedia Commons photo, +then the national aerial photo of the circuit's country, then EOxCloudless. The national credit lines and tile +addresses were read from each provider's own pages and confirmed against real tiles on 2026-11-27: + +- USGS: the service description of USGSImageryOnly (its copyright text is the credit; cached to level 16, 17 is a + 404); USGS-produced data are in the U.S. public domain. +- PDOK: the WMTS capabilities of luchtfotorgb (Actueel_orthoHR, EPSG:3857, column before row); PDOK asks to refer + to "het Samenwerkingsverband Beeldmateriaal en naar de CC-BY-licentie". +- IGN: the Géoplateforme WMTS (Licence Ouverte / Etalab 2.0, whose credit needs the producer and the date of the + last update). A yearly layer holds only the départements flown that year, so a frame near a border falls into a + hole; the frozen mosaic of 2021-2023 covers all of France (every French layout's frame corners answered), and its + dates never change. +- EOX: the WMTS capabilities (s2cloudless_3857 is 2016, CC BY 4.0; the newest is 2025, CC BY-NC-SA 4.0); its + levels go to 21, its own picture's detail stops at about 14 (2016) and 16 (2025). +""" +import dataclasses +import json +import logging +import re +import unicodedata +import urllib.parse +from dataclasses import dataclass +from pathlib import Path +from typing import Optional, Union + +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class MapSource: + """One tiled map source, in one year where it has years.""" + id: str # usgs, pdok, ign, eox, osm + year: Optional[Union[int, str]] # the mosaic's year or years (EOX, IGN); None for a source without years + tiles: str # the tile address, with {z}, {x} and {y} + max_zoom: int # its deepest level: a picture never asks deeper + slots: int # requests to its host at once, over every render side by side + credit: str # drawn on every picture made from it + tint: Optional[str] = None # its tiles recoloured when drawn (dark), whatever bg asked; None: as bg says + + @property + def host(self) -> str: + return urllib.parse.urlsplit(self.tiles).hostname or "" + + @property + def key(self) -> str: + """The source and its year, as a layer key names them.""" + return f"{self.id}-{self.year if self.year is not None else 'current'}" + + @property + def share(self) -> Optional[str]: + """What it asks of a picture made from it: EOX's mosaics after 2016 are NC-SA; the others only a credit.""" + return NC_SA if self.id == "eox" and self.year != EOX_FREE_YEAR else None + + +COMMONS = "commons" # the satellite chain's first link: the layout's picked Commons photo +MAP_OVERRIDE = "map" # a layout's entry {"use": "map"}: its satellite background is the dark map, not EOX + +# What a source asks of a picture made from it, beyond its credit: share-alike (a CC BY-SA photo) or +# non-commercial share-alike (EOX's mosaics after 2016). The two can never meet on one picture. +BY_SA, NC_SA = "by-sa", "nc-sa" +PICTURE_LICENCES = { # what a source asks → the picture's licence, its address, and when it applies + BY_SA: ("CC BY-SA 4.0", "https://creativecommons.org/licenses/by-sa/4.0/", "made from a CC BY-SA photo"), + NC_SA: ("CC BY-NC-SA 4.0", "https://creativecommons.org/licenses/by-nc-sa/4.0/", + "made from EOX's mosaics after 2016"), + None: ("CC BY 4.0", "https://creativecommons.org/licenses/by/4.0/", "otherwise"), +} + +# EOxCloudless: the 2016 mosaic is CC BY 4.0, later ones CC BY-NC-SA 4.0. +EOX_FREE_YEAR = 2016 +EOX_NEWEST = 2025 +# The one switch for EOX's year. True: a layout first raced in or before 2016 takes the 2016 mosaic (its track is on +# it, and the picture stays free of share-alike), a later one the newest. False: every layout takes the newest +# mosaic. A picture's licence (X-License) follows from the mosaic it was made from. The operator chose the newest +# (2026-11-27): the 2016 mosaic is too soft at a circuit's zoom. +EOX_2016_FOR_EARLY_LAYOUTS = False + +# IGN's frozen mosaic of the photos flown in 2021 to 2023: France is flown every three years, so it covers all of +# it, and its dates are the credit's. +IGN_PERIOD = "2021-2023" + +EOX_CREDIT = ("EOxCloudless https://cloudless.eox.at by EOX IT Services GmbH " + "(Contains modified Copernicus Sentinel data {year})") +IGN_CREDIT = "© IGN – BD ORTHO, {years}" +OSM_CREDIT = "© OpenStreetMap contributors" +COMMONS_CREDIT = "Photo: {author}, {licence}, via Wikimedia Commons" +JOLPICA_CREDIT = "Race schedules: Jolpica F1 API (https://github.com/jolpica/jolpica-f1), CC BY-NC-SA 4.0" + + +def usgs() -> MapSource: + return MapSource("usgs", None, + "https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}", + max_zoom=16, slots=4, credit="Imagery: USDA, USGS The National Map: Orthoimagery") + + +def pdok() -> MapSource: + return MapSource("pdok", None, + "https://service.pdok.nl/hwh/luchtfotorgb/wmts/v1_0/Actueel_orthoHR/EPSG:3857/{z}/{x}/{y}.jpeg", + max_zoom=21, slots=4, credit="Luchtfoto: PDOK / Samenwerkingsverband Beeldmateriaal, CC BY 4.0") + + +def ign() -> MapSource: + # Two requests at once: at four, IGN reset connections. + return MapSource("ign", IGN_PERIOD, + "https://data.geopf.fr/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0" + f"&LAYER=ORTHOIMAGERY.ORTHOPHOTOS{IGN_PERIOD}&STYLE=normal&TILEMATRIXSET=PM_6_19" + "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=image/jpeg", + max_zoom=19, slots=2, credit=IGN_CREDIT.format(years=IGN_PERIOD.replace("-", "–"))) + + +def eox(year: int) -> MapSource: + layer = "s2cloudless_3857" if year == EOX_FREE_YEAR else f"s2cloudless-{year}_3857" + return MapSource("eox", year, + f"https://tiles.maps.eox.at/wmts/1.0.0/{layer}/default/g/{{z}}/{{y}}/{{x}}.jpg", + max_zoom=21, slots=4, credit=EOX_CREDIT.format(year=year)) + + +def osm() -> MapSource: + # OpenStreetMap's tile usage policy: at most two connections, only when a picture is asked for, never ahead. + return MapSource("osm", None, "https://tile.openstreetmap.org/{z}/{x}/{y}.png", + max_zoom=19, slots=2, credit=OSM_CREDIT) + + +def layout_first_year(layout_slug: str) -> int: + """A layout is named by its years: "2004-", "1950-1970" or "2010".""" + return int(layout_slug.split("-")[0]) + + +def dark_map() -> MapSource: + """OpenStreetMap drawn dark, credited as OpenStreetMap: a layout's satellite background where the operator set + {"use": "map"}.""" + return dataclasses.replace(osm(), tint="dark") + + +def satellite_source(country_slug: str, circuit_slug: str, layout_slug: str, + entry: Optional[dict] = None) -> Union[str, MapSource]: + """The satellite chain: the layout's picked Commons photo (COMMONS), else the national aerial photo of the + circuit's country, else the chain's last link (satellite_fallback). The layout's entry in circuits/photos.json + is a photo, or the override {"use": "map"}, which a photo or a national source still wins over (they are + sharper).""" + if is_photo(entry): + return COMMONS + if country_slug == "united-states": + return usgs() + if country_slug == "netherlands": + return pdok() + if country_slug == "france": + return ign() + if entry and entry.get("use") == MAP_OVERRIDE: + return dark_map() + return satellite_fallback(layout_slug) + + +def satellite_fallback(layout_slug: str) -> MapSource: + """The satellite chain's last link, for a layout no picked photo and no national aerial photo has: EOxCloudless. + The one place that decides it.""" + early = EOX_2016_FOR_EARLY_LAYOUTS and layout_first_year(layout_slug) <= EOX_FREE_YEAR + return eox(EOX_FREE_YEAR if early else EOX_NEWEST) + + +# ------------------------------------------------------------------ picks + +_FREE_LICENCE = re.compile(r"^(CC0|PUBLIC DOMAIN|PD\b|PD-|CC[- ]BY(-SA)?[- ]\d)", re.IGNORECASE) + + +def is_free_licence(licence: str) -> bool: + """Only CC0, public domain, CC BY and CC BY-SA: never NC or ND, never a photo without a free licence.""" + return bool(_FREE_LICENCE.match((licence or "").strip())) + + +def entry_problem(entry) -> Optional[str]: + """Why a picks file's entry is refused, or None: an entry is a photo (file, licence, author, credit, date) under + a free licence, or the override {"use": "map"}, never both.""" + if not isinstance(entry, dict): + return "not an object" + if "use" in entry: + if entry["use"] != MAP_OVERRIDE: + return f"unknown use {entry['use']!r}; it takes {MAP_OVERRIDE!r}" + return "a file and a use at once" if "file" in entry else None + if not entry.get("file"): + return "neither a file nor a use" + if not is_free_licence(entry.get("licence", "")): + return f"licence {entry.get('licence')!r} is not CC0, public domain, CC BY or CC BY-SA" + return None + + +def is_photo(entry: Optional[dict]) -> bool: + return bool(entry and entry.get("file")) + + +def read_picks(path: Path) -> dict[str, dict]: + """A picks file (circuits/photos.json, seasons/photos.json): key → its entry. Keys starting with "$" are notes; + an entry entry_problem refuses is left out and logged.""" + try: + data = json.loads(path.read_text(encoding="utf-8")) + except FileNotFoundError: + return {} + picks = {} + for key, entry in data.items(): + if key.startswith("$"): + continue + problem = entry_problem(entry) + if problem: + logger.error(f"{path}: the entry {key!r} is refused: {problem}") + continue + picks[key] = entry + return picks + + +def pick_credit(pick: dict) -> str: + return pick.get("credit") or COMMONS_CREDIT.format(author=pick.get("author", "unknown"), + licence=pick.get("licence", "")) + + +def pick_share(pick: dict) -> Optional[str]: + """A CC BY-SA photo (2.0, 3.0, 3.0 DE, 4.0: each allows a later version) makes its picture CC BY-SA 4.0.""" + return BY_SA if re.match(r"^CC[- ]BY-SA\b", (pick.get("licence") or "").strip(), re.IGNORECASE) else None + + +class LicenceClash(ValueError): + """A picture that would be made from a CC BY-SA photo and an NC-SA mosaic: refused, never drawn.""" + + +def picture_licence(shares: list[Optional[str]]) -> str: + """A picture's licence follows its sources: CC BY-SA 4.0 when made from a CC BY-SA photo, CC BY-NC-SA 4.0 when + made from an EOX mosaic after 2016, CC BY 4.0 otherwise (CC0, public domain or CC BY photos, the 2016 mosaic, + USGS, PDOK, IGN, OpenStreetMap). Jolpica's names and dates are single facts and set no licence.""" + asked = set(s for s in shares if s) + if asked == {BY_SA, NC_SA}: + raise LicenceClash("a CC BY-SA photo and an NC-SA mosaic cannot make one picture") + return PICTURE_LICENCES[asked.pop() if asked else None][0] + + +# ------------------------------------------------------------------ credits + +def credit_line(credits: list[str]) -> str: + """Every source a picture was made from, each once, in order, joined with " · ".""" + return " · ".join(dict.fromkeys(c for c in credits if c)) + + +def ascii_header(text: str) -> str: + """The credit line as an ASCII header value (many clients read headers as Latin-1): "©" as "(c)", the " · " + between sources as " | ", accents folded, en and em dashes as "-", any other character outside ASCII as "?". + The drawn line and /licences keep the exact text.""" + text = text.replace("©", "(c)").replace(" · ", " | ") + folded = "".join(c for c in unicodedata.normalize("NFKD", text) if not unicodedata.combining(c)) + folded = folded.replace("–", "-").replace("—", "-") + return "".join(c if ord(c) < 128 else "?" for c in folded) + + +def licences() -> dict: + """/licences: every source, its licence, its credit and its terms' address.""" + by_licence = PICTURE_LICENCES[None][0] + picture_licence_of = {"commons": f"{PICTURE_LICENCES[BY_SA][0]} from a CC BY-SA photo, else {by_licence}", + "eox": PICTURE_LICENCES[NC_SA][0], "jolpica": "does not set a picture's licence", + "traces": "does not set a picture's licence"} + + def source(id, name, used_for, licence, licence_url, credit, terms): + return {"id": id, "name": name, "used_for": used_for, "licence": licence, "licence_url": licence_url, + "credit": credit, "terms": terms, "picture_licence": picture_licence_of.get(id, by_licence)} + nc_sa, by = PICTURE_LICENCES[NC_SA][1], PICTURE_LICENCES[None][1] + return { + "pictures": { + "rule": "A picture's licence follows its sources, and is sent with it as X-License: CC BY-SA 4.0 when it " + "is made from a CC BY-SA photo; CC BY-NC-SA 4.0 when it is made from an EOxCloudless mosaic after " + "2016; CC BY 4.0 otherwise. The satellite chain takes one source, so the first two never meet.", + "licences": [{"licence": name, "licence_url": url, "when": when} + for name, url, when in PICTURE_LICENCES.values()], + }, + "tracks": {"licence": "MIT", "licence_url": "https://opensource.org/license/mit"}, + "sources": [ + source("commons", "Wikimedia Commons aerial and car photos, picked per layout and per season", + "bg=satellite where a photo is picked for the layout; season posters", + "per file: CC0, public domain, CC BY or CC BY-SA only", + "https://commons.wikimedia.org/wiki/Commons:Licensing", + COMMONS_CREDIT.format(author="", licence=""), + "https://commons.wikimedia.org/wiki/Commons:Reusing_content_outside_Wikimedia"), + source("usgs", "USGS The National Map: Orthoimagery (NAIP)", "bg=satellite for circuits in the United States", + "public domain", "https://www.usgs.gov/information-policies-and-instructions/copyrights-and-credits", + usgs().credit, "https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer"), + source("pdok", "PDOK aerial photo (Beeldmateriaal Nederland)", "bg=satellite for circuits in the Netherlands", + "CC BY 4.0", by, pdok().credit, + "https://www.pdok.nl/-/hoge-resolutie-luchtfoto-2026-nu-beschikbaar-bij-pdok"), + source("ign", f"IGN BD ORTHO, the aerial photos of {IGN_PERIOD}", "bg=satellite for circuits in France", + "Licence Ouverte (Etalab) 2.0", "https://www.etalab.gouv.fr/licence-ouverte-open-licence/", + ign().credit, "https://cartes.gouv.fr/cgu"), + ] + ([ + source("eox-2016", "EOxCloudless 2016 (Sentinel-2, 10 m)", + "bg=satellite elsewhere, for a layout first raced in or before 2016", + "CC BY 4.0", by, eox(EOX_FREE_YEAR).credit, "https://cloudless.eox.at/documentation/license"), + ] if EOX_2016_FOR_EARLY_LAYOUTS else []) + [ + source("eox", f"EOxCloudless {EOX_NEWEST} (Sentinel-2, 10 m)", + "bg=satellite elsewhere, for a layout first raced after 2016" if EOX_2016_FOR_EARLY_LAYOUTS + else "bg=satellite elsewhere", + "CC BY-NC-SA 4.0", nc_sa, eox(EOX_NEWEST).credit, "https://cloudless.eox.at/documentation/license"), + source("osm", "OpenStreetMap standard tiles", "bg=osm, bg=dark and bg=light (recoloured), the world locator", + "ODbL (data), tile usage policy", "https://www.openstreetmap.org/copyright", OSM_CREDIT, + "https://operations.osmfoundation.org/policies/tiles/"), + source("jolpica", "Jolpica F1 API", "race schedules: names, rounds, dates", "CC BY-NC-SA 4.0", nc_sa, + JOLPICA_CREDIT, "https://github.com/jolpica/jolpica-f1"), + source("traces", "The circuits' GPS traces and layouts", "track outlines, track files", "MIT", + "https://opensource.org/license/mit", "Circuit traces and layouts: f1-circuits, MIT License", + "https://github.com/bacinger/f1-circuits"), + ], + } diff --git a/posters_service.py b/posters_service.py index 914ae40..ae93907 100644 --- a/posters_service.py +++ b/posters_service.py @@ -1,109 +1,49 @@ -"""Plex-style F1 race + season poster rendering. +"""Plex-style F1 race posters, season posters and session thumbnails (docs/posters.md). -Produces 1000x1500 PNGs (Plex's recommended TV-poster ratio) by compositing: -- Top + bottom checker-flag strips -- "FORMULA 1" wordmark (red) -- Round / year ribbon -- Grand Prix name (bold, large) -- Rasterised track outline (white) for race posters -- Race date +What needs the network is a kept layer, fetched once and kept for good in `layers/`: the map picture of one source +around a layout, a picked Wikimedia Commons photo cropped to the frame, the world locator, and the layout's trace +projected for the frame (the track outline points). What a caller chooses (texts, colours, size, format) is drawn +on every request from those layers, and the finished picture is kept in `posters/`, at most 2 GB, the least +recently used going first. A layer is kept only whole; a picture whose layer did not arrive is served without it +and kept nowhere. -Output is cached under cache/posters/ keyed by (season, round, layout_slug) -so cold paths stay cheap. +Which source, which options and which keys: poster_sources.py and poster_options.py (standard library only). """ -import hashlib import io import json import logging import math import os import threading +import time import urllib.parse import urllib.request from concurrent.futures import ThreadPoolExecutor -from enum import Enum +from dataclasses import dataclass from pathlib import Path -from typing import Optional +from typing import Callable, Optional -import cairosvg -from PIL import Image, ImageDraw, ImageFont +from PIL import Image, ImageDraw, ImageFont, ImageOps +import poster_options as po +import poster_sources as ps +from app_info import PUBLIC_BASE_URL, USER_AGENT from circuits_service import CircuitService from ergast_service import ErgastService -# Where season background images live. Hosted by the dilbert files-api module — -# one landscape JPG per F1 season (key for the season-card grid in Dilbert's UI). -SEASON_BG_URL_TEMPLATE = "https://files-api.novox.be/dilbert/sports/formula1/cars/{season}.jpg" - - -class BackgroundStyle(str, Enum): - """Selectable backdrop for race posters.""" - AERIAL = "aerial" # Esri World Imagery satellite tiles (default) - OSM = "osm" # OpenStreetMap Carto street-map tiles - DARK = "dark" # Esri Dark Gray Canvas — minimalist black-and-grey map - LIGHT = "light" # Esri Light Gray Canvas — minimalist light/grey map - NONE = "none" # Plain black, no map fetch — fast fallback - - -# XYZ tile templates. None require API keys at our volume. CARTO's basemaps do since 2026: they -# answer every tile with an "API KEY REQUIRED" picture, so dark and light are Esri's grey canvases. -# max_zoom is the deepest level a provider draws; deeper, Esri's canvases answer a "Map data not yet -# available" picture, so a poster never asks deeper than its provider's max_zoom. -TILE_PROVIDERS = { - BackgroundStyle.AERIAL: { - "url": "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", - "attribution": "Esri, Maxar, Earthstar Geographics", - "max_zoom": 19, - "concurrency": 6, - }, - BackgroundStyle.OSM: { - "url": "https://tile.openstreetmap.org/{z}/{x}/{y}.png", - "attribution": "© OpenStreetMap contributors", - "max_zoom": 19, - "concurrency": 2, # OpenStreetMap's tile usage policy: at most two connections - }, - BackgroundStyle.DARK: { - "url": "https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Dark_Gray_Base/MapServer/tile/{z}/{y}/{x}", - "attribution": "Esri, HERE, Garmin, © OpenStreetMap contributors", - "max_zoom": 16, - "concurrency": 6, - }, - BackgroundStyle.LIGHT: { - "url": "https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}", - "attribution": "Esri, HERE, Garmin, © OpenStreetMap contributors", - "max_zoom": 16, - "concurrency": 6, - }, -} - -# At most this many requests to one tile host at once, over every render the service runs side by side: -# the satellite and both grey canvases are one Esri host, and share its slots. -_TILE_HOST_SLOTS: dict[str, threading.BoundedSemaphore] = {} -for _provider in TILE_PROVIDERS.values(): - _TILE_HOST_SLOTS.setdefault(urllib.parse.urlsplit(_provider["url"]).hostname, - threading.BoundedSemaphore(_provider["concurrency"])) -TILE_SLOTS = {style: _TILE_HOST_SLOTS[urllib.parse.urlsplit(provider["url"]).hostname] - for style, provider in TILE_PROVIDERS.items()} - -# Part of every race poster's file name in the cache: raised when what a poster looks like changes, -# so posters rendered before (such as over CARTO's "API KEY REQUIRED" tiles) are rendered again. -POSTER_RENDER = "r2" - -# The address this service is reached at, which the Kometa metadata links every poster to. The -# mesh writes it from the name the route is served under (F1_CIRCUITS_BASE_URL); the fallback is -# the address HAL served it at, so a deployment that sets nothing behaves as before. -PUBLIC_BASE_URL = os.environ.get("F1_CIRCUITS_BASE_URL", "https://f1-circuits.zurag.be").rstrip("/") - -# Polite UA — both providers expect one and Esri throttles aggressively without it. -TILE_USER_AGENT = f"f1-circuits-posters/1.0 (+{PUBLIC_BASE_URL})" - logger = logging.getLogger(__name__) -POSTER_W, POSTER_H = 1000, 1500 -THUMB_W, THUMB_H = 1920, 1080 # Plex episode-thumb ratio +LAYERS_DIR = Path("layers") # module.json: class rebuildable (backed up; fetched again if lost) +POSTERS_DIR = Path("posters") # module.json: class cache +POSTERS_CAP = 2 * 1024 ** 3 # bytes +CIRCUIT_PICKS = Path("circuits/photos.json") +SEASON_PICKS = Path("seasons/photos.json") + +POSTER_W, POSTER_H = po.FRAMES["poster"] +THUMB_W, THUMB_H = po.FRAMES["thumb"] # Plex episode-thumb ratio BG = (10, 10, 12) -RED = (220, 18, 32) # F1 red +RED = (220, 18, 32) # F1 red: the thumb's bar and the locator's marker WHITE = (245, 245, 245) GREY = (160, 160, 170) @@ -144,43 +84,339 @@ SESSION_LABEL_BY_SLUG = {slug: label for d in (_SESSION_STD, _SESSION_SPRINT) fo CHECKER_H = 60 CHECKER_SQ = 30 -# Vertical pixel where we want the circuit's geographic centre to land. Picked so -# the track ends up visually centred *in the visible aerial band* — between the -# heading block at the top and the date strip at the bottom, not in the full -# 1000x1500 poster middle (which would look high once the heading dim is over it). -GEO_CENTER_Y = 935 +# Vertical pixel of a frame where the circuit's geographic centre lands: on a poster the middle of the band +# between the heading and the date strip; a thumb centres it. +GEO_CENTER_Y = {"poster": 935, "thumb": THUMB_H // 2} -# Slim-image-friendly font candidates. The Dockerfile installs fonts-dejavu-core -# so DejaVuSans-Bold is always present in production; the others cover common -# local-dev paths (Arch Linux ships Liberation Sans at /usr/share/fonts/liberation). +# The track's zoom fits its bbox into ~85% of a poster's visible map band; a thumb shows the same place at the +# same zoom. +_BBOX_TARGET_W = int(POSTER_W * 0.85) +_BBOX_TARGET_H = int((1300 - 540) * 0.85) +DEFAULT_ZOOM = 15 + +# The locator: OpenStreetMap at zoom 5, a 700 px window around the circuit, drawn small with a marker. +LOCATOR_ZOOM, LOCATOR_WINDOW = 5, 700 +LOCATOR_PLACE = {"poster": (140, 25, CHECKER_H + 25), "thumb": (220, 60, 60)} # size, right margin, top +INSET = {"poster": (220, 25, 1300), "thumb": (300, 60, THUMB_H - 60)} # size, right margin, bottom + +# Slim-image-friendly font candidates. The Dockerfile installs ttf-liberation; the others cover local paths. FONT_CANDIDATES = [ + "/usr/share/fonts/liberation/LiberationSans-Bold.ttf", # Arch, Alpine + "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", # Debian/Ubuntu "/usr/share/fonts/dejavu/DejaVuSans-Bold.ttf", # Fedora - "/usr/share/fonts/liberation/LiberationSans-Bold.ttf", # Arch - "/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf", ] +CREDIT_FONT_CANDIDATES = [ + "/usr/share/fonts/liberation/LiberationSans-Regular.ttf", + "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", + "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", + "/usr/share/fonts/dejavu/DejaVuSans.ttf", +] +CREDIT_MIN_PX = 12 # the credit line's height on the picture as served, after `width` scales it + + +def _hex(colour: str) -> tuple[int, int, int]: + return int(colour[1:3], 16), int(colour[3:5], 16), int(colour[5:7], 16) + + +def latlon_to_pixel(lat: float, lon: float, zoom: int) -> tuple[float, float]: + """Web-Mercator pixel coordinates (slippy-map convention, 256-px tiles).""" + n = 2.0 ** zoom * 256 + x = (lon + 180.0) / 360.0 * n + lat_rad = math.radians(lat) + y = (1.0 - math.log(math.tan(lat_rad) + 1.0 / math.cos(lat_rad)) / math.pi) / 2.0 * n + return x, y + + +def zoom_from_bbox(coords: list, max_zoom: int = 17, min_zoom: int = 10) -> int: + """The most zoomed-in level at which the track's bbox still fits a poster's visible map band.""" + lons = [float(c[0]) for c in coords] + lats = [float(c[1]) for c in coords] + for zoom in range(max_zoom, min_zoom - 1, -1): + x_lo, y_hi = latlon_to_pixel(min(lats), min(lons), zoom) + x_hi, y_lo = latlon_to_pixel(max(lats), max(lons), zoom) + if (x_hi - x_lo) <= _BBOX_TARGET_W and (y_hi - y_lo) <= _BBOX_TARGET_H: + return zoom + return min_zoom + + +def frame_origin(lat: float, lon: float, zoom: int, frame: str) -> tuple[int, int]: + """The world pixel at a frame's top left, the circuit's centre landing where the frame wants it.""" + cpx, cpy = latlon_to_pixel(lat, lon, zoom) + return int(cpx - po.FRAMES[frame][0] / 2), int(cpy - GEO_CENTER_Y[frame]) + + +@dataclass +class Geo: + """Where a layout lies: its centre, its zoom, and its trace (None when the trace is empty or a point, and the + circuit's location is used instead).""" + lat: float + lon: float + zoom: int + trace: Optional[list] + trace_hash: str + + +# ---------------------------------------------------------------------------------------------- stores + +def _write_whole(path: Path, data: bytes) -> None: + """Written to a partial file, then renamed: two requests may make the same file side by side.""" + path.parent.mkdir(parents=True, exist_ok=True) + partial = path.with_name(f"{path.name}.{threading.get_ident()}.partial") + partial.write_bytes(data) + partial.replace(path) + + +class LayerStore: + """The kept layers, for good. A layer is written whole or not at all.""" + + def __init__(self, root: Path): + self.root = root + + def path(self, key: str, ext: str) -> Path: + return self.root / f"{key}.{ext}" + + def read_image(self, key: str, ext: str) -> Optional[Image.Image]: + path = self.path(key, ext) + try: + with Image.open(path) as img: + return img.convert("RGB") + except FileNotFoundError: + return None + except Exception as e: + logger.warning(f"Kept layer {path} is unreadable, made again: {e}") + return None + + def write_image(self, key: str, ext: str, img: Image.Image) -> None: + buf = io.BytesIO() + if ext == "jpg": + img.save(buf, "JPEG", quality=92) + else: + img.save(buf, "PNG", optimize=True) + _write_whole(self.path(key, ext), buf.getvalue()) + + def read_json(self, key: str): + try: + return json.loads(self.path(key, "json").read_text()) + except (FileNotFoundError, ValueError): + return None + + def write_json(self, key: str, value) -> None: + _write_whole(self.path(key, "json"), json.dumps(value, separators=(",", ":")).encode()) + + +class PosterStore: + """Finished pictures under their key, at most `cap` bytes: the least recently used go first when it is full.""" + + def __init__(self, root: Path, cap: int = POSTERS_CAP): + self.root, self.cap = root, cap + self.root.mkdir(parents=True, exist_ok=True) + self._lock = threading.Lock() + self._entries: dict[str, tuple[float, int]] = {} # name → (last used, size) + for path in self.root.iterdir(): + if path.name.endswith(".partial"): + path.unlink(missing_ok=True) + elif path.is_file(): + stat = path.stat() + self._entries[path.name] = (stat.st_mtime, stat.st_size) + + def get(self, name: str) -> Optional[bytes]: + path = self.root / name + try: + data = path.read_bytes() + except FileNotFoundError: + return None + now = time.time() + try: + os.utime(path, (now, now)) # its last use, kept across restarts + except OSError: + pass + with self._lock: + self._entries[name] = (now, len(data)) + return data + + def put(self, name: str, data: bytes) -> None: + _write_whole(self.root / name, data) + with self._lock: + self._entries[name] = (time.time(), len(data)) + gone = po.evictions(self._entries, self.cap) + for old in gone: + self._entries.pop(old, None) + for old in gone: + (self.root / old).unlink(missing_ok=True) + if gone: + logger.info(f"Picture store over {self.cap} bytes: removed the {len(gone)} least recently used") + + +# ---------------------------------------------------------------------------------------------- fetching + +_HOST_SLOTS: dict[str, threading.BoundedSemaphore] = {} +_HOST_SLOTS_LOCK = threading.Lock() + + +def _slots(host: str, count: int) -> threading.BoundedSemaphore: + """At most `count` requests to one host at once, over every render the service runs side by side.""" + with _HOST_SLOTS_LOCK: + return _HOST_SLOTS.setdefault(host, threading.BoundedSemaphore(count)) + + +def _get(url: str, timeout: float = 15) -> bytes: + req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) + with urllib.request.urlopen(req, timeout=timeout) as resp: + return resp.read() + + +def stitch_tiles(source: ps.MapSource, zoom: int, left: int, top: int, width: int, height: int, + wrap_x: bool = False) -> Optional[Image.Image]: + """The window [left, left+width) x [top, top+height) of a source at a zoom, from its tiles fetched in parallel. + + None unless the map is whole: when a tile did not come, or when every tile came back the same picture (a + provider's placeholder answered with a 200).""" + tx_lo, ty_lo = left // 256, top // 256 + tx_hi, ty_hi = (left + width + 255) // 256, (top + height + 255) // 256 + wanted = [(tx, ty) for tx in range(tx_lo, tx_hi) for ty in range(ty_lo, ty_hi)] + slots = _slots(source.host, source.slots) + + def tile_body(tx: int, ty: int) -> Optional[bytes]: + if not 0 <= ty < 2 ** zoom: + return None + x = tx % (2 ** zoom) if wrap_x else tx + try: + with slots: + return _get(source.tiles.format(z=zoom, x=x, y=ty)) + except Exception as e: + logger.warning(f"Tile fetch failed {source.key} z={zoom} x={x} y={ty}: {e}") + return None + + started = time.monotonic() + logger.info(f"Fetching {len(wanted)} {source.key} tiles at z={zoom} from {source.host}") + with ThreadPoolExecutor(max_workers=source.slots) as pool: + bodies = list(pool.map(lambda t: tile_body(*t), wanted)) + if len(bodies) > 1 and bodies[0] and all(b == bodies[0] for b in bodies): + logger.error(f"Every {source.key} tile at z={zoom} is the same picture: the provider answers a placeholder " + f"({source.host}), no map drawn") + return None + canvas = Image.new("RGB", ((tx_hi - tx_lo) * 256, (ty_hi - ty_lo) * 256), BG) + missing = 0 + for (tx, ty), body in zip(wanted, bodies): + try: + tile = Image.open(io.BytesIO(body)).convert("RGB") + except Exception: + missing += 1 + continue + canvas.paste(tile, ((tx - tx_lo) * 256, (ty - ty_lo) * 256)) + if missing: + logger.warning(f"{missing} of {len(wanted)} {source.key} tiles at z={zoom} did not come: no map drawn") + return None + logger.info(f"Fetched {len(wanted)} {source.key} tiles in {time.monotonic() - started:.1f}s") + ox, oy = left - tx_lo * 256, top - ty_lo * 256 + return canvas.crop((ox, oy, ox + width, oy + height)) + + +class Commons: + """Wikimedia Commons: one API request at a time, at most five a second; at most two downloads at once.""" + API = "https://commons.wikimedia.org/w/api.php" + WIDTH = 3840 # a thumbnail step wide enough to cover a portrait poster from a landscape photo + + def __init__(self): + self._api_lock = threading.Lock() + self._last_api = 0.0 + self._downloads = threading.BoundedSemaphore(2) + self._info: dict[str, dict] = {} # file → its address and SHA-1, asked once per run + + def info(self, file: str) -> Optional[dict]: + if file in self._info: + return self._info[file] + query = urllib.parse.urlencode({"action": "query", "format": "json", "formatversion": "2", + "prop": "imageinfo", "iiprop": "url|sha1|size", + "iiurlwidth": str(self.WIDTH), "titles": f"File:{file}"}) + with self._api_lock: + wait = self._last_api + 0.2 - time.monotonic() + if wait > 0: + time.sleep(wait) + self._last_api = time.monotonic() + try: + page = json.loads(_get(f"{self.API}?{query}", timeout=20))["query"]["pages"][0] + info = page["imageinfo"][0] + except Exception as e: + logger.warning(f"Commons gave no file information for {file!r}: {e}") + return None + found = {"sha1": info["sha1"], "url": info.get("thumburl") or info["url"]} + self._info[file] = found + return found + + def download(self, url: str) -> Optional[bytes]: + try: + with self._downloads: + return _get(url, timeout=60) + except Exception as e: + logger.warning(f"Commons download failed {url}: {e}") + return None + + +def recolour(img: Image.Image, bg: str) -> Image.Image: + """OpenStreetMap's standard tiles, recoloured for bg=dark and bg=light (and the dark locator).""" + grey = img.convert("L") + if bg == "dark": + inverted = ImageOps.invert(grey).point(lambda v: round(255 * (v / 255) ** 0.6)) # lifts coasts and labels + return ImageOps.colorize(inverted, black=(18, 19, 23), white=(170, 175, 185)) + if bg == "light": + return ImageOps.colorize(grey, black=(92, 94, 100), white=(236, 237, 240)) + return img + + +def cover(img: Image.Image, size: tuple[int, int]) -> Image.Image: + """Scale a picture so it covers the frame, then crop its middle.""" + w, h = size + scale = max(w / img.width, h / img.height) + img = img.resize((max(w, round(img.width * scale)), max(h, round(img.height * scale))), Image.LANCZOS) + left, top = (img.width - w) // 2, (img.height - h) // 2 + return img.crop((left, top, left + w, top + h)) + + +# ---------------------------------------------------------------------------------------------- the service + +@dataclass +class Rendered: + data: bytes + kept: bool # every layer it needs arrived: stored, and clients may keep it + credit: str # the credit line drawn on it + licence: str # its licence, which follows its sources (poster_sources.picture_licence) + name: str # its name in the picture store, which its ETag is made from + media_type: str + + +@dataclass +class Layer: + """One layer a picture is made from: its key, its credit, what its source asks of the picture (share-alike or + not), and how to get it (from the store, or made now).""" + key: str + credit: str + share: Optional[str] + get: Callable[[], Optional[Image.Image]] class PostersService: - def __init__(self, circuits: CircuitService, ergast: ErgastService): + def __init__(self, circuits: CircuitService, ergast: ErgastService, + layers_dir: Path = LAYERS_DIR, posters_dir: Path = POSTERS_DIR): self.circuits = circuits self.ergast = ergast self.font_path = next((p for p in FONT_CANDIDATES if Path(p).exists()), None) + self.credit_font_path = next((p for p in CREDIT_FONT_CANDIDATES if Path(p).exists()), self.font_path) if not self.font_path: logger.warning("No bundled font found — poster text will use PIL's default bitmap font") - self.cache_dir = Path("cache/posters") - self.cache_dir.mkdir(parents=True, exist_ok=True) - # Pre-tuned zooms per circuit, keyed by the ASCII-slugified name in f1-locations.json and looked up - # by our circuit slug: they meet for ASCII names only. Unread today: every layout has a GeoJSON - # trace, and the image does not copy f1-locations.json. - # Falls back to DEFAULT_ZOOM when not found. + self.layers = LayerStore(layers_dir) + self.store = PosterStore(posters_dir) + self.commons = Commons() + self._layer_locks: dict[str, threading.Lock] = {} + self._layer_locks_guard = threading.Lock() + self._picks: dict[Path, tuple[float, dict]] = {} + # Pre-tuned zooms per circuit, keyed by the ASCII-slugified name in f1-locations.json and looked up by our + # circuit slug; read only when a layout has no trace. Falls back to DEFAULT_ZOOM when not found. self._zoom_by_circuit = self._load_zoom_lookup() - DEFAULT_ZOOM = 15 - @staticmethod def _load_zoom_lookup() -> dict: - """Index f1-locations.json by slugified circuit name for fast zoom lookup.""" from ergast_service import slugify path = Path("f1-locations.json") if not path.exists(): @@ -192,529 +428,455 @@ class PostersService: return {} return {slugify(entry["name"]): entry for entry in data if "name" in entry} - # ------------------------------------------------------------------ utils + # ------------------------------------------------------------------ inputs - def _font(self, size: int) -> ImageFont.FreeTypeFont: - if self.font_path: - return ImageFont.truetype(self.font_path, size) - return ImageFont.load_default() + def picks(self, path: Path) -> dict[str, dict]: + """A picks file, read again when it changed.""" + try: + mtime = path.stat().st_mtime + except FileNotFoundError: + return {} + kept = self._picks.get(path) + if not kept or kept[0] != mtime: + try: + kept = (mtime, ps.read_picks(path)) + except (OSError, ValueError) as e: + logger.error(f"Could not read the picks in {path}: {e}") + kept = (mtime, {}) + self._picks[path] = kept + return kept[1] - def _centered(self, draw: ImageDraw.ImageDraw, text: str, y: int, size: int, fill=WHITE) -> int: - """Draw text centered horizontally; returns the drawn height.""" + def _race(self, grand_prix_name: str, season: int) -> Optional[dict]: + races = self.ergast._fetch_season_schedule(season) + return next((r for r in races if r["raceName"] == grand_prix_name), None) + + def _geo(self, race: dict, layout) -> Optional[Geo]: + """The layout's centre and zoom from its trace; a layout whose trace is empty or a point falls back to the + circuit's location (Jolpica's, with f1-locations.json's zoom).""" + geometry = None + try: + layout.load_geo_json_data() + geometry = layout._geo_data.features[0].geometry if layout._geo_data else None + except Exception as e: + logger.warning(f"Trace of {layout.slug} unreadable: {e}") + coords = geometry.coordinates if geometry is not None and geometry.type == "LineString" else None + if coords and len(coords) >= 2: + lons = [float(c[0]) for c in coords] + lats = [float(c[1]) for c in coords] + return Geo((min(lats) + max(lats)) / 2, (min(lons) + max(lons)) / 2, zoom_from_bbox(coords), coords, + po.trace_hash(coords)) + loc = race.get("Circuit", {}).get("Location", {}) + if "lat" in loc and "long" in loc: + lat, lon = float(loc["lat"]), float(loc["long"]) + elif geometry is not None and geometry.type == "Point": + lon, lat = float(geometry.coordinates[0]), float(geometry.coordinates[1]) + else: + return None + _, _, circuit_slug = self.ergast.find_slugs_for_circuit(race.get("Circuit", {})) + entry = self._zoom_by_circuit.get(circuit_slug) + zoom = entry["zoom"] if entry and "zoom" in entry else DEFAULT_ZOOM + logger.info(f"Layout {layout.slug} of {layout.circuit.slug} has no traced line: drawn at the circuit's " + f"location, without a track") + return Geo(lat, lon, zoom, None, po.trace_hash(("location", round(lat, 5), round(lon, 5)))) + + # ------------------------------------------------------------------ layers + + def _layer_lock(self, key: str) -> threading.Lock: + with self._layer_locks_guard: + return self._layer_locks.setdefault(key, threading.Lock()) + + def _kept_or_made(self, key: str, ext: str, make) -> Optional[Image.Image]: + """A layer from the store, or made now and kept when it came whole. One maker per layer at a time.""" + img = self.layers.read_image(key, ext) + if img is not None: + logger.info(f"Layer {key}: kept, no request") + return img + with self._layer_lock(key): + img = self.layers.read_image(key, ext) + if img is not None: + return img + img = make() + if img is None: + logger.warning(f"Layer {key}: did not arrive, not kept") + return None + self.layers.write_image(key, ext, img) + logger.info(f"Layer {key}: made and kept") + return img + + def _map_layer(self, source: ps.MapSource, geo: Geo, frame: str, zoom: int) -> Layer: + key = po.map_layer_key(source.key, geo.trace_hash, frame, zoom) + w, h = po.FRAMES[frame] + + def make(): + left, top = frame_origin(geo.lat, geo.lon, zoom, frame) + return stitch_tiles(source, zoom, left, top, w, h) + return Layer(key, source.credit, source.share, + lambda: self._kept_or_made(key, "png" if source.id == "osm" else "jpg", make)) + + def _photo_layer(self, pick: dict, frame: str) -> Layer: + credit, share = ps.pick_credit(pick), ps.pick_share(pick) + info = self.commons.info(pick["file"]) + if info is None: # no key without its SHA-1: served without the photo, and asked again next time + return Layer(f"photo/{pick['file']}?", credit, share, lambda: None) + key = po.photo_layer_key(pick["file"], info["sha1"], frame) + + def make(): + body = self.commons.download(info["url"]) + if body is None: + return None + try: + img = Image.open(io.BytesIO(body)).convert("RGB") + except Exception as e: + logger.warning(f"Commons file {pick['file']!r} unreadable: {e}") + return None + return cover(img, po.FRAMES[frame]) # kept untreated: the treatment is drawn on assembly + return Layer(key, credit, share, lambda: self._kept_or_made(key, "jpg", make)) + + def _locator_layer(self, geo: Geo) -> Layer: + lat, lon = round(geo.lat, 2), round(geo.lon, 2) + key = po.locator_layer_key(lat, lon) + + def make(): + cpx, cpy = latlon_to_pixel(lat, lon, LOCATOR_ZOOM) + half = LOCATOR_WINDOW // 2 + window = stitch_tiles(ps.osm(), LOCATOR_ZOOM, int(cpx - half), int(cpy - half), + LOCATOR_WINDOW, LOCATOR_WINDOW, wrap_x=True) + return recolour(window, "dark") if window is not None else None + return Layer(key, ps.OSM_CREDIT, ps.osm().share, lambda: self._kept_or_made(key, "png", make)) + + def _outline(self, geo: Geo, frame: str, zoom: int) -> Optional[list]: + """The trace projected for the frame and zoom: kept, and made from the repository's trace when it is not.""" + if not geo or not geo.trace: + return None + key = po.outline_layer_key(geo.trace_hash, frame, zoom) + points = self.layers.read_json(key) + if points is None: + left, top = frame_origin(geo.lat, geo.lon, zoom, frame) + points = [] + for c in geo.trace: + px, py = latlon_to_pixel(float(c[1]), float(c[0]), zoom) + points.append([round(px - left, 1), round(py - top, 1)]) + self.layers.write_json(key, points) + return points + + # ------------------------------------------------------------------ drawing + + def _font(self, size: int, path: Optional[str] = None) -> ImageFont.FreeTypeFont: + path = path or self.font_path + return ImageFont.truetype(path, size) if path else ImageFont.load_default() + + def _centered(self, draw: ImageDraw.ImageDraw, text: str, y: int, size: int, fill, width: int = POSTER_W) -> None: font = self._font(size) - # Shrink-to-fit if too wide - while size > 18 and draw.textlength(text, font) > POSTER_W - 80: + while size > 18 and draw.textlength(text, font) > width - 80: # shrink to fit size -= 4 font = self._font(size) - w = draw.textlength(text, font) - draw.text(((POSTER_W - w) / 2, y), text, font=font, fill=fill) - bbox = draw.textbbox((0, 0), text, font=font) - return bbox[3] - bbox[1] - - def _checker_strip(self, draw: ImageDraw.ImageDraw, y: int, height: int = CHECKER_H, sq: int = CHECKER_SQ): - for col, x in enumerate(range(0, POSTER_W + sq, sq)): - for row, yy in enumerate(range(y, y + height, sq)): - fill = WHITE if (col + row) % 2 == 0 else BG - draw.rectangle([x, yy, x + sq, yy + sq], fill=fill) - - # ---------------------------------------------------------- map tiles + draw.text(((width - draw.textlength(text, font)) / 2, y), text, font=font, fill=fill) @staticmethod - def _latlon_to_pixel(lat: float, lon: float, zoom: int) -> tuple[float, float]: - """Standard Web-Mercator pixel coordinates (slippy-map convention, 256-px tiles).""" - n = 2.0 ** zoom * 256 - x = (lon + 180.0) / 360.0 * n - lat_rad = math.radians(lat) - y = (1.0 - math.log(math.tan(lat_rad) + 1.0 / math.cos(lat_rad)) / math.pi) / 2.0 * n - return x, y + def _checker_strip(draw: ImageDraw.ImageDraw, y: int, width: int): + for col, x in enumerate(range(0, width + CHECKER_SQ, CHECKER_SQ)): + for row, yy in enumerate(range(y, y + CHECKER_H, CHECKER_SQ)): + draw.rectangle([x, yy, x + CHECKER_SQ, yy + CHECKER_SQ], fill=WHITE if (col + row) % 2 == 0 else BG) @staticmethod - def _capped(geo: Optional[tuple[float, float, int]], style: BackgroundStyle) -> Optional[tuple[float, float, int]]: - """(lat, lon, zoom) with the zoom no deeper than the style's provider draws.""" - provider = TILE_PROVIDERS.get(style) - if not geo or not provider: - return geo - lat, lon, zoom = geo - return lat, lon, min(zoom, provider["max_zoom"]) - - def _stitch_tiles(self, style: BackgroundStyle, zoom: int, tx_lo: int, tx_hi: int, - ty_lo: int, ty_hi: int, wrap_x: bool = False) -> Optional[Image.Image]: - """Fetch the tiles [tx_lo, tx_hi) x [ty_lo, ty_hi) of a style at a zoom onto one canvas, in parallel. - - None unless the map is whole: when a tile did not come (a poster over black squares would be kept - for good), or when every tile came back the same picture: that is a provider's placeholder - (CARTO's "API KEY REQUIRED", Esri's "Map data not yet available"), answered with a 200. A poster - whose map is None is drawn without it, served for five minutes and not kept.""" - provider = TILE_PROVIDERS[style] - canvas = Image.new("RGB", ((tx_hi - tx_lo) * 256, (ty_hi - ty_lo) * 256), BG) - wanted = [(tx, ty, tx % (2 ** zoom) if wrap_x else tx) - for tx in range(tx_lo, tx_hi) for ty in range(ty_lo, ty_hi) if 0 <= ty < 2 ** zoom] - - def tile_body(x: int, y: int) -> Optional[bytes]: - url = provider["url"].format(z=zoom, x=x, y=y) - try: - with TILE_SLOTS[style]: - req = urllib.request.Request(url, headers={"User-Agent": TILE_USER_AGENT}) - with urllib.request.urlopen(req, timeout=10) as resp: - return resp.read() - except Exception as e: - logger.warning(f"Tile fetch failed {style.value} z={zoom} x={x} y={y}: {e}") - return None - - with ThreadPoolExecutor(max_workers=provider["concurrency"]) as pool: - bodies = list(pool.map(lambda t: tile_body(t[2], t[1]), wanted)) - - if len(bodies) > 1 and len({hashlib.sha256(b).digest() if b else None for b in bodies}) == 1 and bodies[0]: - logger.error(f"Every {style.value} tile at z={zoom} is the same picture: the provider answers a " - f"placeholder ({urllib.parse.urlsplit(provider['url']).hostname}), no map drawn") - return None - missing = 0 - for (tx, ty, x), body in zip(wanted, bodies): - try: - tile = Image.open(io.BytesIO(body)).convert("RGB") - except Exception as e: - if body is not None: - logger.warning(f"Tile unreadable {style.value} z={zoom} x={x} y={ty}: {e}") - missing += 1 - continue - canvas.paste(tile, ((tx - tx_lo) * 256, (ty - ty_lo) * 256)) - if missing or not wanted: - logger.warning(f"{missing} of {len(wanted)} {style.value} tiles at z={zoom} did not come: no map drawn") - return None - return canvas - - def _fetch_map_background(self, lat: float, lon: float, zoom: int, style: BackgroundStyle) -> Optional[Image.Image]: - """Stitch enough 256-px tiles around (lat, lon) to fill the full POSTER_W x POSTER_H.""" - provider = TILE_PROVIDERS.get(style) - if not provider: - return None - - # Centre pixel and the slab we need to cover. Anchor the geographic - # centre at GEO_CENTER_Y rather than POSTER_H/2 so the track lands in - # the middle of the *visible* aerial band. - cpx, cpy = self._latlon_to_pixel(lat, lon, zoom) - left, top = int(cpx - POSTER_W / 2), int(cpy - GEO_CENTER_Y) - tile_x_lo, tile_y_lo = left // 256, top // 256 - tile_x_hi = (left + POSTER_W + 255) // 256 - tile_y_hi = (top + POSTER_H + 255) // 256 - - canvas = self._stitch_tiles(style, zoom, tile_x_lo, tile_x_hi, tile_y_lo, tile_y_hi) - if canvas is None: - return None - - ox = left - tile_x_lo * 256 - oy = top - tile_y_lo * 256 - return canvas.crop((ox, oy, ox + POSTER_W, oy + POSTER_H)) - - def _draw_track_projected( - self, - img: Image.Image, - coords: list, - lat0: float, - lon0: float, - zoom: int, - canvas_w: int = POSTER_W, - geo_center_y: int = GEO_CENTER_Y, - ) -> bool: - """Draw the track onto `img` by projecting each GeoJSON (lon, lat) point - into pixel space using the same web-mercator math as the map background. - This guarantees the white outline overlays the actual circuit in the - underlying aerial / OSM tiles. - - canvas_w / geo_center_y must match the dimensions/offset used to fetch - the map background so the polyline aligns with the actual track in the - rendered tiles. Defaults match the race poster; pass THUMB_W / THUMB_H/2 - for landscape session thumbs. - - Returns True on success, False if there's nothing usable to draw.""" - if not coords: - return False - - cpx, cpy = self._latlon_to_pixel(lat0, lon0, zoom) - win_left = cpx - canvas_w / 2 - win_top = cpy - geo_center_y - - pts: list[tuple[float, float]] = [] - for entry in coords: - # GeoJSON LineString is [[lon, lat], ...]; tolerate (lon, lat) tuples too. - if len(entry) < 2: - continue - lon, lat = float(entry[0]), float(entry[1]) - px, py = self._latlon_to_pixel(lat, lon, zoom) - pts.append((px - win_left, py - win_top)) - - if len(pts) < 2: - return False + def _dim_overlay(kind: str, size: tuple[int, int], dim: float) -> Image.Image: + """The darkening over a map or photo: each kind keeps its shape (the poster's text bands darker than the + band behind the track, the season's gradient), scaled by dim; the classic dim draws it as it always was.""" + w, h = size + scale = dim / po.CLASSIC_DIM[kind] + if kind == "race": + base = [200 if y < 540 or y >= 1300 else 110 for y in range(h)] + elif kind == "season": + base = [220 - (y * 220 // 500) if y < 500 else min((y - 1100) * 220 // (h - 1100), 220) if y > 1100 else 60 + for y in range(h)] + else: + base = [140] * h + column = Image.new("L", (1, h)) + column.putdata([min(255, round(a * scale)) for a in base]) + overlay = Image.new("RGBA", size, (0, 0, 0, 0)) + overlay.putalpha(column.resize(size, Image.NEAREST)) + return overlay + @staticmethod + def _draw_track(img: Image.Image, points: list, track: tuple[str, int]) -> None: + colour, width = track + pts = [tuple(p) for p in points] d = ImageDraw.Draw(img) - # Subtle dark stroke under, then the bright white line, so the outline - # stays legible whether the bg is the bright Mediterranean or a dark - # grey canvas tile. - d.line(pts + [pts[0]], fill=(0, 0, 0), width=10, joint="curve") - d.line(pts + [pts[0]], fill=WHITE, width=6, joint="curve") - return True + # A dark stroke under the line keeps it legible over a bright or a dark background. + d.line(pts + [pts[0]], fill=(0, 0, 0), width=width + 4, joint="curve") + d.line(pts + [pts[0]], fill=_hex(colour), width=width, joint="curve") - def _render_world_locator(self, lat: float, lon: float, size: int = 220) -> Optional[Image.Image]: - """A small picture-in-picture map showing where on Earth this race is. - Uses the dark background's tiles (Esri Dark Gray Canvas) at zoom 5 — tight enough that the host country - fills most of the inset, while neighbours and coastlines still give the - viewer a "here's the region" anchor. A marker (red dot + white ring) - is drawn over the exact spot.""" - zoom = 5 - cpx, cpy = self._latlon_to_pixel(lat, lon, zoom) - # Frame 700x700 px window centred on the location, then downscale to `size`. - win = 700 - left, top = int(cpx - win / 2), int(cpy - win / 2) - tx0, ty0 = left // 256, top // 256 - tx1, ty1 = (left + win + 255) // 256, (top + win + 255) // 256 - # Longitude wraps: the world is cyclic, 2**zoom tiles wide - canvas = self._stitch_tiles(BackgroundStyle.DARK, zoom, tx0, tx1, ty0, ty1, wrap_x=True) - if canvas is None: - return None - ox, oy = left - tx0 * 256, top - ty0 * 256 - cropped = canvas.crop((ox, oy, ox + win, oy + win)).resize((size, size), Image.LANCZOS) - - # Marker: red filled circle + white ring at the exact spot (centre of the frame). - d = ImageDraw.Draw(cropped, "RGBA") - cx, cy = size // 2, size // 2 - d.ellipse([cx - 9, cy - 9, cx + 9, cy + 9], outline=(255, 255, 255, 255), width=2) - d.ellipse([cx - 5, cy - 5, cx + 5, cy + 5], fill=RED + (255,)) - - # Thin white frame around the inset itself. - d.rectangle([0, 0, size - 1, size - 1], outline=(255, 255, 255, 200), width=2) - return cropped - - # Visible aerial slot (between heading band and date strip) — target the - # bbox to ~85% of it so there's some breathing room around the track. - _BBOX_TARGET_W = int(POSTER_W * 0.85) - _BBOX_TARGET_H = int((1300 - 540) * 0.85) # visible aerial slot height, scaled - - def _zoom_from_bbox(self, coords: list, max_zoom: int = 17, min_zoom: int = 10) -> int: - """Pick the tightest zoom level at which the track's GeoJSON bbox still - fits inside the visible aerial area. Walks from high → low zoom and - returns the first zoom that fits — i.e. the most zoomed-in view that - still shows the whole lap.""" - if len(coords) < 2: - return self.DEFAULT_ZOOM - lons = [float(c[0]) for c in coords if len(c) >= 2] - lats = [float(c[1]) for c in coords if len(c) >= 2] - if not lons or not lats: - return self.DEFAULT_ZOOM - lat_min, lat_max = min(lats), max(lats) - lon_min, lon_max = min(lons), max(lons) - for zoom in range(max_zoom, min_zoom - 1, -1): - x_lo, y_hi = self._latlon_to_pixel(lat_min, lon_min, zoom) # SW (small x, large y) - x_hi, y_lo = self._latlon_to_pixel(lat_max, lon_max, zoom) # NE (large x, small y) - if (x_hi - x_lo) <= self._BBOX_TARGET_W and (y_hi - y_lo) <= self._BBOX_TARGET_H: - return zoom - return min_zoom - - def _resolve_circuit_geo(self, grand_prix_name: str, season: int) -> Optional[tuple[float, float, int]]: - """Pull (lat, lon, zoom) for the circuit hosting this GP in this season. - - Centre comes from the GeoJSON bbox midpoint (geometrically accurate), - zoom is computed from the bbox so a tight street circuit gets zoomed in - and a sprawling road course is zoomed out — automatically, no hand-tuning. - - Falls back to Jolpica's circuit coordinate + f1-locations.json's hand- - tuned zoom when GeoJSON coords aren't available for this layout.""" - races = self.ergast._fetch_season_schedule(season) - race = next((r for r in races if r["raceName"] == grand_prix_name), None) - if not race: - return None - - layout = self.circuits.get_circuit_layout_by_ergast_data(grand_prix_name, season) - if layout: - try: - layout.load_geo_json_data() - coords = layout.coordinates - except Exception: - coords = None - if coords and len(coords) >= 2: - lons = [float(c[0]) for c in coords if len(c) >= 2] - lats = [float(c[1]) for c in coords if len(c) >= 2] - lat_c = (min(lats) + max(lats)) / 2 - lon_c = (min(lons) + max(lons)) / 2 - return lat_c, lon_c, self._zoom_from_bbox(coords) - - # Fallback path: Jolpica coordinate + hand-tuned zoom - loc = race.get("Circuit", {}).get("Location", {}) - if "lat" not in loc or "long" not in loc: - return None - lat, lon = float(loc["lat"]), float(loc["long"]) - # Our circuit slug, resolved from Jolpica's circuitId: a Jolpica name never keys a lookup - _, _, circuit_slug = self.ergast.find_slugs_for_circuit(race["Circuit"]) - entry = self._zoom_by_circuit.get(circuit_slug) - zoom = entry["zoom"] if entry and "zoom" in entry else self.DEFAULT_ZOOM - return lat, lon, zoom - - # ---------------------------------------------------------- track raster - - def _rasterise_track(self, svg_path: Path, target_w: int = 700) -> Optional[Image.Image]: - try: - png_bytes = cairosvg.svg2png( - bytestring=svg_path.read_bytes(), - output_width=target_w, - ) - except Exception as e: - logger.error(f"Failed to rasterise {svg_path}: {e}") - return None - track = Image.open(io.BytesIO(png_bytes)).convert("RGBA") - # Recolour all opaque pixels (black stroke in source) → white - px = track.load() - for y in range(track.height): - for x in range(track.width): - r, g, b, a = px[x, y] - if a > 0: - px[x, y] = (WHITE[0], WHITE[1], WHITE[2], a) - return track - - # ------------------------------------------------------------------ race poster + def _draw_inset(self, img: Image.Image, frame: str, points: list, track: tuple[str, int]) -> None: + """The track over a photo: the trace fitted to a box at the bottom right, on a half-black panel.""" + size, margin, bottom = INSET[frame] + x0, y0 = img.width - margin - size, bottom - size + panel = Image.new("RGBA", (size, size), (0, 0, 0, 128)) + img.paste(panel, (x0, y0), panel) + xs, ys = [p[0] for p in points], [p[1] for p in points] + span = max(max(xs) - min(xs), max(ys) - min(ys), 1) + pad = 16 + track[1] + scale = (size - 2 * pad) / span + ox = x0 + (size - (max(xs) - min(xs)) * scale) / 2 + oy = y0 + (size - (max(ys) - min(ys)) * scale) / 2 + self._draw_track(img, [((x - min(xs)) * scale + ox, (y - min(ys)) * scale + oy) for x, y in points], track) @staticmethod - def _keep(cache_path: Path, data: bytes) -> None: - """Store a rendered picture whole: two requests may render the same one side by side.""" - partial = cache_path.with_name(f"{cache_path.name}.{threading.get_ident()}.partial") - partial.write_bytes(data) - partial.replace(cache_path) + def _draw_locator(img: Image.Image, frame: str, locator: Image.Image) -> None: + size, margin, top = LOCATOR_PLACE[frame] + inset = locator.resize((size, size), Image.LANCZOS) + d = ImageDraw.Draw(inset, "RGBA") + c = size // 2 + d.ellipse([c - 9, c - 9, c + 9, c + 9], outline=(255, 255, 255, 255), width=2) + d.ellipse([c - 5, c - 5, c + 5, c + 5], fill=RED + (255,)) + d.rectangle([0, 0, size - 1, size - 1], outline=(255, 255, 255, 200), width=2) + img.paste(inset, (img.width - size - margin, top)) - # Every render_* answers (png, kept): kept is False when its map or photo failed, so the picture is - # served but not stored, and the caller tells clients not to keep it either. + def _draw_credit(self, img: Image.Image, credit: str, bottom: int, scale: float) -> None: + """The credit line on a dark band, at least CREDIT_MIN_PX high on the picture as served, wrapped.""" + if not credit: + return + size = 14 + while self._text_height(size) * scale < CREDIT_MIN_PX: + size += 1 + font = self._font(size, self.credit_font_path) + draw = ImageDraw.Draw(img) + margin = max(12, size) + lines, line = [], "" + for word in credit.split(" "): + candidate = f"{line} {word}".strip() + if line and draw.textlength(candidate, font) > img.width - 2 * margin: + lines.append(line) + line = word + else: + line = candidate + lines.append(line) + line_h = round(size * 1.25) + pad = max(4, size // 3) + band_h = len(lines) * line_h + 2 * pad + band = Image.new("RGBA", (img.width, band_h), (0, 0, 0, 170)) + img.paste(band, (0, bottom - band_h), band) + for i, text in enumerate(lines): + x = (img.width - draw.textlength(text, font)) / 2 + draw.text((x, bottom - band_h + pad + i * line_h), text, font=font, fill=(225, 225, 225)) - def render_race_poster( - self, - grand_prix_name: str, - season: int, - bg: BackgroundStyle = BackgroundStyle.AERIAL, - ) -> Optional[tuple[bytes, bool]]: - races = self.ergast._fetch_season_schedule(season) - race = next((r for r in races if r["raceName"] == grand_prix_name), None) + def _text_height(self, size: int) -> int: + box = self._font(size, self.credit_font_path).getbbox("Ag") + return box[3] - box[1] + + @staticmethod + def _encode(img: Image.Image, options: po.Options) -> bytes: + if options.width < img.width: + img = img.resize((options.width, round(img.height * options.width / img.width)), Image.LANCZOS) + buf = io.BytesIO() + if options.format == "jpg": + img.convert("RGB").save(buf, "JPEG", quality=90, optimize=True) + elif options.format == "webp": + img.convert("RGB").save(buf, "WEBP", quality=88) + else: + img.save(buf, "PNG") + return buf.getvalue() + + # ------------------------------------------------------------------ rendering + + def _finish(self, route: str, options: po.Options, background: Optional[Layer], locator: Optional[Layer], + outline: Optional[str], compose) -> Rendered: + """The stored picture for these layers and options, or one drawn now, and stored when every layer came. + A stored picture was made from every layer it names, so its credit line and its licence are theirs.""" + layers = [layer for layer in (background, locator) if layer] + ps.picture_licence([layer.share for layer in layers]) # a clash of share-alike terms is refused, not drawn + name = po.finished_key(route, options, [layer.key for layer in layers] + ([outline] if outline else [])) + media_type = po.FORMATS[options.format] + stored = self.store.get(name) + if stored is not None: + logger.info(f"Picture {route} [{options.canonical()}]: from the store") + return Rendered(stored, True, ps.credit_line([layer.credit for layer in layers]), + ps.picture_licence([layer.share for layer in layers]), name, media_type) + started = time.monotonic() + got = [(layer, layer.get()) for layer in layers] + missing = [layer.key for layer, img in got if img is None] + arrived = [layer for layer, img in got if img is not None] + credit = ps.credit_line([layer.credit for layer in arrived]) + images = {id(layer): img for layer, img in got} + img = compose(images.get(id(background)), images.get(id(locator)), credit) + data = self._encode(img, options) + if not missing: + self.store.put(name, data) + logger.info(f"Picture {route} [{options.canonical()}]: drawn in {(time.monotonic() - started) * 1000:.0f} ms" + + (", stored" if not missing else f", without {', '.join(missing)}: served for five minutes, " + f"not stored")) + return Rendered(data, not missing, credit, ps.picture_licence([layer.share for layer in arrived]), name, + media_type) + + def render(self, kind: str, options: po.Options, grand_prix_name: Optional[str] = None, + season: Optional[int] = None, session_slug: Optional[str] = None) -> Optional[Rendered]: + """A race poster, a session thumbnail (kind race or session) or a season poster; None when it is not known.""" + if kind == "season": + return self._render_season(season, options) + label = SESSION_LABEL_BY_SLUG.get(session_slug) if kind == "session" else None + if kind == "session" and not label: + return None + race = self._race(grand_prix_name, season) if not race: logger.error(f"Race not found: {grand_prix_name} {season}") return None - - round_num = int(race["round"]) - date = race.get("date", "") - layout = self.circuits.get_circuit_layout_by_ergast_data(grand_prix_name, season) if not layout: logger.error(f"Layout not resolved for {grand_prix_name} {season}") return None + frame = po.FRAME_OF[kind] + circuit = layout.circuit + geo = self._geo(race, layout) - cache_key = f"{season}-{round_num:02d}-{layout.slug}-{bg.value}-{POSTER_RENDER}.png" - cache_path = self.cache_dir / cache_key - if cache_path.exists(): - return cache_path.read_bytes(), True + # The background: the satellite chain, OpenStreetMap (recoloured for dark and light), or none. + background, is_photo, tint, zoom = None, False, options.bg, geo.zoom if geo else DEFAULT_ZOOM + if options.bg != "none" and geo: + chosen = ps.osm() + if options.bg == "satellite": + layout_key = f"{circuit.locality.country.slug}/{circuit.locality.slug}/{circuit.slug}/{layout.slug}" + entry = self.picks(CIRCUIT_PICKS).get(layout_key) # a photo, or the override {"use": "map"} + chosen = ps.satellite_source(circuit.locality.country.slug, circuit.slug, layout.slug, entry) + if chosen == ps.COMMONS: + background, is_photo = self._photo_layer(entry, frame), True + else: + zoom, tint = min(zoom, chosen.max_zoom), chosen.tint or options.bg + background = self._map_layer(chosen, geo, frame, zoom) + locator = self._locator_layer(geo) if options.locator and geo else None + outline_key = po.outline_layer_key(geo.trace_hash, frame, zoom) if options.track and geo and geo.trace else None - # Fetch map background if requested; fall back to flat black if anything fails. - # One (lat, lon, zoom) for the map, the projected track and the locator, the zoom no deeper than - # the background's provider draws, so the track lies on the map it was projected for. - map_bg: Optional[Image.Image] = None - locator: Optional[Image.Image] = None - geo = None - if bg is not BackgroundStyle.NONE: - geo = self._capped(self._resolve_circuit_geo(grand_prix_name, season), bg) - if geo: - map_bg = self._fetch_map_background(*geo, bg) + texts = { + "wordmark": "FORMULA 1", + "round": f"ROUND {int(race['round']):02d} / {season}", + "name": grand_prix_name.replace("Grand Prix", "").strip().upper(), + "subtitle": "GRAND PRIX", + "date": race.get("date", ""), + "circuit": circuit.name, + "locality": circuit.locality.name, + "session": label, + } - if map_bg is not None: - # Dim the underlying map so the white track + heading text stay legible. - img = Image.alpha_composite(map_bg.convert("RGBA"), self._race_dark_overlay()).convert("RGB") + def compose(background_img, locator_img, credit): + outline = self._outline(geo, frame, zoom) if outline_key else None + return self._compose(kind, frame, texts, options, background_img, is_photo, outline, locator_img, credit, + tint) + + route = f"{kind}/{grand_prix_name}/{season}" + (f"/{session_slug}" if session_slug else "") + return self._finish(route, options, background, locator, outline_key, compose) + + def _render_season(self, season: int, options: po.Options) -> Rendered: + """A season poster: the year over that season's picked Commons photo, or over black until one is picked.""" + pick = self.picks(SEASON_PICKS).get(str(season)) if options.bg != "none" else None + pick = pick if ps.is_photo(pick) else None + background = self._photo_layer(pick, "poster") if pick else None + texts = {"wordmark": "FORMULA 1", "name": str(season), "subtitle": "WORLD CHAMPIONSHIP"} + + def compose(background_img, _locator_img, credit): + return self._compose("season", "poster", texts, options, background_img, True, None, None, credit) + + return self._finish(f"season/{season}", options, background, None, None, compose) + + def _compose(self, kind: str, frame: str, texts: dict, options: po.Options, background: Optional[Image.Image], + is_photo: bool, outline: Optional[list], locator: Optional[Image.Image], credit: str, + tint: Optional[str] = None) -> Image.Image: + size = po.FRAMES[frame] + w, h = size + img = Image.new("RGB", size, BG) + if background is not None: + if is_photo: + background = background.convert("L").convert("RGB") if options.photo == "bw" else background + else: + background = recolour(background, tint or options.bg) + img = Image.alpha_composite(background.convert("RGBA"), + self._dim_overlay(kind, size, options.dim)).convert("RGB") + draw = ImageDraw.Draw(img) + show = options.show + accent = _hex(options.accent) + if options.checker: + self._checker_strip(draw, 0, w) + self._checker_strip(draw, h - CHECKER_H, w) + + if outline and options.track: + if is_photo and background is not None: + self._draw_inset(img, frame, outline, options.track) + else: + self._draw_track(img, outline, options.track) + + if kind == "season": + if "wordmark" in show: + self._centered(draw, texts["wordmark"], 110, 88, accent) + if "name" in show: + self._centered(draw, texts["name"], 240, 240, WHITE) + if "subtitle" in show: + self._centered(draw, texts["subtitle"], h - 200, 48, WHITE) + elif kind == "race": + if "wordmark" in show: + self._centered(draw, texts["wordmark"], 110, 88, accent) + if "round" in show: + self._centered(draw, texts["round"], 220, 34, GREY) + if "name" in show: + self._centered(draw, texts["name"], 300, 110, WHITE) + if "subtitle" in show: + self._centered(draw, texts["subtitle"], 440, 44, GREY) + place = " · ".join(texts[k] for k in ("circuit", "locality") if k in show) + if place: + self._centered(draw, place, h - 210, 28, GREY) + if "date" in show and texts["date"]: + self._centered(draw, texts["date"], h - 170, 32, WHITE) else: - img = Image.new("RGB", (POSTER_W, POSTER_H), BG) + self._draw_thumb_texts(draw, texts, show, accent, CHECKER_H if options.checker else 0) - draw = ImageDraw.Draw(img) + if locator is not None: + self._draw_locator(img, frame, locator) + self._draw_credit(img, credit, h - CHECKER_H if options.checker else h, options.width / w) + return img - # Top checker - self._checker_strip(draw, 0) - - # FORMULA 1 wordmark - self._centered(draw, "FORMULA 1", y=110, size=88, fill=RED) - - # Round / Year ribbon - self._centered(draw, f"ROUND {round_num:02d} / {season}", y=220, size=34, fill=GREY) - - # GP name (drop "Grand Prix" suffix; render "GRAND PRIX" smaller below) - name_short = grand_prix_name.replace("Grand Prix", "").strip().upper() - self._centered(draw, name_short, y=300, size=110, fill=WHITE) - self._centered(draw, "GRAND PRIX", y=440, size=44, fill=GREY) - - # Track outline. - # When a map background is present we project the GeoJSON lat/lon points - # using the same zoom/centre we used for the tiles — that way the white - # outline is geographically aligned with the actual track in the photo. - # Without a map (bg=NONE) there's nothing to align with so we fall back - # to the hand-drawn SVG centred in the slot. - projected = False - if map_bg is not None: - try: - # GeoJSON is lazy-loaded — trigger the read before pulling coords. - layout.load_geo_json_data() - projected = self._draw_track_projected(img, layout.coordinates, *geo) - except Exception as e: - logger.warning(f"GeoJSON track projection failed; falling back to SVG: {e}") - - if not projected: - svg_path = Path("circuits") / layout.relative_svg_filepath - if svg_path.exists(): - track = self._rasterise_track(svg_path, target_w=720) - if track: - slot_top, slot_bottom = 560, 1250 - tx = (POSTER_W - track.width) // 2 - ty = slot_top + ((slot_bottom - slot_top) - track.height) // 2 - img.paste(track, (tx, ty), track) - - # World locator inset (top-right) — picture-in-picture pointing at the - # exact race location on the globe. Only meaningful when a map bg is on. - # Sized + positioned so it tucks under the top checker and sits to the - # right of the centred FORMULA 1 wordmark without overlapping. - if bg is not BackgroundStyle.NONE: - if geo: - lat, lon, _ = geo - locator = self._render_world_locator(lat, lon, size=140) - if locator: - margin = 25 - img.paste(locator, (POSTER_W - locator.width - margin, CHECKER_H + margin)) - - # Date - if date: - self._centered(draw, date, y=POSTER_H - 170, size=32, fill=WHITE) - - # Bottom checker - self._checker_strip(draw, POSTER_H - CHECKER_H) - - buf = io.BytesIO() - img.save(buf, "PNG") - data = buf.getvalue() - whole = bg is BackgroundStyle.NONE or (map_bg is not None and locator is not None) - if whole: - # A poster whose map failed is served, not kept: the next ask renders it again - self._keep(cache_path, data) - return data, whole - - # ------------------------------------------------------------------ session thumb (16:9) - - def _fetch_map_landscape(self, lat: float, lon: float, zoom: int, style: BackgroundStyle) -> Optional[Image.Image]: - """Like _fetch_map_background but for THUMB_W x THUMB_H (1920x1080). - Centred so the geographic point lands at the visual midpoint.""" - provider = TILE_PROVIDERS.get(style) - if not provider: - return None - cpx, cpy = self._latlon_to_pixel(lat, lon, zoom) - left, top = int(cpx - THUMB_W / 2), int(cpy - THUMB_H / 2) - tx0, ty0 = left // 256, top // 256 - tx1, ty1 = (left + THUMB_W + 255) // 256, (top + THUMB_H + 255) // 256 - canvas = self._stitch_tiles(style, zoom, tx0, tx1, ty0, ty1) - if canvas is None: - return None - ox, oy = left - tx0 * 256, top - ty0 * 256 - return canvas.crop((ox, oy, ox + THUMB_W, oy + THUMB_H)) - - def render_session_thumb(self, grand_prix_name: str, season: int, session_slug: str) -> Optional[tuple[bytes, bool]]: - """1920x1080 Plex episode-thumb. Aerial of the circuit + GP name + session label.""" - label = SESSION_LABEL_BY_SLUG.get(session_slug) - if not label: - return None - - races = self.ergast._fetch_season_schedule(season) - race = next((r for r in races if r["raceName"] == grand_prix_name), None) - if not race: - return None - round_num = int(race["round"]) - layout = self.circuits.get_circuit_layout_by_ergast_data(grand_prix_name, season) - if not layout: - return None - - cache_key = f"thumb-{season}-{round_num:02d}-{layout.slug}-{session_slug}.png" - cache_path = self.cache_dir / cache_key - if cache_path.exists(): - return cache_path.read_bytes(), True - - # Same per-circuit geo (lat, lon, bbox-derived zoom) as the race poster, - # so the thumb shows the same place at the same zoom level. - geo = self._resolve_circuit_geo(grand_prix_name, season) - map_bg = self._fetch_map_landscape(*geo, BackgroundStyle.AERIAL) if geo else None - - img = Image.new("RGB", (THUMB_W, THUMB_H), BG) - if map_bg is not None: - # Heavier dim than the poster — 16:9 fills the player thumb at small - # sizes, so we need solid contrast for the overlaid label text. - overlay = Image.new("RGBA", (THUMB_W, THUMB_H), (0, 0, 0, 140)) - img = Image.alpha_composite(map_bg.convert("RGBA"), overlay).convert("RGB") - - # Project the track polyline onto the landscape canvas — same math - # as the race poster but with THUMB_W / THUMB_H/2 so it overlays the - # actual circuit visible in the aerial. - try: - layout.load_geo_json_data() - self._draw_track_projected( - img, layout.coordinates, *geo, - canvas_w=THUMB_W, geo_center_y=THUMB_H // 2, - ) - except Exception as e: - logger.warning(f"Session-thumb track projection failed: {e}") - - draw = ImageDraw.Draw(img) - - # Two left-aligned text columns: GP name top-left, session label bottom-left. - # Round/year accent in red between them. - x_margin = 80 - name_short = grand_prix_name.replace("Grand Prix", "").strip().upper() - - # FORMULA 1 small wordmark top-left - font_wm = self._font(40) - draw.text((x_margin, 60), "FORMULA 1", fill=RED, font=font_wm) - - # Round/year ribbon - font_ribbon = self._font(28) - draw.text((x_margin, 120), f"ROUND {round_num:02d} / {season}", fill=GREY, font=font_ribbon) - - # GP name — fit to 1300px max width - gp_size = 120 - font_gp = self._font(gp_size) - while gp_size > 60 and draw.textlength(name_short, font_gp) > 1300: + def _draw_thumb_texts(self, draw: ImageDraw.ImageDraw, texts: dict, show: frozenset, accent, lift: int) -> None: + """The thumb's texts: the heading top left, the session label (and the date under it) bottom left, lifted + above the bottom checker strip when it is drawn.""" + x = 80 + if "wordmark" in show: + draw.text((x, 60), texts["wordmark"], fill=accent, font=self._font(40)) + if "round" in show: + draw.text((x, 120), texts["round"], fill=GREY, font=self._font(28)) + name, gp_size = texts["name"], 120 + while gp_size > 60 and draw.textlength(name, self._font(gp_size)) > 1300: gp_size -= 10 - font_gp = self._font(gp_size) - draw.text((x_margin, 180), name_short, fill=WHITE, font=font_gp) - draw.text((x_margin, 180 + gp_size + 5), "GRAND PRIX", fill=GREY, font=self._font(36)) - - # Session label — bottom-left, very prominent - sess_size = 90 - font_sess = self._font(sess_size) - while sess_size > 50 and draw.textlength(label.upper(), font_sess) > 1300: + if "name" in show: + draw.text((x, 180), name, fill=WHITE, font=self._font(gp_size)) + subtitle_y = 180 + gp_size + 5 + if "subtitle" in show: + draw.text((x, subtitle_y), texts["subtitle"], fill=GREY, font=self._font(36)) + place = " · ".join(texts[k] for k in ("circuit", "locality") if k in show) + if place: + draw.text((x, subtitle_y + 36 + 16), place, fill=GREY, font=self._font(28)) + label, sess_size = texts["session"].upper(), 90 + while sess_size > 50 and draw.textlength(label, self._font(sess_size)) > 1300: sess_size -= 6 - font_sess = self._font(sess_size) - sess_label = label.upper() - sess_y = THUMB_H - 130 - sess_size - draw.text((x_margin, sess_y), sess_label, fill=WHITE, font=font_sess) - - # Thin red accent bar above the session label - draw.rectangle([x_margin, sess_y - 16, x_margin + 120, sess_y - 8], fill=RED) - - buf = io.BytesIO() - img.save(buf, "PNG") - data = buf.getvalue() - if map_bg is not None: - # A thumb whose aerial failed is served, not kept: the next ask renders it again - self._keep(cache_path, data) - return data, map_bg is not None + sess_y = THUMB_H - 130 - sess_size - lift + if "session" in show: + draw.rectangle([x, sess_y - 16, x + 120, sess_y - 8], fill=RED) # a thin bar above the session label + draw.text((x, sess_y), label, fill=WHITE, font=self._font(sess_size)) + if "date" in show and texts["date"]: + draw.text((x, sess_y + sess_size + 14), texts["date"], fill=GREY, font=self._font(36)) # ------------------------------------------------------------------ kometa metadata BASE_URL = PUBLIC_BASE_URL def render_kometa_metadata(self, first_season: int = 1950, last_offset: int = 1) -> str: - """Emit the Kometa metadata YAML for the Formula 1 library, covering - every F1 season from `first_season` through current_year + last_offset. - - Per show: f1_season builder + url_poster pointing at the season hero. - Per Plex season (== round): url_poster pointing at the race poster. - Kometa silently skips shows / seasons that don't exist in the library.""" + """The Kometa metadata YAML for the Formula 1 library, every season from `first_season` through + current_year + last_offset. Per show: the f1_season builder and the season poster; per Plex season (a + round): its race poster; per episode: its session thumbnail. Every poster address carries the render + version, so clients keep it for good and a changed look reaches them under a new address.""" from datetime import datetime from urllib.parse import quote + version = f"?v={po.RENDER_VERSION}" last_season = datetime.utcnow().year + last_offset lines: list[str] = [ + "# This file's data (race names, rounds, dates) comes from the Jolpica F1 API " + "(https://github.com/jolpica/jolpica-f1) under CC BY-NC-SA 4.0, and the file is offered under the same.", + "# Each poster's and thumbnail's licence follows the sources of its pictures (sent as X-License); " + f"those sources and their credits: {self.BASE_URL}/licences", "# Auto-generated by f1-circuits (/kometa/formula-1-metadata.yml).", "# Do not commit — fetch via metadata_files.url in Kometa config.", "metadata:", @@ -725,7 +887,7 @@ class PostersService: lines.append(f" f1_season: {season}") lines.append(" round_prefix: true") lines.append(" shorten_gp: true") - lines.append(f" url_poster: {self.BASE_URL}/posters/season/{season}.png") + lines.append(f" url_poster: {self.BASE_URL}/posters/season/{season}.png{version}") if not races: continue lines.append(" seasons:") @@ -735,109 +897,15 @@ class PostersService: name = race["raceName"] except (KeyError, ValueError): continue - race_url = f"{self.BASE_URL}/posters/race/{quote(name)}/{season}.png" lines.append(f" {round_num}:") - lines.append(f" url_poster: {race_url}") - - # Per-episode session thumbs. Detect sprint format from the - # presence of a Sprint section in the Jolpica race entry; the - # F1 builder maps each format to its own episode numbering and - # we follow the same map here so each Plex episode lands on a - # correctly-labelled session thumb. + lines.append(f" url_poster: {self.BASE_URL}/posters/race/{quote(name)}/{season}.png{version}") + # A sprint weekend numbers its episodes on its own (Kometa's F1 builder), told by its Sprint entry. is_sprint = any(k.lower().startswith("sprint") for k in race.keys()) session_map = _SESSION_SPRINT if is_sprint else _SESSION_STD lines.append(" episodes:") for ep_num, (_label, slug) in session_map.items(): - thumb_url = f"{self.BASE_URL}/posters/session/{quote(name)}/{season}/{slug}.png" lines.append(f" {ep_num}:") - lines.append(f" url_poster: {thumb_url}") + lines.append(f" url_poster: {self.BASE_URL}/posters/session/{quote(name)}/{season}/" + f"{slug}.png{version}") lines.append("") return "\n".join(lines) - - # ------------------------------------------------------------------ season poster - - def _fetch_season_background(self, season: int) -> Optional[Image.Image]: - """Pull the season's hero photo from the dilbert files-api CDN.""" - url = SEASON_BG_URL_TEMPLATE.format(season=season) - try: - with urllib.request.urlopen(url, timeout=10) as resp: - bg = Image.open(io.BytesIO(resp.read())).convert("RGB") - except Exception as e: - logger.warning(f"No season background for {season} ({url}): {e}") - return None - # Cover-fit into 1000x1500: scale so both dims meet/exceed target, centre-crop. - sw, sh = bg.size - scale = max(POSTER_W / sw, POSTER_H / sh) - bg = bg.resize((int(sw * scale), int(sh * scale)), Image.LANCZOS) - nw, nh = bg.size - left = (nw - POSTER_W) // 2 - top = (nh - POSTER_H) // 2 - return bg.crop((left, top, left + POSTER_W, top + POSTER_H)) - - def _race_dark_overlay(self) -> Image.Image: - """Dimming overlay for race posters when a map background is present. - Stronger at top (heading area) and middle (track), lighter elsewhere so - the underlying map detail still reads through.""" - overlay = Image.new("RGBA", (POSTER_W, POSTER_H), (0, 0, 0, 0)) - ovr = overlay.load() - for y in range(POSTER_H): - if y < 540: - # Strong dim under the FORMULA 1 / Round / GP-name block - alpha = 200 - elif y < 1300: - # Mid-section behind the track — light dim - alpha = 110 - else: - # Bottom (date strip + checker) - alpha = 200 - for x in range(POSTER_W): - ovr[x, y] = (0, 0, 0, alpha) - return overlay - - def _vertical_dark_gradient(self) -> Image.Image: - """A vertical alpha gradient that's darkest top + bottom — keeps the photo's - midsection visible while making wordmark / year / footer text legible.""" - overlay = Image.new("RGBA", (POSTER_W, POSTER_H), (0, 0, 0, 0)) - ovr = overlay.load() - for y in range(POSTER_H): - if y < 500: - # Strong dim at top for the wordmark + year, fading to nothing at y=500 - alpha = 220 - (y * 220 // 500) - elif y > 1100: - # Strong dim at bottom for "WORLD CHAMPIONSHIP" footer - alpha = (y - 1100) * 220 // (POSTER_H - 1100) - alpha = min(alpha, 220) - else: - # Mild dim through the middle to anchor text contrast - alpha = 60 - for x in range(POSTER_W): - ovr[x, y] = (0, 0, 0, alpha) - return overlay - - def render_season_poster(self, season: int) -> tuple[bytes, bool]: - cache_path = self.cache_dir / f"season-{season}.png" - if cache_path.exists(): - return cache_path.read_bytes(), True - - bg = self._fetch_season_background(season) - if bg is None: - # Fallback to the all-black layout if the background isn't available. - img = Image.new("RGB", (POSTER_W, POSTER_H), BG) - else: - # Composite the dimming gradient over the hero photo for text legibility. - img = Image.alpha_composite(bg.convert("RGBA"), self._vertical_dark_gradient()).convert("RGB") - - draw = ImageDraw.Draw(img) - self._checker_strip(draw, 0) - self._centered(draw, "FORMULA 1", y=110, size=88, fill=RED) - self._centered(draw, str(season), y=240, size=240, fill=WHITE) - self._centered(draw, "WORLD CHAMPIONSHIP", y=POSTER_H - 200, size=48, fill=WHITE) - self._checker_strip(draw, POSTER_H - CHECKER_H) - - buf = io.BytesIO() - img.save(buf, "PNG") - data = buf.getvalue() - if bg is not None: - # A poster whose photo failed is served, not kept: the next ask renders it again - self._keep(cache_path, data) - return data, bg is not None diff --git a/seasons/photos.json b/seasons/photos.json new file mode 100644 index 0000000..8780078 --- /dev/null +++ b/seasons/photos.json @@ -0,0 +1,3 @@ +{ + "$comment": "The picked Wikimedia Commons photo per season, from the \" Formula One season cars\" category (docs/posters.md, Season posters and Picking photos). Key: the year, such as \"2024\". Value: {\"file\": the Commons title without \"File:\", \"licence\": its LicenseShortName (CC0, public domain, CC BY or CC BY-SA only), \"author\", \"credit\": \"Photo: , , via Wikimedia Commons\", \"date\": YYYY[-MM[-DD]]}. Written by the picking tool, read by the poster service; a key starting with \"$\" is a note, not a pick." +} diff --git a/service/Dockerfile b/service/Dockerfile index 9722848..6e0463c 100644 --- a/service/Dockerfile +++ b/service/Dockerfile @@ -22,9 +22,12 @@ RUN apk add --no-cache \ COPY service/requirements.txt ./requirements.txt RUN pip install --no-cache-dir -r requirements.txt -COPY cdn-api.py access_log.py circuits_service.py ergast_service.py posters_service.py ./ +COPY cdn-api.py access_log.py app_info.py circuits_service.py ergast_service.py posters_service.py \ + poster_options.py poster_sources.py ./ COPY models/ ./models/ COPY circuits/ ./circuits/ +# The picked photo per season (the picks per layout are in circuits/photos.json). +COPY seasons/ ./seasons/ # The example site the app serves at /examples/. COPY examples/ ./examples/ diff --git a/tests/test_posters.py b/tests/test_posters.py new file mode 100644 index 0000000..2fe4d6a --- /dev/null +++ b/tests/test_posters.py @@ -0,0 +1,157 @@ +"""A poster's sources, credits, licence, options, keys and cache headers (docs/posters.md). + +Standard library only (no PIL, no numpy), so the merge check runs it as it is. +""" +import json +import tempfile +import unittest +from pathlib import Path + +import poster_options as po +import poster_sources as ps + +ROOT = Path(__file__).resolve().parent.parent + + +class SatelliteChainTest(unittest.TestCase): + def test_the_first_source_that_has_the_layout(self): + early = 2016 if ps.EOX_2016_FOR_EARLY_LAYOUTS else 2025 # the one switch for EOX's year + photo, use_map = {"file": "A.jpg", "licence": "CC BY 4.0"}, {"use": "map"} + cases = [ + # (country, circuit, layout, the layout's entry in circuits/photos.json) → (source, year, tint) + (("bahrain", "bahrain-international-circuit", "2004-", photo), ("commons", None, None)), + (("united-states", "miami-international-autodrome", "2022-", None), ("usgs", None, None)), + (("netherlands", "circuit-park-zandvoort", "2020-", use_map), ("pdok", None, None)), # national wins + (("france", "circuit-paul-ricard", "2018-", None), ("ign", "2021-2023", None)), + (("bahrain", "bahrain-international-circuit", "2004-", None), ("eox", early, None)), # first raced by 2016 + (("bahrain", "bahrain-international-circuit", "2004-", use_map), ("osm", None, "dark")), # the override + (("spain", "madring", "2026-", None), ("eox", 2025, None)), + ] + for given, expected in cases: + chosen = ps.satellite_source(*given) + got = (chosen, None, None) if chosen == ps.COMMONS else (chosen.id, chosen.year, chosen.tint) + self.assertEqual(got, expected, given) + self.assertEqual(ps.satellite_source("bahrain", "x", "2004-", use_map).credit, ps.OSM_CREDIT) + + def test_every_french_layout_takes_ign(self): + france = json.loads((ROOT / "circuits" / "circuits.json").read_text(encoding="utf-8"))["france"] + layouts = [(slug, layout) for locality in france["localities"].values() + for slug, circuit in locality["circuits"].items() for layout in circuit["layouts"]] + self.assertTrue(layouts) + for slug, layout in layouts: + self.assertEqual(ps.satellite_source("france", slug, layout).id, "ign", (slug, layout)) + + +class CreditAndLicenceTest(unittest.TestCase): + def test_credit_line_and_its_header(self): + line = ps.credit_line([ps.ign().credit, ps.OSM_CREDIT, ps.OSM_CREDIT, ""]) + self.assertEqual(line, "© IGN – BD ORTHO, 2021–2023 · © OpenStreetMap contributors") + self.assertEqual(ps.ascii_header(line), "(c) IGN - BD ORTHO, 2021-2023 | (c) OpenStreetMap contributors") + self.assertEqual(ps.ascii_header("Photo: José Müller — 王 CC BY-SA 4.0"), "Photo: Jose Muller - ? CC BY-SA 4.0") + + def test_a_pictures_licence_follows_its_sources(self): + by_sa = ps.pick_share({"licence": "CC BY-SA 3.0 de"}) + cases = [ + ([by_sa, ps.osm().share], "CC BY-SA 4.0"), + ([ps.eox(2025).share, ps.osm().share], "CC BY-NC-SA 4.0"), + ([ps.eox(2016).share, ps.osm().share], "CC BY 4.0"), + ([ps.pick_share({"licence": "CC BY 2.0"}), ps.usgs().share, ps.pdok().share, ps.ign().share], "CC BY 4.0"), + ([], "CC BY 4.0"), + ] + for shares, licence in cases: + self.assertEqual(ps.picture_licence(shares), licence, shares) + with self.assertRaises(ps.LicenceClash): + ps.picture_licence([by_sa, ps.eox(2025).share]) + + def test_picks_skip_notes_and_refuse_what_they_cannot_use(self): + with tempfile.TemporaryDirectory() as kept: + path = Path(kept) / "photos.json" + path.write_text(json.dumps({ + "$comment": "a note", + "a/b/c/2004-": {"file": "A.jpg", "licence": "CC BY-SA 4.0", "author": "A"}, + "a/b/c/1950-": {"file": "B.jpg", "licence": "CC BY-NC-SA 2.0", "author": "B"}, + "a/b/c/2010": {"file": "C.jpg", "licence": "Public domain", "author": "C"}, + "a/b/c/2020-": {"use": "map"}, + "a/b/c/1990": {"use": "satellite"}, + "a/b/c/1991": {"use": "map", "file": "D.jpg", "licence": "CC0"}, + })) + with self.assertLogs(ps.logger, "ERROR") as logged: + self.assertEqual(sorted(ps.read_picks(path)), ["a/b/c/2004-", "a/b/c/2010", "a/b/c/2020-"]) + self.assertEqual(len(logged.output), 3) + for name in ("circuits/photos.json", "seasons/photos.json"): + self.assertEqual(ps.read_picks(ROOT / name).get("$comment"), None, name) + + def test_licences_name_every_source_and_the_pictures_rule(self): + licences = ps.licences() + self.assertEqual([entry["licence"] for entry in licences["pictures"]["licences"]], + ["CC BY-SA 4.0", "CC BY-NC-SA 4.0", "CC BY 4.0"]) + self.assertEqual([source["id"] for source in licences["sources"]], + ["commons", "usgs", "pdok", "ign"] + (["eox-2016"] if ps.EOX_2016_FOR_EARLY_LAYOUTS else []) + + ["eox", "osm", "jolpica", "traces"]) + for source in licences["sources"]: + for field in ("name", "used_for", "licence", "licence_url", "credit", "terms", "picture_licence"): + self.assertTrue(source[field], f"{source['id']} has no {field}") + + +class OptionsTest(unittest.TestCase): + def parse(self, query: str, kind: str = "race") -> po.Options: + return po.parse_options([tuple(part.split("=", 1)) for part in query.split("&") if part], kind) + + def test_presets_per_kind(self): + race, thumb, season = self.parse(""), self.parse("", "session"), self.parse("", "season") + self.assertEqual((race.bg, race.photo, race.checker, race.locator, race.dim, race.track, race.width), + ("satellite", "natural", True, True, 0.43, ("#ffffff", 6), 1000)) + self.assertEqual((thumb.checker, thumb.locator, thumb.width), (False, False, 1920)) # classic: as before + self.assertEqual(sorted(self.parse("style=minimal", "session").show), ["name", "session"]) + self.assertEqual(sorted(self.parse("style=minimal").show), ["date", "name"]) + self.assertEqual(sorted(season.show), ["name", "subtitle", "wordmark"]) + # Any option given overrides the style; equal pictures share one canonical form, whatever their address + self.assertEqual(self.parse("style=minimal&checker=on").checker, True) + self.assertEqual(self.parse("bg=aerial&v=r1").canonical(), self.parse("").canonical()) + self.assertTrue(self.parse(f"v={po.RENDER_VERSION}").versioned) + self.assertFalse(self.parse("v=r2").versioned) + + def test_an_unknown_option_or_value_is_named(self): + cases = { + "colour=red": "'colour'", "bg=esri": "'esri'", "photo=duotone": "'duotone'", "show=name,logo": "'logo'", + "track=#fff": "'#fff'", "track=#ffffff,31": "'#ffffff,31'", "dim=1.5": "'1.5'", "dim=nan": "'nan'", + "width=199": "'199'", "width=1001": "'1001'", "format=gif": "'gif'", "bg=osm&bg=dark": "'bg'", + "locator=yes": "'yes'", "accent=red": "'red'", + } + for query, named in cases.items(): + with self.assertRaises(po.OptionError, msg=query) as caught: + self.parse(query) + self.assertIn(named, str(caught.exception), query) + self.assertEqual(self.parse("width=1920", "session").width, 1920) + + def test_keys(self): + options = self.parse("") + key = po.finished_key("race/Bahrain Grand Prix/2024", options, ["map/eox-2016/x-poster-z15-r3"]) + self.assertNotEqual(key, po.finished_key("race/Bahrain Grand Prix/2024", self.parse("photo=bw"), + ["map/eox-2016/x-poster-z15-r3"])) + self.assertNotEqual(key, po.finished_key("race/Bahrain Grand Prix/2023", options, + ["map/eox-2016/x-poster-z15-r3"])) + self.assertTrue(key.endswith(".png")) + self.assertTrue(po.finished_key("race/Bahrain Grand Prix/2024", self.parse("format=webp"), []).endswith(".webp")) + self.assertEqual(po.locator_layer_key(26.0325, 50.5106), f"locator/26.03_50.51-{po.RENDER_VERSION}") + self.assertIn(po.RENDER_VERSION, po.map_layer_key("eox-2025", po.trace_hash([[1, 2]]), "thumb", 15)) + + +class CachingTest(unittest.TestCase): + def test_what_clients_keep(self): + self.assertEqual(po.cache_headers(True, True, '"e"'), + {"Cache-Control": "public, max-age=31536000, immutable", "ETag": '"e"'}) + self.assertEqual(po.cache_headers(True, False, '"e"'), {"Cache-Control": "public, max-age=86400", "ETag": '"e"'}) + self.assertEqual(po.cache_headers(False, True, '"e"'), {"Cache-Control": "public, max-age=300"}) + self.assertTrue(po.etag_matches('"a", W/"e"', '"e"')) + self.assertFalse(po.etag_matches("", '"e"')) + + def test_the_least_recently_used_go_first(self): + entries = {"old": (1.0, 600), "new": (3.0, 600), "mid": (2.0, 600)} + self.assertEqual(po.evictions(entries, 1300), ["old"]) + self.assertEqual(po.evictions(entries, 600), ["old", "mid"]) + self.assertEqual(po.evictions(entries, 1800), []) + + +if __name__ == "__main__": + unittest.main()