The picker read circuits/photos.json and seasons/photos.json relative to
itself. The API serves only /examples/, so the live page showed two HTTP
404 errors and a "Load it from disk" box for each.
The API now serves both picks files, read-only, at /picks/circuits.json
and /picks/seasons.json. Each answer is the file as the poster service
has it loaded, from the same loader it draws from: the notes first, then
the entries, a refused entry left out. The root route lists both routes.
The picker reads them from the API its site picks. Only a page opened
from a working copy (file:, or a loopback host) falls back to the
repository's files. A failure names each address and why.
Builds: docs/posters.md, Picking photos, as written in 780984064f (the lead's lines 1-4 of 2026-11-30 and answers Q1, Q2)
Claude-Session: https://claude.ai/code/session_01JG73KFhbaNj3tyJ8tKmE3W
373 lines
19 KiB
Python
373 lines
19 KiB
Python
"""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.
|
||
|
||
bg=satellite takes, per layout, the national aerial photo of the circuit's country, else EOxCloudless (or the dark
|
||
map where the operator set {"use": "map"}). bg=photo takes the layout's picked Wikimedia Commons photo, and without a
|
||
pick falls back to bg=satellite. 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" # bg=photo: 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="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) -> MapSource:
|
||
"""The satellite chain (bg=satellite, aerial): the national aerial photo of the circuit's country, else the
|
||
chain's last link (satellite_fallback). "use": "map" in the layout's entry in circuits/photos.json makes that last
|
||
link the dark map, whether or not the entry also holds a photo; a national source still wins over it (it is
|
||
sharper). A picked photo is not in this chain."""
|
||
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 photo_source(country_slug: str, circuit_slug: str, layout_slug: str,
|
||
entry: Optional[dict] = None) -> Union[str, MapSource]:
|
||
"""bg=photo: the layout's picked Commons photo (COMMONS), drawn with the track as an inset; without the photo
|
||
fields, whatever bg=satellite draws for the layout (the dark map where "use": "map" is set). Never the default of
|
||
any style."""
|
||
return COMMONS if is_photo(entry) else satellite_source(country_slug, circuit_slug, layout_slug, entry)
|
||
|
||
|
||
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()))
|
||
|
||
|
||
PHOTO_FIELDS = ("file", "licence", "author", "credit", "date")
|
||
|
||
|
||
def entry_problem(entry) -> Optional[str]:
|
||
"""Why a picks file's entry is refused, or None. An entry carries the photo fields (all of PHOTO_FIELDS, under a
|
||
free licence), which decide bg=photo; the override {"use": "map"}, which decides bg=satellite; or both."""
|
||
if not isinstance(entry, dict):
|
||
return "not an object"
|
||
if "use" in entry and entry["use"] != MAP_OVERRIDE:
|
||
return f"unknown use {entry['use']!r}; it takes {MAP_OVERRIDE!r}"
|
||
given = [field for field in PHOTO_FIELDS if entry.get(field)]
|
||
if given and len(given) < len(PHOTO_FIELDS):
|
||
return f"incomplete photo fields: no {', '.join(f for f in PHOTO_FIELDS if f not in given)}"
|
||
if not given and "use" not in entry:
|
||
return "neither the photo fields nor a use"
|
||
if given and not is_free_licence(entry["licence"]):
|
||
return f"licence {entry['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"))
|
||
|
||
|
||
CIRCUIT_PICKS = Path("circuits/photos.json")
|
||
SEASON_PICKS = Path("seasons/photos.json")
|
||
# The API serves both picks files, read-only, as the poster service has them loaded (docs/posters.md, Picking photos).
|
||
PICKS_ROUTES = {"/picks/circuits.json": CIRCUIT_PICKS, "/picks/seasons.json": SEASON_PICKS}
|
||
|
||
|
||
def read_picks_file(path: Path) -> tuple[dict, dict[str, dict]]:
|
||
"""A picks file (circuits/photos.json, seasons/photos.json): its notes (the keys starting with "$", as they stand)
|
||
and its entries, key → entry; an entry entry_problem refuses is left out and logged."""
|
||
try:
|
||
data = json.loads(path.read_text(encoding="utf-8"))
|
||
except FileNotFoundError:
|
||
return {}, {}
|
||
notes, picks = {}, {}
|
||
for key, entry in data.items():
|
||
if key.startswith("$"):
|
||
notes[key] = entry
|
||
continue
|
||
problem = entry_problem(entry)
|
||
if problem:
|
||
logger.error(f"{path}: the entry {key!r} is refused: {problem}")
|
||
continue
|
||
picks[key] = entry
|
||
return notes, picks
|
||
|
||
|
||
def read_picks(path: Path) -> dict[str, dict]:
|
||
"""A picks file's entries: key → its entry. Keys starting with "$" are notes; an entry entry_problem refuses is
|
||
left out and logged."""
|
||
return read_picks_file(path)[1]
|
||
|
||
|
||
class Picks:
|
||
"""The picks files as the poster service has them loaded, each read again when it changed: the entries it draws
|
||
from, and the file as /picks/… serves it."""
|
||
|
||
def __init__(self, root: Path = Path(".")):
|
||
self.root = root
|
||
self._kept: dict[Path, tuple[float, dict, dict[str, dict]]] = {}
|
||
|
||
def _loaded(self, path: Path) -> tuple[dict, dict[str, dict]]:
|
||
full = self.root / path
|
||
try:
|
||
mtime = full.stat().st_mtime
|
||
except FileNotFoundError:
|
||
return {}, {}
|
||
kept = self._kept.get(path)
|
||
if not kept or kept[0] != mtime:
|
||
try:
|
||
kept = (mtime, *read_picks_file(full))
|
||
except (OSError, ValueError) as e:
|
||
logger.error(f"Could not read the picks in {full}: {e}")
|
||
kept = (mtime, {}, {})
|
||
self._kept[path] = kept
|
||
return kept[1], kept[2]
|
||
|
||
def entries(self, path: Path) -> dict[str, dict]:
|
||
"""What the service draws from: key → entry, the notes and every refused entry left out."""
|
||
return self._loaded(path)[1]
|
||
|
||
def answer(self, path: Path) -> dict:
|
||
"""The file as the API serves it: its notes first, then the entries the service draws from."""
|
||
notes, entries = self._loaded(path)
|
||
return {**notes, **entries}
|
||
|
||
|
||
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))
|
||
|
||
|
||
_SPELLED = {"ß": "ss", "æ": "ae", "Æ": "AE", "ø": "o", "Ø": "O", "œ": "oe", "Œ": "OE", "đ": "d", "Đ": "D"}
|
||
|
||
|
||
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 " | ", ß, æ, ø, œ and đ spelled out, 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(" · ", " | ")
|
||
for letter, spelled in _SPELLED.items(): # letters NFKD does not take apart, spelled out so names stay readable
|
||
text = text.replace(letter, spelled)
|
||
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=photo 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, and a layout switched to the map",
|
||
"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"),
|
||
],
|
||
}
|