Files
f1-circuits/posters_service.py
T
jschoubben 4362e2d10b Draw a picked photo only with bg=photo, keep bg=satellite to aerial imagery
The operator judged the Commons-photo poster unfit as a default: its crop lands beside the circuit and shows the
track only as an inset. bg=satellite is now the national aerial photo, else EOxCloudless (or the dark map where
"use": "map" is set); the new bg=photo draws the layout's picked photo and without one falls back to what
bg=satellite draws. A picks entry may hold the photo fields, "use": "map", or both; an unknown use and incomplete
photo fields are refused at load. The smallest width is 400 px so the full credit line stays readable, and the
ASCII credit header spells out ß, æ, ø, œ and đ so names stay readable.

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

913 lines
43 KiB
Python

"""Plex-style F1 race posters, season posters and session thumbnails (docs/posters.md).
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.
Which source, which options and which keys: poster_sources.py and poster_options.py (standard library only).
"""
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 dataclasses import dataclass
from pathlib import Path
from typing import Callable, Optional
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
logger = logging.getLogger(__name__)
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: the thumb's bar and the locator's marker
WHITE = (245, 245, 245)
GREY = (160, 160, 170)
# Kometa F1 builder episode numbering — keep in sync with Kometa's modules/meta.py.
# Each value is (display_label, url_slug) used for thumb generation + filename.
_SESSION_STD = {
1: ("Free Practice 1", "fp1"),
2: ("Free Practice 2", "fp2"),
3: ("Free Practice 3", "fp3"),
4: ("Pre-Qualifying Buildup", "pre-qualifying"),
5: ("Qualifying", "qualifying"),
6: ("Post-Qualifying", "post-qualifying"),
7: ("Pre-Race Buildup", "pre-race"),
8: ("Race", "race"),
9: ("Post-Race", "post-race"),
10: ("Highlights", "highlights"),
}
_SESSION_SPRINT = {
1: ("Free Practice 1", "fp1"),
2: ("Pre-Sprint-Qualifying Buildup", "pre-sprint-qualifying"),
3: ("Sprint Qualifying", "sprint-qualifying"),
4: ("Post-Sprint-Qualifying", "post-sprint-qualifying"),
5: ("Pre-Sprint Buildup", "pre-sprint"),
6: ("Sprint", "sprint"),
7: ("Post-Sprint", "post-sprint"),
8: ("Pre-Qualifying Buildup", "pre-qualifying"),
9: ("Qualifying", "qualifying"),
10: ("Post-Qualifying", "post-qualifying"),
11: ("Pre-Race Buildup", "pre-race"),
12: ("Race", "race"),
13: ("Post-Race", "post-race"),
14: ("Highlights", "highlights"),
15: ("Bonus Content", "bonus"),
}
# Display-label lookup for the thumb renderer (slug → label, deduped across formats).
SESSION_LABEL_BY_SLUG = {slug: label for d in (_SESSION_STD, _SESSION_SPRINT) for label, slug in d.values()}
CHECKER_H = 60
CHECKER_SQ = 30
# 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}
# 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
]
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,
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.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()
@staticmethod
def _load_zoom_lookup() -> dict:
from ergast_service import slugify
path = Path("f1-locations.json")
if not path.exists():
return {}
try:
data = json.loads(path.read_text())
except Exception as e:
logger.warning(f"Could not load f1-locations.json: {e}")
return {}
return {slugify(entry["name"]): entry for entry in data if "name" in entry}
# ------------------------------------------------------------------ inputs
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 _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)
while size > 18 and draw.textlength(text, font) > width - 80: # shrink to fit
size -= 4
font = self._font(size)
draw.text(((width - draw.textlength(text, font)) / 2, y), text, font=font, fill=fill)
@staticmethod
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 _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)
# 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 _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 _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))
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 _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
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)
# 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 in ("satellite", "photo"):
layout_key = f"{circuit.locality.country.slug}/{circuit.locality.slug}/{circuit.slug}/{layout.slug}"
entry = self.picks(CIRCUIT_PICKS).get(layout_key) # the photo fields, "use": "map", or both
chain = ps.photo_source if options.bg == "photo" else ps.satellite_source
chosen = chain(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
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,
}
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:
self._draw_thumb_texts(draw, texts, show, accent, CHECKER_H if options.checker else 0)
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
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
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
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:
"""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:",
]
for season in range(first_season, last_season + 1):
races = self.ergast._fetch_season_schedule(season)
lines.append(f' "Season {season}":')
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{version}")
if not races:
continue
lines.append(" seasons:")
for race in races:
try:
round_num = int(race["round"])
name = race["raceName"]
except (KeyError, ValueError):
continue
lines.append(f" {round_num}:")
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():
lines.append(f" {ep_num}:")
lines.append(f" url_poster: {self.BASE_URL}/posters/session/{quote(name)}/{season}/"
f"{slug}.png{version}")
lines.append("")
return "\n".join(lines)