Posters from licensed sources only: kept layers, options, credits on every picture #8
@@ -4,3 +4,6 @@ __pycache__/
|
||||
cache/
|
||||
.idea/
|
||||
.venv-site/
|
||||
# The poster service's kept layers and finished pictures, when run from here
|
||||
/layers/
|
||||
/posters/
|
||||
|
||||
@@ -24,10 +24,22 @@ How posters are made (sources and their licences, kept layers, options, credits)
|
||||
| `GET /circuits/{country}/{locality}/{circuit}/layout/{layout}/{format}` | the layout's file: `geojson`, `svg` or `png` |
|
||||
| `GET /tracks/{country}/{locality}/{circuit}/year/{year}/{format}` | the layout the circuit used that year |
|
||||
| `GET /grand-prix/{race}/{season}/{format}` | the layout a race ran on, such as `/grand-prix/Qatar Grand Prix/2025/geojson` |
|
||||
| `GET /posters/race/{race}/{season}.png?bg=…` | a 1000×1500 race poster; `bg` is `aerial` (default), `osm`, `dark`, `light` or `none` |
|
||||
| `GET /posters/season/{season}.png` | a 1000×1500 season poster |
|
||||
| `GET /posters/session/{race}/{season}/{session}.png` | a 1920×1080 thumbnail for one session, such as `fp1`, `qualifying`, `sprint` or `race` |
|
||||
| `GET /posters/race/{race}/{season}.png?…` | a 1000×1500 race poster: the round, the race's name and date and its track over a picture of its circuit |
|
||||
| `GET /posters/season/{season}.png?…` | a 1000×1500 season poster: the year over a picked photo of that season's cars, or over black |
|
||||
| `GET /posters/session/{race}/{season}/{session}.png?…` | a 1920×1080 thumbnail for one session, such as `fp1`, `qualifying`, `sprint` or `race` |
|
||||
| `GET /kometa/formula-1-metadata.yml` | [Kometa](https://kometa.wiki/) metadata that sets these posters on a Plex Formula 1 library |
|
||||
| `GET /licences` | every source a picture may be made from: its licence, its credit and its terms, and how a picture's licence follows from them |
|
||||
|
||||
The three picture routes take the same options as query parameters ([docs/posters.md](docs/posters.md) lists
|
||||
them): `style` (`classic`, `minimal`), `bg` (`satellite`, its alias `aerial`, `osm`, `dark`, `light`, `none`),
|
||||
`photo` (`natural`, `bw`), `show` (a comma list of `wordmark`, `round`, `name`, `subtitle`, `date`, `circuit`,
|
||||
`locality`, `session`), `locator` and `checker` (`on`, `off`), `track` (`off`, or a colour with an optional width,
|
||||
`#ffffff,6`), `dim` (0 to 1), `accent` (a colour), `width` (200 up to the picture's own) and `format` (`png`, `jpg`,
|
||||
`webp`). An unknown option or value is answered 422, naming it. `bg=satellite` takes the layout's picked Wikimedia
|
||||
Commons photo, else the national aerial photo (USGS in the United States, PDOK in the Netherlands, IGN in France),
|
||||
else EOxCloudless; [circuits/photos.json](circuits/photos.json) holds the picks, and `{"use": "map"}` there makes a
|
||||
layout draw the dark map instead of EOxCloudless. Every picture carries the credit line of its sources at its
|
||||
bottom and in `X-Credits`, its licence in `X-License` (it follows its sources), and `Link: </licences>; rel="license"`.
|
||||
|
||||
A race is named as [Jolpica](https://github.com/jolpica/jolpica-f1) (the Ergast API's successor) names it in
|
||||
its schedule, and its circuit is found by Jolpica's circuit id (`ergastId` in `circuits.json`), never by the
|
||||
@@ -133,18 +145,26 @@ rate limit and kept in `cache/jolpica/`; a throttled or failed fetch is said in
|
||||
|
||||
## Caching
|
||||
|
||||
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.
|
||||
Race schedules from Jolpica are kept in `cache/jolpica/` (a season that is over for good, the running one for six
|
||||
hours). What a picture needs from the network is a layer, kept for good in `layers/` (the module's `layers` directory,
|
||||
backed up and fetched again if lost): the map picture of one source around a layout, a picked photo cropped to the
|
||||
picture, the world locator and the track's outline. A layer is kept only whole, when every tile came and they are
|
||||
not all one picture. Every finished picture is kept in `posters/` under a key of its route, its options and its
|
||||
layers, at most 2 GB, the least recently used going first; a second season of a circuit draws from the kept layers
|
||||
and fetches nothing. A picture whose map or photo did not arrive is served without it, kept nowhere, and sent with
|
||||
five minutes' `Cache-Control` and no `ETag`.
|
||||
|
||||
Clients keep an address that carries the render version (`?v=r3`, as the Kometa file writes it) for good
|
||||
(`immutable`); any other address a day, then ask again with its `ETag` and get a 304 while it is unchanged. Every
|
||||
request the service makes carries the User-Agent `f1-circuits/<version> (+<its public address>)`. OpenStreetMap tiles
|
||||
are fetched only when a picture asks for them, at most two at once; Wikimedia Commons is asked one request at a time.
|
||||
|
||||
## Checks
|
||||
|
||||
`merge-check.sh` runs before a change merges: every Python file the service ships must parse, and the tests in
|
||||
`tests/` must pass (every circuit has one unique `ergastId`, a race resolves by it, a failed Jolpica fetch is never
|
||||
kept, every link in this README leads to a file).
|
||||
kept, every link in this README leads to a file; a poster's satellite source,
|
||||
credits and licence, its options, keys and cache headers, and the picture store's cap).
|
||||
|
||||
## Acknowledgment
|
||||
|
||||
@@ -152,8 +172,9 @@ 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
|
||||
and the grey canvases) and OpenStreetMap.
|
||||
* Race schedules from [Jolpica](https://github.com/jolpica/jolpica-f1) (CC BY-NC-SA 4.0); the posters' pictures from
|
||||
Wikimedia Commons, USGS, PDOK (Beeldmateriaal Nederland), IGN, EOX (EOxCloudless) and OpenStreetMap, each under
|
||||
its licence and with its credit: `/licences` and [docs/posters.md](docs/posters.md).
|
||||
|
||||
## Disclaimer
|
||||
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
"""Who this service is to the outside: its version, its public address and the User-Agent it sends.
|
||||
|
||||
Standard library only: the Jolpica client, the poster sources and the API share it.
|
||||
"""
|
||||
import os
|
||||
|
||||
# The API's own version (cdn-api.py's FastAPI app says the same).
|
||||
APP_VERSION = "1.0.0"
|
||||
|
||||
# The address this service is reached at, which the Kometa metadata links every poster to and every outgoing
|
||||
# request names. 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.
|
||||
PUBLIC_BASE_URL = os.environ.get("F1_CIRCUITS_BASE_URL", "https://f1-circuits.zurag.be").rstrip("/")
|
||||
|
||||
# Every outgoing request carries it (Jolpica, the map and photo sources): the app's name and its public address,
|
||||
# never a person's address.
|
||||
USER_AGENT = f"f1-circuits/{APP_VERSION} (+{PUBLIC_BASE_URL})"
|
||||
+83
-45
@@ -1,32 +1,42 @@
|
||||
import hashlib
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Request, Response
|
||||
from fastapi.responses import FileResponse, Response as FastAPIResponse, PlainTextResponse
|
||||
from fastapi.openapi.docs import get_swagger_ui_html
|
||||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, PlainTextResponse
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
import logging
|
||||
|
||||
# Import our CircuitService
|
||||
from app_info import APP_VERSION
|
||||
from circuits_service import CircuitService, Format
|
||||
from posters_service import PostersService, BackgroundStyle
|
||||
from posters_service import PostersService, Rendered
|
||||
import poster_options
|
||||
import poster_sources
|
||||
from access_log import log_request
|
||||
from models.track_layout import TrackLayout
|
||||
|
||||
# Initialize FastAPI app
|
||||
# The unofficial-use disclaimer for the Formula 1 marks, at the foot of / and /docs (and of the example site).
|
||||
DISCLAIMER = ("This service is unofficial and is not associated in any way with the Formula 1 companies. F1, FORMULA "
|
||||
"ONE, FORMULA 1, FIA FORMULA ONE WORLD CHAMPIONSHIP, GRAND PRIX, and related marks are trademarks of "
|
||||
"Formula One Licensing B.V.")
|
||||
|
||||
# Initialize FastAPI app; /docs is served below, with the disclaimer at its foot
|
||||
app = FastAPI(
|
||||
title="F1 Track Layouts API",
|
||||
description="API serving F1 track layout images, vectors and GeoJSON files",
|
||||
version="1.0.0"
|
||||
version=APP_VERSION,
|
||||
docs_url=None,
|
||||
)
|
||||
|
||||
# Add CORS middleware
|
||||
# Add CORS middleware. The example pages, opened from another origin, read a picture's credits and licence.
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
expose_headers=["X-Credits", "X-License", "Link", "ETag"],
|
||||
)
|
||||
|
||||
# Configure logging
|
||||
@@ -84,11 +94,29 @@ async def root():
|
||||
"/posters/season/{season}.png",
|
||||
"/posters/session/{grand_prix_name}/{season}/{session_slug}.png",
|
||||
"/kometa/formula-1-metadata.yml",
|
||||
"/licences",
|
||||
],
|
||||
"examples": "/examples/",
|
||||
"disclaimer": DISCLAIMER,
|
||||
}
|
||||
|
||||
|
||||
@app.get("/docs", include_in_schema=False)
|
||||
async def docs() -> HTMLResponse:
|
||||
"""The OpenAPI docs, with the disclaimer at their foot."""
|
||||
page = get_swagger_ui_html(openapi_url=app.openapi_url, title=f"{app.title} - docs").body.decode()
|
||||
footer = (f'<footer style="font-family: sans-serif; font-size: 12px; color: #666; margin: 2em; '
|
||||
f'text-align: center">{DISCLAIMER}</footer>')
|
||||
return HTMLResponse(page.replace("</body>", f"{footer}</body>"))
|
||||
|
||||
|
||||
@app.get("/licences")
|
||||
async def get_licences():
|
||||
"""Every source a picture may be made from: its licence, its credit and its terms' address, and how a picture's
|
||||
licence follows from them."""
|
||||
return poster_sources.licences()
|
||||
|
||||
|
||||
# The example site: one page per area of the API, each calling the routes above (examples/index.html).
|
||||
app.mount(
|
||||
"/examples",
|
||||
@@ -100,66 +128,76 @@ app.mount(
|
||||
# The poster routes are plain defs, not async: a render fetches map tiles and a schedule and draws for
|
||||
# seconds, so it runs in the threadpool instead of holding up every other request on the event loop.
|
||||
|
||||
def poster_response(request: Request, png: bytes, kept: bool) -> Response:
|
||||
"""A stored poster: clients keep it a day, then ask again with its ETag and get a 304 while it is
|
||||
unchanged, so a poster whose look changed reaches them within a day, not a year. A poster whose map
|
||||
or photo failed is kept by clients for five minutes, with no ETag, so they ask again soon."""
|
||||
if not kept:
|
||||
return FastAPIResponse(content=png, media_type="image/png", headers={"Cache-Control": "public, max-age=300"})
|
||||
etag = '"' + hashlib.sha256(png).hexdigest()[:32] + '"'
|
||||
headers = {"Cache-Control": "public, max-age=86400", "ETag": etag}
|
||||
if etag in [tag.strip().removeprefix("W/") for tag in request.headers.get("if-none-match", "").split(",")]:
|
||||
POSTER_OPTIONS_DOC = """Options are query parameters, the same on every poster route (docs/posters.md); an unknown option
|
||||
or value is answered 422, naming it: `style` (classic, minimal), `bg` (satellite, its alias aerial, osm, dark,
|
||||
light, none), `photo` (natural, bw), `show` (a comma list of wordmark, round, name, subtitle, date, circuit,
|
||||
locality, session), `locator` and `checker` (on, off), `track` (off, or #rrggbb with an optional width:
|
||||
#ffffff,6), `dim` (0 to 1), `accent` (#rrggbb), `width` (200 up to the frame's), `format` (png, jpg, webp), and
|
||||
`v`, the render version, which the Kometa file adds so clients keep the picture for good."""
|
||||
|
||||
|
||||
def render_poster(request: Request, kind: str, grand_prix_name: Optional[str] = None, season: Optional[int] = None,
|
||||
session_slug: Optional[str] = None) -> Response:
|
||||
"""A picture with its credits, its licence and what clients may keep of it.
|
||||
|
||||
An address with the current render version (?v=) is kept for good; any other a day, then asked again with its
|
||||
ETag (a 304 while it is unchanged); a picture served without its map or photo five minutes, with no ETag."""
|
||||
try:
|
||||
options = poster_options.parse_options(request.query_params.multi_items(), kind)
|
||||
except poster_options.OptionError as e:
|
||||
return JSONResponse(status_code=422, content={"detail": str(e)})
|
||||
try:
|
||||
rendered: Optional[Rendered] = posters_service.render(kind, options, grand_prix_name, season, session_slug)
|
||||
except poster_sources.LicenceClash as e:
|
||||
logger.error(f"Picture refused, {kind} {grand_prix_name} {season} {session_slug}: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"Picture refused: {e}")
|
||||
if rendered is None:
|
||||
what = " ".join(str(part) for part in (grand_prix_name, season, session_slug) if part is not None)
|
||||
raise HTTPException(status_code=404, detail=f"No {kind} picture available for {what}")
|
||||
etag = '"' + rendered.name.split(".")[0][:32] + '"'
|
||||
headers = poster_options.cache_headers(rendered.kept, options.versioned, etag)
|
||||
headers.update({"X-Credits": poster_sources.ascii_header(rendered.credit), "X-License": rendered.licence,
|
||||
"Link": '</licences>; rel="license"'})
|
||||
if rendered.kept and poster_options.etag_matches(request.headers.get("if-none-match", ""), etag):
|
||||
return Response(status_code=304, headers=headers)
|
||||
return FastAPIResponse(content=png, media_type="image/png", headers=headers)
|
||||
return Response(content=rendered.data, media_type=rendered.media_type, headers=headers)
|
||||
|
||||
|
||||
@app.get("/posters/race/{grand_prix_name}/{season}.png")
|
||||
def get_race_poster(request: Request, grand_prix_name: str, season: int, bg: BackgroundStyle = BackgroundStyle.AERIAL):
|
||||
"""Plex-ready 1000x1500 race poster (PNG). Cached on disk per (race, bg).
|
||||
|
||||
`?bg=` selects the backdrop:
|
||||
- aerial (default) — Esri World Imagery satellite at the circuit's coords
|
||||
- osm — OpenStreetMap Carto street-map at the circuit's coords
|
||||
- dark — Esri Dark Gray Canvas
|
||||
- light — Esri Light Gray Canvas
|
||||
- none — plain black background (skip tile fetch)
|
||||
"""
|
||||
rendered = posters_service.render_race_poster(grand_prix_name, season, bg=bg)
|
||||
if not rendered:
|
||||
raise HTTPException(status_code=404, detail=f"No poster available for {grand_prix_name} {season}")
|
||||
return poster_response(request, *rendered)
|
||||
@app.get("/posters/race/{grand_prix_name}/{season}.png", description=POSTER_OPTIONS_DOC)
|
||||
def get_race_poster(request: Request, grand_prix_name: str, season: int):
|
||||
"""Plex-ready 1000x1500 race poster: the round, the race's name and date and its track over a map or photo of
|
||||
its circuit."""
|
||||
return render_poster(request, "race", grand_prix_name, season)
|
||||
|
||||
|
||||
@app.get("/posters/season/{season}.png")
|
||||
@app.get("/posters/season/{season}.png", description=POSTER_OPTIONS_DOC)
|
||||
def get_season_poster(request: Request, season: int):
|
||||
"""Plex-ready 1000x1500 season poster (PNG). Cached on disk."""
|
||||
return poster_response(request, *posters_service.render_season_poster(season))
|
||||
"""Plex-ready 1000x1500 season poster: the year over a picked photo of that season's cars, or over black."""
|
||||
return render_poster(request, "season", season=season)
|
||||
|
||||
|
||||
@app.get("/posters/session/{grand_prix_name}/{season}/{session_slug}.png")
|
||||
@app.get("/posters/session/{grand_prix_name}/{season}/{session_slug}.png", description=POSTER_OPTIONS_DOC)
|
||||
def get_session_thumb(request: Request, grand_prix_name: str, season: int, session_slug: str):
|
||||
"""Plex episode-thumb (1920x1080) for a specific session of a race weekend.
|
||||
"""Plex episode-thumb (1920x1080) for one session of a race weekend.
|
||||
|
||||
`session_slug` is one of: fp1, fp2, fp3, pre-qualifying, qualifying,
|
||||
post-qualifying, pre-race, race, post-race, highlights, pre-sprint,
|
||||
sprint, post-sprint, pre-sprint-qualifying, sprint-qualifying,
|
||||
post-sprint-qualifying, bonus.
|
||||
"""
|
||||
rendered = posters_service.render_session_thumb(grand_prix_name, season, session_slug)
|
||||
if not rendered:
|
||||
raise HTTPException(status_code=404, detail=f"No session thumb for {grand_prix_name} {season} {session_slug}")
|
||||
return poster_response(request, *rendered)
|
||||
return render_poster(request, "session", grand_prix_name, season, session_slug)
|
||||
|
||||
|
||||
@app.get("/kometa/formula-1-metadata.yml")
|
||||
def get_kometa_metadata():
|
||||
"""Generate a Kometa-compatible metadata YAML for the Formula 1 library.
|
||||
|
||||
One entry per F1 season from 1950..current+1. Each entry:
|
||||
Its first lines say where its data comes from (Jolpica, CC BY-NC-SA 4.0). One entry per F1 season from
|
||||
1950..current+1. Each entry:
|
||||
- uses Kometa's f1_season builder for round/episode names
|
||||
- sets url_poster on the show (per-season hero from files-api)
|
||||
- sets url_poster on each Plex 'season' (== each F1 round) from the
|
||||
f1-circuits race poster endpoint
|
||||
- sets url_poster on the show (the season poster)
|
||||
- sets url_poster on each Plex 'season' (== each F1 round) from the race poster route, and on each episode
|
||||
from the session thumbnail route; every address carries ?v=<render version>
|
||||
|
||||
Kometa harmlessly skips shows / seasons that don't exist in the Plex
|
||||
library, so we can emit the full schedule and let Kometa do the matching.
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"$comment": "The picked Wikimedia Commons aerial photo per layout (docs/posters.md, Picking photos). Key: the layout's path under circuits/ without extension, country/city/circuit/layout, such as \"belgium/spa/circuit-de-spa-francorchamps/1983-\". Value: {\"file\": the Commons title without \"File:\", \"licence\": its LicenseShortName (CC0, public domain, CC BY or CC BY-SA only), \"author\", \"credit\": \"Photo: <author>, <licence>, via Wikimedia Commons\", \"date\": YYYY[-MM[-DD]]}; or, instead of a photo, {\"use\": \"map\"}: that layout's bg=satellite then draws the dark OpenStreetMap map instead of EOxCloudless (a photo or a national aerial photo still comes first). Written by the picking tool, read by the poster service; a key starting with \"$\" is a note, not a pick."
|
||||
}
|
||||
+4
-1
@@ -9,6 +9,8 @@ from datetime import date
|
||||
from pathlib import Path
|
||||
from typing import Optional, TYPE_CHECKING
|
||||
|
||||
from app_info import USER_AGENT
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from circuits_service import CircuitService
|
||||
|
||||
@@ -112,7 +114,8 @@ class ErgastService:
|
||||
time.sleep(wait)
|
||||
self._last_request = time.monotonic()
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=self.REQUEST_TIMEOUT) as resp:
|
||||
request = urllib.request.Request(url, headers={'User-Agent': USER_AGENT})
|
||||
with urllib.request.urlopen(request, timeout=self.REQUEST_TIMEOUT) as resp:
|
||||
return json.loads(resp.read())['MRData']['RaceTable']['Races']
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code != 429 or attempt == self.RETRIES:
|
||||
|
||||
+4
-2
@@ -11,14 +11,16 @@
|
||||
# models it imports. Then the tests in tests/, which need the standard library only: every circuit in
|
||||
# circuits/circuits.json carries one unique ergastId, and a race's circuit resolves by that id, never by
|
||||
# its name; a failed Jolpica fetch is never kept, a season that is over is read from disk, a throttled
|
||||
# request is asked again.
|
||||
# request is asked again; a poster's options, keys, cache headers and store cap, its satellite source, credits and
|
||||
# licence (poster_options.py and poster_sources.py, standard library only).
|
||||
#
|
||||
# **Said, never passed silently**: the service's dependencies (service/requirements.txt) are the image's to
|
||||
# install, so the service is not started.
|
||||
set -eu
|
||||
|
||||
# Parsed, not compiled to files: a check leaves the tree as it found it.
|
||||
find cdn-api.py access_log.py circuits_service.py ergast_service.py posters_service.py models -name '*.py' -print0 |
|
||||
find cdn-api.py access_log.py app_info.py circuits_service.py ergast_service.py posters_service.py poster_options.py \
|
||||
poster_sources.py models -name '*.py' -print0 |
|
||||
xargs -0 python3 -c 'import ast, sys
|
||||
for f in sys.argv[1:]:
|
||||
ast.parse(open(f, encoding="utf-8").read(), f)
|
||||
|
||||
+27
-3
@@ -23,7 +23,7 @@
|
||||
"port": 8000,
|
||||
"protocol": "tcp",
|
||||
"from": "mesh",
|
||||
"why": "the track-layout CDN, the race posters and the Kometa metadata over http; its public name is a route grant and the proxy reaches it here. Kometa fetches the metadata and every poster by that public name"
|
||||
"why": "the track-layout CDN, the race posters, their licences and the Kometa metadata over http; its public name is a route grant and the proxy reaches it here. Kometa fetches the metadata and every poster by that public name"
|
||||
}
|
||||
],
|
||||
"data": {
|
||||
@@ -32,7 +32,19 @@
|
||||
"id": "cache",
|
||||
"path": "${dir:cache}",
|
||||
"class": "cache",
|
||||
"why": "the generated track layouts and posters, rebuilt on demand"
|
||||
"why": "the race schedules asked from Jolpica, asked again when lost"
|
||||
},
|
||||
{
|
||||
"id": "layers",
|
||||
"path": "${dir:layers}",
|
||||
"class": "rebuildable",
|
||||
"why": "the kept layers of the posters: the map pictures, picked photos, world locators and track outlines, fetched once and kept for good; fetched again if lost"
|
||||
},
|
||||
{
|
||||
"id": "posters",
|
||||
"path": "${dir:posters}",
|
||||
"class": "cache",
|
||||
"why": "the finished posters and thumbnails, at most 2 GB, drawn again from the layers on demand"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -48,6 +60,16 @@
|
||||
"type": "directory",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "layers",
|
||||
"type": "directory",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "posters",
|
||||
"type": "directory",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "site-env",
|
||||
"type": "file",
|
||||
@@ -67,7 +89,9 @@
|
||||
"${dir:state}/site.env"
|
||||
],
|
||||
"volumes": [
|
||||
"${dir:cache}:/app/cache"
|
||||
"${dir:cache}:/app/cache",
|
||||
"${dir:layers}:/app/layers",
|
||||
"${dir:posters}:/app/posters"
|
||||
],
|
||||
"restart-on": [
|
||||
"site-env"
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
"""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
|
||||
@@ -0,0 +1,307 @@
|
||||
"""Where every poster picture comes from, under which licence, and the credit each source asks for (docs/posters.md,
|
||||
Sources). Standard library only, so the merge check tests it as it is.
|
||||
|
||||
The satellite chain takes, per layout, the first source that has it: the layout's picked Wikimedia Commons photo,
|
||||
then the national aerial photo of the circuit's country, then EOxCloudless. The national credit lines and tile
|
||||
addresses were read from each provider's own pages and confirmed against real tiles on 2026-11-27:
|
||||
|
||||
- USGS: the service description of USGSImageryOnly (its copyright text is the credit; cached to level 16, 17 is a
|
||||
404); USGS-produced data are in the U.S. public domain.
|
||||
- PDOK: the WMTS capabilities of luchtfotorgb (Actueel_orthoHR, EPSG:3857, column before row); PDOK asks to refer
|
||||
to "het Samenwerkingsverband Beeldmateriaal en naar de CC-BY-licentie".
|
||||
- IGN: the Géoplateforme WMTS (Licence Ouverte / Etalab 2.0, whose credit needs the producer and the date of the
|
||||
last update). A yearly layer holds only the départements flown that year, so a frame near a border falls into a
|
||||
hole; the frozen mosaic of 2021-2023 covers all of France (every French layout's frame corners answered), and its
|
||||
dates never change.
|
||||
- EOX: the WMTS capabilities (s2cloudless_3857 is 2016, CC BY 4.0; the newest is 2025, CC BY-NC-SA 4.0); its
|
||||
levels go to 21, its own picture's detail stops at about 14 (2016) and 16 (2025).
|
||||
"""
|
||||
import dataclasses
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import unicodedata
|
||||
import urllib.parse
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Optional, Union
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MapSource:
|
||||
"""One tiled map source, in one year where it has years."""
|
||||
id: str # usgs, pdok, ign, eox, osm
|
||||
year: Optional[Union[int, str]] # the mosaic's year or years (EOX, IGN); None for a source without years
|
||||
tiles: str # the tile address, with {z}, {x} and {y}
|
||||
max_zoom: int # its deepest level: a picture never asks deeper
|
||||
slots: int # requests to its host at once, over every render side by side
|
||||
credit: str # drawn on every picture made from it
|
||||
tint: Optional[str] = None # its tiles recoloured when drawn (dark), whatever bg asked; None: as bg says
|
||||
|
||||
@property
|
||||
def host(self) -> str:
|
||||
return urllib.parse.urlsplit(self.tiles).hostname or ""
|
||||
|
||||
@property
|
||||
def key(self) -> str:
|
||||
"""The source and its year, as a layer key names them."""
|
||||
return f"{self.id}-{self.year if self.year is not None else 'current'}"
|
||||
|
||||
@property
|
||||
def share(self) -> Optional[str]:
|
||||
"""What it asks of a picture made from it: EOX's mosaics after 2016 are NC-SA; the others only a credit."""
|
||||
return NC_SA if self.id == "eox" and self.year != EOX_FREE_YEAR else None
|
||||
|
||||
|
||||
COMMONS = "commons" # the satellite chain's first link: the layout's picked Commons photo
|
||||
MAP_OVERRIDE = "map" # a layout's entry {"use": "map"}: its satellite background is the dark map, not EOX
|
||||
|
||||
# What a source asks of a picture made from it, beyond its credit: share-alike (a CC BY-SA photo) or
|
||||
# non-commercial share-alike (EOX's mosaics after 2016). The two can never meet on one picture.
|
||||
BY_SA, NC_SA = "by-sa", "nc-sa"
|
||||
PICTURE_LICENCES = { # what a source asks → the picture's licence, its address, and when it applies
|
||||
BY_SA: ("CC BY-SA 4.0", "https://creativecommons.org/licenses/by-sa/4.0/", "made from a CC BY-SA photo"),
|
||||
NC_SA: ("CC BY-NC-SA 4.0", "https://creativecommons.org/licenses/by-nc-sa/4.0/",
|
||||
"made from EOX's mosaics after 2016"),
|
||||
None: ("CC BY 4.0", "https://creativecommons.org/licenses/by/4.0/", "otherwise"),
|
||||
}
|
||||
|
||||
# EOxCloudless: the 2016 mosaic is CC BY 4.0, later ones CC BY-NC-SA 4.0.
|
||||
EOX_FREE_YEAR = 2016
|
||||
EOX_NEWEST = 2025
|
||||
# The one switch for EOX's year. True: a layout first raced in or before 2016 takes the 2016 mosaic (its track is on
|
||||
# it, and the picture stays free of share-alike), a later one the newest. False: every layout takes the newest
|
||||
# mosaic. A picture's licence (X-License) follows from the mosaic it was made from. The operator chose the newest
|
||||
# (2026-11-27): the 2016 mosaic is too soft at a circuit's zoom.
|
||||
EOX_2016_FOR_EARLY_LAYOUTS = False
|
||||
|
||||
# IGN's frozen mosaic of the photos flown in 2021 to 2023: France is flown every three years, so it covers all of
|
||||
# it, and its dates are the credit's.
|
||||
IGN_PERIOD = "2021-2023"
|
||||
|
||||
EOX_CREDIT = ("EOxCloudless https://cloudless.eox.at by EOX IT Services GmbH "
|
||||
"(Contains modified Copernicus Sentinel data {year})")
|
||||
IGN_CREDIT = "© IGN – BD ORTHO, {years}"
|
||||
OSM_CREDIT = "© OpenStreetMap contributors"
|
||||
COMMONS_CREDIT = "Photo: {author}, {licence}, via Wikimedia Commons"
|
||||
JOLPICA_CREDIT = "Race schedules: Jolpica F1 API (https://github.com/jolpica/jolpica-f1), CC BY-NC-SA 4.0"
|
||||
|
||||
|
||||
def usgs() -> MapSource:
|
||||
return MapSource("usgs", None,
|
||||
"https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}",
|
||||
max_zoom=16, slots=4, credit="Imagery: USDA, USGS The National Map: Orthoimagery")
|
||||
|
||||
|
||||
def pdok() -> MapSource:
|
||||
return MapSource("pdok", None,
|
||||
"https://service.pdok.nl/hwh/luchtfotorgb/wmts/v1_0/Actueel_orthoHR/EPSG:3857/{z}/{x}/{y}.jpeg",
|
||||
max_zoom=21, slots=4, credit="Luchtfoto: PDOK / Samenwerkingsverband Beeldmateriaal, CC BY 4.0")
|
||||
|
||||
|
||||
def ign() -> MapSource:
|
||||
# Two requests at once: at four, IGN reset connections.
|
||||
return MapSource("ign", IGN_PERIOD,
|
||||
"https://data.geopf.fr/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0"
|
||||
f"&LAYER=ORTHOIMAGERY.ORTHOPHOTOS{IGN_PERIOD}&STYLE=normal&TILEMATRIXSET=PM_6_19"
|
||||
"&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=image/jpeg",
|
||||
max_zoom=19, slots=2, credit=IGN_CREDIT.format(years=IGN_PERIOD.replace("-", "–")))
|
||||
|
||||
|
||||
def eox(year: int) -> MapSource:
|
||||
layer = "s2cloudless_3857" if year == EOX_FREE_YEAR else f"s2cloudless-{year}_3857"
|
||||
return MapSource("eox", year,
|
||||
f"https://tiles.maps.eox.at/wmts/1.0.0/{layer}/default/g/{{z}}/{{y}}/{{x}}.jpg",
|
||||
max_zoom=21, slots=4, credit=EOX_CREDIT.format(year=year))
|
||||
|
||||
|
||||
def osm() -> MapSource:
|
||||
# OpenStreetMap's tile usage policy: at most two connections, only when a picture is asked for, never ahead.
|
||||
return MapSource("osm", None, "https://tile.openstreetmap.org/{z}/{x}/{y}.png",
|
||||
max_zoom=19, slots=2, credit=OSM_CREDIT)
|
||||
|
||||
|
||||
def layout_first_year(layout_slug: str) -> int:
|
||||
"""A layout is named by its years: "2004-", "1950-1970" or "2010"."""
|
||||
return int(layout_slug.split("-")[0])
|
||||
|
||||
|
||||
def dark_map() -> MapSource:
|
||||
"""OpenStreetMap drawn dark, credited as OpenStreetMap: a layout's satellite background where the operator set
|
||||
{"use": "map"}."""
|
||||
return dataclasses.replace(osm(), tint="dark")
|
||||
|
||||
|
||||
def satellite_source(country_slug: str, circuit_slug: str, layout_slug: str,
|
||||
entry: Optional[dict] = None) -> Union[str, MapSource]:
|
||||
"""The satellite chain: the layout's picked Commons photo (COMMONS), else the national aerial photo of the
|
||||
circuit's country, else the chain's last link (satellite_fallback). The layout's entry in circuits/photos.json
|
||||
is a photo, or the override {"use": "map"}, which a photo or a national source still wins over (they are
|
||||
sharper)."""
|
||||
if is_photo(entry):
|
||||
return COMMONS
|
||||
if country_slug == "united-states":
|
||||
return usgs()
|
||||
if country_slug == "netherlands":
|
||||
return pdok()
|
||||
if country_slug == "france":
|
||||
return ign()
|
||||
if entry and entry.get("use") == MAP_OVERRIDE:
|
||||
return dark_map()
|
||||
return satellite_fallback(layout_slug)
|
||||
|
||||
|
||||
def satellite_fallback(layout_slug: str) -> MapSource:
|
||||
"""The satellite chain's last link, for a layout no picked photo and no national aerial photo has: EOxCloudless.
|
||||
The one place that decides it."""
|
||||
early = EOX_2016_FOR_EARLY_LAYOUTS and layout_first_year(layout_slug) <= EOX_FREE_YEAR
|
||||
return eox(EOX_FREE_YEAR if early else EOX_NEWEST)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ picks
|
||||
|
||||
_FREE_LICENCE = re.compile(r"^(CC0|PUBLIC DOMAIN|PD\b|PD-|CC[- ]BY(-SA)?[- ]\d)", re.IGNORECASE)
|
||||
|
||||
|
||||
def is_free_licence(licence: str) -> bool:
|
||||
"""Only CC0, public domain, CC BY and CC BY-SA: never NC or ND, never a photo without a free licence."""
|
||||
return bool(_FREE_LICENCE.match((licence or "").strip()))
|
||||
|
||||
|
||||
def entry_problem(entry) -> Optional[str]:
|
||||
"""Why a picks file's entry is refused, or None: an entry is a photo (file, licence, author, credit, date) under
|
||||
a free licence, or the override {"use": "map"}, never both."""
|
||||
if not isinstance(entry, dict):
|
||||
return "not an object"
|
||||
if "use" in entry:
|
||||
if entry["use"] != MAP_OVERRIDE:
|
||||
return f"unknown use {entry['use']!r}; it takes {MAP_OVERRIDE!r}"
|
||||
return "a file and a use at once" if "file" in entry else None
|
||||
if not entry.get("file"):
|
||||
return "neither a file nor a use"
|
||||
if not is_free_licence(entry.get("licence", "")):
|
||||
return f"licence {entry.get('licence')!r} is not CC0, public domain, CC BY or CC BY-SA"
|
||||
return None
|
||||
|
||||
|
||||
def is_photo(entry: Optional[dict]) -> bool:
|
||||
return bool(entry and entry.get("file"))
|
||||
|
||||
|
||||
def read_picks(path: Path) -> dict[str, dict]:
|
||||
"""A picks file (circuits/photos.json, seasons/photos.json): key → its entry. Keys starting with "$" are notes;
|
||||
an entry entry_problem refuses is left out and logged."""
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
picks = {}
|
||||
for key, entry in data.items():
|
||||
if key.startswith("$"):
|
||||
continue
|
||||
problem = entry_problem(entry)
|
||||
if problem:
|
||||
logger.error(f"{path}: the entry {key!r} is refused: {problem}")
|
||||
continue
|
||||
picks[key] = entry
|
||||
return picks
|
||||
|
||||
|
||||
def pick_credit(pick: dict) -> str:
|
||||
return pick.get("credit") or COMMONS_CREDIT.format(author=pick.get("author", "unknown"),
|
||||
licence=pick.get("licence", ""))
|
||||
|
||||
|
||||
def pick_share(pick: dict) -> Optional[str]:
|
||||
"""A CC BY-SA photo (2.0, 3.0, 3.0 DE, 4.0: each allows a later version) makes its picture CC BY-SA 4.0."""
|
||||
return BY_SA if re.match(r"^CC[- ]BY-SA\b", (pick.get("licence") or "").strip(), re.IGNORECASE) else None
|
||||
|
||||
|
||||
class LicenceClash(ValueError):
|
||||
"""A picture that would be made from a CC BY-SA photo and an NC-SA mosaic: refused, never drawn."""
|
||||
|
||||
|
||||
def picture_licence(shares: list[Optional[str]]) -> str:
|
||||
"""A picture's licence follows its sources: CC BY-SA 4.0 when made from a CC BY-SA photo, CC BY-NC-SA 4.0 when
|
||||
made from an EOX mosaic after 2016, CC BY 4.0 otherwise (CC0, public domain or CC BY photos, the 2016 mosaic,
|
||||
USGS, PDOK, IGN, OpenStreetMap). Jolpica's names and dates are single facts and set no licence."""
|
||||
asked = set(s for s in shares if s)
|
||||
if asked == {BY_SA, NC_SA}:
|
||||
raise LicenceClash("a CC BY-SA photo and an NC-SA mosaic cannot make one picture")
|
||||
return PICTURE_LICENCES[asked.pop() if asked else None][0]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ credits
|
||||
|
||||
def credit_line(credits: list[str]) -> str:
|
||||
"""Every source a picture was made from, each once, in order, joined with " · "."""
|
||||
return " · ".join(dict.fromkeys(c for c in credits if c))
|
||||
|
||||
|
||||
def ascii_header(text: str) -> str:
|
||||
"""The credit line as an ASCII header value (many clients read headers as Latin-1): "©" as "(c)", the " · "
|
||||
between sources as " | ", accents folded, en and em dashes as "-", any other character outside ASCII as "?".
|
||||
The drawn line and /licences keep the exact text."""
|
||||
text = text.replace("©", "(c)").replace(" · ", " | ")
|
||||
folded = "".join(c for c in unicodedata.normalize("NFKD", text) if not unicodedata.combining(c))
|
||||
folded = folded.replace("–", "-").replace("—", "-")
|
||||
return "".join(c if ord(c) < 128 else "?" for c in folded)
|
||||
|
||||
|
||||
def licences() -> dict:
|
||||
"""/licences: every source, its licence, its credit and its terms' address."""
|
||||
by_licence = PICTURE_LICENCES[None][0]
|
||||
picture_licence_of = {"commons": f"{PICTURE_LICENCES[BY_SA][0]} from a CC BY-SA photo, else {by_licence}",
|
||||
"eox": PICTURE_LICENCES[NC_SA][0], "jolpica": "does not set a picture's licence",
|
||||
"traces": "does not set a picture's licence"}
|
||||
|
||||
def source(id, name, used_for, licence, licence_url, credit, terms):
|
||||
return {"id": id, "name": name, "used_for": used_for, "licence": licence, "licence_url": licence_url,
|
||||
"credit": credit, "terms": terms, "picture_licence": picture_licence_of.get(id, by_licence)}
|
||||
nc_sa, by = PICTURE_LICENCES[NC_SA][1], PICTURE_LICENCES[None][1]
|
||||
return {
|
||||
"pictures": {
|
||||
"rule": "A picture's licence follows its sources, and is sent with it as X-License: CC BY-SA 4.0 when it "
|
||||
"is made from a CC BY-SA photo; CC BY-NC-SA 4.0 when it is made from an EOxCloudless mosaic after "
|
||||
"2016; CC BY 4.0 otherwise. The satellite chain takes one source, so the first two never meet.",
|
||||
"licences": [{"licence": name, "licence_url": url, "when": when}
|
||||
for name, url, when in PICTURE_LICENCES.values()],
|
||||
},
|
||||
"tracks": {"licence": "MIT", "licence_url": "https://opensource.org/license/mit"},
|
||||
"sources": [
|
||||
source("commons", "Wikimedia Commons aerial and car photos, picked per layout and per season",
|
||||
"bg=satellite where a photo is picked for the layout; season posters",
|
||||
"per file: CC0, public domain, CC BY or CC BY-SA only",
|
||||
"https://commons.wikimedia.org/wiki/Commons:Licensing",
|
||||
COMMONS_CREDIT.format(author="<author>", licence="<licence>"),
|
||||
"https://commons.wikimedia.org/wiki/Commons:Reusing_content_outside_Wikimedia"),
|
||||
source("usgs", "USGS The National Map: Orthoimagery (NAIP)", "bg=satellite for circuits in the United States",
|
||||
"public domain", "https://www.usgs.gov/information-policies-and-instructions/copyrights-and-credits",
|
||||
usgs().credit, "https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer"),
|
||||
source("pdok", "PDOK aerial photo (Beeldmateriaal Nederland)", "bg=satellite for circuits in the Netherlands",
|
||||
"CC BY 4.0", by, pdok().credit,
|
||||
"https://www.pdok.nl/-/hoge-resolutie-luchtfoto-2026-nu-beschikbaar-bij-pdok"),
|
||||
source("ign", f"IGN BD ORTHO, the aerial photos of {IGN_PERIOD}", "bg=satellite for circuits in France",
|
||||
"Licence Ouverte (Etalab) 2.0", "https://www.etalab.gouv.fr/licence-ouverte-open-licence/",
|
||||
ign().credit, "https://cartes.gouv.fr/cgu"),
|
||||
] + ([
|
||||
source("eox-2016", "EOxCloudless 2016 (Sentinel-2, 10 m)",
|
||||
"bg=satellite elsewhere, for a layout first raced in or before 2016",
|
||||
"CC BY 4.0", by, eox(EOX_FREE_YEAR).credit, "https://cloudless.eox.at/documentation/license"),
|
||||
] if EOX_2016_FOR_EARLY_LAYOUTS else []) + [
|
||||
source("eox", f"EOxCloudless {EOX_NEWEST} (Sentinel-2, 10 m)",
|
||||
"bg=satellite elsewhere, for a layout first raced after 2016" if EOX_2016_FOR_EARLY_LAYOUTS
|
||||
else "bg=satellite elsewhere",
|
||||
"CC BY-NC-SA 4.0", nc_sa, eox(EOX_NEWEST).credit, "https://cloudless.eox.at/documentation/license"),
|
||||
source("osm", "OpenStreetMap standard tiles", "bg=osm, bg=dark and bg=light (recoloured), the world locator",
|
||||
"ODbL (data), tile usage policy", "https://www.openstreetmap.org/copyright", OSM_CREDIT,
|
||||
"https://operations.osmfoundation.org/policies/tiles/"),
|
||||
source("jolpica", "Jolpica F1 API", "race schedules: names, rounds, dates", "CC BY-NC-SA 4.0", nc_sa,
|
||||
JOLPICA_CREDIT, "https://github.com/jolpica/jolpica-f1"),
|
||||
source("traces", "The circuits' GPS traces and layouts", "track outlines, track files", "MIT",
|
||||
"https://opensource.org/license/mit", "Circuit traces and layouts: f1-circuits, MIT License",
|
||||
"https://github.com/bacinger/f1-circuits"),
|
||||
],
|
||||
}
|
||||
+752
-684
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"$comment": "The picked Wikimedia Commons photo per season, from the \"<year> Formula One season cars\" category (docs/posters.md, Season posters and Picking photos). Key: the year, such as \"2024\". Value: {\"file\": the Commons title without \"File:\", \"licence\": its LicenseShortName (CC0, public domain, CC BY or CC BY-SA only), \"author\", \"credit\": \"Photo: <author>, <licence>, via Wikimedia Commons\", \"date\": YYYY[-MM[-DD]]}. Written by the picking tool, read by the poster service; a key starting with \"$\" is a note, not a pick."
|
||||
}
|
||||
+4
-1
@@ -22,9 +22,12 @@ RUN apk add --no-cache \
|
||||
COPY service/requirements.txt ./requirements.txt
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY cdn-api.py access_log.py circuits_service.py ergast_service.py posters_service.py ./
|
||||
COPY cdn-api.py access_log.py app_info.py circuits_service.py ergast_service.py posters_service.py \
|
||||
poster_options.py poster_sources.py ./
|
||||
COPY models/ ./models/
|
||||
COPY circuits/ ./circuits/
|
||||
# The picked photo per season (the picks per layout are in circuits/photos.json).
|
||||
COPY seasons/ ./seasons/
|
||||
# The example site the app serves at /examples/.
|
||||
COPY examples/ ./examples/
|
||||
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
"""A poster's sources, credits, licence, options, keys and cache headers (docs/posters.md).
|
||||
|
||||
Standard library only (no PIL, no numpy), so the merge check runs it as it is.
|
||||
"""
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import poster_options as po
|
||||
import poster_sources as ps
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
class SatelliteChainTest(unittest.TestCase):
|
||||
def test_the_first_source_that_has_the_layout(self):
|
||||
early = 2016 if ps.EOX_2016_FOR_EARLY_LAYOUTS else 2025 # the one switch for EOX's year
|
||||
photo, use_map = {"file": "A.jpg", "licence": "CC BY 4.0"}, {"use": "map"}
|
||||
cases = [
|
||||
# (country, circuit, layout, the layout's entry in circuits/photos.json) → (source, year, tint)
|
||||
(("bahrain", "bahrain-international-circuit", "2004-", photo), ("commons", None, None)),
|
||||
(("united-states", "miami-international-autodrome", "2022-", None), ("usgs", None, None)),
|
||||
(("netherlands", "circuit-park-zandvoort", "2020-", use_map), ("pdok", None, None)), # national wins
|
||||
(("france", "circuit-paul-ricard", "2018-", None), ("ign", "2021-2023", None)),
|
||||
(("bahrain", "bahrain-international-circuit", "2004-", None), ("eox", early, None)), # first raced by 2016
|
||||
(("bahrain", "bahrain-international-circuit", "2004-", use_map), ("osm", None, "dark")), # the override
|
||||
(("spain", "madring", "2026-", None), ("eox", 2025, None)),
|
||||
]
|
||||
for given, expected in cases:
|
||||
chosen = ps.satellite_source(*given)
|
||||
got = (chosen, None, None) if chosen == ps.COMMONS else (chosen.id, chosen.year, chosen.tint)
|
||||
self.assertEqual(got, expected, given)
|
||||
self.assertEqual(ps.satellite_source("bahrain", "x", "2004-", use_map).credit, ps.OSM_CREDIT)
|
||||
|
||||
def test_every_french_layout_takes_ign(self):
|
||||
france = json.loads((ROOT / "circuits" / "circuits.json").read_text(encoding="utf-8"))["france"]
|
||||
layouts = [(slug, layout) for locality in france["localities"].values()
|
||||
for slug, circuit in locality["circuits"].items() for layout in circuit["layouts"]]
|
||||
self.assertTrue(layouts)
|
||||
for slug, layout in layouts:
|
||||
self.assertEqual(ps.satellite_source("france", slug, layout).id, "ign", (slug, layout))
|
||||
|
||||
|
||||
class CreditAndLicenceTest(unittest.TestCase):
|
||||
def test_credit_line_and_its_header(self):
|
||||
line = ps.credit_line([ps.ign().credit, ps.OSM_CREDIT, ps.OSM_CREDIT, ""])
|
||||
self.assertEqual(line, "© IGN – BD ORTHO, 2021–2023 · © OpenStreetMap contributors")
|
||||
self.assertEqual(ps.ascii_header(line), "(c) IGN - BD ORTHO, 2021-2023 | (c) OpenStreetMap contributors")
|
||||
self.assertEqual(ps.ascii_header("Photo: José Müller — 王 CC BY-SA 4.0"), "Photo: Jose Muller - ? CC BY-SA 4.0")
|
||||
|
||||
def test_a_pictures_licence_follows_its_sources(self):
|
||||
by_sa = ps.pick_share({"licence": "CC BY-SA 3.0 de"})
|
||||
cases = [
|
||||
([by_sa, ps.osm().share], "CC BY-SA 4.0"),
|
||||
([ps.eox(2025).share, ps.osm().share], "CC BY-NC-SA 4.0"),
|
||||
([ps.eox(2016).share, ps.osm().share], "CC BY 4.0"),
|
||||
([ps.pick_share({"licence": "CC BY 2.0"}), ps.usgs().share, ps.pdok().share, ps.ign().share], "CC BY 4.0"),
|
||||
([], "CC BY 4.0"),
|
||||
]
|
||||
for shares, licence in cases:
|
||||
self.assertEqual(ps.picture_licence(shares), licence, shares)
|
||||
with self.assertRaises(ps.LicenceClash):
|
||||
ps.picture_licence([by_sa, ps.eox(2025).share])
|
||||
|
||||
def test_picks_skip_notes_and_refuse_what_they_cannot_use(self):
|
||||
with tempfile.TemporaryDirectory() as kept:
|
||||
path = Path(kept) / "photos.json"
|
||||
path.write_text(json.dumps({
|
||||
"$comment": "a note",
|
||||
"a/b/c/2004-": {"file": "A.jpg", "licence": "CC BY-SA 4.0", "author": "A"},
|
||||
"a/b/c/1950-": {"file": "B.jpg", "licence": "CC BY-NC-SA 2.0", "author": "B"},
|
||||
"a/b/c/2010": {"file": "C.jpg", "licence": "Public domain", "author": "C"},
|
||||
"a/b/c/2020-": {"use": "map"},
|
||||
"a/b/c/1990": {"use": "satellite"},
|
||||
"a/b/c/1991": {"use": "map", "file": "D.jpg", "licence": "CC0"},
|
||||
}))
|
||||
with self.assertLogs(ps.logger, "ERROR") as logged:
|
||||
self.assertEqual(sorted(ps.read_picks(path)), ["a/b/c/2004-", "a/b/c/2010", "a/b/c/2020-"])
|
||||
self.assertEqual(len(logged.output), 3)
|
||||
for name in ("circuits/photos.json", "seasons/photos.json"):
|
||||
self.assertEqual(ps.read_picks(ROOT / name).get("$comment"), None, name)
|
||||
|
||||
def test_licences_name_every_source_and_the_pictures_rule(self):
|
||||
licences = ps.licences()
|
||||
self.assertEqual([entry["licence"] for entry in licences["pictures"]["licences"]],
|
||||
["CC BY-SA 4.0", "CC BY-NC-SA 4.0", "CC BY 4.0"])
|
||||
self.assertEqual([source["id"] for source in licences["sources"]],
|
||||
["commons", "usgs", "pdok", "ign"] + (["eox-2016"] if ps.EOX_2016_FOR_EARLY_LAYOUTS else [])
|
||||
+ ["eox", "osm", "jolpica", "traces"])
|
||||
for source in licences["sources"]:
|
||||
for field in ("name", "used_for", "licence", "licence_url", "credit", "terms", "picture_licence"):
|
||||
self.assertTrue(source[field], f"{source['id']} has no {field}")
|
||||
|
||||
|
||||
class OptionsTest(unittest.TestCase):
|
||||
def parse(self, query: str, kind: str = "race") -> po.Options:
|
||||
return po.parse_options([tuple(part.split("=", 1)) for part in query.split("&") if part], kind)
|
||||
|
||||
def test_presets_per_kind(self):
|
||||
race, thumb, season = self.parse(""), self.parse("", "session"), self.parse("", "season")
|
||||
self.assertEqual((race.bg, race.photo, race.checker, race.locator, race.dim, race.track, race.width),
|
||||
("satellite", "natural", True, True, 0.43, ("#ffffff", 6), 1000))
|
||||
self.assertEqual((thumb.checker, thumb.locator, thumb.width), (False, False, 1920)) # classic: as before
|
||||
self.assertEqual(sorted(self.parse("style=minimal", "session").show), ["name", "session"])
|
||||
self.assertEqual(sorted(self.parse("style=minimal").show), ["date", "name"])
|
||||
self.assertEqual(sorted(season.show), ["name", "subtitle", "wordmark"])
|
||||
# Any option given overrides the style; equal pictures share one canonical form, whatever their address
|
||||
self.assertEqual(self.parse("style=minimal&checker=on").checker, True)
|
||||
self.assertEqual(self.parse("bg=aerial&v=r1").canonical(), self.parse("").canonical())
|
||||
self.assertTrue(self.parse(f"v={po.RENDER_VERSION}").versioned)
|
||||
self.assertFalse(self.parse("v=r2").versioned)
|
||||
|
||||
def test_an_unknown_option_or_value_is_named(self):
|
||||
cases = {
|
||||
"colour=red": "'colour'", "bg=esri": "'esri'", "photo=duotone": "'duotone'", "show=name,logo": "'logo'",
|
||||
"track=#fff": "'#fff'", "track=#ffffff,31": "'#ffffff,31'", "dim=1.5": "'1.5'", "dim=nan": "'nan'",
|
||||
"width=199": "'199'", "width=1001": "'1001'", "format=gif": "'gif'", "bg=osm&bg=dark": "'bg'",
|
||||
"locator=yes": "'yes'", "accent=red": "'red'",
|
||||
}
|
||||
for query, named in cases.items():
|
||||
with self.assertRaises(po.OptionError, msg=query) as caught:
|
||||
self.parse(query)
|
||||
self.assertIn(named, str(caught.exception), query)
|
||||
self.assertEqual(self.parse("width=1920", "session").width, 1920)
|
||||
|
||||
def test_keys(self):
|
||||
options = self.parse("")
|
||||
key = po.finished_key("race/Bahrain Grand Prix/2024", options, ["map/eox-2016/x-poster-z15-r3"])
|
||||
self.assertNotEqual(key, po.finished_key("race/Bahrain Grand Prix/2024", self.parse("photo=bw"),
|
||||
["map/eox-2016/x-poster-z15-r3"]))
|
||||
self.assertNotEqual(key, po.finished_key("race/Bahrain Grand Prix/2023", options,
|
||||
["map/eox-2016/x-poster-z15-r3"]))
|
||||
self.assertTrue(key.endswith(".png"))
|
||||
self.assertTrue(po.finished_key("race/Bahrain Grand Prix/2024", self.parse("format=webp"), []).endswith(".webp"))
|
||||
self.assertEqual(po.locator_layer_key(26.0325, 50.5106), f"locator/26.03_50.51-{po.RENDER_VERSION}")
|
||||
self.assertIn(po.RENDER_VERSION, po.map_layer_key("eox-2025", po.trace_hash([[1, 2]]), "thumb", 15))
|
||||
|
||||
|
||||
class CachingTest(unittest.TestCase):
|
||||
def test_what_clients_keep(self):
|
||||
self.assertEqual(po.cache_headers(True, True, '"e"'),
|
||||
{"Cache-Control": "public, max-age=31536000, immutable", "ETag": '"e"'})
|
||||
self.assertEqual(po.cache_headers(True, False, '"e"'), {"Cache-Control": "public, max-age=86400", "ETag": '"e"'})
|
||||
self.assertEqual(po.cache_headers(False, True, '"e"'), {"Cache-Control": "public, max-age=300"})
|
||||
self.assertTrue(po.etag_matches('"a", W/"e"', '"e"'))
|
||||
self.assertFalse(po.etag_matches("", '"e"'))
|
||||
|
||||
def test_the_least_recently_used_go_first(self):
|
||||
entries = {"old": (1.0, 600), "new": (3.0, 600), "mid": (2.0, 600)}
|
||||
self.assertEqual(po.evictions(entries, 1300), ["old"])
|
||||
self.assertEqual(po.evictions(entries, 600), ["old", "mid"])
|
||||
self.assertEqual(po.evictions(entries, 1800), [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user