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.
+
@@ -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"]],