Match races by circuit id (Qatar 404), keep schedules, fix posters, add the example site #7

Merged
mesh-tools merged 20 commits from fix/match-circuits-by-id into master 2026-11-27 09:56:42 +00:00
2 changed files with 28 additions and 56 deletions
Showing only changes of commit 6e62440102 - Show all commits
+6 -5
View File
@@ -131,11 +131,12 @@ rate limit and kept in `cache/jolpica/`; a throttled or failed fetch is said in
## Caching
Everything 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), map tiles in
`cache/tiles/` (30 days), and every poster and thumbnail in `cache/posters/` once its map or photo 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.
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.
## Checks
+22 -51
View File
@@ -19,7 +19,6 @@ import logging
import math
import os
import threading
import time
import urllib.parse
import urllib.request
from concurrent.futures import ThreadPoolExecutor
@@ -78,9 +77,6 @@ TILE_PROVIDERS = {
},
}
# Tiles are kept on disk under cache/tiles/<style>/<z>/<x>/<y> and used for this long: every poster,
# thumb and locator of a circuit draws on the same tiles (OpenStreetMap's policy asks for at least a week).
TILE_KEEP_SECONDS = 30 * 24 * 3600
# 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] = {}
@@ -174,7 +170,6 @@ class PostersService:
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)
self.tile_dir = Path("cache/tiles")
# 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.
@@ -244,76 +239,50 @@ class PostersService:
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.
"""Fetch the tiles [tx_lo, tx_hi) x [ty_lo, ty_hi) of a style at a zoom onto one canvas, in parallel.
None when no tile came, 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, and a poster over it is worse than one over black."""
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) -> tuple[Optional[bytes], bool]:
"""A tile's bytes and whether they came from the network (False: from disk)."""
path = self.tile_dir / style.value / str(zoom) / str(x) / str(y)
try:
if time.time() - path.stat().st_mtime < TILE_KEEP_SECONDS:
return path.read_bytes(), False
except OSError:
pass
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(), True
return resp.read()
except Exception as e:
logger.warning(f"Tile fetch failed {style.value} z={zoom} x={x} y={y}: {e}")
return None, False
return None
with ThreadPoolExecutor(max_workers=provider["concurrency"]) as pool:
bodies_in_order = list(pool.map(lambda t: tile_body(t[2], t[1]), wanted))
bodies = list(pool.map(lambda t: tile_body(t[2], t[1]), wanted))
# The tiles fetched now are judged on their own, apart from those read from disk: two or more that
# are all one picture, matching no tile kept before (a real uniform tile, such as open sea, does),
# are a placeholder, and the map fails whole: nothing drawn, nothing kept.
on_disk = {hashlib.sha256(body).digest() for body, from_network in bodies_in_order if body and not from_network}
from_net = [hashlib.sha256(body).digest() for body, from_network in bodies_in_order if body and from_network]
if len(from_net) > 1 and len(set(from_net)) == 1 and from_net[0] not in on_disk:
logger.error(f"Every {style.value} tile fetched at z={zoom} is the same picture: the provider answers a "
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
drawn = 0
new_tiles = []
for (tx, ty, x), (body, from_network) in zip(wanted, bodies_in_order):
if body is None:
continue
missing = 0
for (tx, ty, x), body in zip(wanted, bodies):
try:
tile = Image.open(io.BytesIO(body)).convert("RGB")
except Exception as e:
logger.warning(f"Tile unreadable {style.value} z={zoom} x={x} y={ty}: {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))
drawn += 1
if from_network:
new_tiles.append((x, ty, body))
if not drawn:
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
# Kept only now: a placeholder never reaches the disk
for x, y, body in new_tiles:
self._keep_tile(style, zoom, x, y, body)
return canvas
def _keep_tile(self, style: BackgroundStyle, zoom: int, x: int, y: int, body: bytes) -> None:
path = self.tile_dir / style.value / str(zoom) / str(x) / str(y)
try:
path.parent.mkdir(parents=True, exist_ok=True)
self._keep(path, body)
except OSError as e:
logger.warning(f"Could not keep tile {path}: {e}")
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)
@@ -541,6 +510,7 @@ class PostersService:
# 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)
@@ -616,10 +586,11 @@ class PostersService:
buf = io.BytesIO()
img.save(buf, "PNG")
data = buf.getvalue()
if bg is BackgroundStyle.NONE or map_bg is not None:
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, bg is BackgroundStyle.NONE or map_bg is not None
return data, whole
# ------------------------------------------------------------------ session thumb (16:9)