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
This commit is contained in:
2026-11-27 15:13:29 +01:00
parent 4f00403e13
commit db5c19f0d4
14 changed files with 1620 additions and 748 deletions
+157
View File
@@ -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()