diff --git a/README.md b/README.md index c9c857e..9294ee3 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,8 @@ How posters are made (sources and their licences, kept layers, options, credits) | `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 | +| `GET /picks/circuits.json` | the photo or map picked per layout, as the poster service has `circuits/photos.json` loaded: its notes and the entries it draws from | +| `GET /picks/seasons.json` | the photo picked per season, as the poster service has `seasons/photos.json` loaded: its notes and the entries it draws from | 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`, `photo`, `osm`, `dark`, `light`, `none`), @@ -167,7 +169,7 @@ are fetched only when a picture asks for them, at most two at once; Wikimedia Co `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, an unknown circuit or layout is named; a poster's satellite source, -credits and licence, its options, keys and cache headers, and the picture store's cap). +credits and licence, its options, keys and cache headers, the picture store's cap, and the picks `/picks/…` answers). ## Acknowledgment diff --git a/cdn-api.py b/cdn-api.py index 1e7a461..e9dd22e 100644 --- a/cdn-api.py +++ b/cdn-api.py @@ -95,6 +95,7 @@ async def root(): "/posters/session/{grand_prix_name}/{season}/{session_slug}.png", "/kometa/formula-1-metadata.yml", "/licences", + *poster_sources.PICKS_ROUTES, ], "examples": "/examples/", "disclaimer": DISCLAIMER, @@ -117,6 +118,20 @@ async def get_licences(): return poster_sources.licences() +def picks_route(path: Path): + """A picks file, read-only, as the poster service has it loaded: its notes, then the entries it draws from (an + entry it refused is left out). Plain def: a changed file is read again, in the threadpool.""" + def answer(): + return posters_service.picks.answer(path) + return answer + + +# /picks/circuits.json and /picks/seasons.json (docs/posters.md, Picking photos). +for route, picks_path in poster_sources.PICKS_ROUTES.items(): + app.get(route, name=f"picks_{picks_path.parent}", + summary=f"The picks of {picks_path}, as the poster service draws from them")(picks_route(picks_path)) + + # The example site: one page per area of the API, each calling the routes above (examples/index.html). app.mount( "/examples", diff --git a/docs/posters.md b/docs/posters.md index 3b6c147..4b2c638 100644 --- a/docs/posters.md +++ b/docs/posters.md @@ -133,6 +133,13 @@ An entry holds the photo fields (`file`, the Commons title without "File:"; `lic `date`, `YYYY[-MM[-DD]]`), `"use": "map"`, or both. A key starting with `$` is a note and is skipped. Refused and logged when read: an unknown `use`, incomplete photo fields, an entry with neither, a licence that is not free. +The API serves both files, read-only, as the poster service has them loaded: `/picks/circuits.json` and +`/picks/seasons.json` answer the notes first, then the entries it draws from (a refused entry is left out), with the +CORS of every route and, like the other JSON routes, no `Cache-Control`; the root route lists both. The picker reads the picks +there first, from the API its site picks. Only a page opened from a working copy (from disk, or on a loopback host: +`localhost`, `127.0.0.1`, `[::1]`) falls back to the repository's files when the API does not answer them; anywhere +else a failure says which address failed and why. + ## Licences, stated - On every picture: the credit line of each source it was made from, joined with " · ", at least 12 px high diff --git a/examples/index.html b/examples/index.html index 01f78bc..f329b8e 100644 --- a/examples/index.html +++ b/examples/index.html @@ -114,7 +114,7 @@

Choose a freely licensed Wikimedia Commons photo per circuit layout and per season, seen as the poster crops it, and copy its entry for the picks file.

diff --git a/examples/picker.html b/examples/picker.html index 93a84cc..dbbe654 100644 --- a/examples/picker.html +++ b/examples/picker.html @@ -54,9 +54,11 @@

1. The lists

-

The candidates come with the site; the picks are read from the repository, beside the page’s folder. - Run python3 -m http.server in the working copy and open /examples/picker.html there to - have both, or load a picks file from disk below.

+

The candidates come with the site; the picks are the API’s, /picks/circuits.json and + /picks/seasons.json, as the poster service draws from them. A page opened from a working copy (from + disk, or served on this machine with python3 -m http.server) reads the working copy’s + circuits/photos.json and seasons/photos.json when the API does not answer; or load a + picks file from disk below.

@@ -140,11 +142,15 @@ const FRAMES = { poster: [1000, 1500], thumb: [1920, 1080] }; const PICK_FIELDS = ['file', 'licence', 'author', 'credit', 'date']; + // The picks are the API's (docs/posters.md, Picking photos): route is its address, local the working copy's file. const FILES = { candidates: { card: $('cand-file'), url: 'data/candidates.json', what: 'the candidates (examples/data/candidates.json)' }, - circuits: { card: $('picks-circuits'), url: '../circuits/photos.json', what: 'the layouts’ picks (circuits/photos.json)' }, - seasons: { card: $('picks-seasons'), url: '../seasons/photos.json', what: 'the seasons’ picks (seasons/photos.json)' }, + circuits: { card: $('picks-circuits'), route: '/picks/circuits.json', local: '../circuits/photos.json', what: 'the layouts’ picks (circuits/photos.json)' }, + seasons: { card: $('picks-seasons'), route: '/picks/seasons.json', local: '../seasons/photos.json', what: 'the seasons’ picks (seasons/photos.json)' }, }; + // A page opened from a working copy: from disk, or served on this machine. Only such a page falls back to the + // working copy's picks files when the API does not answer them; on any other host a failure is said and stays. + const WORKING_COPY = location.protocol === 'file:' || ['localhost', '127.0.0.1', '[::1]'].includes(location.hostname); const state = { mode: params.get('mode') === 'season' ? 'season' : 'layout', @@ -182,30 +188,47 @@ return ''; } - /** Reads one file over http, or offers to load it from disk when that fails; calls done(value) once read. */ + /** One address read as JSON and checked: { value }, or { why } it could not be used. */ + async function readJSON(url, check) { + try { + const res = await fetch(url, { cache: 'no-cache' }); + if (!res.ok) return { why: `HTTP ${res.status}` }; + const value = JSON.parse(await res.text()); + const why = check(value); + return why ? { why } : { value }; + } catch (e) { + return { why: e instanceof SyntaxError ? 'it is not JSON' : `no answer (${e.message})` }; + } + } + + /** + * Reads one file: the candidates from the site; the picks from the API and, only on a working copy, from its own + * file when the API does not answer them. When every address failed, says each with why and offers to load the + * file from disk; calls done(value) once read. + */ async function readFile(name, done) { const f = FILES[name]; const card = f.card; const out = card.querySelector('.result'); - const url = new URL(f.url, location.href).href; - setRequest(card.querySelector('.request'), url, name === 'candidates' ? 'a file of the site, not the API' : 'a file of the repository, not the API'); - setStatus(card.querySelector('.status'), 'pending', `Reading ${f.what}…`); + const tries = name === 'candidates' + ? [{ url: f.url, label: 'a file of the site, not the API' }] + : [{ url: api(f.route), label: null }, + ...(WORKING_COPY ? [{ url: f.local, label: 'a file of the working copy, not the API' }] : [])]; const check = name === 'candidates' ? validCandidates : validPicks; - let why = ''; - try { - const res = await fetch(url, { cache: 'no-cache' }); - if (!res.ok) throw new Error(`HTTP ${res.status}`); - const value = JSON.parse(await res.text()); - why = check(value); - if (!why) { - accept(name, value, `Read ${f.what} from ${url}.`); - done(value); + const failed = []; + for (const t of tries) { + const url = new URL(t.url, location.href).href; + setRequest(card.querySelector('.request'), url, t.label); + setStatus(card.querySelector('.status'), 'pending', `Reading ${f.what}…`); + const read = await readJSON(url, check); + if (read.value) { + accept(name, read.value, `Read ${f.what} from ${url}${failed.length ? ` (${failed.join('; ')})` : ''}.`); + done(read.value); return; } - } catch (e) { - why = e instanceof SyntaxError ? 'it is not JSON' : e.message; + failed.push(`${url}: ${read.why}`); } - setStatus(card.querySelector('.status'), 'error', `Could not read ${f.what}: ${why}.`); + setStatus(card.querySelector('.status'), 'error', `Could not read ${f.what}: ${failed.join('; ')}.`); const input = h('input', { type: 'file', accept: '.json,application/json' }); input.addEventListener('change', async () => { const file = input.files && input.files[0]; @@ -224,7 +247,7 @@ name === 'candidates' ? 'Without the candidates there is nothing to show. ' : 'Without the picks file the page cannot show what is picked, nor the whole file with a new pick. ', - 'The page reads it relative to itself; served by the API only /examples/ is there. Load it from disk: ', input)); + 'Load it from disk: ', input)); } function accept(name, value, text) { diff --git a/poster_sources.py b/poster_sources.py index 5e48b48..58add87 100644 --- a/poster_sources.py +++ b/poster_sources.py @@ -201,23 +201,70 @@ 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.""" +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 {} - picks = {} + 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 picks + 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: diff --git a/posters_service.py b/posters_service.py index 91f4aaa..cca7c73 100644 --- a/posters_service.py +++ b/posters_service.py @@ -38,8 +38,6 @@ logger = logging.getLogger(__name__) LAYERS_DIR = Path("layers") # module.json: class rebuildable (backed up; fetched again if lost) POSTERS_DIR = Path("posters") # module.json: class cache POSTERS_CAP = 2 * 1024 ** 3 # bytes -CIRCUIT_PICKS = Path("circuits/photos.json") -SEASON_PICKS = Path("seasons/photos.json") POSTER_W, POSTER_H = po.FRAMES["poster"] THUMB_W, THUMB_H = po.FRAMES["thumb"] # Plex episode-thumb ratio @@ -444,7 +442,7 @@ class PostersService: self.commons = Commons(self.layers) self._layer_locks: dict[str, threading.Lock] = {} self._layer_locks_guard = threading.Lock() - self._picks: dict[Path, tuple[float, dict]] = {} + self.picks = ps.Picks() # the picks files, as the routes /picks/… serve them too # Pre-tuned zooms per circuit, keyed by the ASCII-slugified name in f1-locations.json and looked up by our # circuit slug; read only when a layout has no trace. Falls back to DEFAULT_ZOOM when not found. self._zoom_by_circuit = self._load_zoom_lookup() @@ -464,22 +462,6 @@ class PostersService: # ------------------------------------------------------------------ inputs - def picks(self, path: Path) -> dict[str, dict]: - """A picks file, read again when it changed.""" - try: - mtime = path.stat().st_mtime - except FileNotFoundError: - return {} - kept = self._picks.get(path) - if not kept or kept[0] != mtime: - try: - kept = (mtime, ps.read_picks(path)) - except (OSError, ValueError) as e: - logger.error(f"Could not read the picks in {path}: {e}") - kept = (mtime, {}) - self._picks[path] = kept - return kept[1] - def _race(self, grand_prix_name: str, season: int) -> Optional[dict]: races = self.ergast._fetch_season_schedule(season) return next((r for r in races if r["raceName"] == grand_prix_name), None) @@ -781,7 +763,7 @@ class PostersService: chosen = ps.osm() if options.bg in ("satellite", "photo"): layout_key = f"{circuit.locality.country.slug}/{circuit.locality.slug}/{circuit.slug}/{layout.slug}" - entry = self.picks(CIRCUIT_PICKS).get(layout_key) # the photo fields, "use": "map", or both + entry = self.picks.entries(ps.CIRCUIT_PICKS).get(layout_key) # the photo fields, "use": "map", or both chain = ps.photo_source if options.bg == "photo" else ps.satellite_source chosen = chain(circuit.locality.country.slug, circuit.slug, layout.slug, entry) if chosen == ps.COMMONS: @@ -813,7 +795,7 @@ class PostersService: def _render_season(self, season: int, options: po.Options) -> Rendered: """A season poster: the year over that season's picked Commons photo, or over black until one is picked.""" - pick = self.picks(SEASON_PICKS).get(str(season)) if options.bg != "none" else None + pick = self.picks.entries(ps.SEASON_PICKS).get(str(season)) if options.bg != "none" else None pick = pick if ps.is_photo(pick) else None background = self._photo_layer(pick, "poster") if pick else None texts = {"wordmark": "FORMULA 1", "name": str(season), "subtitle": "WORLD CHAMPIONSHIP"} diff --git a/tests/test_posters.py b/tests/test_posters.py index 18caee4..850376d 100644 --- a/tests/test_posters.py +++ b/tests/test_posters.py @@ -3,6 +3,7 @@ Standard library only (no PIL, no numpy), so the merge check runs it as it is. """ import json +import os import tempfile import unittest from pathlib import Path @@ -102,6 +103,33 @@ class CreditAndLicenceTest(unittest.TestCase): for name in ("circuits/photos.json", "seasons/photos.json"): self.assertEqual(ps.read_picks(ROOT / name).get("$comment"), None, name) + def test_the_picks_routes_answer_the_picks_as_the_service_has_them_loaded(self): + photo = {"file": "A.jpg", "licence": "CC BY 4.0", "author": "A", "credit": "Photo: A", "date": "2020"} + refused = {"use": "satellite"} + cases = [ + # (route, the file the poster service reads, a pick's key in it) + ("/picks/circuits.json", "circuits/photos.json", "a/b/c/2004-"), + ("/picks/seasons.json", "seasons/photos.json", "2024"), + ] + self.assertEqual(sorted(ps.PICKS_ROUTES), sorted(route for route, _, _ in cases)) + with tempfile.TemporaryDirectory() as kept: + root = Path(kept) + picks = ps.Picks(root) + for route, name, key in cases: + path = ps.PICKS_ROUTES[route] + self.assertEqual(path, Path(name), route) + (root / name).parent.mkdir() + (root / name).write_text(json.dumps({"$comment": f"a note on {name}", key: photo, "x": refused})) + os.utime(root / name, (1, 1)) + with self.assertLogs(ps.logger, "ERROR"): # the refused entry, logged once when read + self.assertEqual(picks.entries(path), {key: photo}, route) # what the service draws from + answer = picks.answer(path) + self.assertEqual(list(answer), ["$comment", key], route) # its notes first, the refused one left out + self.assertEqual(answer, {"$comment": f"a note on {name}", key: photo}, route) + (root / name).write_text(json.dumps({key: {"use": "map"}})) + os.utime(root / name, (2, 2)) # a changed file is read again + self.assertEqual(picks.answer(path), {key: {"use": "map"}}, route) + def test_licences_name_every_source_and_the_pictures_rule(self): licences = ps.licences() self.assertEqual([entry["licence"] for entry in licences["pictures"]["licences"]],