Draw dark and light posters from Esri; keep no poster whose picture failed
CARTO's basemaps now need an API key and answer every tile with an "API KEY REQUIRED" picture under a 200, so the dark and light backgrounds and the world locator showed that text. They now use Esri's grey canvases, which need no key and draw to zoom 16; each provider names its deepest zoom, and a race poster resolves its position once, capped to it, for the map, the projected track and the locator alike. One tile stitcher replaces three copies and refuses a map whose tiles are all the same picture: a provider's placeholder is said in the log, not drawn. A race poster, a thumb or a season poster whose map or photo failed is served but no longer kept, so the next ask renders it again; race posters carry a render version in their file name, so those drawn over CARTO's placeholder are rendered again. Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
This commit is contained in:
@@ -141,8 +141,8 @@ 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, OpenStreetMap and CARTO.
|
||||
* Race schedules from [Jolpica](https://github.com/jolpica/jolpica-f1); poster backgrounds from Esri (World Imagery
|
||||
and the grey canvases) and OpenStreetMap.
|
||||
|
||||
## Disclaimer
|
||||
|
||||
|
||||
@@ -49,8 +49,8 @@
|
||||
<select id="bg">
|
||||
<option value="aerial">aerial: Esri satellite imagery (the default)</option>
|
||||
<option value="osm">osm: OpenStreetMap street map</option>
|
||||
<option value="dark">dark: Carto Dark Matter</option>
|
||||
<option value="light">light: Carto Positron</option>
|
||||
<option value="dark">dark: Esri Dark Gray Canvas</option>
|
||||
<option value="light">light: Esri Light Gray Canvas</option>
|
||||
<option value="none">none: plain black, no tiles (fastest)</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
+86
-72
@@ -12,6 +12,7 @@ Output is cached under cache/posters/ keyed by (season, round, layout_slug)
|
||||
so cold paths stay cheap.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
@@ -37,31 +38,42 @@ 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" # CartoDB Dark Matter — minimalist black-and-grey map
|
||||
LIGHT = "light" # CartoDB Positron — minimalist light/grey map
|
||||
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.
|
||||
# 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,
|
||||
},
|
||||
BackgroundStyle.OSM: {
|
||||
"url": "https://tile.openstreetmap.org/{z}/{x}/{y}.png",
|
||||
"attribution": "© OpenStreetMap contributors",
|
||||
"max_zoom": 19,
|
||||
},
|
||||
BackgroundStyle.DARK: {
|
||||
"url": "https://basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png",
|
||||
"attribution": "© CartoDB, © OpenStreetMap contributors",
|
||||
"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,
|
||||
},
|
||||
BackgroundStyle.LIGHT: {
|
||||
"url": "https://basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png",
|
||||
"attribution": "© CartoDB, © OpenStreetMap contributors",
|
||||
"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,
|
||||
},
|
||||
}
|
||||
|
||||
# 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.
|
||||
@@ -198,6 +210,50 @@ class PostersService:
|
||||
y = (1.0 - math.log(math.tan(lat_rad) + 1.0 / math.cos(lat_rad)) / math.pi) / 2.0 * n
|
||||
return x, y
|
||||
|
||||
@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.
|
||||
|
||||
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."""
|
||||
provider = TILE_PROVIDERS[style]
|
||||
canvas = Image.new("RGB", ((tx_hi - tx_lo) * 256, (ty_hi - ty_lo) * 256), BG)
|
||||
bodies = set()
|
||||
fetched = 0
|
||||
for tx in range(tx_lo, tx_hi):
|
||||
for ty in range(ty_lo, ty_hi):
|
||||
x = tx % (2 ** zoom) if wrap_x else tx
|
||||
if not (0 <= ty < 2 ** zoom):
|
||||
continue
|
||||
url = provider["url"].format(z=zoom, x=x, y=ty)
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": TILE_USER_AGENT})
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
body = resp.read()
|
||||
tile = Image.open(io.BytesIO(body)).convert("RGB")
|
||||
canvas.paste(tile, ((tx - tx_lo) * 256, (ty - ty_lo) * 256))
|
||||
bodies.add(hashlib.sha256(body).digest())
|
||||
fetched += 1
|
||||
except Exception as e:
|
||||
logger.warning(f"Tile fetch failed {style.value} z={zoom} x={x} y={ty}: {e}")
|
||||
if not fetched:
|
||||
return None
|
||||
if fetched > 1 and len(bodies) == 1:
|
||||
logger.error(f"Every {style.value} tile at z={zoom} is the same picture: the provider answers a "
|
||||
f"placeholder ({provider['url'].split('/')[2]}), 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)
|
||||
@@ -213,24 +269,8 @@ class PostersService:
|
||||
tile_x_hi = (left + POSTER_W + 255) // 256
|
||||
tile_y_hi = (top + POSTER_H + 255) // 256
|
||||
|
||||
canvas_w = (tile_x_hi - tile_x_lo) * 256
|
||||
canvas_h = (tile_y_hi - tile_y_lo) * 256
|
||||
canvas = Image.new("RGB", (canvas_w, canvas_h), BG)
|
||||
|
||||
any_ok = False
|
||||
for tx in range(tile_x_lo, tile_x_hi):
|
||||
for ty in range(tile_y_lo, tile_y_hi):
|
||||
url = provider["url"].format(z=zoom, x=tx, y=ty)
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": TILE_USER_AGENT})
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
tile = Image.open(io.BytesIO(resp.read())).convert("RGB")
|
||||
canvas.paste(tile, ((tx - tile_x_lo) * 256, (ty - tile_y_lo) * 256))
|
||||
any_ok = True
|
||||
except Exception as e:
|
||||
logger.warning(f"Tile fetch failed {style.value} z={zoom} x={tx} y={ty}: {e}")
|
||||
|
||||
if not any_ok:
|
||||
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
|
||||
@@ -292,34 +332,15 @@ class PostersService:
|
||||
viewer a "here's the region" anchor. A marker (red dot + white ring)
|
||||
is drawn over the exact spot."""
|
||||
zoom = 5
|
||||
# Use the same stitcher with a custom canvas target.
|
||||
provider = TILE_PROVIDERS[BackgroundStyle.DARK]
|
||||
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
|
||||
canvas = Image.new("RGB", ((tx1 - tx0) * 256, (ty1 - ty0) * 256), BG)
|
||||
any_ok = False
|
||||
for tx in range(tx0, tx1):
|
||||
for ty in range(ty0, ty1):
|
||||
# Wrap longitude tiles (world is cyclic at zoom 2 = 4 tiles wide)
|
||||
wrapped_x = tx % (2 ** zoom)
|
||||
if wrapped_x < 0:
|
||||
wrapped_x += 2 ** zoom
|
||||
if not (0 <= ty < 2 ** zoom):
|
||||
continue
|
||||
url = provider["url"].format(z=zoom, x=wrapped_x, y=ty)
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": TILE_USER_AGENT})
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
tile = Image.open(io.BytesIO(resp.read())).convert("RGB")
|
||||
canvas.paste(tile, ((tx - tx0) * 256, (ty - ty0) * 256))
|
||||
any_ok = True
|
||||
except Exception as e:
|
||||
logger.warning(f"Locator tile fail {tx},{ty}: {e}")
|
||||
if not any_ok:
|
||||
# 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)
|
||||
@@ -441,18 +462,20 @@ class PostersService:
|
||||
logger.error(f"Layout not resolved for {grand_prix_name} {season}")
|
||||
return None
|
||||
|
||||
cache_key = f"{season}-{round_num:02d}-{layout.slug}-{bg.value}.png"
|
||||
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()
|
||||
|
||||
# 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
|
||||
geo = None
|
||||
if bg is not BackgroundStyle.NONE:
|
||||
geo = self._resolve_circuit_geo(grand_prix_name, season)
|
||||
geo = self._capped(self._resolve_circuit_geo(grand_prix_name, season), bg)
|
||||
if geo:
|
||||
lat, lon, zoom = geo
|
||||
map_bg = self._fetch_map_background(lat, lon, zoom, bg)
|
||||
map_bg = self._fetch_map_background(*geo, bg)
|
||||
|
||||
if map_bg is not None:
|
||||
# Dim the underlying map so the white track + heading text stay legible.
|
||||
@@ -487,9 +510,7 @@ class PostersService:
|
||||
try:
|
||||
# GeoJSON is lazy-loaded — trigger the read before pulling coords.
|
||||
layout.load_geo_json_data()
|
||||
projected = self._draw_track_projected(
|
||||
img, layout.coordinates, *self._resolve_circuit_geo(grand_prix_name, season)
|
||||
)
|
||||
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}")
|
||||
|
||||
@@ -508,7 +529,6 @@ class PostersService:
|
||||
# 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:
|
||||
geo = self._resolve_circuit_geo(grand_prix_name, season)
|
||||
if geo:
|
||||
lat, lon, _ = geo
|
||||
locator = self._render_world_locator(lat, lon, size=140)
|
||||
@@ -526,7 +546,9 @@ class PostersService:
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, "PNG", optimize=True)
|
||||
data = buf.getvalue()
|
||||
cache_path.write_bytes(data)
|
||||
if bg is BackgroundStyle.NONE or map_bg is not None:
|
||||
# A poster whose map failed is served, not kept: the next ask renders it again
|
||||
cache_path.write_bytes(data)
|
||||
return data
|
||||
|
||||
# ------------------------------------------------------------------ session thumb (16:9)
|
||||
@@ -541,20 +563,8 @@ class PostersService:
|
||||
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 = Image.new("RGB", ((tx1 - tx0) * 256, (ty1 - ty0) * 256), BG)
|
||||
any_ok = False
|
||||
for tx in range(tx0, tx1):
|
||||
for ty in range(ty0, ty1):
|
||||
url = provider["url"].format(z=zoom, x=tx, y=ty)
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": TILE_USER_AGENT})
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
tile = Image.open(io.BytesIO(resp.read())).convert("RGB")
|
||||
canvas.paste(tile, ((tx - tx0) * 256, (ty - ty0) * 256))
|
||||
any_ok = True
|
||||
except Exception as e:
|
||||
logger.warning(f"Landscape tile fail {style.value} z={zoom} x={tx} y={ty}: {e}")
|
||||
if not any_ok:
|
||||
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))
|
||||
@@ -643,7 +653,9 @@ class PostersService:
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, "PNG", optimize=True)
|
||||
data = buf.getvalue()
|
||||
cache_path.write_bytes(data)
|
||||
if map_bg is not None:
|
||||
# A thumb whose aerial failed is served, not kept: the next ask renders it again
|
||||
cache_path.write_bytes(data)
|
||||
return data
|
||||
|
||||
# ------------------------------------------------------------------ kometa metadata
|
||||
@@ -784,5 +796,7 @@ class PostersService:
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, "PNG", optimize=True)
|
||||
data = buf.getvalue()
|
||||
cache_path.write_bytes(data)
|
||||
if bg is not None:
|
||||
# A poster whose photo failed is served, not kept: the next ask renders it again
|
||||
cache_path.write_bytes(data)
|
||||
return data
|
||||
|
||||
Reference in New Issue
Block a user