Files
f1-circuits/poster_sources.py
T
jschoubben db5c19f0d4 Draw posters from kept layers of licensed sources, credited on every picture
Esri's, Bing's and Google's terms forbid keeping or serving pictures made from their maps, so the posters move to
sources whose licence allows a kept copy: a picked Wikimedia Commons photo, USGS, PDOK and IGN's frozen 2021-2023
mosaic by country, else EOxCloudless's newest mosaic, and OpenStreetMap for the maps and the locator. What needs
the network is a layer fetched once and kept whole in layers/; texts, colours, size and format are drawn on every
request, and finished pictures are kept in posters/ up to 2 GB. Every picture carries its sources' credit line,
X-Credits, X-License (which follows its sources) and a link to /licences. Options are checked into a named 422;
the Kometa file states Jolpica's licence and versions its addresses so clients keep them for good. A layout whose
trace is a point (Madring) is drawn at the circuit's location instead of failing.

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

308 lines
16 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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"),
],
}