Files
f1-circuits/poster_options.py
T
jschoubben db5c19f0d4 Draw posters from kept layers of licensed sources, credited on every picture
Esri's, Bing's and Google's terms forbid keeping or serving pictures made from their maps, so the posters move to
sources whose licence allows a kept copy: a picked Wikimedia Commons photo, USGS, PDOK and IGN's frozen 2021-2023
mosaic by country, else EOxCloudless's newest mosaic, and OpenStreetMap for the maps and the locator. What needs
the network is a layer fetched once and kept whole in layers/; texts, colours, size and format are drawn on every
request, and finished pictures are kept in posters/ up to 2 GB. Every picture carries its sources' credit line,
X-Credits, X-License (which follows its sources) and a link to /licences. Options are checked into a named 422;
the Kometa file states Jolpica's licence and versions its addresses so clients keep them for good. A layout whose
trace is a point (Madring) is drawn at the circuit's location instead of failing.

Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
2026-11-27 15:13:29 +01:00

224 lines
9.9 KiB
Python

"""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