Files
f1-circuits/poster_options.py
T
jschoubben 1cefc6dd52 Keep asked-for texts clear of the credit band; answer review round 1
At 400 to 640 px the credit band, held to 12 px after scaling, covered the date, the circuit line, the session
label and the season's subtitle. The band is now laid out first and every bottom text, the photo inset and the
poster's dark band are lifted by as much as it would cover them, which at full size is nothing, so classic draws
as before; the bottom checker is drawn last again, over the track's end. A first render now draws from the layer
as kept, so it matches every later render of its key, and the ETag is weak all the same. A Commons file's SHA-1
is kept beside the layers and asked once, so photo pictures need no Commons request after a restart. The USGS
credit carries no prefix, and /licences names a layout switched to the map among OpenStreetMap's uses.

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

225 lines
10 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", "photo", "osm", "dark", "light", "none") # photo is never a style's default
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 = 400 # the full credit line stays readable
# 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:
"""If-None-Match against our ETag by the weak comparison: W/ is ignored on both sides."""
tags = [tag.strip().removeprefix("W/") for tag in (if_none_match or "").split(",")]
return etag.removeprefix("W/") 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