34 Commits
Author SHA1 Message Date
mesh-tools ab1e4342cb Merge pull request 'Guide Plex and Emby users step by step to the posters, at /guides/' (#12) from docs/guides into master 2026-11-30 11:48:21 +00:00
jschoubben c7753af419 Use a documentation address for the example Plex server 2026-11-30 12:47:36 +01:00
jschoubben 09a83f6ad9 Guide Plex and Emby users step by step to the posters, at /guides/
People put the posters in their own libraries (one in an automated F1 library in Emby), and
the only help was the Kometa example page, written for developers. The guides are for people
who are not: numbered steps of one action each, the exact menus and buttons of Plex, Kometa and
Emby as their own documentation names them, boxes to copy, the pictures from the live API,
what to see after a step and what to do when it does not work. The technical details (routes,
options, the address version, a script and Emby's API) sit at the end of each.

guides/ holds the index, plex.html (a Plex TV library on the Personal Media Shows agent, Kometa
pointed at /kometa/formula-1-metadata.yml, its daily run) and emby.html (Kometa needs Plex, so:
Set Image from URL by hand, or picture files named as Emby's TV naming page reads them, and a
script that saves a whole season from the Kometa file). They use the example site's style
sheet; every example page's nav links them, and README.md lists them.

cdn-api.py serves guides/ at /guides/ beside /examples/, and the image copies it. A mount of a
directory the image lacks stops the service at its start, so tests/test_image.py holds that
every directory the app serves is copied by service/Dockerfile.
2026-11-30 12:46:36 +01:00
mesh-tools 8754f64f80 Merge pull request 'Season posters: a free photo of each season's car, matched to the operator's curated cars' (#11) from feat/season-picks into master 2026-11-30 10:51:58 +00:00
jschoubben e5874f2d9f Key a finished picture by the credit it draws
A finished picture's key named its route, its options and its layers' keys, but not the credit
it draws from a pick. A pick whose author or licence changed while its file stayed the same kept
its photo layer's key, so the stored picture was served again with the old credit drawn on it,
while X-Credits already said the new one (seen locally for 1967, whose author lost Commons'
"upload by" appendix).

finished_key now also takes every text the picture draws from a pick: the credit of each layer
made from a pick's photo (Layer.from_pick, season and layout picks alike). A map's credit follows
its source, which its layer key already names. A picture drawn from no pick adds nothing to the
digest, so its key is the one it had: no kept race, session or pick-less season picture is drawn
again. Seen locally with the old store in place: the race poster, the session thumbnail and the
season poster with bg=none came from the store under their old keys; the 1967 and 1989 season
posters were drawn once under new keys. No release of master ever held a photo pick (neither
seasons/photos.json nor circuits/photos.json), so the running service keeps no picture whose key
changes.

The keys test: the same photo with another credit makes another key (on the old code finished_key
takes no credit; with the credit ignored the keys are equal), and a picture drawn from no pick
keeps the digest of render version, route, options and layer keys it had.

Builds: docs/posters.md at f6b9f937d0 (Finished images: the key names the credit of each layer drawn from a pick; Principles, 2: a changed input makes a new key)

Claude-Session: https://claude.ai/code/session_01JG73KFhbaNj3tyJ8tKmE3W
2026-11-30 11:33:56 +01:00
jschoubben 25fee9ca85 Give the addresses an address version of their own, raised to a1
Every season poster changed with the joined picks, but the Kometa file kept handing out
?v=r3, an address clients keep for good: they would never load the new season posters. Raising
the render version instead would draw every kept layer and finished picture again, though only
the season posters changed.

poster_options.ADDRESS_VERSION ("a1") sits beside RENDER_VERSION: the Kometa file writes it into
every poster address, and only an address carrying it is sent the immutable Cache-Control; an
address with ?v=r3 is now any other address (a day, then its ETag). Layers and finished pictures
stay keyed by RENDER_VERSION, still r3, so nothing kept is drawn again except the season posters
whose photo changed. The API's option text, the Kometa docstring and the README say "address
version".

The options test: ?v=a1 is kept for good, ?v=r3 no longer (on master it fails: no
ADDRESS_VERSION, and ?v=r3 is still the immutable address).

Builds: docs/posters.md at f6b9f937d0 (Finished images: what clients keep, the address version)

Claude-Session: https://claude.ai/code/session_01JG73KFhbaNj3tyJ8tKmE3W
2026-11-30 11:33:56 +01:00
jschoubben ab0c4b9244 Join the season photo picks: every season from 1950 to 2026 matched to its curated car
seasons/photos.json held only its note, so every season poster was drawn without a photo. It now
holds the 77 picks made by the curated car of each season (three runs: 1950-1975, 1976-2000,
2001-2026), keyed in year order. Licence, author and date of each were read from Commons' own
metadata. Where that date cannot be when the photo was taken, the entry says where its date
comes from: 1978, 1984, 1988 and 1991 from the description (Commons gives a scan or upload
date); 1989 the upload's month, 2012-08 (Commons' 2013-08-21 is the camera's clock, after the
upload of 2012-08-28, and neither the description, whose 1989 is the car's year, nor a category
says when it was taken). 1967's author is the photographer as Commons names him on his other
files, "edvvc from London, UK", without the uploader Commons' Artist field appends. The $comment
says where a candidate comes from, the match order and date_from's three values.

seasons/picks.md is the table of picks the design names: one row per season, newest first, the
curated car named and described (never its photo, never where it is kept), the picked file, its
licence, the match and why, joined from the three runs' tables. 1957, 1975 and 1977 are not in
their season's cars category (searched as the candidates tool searches it, and their own
categories walked up): their rows say they were found by a search for the car by name. Five
seasons are not the same car: 1952 (the champion's car), 1967, 2023 and 2026 (the same team's
car of that season), 1971 (the same model in the livery it raced that season).

The tests read both files as the service does: every season 1950-2026 written in year order and
accepted by poster_sources' reader, each date_from one of the design's three; the table names
every picked season newest first, with the file and licence of seasons/photos.json and one of the
design's four matches (on master both fail: no season is picked, no table). The licence test
gains CC BY-SA 2.5 and the three ported licences the picks use (2.0 de, 3.0 de, 3.0 nl): free,
and the picture CC BY-SA 4.0; pick_share's docstring names them. The reader does not check
date_from, so it needs no change for "upload".

Builds: docs/posters.md at f6b9f937d0 (Season posters: each season's photo is matched to the curated car, the table of picks seasons/picks.md; Picking photos: the name search said in the pick's row, date and date_from, the ported CC BY-SA licences; Licences, stated: 2.5 and the ported licences)

Claude-Session: https://claude.ai/code/session_01JG73KFhbaNj3tyJ8tKmE3W
2026-11-30 11:33:56 +01:00
jschoubben f6b9f937d0 Write the lead's answers on the season photos into the design
The season photos are matched to the operator's curated cars (77 seasons, 1950-2026), and the
picks raised questions the design did not answer. The lead's answers of 2026-11-30:

- Season posters: each season's photo is matched to the curated car of that season, in order the
  same car, the same model in a livery it raced that season, the same team's car of that season,
  that season's champion car; a curated photo of another year's car gives way to that season's
  car; the table of picks, seasons/picks.md, names the match per season.
- Picking photos: tools/commons_candidates.py lists a season's candidates from its "<year>
  Formula One season cars" category; where that category holds no free photo of the curated car,
  the person or session picking searches Commons for that car by name, and the pick's row in
  seasons/picks.md says so (no part runs the search: every season is picked).
- An entry's date is when the photo was taken. Where the date Commons gives cannot be (a scan, an
  upload, a camera clock never set, a date after the file's upload), the date its description or
  category gives, marked "date_from"; where neither says, the month of the file's upload, the
  latest it can have been taken, marked "upload" (a true bound, not a date nobody measured).
- The ported CC BY-SA licences (2.0 de, 3.0 de, 3.0 nl) are free like their unported versions and
  give the picture CC BY-SA 4.0; the licences list names them, and 2.5 beside 2.0 and 3.0 (it
  also allows a later version with the same elements).
- Finished images: a finished picture's key also names the credit of each layer drawn from a
  pick, so a pick's changed credit makes a new key (principle 2: a changed input makes a new key).
- What clients keep: the address carries an address version of its own (?v=), separate from the
  render version that keys kept layers and finished pictures; raised when a look changes, so
  clients load it again from the pictures already kept. Raised now to a1 because every season
  poster changed; the render version stays r3.

The season photos leave "Not in this change".

Claude-Session: https://claude.ai/code/session_01JG73KFhbaNj3tyJ8tKmE3W
2026-11-30 11:33:50 +01:00
mesh-tools 072bbcc023 Merge pull request 'Draw Madring's track: take upstream's GPS trace instead of a point' (#10) from fix/madring-trace into master 2026-11-30 09:25:41 +00:00
mesh-tools 7cee693a2c Merge pull request 'Serve the picks from the API, so the live picker reads them' (#9) from fix/picker-reads-picks into master 2026-11-30 09:25:39 +00:00
jschoubben 82a0efabbc Fail the merge check on a point trace for a current race
Madring's point trace reached the 2026 poster unnoticed: nothing held that a layout a race draws
has a traced line. tests/test_traces.py takes every layout the service picks for a season from
2020 to next season (find_layout_slug_for_year over circuits.json, the data the posters draw
from) and fails each whose trace is not a LineString of more than ten points. On master it fails
on spain/madrid/madring/2026- alone; here it passes for all 35.

Builds: docs/posters.md at 8834df45e6 (Layers: no current race draws a layout without a traced line)

Claude-Session: https://claude.ai/code/session_01JG73KFhbaNj3tyJ8tKmE3W
2026-11-30 10:20:48 +01:00
jschoubben 613103e670 Take upstream's re-traced Baku, Miami and Las Vegas traces
Our three files were word-for-word copies of the dataset's traces as they stood in May 2025;
the dataset (bacinger/f1-circuits, MIT) has re-traced all three since: Las Vegas on 2025-07-12 to
2025-08-05 (56 to 100 points, our line up to about 70 m off the new one, length 6116 to 6201),
Miami on 2025-07-29 (109 to 103 points, within 7 m) and Baku on 2025-07-24 and 2026-10-16 (86
points, within 11 m). A newer upstream trace of a circuit already drawn is a plain update: each
is taken word for word, as Madring's, and its SVG and PNG drawn again the same way.

Builds: docs/posters.md at 8834df45e6 (Sources: the traces follow upstream; Layers: track outline points)

Claude-Session: https://claude.ai/code/session_01JG73KFhbaNj3tyJ8tKmE3W
2026-11-30 10:20:43 +01:00
jschoubben 9da882dd73 Draw Madring's track: take the upstream GPS trace instead of a point
The 2026 Spanish race poster showed Madrid with no track, because Madring's trace was a single
point and docs/posters.md (Layers) draws such a layout at its location without a track. The
dataset our traces come from (bacinger/f1-circuits, MIT) traced it on 2025-06-11 as
circuits/es-2026.geojson: a LineString of 116 points, length 5474. It is taken word for word, in
the form of every other trace here (two-space JSON, upstream's id es-2026 and properties).

The SVG is drawn again by generate_svgs.py (TrackLayout.save_svg), the PNG by
circuits/svg-generator.py's Circuit.plot saved transparent with a tight box, as every other PNG
here; both replace the ones drawn from the Wikimedia path. A new trace makes new layer keys,
so no kept poster of Madring is served again.

Upstream's MIT notice is copied word for word with it, as upstream's LICENSE.md holds it since
78726e6 (2025-06-11, the day Madring was traced): "Copyright (c) 2019-2025 Tomislav Bacinger",
in LICENSE.md and in README.md's licence line.

Builds: docs/posters.md at 8834df45e6 (Sources: the traces follow upstream; Layers: track outline points)

Claude-Session: https://claude.ai/code/session_01JG73KFhbaNj3tyJ8tKmE3W
2026-11-30 10:20:37 +01:00
jschoubben 8834df45e6 Write the lead's answers on the circuits' traces into the design
The operator's symptom of 2026-11-30: the 2026 Spanish race poster draws no track, because
Madring's trace is a point. The lead's answers of 2026-11-30 to the questions it raised: a
layout's trace is upstream's newest trace of that circuit (bacinger/f1-circuits), copied once
word for word and never fetched at run time, and a newer upstream trace of a circuit already
drawn is taken as a plain update; the merge check holds that every layout
find_layout_slug_for_year chooses for a season from 2020 on has a LineString trace of more than
10 points (tests/test_traces.py). "Not in this change" now names what remains: three layouts
with an empty trace, Bahrain's offset, and Donington, a copy of Aintree's trace.

Claude-Session: https://claude.ai/code/session_01JG73KFhbaNj3tyJ8tKmE3W
2026-11-30 10:20:26 +01:00
jschoubben 250828710c Serve the picks from the API, so the live picker reads them
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
2026-11-30 10:18:16 +01:00
jschoubben 780984064f Write the lead's lines and answers for the picks routes into the design
The operator's symptom of 2026-11-30: the live picker showed two HTTP 404
errors, one for circuits/photos.json and one for seasons/photos.json,
each with a "Load it from disk" box. The page read the picks relative to
itself, and the API serves only /examples/.

These are the lead's lines and answers of 2026-11-30, written into
Picking photos. The API serves both picks files, read-only, as the poster
service has them loaded, at /picks/circuits.json and /picks/seasons.json:
the notes first, then the entries it draws from, a refused entry left out.
Both routes have the CORS of every route and, like the other JSON routes,
no Cache-Control (answer Q1). The picker reads them from the API base and
falls back to the repository's files only on file: or a loopback host:
localhost, 127.0.0.1, [::1] (answer Q2).

Claude-Session: https://claude.ai/code/session_01JG73KFhbaNj3tyJ8tKmE3W
2026-11-30 10:18:11 +01:00
mesh-tools 57e1bef170 Merge pull request 'Posters from licensed sources only: kept layers, options, credits on every picture' (#8) from feat/poster-layers into master 2026-11-27 14:39:51 +00:00
jschoubben f5257d67bb Join the picker's review-round-1 fixes
Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
2026-11-27 15:35:58 +01:00
jschoubben f8d3083fb4 Show the satellite sources' credits as the service draws them
The picker showed shorter PDOK and USGS credits than the design's lines; it now shows them word
for word, as it does IGN's and EOX's. A season photo dated by its category says so on its card,
and a candidate with no date gives no entry, since the service refuses one.

Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
2026-11-27 15:35:42 +01:00
jschoubben 1cefc6dd52 Keep asked-for texts clear of the credit band; answer review round 1
At 400 to 640 px the credit band, held to 12 px after scaling, covered the date, the circuit line, the session
label and the season's subtitle. The band is now laid out first and every bottom text, the photo inset and the
poster's dark band are lifted by as much as it would cover them, which at full size is nothing, so classic draws
as before; the bottom checker is drawn last again, over the track's end. A first render now draws from the layer
as kept, so it matches every later render of its key, and the ETag is weak all the same. A Commons file's SHA-1
is kept beside the layers and asked once, so photo pictures need no Commons request after a restart. The USGS
credit carries no prefix, and /licences names a layout switched to the map among OpenStreetMap's uses.

Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
2026-11-27 15:34:38 +01:00
jschoubben f96db9f4ac List the candidates again, every season photo dated
The run of 2026-11-27 (892 requests) changed 8 season candidates and nothing else: each had no
date of its own and now takes its season's year from its category (1969 twice, 1973, 1981, 1989,
1991, 2003, 2008). 31 of 122 layouts and 77 of 77 seasons still have a candidate.

Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
2026-11-27 15:34:22 +01:00
jschoubben 58ac9472d0 Date an undated season photo by its season
A photo filed under "<year> Formula One season cars" is of that season, and the service refuses
a pick without a date: a season candidate whose file gives none takes the season's year, marked
"date_from": "category". An undated layout candidate still stays out.

Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
2026-11-27 15:30:31 +01:00
jschoubben d32e57ec41 Write the operator's decisions and the lead's answers into the design
Since the first draft: Commons photos left bg=satellite for an explicit
bg=photo; EOX's 2016 mosaic was rejected for the newest; IGN takes its
frozen 2021-2023 mosaic; a layout can be switched to the map; photo
treatments are natural (default) or bw; a picture's licence follows its
sources; and the builders' questions (presets per frame, placement, dim,
season options, the picks' key and shape, header folding, the smallest
width) are answered where they belong.

Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
2026-11-27 15:21:24 +01:00
jschoubben 812b01b9dd Join the photo picker and the example pages into the poster layers
Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
2026-11-27 15:20:34 +01:00
jschoubben 445235ca58 Show bg=photo apart from bg=satellite, on the service's layers
The operator, after seeing real posters: EOX's 2016 mosaic is rejected, and a layout's Commons
photo now serves only an explicit bg=photo, which falls back to what bg=satellite draws. The
picker therefore puts the satellite-or-map choice first, per layout, on the layers the service
uses (PDOK HR, IGN's frozen BD ORTHO 2021-2023, USGS, EOxCloudless 2025), and offers the photos
as optional for bg=photo. One picks entry may carry a photo, "use": "map", or both, and each
choice keeps the other half. The builder and the posters page offer bg=photo; width starts at
400; the licences page sets the options in "used for" as code.

Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
2026-11-27 15:20:09 +01:00
jschoubben 4362e2d10b Draw a picked photo only with bg=photo, keep bg=satellite to aerial imagery
The operator judged the Commons-photo poster unfit as a default: its crop lands beside the circuit and shows the
track only as an inset. bg=satellite is now the national aerial photo, else EOxCloudless (or the dark map where
"use": "map" is set); the new bg=photo draws the layout's picked photo and without one falls back to what
bg=satellite draws. A picks entry may hold the photo fields, "use": "map", or both; an unknown use and incomplete
photo fields are refused at load. The smallest width is 400 px so the full credit line stays readable, and the
ASCII credit header spells out ß, æ, ø, œ and đ so names stay readable.

Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
2026-11-27 15:18:09 +01:00
jschoubben d514eb57a3 Name an unknown circuit, layout or year with a 404 instead of a 500
The circuit and track routes walked circuits.json with chained lookups, so an unknown country, locality, circuit
or layout, or a year no layout covers, raised and answered 500 (/circuits/photos.json among them). One lookup now
names the first unknown part and the API answers it 404. numpy loads only where a script uses it, so the models,
and this lookup's test, need the standard library alone.

Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
2026-11-27 15:13:34 +01:00
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
jschoubben 4a9bd4464b Let the picker keep a layout's satellite or give it the map instead
EOX's newest mosaic suits some circuits and not others (the operator, 2026-11-27). Beside a
layout's Commons candidates the picker now frames its trace on what bg=satellite draws without
a photo: the country's own aerial photo (PDOK, IGN, USGS) and EOxCloudless (2016 for a layout
raced in or before 2016, else 2025), with each picture's licence, and the service's own poster
on request. "Keep the satellite" means no entry; "use the map instead" gives {"use": "map"},
from which the service draws the dark map for that layout.

Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
2026-11-27 15:13:20 +01:00
jschoubben c3c98a9a74 Show the map's satellite layer from EOxCloudless, not Esri
docs/posters.md drops Esri as a source: its terms forbid how this site uses it. The GPS-trace map
now takes its satellite layer from EOX's newest Sentinel-2 mosaic, the posters' own fallback,
credited and licensed (CC BY-NC-SA 4.0) in the map's corner; the scale moves to the top left so
the two-line credit does not cover it.

Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
2026-11-27 15:07:10 +01:00
jschoubben 49a2ebcf15 Add the photo picker, poster builder and licences pages
A pick is a repository edit, so the picker shows the Commons candidates cropped to the poster's
frame, natural or bw as the service treats them, beside the picks of the circuit's other
layouts, and gives the entry to copy (the picks file's "$comment" kept first). The builder sends
every option of docs/posters.md as a query parameter, renders only on request and shows the
answer's X-Credits and X-License. The licences page shows /licences: each source, its credit and
the licence a picture made from it gets.

Every page now carries the Formula 1 disclaimer at its foot, as F1's guidelines ask of an
unofficial site, and the posters page lists the backgrounds the design keeps (no Esri).

Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
2026-11-27 15:04:38 +01:00
jschoubben d087b8a4f3 List the Commons candidates for the photo picker
Made by tools/commons_candidates.py on 2026-11-27 with 892 requests: 31 of 122 layouts and
77 of 77 seasons have at least one candidate; 91 layouts have none, mostly layouts raced
before 1980.

Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
2026-11-27 15:01:59 +01:00
jschoubben ab9e141cdf Add a tool that lists the Commons photos a poster may use
The posters take an aerial photo per layout and a car photo per season only from Wikimedia
Commons files under CC0, public domain, CC BY or CC BY-SA (docs/posters.md, "Picking photos").
The tool reads each file's licence, author, credit, date and quality marks from the API, keeps
only aerial photos dated within a layout's years, ranks quality marks, size and landscape first,
and keeps Commons' rules: a descriptive User-Agent, one request at a time, at most five a second.

Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
2026-11-27 14:57:55 +01:00
jschoubben 4f00403e13 Design the posters: licensed sources, kept layers, options, credits
Decided with the operator on 2026-11-27 after reading every source's
terms: Esri (and Bing, Azure, Google, Mapbox, MapTiler) do not allow
keeping or serving images made from their maps, so satellite pictures
come from picked Commons photos, national open aerial photos and
EOxCloudless, maps from OpenStreetMap. Heavy layers are fetched once and
kept; options are drawn on the fly; every picture carries its sources'
credits. The design lives in docs/posters.md.

Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
2026-11-27 14:37:13 +01:00
54 changed files with 62938 additions and 1443 deletions
+3
View File
@@ -4,3 +4,6 @@ __pycache__/
cache/ cache/
.idea/ .idea/
.venv-site/ .venv-site/
# The poster service's kept layers and finished pictures, when run from here
/layers/
/posters/
+1 -1
View File
@@ -1,4 +1,4 @@
Copyright (c) 2019-2024 Tomislav Bacinger Copyright (c) 2019-2025 Tomislav Bacinger
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
+49 -13
View File
@@ -10,6 +10,8 @@ Kometa.
* **The data**: [circuits/circuits.json](circuits/circuits.json) and one folder per circuit under * **The data**: [circuits/circuits.json](circuits/circuits.json) and one folder per circuit under
[circuits/](circuits/) — 77 circuits, 122 layouts [circuits/](circuits/) — 77 circuits, 122 layouts
How posters are made (sources and their licences, kept layers, options, credits): [docs/posters.md](docs/posters.md).
## The API ## The API
| Request | Answers | | Request | Answers |
@@ -22,15 +24,39 @@ Kometa.
| `GET /circuits/{country}/{locality}/{circuit}/layout/{layout}/{format}` | the layout's file: `geojson`, `svg` or `png` | | `GET /circuits/{country}/{locality}/{circuit}/layout/{layout}/{format}` | the layout's file: `geojson`, `svg` or `png` |
| `GET /tracks/{country}/{locality}/{circuit}/year/{year}/{format}` | the layout the circuit used that year | | `GET /tracks/{country}/{locality}/{circuit}/year/{year}/{format}` | the layout the circuit used that year |
| `GET /grand-prix/{race}/{season}/{format}` | the layout a race ran on, such as `/grand-prix/Qatar Grand Prix/2025/geojson` | | `GET /grand-prix/{race}/{season}/{format}` | the layout a race ran on, such as `/grand-prix/Qatar Grand Prix/2025/geojson` |
| `GET /posters/race/{race}/{season}.png?bg=…` | a 1000×1500 race poster; `bg` is `aerial` (default), `osm`, `dark`, `light` or `none` | | `GET /posters/race/{race}/{season}.png?…` | a 1000×1500 race poster: the round, the race's name and date and its track over a picture of its circuit |
| `GET /posters/season/{season}.png` | a 1000×1500 season poster | | `GET /posters/season/{season}.png?…` | a 1000×1500 season poster: the year over a picked photo of that season's cars, or over black |
| `GET /posters/session/{race}/{season}/{session}.png` | a 1920×1080 thumbnail for one session, such as `fp1`, `qualifying`, `sprint` or `race` | | `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 /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`),
`photo` (`natural`, `bw`), `show` (a comma list of `wordmark`, `round`, `name`, `subtitle`, `date`, `circuit`,
`locality`, `session`), `locator` and `checker` (`on`, `off`), `track` (`off`, or a colour with an optional width,
`#ffffff,6`), `dim` (0 to 1), `accent` (a colour), `width` (400 up to the picture's own) and `format` (`png`, `jpg`,
`webp`). An unknown option or value is answered 422, naming it. `bg=satellite` takes the national aerial photo
(USGS in the United States, PDOK in the Netherlands, IGN in France), else EOxCloudless; `{"use": "map"}` for a
layout in [circuits/photos.json](circuits/photos.json) makes it draw the dark map instead of EOxCloudless. `bg=photo`
takes the layout's picked Wikimedia Commons photo from that file, with the track as an inset, and without a pick
falls back to `bg=satellite`; no style takes it by default. Every picture carries the credit line of its sources at its
bottom and in `X-Credits`, its licence in `X-License` (it follows its sources), and `Link: </licences>; rel="license"`.
An unknown country, locality, circuit or layout, or a year no layout of the circuit covers, is answered 404, naming it.
A race is named as [Jolpica](https://github.com/jolpica/jolpica-f1) (the Ergast API's successor) names it in A race is named as [Jolpica](https://github.com/jolpica/jolpica-f1) (the Ergast API's successor) names it in
its schedule, and its circuit is found by Jolpica's circuit id (`ergastId` in `circuits.json`), never by the its schedule, and its circuit is found by Jolpica's circuit id (`ergastId` in `circuits.json`), never by the
circuit's name: Jolpica renames circuits (Losail became Lusail), the id stays. circuit's name: Jolpica renames circuits (Losail became Lusail), the id stays.
## Guides
Step-by-step guides for putting the posters in a media server, on the site at https://f1-circuits.zurag.be/guides/:
* [Plex](guides/plex.html), with Kometa: https://f1-circuits.zurag.be/guides/plex.html
* [Emby](guides/emby.html), by hand or as picture files: https://f1-circuits.zurag.be/guides/emby.html
## The data ## The data
`circuits/circuits.json` holds country → locality → circuit → layout. A circuit has its `name`, its Jolpica `circuits/circuits.json` holds country → locality → circuit → layout. A circuit has its `name`, its Jolpica
@@ -131,18 +157,27 @@ rate limit and kept in `cache/jolpica/`; a throttled or failed fetch is said in
## Caching ## Caching
What the service fetches or renders is kept in `cache/` (the module's cache volume): race schedules from Jolpica Race schedules from Jolpica are kept in `cache/jolpica/` (a season that is over for good, the running one for six
in `cache/jolpica/` (a season that is over for good, the running one for six hours), and every poster and thumbnail hours). What a picture needs from the network is a layer, kept for good in `layers/` (the module's `layers` directory,
in `cache/posters/` once every map tile and photo it needs came. A poster is sent with an `ETag` and a day's backed up and fetched again if lost): the map picture of one source around a layout, a picked photo cropped to the
`Cache-Control`; one whose map or photo failed is not kept, and is sent with five minutes', so it is rendered again picture, the world locator and the track's outline. A layer is kept only whole, when every tile came and they are
once its source answers. Map tiles are fetched in parallel, at most six at once from Esri and two from not all one picture. Every finished picture is kept in `posters/` under a key of its route, its options and its
OpenStreetMap. layers, at most 2 GB, the least recently used going first; a second season of a circuit draws from the kept layers
and fetches nothing. A picture whose map or photo did not arrive is served without it, kept nowhere, and sent with
five minutes' `Cache-Control` and no `ETag`.
Clients keep an address that carries the address version (`?v=a1`, as the Kometa file writes it) for good
(`immutable`); any other address a day, then ask again with its `ETag` and get a 304 while it is unchanged. Every
request the service makes carries the User-Agent `f1-circuits/<version> (+<its public address>)`. OpenStreetMap tiles
are fetched only when a picture asks for them, at most two at once; Wikimedia Commons is asked one request at a time.
## Checks ## Checks
`merge-check.sh` runs before a change merges: every Python file the service ships must parse, and the tests in `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 `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). kept, every link in this README leads to a file, every directory the service serves is copied into its image, an
unknown circuit or layout is named; a poster's satellite source, credits and licence, its options, keys and cache
headers, the picture store's cap, and the picks `/picks/…` answers).
## Acknowledgment ## Acknowledgment
@@ -150,8 +185,9 @@ kept, every link in this README leads to a file).
[initial data source](https://www.google.com/maps/d/u/0/viewer?mid=1nv6ugq4H67CSzKUauW92-pPstYw&ll=-37.84579005412956%2C144.96881158570557&z=16) [initial data source](https://www.google.com/maps/d/u/0/viewer?mid=1nv6ugq4H67CSzKUauW92-pPstYw&ll=-37.84579005412956%2C144.96881158570557&z=16)
and altitudes (from [Highs and lows - which F1 track has the most elevation changes?](https://www.formula1.com/en/latest/features/2016/10/highs-and-lows---which-f1-track-has-the-most-elevation-changes-.html)) and altitudes (from [Highs and lows - which F1 track has the most elevation changes?](https://www.formula1.com/en/latest/features/2016/10/highs-and-lows---which-f1-track-has-the-most-elevation-changes-.html))
are kept in the upstream files. are kept in the upstream files.
* Race schedules from [Jolpica](https://github.com/jolpica/jolpica-f1); poster backgrounds from Esri (World Imagery * Race schedules from [Jolpica](https://github.com/jolpica/jolpica-f1) (CC BY-NC-SA 4.0); the posters' pictures from
and the grey canvases) and OpenStreetMap. Wikimedia Commons, USGS, PDOK (Beeldmateriaal Nederland), IGN, EOX (EOxCloudless) and OpenStreetMap, each under
its licence and with its credit: `/licences` and [docs/posters.md](docs/posters.md).
## Disclaimer ## Disclaimer
@@ -163,4 +199,4 @@ Formula 1™ circuits data are not official, and they are not approved nor endor
## License ## License
[The MIT License (MIT)](LICENSE.md) - Copyright (c) 2019-2024 Tomislav Bacinger [The MIT License (MIT)](LICENSE.md) - Copyright (c) 2019-2025 Tomislav Bacinger
+17
View File
@@ -0,0 +1,17 @@
"""Who this service is to the outside: its version, its public address and the User-Agent it sends.
Standard library only: the Jolpica client, the poster sources and the API share it.
"""
import os
# The API's own version (cdn-api.py's FastAPI app says the same).
APP_VERSION = "1.0.0"
# The address this service is reached at, which the Kometa metadata links every poster to and every outgoing
# request names. The mesh writes it from the name the route is served under (F1_CIRCUITS_BASE_URL); the fallback
# is the address HAL served it at, so a deployment that sets nothing behaves as before.
PUBLIC_BASE_URL = os.environ.get("F1_CIRCUITS_BASE_URL", "https://f1-circuits.zurag.be").rstrip("/")
# Every outgoing request carries it (Jolpica, the map and photo sources): the app's name and its public address,
# never a person's address.
USER_AGENT = f"f1-circuits/{APP_VERSION} (+{PUBLIC_BASE_URL})"
+123 -73
View File
@@ -1,32 +1,42 @@
import hashlib
from fastapi import FastAPI, HTTPException, Request, Response from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.responses import FileResponse, Response as FastAPIResponse, PlainTextResponse from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, PlainTextResponse
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from pathlib import Path from pathlib import Path
from typing import Optional
import logging import logging
# Import our CircuitService # Import our CircuitService
from circuits_service import CircuitService, Format from app_info import APP_VERSION
from posters_service import PostersService, BackgroundStyle from circuits_service import CircuitService, Format, NotFound
from posters_service import PostersService, Rendered
import poster_options
import poster_sources
from access_log import log_request from access_log import log_request
from models.track_layout import TrackLayout from models.track_layout import TrackLayout
# Initialize FastAPI app # The unofficial-use disclaimer for the Formula 1 marks, at the foot of / and /docs (and of the example site).
DISCLAIMER = ("This service is unofficial and is not associated in any way with the Formula 1 companies. F1, FORMULA "
"ONE, FORMULA 1, FIA FORMULA ONE WORLD CHAMPIONSHIP, GRAND PRIX, and related marks are trademarks of "
"Formula One Licensing B.V.")
# Initialize FastAPI app; /docs is served below, with the disclaimer at its foot
app = FastAPI( app = FastAPI(
title="F1 Track Layouts API", title="F1 Track Layouts API",
description="API serving F1 track layout images, vectors and GeoJSON files", description="API serving F1 track layout images, vectors and GeoJSON files",
version="1.0.0" version=APP_VERSION,
docs_url=None,
) )
# Add CORS middleware # Add CORS middleware. The example pages, opened from another origin, read a picture's credits and licence.
app.add_middleware( app.add_middleware(
CORSMiddleware, CORSMiddleware,
allow_origins=["*"], allow_origins=["*"],
allow_credentials=True, allow_credentials=True,
allow_methods=["*"], allow_methods=["*"],
allow_headers=["*"], allow_headers=["*"],
expose_headers=["X-Credits", "X-License", "Link", "ETag"],
) )
# Configure logging # Configure logging
@@ -84,11 +94,45 @@ async def root():
"/posters/season/{season}.png", "/posters/season/{season}.png",
"/posters/session/{grand_prix_name}/{season}/{session_slug}.png", "/posters/session/{grand_prix_name}/{season}/{session_slug}.png",
"/kometa/formula-1-metadata.yml", "/kometa/formula-1-metadata.yml",
"/licences",
*poster_sources.PICKS_ROUTES,
], ],
"examples": "/examples/", "examples": "/examples/",
"guides": "/guides/",
"disclaimer": DISCLAIMER,
} }
@app.get("/docs", include_in_schema=False)
async def docs() -> HTMLResponse:
"""The OpenAPI docs, with the disclaimer at their foot."""
page = get_swagger_ui_html(openapi_url=app.openapi_url, title=f"{app.title} - docs").body.decode()
footer = (f'<footer style="font-family: sans-serif; font-size: 12px; color: #666; margin: 2em; '
f'text-align: center">{DISCLAIMER}</footer>')
return HTMLResponse(page.replace("</body>", f"{footer}</body>"))
@app.get("/licences")
async def get_licences():
"""Every source a picture may be made from: its licence, its credit and its terms' address, and how a picture's
licence follows from them."""
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). # The example site: one page per area of the API, each calling the routes above (examples/index.html).
app.mount( app.mount(
"/examples", "/examples",
@@ -96,70 +140,89 @@ app.mount(
name="examples", name="examples",
) )
# The guides: step by step, putting the posters in a Plex or Emby library (guides/index.html), in the style of the
# example site.
app.mount(
"/guides",
StaticFiles(directory=Path(__file__).resolve().parent / "guides", html=True),
name="guides",
)
# The poster routes are plain defs, not async: a render fetches map tiles and a schedule and draws for # The poster routes are plain defs, not async: a render fetches map tiles and a schedule and draws for
# seconds, so it runs in the threadpool instead of holding up every other request on the event loop. # seconds, so it runs in the threadpool instead of holding up every other request on the event loop.
def poster_response(request: Request, png: bytes, kept: bool) -> Response: POSTER_OPTIONS_DOC = """Options are query parameters, the same on every poster route (docs/posters.md); an unknown option
"""A stored poster: clients keep it a day, then ask again with its ETag and get a 304 while it is or value is answered 422, naming it: `style` (classic, minimal), `bg` (satellite, its alias aerial, photo, osm,
unchanged, so a poster whose look changed reaches them within a day, not a year. A poster whose map dark, light, none), `photo` (natural, bw), `show` (a comma list of wordmark, round, name, subtitle, date, circuit,
or photo failed is kept by clients for five minutes, with no ETag, so they ask again soon.""" locality, session), `locator` and `checker` (on, off), `track` (off, or #rrggbb with an optional width:
if not kept: #ffffff,6), `dim` (0 to 1), `accent` (#rrggbb), `width` (400 up to the frame's), `format` (png, jpg, webp), and
return FastAPIResponse(content=png, media_type="image/png", headers={"Cache-Control": "public, max-age=300"}) `v`, the address version, which the Kometa file adds so clients keep the picture for good."""
etag = '"' + hashlib.sha256(png).hexdigest()[:32] + '"'
headers = {"Cache-Control": "public, max-age=86400", "ETag": etag}
if etag in [tag.strip().removeprefix("W/") for tag in request.headers.get("if-none-match", "").split(",")]: def render_poster(request: Request, kind: str, grand_prix_name: Optional[str] = None, season: Optional[int] = None,
session_slug: Optional[str] = None) -> Response:
"""A picture with its credits, its licence and what clients may keep of it.
An address with the current address version (?v=) is kept for good; any other a day, then asked again with its
ETag (a 304 while it is unchanged); a picture served without its map or photo five minutes, with no ETag."""
try:
options = poster_options.parse_options(request.query_params.multi_items(), kind)
except poster_options.OptionError as e:
return JSONResponse(status_code=422, content={"detail": str(e)})
try:
rendered: Optional[Rendered] = posters_service.render(kind, options, grand_prix_name, season, session_slug)
except poster_sources.LicenceClash as e:
logger.error(f"Picture refused, {kind} {grand_prix_name} {season} {session_slug}: {e}")
raise HTTPException(status_code=500, detail=f"Picture refused: {e}")
if rendered is None:
what = " ".join(str(part) for part in (grand_prix_name, season, session_slug) if part is not None)
raise HTTPException(status_code=404, detail=f"No {kind} picture available for {what}")
# Weak: two first renders of one key side by side may differ in their bytes, never in what they show.
etag = 'W/"' + rendered.name.split(".")[0][:32] + '"'
headers = poster_options.cache_headers(rendered.kept, options.versioned, etag)
headers.update({"X-Credits": poster_sources.ascii_header(rendered.credit), "X-License": rendered.licence,
"Link": '</licences>; rel="license"'})
if rendered.kept and poster_options.etag_matches(request.headers.get("if-none-match", ""), etag):
return Response(status_code=304, headers=headers) return Response(status_code=304, headers=headers)
return FastAPIResponse(content=png, media_type="image/png", headers=headers) return Response(content=rendered.data, media_type=rendered.media_type, headers=headers)
@app.get("/posters/race/{grand_prix_name}/{season}.png") @app.get("/posters/race/{grand_prix_name}/{season}.png", description=POSTER_OPTIONS_DOC)
def get_race_poster(request: Request, grand_prix_name: str, season: int, bg: BackgroundStyle = BackgroundStyle.AERIAL): def get_race_poster(request: Request, grand_prix_name: str, season: int):
"""Plex-ready 1000x1500 race poster (PNG). Cached on disk per (race, bg). """Plex-ready 1000x1500 race poster: the round, the race's name and date and its track over a map or photo of
its circuit."""
`?bg=` selects the backdrop: return render_poster(request, "race", grand_prix_name, season)
- aerial (default) — Esri World Imagery satellite at the circuit's coords
- osm — OpenStreetMap Carto street-map at the circuit's coords
- dark — Esri Dark Gray Canvas
- light — Esri Light Gray Canvas
- none — plain black background (skip tile fetch)
"""
rendered = posters_service.render_race_poster(grand_prix_name, season, bg=bg)
if not rendered:
raise HTTPException(status_code=404, detail=f"No poster available for {grand_prix_name} {season}")
return poster_response(request, *rendered)
@app.get("/posters/season/{season}.png") @app.get("/posters/season/{season}.png", description=POSTER_OPTIONS_DOC)
def get_season_poster(request: Request, season: int): def get_season_poster(request: Request, season: int):
"""Plex-ready 1000x1500 season poster (PNG). Cached on disk.""" """Plex-ready 1000x1500 season poster: the year over a picked photo of that season's cars, or over black."""
return poster_response(request, *posters_service.render_season_poster(season)) return render_poster(request, "season", season=season)
@app.get("/posters/session/{grand_prix_name}/{season}/{session_slug}.png") @app.get("/posters/session/{grand_prix_name}/{season}/{session_slug}.png", description=POSTER_OPTIONS_DOC)
def get_session_thumb(request: Request, grand_prix_name: str, season: int, session_slug: str): def get_session_thumb(request: Request, grand_prix_name: str, season: int, session_slug: str):
"""Plex episode-thumb (1920x1080) for a specific session of a race weekend. """Plex episode-thumb (1920x1080) for one session of a race weekend.
`session_slug` is one of: fp1, fp2, fp3, pre-qualifying, qualifying, `session_slug` is one of: fp1, fp2, fp3, pre-qualifying, qualifying,
post-qualifying, pre-race, race, post-race, highlights, pre-sprint, post-qualifying, pre-race, race, post-race, highlights, pre-sprint,
sprint, post-sprint, pre-sprint-qualifying, sprint-qualifying, sprint, post-sprint, pre-sprint-qualifying, sprint-qualifying,
post-sprint-qualifying, bonus. post-sprint-qualifying, bonus.
""" """
rendered = posters_service.render_session_thumb(grand_prix_name, season, session_slug) return render_poster(request, "session", grand_prix_name, season, session_slug)
if not rendered:
raise HTTPException(status_code=404, detail=f"No session thumb for {grand_prix_name} {season} {session_slug}")
return poster_response(request, *rendered)
@app.get("/kometa/formula-1-metadata.yml") @app.get("/kometa/formula-1-metadata.yml")
def get_kometa_metadata(): def get_kometa_metadata():
"""Generate a Kometa-compatible metadata YAML for the Formula 1 library. """Generate a Kometa-compatible metadata YAML for the Formula 1 library.
One entry per F1 season from 1950..current+1. Each entry: Its first lines say where its data comes from (Jolpica, CC BY-NC-SA 4.0). One entry per F1 season from
1950..current+1. Each entry:
- uses Kometa's f1_season builder for round/episode names - uses Kometa's f1_season builder for round/episode names
- sets url_poster on the show (per-season hero from files-api) - sets url_poster on the show (the season poster)
- sets url_poster on each Plex 'season' (== each F1 round) from the - sets url_poster on each Plex 'season' (== each F1 round) from the race poster route, and on each episode
f1-circuits race poster endpoint from the session thumbnail route; every address carries ?v=<address version>
Kometa harmlessly skips shows / seasons that don't exist in the Plex Kometa harmlessly skips shows / seasons that don't exist in the Plex
library, so we can emit the full schedule and let Kometa do the matching. library, so we can emit the full schedule and let Kometa do the matching.
@@ -182,37 +245,31 @@ async def get_countries():
"countries": [c.to_dict() for c in circuit_service.get_countries_list()] "countries": [c.to_dict() for c in circuit_service.get_countries_list()]
} }
@app.exception_handler(NotFound)
async def not_found(request: Request, error: NotFound) -> JSONResponse:
"""A country, locality, circuit or layout circuits.json does not hold, or a year no layout covers: named."""
return JSONResponse(status_code=404, content={"detail": str(error)})
@app.get("/circuits/{country_slug}") @app.get("/circuits/{country_slug}")
async def get_cities(country_slug: str): async def get_cities(country_slug: str):
"""Get list of cities for a specific country""" """Get list of cities for a specific country"""
cities = circuit_service.get_localities_list(country_slug) return {"cities": [c.to_dict() for c in circuit_service.get_localities_list(country_slug)]}
if not cities:
raise HTTPException(status_code=404, detail="Country not found")
return {"cities": [c.to_dict() for c in cities]}
@app.get("/circuits/{country_slug}/{city_slug}") @app.get("/circuits/{country_slug}/{city_slug}")
async def get_circuits(country_slug: str, city_slug: str): async def get_circuits(country_slug: str, city_slug: str):
"""Get list of circuits for a specific city""" """Get list of circuits for a specific city"""
circuits = circuit_service.get_circuits_list(country_slug, city_slug) return {"circuits": [c.to_dict() for c in circuit_service.get_circuits_list(country_slug, city_slug)]}
if not circuits:
raise HTTPException(status_code=404, detail="City not found")
return {"circuits": [c.to_dict() for c in circuits]}
@app.get("/circuits/{country_slug}/{city_slug}/{circuit_slug}") @app.get("/circuits/{country_slug}/{city_slug}/{circuit_slug}")
async def get_circuit_details(country_slug: str, city_slug: str, circuit_slug: str): async def get_circuit_details(country_slug: str, city_slug: str, circuit_slug: str):
"""Get circuit details and available formats""" """Get circuit details and available formats"""
circuit_details = circuit_service.get_circuit_details(country_slug, city_slug, circuit_slug) return circuit_service.resolve(country_slug, city_slug, circuit_slug).to_dict()
if not circuit_details:
raise HTTPException(status_code=404, detail="Circuit not found")
return circuit_details.to_dict()
@app.get("/circuits/{country_slug}/{city_slug}/{circuit_slug}/layout/{layout_slug}") @app.get("/circuits/{country_slug}/{city_slug}/{circuit_slug}/layout/{layout_slug}")
async def get_layout_details(country_slug: str, city_slug: str, circuit_slug: str, layout_slug: str): async def get_layout_details(country_slug: str, city_slug: str, circuit_slug: str, layout_slug: str):
"""Get details for a specific layout""" """Get details for a specific layout"""
layout_details = circuit_service.get_layout_details(country_slug, city_slug, circuit_slug, layout_slug) return circuit_service.resolve(country_slug, city_slug, circuit_slug, layout_slug).to_dict()
if not layout_details:
raise HTTPException(status_code=404, detail="Layout not found")
return layout_details.to_dict()
@app.get("/tracks/{country_slug}/{city_slug}/{circuit_slug}/year/{year}/{image_format}") @app.get("/tracks/{country_slug}/{city_slug}/{circuit_slug}/year/{year}/{image_format}")
async def get_track_by_year( async def get_track_by_year(
@@ -224,16 +281,8 @@ async def get_track_by_year(
response: Response response: Response
): ):
"""Get track layout for a specific year""" """Get track layout for a specific year"""
circuit_details = circuit_service.get_circuit_details(country_slug, city_slug, circuit_slug) return get_file_response(circuit_service.layout_for_year(country_slug, city_slug, circuit_slug, year),
if not circuit_details: image_format, response)
raise HTTPException(status_code=404, detail="Circuit not found")
try:
layout_slug = circuit_service.find_layout_slug_for_year(circuit_details, year)
return get_file_response(circuit_service.get_layout_details(country_slug, city_slug, circuit_slug, layout_slug), image_format, response)
except KeyError as e:
logger.error(f"KeyError in get_track_by_year: {str(e)}")
raise HTTPException(status_code=404, detail="Circuit or layout not found")
@app.get("/circuits/{country_slug}/{city_slug}/{circuit_slug}/layout/{layout_slug}/{image_format}") @app.get("/circuits/{country_slug}/{city_slug}/{circuit_slug}/layout/{layout_slug}/{image_format}")
async def get_track_by_layout( async def get_track_by_layout(
@@ -245,7 +294,8 @@ async def get_track_by_layout(
response: Response response: Response
): ):
"""Get specific track layout""" """Get specific track layout"""
return get_file_response(circuit_service.get_layout_details(country_slug, city_slug, circuit_slug, layout_slug), image_format, response) return get_file_response(circuit_service.resolve(country_slug, city_slug, circuit_slug, layout_slug),
image_format, response)
@app.get("/grand-prix/{grand_prix_name}/{season}/{image_format}") @app.get("/grand-prix/{grand_prix_name}/{season}/{image_format}")
def get_grand_prix_circuit(grand_prix_name: str, season: int, image_format: Format, response: Response): def get_grand_prix_circuit(grand_prix_name: str, season: int, image_format: Format, response: Response):
@@ -3,7 +3,7 @@
"name": "az-2016", "name": "az-2016",
"bbox": [ "bbox": [
49.830927, 49.830927,
40.362639, 40.362541,
49.855189, 49.855189,
40.376148 40.376148
], ],
@@ -15,21 +15,13 @@
"Location": "Baku", "Location": "Baku",
"Name": "Baku City Circuit", "Name": "Baku City Circuit",
"opened": 2016, "opened": 2016,
"seasons": [ "firstgp": 2016,
2017,
2018,
2019,
2021,
2022,
2023,
2024
],
"length": 6003, "length": 6003,
"altitude": -25 "altitude": -25
}, },
"bbox": [ "bbox": [
49.830927, 49.830927,
40.362639, 40.362541,
49.855189, 49.855189,
40.376148 40.376148
], ],
@@ -41,340 +33,340 @@
40.372688 40.372688
], ],
[ [
49.851442, 49.855023,
40.372113 40.373268
],
[
49.848684,
40.371218
],
[
49.847606,
40.370845
],
[
49.844949,
40.369978
],
[
49.84386,
40.369591
],
[
49.842635,
40.3692
],
[
49.84225,
40.369059
],
[
49.841836,
40.368889
],
[
49.841469,
40.368705
],
[
49.838752,
40.367098
],
[
49.838586,
40.366985
],
[
49.838444,
40.366824
],
[
49.838373,
40.366655
],
[
49.838207,
40.365792
],
[
49.83813,
40.365632
],
[
49.837976,
40.365467
],
[
49.836088,
40.364156
],
[
49.835911,
40.363982
],
[
49.835757,
40.363765
],
[
49.835094,
40.362832
],
[
49.834993,
40.362747
],
[
49.834839,
40.362667
],
[
49.83462,
40.362639
],
[
49.834431,
40.362662
],
[
49.834094,
40.362756
],
[
49.833478,
40.362964
],
[
49.831282,
40.363841
],
[
49.831152,
40.363958
],
[
49.831099,
40.364076
],
[
49.830927,
40.365957
],
[
49.830963,
40.366141
],
[
49.831489,
40.367503
],
[
49.831643,
40.367744
],
[
49.831809,
40.367913
],
[
49.832022,
40.368045
],
[
49.833093,
40.368535
],
[
49.834715,
40.369139
],
[
49.835733,
40.369408
],
[
49.835875,
40.369403
],
[
49.83597,
40.369356
],
[
49.836035,
40.369294
],
[
49.836171,
40.368955
],
[
49.836248,
40.368865
],
[
49.836402,
40.368818
],
[
49.836544,
40.368828
],
[
49.836692,
40.368832
],
[
49.836834,
40.368804
],
[
49.837065,
40.368696
],
[
49.837219,
40.368696
],
[
49.837337,
40.368677
],
[
49.837414,
40.368616
],
[
49.838053,
40.367183
],
[
49.838195,
40.367065
],
[
49.838367,
40.36706
],
[
49.838539,
40.36715
],
[
49.838947,
40.367432
],
[
49.841362,
40.368856
],
[
49.841764,
40.369125
],
[
49.841853,
40.369191
],
[
49.841859,
40.369276
],
[
49.841682,
40.369572
],
[
49.841658,
40.369667
],
[
49.841723,
40.369733
],
[
49.842783,
40.370251
],
[
49.84357,
40.370581
],
[
49.844961,
40.371081
],
[
49.845085,
40.371189
],
[
49.845079,
40.371312
],
[
49.84428,
40.372891
],
[
49.84428,
40.373065
],
[
49.84444,
40.373193
],
[
49.846884,
40.374046
],
[
49.849719,
40.375017
],
[
49.851797,
40.37563
],
[
49.853496,
40.376148
],
[
49.853602,
40.376134
],
[
49.853685,
40.376092
],
[
49.854188,
40.37522
],
[
49.854798,
40.374319
],
[
49.855159,
40.373607
],
[
49.855189,
40.37349
],
[
49.855177,
40.373409
], ],
[ [
49.855117, 49.855117,
40.373325 40.373325
], ],
[ [
49.855023, 49.855177,
40.373268 40.373409
],
[
49.855189,
40.37349
],
[
49.855159,
40.373607
],
[
49.854693,
40.374371
],
[
49.854188,
40.37522
],
[
49.853685,
40.376092
],
[
49.853602,
40.376134
],
[
49.853496,
40.376148
],
[
49.851797,
40.37563
],
[
49.849719,
40.375017
],
[
49.846884,
40.374046
],
[
49.84444,
40.373193
],
[
49.84423,
40.373102
],
[
49.844188,
40.372906
],
[
49.845096,
40.371215
],
[
49.845087,
40.371103
],
[
49.844467,
40.370887
],
[
49.843241,
40.370488
],
[
49.842408,
40.370106
],
[
49.841935,
40.369878
],
[
49.841731,
40.369687
],
[
49.841736,
40.369485
],
[
49.841859,
40.369244
],
[
49.841817,
40.369132
],
[
49.84166,
40.369013
],
[
49.840066,
40.368088
],
[
49.838947,
40.367432
],
[
49.838477,
40.367168
],
[
49.838321,
40.367075
],
[
49.838174,
40.367071
],
[
49.838053,
40.367183
],
[
49.837442,
40.368517
],
[
49.837345,
40.368726
],
[
49.837243,
40.368755
],
[
49.837091,
40.368716
],
[
49.836893,
40.3688
],
[
49.836732,
40.368858
],
[
49.836434,
40.368845
],
[
49.836255,
40.368863
],
[
49.836168,
40.368917
],
[
49.836123,
40.369052
],
[
49.836011,
40.369317
],
[
49.835893,
40.369447
],
[
49.835721,
40.369434
],
[
49.835016,
40.369241
],
[
49.834382,
40.369045
],
[
49.832977,
40.368541
],
[
49.831946,
40.368068
],
[
49.83169,
40.36792
],
[
49.831539,
40.367693
],
[
49.831265,
40.366983
],
[
49.830942,
40.36612
],
[
49.830927,
40.365957
],
[
49.831065,
40.364172
],
[
49.831051,
40.364003
],
[
49.831108,
40.363913
],
[
49.833478,
40.362964
],
[
49.833894,
40.362815
],
[
49.834357,
40.362639
],
[
49.834674,
40.362541
],
[
49.83484,
40.36257
],
[
49.834993,
40.362747
],
[
49.835303,
40.363179
],
[
49.835635,
40.363656
],
[
49.835947,
40.36411
],
[
49.836032,
40.364197
],
[
49.837749,
40.365388
],
[
49.837995,
40.365562
],
[
49.838142,
40.365825
],
[
49.838331,
40.36672
],
[
49.838393,
40.366915
],
[
49.83853,
40.367067
],
[
49.838823,
40.367233
],
[
49.841165,
40.368612
],
[
49.841595,
40.36885
],
[
49.841856,
40.368962
],
[
49.842622,
40.369232
],
[
49.844282,
40.36977
],
[
49.845881,
40.370304
],
[
49.847461,
40.370818
],
[
49.848684,
40.371218
],
[
49.851442,
40.372113
], ],
[ [
49.853247, 49.853247,
Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 23 KiB

@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="150px" height="93px" viewBox="0 0 150 93" xmlns="http://www.w3.org/2000/svg"> <svg width="150px" height="93px" viewBox="0 0 150 93" xmlns="http://www.w3.org/2000/svg">
<title>Baku City Circuit - Baku</title> <title>Baku City Circuit - Baku</title>
<path d="M132.27,27.98 L122.12,31.22 L106.62,36.25 L100.56,38.34 L85.63,43.21 L79.51,45.39 L72.62,47.59 L70.46,48.38 L68.13,49.34 L66.07,50.37 L50.80,59.40 L49.87,60.04 L49.07,60.94 L48.67,61.89 L47.74,66.74 L47.30,67.64 L46.44,68.57 L35.83,75.94 L34.83,76.92 L33.97,78.13 L30.24,83.38 L29.67,83.86 L28.81,84.31 L27.57,84.46 L26.51,84.33 L24.62,83.81 L21.16,82.64 L8.81,77.71 L8.08,77.05 L7.78,76.39 L6.82,65.81 L7.02,64.78 L9.98,57.13 L10.84,55.77 L11.78,54.82 L12.97,54.08 L18.99,51.33 L28.11,47.93 L33.83,46.42 L34.63,46.45 L35.16,46.71 L35.53,47.06 L36.29,48.96 L36.72,49.47 L37.59,49.73 L38.39,49.68 L39.22,49.66 L40.02,49.81 L41.32,50.42 L42.18,50.42 L42.85,50.53 L43.28,50.87 L46.87,58.92 L47.67,59.59 L48.63,59.62 L49.60,59.11 L51.89,57.52 L65.47,49.52 L67.73,48.01 L68.23,47.64 L68.26,47.16 L67.27,45.50 L67.13,44.96 L67.50,44.59 L73.45,41.68 L77.88,39.83 L85.70,37.02 L86.39,36.41 L86.36,35.72 L81.87,26.84 L81.87,25.86 L82.77,25.15 L96.50,20.35 L112.44,14.89 L124.12,11.45 L133.67,8.54 L134.26,8.62 L134.73,8.85 L137.56,13.75 L140.98,18.82 L143.01,22.82 L143.18,23.48 L143.11,23.93 L142.78,24.40 L142.25,24.72 L132.27,27.98" fill="none" stroke="black" stroke-width="2"/> <path d="M132.27,27.71 L142.25,24.45 L142.78,24.13 L143.11,23.66 L143.18,23.20 L143.01,22.54 L140.39,18.25 L137.56,13.48 L134.73,8.58 L134.26,8.34 L133.67,8.26 L124.12,11.17 L112.44,14.62 L96.50,20.08 L82.77,24.87 L81.59,25.38 L81.35,26.48 L86.45,35.99 L86.40,36.62 L82.92,37.83 L76.03,40.07 L71.35,42.22 L68.69,43.50 L67.54,44.57 L67.57,45.71 L68.26,47.06 L68.03,47.69 L67.14,48.36 L58.18,53.56 L51.89,57.25 L49.25,58.73 L48.38,59.26 L47.55,59.28 L46.87,58.65 L43.44,51.15 L42.89,49.98 L42.32,49.81 L41.46,50.03 L40.35,49.56 L39.44,49.23 L37.77,49.31 L36.76,49.21 L36.28,48.90 L36.02,48.14 L35.39,46.65 L34.73,45.92 L33.76,46.00 L29.80,47.08 L26.24,48.18 L18.34,51.02 L12.55,53.67 L11.11,54.51 L10.26,55.78 L8.72,59.77 L6.90,64.62 L6.82,65.54 L7.59,75.57 L7.52,76.52 L7.84,77.03 L21.16,82.36 L23.49,83.20 L26.10,84.19 L27.88,84.74 L28.81,84.58 L29.67,83.58 L31.41,81.15 L33.28,78.47 L35.03,75.92 L35.51,75.43 L45.16,68.74 L46.54,67.76 L47.37,66.28 L48.43,61.25 L48.78,60.15 L49.55,59.30 L51.20,58.37 L64.36,50.62 L66.78,49.28 L68.24,48.65 L72.55,47.13 L81.88,44.11 L90.87,41.11 L99.75,38.22 L106.62,35.97 L122.12,30.94 L132.27,27.71" fill="none" stroke="black" stroke-width="2"/>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

+3
View File
@@ -0,0 +1,3 @@
{
"$comment": "The picked Wikimedia Commons aerial photo per layout (docs/posters.md, Picking photos). Key: the layout's path under circuits/ without extension, country/city/circuit/layout, such as \"belgium/spa/circuit-de-spa-francorchamps/1983-\". Value: the photo fields {\"file\": the Commons title without \"File:\", \"licence\": its LicenseShortName (CC0, public domain, CC BY or CC BY-SA only), \"author\", \"credit\": \"Photo: <author>, <licence>, via Wikimedia Commons\", \"date\": YYYY[-MM[-DD]]}, which bg=photo draws; \"use\": \"map\", which makes bg=satellite draw the dark OpenStreetMap map instead of EOxCloudless (a national aerial photo still comes first); or both. Written by the picking tool, read by the poster service; a key starting with \"$\" is a note, not a pick."
}
+479 -16
View File
@@ -1,34 +1,497 @@
{ {
"type": "FeatureCollection", "type": "FeatureCollection",
"name": "es-madring", "name": "es-2026",
"bbox": [ "bbox": [
-3.62, -3.62534,
40.462, 40.464278,
-3.61, -3.611988,
40.47 40.480641
], ],
"features": [ "features": [
{ {
"type": "Feature", "type": "Feature",
"properties": { "properties": {
"id": "es-madring", "id": "es-2026",
"Location": "Madrid", "Location": "Madrid",
"Name": "Madring", "Name": "Circuito de Madring",
"opened": 2026, "opened": 2026,
"length": 5416, "firstgp": 2026,
"altitude": 620 "length": 5474,
"altitude": 646
}, },
"bbox": [ "bbox": [
-3.62, -3.62534,
40.462, 40.464278,
-3.61, -3.611988,
40.47 40.480641
], ],
"geometry": { "geometry": {
"type": "Point", "type": "LineString",
"coordinates": [ "coordinates": [
-3.61528, [
40.46528 -3.616887,
40.465178
],
[
-3.619097,
40.464882
],
[
-3.619229,
40.464821
],
[
-3.61925,
40.464438
],
[
-3.619316,
40.464377
],
[
-3.619673,
40.464327
],
[
-3.620088,
40.464278
],
[
-3.620452,
40.464294
],
[
-3.620904,
40.464438
],
[
-3.621225,
40.464671
],
[
-3.622922,
40.466741
],
[
-3.62384,
40.467827
],
[
-3.624116,
40.468257
],
[
-3.624284,
40.46855
],
[
-3.624364,
40.468728
],
[
-3.624554,
40.469276
],
[
-3.624641,
40.469864
],
[
-3.624612,
40.470307
],
[
-3.624532,
40.470784
],
[
-3.624313,
40.471233
],
[
-3.624095,
40.47151
],
[
-3.624007,
40.471604
],
[
-3.624007,
40.471681
],
[
-3.624131,
40.471737
],
[
-3.624233,
40.471814
],
[
-3.624218,
40.471909
],
[
-3.624131,
40.472003
],
[
-3.62408,
40.472114
],
[
-3.624109,
40.472335
],
[
-3.624262,
40.47274
],
[
-3.624393,
40.473017
],
[
-3.624583,
40.473244
],
[
-3.624743,
40.47341
],
[
-3.62483,
40.473604
],
[
-3.625056,
40.474303
],
[
-3.62518,
40.474563
],
[
-3.625333,
40.47469
],
[
-3.62534,
40.474779
],
[
-3.625209,
40.474857
],
[
-3.624976,
40.474992
],
[
-3.624852,
40.475148
],
[
-3.624852,
40.475303
],
[
-3.624932,
40.475491
],
[
-3.625297,
40.476001
],
[
-3.625326,
40.476142
],
[
-3.62534,
40.477106
],
[
-3.625304,
40.477483
],
[
-3.625158,
40.477641
],
[
-3.624838,
40.477829
],
[
-3.624481,
40.478051
],
[
-3.624342,
40.478262
],
[
-3.62435,
40.478517
],
[
-3.624393,
40.478669
],
[
-3.62483,
40.479472
],
[
-3.624874,
40.479738
],
[
-3.624845,
40.48001
],
[
-3.624692,
40.480254
],
[
-3.624459,
40.480464
],
[
-3.624109,
40.480597
],
[
-3.62373,
40.480641
],
[
-3.623322,
40.480625
],
[
-3.622922,
40.48047
],
[
-3.622536,
40.480209
],
[
-3.622303,
40.47991
],
[
-3.622237,
40.479561
],
[
-3.622266,
40.479245
],
[
-3.622426,
40.478913
],
[
-3.622667,
40.478594
],
[
-3.622791,
40.478439
],
[
-3.623993,
40.477298
],
[
-3.62459,
40.476599
],
[
-3.624641,
40.476477
],
[
-3.624597,
40.476306
],
[
-3.624342,
40.476123
],
[
-3.623483,
40.475666
],
[
-3.623133,
40.475433
],
[
-3.62298,
40.475239
],
[
-3.622907,
40.47504
],
[
-3.622907,
40.47405
],
[
-3.622864,
40.473856
],
[
-3.622725,
40.473629
],
[
-3.622521,
40.473394
],
[
-3.622303,
40.473211
],
[
-3.622004,
40.473072
],
[
-3.621654,
40.472984
],
[
-3.620044,
40.472984
],
[
-3.619768,
40.473078
],
[
-3.619484,
40.4732
],
[
-3.619345,
40.473228
],
[
-3.619221,
40.473144
],
[
-3.618784,
40.472646
],
[
-3.618238,
40.471917
],
[
-3.618129,
40.471734
],
[
-3.61799,
40.471579
],
[
-3.617735,
40.471457
],
[
-3.617488,
40.471424
],
[
-3.616541,
40.471518
],
[
-3.616089,
40.471512
],
[
-3.61563,
40.471391
],
[
-3.615324,
40.471161
],
[
-3.615178,
40.47095
],
[
-3.614654,
40.468719
],
[
-3.614603,
40.468445
],
[
-3.614537,
40.468312
],
[
-3.614348,
40.468295
],
[
-3.614071,
40.468451
],
[
-3.613904,
40.468484
],
[
-3.612782,
40.468589
],
[
-3.61268,
40.468506
],
[
-3.612461,
40.467946
],
[
-3.612228,
40.467212
],
[
-3.61201,
40.466237
],
[
-3.611988,
40.465982
],
[
-3.61217,
40.465821
],
[
-3.612454,
40.465771
],
[
-3.616887,
40.465178
]
] ]
} }
} }
Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

After

Width:  |  Height:  |  Size: 23 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 6.8 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

@@ -2,10 +2,10 @@
"type": "FeatureCollection", "type": "FeatureCollection",
"name": "us-2023", "name": "us-2023",
"bbox": [ "bbox": [
-115.173015, -115.173181,
36.108017, 36.107928,
-115.160217, -115.160107,
36.125492 36.12554
], ],
"features": [ "features": [
{ {
@@ -16,65 +16,101 @@
"Name": "Las Vegas Street Circuit", "Name": "Las Vegas Street Circuit",
"opened": 2023, "opened": 2023,
"firstgp": 2023, "firstgp": 2023,
"length": 6116, "length": 6201,
"altitude": 610 "altitude": 610
}, },
"bbox": [ "bbox": [
-115.173015, -115.173181,
36.108017, 36.107928,
-115.160217, -115.160107,
36.125492 36.12554
], ],
"geometry": { "geometry": {
"type": "LineString", "type": "LineString",
"coordinates": [ "coordinates": [
[ [
-115.162219, -115.161202,
36.109017 36.109904
], ],
[ [
-115.16025, -115.160589,
36.110295 36.110461
],
[
-115.160217,
36.110399
],
[
-115.160308,
36.110513
], ],
[ [
-115.160459, -115.160459,
36.110517 36.110578
], ],
[ [
-115.161489, -115.160366,
36.110472 36.110705
], ],
[ [
-115.162366, -115.160335,
36.110008 36.110856
], ],
[ [
-115.162725, -115.160414,
36.109881 36.110992
], ],
[ [
-115.163063, -115.160543,
36.109861 36.111079
], ],
[ [
-115.163375, -115.160775,
36.109975 36.11115
], ],
[ [
-115.163698, -115.160996,
36.110252 36.111179
], ],
[ [
-115.163981, -115.161209,
36.110815 36.111169
],
[
-115.161408,
36.111121
],
[
-115.161844,
36.110909
],
[
-115.162247,
36.110586
],
[
-115.162402,
36.110503
],
[
-115.162741,
36.110442
],
[
-115.162924,
36.110445
],
[
-115.163255,
36.110535
],
[
-115.163438,
36.110617
],
[
-115.163608,
36.110734
],
[
-115.16389,
36.111042
],
[
-115.164004,
36.111303
], ],
[ [
-115.164082, -115.164082,
@@ -85,52 +121,96 @@
36.119152 36.119152
], ],
[ [
-115.163838, -115.163908,
36.11919 36.119211
], ],
[ [
-115.162026, -115.161934,
36.119181
],
[
-115.161342,
36.119184 36.119184
], ],
[ [
-115.161677, -115.161033,
36.119275 36.119242
], ],
[ [
-115.1614, -115.160908,
36.119472 36.119329
], ],
[ [
-115.160834, -115.160559,
36.120057 36.119604
], ],
[ [
-115.160596, -115.160402,
36.120547 36.119783
], ],
[ [
-115.160557, -115.160282,
36.120991 36.119976
], ],
[ [
-115.160616, -115.160195,
36.121204 36.120145
], ],
[ [
-115.160853, -115.160143,
36.121263 36.120365
], ],
[ [
-115.160926, -115.160107,
36.121353 36.120627
], ],
[ [
-115.160735, -115.160117,
36.122189 36.120781
], ],
[ [
-115.160754, -115.160225,
36.122295 36.120836
],
[
-115.160511,
36.120862
],
[
-115.160611,
36.120913
],
[
-115.160697,
36.12102
],
[
-115.160731,
36.121187
],
[
-115.160715,
36.121309
],
[
-115.160438,
36.121696
],
[
-115.16039,
36.121799
],
[
-115.160274,
36.121977
],
[
-115.160316,
36.122164
],
[
-115.160541,
36.122284
], ],
[ [
-115.160959, -115.160959,
@@ -173,84 +253,180 @@
36.125279 36.125279
], ],
[ [
-115.169159, -115.168652,
36.125492 36.125432
], ],
[ [
-115.169376, -115.169318,
36.125433 36.12554
], ],
[ [
-115.169429, -115.169409,
36.125279 36.125522
], ],
[ [
-115.171142, -115.169496,
36.122745 36.125468
], ],
[ [
-115.171849, -115.169564,
36.121548 36.125284
], ],
[ [
-115.17235, -115.169633,
36.120307 36.125158
], ],
[ [
-115.172666, -115.170324,
36.119312 36.124067
], ],
[ [
-115.172857, -115.170754,
36.118128 36.123418
], ],
[ [
-115.17289, -115.170978,
36.117356 36.123089
], ],
[ [
-115.172857, -115.171208,
36.114684 36.122772
], ],
[ [
-115.173015, -115.171605,
36.108714 36.122215
], ],
[ [
-115.172877, -115.172013,
36.10857 36.121466
], ],
[ [
-115.1726, -115.172229,
36.108469 36.1209
], ],
[ [
-115.172383, -115.172466,
36.108448 36.120249
], ],
[ [
-115.172126, -115.172625,
36.108235 36.119783
], ],
[ [
-115.171981, -115.172744,
36.108091 36.119319
], ],
[ [
-115.17173, -115.172839,
36.108038 36.118849
], ],
[ [
-115.163947, -115.17294,
36.108017 36.11816
], ],
[ [
-115.16371, -115.172965,
36.108091 36.117758
], ],
[ [
-115.162219, -115.172991,
36.109017 36.117279
],
[
-115.17298,
36.115982
],
[
-115.172974,
36.115241
],
[
-115.172971,
36.114679
],
[
-115.173104,
36.111742
],
[
-115.173144,
36.110235
],
[
-115.173145,
36.109483
],
[
-115.173181,
36.108577
],
[
-115.173118,
36.108504
],
[
-115.173032,
36.10848
],
[
-115.172826,
36.108483
],
[
-115.172674,
36.108436
],
[
-115.172332,
36.108159
],
[
-115.172033,
36.108021
],
[
-115.171635,
36.107958
],
[
-115.169902,
36.107928
],
[
-115.167635,
36.10795
],
[
-115.16577,
36.107941
],
[
-115.164859,
36.107951
],
[
-115.164113,
36.108035
],
[
-115.163333,
36.108155
],
[
-115.16313,
36.10823
],
[
-115.162966,
36.108313
],
[
-115.162835,
36.108413
],
[
-115.161202,
36.109904
] ]
] ]
} }
Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 18 KiB

@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="150px" height="93px" viewBox="0 0 150 93" xmlns="http://www.w3.org/2000/svg"> <svg width="150px" height="93px" viewBox="0 0 150 93" xmlns="http://www.w3.org/2000/svg">
<title>Las Vegas Street Circuit - Nevada</title> <title>Las Vegas Street Circuit - Nevada</title>
<path d="M96.27,83.93 L105.80,77.75 L105.96,77.25 L105.52,76.70 L104.79,76.68 L99.80,76.90 L95.56,79.14 L93.82,79.75 L92.19,79.85 L90.68,79.30 L89.12,77.96 L87.75,75.24 L87.26,35.47 L87.55,34.90 L88.44,34.72 L97.21,34.75 L98.90,34.31 L100.24,33.35 L102.97,30.52 L104.13,28.15 L104.31,26.00 L104.03,24.97 L102.88,24.69 L102.53,24.25 L103.45,20.21 L103.36,19.69 L102.37,19.56 L87.23,19.25 L81.63,18.60 L79.78,17.88 L77.74,16.18 L75.99,13.35 L73.31,8.26 L71.59,6.79 L69.80,5.80 L67.99,5.26 L62.70,4.23 L61.65,4.51 L61.39,5.26 L53.10,17.52 L49.68,23.31 L47.26,29.31 L45.73,34.13 L44.81,39.85 L44.65,43.59 L44.81,56.52 L44.04,85.40 L44.71,86.10 L46.05,86.59 L47.10,86.69 L48.34,87.72 L49.04,88.41 L50.26,88.67 L87.91,88.77 L89.06,88.41 L96.27,83.93" fill="none" stroke="black" stroke-width="2"/> <path d="M101.12,79.29 L104.07,76.61 L104.69,76.05 L105.14,75.44 L105.29,74.72 L104.91,74.06 L104.29,73.65 L103.17,73.31 L102.11,73.17 L101.09,73.21 L100.14,73.44 L98.04,74.46 L96.11,76.01 L95.36,76.41 L93.74,76.70 L92.86,76.69 L91.27,76.26 L90.39,75.86 L89.57,75.30 L88.22,73.82 L87.67,72.57 L87.30,35.45 L87.58,34.89 L88.13,34.61 L97.61,34.75 L100.45,34.74 L101.94,34.46 L102.54,34.04 L104.21,32.72 L104.96,31.86 L105.54,30.94 L105.96,30.13 L106.21,29.07 L106.38,27.81 L106.33,27.07 L105.81,26.81 L104.44,26.68 L103.96,26.44 L103.55,25.93 L103.39,25.12 L103.46,24.54 L104.79,22.68 L105.02,22.19 L105.58,21.33 L105.38,20.43 L104.30,19.86 L102.29,19.68 L87.27,19.37 L81.72,18.72 L79.88,18.00 L77.86,16.31 L76.12,13.51 L73.46,8.46 L71.75,7.00 L69.98,6.02 L68.18,5.48 L65.36,4.75 L62.16,4.23 L61.73,4.31 L61.31,4.57 L60.98,5.46 L60.65,6.06 L57.33,11.30 L55.27,14.41 L54.19,15.99 L53.09,17.51 L51.18,20.19 L49.23,23.78 L48.19,26.50 L47.05,29.63 L46.29,31.86 L45.72,34.09 L45.26,36.35 L44.78,39.65 L44.66,41.58 L44.53,43.88 L44.58,50.11 L44.61,53.67 L44.63,56.36 L43.99,70.46 L43.80,77.70 L43.79,81.31 L43.62,85.66 L43.92,86.01 L44.33,86.12 L45.32,86.11 L46.05,86.33 L47.70,87.66 L49.13,88.33 L51.04,88.63 L59.36,88.77 L70.24,88.67 L79.20,88.71 L83.57,88.66 L87.15,88.26 L90.89,87.68 L91.87,87.32 L92.66,86.92 L93.28,86.44 L101.12,79.29" fill="none" stroke="black" stroke-width="2"/>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 995 B

After

Width:  |  Height:  |  Size: 1.5 KiB

@@ -2,10 +2,10 @@
"type": "FeatureCollection", "type": "FeatureCollection",
"name": "us-2022", "name": "us-2022",
"bbox": [ "bbox": [
-80.244805, -80.244783,
25.955259, 25.955221,
-80.229711, -80.229764,
25.960590 25.96059
], ],
"features": [ "features": [
{ {
@@ -15,22 +15,66 @@
"Location": "Miami", "Location": "Miami",
"Name": "Miami International Autodrome", "Name": "Miami International Autodrome",
"opened": 2022, "opened": 2022,
"seasons": [2022, 2023, 2024], "firstgp": 2022,
"length": 5412, "length": 5412,
"altitude": 1 "altitude": 1
}, },
"bbox": [ "bbox": [
-80.244805, -80.244783,
25.955259, 25.955221,
-80.229711, -80.229764,
25.96059 25.96059
], ],
"geometry": { "geometry": {
"type": "LineString", "type": "LineString",
"coordinates": [ "coordinates": [
[ [
-80.236636, -80.237371,
25.955895 25.959092
],
[
-80.235319,
25.95794
],
[
-80.235284,
25.957855
],
[
-80.235299,
25.957776
],
[
-80.23536,
25.957671
],
[
-80.235797,
25.957379
],
[
-80.235933,
25.957247
],
[
-80.235978,
25.957009
],
[
-80.235933,
25.956757
],
[
-80.235976,
25.956446
],
[
-80.236081,
25.956247
],
[
-80.236477,
25.955962
], ],
[ [
-80.236928, -80.236928,
@@ -125,20 +169,20 @@
25.957311 25.957311
], ],
[ [
-80.24439, -80.244395,
25.957229 25.957215
], ],
[ [
-80.244562, -80.244562,
25.957076 25.957076
], ],
[ [
-80.244706, -80.244721,
25.956851 25.956852
], ],
[ [
-80.244805, -80.244783,
25.956619 25.956614
], ],
[ [
-80.244776, -80.244776,
@@ -165,132 +209,124 @@
25.956157 25.956157
], ],
[ [
-80.243762, -80.243761,
25.956178 25.956156
], ],
[ [
-80.243527, -80.243194,
25.956146 25.956048
], ],
[ [
-80.242561, -80.242156,
25.955939 25.955859
], ],
[ [
-80.242249, -80.241083,
25.955896 25.955887
], ],
[ [
-80.241873, -80.239445,
25.955898 25.955948
], ],
[ [
-80.239344, -80.238992,
25.955952 25.955819
], ],
[ [
-80.23896, -80.238432,
25.955847 25.955639
], ],
[ [
-80.238518, -80.237981,
25.955702
],
[
-80.23788,
25.955496 25.955496
], ],
[ [
-80.237521, -80.237375,
25.955398 25.955323
], ],
[ [
-80.237233, -80.236745,
25.955329 25.955228
], ],
[ [
-80.236835, -80.236112,
25.955278 25.955221
], ],
[ [
-80.236256, -80.235447,
25.955259 25.955319
],
[
-80.235521,
25.955351
], ],
[ [
-80.23484, -80.23484,
25.955511 25.955511
], ],
[ [
-80.233638, -80.233453,
25.955878 25.955966
], ],
[ [
-80.232783, -80.232648,
25.956175 25.956242
], ],
[ [
-80.23226, -80.23226,
25.956397 25.956397
], ],
[ [
-80.231591, -80.231268,
25.956683 25.956871
],
[
-80.231134,
25.956926
], ],
[ [
-80.230734, -80.230734,
25.957178 25.957178
], ],
[ [
-80.230629, -80.230627,
25.957322 25.957308
], ],
[ [
-80.230624, -80.230662,
25.957412 25.957416
], ],
[ [
-80.230714, -80.230759,
25.957497 25.9575
], ],
[ [
-80.230859, -80.231004,
25.957578 25.957633
], ],
[ [
-80.231179, -80.231175,
25.957794 25.957748
], ],
[ [
-80.231252, -80.231268,
25.95794 25.957916
], ],
[ [
-80.231269, -80.231288,
25.958145 25.958091
], ],
[ [
-80.231191, -80.231233,
25.958304 25.958304
], ],
[ [
-80.23101, -80.231101,
25.958424 25.958423
], ],
[ [
-80.2307, -80.230946,
25.958456 25.958479
], ],
[ [
-80.23036, -80.230487,
25.958483 25.958454
],
[
-80.230258,
25.958482
], ],
[ [
-80.230157, -80.230157,
@@ -301,44 +337,44 @@
25.958676 25.958676
], ],
[ [
-80.229711, -80.229764,
25.959114 25.95906
], ],
[ [
-80.229723, -80.22978,
25.95918 25.959144
], ],
[ [
-80.229857, -80.229896,
25.95923 25.959186
], ],
[ [
-80.229938, -80.230001,
25.959267 25.959256
], ],
[ [
-80.229971, -80.230005,
25.959336 25.959399
], ],
[ [
-80.229829, -80.229815,
25.959781 25.95995
], ],
[ [
-80.22977, -80.22983,
25.960005 25.960044
], ],
[ [
-80.22979, -80.229916,
25.960073 25.960107
], ],
[ [
-80.22988, -80.230394,
25.960131 25.960146
], ],
[ [
-80.23021, -80.237297,
25.960149 25.960366
], ],
[ [
-80.242801, -80.242801,
@@ -361,108 +397,48 @@
25.960144 25.960144
], ],
[ [
-80.242262, -80.242453,
25.959854 25.959941
], ],
[ [
-80.242062, -80.242134,
25.959736 25.959787
], ],
[ [
-80.24179, -80.241874,
25.959705 25.959728
], ],
[ [
-80.241472, -80.241645,
25.95977 25.959745
], ],
[ [
-80.240543, -80.241365,
25.960163 25.959836
], ],
[ [
-80.240237, -80.240712,
25.960266 25.960112
], ],
[ [
-80.239932, -80.240346,
25.96027 25.9602
], ],
[ [
-80.239632, -80.239896,
25.96024 25.960235
], ],
[ [
-80.23935, -80.239452,
25.960194 25.960179
], ],
[ [
-80.238934, -80.239033,
25.960033 25.960022
], ],
[ [
-80.235522, -80.237371,
25.95807 25.959092
],
[
-80.235365,
25.957974
],
[
-80.235293,
25.957894
],
[
-80.23528,
25.957799
],
[
-80.235374,
25.957669
],
[
-80.235529,
25.957582
],
[
-80.235691,
25.957473
],
[
-80.235918,
25.957258
],
[
-80.235984,
25.957061
],
[
-80.235925,
25.956832
],
[
-80.235917,
25.956661
],
[
-80.235963,
25.956401
],
[
-80.236066,
25.956259
],
[
-80.236208,
25.956124
],
[
-80.236366,
25.956036
],
[
-80.236636,
25.955895
] ]
] ]
} }
Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

After

Width:  |  Height:  |  Size: 20 KiB

@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="150px" height="93px" viewBox="0 0 150 93" xmlns="http://www.w3.org/2000/svg"> <svg width="150px" height="93px" viewBox="0 0 150 93" xmlns="http://www.w3.org/2000/svg">
<title>Miami International Autodrome - Miami</title> <title>Miami International Autodrome - Miami</title>
<path d="M80.62,64.84 L77.98,65.49 L75.33,66.03 L71.43,66.11 L68.37,65.61 L64.78,64.17 L46.59,54.36 L43.98,52.94 L42.64,52.73 L41.10,52.62 L39.57,52.80 L37.62,53.35 L35.97,54.18 L34.29,55.40 L32.54,56.45 L30.24,56.79 L28.18,56.62 L25.95,55.66 L23.87,53.98 L21.97,52.29 L19.84,51.34 L17.64,50.94 L14.99,51.36 L12.56,52.04 L10.57,52.78 L9.01,54.17 L7.71,56.20 L6.82,58.29 L7.08,60.14 L7.52,61.35 L8.25,62.18 L9.75,62.91 L11.54,62.91 L13.77,62.47 L16.24,62.28 L18.36,62.57 L27.09,64.44 L29.91,64.83 L33.31,64.81 L56.15,64.32 L59.62,65.27 L63.62,66.58 L69.38,68.44 L72.62,69.33 L75.23,69.95 L78.82,70.41 L84.05,70.58 L90.69,69.75 L96.84,68.30 L107.70,64.99 L115.43,62.31 L120.15,60.30 L126.20,57.72 L130.33,55.52 L133.94,53.24 L134.89,51.94 L134.93,51.13 L134.12,50.36 L132.81,49.63 L129.92,47.68 L129.26,46.36 L129.11,44.51 L129.81,43.07 L131.45,41.99 L134.25,41.70 L137.32,41.45 L139.15,40.93 L140.54,39.71 L143.18,35.75 L143.07,35.16 L141.86,34.71 L141.13,34.37 L140.83,33.75 L142.12,29.73 L142.65,27.70 L142.47,27.09 L141.66,26.57 L138.67,26.40 L24.92,22.42 L23.47,22.76 L23.16,23.79 L23.66,25.08 L25.38,26.45 L29.79,29.07 L31.60,30.13 L34.06,30.41 L36.93,29.83 L45.32,26.28 L48.09,25.35 L50.84,25.31 L53.55,25.58 L56.10,26.00 L59.86,27.45 L90.68,45.19 L92.10,46.05 L92.75,46.78 L92.87,47.63 L92.02,48.81 L90.62,49.59 L89.16,50.58 L87.11,52.52 L86.51,54.30 L87.04,56.37 L87.11,57.91 L86.70,60.26 L85.77,61.55 L84.49,62.77 L83.06,63.56 L80.62,64.84" fill="none" stroke="black" stroke-width="2"/> <path d="M74.11,35.73 L92.75,46.19 L93.06,46.96 L92.93,47.68 L92.37,48.63 L88.41,51.28 L87.17,52.48 L86.76,54.64 L87.17,56.93 L86.78,59.75 L85.83,61.56 L82.23,64.15 L78.14,65.42 L75.48,65.95 L71.55,66.03 L68.48,65.53 L64.87,64.08 L46.59,54.22 L43.96,52.80 L42.62,52.59 L41.07,52.48 L39.53,52.66 L37.57,53.21 L35.92,54.05 L34.23,55.28 L32.47,56.33 L30.16,56.67 L28.08,56.50 L25.85,55.53 L23.75,53.84 L21.84,52.14 L19.70,51.19 L17.50,50.79 L14.84,51.21 L12.39,51.90 L10.34,52.77 L8.82,54.03 L7.38,56.07 L6.82,58.23 L6.88,60.03 L7.33,61.25 L8.06,62.08 L9.56,62.82 L11.37,62.82 L13.60,62.38 L16.10,62.38 L21.25,63.37 L30.67,65.08 L40.41,64.83 L55.28,64.27 L59.40,65.44 L64.48,67.08 L68.58,68.38 L74.08,69.95 L79.80,70.81 L85.55,70.87 L91.58,69.98 L97.09,68.24 L109.69,64.11 L117.00,61.60 L120.52,60.20 L129.53,55.89 L134.37,53.11 L135.35,51.92 L135.03,50.94 L134.15,50.18 L131.92,48.97 L130.37,47.93 L129.53,46.40 L129.34,44.82 L129.84,42.88 L131.04,41.80 L132.45,41.29 L136.62,41.52 L138.70,41.27 L139.61,40.73 L141.01,39.50 L143.18,36.02 L143.04,35.26 L141.98,34.87 L141.03,34.24 L140.99,32.94 L142.72,27.94 L142.58,27.08 L141.80,26.51 L137.46,26.16 L74.79,24.16 L24.81,22.13 L23.35,22.47 L23.04,23.51 L23.54,24.80 L25.28,26.18 L27.97,28.02 L30.87,29.42 L33.23,29.95 L35.31,29.80 L37.85,28.97 L43.78,26.47 L47.10,25.67 L51.19,25.35 L55.22,25.86 L59.02,27.28 L74.11,35.73" fill="none" stroke="black" stroke-width="2"/>
</svg> </svg>

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

+51 -13
View File
@@ -12,6 +12,11 @@ from models.model_builder import parse_circuits_json
from models.track_layout import TrackLayout from models.track_layout import TrackLayout
class NotFound(LookupError):
"""A country, locality, circuit or layout circuits.json does not hold, or a year no layout covers: answered 404,
naming it."""
# Define supported formats # Define supported formats
class Format(str, Enum): class Format(str, Enum):
PNG = "png" PNG = "png"
@@ -69,6 +74,31 @@ class CircuitService:
return layout_slug return layout_slug
return None return None
def resolve(self, country_slug: str, locality_slug: Optional[str] = None, circuit_slug: Optional[str] = None,
layout_slug: Optional[str] = None):
"""The country, locality, circuit or layout the given slugs lead to (the deepest one given); NotFound names
the first that circuits.json does not hold."""
found = self.circuit_data.get(country_slug)
if found is None:
raise NotFound(f"No country {country_slug!r}")
for kind, slug, children in (("locality", locality_slug, "localities"), ("circuit", circuit_slug, "circuits"),
("layout", layout_slug, "layouts")):
if slug is None:
return found
parent = found
found = getattr(parent, children).get(slug)
if found is None:
raise NotFound(f"No {kind} {slug!r} in {getattr(parent, 'name', None) or getattr(parent, 'slug', '')}")
return found
def layout_for_year(self, country_slug: str, locality_slug: str, circuit_slug: str, year: int) -> TrackLayout:
"""The layout a circuit used in a year; NotFound when the circuit is unknown or no layout covers the year."""
circuit = self.resolve(country_slug, locality_slug, circuit_slug)
layout_slug = self.find_layout_slug_for_year(circuit, year)
if layout_slug is None:
raise NotFound(f"No layout of {circuit.name} covers {year}")
return circuit.layouts[layout_slug]
def get_countries_list(self) -> Optional[list[Country]]: def get_countries_list(self) -> Optional[list[Country]]:
"""Get list of all available countries with their slugs""" """Get list of all available countries with their slugs"""
return [country for _, country in self.circuit_data.items()] return [country for _, country in self.circuit_data.items()]
@@ -77,26 +107,34 @@ class CircuitService:
"""Get details for a specific country""" """Get details for a specific country"""
return self.circuit_data.get(country_slug) return self.circuit_data.get(country_slug)
def get_localities_list(self, country_slug: str) -> Optional[list[Locality]]: def get_localities_list(self, country_slug: str) -> list[Locality]:
"""Get list of cities for a specific country""" """The localities of a country; NotFound when it is unknown"""
return [locality for _, locality in self.circuit_data[country_slug].localities.items()] return list(self.resolve(country_slug).localities.values())
def get_locality_details(self, country_slug: str, locality_slug: str) -> Optional[Locality]: def get_locality_details(self, country_slug: str, locality_slug: str) -> Optional[Locality]:
"""Get details for a specific city""" """Get details for a specific city; None when it is unknown"""
return self.circuit_data[country_slug].localities.get(locality_slug) try:
return self.resolve(country_slug, locality_slug)
except NotFound:
return None
def get_circuits_list(self, country_slug: str, locality_slug: str) -> Optional[list[Circuit]]: def get_circuits_list(self, country_slug: str, locality_slug: str) -> list[Circuit]:
"""Get list of circuits for a specific city""" """The circuits of a locality; NotFound when it is unknown"""
return [circuit_data for _, circuit_data in self.circuit_data[country_slug].localities.get(locality_slug).circuits.items()] return list(self.resolve(country_slug, locality_slug).circuits.values())
def get_circuit_details(self, country_slug: str, locality_slug: str, circuit_slug: str) -> Optional[Circuit]: def get_circuit_details(self, country_slug: str, locality_slug: str, circuit_slug: str) -> Optional[Circuit]:
"""Get circuit details and available formats""" """Get circuit details and available formats; None when it is unknown"""
return self.circuit_data[country_slug].localities.get(locality_slug).circuits.get(circuit_slug) try:
return self.resolve(country_slug, locality_slug, circuit_slug)
except NotFound:
return None
def get_layout_details(self, country_slug: str, locality_slug: str, circuit_slug: str, layout_slug: str) -> Optional[TrackLayout]: def get_layout_details(self, country_slug: str, locality_slug: str, circuit_slug: str, layout_slug: str) -> Optional[TrackLayout]:
"""Get details for a specific layout""" """Get details for a specific layout; None when it is unknown"""
return self.circuit_data[country_slug].localities.get(locality_slug).circuits.get(circuit_slug).layouts.get( try:
layout_slug) return self.resolve(country_slug, locality_slug, circuit_slug, layout_slug)
except NotFound:
return None
def get_circuit_layout_by_ergast_data(self, grand_prix_name: str, season: int) -> Optional[TrackLayout]: def get_circuit_layout_by_ergast_data(self, grand_prix_name: str, season: int) -> Optional[TrackLayout]:
""" """
+189
View File
@@ -0,0 +1,189 @@
# Posters: sources, layers, options and credits
How F1 Circuits makes its race posters, season posters and session thumbnails: where every picture comes
from and under which licence, what it fetches once and keeps, what it draws on every request, which options a
caller has, and how every image says where it comes from. Decided with the operator on 2026-11-27, after
reading each source's own terms; the lead's answers to the builders' questions are written in where they
belong.
## Principles
1. **Every source is used only as its terms allow, and says so.** The credit each source asks for is drawn on
every image made from it, sent in a header, and listed on the licences page. A caller cannot switch it off.
2. **Static is kept.** The circuits, their layouts and finished seasons do not change, so what is made from
them is fetched or rendered once and kept. Nothing expires; a changed input makes a new key.
3. **Heavy once, light every time.** What needs the network (a map, a photo) is a kept layer. What a caller
can choose (texts, colours, treatment, size, format) is drawn on the fly from the kept layers.
4. **Whole or not at all.** A layer is kept only when every part of it arrived. A picture whose layer did not
arrive is served without it, for five minutes, and not kept.
## Sources
Only sources whose licence allows keeping a copy for good are used. Esri, Bing, Azure Maps, Google, Mapbox and
MapTiler are not: their terms forbid automated fetching, keeping, or serving images made from their maps to the
public.
| Source | Used for | Licence | Credit drawn on the image |
|:---|:---|:---|:---|
| USGS imagery (USGSImageryOnly, to zoom 16), United States | `bg=satellite` for circuits in the US | public domain | `USDA, USGS The National Map: Orthoimagery` |
| PDOK aerial photo (Actueel_orthoHR), the Netherlands | `bg=satellite` for circuits in the Netherlands | CC BY 4.0 | `Luchtfoto: PDOK / Samenwerkingsverband Beeldmateriaal, CC BY 4.0` |
| IGN, the frozen mosaic ORTHOIMAGERY.ORTHOPHOTOS2021-2023, France | `bg=satellite` for circuits in France | Licence Ouverte (Etalab) 2.0 | `© IGN – BD ORTHO, 2021–2023` |
| EOxCloudless, the newest mosaic (2025) | `bg=satellite` everywhere else | CC BY-NC-SA 4.0 | `EOxCloudless https://cloudless.eox.at by EOX IT Services GmbH (Contains modified Copernicus Sentinel data 2025)` |
| OpenStreetMap standard tiles | `bg=osm`, `bg=dark`, `bg=light` (recoloured), the world locator, and a layout switched to the map | ODbL (data), tile usage policy | `© OpenStreetMap contributors` |
| Wikimedia Commons photo, picked per layout or per season | `bg=photo`; season posters | per file: CC0, public domain, CC BY or CC BY-SA only | `Photo: <author>, <licence>, via Wikimedia Commons` |
| Jolpica F1 API | race schedules: names, rounds, dates | CC BY-NC-SA 4.0 | in the docs and the Kometa file |
| The circuits' GPS traces and layouts | track outlines, track files | MIT (LICENSE.md) | in the docs |
IGN's yearly layers cover only the départements flown that year, so a frame near a border falls into a hole;
the 2021–2023 mosaic covers the whole country, and its frozen date range is the date the Etalab licence asks
for. EOX's 2016 mosaic (CC BY 4.0) was rejected by the operator: too soft to read a circuit. (EOX's
capabilities also mark 2017 as CC BY 4.0.)
**The traces follow upstream.** A layout's trace is upstream's (bacinger/f1-circuits) newest trace of that
circuit, copied once into the repository word for word, never fetched at run time. A newer upstream trace of a
circuit already drawn is taken as a plain update.
**`bg=satellite`** (and `aerial`, kept for addresses already in use) takes, per layout, the national aerial
photo of the circuit's country, else EOX's newest mosaic. The operator can switch a layout to the dark
OpenStreetMap map, where EOX is too soft to read the circuit: `"use": "map"` in its entry of
`circuits/photos.json`; a national source still wins, as it is sharper. **`bg=photo`** draws the layout's picked
Commons photo, with the track as an inset; without a picked photo it draws what `bg=satellite` draws for that
layout. No style takes `bg=photo` by default: a photo is not placed on the map, so its crop need not show the
circuit, and the operator judged it unfit as a default.
**Fetching.** Every request carries the app's own User-Agent, `f1-circuits/1.0.0 (+<public address>)`, never a
person's address; Jolpica's included. OpenStreetMap tiles are fetched only when a picture is asked for, never
ahead (its policy forbids pre-seeding). At most 2 requests at once go to OpenStreetMap and to IGN, 4 to the
others. Commons: one API request at a time, at most five a second, at most two downloads at once.
## Layers (kept for good)
| Layer | Made from | Key | Class |
|:---|:---|:---|:---|
| Map picture | the tiles of one source around a layout's trace, at its zoom (at most the source's deepest), for one frame (poster 1000×1500, thumb 1920×1080) | source, source year, trace hash, frame, zoom, render version | `rebuildable` |
| Photo picture | one picked Commons file, cropped to the frame, untreated | file name, file's SHA-1 from Commons, frame, render version | `rebuildable` |
| World locator | OpenStreetMap tiles at zoom 5 around the circuit, dark | latitude and longitude rounded to 0.01°, render version | `rebuildable` |
| Track outline points | the layout's trace projected for the frame and zoom | trace hash, frame, zoom | `rebuildable` |
A map is kept only when every tile came and the tiles are not all one picture (a provider's placeholder).
`dark` and `light` are made from the kept OpenStreetMap layer. A layout whose trace is a point or empty is drawn
at the circuit's location, without a track; no current race may draw one, which the merge check holds: every
layout that `find_layout_slug_for_year` chooses for a season from 2020 on has a LineString trace of more than 10
points (`tests/test_traces.py`). Layers live in the module's directory `layers`, class `rebuildable`
(backed up; fetched again if lost).
## Finished images (kept, capped)
Every finished picture is stored under a key made of its route, its resolved options, the keys of the layers it was
made from, and the credit of each layer drawn from a pick, in the directory `posters`, class `cache`, at most 2 GB;
the least recently used go first when it is full. A picture whose layer did not arrive is not stored. The render
version is `r3`: no poster stored before it is served again.
**What clients keep.** The address clients are given carries an address version of its own (`?v=a1`, as the
Kometa file writes it), separate from the render version that keys kept layers and finished pictures. The address
version is raised when a look changes, so clients load it again from the pictures already kept; the render version
is raised only when the drawing itself changes. The address version was raised to `a1` (from `r3`, the render
version the addresses carried before) because every season poster changed; the render version stays `r3`.
An address that carries the address version is sent `Cache-Control: public, max-age=31536000, immutable`. Any
other address is sent an ETag and `max-age=86400`, and a matching `If-None-Match` (weak or strong) gets a 304. A
picture served without its layer is sent `max-age=300` and no ETag.
## Options
Query parameters, the same on `/posters/race/…`, `/posters/season/…` and `/posters/session/…`. An unknown
option or value is answered 422, naming it.
| Option | Values | Default | Drawn |
|:---|:---|:---|:---|
| `style` | `classic`, `minimal` | `classic` | a preset per frame of the options below; any option given overrides it |
| `bg` | `satellite` (alias `aerial`), `photo`, `osm`, `dark`, `light`, `none` | `satellite` | the kept map or photo layer |
| `photo` | `bw`, `natural` | `natural` | the treatment of a photo layer, applied when the picture is assembled (`bw`: luminance greyscale) |
| `show` | a comma list of `wordmark`, `round`, `name`, `subtitle`, `date`, `circuit`, `locality`, `session` | the style's | on the fly |
| `locator` | `on`, `off` | the style's | the kept locator layer |
| `checker` | `on`, `off` | the style's | on the fly |
| `track` | `off`, or a colour `#rrggbb` with an optional width 1 to 30, `#ffffff,6` | white, 6 | on the fly from the kept outline points; over a photo, an inset |
| `dim` | 0 to 1: the darkening behind the track; the bands behind the texts keep their proportion | the style's | on the fly |
| `accent` | `#rrggbb` | the style's | the wordmark's colour |
| `width` | 400 up to the frame's own width | the frame's | scaled down at encoding |
| `format` | `png`, `jpg`, `webp` | `png` | encoding, with its Content-Type, on the same `.png` addresses |
**The presets.** `classic` reproduces the earlier look per frame: on a poster checker and locator on, dim 0.43;
on a thumb checker and locator off, dim 0.55; on a season poster dim 0.24. `minimal`: on a poster
`show=name,date`, on a thumb `show=name,session`; checker off, locator off, dim 0.25; accent and track as
`classic`.
**Placement.** `circuit` and `locality`, when asked for, are one grey 28 px line "<circuit> · <locality>" above
the date on a poster, under the subtitle on a thumb. A `date` asked for on a thumb goes under the session label,
grey, 36 px. The track inset over a photo is the trace fitted to 220×220 px (300×300 on a thumb), bottom right
above the date strip, on a 50% black panel. A locator on a thumb sits top right, 220 px, 60 px from the edges.
**Season posters.** `wordmark` is "FORMULA 1", `name` the year, `subtitle` "WORLD CHAMPIONSHIP"; `round`, `date`,
`circuit`, `locality`, `session`, `locator` and `track` are accepted and draw nothing. `bg=none` draws no photo;
any other `bg` draws the season's picked photo, if any.
## Season posters
A season poster shows a season's cars only from a photo picked from Wikimedia Commons, credited like any
Commons photo; until one is picked, it is drawn without a photo. Photos without a free licence are never used:
the operator's earlier, hand-curated season photos carry agency credits (Getty Images, Motorsport Images/LAT
and others) and stay private, as the reference for finding a freely licensed photo of the same car.
**Each season's photo is matched to the operator's curated car of that season**, in this order: the same car; the
same model in a livery it raced that season; the same team's car of that season; that season's champion car. A
curated photo of another year's car gives way to that season's car. The table of picks, `seasons/picks.md`, names
the match per season.
## Picking photos
`tools/commons_candidates.py` lists candidates from Commons per layout (aerial photos of the circuit dated in the
layout's years) and per season (the photos in its "<year> Formula One season cars" category): only CC0, public
domain, CC BY and CC BY-SA; quality marks, size and landscape first; written to `examples/data/candidates.json`.
Where a season's category holds no free photo of the curated car, the person or session picking searches Commons for
that car by name, and the pick's row in `seasons/picks.md` says so. The picker page shows, per layout, the
`bg=satellite` decision first (the national photo and EOX next to each other; keep the satellite, or use the map
instead), then the optional photo candidates for `bg=photo`, beside the picks of the circuit's other layouts; per
season, its candidates beside the nearest seasons' picks. It gives the entry to copy; it writes nothing.
The picks live in the repository. `circuits/photos.json` is keyed by the layout's path under `circuits/`
without extension (`belgium/spa/circuit-de-spa-francorchamps/1983-`), `seasons/photos.json` by the year as text.
An entry holds the photo fields (`file`, the Commons title without "File:"; `licence`; `author`; `credit`;
`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.
An entry's `date` is when the photo was taken. Where the date Commons gives cannot be when the photo was taken (a
scan, an upload, a camera clock that was never set, a date after the file's upload), it is the date the file's
description or category gives, and the entry is marked `"date_from"`: `"description"` or `"category"`. Where neither
says when the photo was taken, it is the month of the file's upload, the latest it can have been taken, marked
`"date_from": "upload"`. The ported CC BY-SA licences (2.0 de, 3.0 de, 3.0 nl) are free like their unported versions
and give the picture CC BY-SA 4.0.
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
after scaling, wrapping when needed, on a dark band above the bottom strip.
- **A picture's licence follows its sources:** CC BY-SA 4.0 when made from a CC BY-SA photo (2.0, 2.5, 3.0
and the ported 2.0 DE, 3.0 DE and 3.0 NL allow a later version with the same elements); CC BY-NC-SA 4.0 when made
from EOX's mosaic; CC BY 4.0 otherwise. Jolpica's race names and dates are single facts and do not set it. The
satellite chain takes one source, so a BY-SA photo and an NC-SA mosaic never meet on one picture; a picture that
would combine them is refused.
- In every picture's response: `X-Credits` (the credit line folded to ASCII: ß→ss, æ→ae, ø→o, œ→oe, đ→d, then
accents dropped, "©" as "(c)", sources joined with " | "), `X-License`, and `Link: </licences>; rel="license"`;
CORS exposes them and the ETag.
- `/licences`: `pictures` (the rule and its licences), `tracks` (MIT), and every source with its licence, credit,
terms' address and the licence a picture made from it gets; the example site's licences page shows it.
- The Kometa file says in its first lines that its data comes from Jolpica under CC BY-NC-SA 4.0.
- The unofficial-use disclaimer for the Formula 1 marks is shown at the foot of `/`, `/docs` and every example
page.
## Not in this change
The disk tile store (replaced by kept layers); renaming the service away from "F1"; the three layouts whose trace
is empty (Mont-Tremblant 1968-1970, Buddh 2011-2013, Yeongam 2010-2013), Bahrain's trace that sits off its real
track, and Donington's, a copy of Aintree's trace (traced separately).
+4 -1
View File
@@ -9,6 +9,8 @@ from datetime import date
from pathlib import Path from pathlib import Path
from typing import Optional, TYPE_CHECKING from typing import Optional, TYPE_CHECKING
from app_info import USER_AGENT
if TYPE_CHECKING: if TYPE_CHECKING:
from circuits_service import CircuitService from circuits_service import CircuitService
@@ -112,7 +114,8 @@ class ErgastService:
time.sleep(wait) time.sleep(wait)
self._last_request = time.monotonic() self._last_request = time.monotonic()
try: try:
with urllib.request.urlopen(url, timeout=self.REQUEST_TIMEOUT) as resp: request = urllib.request.Request(url, headers={'User-Agent': USER_AGENT})
with urllib.request.urlopen(request, timeout=self.REQUEST_TIMEOUT) as resp:
return json.loads(resp.read())['MRData']['RaceTable']['Races'] return json.loads(resp.read())['MRData']['RaceTable']['Races']
except urllib.error.HTTPError as e: except urllib.error.HTTPError as e:
if e.code != 429 or attempt == self.RETRIES: if e.code != 429 or attempt == self.RETRIES:
+361
View File
@@ -0,0 +1,361 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Poster builder · F1 Circuits API examples</title>
<meta name="description" content="Build a race poster, season poster or session thumbnail address of the F1 Circuits API option by option, render it, and read the credits it carries.">
<link rel="icon" href="data:,">
<link rel="stylesheet" href="site.css">
</head>
<body>
<header class="site">
<a class="brand" href="index.html">F1 <span>Circuits</span> API</a>
<nav aria-label="Examples">
<a href="index.html">Overview</a>
<a href="circuits.html">Circuit browser</a>
<a href="tracks.html">Track images</a>
<a href="map.html">GPS traces</a>
<a href="grand-prix.html">Grand prix lookup</a>
<a href="posters.html">Posters</a>
<a href="builder.html" aria-current="page">Poster builder</a>
<a href="kometa.html">Kometa</a>
<a href="library.html">Library</a>
<a href="picker.html">Photo picker</a>
<a href="licences.html">Licences</a>
<a href="../guides/index.html">Guides</a>
</nav>
<div id="api-base"></div>
</header>
<main>
<h1>Poster builder</h1>
<p class="lead">
Every poster route takes the same options as query parameters. Tick an option to send it; an option left out takes
its default. The address below follows every change, and the picture is rendered only when you press the button,
because the server draws it and may fetch map tiles first.
</p>
<section class="card" id="what">
<h2>1. Which picture</h2>
<div class="controls">
<label><span>Route</span>
<span class="seg" id="route">
<button type="button" data-v="race">Race poster</button><button type="button" data-v="season">Season poster</button><button type="button" data-v="session">Session thumbnail</button>
</span>
</label>
</div>
<div id="race-wrap"><div class="controls" id="race-picker"></div></div>
<div class="controls">
<label id="season-label">Season <input type="number" id="season" min="1950" max="2100"></label>
<label id="session-label"><span>Session</span> <select id="session"></select></label>
</div>
<div class="request"></div>
<div class="status"></div>
</section>
<section class="card">
<h2>2. The options</h2>
<p class="hint">An unknown option or value is answered 422, naming it. The credit line is drawn on every picture
whatever the options; no option takes it off.</p>
<div class="options" id="options"></div>
</section>
<section class="card" id="render-card">
<h2>3. The picture</h2>
<div class="controls">
<button type="button" class="primary" id="render">Render it</button>
</div>
<div class="request"></div>
<div class="status idle">Not rendered yet.</div>
<div class="result preview"></div>
<div class="credits" id="credits"></div>
</section>
</main>
<footer class="pager">
<a rel="prev" href="posters.html">← Posters</a>
<a class="home" href="index.html">All examples</a>
<a rel="next" href="kometa.html">Kometa →</a>
</footer>
<footer class="disclaimer">
<p>This website is unofficial and is not associated in any way with the Formula 1 companies. F1, FORMULA ONE,
FORMULA 1, FIA FORMULA ONE WORLD CHAMPIONSHIP, GRAND PRIX and related marks are trade marks of Formula One
Licensing B.V.</p>
<p><a href="licences.html">Licences and credits</a>: every source the pictures are made from, the licence each
picture takes from its sources, and the licence of the track files and the GPS traces (MIT).</p>
</footer>
<script src="site.js"></script>
<script>
(function () {
const { h, api, path, call, setRequest, setStatus, showImage, racePicker, notice, params } = F1;
const $ = (id) => document.getElementById(id);
const FRAME_WIDTH = { race: 1000, season: 1000, session: 1920 };
const SHOW = ['wordmark', 'round', 'name', 'subtitle', 'date', 'circuit', 'locality', 'session'];
// The design's Options table (docs/posters.md), in its order; photo per the operator's decision of 2026-11-27.
const OPTIONS = [
{ name: 'style', kind: 'select', def: 'classic', values: [['classic', 'classic'], ['minimal', 'minimal']],
note: 'A preset of the options below; any option given overrides it.' },
{ name: 'bg', kind: 'select', def: 'satellite', values: [
['satellite', 'satellite: the national aerial photo, else EOxCloudless 2025; the dark map for a layout that asks for it'],
['aerial', 'aerial: the same as satellite, for addresses in use'],
['photo', 'photo: the layout’s picked Commons photo, else what satellite draws'],
['osm', 'osm: OpenStreetMap'], ['dark', 'dark: OpenStreetMap, recoloured dark'],
['light', 'light: OpenStreetMap, recoloured light'], ['none', 'none: no map']],
note: 'The kept map or photo layer.' },
{ name: 'photo', kind: 'select', def: 'natural', values: [['natural', 'natural'], ['bw', 'bw: black and white']],
note: 'The treatment of a photo layer.' },
{ name: 'show', kind: 'list', def: 'the style’s', note: 'What is written on the picture, drawn on the fly.' },
{ name: 'locator', kind: 'select', def: 'on', values: [['on', 'on'], ['off', 'off']], note: 'The kept world locator.' },
{ name: 'checker', kind: 'select', def: 'on', values: [['on', 'on'], ['off', 'off']], note: 'The chequered band, drawn on the fly.' },
{ name: 'track', kind: 'track', def: 'white, 6', note: 'The outline, from the kept points; an inset over a photo layer.' },
{ name: 'dim', kind: 'range', def: 'the style’s', note: 'How much the background is darkened, 0 to 1.' },
{ name: 'accent', kind: 'color', def: 'the style’s', note: 'The wordmark’s colour.' },
{ name: 'width', kind: 'width', def: 'the frame’s', note: 'Scaled down at encoding, from 400 up to the frame’s width.' },
{ name: 'format', kind: 'select', def: 'png', values: [['png', 'png'], ['jpg', 'jpg'], ['webp', 'webp']], note: 'The encoding.' },
];
let route = ['race', 'season', 'session'].includes(params.get('route')) ? params.get('route') : 'race';
let chosen = null;
let seasonTouched = false;
// ------------------------------------------------------------ the option cards
/** One card per option: a tick to send it, and its control. Each returns its value, or null when not sent. */
const controls = OPTIONS.map((o) => {
const give = h('input', { type: 'checkbox', 'aria-label': `Send ${o.name}` });
const body = h('div', { class: 'opt-body' });
const box = h('div', { class: 'option' },
h('div', { class: 'opt-head' },
h('label', {}, give, ' ', h('code', {}, o.name)),
h('small', {}, `default: ${o.def}`)),
body,
h('div', { class: 'hint' }, o.note));
let value = () => null;
const touch = () => { give.checked = true; changed(); };
if (o.kind === 'select') {
const sel = h('select', { 'aria-label': o.name }, ...o.values.map(([v, label]) => h('option', { value: v }, label)));
sel.value = o.def;
sel.addEventListener('change', touch);
body.append(sel);
value = () => sel.value;
box._set = (v) => { sel.value = v; };
} else if (o.kind === 'list') {
const boxes = SHOW.map((s) => {
const c = h('input', { type: 'checkbox', value: s, checked: true });
c.addEventListener('change', touch);
body.append(h('label', {}, c, s));
return c;
});
value = () => boxes.filter((c) => c.checked).map((c) => c.value).join(',');
box._set = (v) => { const want = new Set(v.split(',')); for (const c of boxes) c.checked = want.has(c.value); };
} else if (o.kind === 'track') {
const off = h('input', { type: 'radio', name: 'track-kind', value: 'off' });
const colour = h('input', { type: 'radio', name: 'track-kind', value: 'colour', checked: true });
const pick = h('input', { type: 'color', value: '#ffffff', 'aria-label': 'Track colour' });
const width = h('input', { type: 'number', min: 1, max: 40, value: '6', 'aria-label': 'Track width', style: 'width:4.5rem' });
for (const el of [off, colour, pick, width]) el.addEventListener('input', touch);
pick.addEventListener('input', () => { colour.checked = true; });
width.addEventListener('input', () => { colour.checked = true; });
body.append(h('label', {}, off, 'off'), h('label', {}, colour, 'colour'), pick, h('label', {}, 'width', width));
value = () => (off.checked ? 'off' : `${pick.value}${width.value ? `,${width.value}` : ''}`);
box._set = (v) => {
if (v === 'off') { off.checked = true; return; }
const [c, w] = v.split(',');
colour.checked = true;
if (/^#[0-9a-f]{6}$/i.test(c)) pick.value = c;
width.value = w || '';
};
} else if (o.kind === 'range') {
const range = h('input', { type: 'range', min: 0, max: 1, step: 0.05, value: 0.5, 'aria-label': o.name });
const shown = h('output', {}, '0.50');
range.addEventListener('input', () => { shown.textContent = Number(range.value).toFixed(2); touch(); });
body.append(range, shown);
value = () => String(Number(range.value));
box._set = (v) => { range.value = v; shown.textContent = Number(v).toFixed(2); };
} else if (o.kind === 'color') {
const pick = h('input', { type: 'color', value: '#dc1220', 'aria-label': o.name });
pick.addEventListener('input', touch);
body.append(pick);
value = () => pick.value;
box._set = (v) => { if (/^#[0-9a-f]{6}$/i.test(v)) pick.value = v; };
} else if (o.kind === 'width') {
const num = h('input', { type: 'number', min: 400, step: 10, value: 600, 'aria-label': o.name });
const max = h('span', { class: 'hint' });
num.addEventListener('input', touch);
body.append(num, max);
box._max = (m) => { num.max = m; max.textContent = `400 to ${m} for this route`; };
value = () => num.value;
box._set = (v) => { num.value = v; };
}
give.addEventListener('change', changed);
$('options').append(box);
return { o, box, give, value: () => (give.checked ? value() : null) };
});
// Options given in the page's address are ticked and set: a copied address opens as it was built.
for (const c of controls) {
if (params.has(c.o.name) && c.box._set) { c.box._set(params.get(c.o.name)); c.give.checked = true; }
}
// ------------------------------------------------------------ the address
/** A query value encoded, its commas kept readable (a comma needs no encoding in a query). */
const enc = (v) => encodeURIComponent(v).replace(/%2C/gi, ',');
function query() {
const parts = [];
for (const c of controls) {
c.box.classList.toggle('set', c.give.checked);
const v = c.value();
if (v !== null) parts.push(`${c.o.name}=${enc(v)}`);
}
return parts.length ? `?${parts.join('&')}` : '';
}
function routePath() {
if (route === 'season') return $('season').value ? path`/posters/season/${$('season').value}.png` : null;
if (!chosen || !chosen.name) return null;
if (route === 'race') return path`/posters/race/${chosen.name}/${chosen.season}.png`;
return path`/posters/session/${chosen.name}/${chosen.season}/${$('session').value}.png`;
}
function currentURL() {
const p = routePath();
return p ? api(p) + query() : null;
}
function syncPage() {
const url = new URL(location.href);
url.searchParams.set('route', route);
for (const c of controls) {
const v = c.value();
if (v === null) url.searchParams.delete(c.o.name); else url.searchParams.set(c.o.name, v);
}
if (route === 'season') url.searchParams.set('season', $('season').value);
history.replaceState(null, '', url.href);
}
const card = $('render-card');
function changed() {
for (const b of $('route').querySelectorAll('button')) b.setAttribute('aria-pressed', String(b.dataset.v === route));
// The race picker, its hint and its Jolpica call serve the race and session routes only.
$('race-wrap').hidden = route === 'season';
for (const sel of ['.request', '.status']) $('what').querySelector(`:scope > ${sel}`).hidden = route === 'season';
$('season-label').hidden = route !== 'season';
$('session-label').hidden = route !== 'session';
const width = controls.find((c) => c.o.name === 'width');
width.box._max(FRAME_WIDTH[route]);
const url = currentURL();
syncPage();
card._wanted = url;
if (!url) {
card.querySelector('.request').replaceChildren();
setStatus(card.querySelector('.status'), 'idle', 'Choose a race first.');
return;
}
if (card._shown === url) return;
setRequest(card.querySelector('.request'), url);
card.querySelector('.result').replaceChildren();
$('credits').replaceChildren();
card._shown = null;
if (!card.querySelector('.status').classList.contains('pending')) {
setStatus(card.querySelector('.status'), 'idle', 'Not rendered yet: press the button.');
}
}
// ------------------------------------------------------------ rendering, and the credits it carries
/** The answer's credit headers: what a page on another origin reads only when the service exposes them. */
function showCredits(answer) {
const get = (n) => answer.headers.get(n);
const credits = get('X-Credits');
const licence = get('X-License');
const link = get('Link');
const rows = [
['X-Credits', credits ? h('code', {}, credits) : h('em', {}, 'not readable')],
['X-License', licence ? h('code', {}, licence) : h('em', {}, 'not readable')],
['Link', link ? h('code', {}, link) : h('em', {}, 'not readable')],
['Cache-Control', get('Cache-Control') ? h('code', {}, get('Cache-Control')) : h('em', {}, 'none')],
['ETag', get('ETag') ? h('code', {}, get('ETag')) : h('em', {}, 'none or not readable')],
];
const parts = [
h('h3', {}, 'What the answer says about its sources and its licence'),
h('table', { class: 'kv' }, h('tbody', {}, ...rows.map(([k, v]) => h('tr', {}, h('th', {}, k), h('td', {}, v))))),
];
const unread = [!credits && 'X-Credits', !licence && 'X-License'].filter(Boolean);
if (unread.length) {
parts.push(notice('error', `The answer carries no ${unread.join(' or ')} header this page can read. Either the service does not send it yet, or the page runs on another origin and the service does not expose the header through CORS (Access-Control-Expose-Headers).`));
}
if (credits) {
parts.push(h('p', { class: 'hint' }, 'X-Credits is plain ASCII, folded from the credit drawn on the picture: accents dropped, dashes written as "-". The exact text of every credit is on ',
h('a', { href: F1.linkWithKept('licences.html') }, 'the licences page'), '.'));
}
$('credits').replaceChildren(...parts);
}
async function render() {
const url = currentURL();
if (!url) return;
const button = $('render');
button.disabled = true;
try {
const answer = await call(card, url, { waiting: 'Rendering on the server: a picture whose layers are not kept yet fetches them first…' });
if (card._wanted !== url) {
setRequest(card.querySelector('.request'), card._wanted);
setStatus(card.querySelector('.status'), 'idle', 'The choice changed while it rendered: press the button again.');
return;
}
const out = card.querySelector('.result');
if (!answer) { out.replaceChildren(); $('credits').replaceChildren(); return; }
const format = (controls.find((c) => c.o.name === 'format').value()) || 'png';
await showImage(out, answer, format, {
alt: 'The rendered picture', tile: false,
className: route === 'session' ? 'poster' : 'poster portrait', status: card.querySelector('.status'),
});
showCredits(answer);
card._shown = url;
} finally {
button.disabled = false;
}
}
// ------------------------------------------------------------ the picture's subject
function fillSessions() {
const keep = $('session').value || params.get('session') || 'race';
const own = chosen && chosen.sprint ? F1.SESSIONS.sprint : F1.SESSIONS.standard;
$('session').replaceChildren(...own.map(([s, label], i) => h('option', { value: s }, `Episode ${i + 1} · ${label} (${s})`)));
$('session').value = own.some(([s]) => s === keep) ? keep : 'race';
}
$('route').addEventListener('click', (e) => {
const b = e.target.closest('button');
if (!b) return;
route = b.dataset.v;
changed();
});
$('season').addEventListener('input', () => { seasonTouched = true; changed(); });
$('session').addEventListener('change', changed);
$('render').addEventListener('click', render);
$('season').value = params.get('season') || 2024;
changed();
racePicker($('race-picker'), {
card: $('what'),
onChange: (c) => {
chosen = c;
if (!seasonTouched && !params.get('season')) $('season').value = c.season;
fillSessions();
changed();
},
});
})();
</script>
</body>
</html>
+11
View File
@@ -18,8 +18,12 @@
<a href="map.html">GPS traces</a> <a href="map.html">GPS traces</a>
<a href="grand-prix.html">Grand prix lookup</a> <a href="grand-prix.html">Grand prix lookup</a>
<a href="posters.html">Posters</a> <a href="posters.html">Posters</a>
<a href="builder.html">Poster builder</a>
<a href="kometa.html">Kometa</a> <a href="kometa.html">Kometa</a>
<a href="library.html">Library</a> <a href="library.html">Library</a>
<a href="picker.html">Photo picker</a>
<a href="licences.html">Licences</a>
<a href="../guides/index.html">Guides</a>
</nav> </nav>
<div id="api-base"></div> <div id="api-base"></div>
</header> </header>
@@ -89,6 +93,13 @@
<a class="home" href="index.html">All examples</a> <a class="home" href="index.html">All examples</a>
<a rel="next" href="tracks.html">Track images →</a> <a rel="next" href="tracks.html">Track images →</a>
</footer> </footer>
<footer class="disclaimer">
<p>This website is unofficial and is not associated in any way with the Formula 1 companies. F1, FORMULA ONE,
FORMULA 1, FIA FORMULA ONE WORLD CHAMPIONSHIP, GRAND PRIX and related marks are trade marks of Formula One
Licensing B.V.</p>
<p><a href="licences.html">Licences and credits</a>: every source the pictures are made from, the licence each
picture takes from its sources, and the licence of the track files and the GPS traces (MIT).</p>
</footer>
<script src="site.js"></script> <script src="site.js"></script>
<script> <script>
File diff suppressed because it is too large Load Diff
+11
View File
@@ -18,8 +18,12 @@
<a href="map.html">GPS traces</a> <a href="map.html">GPS traces</a>
<a href="grand-prix.html" aria-current="page">Grand prix lookup</a> <a href="grand-prix.html" aria-current="page">Grand prix lookup</a>
<a href="posters.html">Posters</a> <a href="posters.html">Posters</a>
<a href="builder.html">Poster builder</a>
<a href="kometa.html">Kometa</a> <a href="kometa.html">Kometa</a>
<a href="library.html">Library</a> <a href="library.html">Library</a>
<a href="picker.html">Photo picker</a>
<a href="licences.html">Licences</a>
<a href="../guides/index.html">Guides</a>
</nav> </nav>
<div id="api-base"></div> <div id="api-base"></div>
</header> </header>
@@ -66,6 +70,13 @@
<a class="home" href="index.html">All examples</a> <a class="home" href="index.html">All examples</a>
<a rel="next" href="posters.html">Posters →</a> <a rel="next" href="posters.html">Posters →</a>
</footer> </footer>
<footer class="disclaimer">
<p>This website is unofficial and is not associated in any way with the Formula 1 companies. F1, FORMULA ONE,
FORMULA 1, FIA FORMULA ONE WORLD CHAMPIONSHIP, GRAND PRIX and related marks are trade marks of Formula One
Licensing B.V.</p>
<p><a href="licences.html">Licences and credits</a>: every source the pictures are made from, the licence each
picture takes from its sources, and the licence of the track files and the GPS traces (MIT).</p>
</footer>
<script src="site.js"></script> <script src="site.js"></script>
<script> <script>
+35 -2
View File
@@ -18,8 +18,12 @@
<a href="map.html">GPS traces</a> <a href="map.html">GPS traces</a>
<a href="grand-prix.html">Grand prix lookup</a> <a href="grand-prix.html">Grand prix lookup</a>
<a href="posters.html">Posters</a> <a href="posters.html">Posters</a>
<a href="builder.html">Poster builder</a>
<a href="kometa.html">Kometa</a> <a href="kometa.html">Kometa</a>
<a href="library.html">Library</a> <a href="library.html">Library</a>
<a href="picker.html">Photo picker</a>
<a href="licences.html">Licences</a>
<a href="../guides/index.html">Guides</a>
</nav> </nav>
<div id="api-base"></div> <div id="api-base"></div>
</header> </header>
@@ -75,13 +79,20 @@
</a> </a>
<a class="page" href="posters.html"> <a class="page" href="posters.html">
<h3>Posters</h3> <h3>Posters</h3>
<p>Race posters on five backgrounds, season posters and a thumbnail per session of a race weekend, rendered on request.</p> <p>Race posters on six backgrounds, season posters and a thumbnail per session of a race weekend, rendered on request.</p>
<ul> <ul>
<li><code>/posters/race/{race name}/{season}.png?bg={aerial|osm|dark|light|none}</code></li> <li><code>/posters/race/{race name}/{season}.png?bg={satellite|photo|osm|dark|light|none}</code></li>
<li><code>/posters/season/{season}.png</code></li> <li><code>/posters/season/{season}.png</code></li>
<li><code>/posters/session/{race name}/{season}/{session}.png</code></li> <li><code>/posters/session/{race name}/{season}/{session}.png</code></li>
</ul> </ul>
</a> </a>
<a class="page" href="builder.html">
<h3>Poster builder</h3>
<p>Every option of the poster routes as a control: style, background, photo, texts, locator, track, colours, size and format. Render on demand and read the credits the answer carries.</p>
<ul>
<li><code>/posters/{race|season|session}/….png?style=…&amp;bg=…&amp;photo=…&amp;show=…</code></li>
</ul>
</a>
<a class="page" href="kometa.html"> <a class="page" href="kometa.html">
<h3>Kometa metadata</h3> <h3>Kometa metadata</h3>
<p>The metadata file that gives a Plex Formula 1 library every poster and thumbnail above, and how Kometa uses it.</p> <p>The metadata file that gives a Plex Formula 1 library every poster and thumbnail above, and how Kometa uses it.</p>
@@ -99,6 +110,21 @@
<li><code>/posters/session/{race name}/{season}/{session}.png</code></li> <li><code>/posters/session/{race name}/{season}/{session}.png</code></li>
</ul> </ul>
</a> </a>
<a class="page" href="picker.html">
<h3>Photo picker</h3>
<p>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.</p>
<ul>
<li><code>examples/data/candidates.json</code></li>
<li><code>/picks/circuits.json</code>, <code>/picks/seasons.json</code></li>
</ul>
</a>
<a class="page" href="licences.html">
<h3>Licences</h3>
<p>Every source the pictures are made from, its licence and the credit drawn on every picture; the licence each picture takes from its sources, and that of the track files and the GPS traces.</p>
<ul>
<li><code>/licences</code></li>
</ul>
</a>
</div> </div>
<h2>Choosing which API a page calls</h2> <h2>Choosing which API a page calls</h2>
@@ -136,6 +162,13 @@
<a class="home" href="index.html">All examples</a> <a class="home" href="index.html">All examples</a>
<a rel="next" href="circuits.html">Circuit browser →</a> <a rel="next" href="circuits.html">Circuit browser →</a>
</footer> </footer>
<footer class="disclaimer">
<p>This website is unofficial and is not associated in any way with the Formula 1 companies. F1, FORMULA ONE,
FORMULA 1, FIA FORMULA ONE WORLD CHAMPIONSHIP, GRAND PRIX and related marks are trade marks of Formula One
Licensing B.V.</p>
<p><a href="licences.html">Licences and credits</a>: every source the pictures are made from, the licence each
picture takes from its sources, and the licence of the track files and the GPS traces (MIT).</p>
</footer>
<script src="site.js"></script> <script src="site.js"></script>
<script> <script>
+12 -1
View File
@@ -18,8 +18,12 @@
<a href="map.html">GPS traces</a> <a href="map.html">GPS traces</a>
<a href="grand-prix.html">Grand prix lookup</a> <a href="grand-prix.html">Grand prix lookup</a>
<a href="posters.html">Posters</a> <a href="posters.html">Posters</a>
<a href="builder.html">Poster builder</a>
<a href="kometa.html" aria-current="page">Kometa</a> <a href="kometa.html" aria-current="page">Kometa</a>
<a href="library.html">Library</a> <a href="library.html">Library</a>
<a href="picker.html">Photo picker</a>
<a href="licences.html">Licences</a>
<a href="../guides/index.html">Guides</a>
</nav> </nav>
<div id="api-base"></div> <div id="api-base"></div>
</header> </header>
@@ -80,10 +84,17 @@
</main> </main>
<footer class="pager"> <footer class="pager">
<a rel="prev" href="posters.html">← Posters</a> <a rel="prev" href="builder.html">← Poster builder</a>
<a class="home" href="index.html">All examples</a> <a class="home" href="index.html">All examples</a>
<a rel="next" href="library.html">Library →</a> <a rel="next" href="library.html">Library →</a>
</footer> </footer>
<footer class="disclaimer">
<p>This website is unofficial and is not associated in any way with the Formula 1 companies. F1, FORMULA ONE,
FORMULA 1, FIA FORMULA ONE WORLD CHAMPIONSHIP, GRAND PRIX and related marks are trade marks of Formula One
Licensing B.V.</p>
<p><a href="licences.html">Licences and credits</a>: every source the pictures are made from, the licence each
picture takes from its sources, and the licence of the track files and the GPS traces (MIT).</p>
</footer>
<script src="site.js"></script> <script src="site.js"></script>
<script> <script>
+12 -1
View File
@@ -18,8 +18,12 @@
<a href="map.html">GPS traces</a> <a href="map.html">GPS traces</a>
<a href="grand-prix.html">Grand prix lookup</a> <a href="grand-prix.html">Grand prix lookup</a>
<a href="posters.html">Posters</a> <a href="posters.html">Posters</a>
<a href="builder.html">Poster builder</a>
<a href="kometa.html">Kometa</a> <a href="kometa.html">Kometa</a>
<a href="library.html" aria-current="page">Library</a> <a href="library.html" aria-current="page">Library</a>
<a href="picker.html">Photo picker</a>
<a href="licences.html">Licences</a>
<a href="../guides/index.html">Guides</a>
</nav> </nav>
<div id="api-base"></div> <div id="api-base"></div>
</header> </header>
@@ -50,7 +54,14 @@
<footer class="pager"> <footer class="pager">
<a rel="prev" href="kometa.html">← Kometa</a> <a rel="prev" href="kometa.html">← Kometa</a>
<a class="home" href="index.html">All examples</a> <a class="home" href="index.html">All examples</a>
<span></span> <a rel="next" href="picker.html">Photo picker →</a>
</footer>
<footer class="disclaimer">
<p>This website is unofficial and is not associated in any way with the Formula 1 companies. F1, FORMULA ONE,
FORMULA 1, FIA FORMULA ONE WORLD CHAMPIONSHIP, GRAND PRIX and related marks are trade marks of Formula One
Licensing B.V.</p>
<p><a href="licences.html">Licences and credits</a>: every source the pictures are made from, the licence each
picture takes from its sources, and the licence of the track files and the GPS traces (MIT).</p>
</footer> </footer>
<script src="site.js"></script> <script src="site.js"></script>
+177
View File
@@ -0,0 +1,177 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Licences · F1 Circuits API examples</title>
<meta name="description" content="Every source the F1 Circuits posters are made from, its licence and the credit drawn on every picture; the licences of the posters, the track files and the GPS traces.">
<link rel="icon" href="data:,">
<link rel="stylesheet" href="site.css">
</head>
<body>
<header class="site">
<a class="brand" href="index.html">F1 <span>Circuits</span> API</a>
<nav aria-label="Examples">
<a href="index.html">Overview</a>
<a href="circuits.html">Circuit browser</a>
<a href="tracks.html">Track images</a>
<a href="map.html">GPS traces</a>
<a href="grand-prix.html">Grand prix lookup</a>
<a href="posters.html">Posters</a>
<a href="builder.html">Poster builder</a>
<a href="kometa.html">Kometa</a>
<a href="library.html">Library</a>
<a href="picker.html">Photo picker</a>
<a href="licences.html" aria-current="page">Licences</a>
<a href="../guides/index.html">Guides</a>
</nav>
<div id="api-base"></div>
</header>
<main>
<h1>Licences</h1>
<p class="lead">
Every picture the API makes is drawn from sources whose licences allow keeping a copy, and each says where it comes
from: the credit of every source it was made from is drawn at its foot, sent in its <code>X-Credits</code> header,
and listed here. A picture’s licence follows its sources, and is sent in its <code>X-License</code> header. Its
<code>Link: &lt;/licences&gt;; rel="license"</code> header points to this list.
</p>
<section class="card" id="call">
<h2>The sources</h2>
<p>What <code>/licences</code> answers, as a table. A credit with <code>&lt;author&gt;</code> and
<code>&lt;licence&gt;</code> is filled in with the photo’s own; one with <code>&lt;year&gt;</code> with the mosaic’s
year. The last column is the licence a picture made from that source gets.</p>
<div class="request"></div>
<div class="status"></div>
<div id="sources"></div>
<details class="result-raw"><summary>The answer as it came</summary><div class="result"></div></details>
</section>
<section class="card">
<h2>What the API offers, and under which licence</h2>
<div id="outputs"></div>
<p class="hint">A race name and its date on a picture are single facts: they do not set its licence. The Kometa
file says in its first lines that its race schedules come from Jolpica, under CC BY-NC-SA 4.0.</p>
</section>
<section class="card">
<h2>Formula 1</h2>
<p>This website is unofficial and is not associated in any way with the Formula 1 companies. F1, FORMULA ONE,
FORMULA 1, FIA FORMULA ONE WORLD CHAMPIONSHIP, GRAND PRIX and related marks are trade marks of Formula One
Licensing B.V.</p>
</section>
</main>
<footer class="pager">
<a rel="prev" href="picker.html">← Photo picker</a>
<a class="home" href="index.html">All examples</a>
<span></span>
</footer>
<footer class="disclaimer">
<p>This website is unofficial and is not associated in any way with the Formula 1 companies. F1, FORMULA ONE,
FORMULA 1, FIA FORMULA ONE WORLD CHAMPIONSHIP, GRAND PRIX and related marks are trade marks of Formula One
Licensing B.V.</p>
<p><a href="licences.html">Licences and credits</a>: every source the pictures are made from, the licence each
picture takes from its sources, and the licence of the track files and the GPS traces (MIT).</p>
</footer>
<script src="site.js"></script>
<script>
(function () {
const { h, api, callJSON, notice } = F1;
const $ = (id) => document.getElementById(id);
const CC = (code) => `https://creativecommons.org/licenses/${code}/4.0/`;
// The rule as the lead settled it (2026-11-27): shown only where /licences does not say it, and marked so.
const STATED = {
pictures: {
rule: 'A picture’s licence follows the sources it is made from.',
licences: [
{ licence: 'CC BY-SA 4.0', licence_url: CC('by-sa'), when: 'made from a CC BY-SA photo' },
{ licence: 'CC BY-NC-SA 4.0', licence_url: CC('by-nc-sa'), when: 'made from EOxCloudless 2025' },
{ licence: 'CC BY 4.0', licence_url: CC('by'), when: 'otherwise' },
],
},
tracks: { licence: 'MIT', licence_url: null },
};
/** The licence a picture from a source gets, by the rule, for a source whose entry does not say it. */
const BY_RULE = {
commons: 'CC BY-SA 4.0 from a CC BY-SA photo, else CC BY 4.0',
eox: 'CC BY-NC-SA 4.0',
jolpica: 'does not set a picture’s licence',
traces: 'does not set a picture’s licence',
};
const link = (href, text) => (href ? h('a', { href, target: '_blank', rel: 'noopener' }, text || href) : text || '–');
/** What a source is used for, its options (bg=photo, bg=satellite, …) set as code so they read as the options they are. */
function usedFor(text) {
const out = h('span');
for (const part of String(text).split(/(\b(?:bg|photo|locator|track)=[a-z0-9#]+(?:\|[a-z0-9]+)*)/)) {
if (part) out.append(/^(bg|photo|locator|track)=/.test(part) ? h('code', {}, part) : part);
}
return out;
}
/** A credit form, its placeholders marked. */
function credit(text) {
const code = h('code');
for (const part of String(text || '').split(/(<[a-z]+>)/)) {
if (!part) continue;
code.append(/^<[a-z]+>$/.test(part) ? h('em', { title: 'Filled in per picture' }, part) : part);
}
return code;
}
function sourcesTable(sources) {
return h('table', { class: 'sources' },
h('thead', {}, h('tr', {}, ...['Source', 'Used for', 'Licence', 'Credit', 'Terms', 'A picture from it'].map((t) => h('th', {}, t)))),
h('tbody', {}, ...sources.map((s) => h('tr', { id: `source-${s.id}` },
h('td', {}, h('b', {}, s.name || s.id), h('br'), h('small', {}, h('code', {}, s.id))),
h('td', {}, s.used_for ? usedFor(s.used_for) : '–'),
h('td', {}, link(s.licence_url, s.licence)),
h('td', {}, credit(s.credit)),
h('td', {}, s.terms ? link(s.terms, new URL(s.terms, location.href).host || s.terms) : '–'),
h('td', {}, s.picture_licence || h('span', { title: 'The answer does not say it; derived from the rule' },
BY_RULE[s.id] || 'CC BY 4.0', h('br'), h('small', {}, h('em', {}, 'by the rule'))))))));
}
function outputs(answer) {
const pictures = (answer && answer.pictures) || STATED.pictures;
const tracks = (answer && answer.tracks) || STATED.tracks;
const missing = [!(answer && answer.pictures) && 'the pictures’ licence', !(answer && answer.tracks) && 'the track files’ licence'].filter(Boolean);
const rows = [
...(pictures.licences || []).map((l, i) => h('tr', {},
i === 0 ? h('td', { rowspan: pictures.licences.length }, 'Race posters, season posters and session thumbnails') : null,
h('td', {}, link(l.licence_url, l.licence)),
h('td', {}, l.when || '–'))),
h('tr', {}, h('td', {}, 'Track files (SVG, PNG, GeoJSON) and the GPS traces'), h('td', {}, link(tracks.licence_url, tracks.licence)),
h('td', {}, 'LICENSE.md in the repository')),
];
$('outputs').replaceChildren(
missing.length ? notice('error', `/licences did not say ${missing.join(' or ')}, so this shows the rule as it was decided, not what the service says.`) : '',
h('p', {}, pictures.rule || ''),
h('table', {},
h('thead', {}, h('tr', {}, h('th', {}, 'What'), h('th', {}, 'Licence'), h('th', {}, 'When'))),
h('tbody', {}, ...rows)));
}
(async () => {
const answer = await callJSON($('call'), api('/licences'));
if (!answer) {
$('sources').replaceChildren(notice('error', 'The sources cannot be listed: /licences did not answer (see above). The service may not serve it yet.'));
outputs(null);
return;
}
if (!Array.isArray(answer.sources)) {
$('sources').replaceChildren(notice('error', 'The answer has no list of sources (no "sources" array).'));
} else {
$('sources').replaceChildren(sourcesTable(answer.sources));
}
outputs(answer);
})();
})();
</script>
</body>
</html>
+22 -6
View File
@@ -20,8 +20,12 @@
<a href="map.html" aria-current="page">GPS traces</a> <a href="map.html" aria-current="page">GPS traces</a>
<a href="grand-prix.html">Grand prix lookup</a> <a href="grand-prix.html">Grand prix lookup</a>
<a href="posters.html">Posters</a> <a href="posters.html">Posters</a>
<a href="builder.html">Poster builder</a>
<a href="kometa.html">Kometa</a> <a href="kometa.html">Kometa</a>
<a href="library.html">Library</a> <a href="library.html">Library</a>
<a href="picker.html">Photo picker</a>
<a href="licences.html">Licences</a>
<a href="../guides/index.html">Guides</a>
</nav> </nav>
<div id="api-base"></div> <div id="api-base"></div>
</header> </header>
@@ -32,7 +36,7 @@
Each layout was traced by GPS along the track. Its <code>geojson</code> format is that trace: a GeoJSON Each layout was traced by GPS along the track. Its <code>geojson</code> format is that trace: a GeoJSON
<code>FeatureCollection</code> holding one <code>LineString</code> of <code>[longitude, latitude]</code> points. Any <code>FeatureCollection</code> holding one <code>LineString</code> of <code>[longitude, latitude]</code> points. Any
map library draws it as it comes; this page uses <a href="https://leafletjs.com/">Leaflet</a>. Switch to the map library draws it as it comes; this page uses <a href="https://leafletjs.com/">Leaflet</a>. Switch to the
satellite layer to see the trace follow the tarmac. satellite layer (EOxCloudless, Sentinel-2 at 10 m) to see the trace over the ground.
</p> </p>
<div class="card" id="tree"> <div class="card" id="tree">
@@ -65,6 +69,13 @@
<a class="home" href="index.html">All examples</a> <a class="home" href="index.html">All examples</a>
<a rel="next" href="grand-prix.html">Grand prix lookup →</a> <a rel="next" href="grand-prix.html">Grand prix lookup →</a>
</footer> </footer>
<footer class="disclaimer">
<p>This website is unofficial and is not associated in any way with the Formula 1 companies. F1, FORMULA ONE,
FORMULA 1, FIA FORMULA ONE WORLD CHAMPIONSHIP, GRAND PRIX and related marks are trade marks of Formula One
Licensing B.V.</p>
<p><a href="licences.html">Licences and credits</a>: every source the pictures are made from, the licence each
picture takes from its sources, and the licence of the track files and the GPS traces (MIT).</p>
</footer>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script> integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
@@ -88,13 +99,18 @@
maxZoom: 19, maxZoom: 19,
attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors', attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
}).addTo(map); }).addTo(map);
const satellite = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', { // EOxCloudless, the newest Sentinel-2 mosaic (10 m): the satellite source the posters use where no photo or national
// aerial photo exists (docs/posters.md). Tiles past zoom 15 are the same pixels, so Leaflet scales them up.
const satellite = L.tileLayer('https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-2025_3857/default/g/{z}/{y}/{x}.jpg', {
maxZoom: 19, maxZoom: 19,
maxNativeZoom: 18, maxNativeZoom: 15,
attribution: 'Imagery &copy; Esri, Maxar, Earthstar Geographics', attribution: 'EOxCloudless <a href="https://cloudless.eox.at">https://cloudless.eox.at</a> by EOX IT Services GmbH'
+ ' (Contains modified Copernicus Sentinel data 2025),'
+ ' <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a>',
}); });
L.control.layers({ 'OpenStreetMap': osm, 'Satellite (Esri)': satellite }).addTo(map); L.control.layers({ 'OpenStreetMap': osm, 'Satellite (EOxCloudless 2025)': satellite }).addTo(map);
L.control.scale({ imperial: false }).addTo(map); // Top left: EOxCloudless's credit runs over two lines at the foot, where it would cover the scale.
L.control.scale({ imperial: false, position: 'topleft' }).addTo(map);
map.on('focus', () => map.scrollWheelZoom.enable()); map.on('focus', () => map.scrollWheelZoom.enable());
map.on('blur', () => map.scrollWheelZoom.disable()); map.on('blur', () => map.scrollWheelZoom.disable());
+793
View File
@@ -0,0 +1,793 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Photo picker · F1 Circuits API examples</title>
<meta name="description" content="Pick a freely licensed Wikimedia Commons photo per circuit layout and per season for the F1 Circuits posters, and copy its entry for the picks file.">
<link rel="icon" href="data:,">
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="">
<link rel="stylesheet" href="site.css">
</head>
<body>
<header class="site">
<a class="brand" href="index.html">F1 <span>Circuits</span> API</a>
<nav aria-label="Examples">
<a href="index.html">Overview</a>
<a href="circuits.html">Circuit browser</a>
<a href="tracks.html">Track images</a>
<a href="map.html">GPS traces</a>
<a href="grand-prix.html">Grand prix lookup</a>
<a href="posters.html">Posters</a>
<a href="builder.html">Poster builder</a>
<a href="kometa.html">Kometa</a>
<a href="library.html">Library</a>
<a href="picker.html" aria-current="page">Photo picker</a>
<a href="licences.html">Licences</a>
<a href="../guides/index.html">Guides</a>
</nav>
<div id="api-base"></div>
</header>
<!-- bw as the service draws it: Pillow's convert("L"), L = 0.299 R + 0.587 G + 0.114 B on the sRGB values. -->
<svg width="0" height="0" style="position:absolute" aria-hidden="true" focusable="false">
<filter id="bw" color-interpolation-filters="sRGB">
<feColorMatrix type="matrix" values="0.299 0.587 0.114 0 0 0.299 0.587 0.114 0 0 0.299 0.587 0.114 0 0 0 0 0 1 0"/>
</filter>
</svg>
<main>
<h1>Photo picker</h1>
<p class="lead">
Per layout, the main choice is what <code>bg=satellite</code> draws: the country’s own aerial photo or
EOxCloudless 2025, or the dark map instead. A layout may also have a Wikimedia Commons photo picked for
<code>bg=photo</code>, which falls back to what <code>bg=satellite</code> draws while none is picked; a season poster
shows that season’s cars only from a picked photo. The photos are the candidates
<code>tools/commons_candidates.py</code> found, cropped to the poster’s frame as the service crops them, in natural
colour or black and white. Each choice gives the entry to copy into the picks file. The page writes nothing to the
server: a pick is a change to the repository.
</p>
<p>
Only CC0, public domain, CC BY and CC BY-SA files are listed, with Commons’ quality marks first, then size, then
landscape. A search also finds ground photos, maps and the odd helicopter, so look at each one before you pick it.
</p>
<section class="card" id="files">
<h2>1. The lists</h2>
<p class="hint">The candidates come with the site; the picks are the API’s, <code>/picks/circuits.json</code> and
<code>/picks/seasons.json</code>, as the poster service draws from them. A page opened from a working copy (from
disk, or served on this machine with <code>python3 -m http.server</code>) reads the working copy’s
<code>circuits/photos.json</code> and <code>seasons/photos.json</code> when the API does not answer; or load a
picks file from disk below.</p>
<div id="cand-file">
<div class="request"></div>
<div class="status"></div>
<div class="result"></div>
</div>
<div id="picks-circuits">
<div class="request"></div>
<div class="status"></div>
<div class="result"></div>
</div>
<div id="picks-seasons">
<div class="request"></div>
<div class="status"></div>
<div class="result"></div>
</div>
</section>
<section class="card" id="choose">
<h2>2. What to pick for</h2>
<div class="controls">
<label><span>Pick for</span>
<span class="seg" id="mode">
<button type="button" data-v="layout">A layout</button><button type="button" data-v="season">A season</button>
</span>
</label>
<label><span>Photo (<code>photo</code>)</span>
<span class="seg" id="treat">
<button type="button" data-v="natural">natural</button><button type="button" data-v="bw">bw</button>
</span>
</label>
<label id="frame-label"><span>Frame</span>
<span class="seg" id="frame">
<button type="button" data-v="poster">poster 1000×1500</button><button type="button" data-v="thumb">thumbnail 1920×1080</button>
</span>
</label>
</div>
<div class="controls" id="layout-picker"></div>
<div class="controls" id="season-picker" hidden>
<label>Season <select id="season" aria-label="Season"></select></label>
</div>
<div class="request"></div>
<div class="status"></div>
<div class="result"></div>
</section>
<section class="card" id="entry" hidden>
<h2>3. The entry to copy</h2>
<div id="entry-body"></div>
</section>
<div id="photos-root">
<h2 id="sat-title" hidden>bg=satellite: the satellite, or the map</h2>
<div id="sat"></div>
<h2 id="others-title">Picks of the circuit’s other layouts</h2>
<div id="others"></div>
<h2 id="cands-title">Candidates</h2>
<div id="cands"></div>
</div>
</main>
<footer class="pager">
<a rel="prev" href="library.html">← Library</a>
<a class="home" href="index.html">All examples</a>
<a rel="next" href="licences.html">Licences →</a>
</footer>
<footer class="disclaimer">
<p>This website is unofficial and is not associated in any way with the Formula 1 companies. F1, FORMULA ONE,
FORMULA 1, FIA FORMULA ONE WORLD CHAMPIONSHIP, GRAND PRIX and related marks are trade marks of Formula One
Licensing B.V.</p>
<p><a href="licences.html">Licences and credits</a>: every source the pictures are made from, the licence each
picture takes from its sources, and the licence of the track files and the GPS traces (MIT).</p>
</footer>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"
integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
<script src="site.js"></script>
<script>
(function () {
const { h, notice, setRequest, setStatus, showJSON, layoutPicker, layoutYears, params, api, path, call, showImage } = F1;
const $ = (id) => document.getElementById(id);
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'), 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',
treat: params.get('photo') === 'bw' ? 'bw' : 'natural',
frame: params.get('frame') === 'thumb' ? 'thumb' : 'poster',
candidates: null,
picks: { circuits: null, seasons: null },
pick: null, // the layout picker's choice
chosen: null, // { key, cand }
};
function syncURL() {
const url = new URL(location.href);
url.searchParams.set('mode', state.mode);
url.searchParams.set('photo', state.treat);
url.searchParams.set('frame', state.frame);
if (state.mode === 'season' && $('season').value) url.searchParams.set('season', $('season').value);
history.replaceState(null, '', url.href);
}
// ------------------------------------------------------------ the three files
/** A picks file read: an object of entries; keys starting with "$" (the format note) are kept but are no pick. */
function validPicks(value) {
if (!value || typeof value !== 'object' || Array.isArray(value)) return 'it is not a JSON object';
for (const [k, v] of Object.entries(value)) {
if (k.startsWith('$')) continue;
if (!v || typeof v !== 'object' || (typeof v.file !== 'string' && v.use !== 'map')) return `its entry “${k}” has no file and does not say {"use": "map"}`;
}
return '';
}
function validCandidates(value) {
if (!value || typeof value !== 'object' || !value.layouts || !value.seasons) return 'it has no layouts and seasons';
return '';
}
/** 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 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;
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;
}
failed.push(`${url}: ${read.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];
if (!file) return;
try {
const value = JSON.parse(await file.text());
const bad = check(value);
if (bad) { setStatus(card.querySelector('.status'), 'error', `${file.name}: ${bad}.`); return; }
accept(name, value, `Loaded ${f.what} from disk (${file.name}).`);
done(value);
} catch (e) {
setStatus(card.querySelector('.status'), 'error', `${file.name} is not JSON: ${e.message}`);
}
});
out.replaceChildren(notice('error',
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. ',
'Load it from disk: ', input));
}
function accept(name, value, text) {
const f = FILES[name];
const card = f.card;
setStatus(card.querySelector('.status'), 'ok', text);
const out = card.querySelector('.result');
if (name === 'candidates') {
const ls = Object.values(value.layouts);
const ss = Object.values(value.seasons);
const about = value.about || {};
out.replaceChildren(h('p', { class: 'hint' },
`${ls.filter((l) => l.length).length} of ${ls.length} layouts and ${ss.filter((s) => s.length).length} of ${ss.length} seasons have at least one candidate. `,
about.made ? `Listed ${about.made.replace('T', ' ').replace('+00:00', ' UTC')}` : '',
about.requests ? ` with ${about.requests} requests to Commons.` : '.'));
} else {
const n = Object.keys(value).filter((k) => !k.startsWith('$')).length;
out.replaceChildren(h('p', { class: 'hint' }, `${n} pick${n === 1 ? '' : 's'} so far.`,
value.$comment ? h('span', {}, ' Its note: ', h('em', {}, String(value.$comment))) : ''));
}
if (name === 'candidates') state.candidates = value; else state.picks[name] = value;
}
// ------------------------------------------------------------ cards
/** Commons' thumbnail of a file: from the candidates when listed, else its standard 500-px thumbnail address. */
function thumbOf(file) {
const c = state.candidates;
if (c) {
for (const list of [...Object.values(c.layouts), ...Object.values(c.seasons)]) {
const hit = list.find((x) => x.file === file);
if (hit) return hit.thumb;
}
}
return `https://commons.wikimedia.org/wiki/Special:FilePath/${encodeURIComponent(file)}?width=500`;
}
function pageOf(file) { return `https://commons.wikimedia.org/wiki/File:${encodeURIComponent(file.replace(/ /g, '_'))}`; }
/** How much the service scales a photo up to cover the frame, when it does. */
function scaleUp(c) {
const [fw, fh] = FRAMES[frameNow()];
if (!c.width || !c.height) return 0;
const s = Math.max(fw / c.width, fh / c.height);
return s > 1 ? s : 0;
}
function frameNow() { return state.mode === 'season' ? 'poster' : state.frame; }
function photoCard(c, opts = {}) {
const up = scaleUp(c);
const tags = [
...(c.marks || []).map((m) => h('span', { class: 'tag mark', title: 'A Commons quality mark' }, m)),
...(c.restrictions || []).map((r) => h('span', { class: 'tag warn', title: 'A right beside copyright the file names' }, `${r} rights`)),
up ? h('span', { class: 'tag warn', title: 'Smaller than the frame: the service scales it up' }, `scaled up ×${up.toFixed(2)}`) : null,
].filter(Boolean);
const chosen = opts.choose && state.chosen && state.chosen.cand && state.chosen.cand.file === c.file;
const card = h('article', { class: `photo-card${opts.picked ? ' picked' : ''}${chosen ? ' chosen' : ''}` },
h('div', { class: 'photo-frame' },
h('img', { src: c.thumb || thumbOf(c.file), alt: c.file, loading: 'lazy', decoding: 'async', referrerpolicy: 'no-referrer' })),
opts.label ? h('div', { class: 'meta' }, h('b', {}, opts.label)) : null,
h('div', { class: 'name' }, c.file),
h('div', { class: 'meta' },
h('b', { title: c.date_from === 'category' ? 'The file gives no date: the season it is filed under' : null },
c.date ? `${c.date}${c.date_from === 'category' ? ' (its season)' : ''}` : 'undated'),
c.width ? ` · ${c.width}×${c.height}` : '',
' · ', c.licence_url ? h('a', { href: c.licence_url, target: '_blank', rel: 'noopener' }, c.licence) : c.licence,
h('br'), c.author),
tags.length ? h('div', { class: 'tags' }, ...tags) : null,
c.found ? h('div', { class: 'meta', title: 'How the tool found it' },
`Found by ${c.found.map((f) => (f === 'marked' ? 'a search for its category’s quality-marked files' : f)).join('; ')}`) : null,
h('div', { class: 'actions' },
opts.choose ? h('button', { type: 'button', class: 'primary', onclick: () => opts.choose(card) }, 'Choose') : null,
h('a', { href: c.page || pageOf(c.file), target: '_blank', rel: 'noopener' }, 'On Commons')));
return card;
}
/** A pick as the picks file holds it: a photo, or {"use": "map"}. */
function pickCard(entry, label, picked) {
if (typeof entry.file === 'string' && entry.use === 'map') {
const card = photoCard({ ...entry, thumb: thumbOf(entry.file) }, { label, picked });
card.querySelector('.name').after(h('div', { class: 'tags' }, h('span', { class: 'tag', title: 'Its entry also says "use": "map"' }, 'the dark map for bg=satellite')));
return card;
}
if (entry.use === 'map') {
return h('article', { class: `photo-card${picked ? ' picked' : ''}` },
h('div', { class: 'map-frame plain' }, h('span', {}, 'The dark map')),
h('div', { class: 'meta' }, h('b', {}, label)),
h('div', { class: 'name' }, '{"use": "map"}: the dark map for bg=satellite'));
}
return photoCard({ ...entry, thumb: thumbOf(entry.file) }, { label, picked });
}
function grid(cards, extra = '') {
const cls = `photos${frameNow() === 'thumb' ? ' thumb' : ''}${extra ? ` ${extra}` : ''}`;
return h('div', { class: cls }, ...cards);
}
// ------------------------------------------------------------ the entry to copy
function entryOf(c) {
const e = {};
for (const k of PICK_FIELDS) e[k] = c[k] === undefined ? null : c[k];
return e;
}
/**
* The picks file's text with one entry set: its "$" keys first as they stand, then every pick by key. Written from
* a list of pairs, not an object: an object lists keys such as "2024" before "$comment", whatever their order.
*/
function withPick(file, key, entry) {
const notes = Object.entries(file).filter(([k]) => k.startsWith('$'));
const picks = new Map(Object.entries(file).filter(([k]) => !k.startsWith('$')));
if (entry === null) picks.delete(key); else picks.set(key, entry);
const sorted = [...picks.keys()].sort((a, b) => a.localeCompare(b, 'en', { numeric: true })).map((k) => [k, picks.get(k)]);
const pairs = [...notes, ...sorted];
const indent = (text) => text.replace(/\n/g, '\n ');
return pairs.length
? `{\n${pairs.map(([k, v]) => ` ${JSON.stringify(k)}: ${indent(JSON.stringify(v, null, 2))}`).join(',\n')}\n}`
: '{}';
}
function copyBlock(title, text) {
const button = h('button', { type: 'button' }, 'Copy');
button.addEventListener('click', async () => {
try { await navigator.clipboard.writeText(text); button.textContent = 'Copied'; } catch { button.textContent = 'Select and copy'; }
setTimeout(() => { button.textContent = 'Copy'; }, 1500);
});
const body = h('div');
showJSON(body, text);
return h('div', { class: 'copy-block' }, h('div', { class: 'head' }, h('span', {}, title), button), body);
}
/**
* The entry a choice leaves for a key, from the one there now: one entry may carry the photo fields (bg=photo),
* "use": "map" (bg=satellite), or both. Choosing a photo keeps "use": "map"; the map keeps the photo; keeping the
* satellite drops only "use". null: no entry is left.
*/
function entryFor(existing, kind, cand) {
const photo = existing && typeof existing.file === 'string'
? Object.fromEntries(PICK_FIELDS.filter((k) => k in existing).map((k) => [k, existing[k]])) : null;
const map = !!existing && existing.use === 'map';
if (kind === 'photo') return { ...entryOf(cand), ...(map ? { use: 'map' } : {}) };
if (kind === 'map') return { ...(photo || {}), use: 'map' };
return photo;
}
/** What of the entry there now a choice keeps, said in one sentence. */
function keeps(existing, kind) {
if (!existing) return '';
if (kind === 'photo' && existing.use === 'map') return ' It keeps "use": "map" for bg=satellite.';
if (kind === 'map' && typeof existing.file === 'string') return ' It keeps the photo picked for bg=photo.';
if (kind === 'satellite') return ' It keeps the photo picked for bg=photo, without "use".';
return '';
}
function showEntry() {
const section = $('entry');
const body = $('entry-body');
if (!state.chosen) { section.hidden = true; return; }
const { key, cand, fileName, fileKey, kind } = state.chosen;
const file = state.picks[fileKey];
const existing = file && Object.prototype.hasOwnProperty.call(file, key) ? file[key] : null;
if (kind === 'photo' && !cand.date) {
body.replaceChildren(notice('error', `${cand.file} has no date, and the service refuses an entry without one: run tools/commons_candidates.py again, or choose another.`));
section.hidden = false;
return;
}
const entry = entryFor(existing, kind, cand);
const rule = [' ', h('a', { href: F1.linkWithKept('licences.html') }, 'The licences page'), ' states the rule.'];
const what = kind === 'satellite' ? 'the satellite, not the map' : kind === 'map' ? 'the dark map instead of the satellite' : cand.file;
const parts = [h('p', {}, 'For ', h('code', {}, key), ': ', h('b', {}, what), '.')];
if (entry) {
parts.push(
h('p', {}, 'Copy the entry into ', h('code', {}, fileName), ', or the whole file below with the entry in place.', keeps(existing, kind)),
copyBlock(`The entry, for ${fileName}`, `${JSON.stringify(key)}: ${JSON.stringify(entry, null, 2)}`));
} else if (!file) {
parts.push(h('p', {}, 'No entry is needed for it.'));
} else if (existing) {
parts.push(h('p', {}, `No entry is left for it: remove the one ${fileName} has now.`));
} else {
parts.push(h('p', { class: 'hint' }, `No entry is needed for it, and ${fileName} has none: nothing to change.`));
}
if (kind === 'satellite') {
const src = satelliteSource(key);
parts.push(notice('info', `bg=satellite draws ${src.name} for this layout; a poster from it is ${src.poster}. A picture’s licence follows its sources.`, ...rule));
} else if (kind === 'map') {
parts.push(notice('info', 'The service draws the dark OpenStreetMap map for this layout in place of the satellite: for bg=satellite, and for bg=photo while no photo is picked. A poster on it is CC BY 4.0.', ...rule));
} else {
const sa = /\bBY-SA\b/i.test(cand.licence);
parts.push(notice('info', fileKey === 'circuits' ? 'This photo serves bg=photo only; bg=satellite does not change. ' : '', sa
? `${cand.licence} is share-alike: a poster made from it is adapted material, shared under CC BY-SA terms. Such a poster is CC BY-SA 4.0.`
: `A poster made from it is CC BY 4.0: a picture’s licence follows its sources, and ${cand.licence} asks no share-alike.`, ...rule));
if ((cand.restrictions || []).length) {
parts.push(notice('', `Commons names ${cand.restrictions.join(' and ')} rights for this file: rights beside its copyright licence, such as a person’s likeness or a trade mark shown in it.`));
}
}
if (!file) parts.push(notice('error', `${fileName} was not read, so the whole file cannot be shown${kind === 'photo' ? '' : ', nor whether it has an entry for this layout now'}: load it from disk above.`));
else if (entry || existing) parts.push(copyBlock(`The whole of ${fileName} ${entry ? 'with this entry' : 'without an entry for it'}`, withPick(file, key, entry)));
body.replaceChildren(...parts);
section.hidden = false;
}
function choose(key, cand, card, fileName, fileKey) {
for (const el of document.querySelectorAll('.photo-card.chosen')) el.classList.remove('chosen');
card.classList.add('chosen');
state.chosen = { key, cand, fileName, fileKey, mode: state.mode, kind: 'photo' };
markChoices();
showEntry();
$('entry').scrollIntoView({ behavior: 'smooth', block: 'start' });
}
/** "Keep the satellite" (no entry) or "use the map instead" ({"use": "map"}) for a layout. */
function chooseSurface(key, kind) {
for (const el of document.querySelectorAll('.photo-card.chosen')) el.classList.remove('chosen');
state.chosen = { key, kind, fileName: 'circuits/photos.json', fileKey: 'circuits', mode: 'layout' };
markChoices();
showEntry();
$('entry').scrollIntoView({ behavior: 'smooth', block: 'start' });
}
function markChoices() {
for (const b of document.querySelectorAll('#sat .choices button')) {
b.setAttribute('aria-pressed', String(!!state.chosen && state.chosen.kind === b.dataset.kind));
}
}
// ------------------------------------------------------------ without a photo: the satellite, or the map
// What bg=satellite draws (the operator, 2026-11-27): the country's own aerial photo, else EOxCloudless 2025; a
// Commons photo only ever for bg=photo. The layers the service uses; past maxNativeZoom (the deepest level every
// circuit of that country has, checked 2026-11-27) Leaflet scales the deepest tiles up.
const NATIONAL = {
netherlands: { name: 'PDOK’s aerial photo', url: 'https://service.pdok.nl/hwh/luchtfotorgb/wmts/v1_0/Actueel_orthoHR/EPSG:3857/{z}/{x}/{y}.jpeg',
maxNativeZoom: 19, credit: 'Luchtfoto: PDOK / Samenwerkingsverband Beeldmateriaal, CC BY 4.0', licence: 'CC BY 4.0', poster: 'CC BY 4.0' },
france: { name: 'IGN’s BD ORTHO 2021–2023', url: 'https://data.geopf.fr/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ORTHOIMAGERY.ORTHOPHOTOS2021-2023&STYLE=normal&TILEMATRIXSET=PM&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=image/jpeg',
maxNativeZoom: 18, credit: '© IGN – BD ORTHO, 2021–2023', licence: 'Licence Ouverte (Etalab) 2.0', poster: 'CC BY 4.0' },
'united-states': { name: 'USGS imagery', url: 'https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}',
maxNativeZoom: 16, credit: 'USDA, USGS The National Map: Orthoimagery', licence: 'public domain', poster: 'CC BY 4.0' },
};
const EOX = {
name: 'EOxCloudless 2025',
url: 'https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-2025_3857/default/g/{z}/{y}/{x}.jpg',
maxNativeZoom: 15,
credit: 'EOxCloudless https://cloudless.eox.at by EOX IT Services GmbH (Contains modified Copernicus Sentinel data 2025)',
licence: 'CC BY-NC-SA 4.0',
poster: 'CC BY-NC-SA 4.0',
};
/** What bg=satellite draws for a layout that does not ask for the map. */
function satelliteSource(key) {
return NATIONAL[key.split('/')[0]] || EOX;
}
const traces = new Map();
const races = new Map();
let satMaps = [];
let satShown = '';
/** A layout's GPS trace as [lat, lon] points, or null when it has none. */
async function traceOf(p) {
const key = `${p.country}/${p.city}/${p.circuit}/${p.layout}`;
if (!traces.has(key)) {
traces.set(key, (async () => {
const res = await fetch(api(path`/circuits/${p.country}/${p.city}/${p.circuit}/layout/${p.layout}/geojson`));
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const line = F1.lineOf(await res.json());
const pts = line ? line.geometry.coordinates.map(([lon, lat]) => [lat, lon]) : [];
return pts.length > 1 ? pts : null;
})());
}
return traces.get(key);
}
/** The latest race at a circuit within a layout's years, from Jolpica; null when none. */
async function raceOn(p) {
const id = p.circuitData && p.circuitData.ergastId;
if (!id) return null;
if (!races.has(id)) {
races.set(id, (async () => {
const all = [];
for (let offset = 0; ; offset += 100) {
const res = await fetch(`${F1.JOLPICA}/circuits/${encodeURIComponent(id)}/races.json?limit=100&offset=${offset}`);
if (!res.ok) throw new Error(`Jolpica answered HTTP ${res.status}`);
const d = (await res.json()).MRData;
all.push(...d.RaceTable.Races);
if (offset + 100 >= Number(d.total)) return all;
}
})());
}
const list = await races.get(id);
const first = parseInt(p.layout, 10);
const last = p.layout.endsWith('-') ? Infinity : parseInt(p.layout.split('-')[1] || p.layout, 10);
const fit = list.filter((r) => Number(r.season) >= first && Number(r.season) <= last);
return fit.length ? fit[fit.length - 1] : null;
}
function mapCard(src, note) {
const box = h('div', { class: 'map-box' });
const card = h('article', { class: 'photo-card' },
h('div', { class: 'map-frame' }, box),
note ? h('div', { class: 'meta' }, h('b', {}, note)) : null,
h('div', { class: 'name' }, src.name),
h('div', { class: 'meta' }, src.credit, h('br'), `${src.licence}; a poster from it: `, h('b', {}, src.poster)));
card._box = box;
card._src = src;
return card;
}
function serviceCard(p) {
const route = frameNow() === 'thumb' ? 'session thumbnail' : 'race poster';
const button = h('button', { type: 'button' }, `Render the service’s ${route}`);
const card = h('article', { class: 'photo-card' },
h('div', { class: 'map-frame plain result' }, h('span', {}, 'What the service draws now, on demand: it renders and may fetch tiles first.')),
h('div', { class: 'name' }, `The service’s ${route}, bg=satellite`),
h('div', { class: 'request compact' }),
h('div', { class: 'status idle' }, 'Not rendered yet.'),
h('div', { class: 'actions' }, button));
button.addEventListener('click', async () => {
button.disabled = true;
const st = card.querySelector('.status');
try {
setStatus(st, 'pending', 'Finding a race on this layout at Jolpica…');
const race = await raceOn(p);
if (!race) { setStatus(st, 'error', `Jolpica lists no race at this circuit in ${layoutYears(p.layout)}.`); return; }
const url = frameNow() === 'thumb'
? api(path`/posters/session/${race.raceName}/${race.season}/race.png`) + '?bg=satellite'
: api(path`/posters/race/${race.raceName}/${race.season}.png`) + '?bg=satellite';
const answer = await call(card, url, { label: `${race.raceName} ${race.season}`, waiting: 'Rendering on the server…' });
const frame = card.querySelector('.map-frame');
if (!answer) { frame.replaceChildren(h('span', {}, 'No picture: see the status below.')); return; }
frame.classList.remove('plain');
await showImage(frame, answer, 'png', { alt: `${race.raceName} ${race.season}, bg=satellite`, tile: false, status: st });
} catch (e) {
setStatus(st, 'error', e.message);
} finally {
button.disabled = false;
}
});
return card;
}
function renderSat(p, key, current) {
const sig = `${key}|${frameNow()}`;
const src = satelliteSource(key);
const status = !state.picks.circuits ? 'circuits/photos.json was not read, so what this layout uses now is not known.'
: current && current.use === 'map' ? 'Its entry says "use": "map": bg=satellite draws the dark map for it now.'
: `Its entry does not ask for the map: bg=satellite draws ${src.name} for it now.`;
const head = h('p', { class: 'hint' }, `bg=satellite draws ${src.name} for this layout, and bg=photo does too while it has no picked photo. Judge it below, its trace drawn in white: keep the satellite, or have the service draw the dark map instead. `, h('b', {}, status));
const choices = h('div', { class: 'choices' },
h('button', { type: 'button', 'data-kind': 'satellite', onclick: () => chooseSurface(key, 'satellite') }, 'Keep the satellite (no entry)'),
h('button', { type: 'button', 'data-kind': 'map', onclick: () => chooseSurface(key, 'map') }, 'Use the map instead'));
if (sig === satShown && satMaps.length) {
$('sat').firstChild.replaceWith(head);
$('sat').querySelector('.choices').replaceWith(choices);
markChoices();
return;
}
for (const m of satMaps) m.remove();
satMaps = [];
satShown = sig;
const country = p.country;
const cards = [];
if (NATIONAL[country]) cards.push(mapCard(NATIONAL[country], 'What bg=satellite draws for this country'));
cards.push(mapCard(EOX, NATIONAL[country] ? 'What bg=satellite draws where the national photo has no tiles' : 'What bg=satellite draws here'));
cards.push(serviceCard(p));
$('sat').replaceChildren(head, grid(cards), choices);
markChoices();
traceOf(p).then((pts) => {
if (satShown !== sig) return;
for (const card of cards.filter((c) => c._box)) {
// Whole zoom levels: at a fractional one the browser draws seams between tiles that read as flaws in the imagery.
const m = L.map(card._box, { attributionControl: false, scrollWheelZoom: false });
L.tileLayer(card._src.url, { maxZoom: 19, maxNativeZoom: card._src.maxNativeZoom }).addTo(m);
if (pts) {
const line = L.polyline(pts, { color: '#ffffff', weight: 2, opacity: 0.9 }).addTo(m);
m.fitBounds(line.getBounds(), { padding: [14, 14] });
} else {
m.setView([0, 0], 2);
card._box.after(h('div', { class: 'meta' }, 'This layout has no trace to frame.'));
}
satMaps.push(m);
}
}).catch((err) => {
for (const card of cards.filter((c) => c._box)) card._box.replaceWith(notice('error', `The layout’s trace could not be read: ${err.message}`));
});
}
// ------------------------------------------------------------ rendering a layout or a season
function picksOf(name) {
const file = state.picks[name];
return file ? Object.fromEntries(Object.entries(file).filter(([k]) => !k.startsWith('$'))) : null;
}
function render() {
syncURL();
$('photos-root').className = state.treat === 'bw' ? 'treat-bw' : '';
$('frame-label').hidden = state.mode === 'season';
$('layout-picker').hidden = state.mode !== 'layout';
$('season-picker').hidden = state.mode !== 'season';
// The /circuits call fills the layout picker only.
for (const sel of ['.request', '.status', '.result']) $('choose').querySelector(`:scope > ${sel}`).hidden = state.mode !== 'layout';
for (const [id, v] of [['mode', state.mode], ['treat', state.treat], ['frame', state.frame]]) {
for (const b of $(id).querySelectorAll('button')) b.setAttribute('aria-pressed', String(b.dataset.v === v));
}
if (state.chosen && state.chosen.mode !== state.mode) { state.chosen = null; showEntry(); }
if (!state.candidates) {
$('others-title').hidden = true;
$('others').replaceChildren();
$('cands-title').textContent = 'Candidates';
$('cands').replaceChildren(notice('error', 'The candidates were not read (see 1).'));
return;
}
if (state.mode === 'layout') renderLayout(); else renderSeason();
}
function renderLayout() {
const p = state.pick;
if (!p || !p.layout) return;
const circuitKey = `${p.country}/${p.city}/${p.circuit}`;
const key = `${circuitKey}/${p.layout}`;
const picks = picksOf('circuits');
const list = state.candidates.layouts[key];
const current = picks && picks[key];
if (state.chosen && state.chosen.key !== key) { state.chosen = null; showEntry(); }
$('sat-title').hidden = false;
renderSat(p, key, current);
// The circuit's other layouts, and this one's pick when it has one.
$('others-title').hidden = false;
$('others-title').textContent = `For bg=photo (optional): the picks of ${p.circuitName || 'this circuit'}’s layouts`;
if (!picks) {
$('others').replaceChildren(notice('error', 'circuits/photos.json was not read (see 1), so the picks are not shown.'));
} else {
const cards = p.layouts.filter((l) => picks[`${circuitKey}/${l}`]).map((l) => {
const k = `${circuitKey}/${l}`;
const label = `${layoutYears(l)}${l === p.layout ? ' (this layout, picked now)' : ''}`;
return pickCard(picks[k], label, l === p.layout);
});
$('others').replaceChildren(cards.length ? grid(cards, 'small')
: h('p', { class: 'hint' }, `None of its ${p.layouts.length} layout${p.layouts.length === 1 ? '' : 's'} has a pick yet.`));
}
const undated = ((state.candidates.about || {}).undated_per_circuit || {})[circuitKey];
$('cands-title').textContent = `Candidates for bg=photo (optional), ${layoutYears(p.layout)}${list ? ` (${list.length})` : ''}`;
if (!list) {
$('cands').replaceChildren(notice('error', `The candidates file has no entry for ${key}: run tools/commons_candidates.py again.`));
return;
}
const why = undated ? ` The tool found ${undated} more photo${undated === 1 ? '' : 's'} of this circuit with no date it can read; a layout lists only photos dated within its years.` : '';
if (!list.length) {
$('cands').replaceChildren(notice('', `Commons has no freely licensed aerial photo of this circuit dated ${layoutYears(p.layout)} that the tool found: bg=photo draws what bg=satellite draws for it (above).${why}`));
return;
}
$('cands').replaceChildren(
why ? h('p', { class: 'hint' }, why.trim()) : '',
grid(list.map((c) => photoCard(c, {
picked: current && current.file === c.file,
label: current && current.file === c.file ? 'Picked now' : null,
choose: (card) => choose(key, c, card, 'circuits/photos.json', 'circuits'),
}))));
}
function renderSeason() {
const year = $('season').value;
if (!year) return;
$('sat-title').hidden = true;
$('sat').replaceChildren();
for (const m of satMaps) m.remove();
satMaps = [];
satShown = '';
const picks = picksOf('seasons');
const list = state.candidates.seasons[year] || null;
const current = picks && picks[year];
$('others-title').hidden = false;
$('others-title').textContent = 'Picks of the seasons nearest to it';
if (!picks) {
$('others').replaceChildren(notice('error', 'seasons/photos.json was not read (see 1), so the picks are not shown.'));
} else {
const near = Object.keys(picks).sort((a, b) => Math.abs(a - year) - Math.abs(b - year) || a - b).slice(0, 10);
$('others').replaceChildren(near.length
? grid(near.map((y) => pickCard(picks[y], `${y}${y === year ? ' (this season, picked now)' : ''}`, y === year)), 'small')
: h('p', { class: 'hint' }, 'No season has a pick yet.'));
}
$('cands-title').textContent = `Candidates for ${year}${list ? ` (${list.length})` : ''}`;
if (!list) {
$('cands').replaceChildren(notice('error', `The candidates file has no entry for ${year}: run tools/commons_candidates.py again.`));
return;
}
if (!list.length) {
$('cands').replaceChildren(notice('', `No freely licensed photo in “${year} Formula One season cars” was found; until one is picked, the season poster is drawn without a photo.`));
return;
}
state.chosen = state.chosen && state.chosen.key === year ? state.chosen : null;
$('cands').replaceChildren(h('p', { class: 'hint' }, `From Commons’ “${year} Formula One season cars”, the best ${list.length} by quality marks, size and landscape.`),
grid(list.map((c) => photoCard(c, {
picked: current && current.file === c.file,
label: current && current.file === c.file ? 'Picked now' : null,
choose: (card) => choose(year, c, card, 'seasons/photos.json', 'seasons'),
}))));
if (!state.chosen) showEntry();
}
// ------------------------------------------------------------ controls
function seg(id, key) {
$(id).addEventListener('click', (e) => {
const b = e.target.closest('button');
if (!b) return;
state[key] = b.dataset.v;
render();
if (state.chosen) showEntry();
});
}
seg('mode', 'mode');
seg('treat', 'treat');
seg('frame', 'frame');
$('season').addEventListener('change', () => { state.chosen = null; render(); });
function fillSeasons() {
const years = Object.keys(state.candidates.seasons).sort();
const want = params.get('season') || '2024';
$('season').replaceChildren(...years.map((y) => h('option', { value: y }, `${y} · ${state.candidates.seasons[y].length} candidate${state.candidates.seasons[y].length === 1 ? '' : 's'}`)));
$('season').value = years.includes(want) ? want : years[years.length - 1];
}
render();
readFile('candidates', () => { fillSeasons(); render(); });
readFile('circuits', render);
readFile('seasons', render);
layoutPicker($('layout-picker'), {
treeCard: $('choose'),
sync: true,
onChange: (p) => { state.pick = p; state.chosen = null; render(); },
});
})();
</script>
</body>
</html>
+17 -5
View File
@@ -18,8 +18,12 @@
<a href="map.html">GPS traces</a> <a href="map.html">GPS traces</a>
<a href="grand-prix.html">Grand prix lookup</a> <a href="grand-prix.html">Grand prix lookup</a>
<a href="posters.html" aria-current="page">Posters</a> <a href="posters.html" aria-current="page">Posters</a>
<a href="builder.html">Poster builder</a>
<a href="kometa.html">Kometa</a> <a href="kometa.html">Kometa</a>
<a href="library.html">Library</a> <a href="library.html">Library</a>
<a href="picker.html">Photo picker</a>
<a href="licences.html">Licences</a>
<a href="../guides/index.html">Guides</a>
</nav> </nav>
<div id="api-base"></div> <div id="api-base"></div>
</header> </header>
@@ -44,14 +48,15 @@
<div class="grid-2"> <div class="grid-2">
<section class="card" id="race-poster"> <section class="card" id="race-poster">
<h2>Race poster</h2> <h2>Race poster</h2>
<p><code>/posters/race/{race name}/{season}.png?bg={background}</code>, 1000×1500: the round, the race’s name, the track and its date over a map of the circuit.</p> <p><code>/posters/race/{race name}/{season}.png?bg={background}</code>, 1000×1500: the round, the race’s name, the track and its date over a map of the circuit. Every other option is on the <a href="builder.html">poster builder</a>.</p>
<div class="controls"> <div class="controls">
<label><span>Background (<code>bg</code>)</span> <label><span>Background (<code>bg</code>)</span>
<select id="bg"> <select id="bg">
<option value="aerial">aerial: Esri satellite imagery (the default)</option> <option value="satellite">satellite: the national aerial photo, else EOxCloudless 2025 (the default)</option>
<option value="photo">photo: the layout’s picked Commons photo, else what satellite draws</option>
<option value="osm">osm: OpenStreetMap street map</option> <option value="osm">osm: OpenStreetMap street map</option>
<option value="dark">dark: Esri Dark Gray Canvas</option> <option value="dark">dark: OpenStreetMap, recoloured dark</option>
<option value="light">light: Esri Light Gray Canvas</option> <option value="light">light: OpenStreetMap, recoloured light</option>
<option value="none">none: plain black, no tiles (fastest)</option> <option value="none">none: plain black, no tiles (fastest)</option>
</select> </select>
</label> </label>
@@ -101,7 +106,14 @@
<footer class="pager"> <footer class="pager">
<a rel="prev" href="grand-prix.html">← Grand prix lookup</a> <a rel="prev" href="grand-prix.html">← Grand prix lookup</a>
<a class="home" href="index.html">All examples</a> <a class="home" href="index.html">All examples</a>
<a rel="next" href="kometa.html">Kometa →</a> <a rel="next" href="builder.html">Poster builder →</a>
</footer>
<footer class="disclaimer">
<p>This website is unofficial and is not associated in any way with the Formula 1 companies. F1, FORMULA ONE,
FORMULA 1, FIA FORMULA ONE WORLD CHAMPIONSHIP, GRAND PRIX and related marks are trade marks of Formula One
Licensing B.V.</p>
<p><a href="licences.html">Licences and credits</a>: every source the pictures are made from, the licence each
picture takes from its sources, and the licence of the track files and the GPS traces (MIT).</p>
</footer> </footer>
<script src="site.js"></script> <script src="site.js"></script>
+125
View File
@@ -44,6 +44,9 @@
* { box-sizing: border-box; } * { box-sizing: border-box; }
/* An element hidden by the page stays hidden, whatever display its class gives it. */
[hidden] { display: none !important; }
body { body {
margin: 0; margin: 0;
background: var(--bg); background: var(--bg);
@@ -353,3 +356,125 @@ a.tile-link:hover .tile-frame { outline: 3px solid var(--accent); }
@media (prefers-reduced-motion: reduce) { .spinner { animation-duration: 4s; } } @media (prefers-reduced-motion: reduce) { .spinner { animation-duration: 4s; } }
.waiting { display: flex; gap: 1rem; align-items: center; } .waiting { display: flex; gap: 1rem; align-items: center; }
.waiting p { margin: 0.2rem 0; } .waiting p { margin: 0.2rem 0; }
/* ---- the Formula 1 disclaimer, at the foot of every page ---- */
footer.disclaimer {
max-width: 1200px;
margin: 0 auto;
padding: 0 1.5rem 2.5rem;
font-size: 0.78rem;
color: var(--muted);
}
footer.disclaimer p { margin: 0.3rem 0; max-width: 60rem; }
/* ---- segmented toggles (picker, builder) ---- */
.seg { display: inline-flex; border: 1px solid var(--line); border-radius: 6px; overflow: hidden; }
.seg button { border: none; border-radius: 0; border-right: 1px solid var(--line); }
.seg button:last-child { border-right: none; }
.seg button[aria-pressed="true"] { background: var(--accent); color: var(--accent-text); }
/* ---- photo picker ---- */
.photos { display: grid; gap: 1rem; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); }
.photos.thumb { grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); }
.photo-card {
border: 1px solid var(--line);
border-radius: var(--radius);
padding: 0.5rem;
display: flex;
flex-direction: column;
gap: 0.35rem;
min-width: 0;
background: var(--card);
}
.photo-card.chosen { outline: 3px solid var(--accent); }
.photo-card.picked { border-color: var(--ok); border-width: 2px; }
.photo-frame { background: #000; border-radius: 6px; overflow: hidden; aspect-ratio: 2 / 3; }
.photos.thumb .photo-frame { aspect-ratio: 16 / 9; }
.photo-frame img { width: 100%; height: 100%; object-fit: cover; object-position: center; display: block; }
.treat-bw .photo-frame img { filter: url(#bw); }
.photo-card .name { font-weight: 650; font-size: 0.85rem; line-height: 1.3; overflow-wrap: anywhere; }
.photo-card .meta { font-size: 0.78rem; color: var(--muted); line-height: 1.4; }
.photo-card .meta b { color: var(--text); font-weight: 600; }
.photo-card .tags { display: flex; flex-wrap: wrap; gap: 0.25rem; }
.tag { font-size: 0.7rem; border: 1px solid var(--line); border-radius: 999px; padding: 0.05rem 0.45rem; color: var(--muted); }
.tag.mark { border-color: var(--ok); color: var(--ok); }
.tag.warn { border-color: var(--warn); color: var(--warn); }
.photo-card .actions { display: flex; gap: 0.5rem; align-items: center; margin-top: auto; font-size: 0.8rem; }
.photo-card .actions button { font-size: 0.8rem; padding: 0.2rem 0.6rem; }
.photos.small { grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); }
.copy-block { display: flex; flex-direction: column; gap: 0.35rem; margin: 0.6rem 0; }
.copy-block .head { display: flex; gap: 0.5rem; align-items: center; justify-content: space-between; }
.copy-block .head span { font-size: 0.85rem; color: var(--muted); }
/* ---- poster builder ---- */
.options { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 0.75rem 1.25rem; }
.option { border: 1px solid var(--line); border-radius: 8px; padding: 0.55rem 0.7rem; display: flex; flex-direction: column; gap: 0.35rem; }
.option .opt-head { display: flex; align-items: baseline; justify-content: space-between; gap: 0.5rem; }
.option .opt-head code { font-weight: 700; }
.option .opt-head small { color: var(--muted); font-size: 0.75rem; text-align: right; }
.option .opt-body { display: flex; flex-wrap: wrap; gap: 0.4rem 0.75rem; align-items: center; font-size: 0.88rem; }
.option .opt-body label { display: inline-flex; align-items: center; gap: 0.3rem; }
.option.set { border-color: var(--accent); }
.option select { max-width: 100%; min-width: 0; }
.option .opt-body > select { flex: 1; }
.option input[type="color"] { padding: 0.1rem; width: 3rem; height: 2rem; }
.option input[type="range"] { flex: 1; min-width: 8rem; }
.credits { margin-top: 0.75rem; }
.credits table th { width: 9rem; }
.credits td code { white-space: normal; overflow-wrap: anywhere; }
details.result-raw { margin-top: 0.75rem; }
details.result-raw summary { cursor: pointer; color: var(--muted); font-size: 0.88rem; margin-bottom: 0.5rem; }
table.sources td code { white-space: normal; overflow-wrap: anywhere; }
table.sources th:nth-child(3), table.sources td:nth-child(3) { min-width: 9rem; }
table.sources th:nth-child(4), table.sources td:nth-child(4) { width: 34%; }
.card > div + p.hint { margin-top: 0.75rem; }
/* ---- the picker's satellite frames ---- */
.map-frame { position: relative; background: #111; border-radius: 6px; overflow: hidden; aspect-ratio: 2 / 3; }
.photos.thumb .map-frame { aspect-ratio: 16 / 9; }
.map-frame .map-box { position: absolute; inset: 0; }
.map-frame img { width: 100%; height: 100%; object-fit: cover; display: block; }
.map-frame.plain { display: grid; place-items: center; padding: 0.75rem; text-align: center; color: #c8c8d2; background: #1d1d24; font-size: 0.82rem; }
.photo-card .request.compact { padding: 0.25rem 0.35rem; min-height: 0; gap: 0.3rem; }
.photo-card .request.compact .url { font-size: 0.66rem; }
.photo-card .status { font-size: 0.75rem; margin: 0; }
#sat .choices { margin: 0.75rem 0 0.25rem; }
/* ---- guides (guides/): numbered steps, boxes to copy, example pictures ---- */
ol.steps { padding-left: 1.6rem; max-width: 60rem; }
ol.steps > li { margin: 0.55rem 0; padding-left: 0.2rem; }
ol.steps > li::marker { font-weight: 700; color: var(--accent); }
.see { color: var(--ok); font-weight: 600; }
.copy {
display: flex;
align-items: flex-start;
gap: 0.5rem;
background: var(--code-bg);
border: 1px solid var(--line);
border-radius: 8px;
padding: 0.5rem 0.6rem;
margin: 0.5rem 0;
max-width: 60rem;
}
.copy code { flex: 1; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 0.88rem; }
.copy button { flex: none; font-size: 0.8rem; padding: 0.2rem 0.6rem; }
.examples-row { display: flex; flex-wrap: wrap; gap: 1rem; align-items: flex-start; margin: 0.75rem 0; }
.examples-row figure { margin: 0; }
.examples-row img { display: block; border-radius: 8px; border: 1px solid var(--line); height: 240px; width: auto; }
.examples-row figcaption { font-size: 0.85rem; color: var(--muted); margin-top: 0.3rem; max-width: 22rem; }
.guide-step { max-width: 62rem; }
.guide-step h2 .num { color: var(--accent); }
details.more { margin: 0.6rem 0; max-width: 60rem; }
details.more summary { cursor: pointer; font-weight: 600; }
/* In a guide, an address or file name in a table wraps, so the table fits a phone. */
.guide-step td code { white-space: normal; overflow-wrap: anywhere; }
+11 -5
View File
@@ -182,7 +182,7 @@
return null; return null;
} }
setStatus(statusEl, 'ok', summary); setStatus(statusEl, 'ok', summary);
return { status: res.status, type, blob, ms, size: blob.size, url }; return { status: res.status, type, blob, ms, size: blob.size, url, headers: res.headers };
} }
/** Fetches JSON for a card and shows it in its `.result`; returns the parsed value or null. */ /** Fetches JSON for a card and shows it in its `.result`; returns the parsed value or null. */
@@ -243,10 +243,13 @@
return pre; return pre;
} }
/** What the first bytes of a body are: 'png', 'svg', 'json' or 'unknown'. */ /** What the first bytes of a body are: 'png', 'jpg', 'webp', 'svg', 'json' or 'unknown'. */
async function sniff(blob) { async function sniff(blob) {
const head = new Uint8Array(await blob.slice(0, 256).arrayBuffer()); const head = new Uint8Array(await blob.slice(0, 256).arrayBuffer());
if (head[0] === 0x89 && head[1] === 0x50 && head[2] === 0x4e && head[3] === 0x47) return 'png'; if (head[0] === 0x89 && head[1] === 0x50 && head[2] === 0x4e && head[3] === 0x47) return 'png';
if (head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff) return 'jpg';
const ascii = (from, to) => String.fromCharCode(...head.slice(from, to));
if (ascii(0, 4) === 'RIFF' && ascii(8, 12) === 'WEBP') return 'webp';
const text = new TextDecoder().decode(head).trimStart(); const text = new TextDecoder().decode(head).trimStart();
if (text.startsWith('<?xml') || text.startsWith('<svg')) return 'svg'; if (text.startsWith('<?xml') || text.startsWith('<svg')) return 'svg';
if (text.startsWith('{') || text.startsWith('[')) return 'json'; if (text.startsWith('{') || text.startsWith('[')) return 'json';
@@ -261,9 +264,11 @@
return el._objectURL; return el._objectURL;
} }
const RASTER = { png: 'image/png', jpg: 'image/jpeg', webp: 'image/webp' };
/** /**
* Shows an image answer. `expected` is 'png' or 'svg'; when the body is something else, says so first * Shows an image answer. `expected` is 'png', 'jpg', 'webp' or 'svg'; when the body is something else,
* (loudly) and shows what came back. * says so first (loudly) and shows what came back.
*/ */
async function showImage(el, answer, expected, opts = {}) { async function showImage(el, answer, expected, opts = {}) {
const got = await sniff(answer.blob); const got = await sniff(answer.blob);
@@ -273,7 +278,8 @@
if (opts.status) setStatus(opts.status, 'error', `${opts.status.textContent} — not ${expected.toUpperCase()}`); if (opts.status) setStatus(opts.status, 'error', `${opts.status.textContent} — not ${expected.toUpperCase()}`);
parts.push(notice('error', `Asked for ${expected.toUpperCase()}, but the body is ${got === 'unknown' ? 'not an image this page knows' : `${got === 'svg' ? 'an' : 'a'} ${got.toUpperCase()} document`} (the Content-Type header says ${answer.type}).`)); parts.push(notice('error', `Asked for ${expected.toUpperCase()}, but the body is ${got === 'unknown' ? 'not an image this page knows' : `${got === 'svg' ? 'an' : 'a'} ${got.toUpperCase()} document`} (the Content-Type header says ${answer.type}).`));
if (got === 'svg') blob = new Blob([blob], { type: 'image/svg+xml' }); if (got === 'svg') blob = new Blob([blob], { type: 'image/svg+xml' });
else if (got !== 'png') { el.replaceChildren(...parts); return false; } else if (RASTER[got]) blob = new Blob([blob], { type: RASTER[got] });
else { el.replaceChildren(...parts); return false; }
if (got === 'svg') parts.push(h('p', {}, 'What came back, shown as an SVG:')); if (got === 'svg') parts.push(h('p', {}, 'What came back, shown as an SVG:'));
} else if (expected === 'svg') { } else if (expected === 'svg') {
blob = new Blob([blob], { type: 'image/svg+xml' }); blob = new Blob([blob], { type: 'image/svg+xml' });
+11
View File
@@ -18,8 +18,12 @@
<a href="map.html">GPS traces</a> <a href="map.html">GPS traces</a>
<a href="grand-prix.html">Grand prix lookup</a> <a href="grand-prix.html">Grand prix lookup</a>
<a href="posters.html">Posters</a> <a href="posters.html">Posters</a>
<a href="builder.html">Poster builder</a>
<a href="kometa.html">Kometa</a> <a href="kometa.html">Kometa</a>
<a href="library.html">Library</a> <a href="library.html">Library</a>
<a href="picker.html">Photo picker</a>
<a href="licences.html">Licences</a>
<a href="../guides/index.html">Guides</a>
</nav> </nav>
<div id="api-base"></div> <div id="api-base"></div>
</header> </header>
@@ -80,6 +84,13 @@
<a class="home" href="index.html">All examples</a> <a class="home" href="index.html">All examples</a>
<a rel="next" href="map.html">GPS traces →</a> <a rel="next" href="map.html">GPS traces →</a>
</footer> </footer>
<footer class="disclaimer">
<p>This website is unofficial and is not associated in any way with the Formula 1 companies. F1, FORMULA ONE,
FORMULA 1, FIA FORMULA ONE WORLD CHAMPIONSHIP, GRAND PRIX and related marks are trade marks of Formula One
Licensing B.V.</p>
<p><a href="licences.html">Licences and credits</a>: every source the pictures are made from, the licence each
picture takes from its sources, and the licence of the track files and the GPS traces (MIT).</p>
</footer>
<script src="site.js"></script> <script src="site.js"></script>
<script> <script>
+292
View File
@@ -0,0 +1,292 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Using the posters in Emby · Guides · F1 Circuits</title>
<meta name="description" content="Step by step: give every season, race weekend and session of your Formula 1 library in Emby its poster or thumbnail from F1 Circuits, by hand or as picture files.">
<link rel="icon" href="data:,">
<link rel="stylesheet" href="../examples/site.css">
</head>
<body>
<header class="site">
<a class="brand" href="../examples/index.html">F1 <span>Circuits</span> API</a>
<nav aria-label="Guides">
<a href="index.html">Guides</a>
<a href="plex.html">Plex</a>
<a href="emby.html" aria-current="page">Emby</a>
<a href="../examples/index.html">Examples</a>
</nav>
</header>
<main>
<h1>Using the posters in Emby</h1>
<p class="lead">
Emby can show your Formula 1 library with a poster for every season, a poster for every race weekend and a picture
for every session. This guide shows two ways to put them in: by hand in Emby's own screens, or as picture files
next to your videos.
</p>
<p class="notice info">
Kometa, the helper the <a href="plex.html">Plex guide</a> uses, works only with Plex: it
<a href="https://kometa.wiki/en/latest/config/plex/">cannot run</a> without a Plex Media Server. In Emby you put the
pictures in yourself.
</p>
<h2>What you will get</h2>
<div class="examples-row">
<figure>
<img src="https://f1-circuits.zurag.be/posters/season/2025.png?v=a1&amp;width=400&amp;format=jpg"
alt="The 2025 season poster" loading="lazy">
<figcaption>The show “Season 2025” gets the season poster.</figcaption>
</figure>
<figure>
<img src="https://f1-circuits.zurag.be/posters/race/Qatar%20Grand%20Prix/2025.png?v=a1&amp;width=400&amp;format=jpg"
alt="The 2025 Qatar Grand Prix poster" loading="lazy">
<figcaption>Each race weekend gets its race poster: here round 23, Qatar.</figcaption>
</figure>
<figure>
<img src="https://f1-circuits.zurag.be/posters/session/Qatar%20Grand%20Prix/2025/race.png?v=a1&amp;width=640&amp;format=jpg"
alt="The thumbnail of the race session of the 2025 Qatar Grand Prix" loading="lazy">
<figcaption>Each session gets its thumbnail: here the race.</figcaption>
</figure>
</div>
<h2>What you need</h2>
<ul>
<li>Emby Server, and Emby's web app open in your browser, signed in as an administrator.</li>
<li>Your Formula 1 videos in a library of the type <strong>TV shows</strong>, in folders as step 1 shows.</li>
<li>For the second way: access to the folders your videos are in.</li>
</ul>
<section class="guide-step">
<h2><span class="num">1.</span> How the library is laid out</h2>
<p>Emby calls the levels of a TV library show, season and episode. The pictures fit this layout, the one the
<a href="../examples/library.html">Library page</a> shows:</p>
<ul>
<li>Every Formula 1 season is a <strong>show</strong>, such as <code>Season 2025</code>.</li>
<li>Every race weekend is a <strong>season</strong> of that show, numbered by its round: the Qatar Grand Prix,
round 23, is season 23.</li>
<li>Every session is an <strong>episode</strong> of that season: the race of a sprint weekend is episode 12.</li>
</ul>
<p>Emby reads the numbers from the names of your folders and files, as its
<a href="https://emby.media/support/articles/TV-Naming.html">TV naming page</a> shows. For example:</p>
<pre class="code">Formula 1 ← the library's folder
└── Season 2025 ← a show: the 2025 season
├── Season 1 ← a season of the show: round 1, Australia
│ └── Season 2025 S01E08 Race.mkv ← episode 8: the race
└── Season 23 ← round 23, Qatar, a sprint weekend
├── Season 2025 S23E06 Sprint.mkv
└── Season 2025 S23E12 Race.mkv</pre>
<details class="more">
<summary>Which episode number is which session</summary>
<p>This is how the Library page and the Plex guide number them. A sprint weekend has more sessions, so its numbers
differ:</p>
<table>
<thead><tr><th>Episode</th><th>Standard weekend</th><th>Sprint weekend</th></tr></thead>
<tbody>
<tr><td>1</td><td>Free Practice 1</td><td>Free Practice 1</td></tr>
<tr><td>2</td><td>Free Practice 2</td><td>Pre-Sprint-Qualifying Buildup</td></tr>
<tr><td>3</td><td>Free Practice 3</td><td>Sprint Qualifying</td></tr>
<tr><td>4</td><td>Pre-Qualifying Buildup</td><td>Post-Sprint-Qualifying</td></tr>
<tr><td>5</td><td>Qualifying</td><td>Pre-Sprint Buildup</td></tr>
<tr><td>6</td><td>Post-Qualifying</td><td>Sprint</td></tr>
<tr><td>7</td><td>Pre-Race Buildup</td><td>Post-Sprint</td></tr>
<tr><td>8</td><td>Race</td><td>Pre-Qualifying Buildup</td></tr>
<tr><td>9</td><td>Post-Race</td><td>Qualifying</td></tr>
<tr><td>10</td><td>Highlights</td><td>Post-Qualifying</td></tr>
<tr><td>11</td><td></td><td>Pre-Race Buildup</td></tr>
<tr><td>12</td><td></td><td>Race</td></tr>
<tr><td>13</td><td></td><td>Post-Race</td></tr>
<tr><td>14</td><td></td><td>Highlights</td></tr>
<tr><td>15</td><td></td><td>Bonus Content</td></tr>
</tbody>
</table>
</details>
</section>
<section class="guide-step">
<h2><span class="num">2.</span> Find a picture's address</h2>
<p>Every picture has its own web address. The Library page lists them all:</p>
<ol class="steps">
<li>Open the <a href="../examples/library.html">Library page</a>. When the site has just started, it can take a
few minutes to load.</li>
<li>Click a season, such as 2025. You see its season poster and one poster per race weekend.</li>
<li>Click a race weekend. You see its race poster and one thumbnail per session.</li>
<li>Under each picture is its address, with a <strong>Copy</strong> button and an <strong>Open</strong> button.</li>
</ol>
<table>
<thead><tr><th>In Emby</th><th>Picture</th><th>Its address, for example</th></tr></thead>
<tbody>
<tr><td>The show “Season 2025”</td><td>Season poster</td>
<td><code>https://f1-circuits.zurag.be/posters/season/2025.png?v=a1</code></td></tr>
<tr><td>Season 23 of it (Qatar)</td><td>Race poster</td>
<td><code>https://f1-circuits.zurag.be/posters/race/Qatar%20Grand%20Prix/2025.png?v=a1</code></td></tr>
<tr><td>Episode 12 of season 23 (the race)</td><td>Session thumbnail</td>
<td><code>https://f1-circuits.zurag.be/posters/session/Qatar%20Grand%20Prix/2025/race.png?v=a1</code></td></tr>
</tbody>
</table>
</section>
<section class="guide-step">
<h2><span class="num">3a.</span> The first way: by hand in Emby</h2>
<p>Nothing to install, nothing to save. Do this for the show, then for each race weekend, then for each session you
want a picture on.</p>
<ol class="steps">
<li>Copy the picture's address from the Library page (step 2).</li>
<li>In Emby's web app, open your Formula 1 library and find the show, race weekend or session.</li>
<li>On its picture, click <strong>⋯</strong> and choose <strong>Edit Images</strong>.</li>
<li>On the picture marked <strong>Primary</strong>, click <strong>⋯</strong> and choose
<strong>Set Image from URL</strong>.</li>
<li>Paste the address and confirm.</li>
</ol>
<p class="see">You should see: the Formula 1 picture on the item, in place of the old one.</p>
<p class="hint">A season has over 20 race weekends and over 200 sessions. By hand suits the show and the race
weekends; for every session, the second way with the script at the end of this page is faster.</p>
</section>
<section class="guide-step">
<h2><span class="num">3b.</span> The second way: picture files next to your videos</h2>
<p>Emby reads pictures that sit in your folders under these names (its
<a href="https://emby.media/support/articles/TV-Naming.html">TV naming page</a>, “Series &amp; Season Images” and
“Episode Images”):</p>
<table>
<thead><tr><th>For</th><th>Save the picture as</th><th>In the folder</th></tr></thead>
<tbody>
<tr><td>The show</td><td><code>folder.png</code></td><td>of the show: <code>Season 2025</code></td></tr>
<tr><td>A race weekend</td><td><code>folder.png</code></td><td>of the race weekend: <code>Season 23</code></td></tr>
<tr><td>A session</td><td>the video's name, with <code>-thumb.png</code> in place of its ending:
<code>Season 2025 S23E12 Race-thumb.png</code></td><td>next to the video</td></tr>
</tbody>
</table>
<ol class="steps">
<li>On the Library page (step 2), click <strong>Open</strong> under the picture. It opens on its own.</li>
<li>Right-click the picture and choose <strong>Save Image As</strong> (the words differ a little per browser).</li>
<li>Save it in the folder, under the name, that the table gives.</li>
<li>When the folder has its pictures: in Emby, on the show's picture, click <strong>⋯</strong> and choose
<strong>Refresh Metadata</strong>.</li>
<li>Set <strong>Refresh mode</strong> to <strong>Search for missing metadata</strong>, leave
<strong>Replace existing images</strong> off, and click <strong>Refresh</strong>.</li>
</ol>
<p class="see">You should see: the show, its race weekends and its sessions with the pictures you saved.</p>
<p class="hint">Emby also reads <code>poster.png</code> for a show or race weekend, and
<code>season23-poster.png</code> for round 23 when it sits in the show's folder. It looks for
<code>folder</code> first.</p>
</section>
<section class="guide-step">
<h2><span class="num">4.</span> When the pictures get a new look</h2>
<p>Emby keeps the picture it was given. When the pictures get a new look, they get new addresses (the Library page
always shows the current ones). Put the new ones in the same way: by hand (step 3a), or by saving the files again
and refreshing (step 3b).</p>
<p class="notice">Never switch on <strong>Replace existing images</strong> in Refresh Metadata for this library.
Emby then deletes the item's pictures, your own included, and downloads new ones from the online databases it
uses (<a href="https://emby.media/support/articles/Metadata-manager.html">Emby's metadata manager page</a>).</p>
</section>
<h2>If it doesn't work</h2>
<ul>
<li><strong>A picture you saved does not show.</strong> Check its name and folder against the table in step 3b,
and that it ends in <code>.png</code> or <code>.jpg</code>. Then, on the library itself, click <strong>⋯</strong>
and choose <strong>Scan Library Files</strong>.</li>
<li><strong>A race poster sits on the wrong race weekend.</strong> Emby's season number must be the round: check
the folder's name (<code>Season 23</code>) or the <code>S23</code> in the file names.</li>
<li><strong>A thumbnail sits on the wrong session.</strong> Check the episode numbers against the table in step 1:
a sprint weekend is numbered differently from a standard one.</li>
<li><strong>Your pictures were replaced.</strong> A refresh with <strong>Replace existing images</strong> on does
that. Put them in again (step 3a or 3b).</li>
<li><strong>Set Image from URL does nothing.</strong> Emby fetches the picture from this site itself, so the
computer Emby runs on must reach <code>https://f1-circuits.zurag.be</code>. Open
<a href="https://f1-circuits.zurag.be/posters/season/2025.png?v=a1">a poster</a> in a browser on that computer to
check.</li>
</ul>
<h2>For the technically minded</h2>
<h3>The pictures</h3>
<ul>
<li>Three routes, each a plain <code>GET</code>, no key: <code>/posters/season/{season}.png</code> (1000×1500),
<code>/posters/race/{race name}/{season}.png</code> (1000×1500) and
<code>/posters/session/{race name}/{season}/{session}.png</code> (1920×1080). The sessions are <code>fp1</code>,
<code>fp2</code>, <code>fp3</code>, <code>pre-qualifying</code>, <code>qualifying</code>,
<code>post-qualifying</code>, <code>pre-race</code>, <code>race</code>, <code>post-race</code>,
<code>highlights</code>, <code>pre-sprint-qualifying</code>, <code>sprint-qualifying</code>,
<code>post-sprint-qualifying</code>, <code>pre-sprint</code>, <code>sprint</code>, <code>post-sprint</code> and
<code>bonus</code>.</li>
<li>A race name is Jolpica's, its spaces and other characters encoded: <code>Qatar%20Grand%20Prix</code>,
<code>S%C3%A3o%20Paulo%20Grand%20Prix</code>.</li>
<li>Options as query parameters, such as <code>format=jpg</code> (smaller files; the address keeps its
<code>.png</code>), <code>width=600</code>, <code>style=minimal</code> and <code>bg=photo</code>. Try every option
in the <a href="../examples/builder.html">poster builder</a>; the <a href="https://f1-circuits.zurag.be/docs">API
reference</a> lists them.</li>
<li><code>?v=a1</code> is the address version. An address that carries it is kept by clients for good; it is raised
when the look changes. The <a href="https://f1-circuits.zurag.be/kometa/formula-1-metadata.yml">Kometa file</a>
always carries the current one, and lists every picture's address per season, round and episode number.</li>
</ul>
<h3>A whole season as files, with a script</h3>
<p>For Linux, macOS or a NAS with a shell. It reads the season's addresses from the Kometa file and saves, as JPEG,
<code>folder.jpg</code> in the show's folder, <code>seasonNN-poster.jpg</code> per round next to it, and
<code>&lt;video&gt;-thumb.jpg</code> next to every video whose name carries its round and episode
(<code>S23E12</code> or <code>23x12</code>). Keep one picture per item: delete a <code>.png</code> you saved by hand
for the same item. Then refresh as in step 3b.</p>
<div class="copy"><code>#!/bin/sh
# Usage: f1-emby-art.sh 2025 "/media/Formula 1/Season 2025"
season=$1 show=$2 api=https://f1-circuits.zurag.be opts=format=jpg
# Every address of the season: "round episode address", 0 for the show's or a round's own picture.
list=$(curl -fsS "$api/kometa/formula-1-metadata.yml" | awk -v season="$season" '
/^ "Season [0-9]+":/ { on = index($0, "\"Season " season "\":") &gt; 0; round = ep = 0; next }
!on { next }
/^ [0-9]+:$/ { round = $1 + 0; ep = 0; next }
/^ [0-9]+:$/ { ep = $1 + 0; next }
/url_poster:/ { print round, ep, $2 }')
address() { printf '%s\n' "$list" | awk -v r="$1" -v e="$2" -v o="$opts" '$1 == r &amp;&amp; $2 == e { print $3 "&amp;" o }'; }
curl -fsSo "$show/folder.jpg" "$(address 0 0)"
for round in $(printf '%s\n' "$list" | awk '$1 &gt; 0 &amp;&amp; $2 == 0 { print $1 }'); do
curl -fsSo "$show/$(printf 'season%02d-poster.jpg' "$round")" "$(address "$round" 0)"
done
find "$show" -type f | grep -Ei '\.(mkv|mp4|m4v|ts|avi|mov|webm)$' | while IFS= read -r file; do
set -- $(printf '%s\n' "${file##*/}" | sed -nE -e 's/.*[Ss]([0-9]+)[Ee]([0-9]+).*/\1 \2/p' -e t \
-e 's/^(.*[^0-9])?([0-9]+)x([0-9]+)([^0-9].*)?$/\2 \3/p')
[ $# = 2 ] &amp;&amp; url=$(address "$1" "$2") &amp;&amp; [ -n "$url" ] &amp;&amp; curl -fsSo "${file%.*}-thumb.jpg" "$url"
done</code></div>
<h3>Through Emby's API</h3>
<p>Emby downloads a picture from an address onto an item with
<a href="https://dev.emby.media/reference/RestAPI/RemoteImageService/postItemsByIdRemoteimagesDownload.html"><code>POST
/Items/{Id}/RemoteImages/Download</code></a>, with <code>Type</code> (<code>Primary</code> for the show's, a
season's and an episode's picture) and <code>ImageUrl</code> in the query. It needs an administrator: make an
<a href="https://dev.emby.media/doc/restapi/API-Key-Authentication.html">API key</a> in the server dashboard
(Advanced, Security, Add) and send it in the <code>X-Emby-Token</code> header.</p>
<div class="copy"><code>EMBY=http://localhost:8096/emby
KEY=your-api-key
# The show's Id: search the library for it
curl -fsS -H "X-Emby-Token: $KEY" "$EMBY/Items?IncludeItemTypes=Series&amp;Recursive=true&amp;SearchTerm=Season%202025"
# Its seasons (IndexNumber is the round) and one season's episodes (IndexNumber is the episode)
curl -fsS -H "X-Emby-Token: $KEY" "$EMBY/Shows/$SHOW/Seasons"
curl -fsS -H "X-Emby-Token: $KEY" "$EMBY/Shows/$SHOW/Episodes?SeasonId=$SEASON"
# Round 23's poster onto its season
curl -fsS -X POST -H "X-Emby-Token: $KEY" -G "$EMBY/Items/$SEASON/RemoteImages/Download" \
--data-urlencode Type=Primary \
--data-urlencode "ImageUrl=https://f1-circuits.zurag.be/posters/race/Qatar%20Grand%20Prix/2025.png?v=a1&amp;format=jpg"</code></div>
<p>Emby keeps the copy it downloaded. When the address version is raised, call it again with the new address.</p>
</main>
<footer class="pager">
<a rel="prev" href="plex.html">← Plex</a>
<span class="home"></span>
<a rel="next" href="index.html">Guides →</a>
</footer>
<footer class="disclaimer">
<p>This website is unofficial and is not associated in any way with the Formula 1 companies. F1, FORMULA ONE,
FORMULA 1, FIA FORMULA ONE WORLD CHAMPIONSHIP, GRAND PRIX and related marks are trade marks of Formula One
Licensing B.V.</p>
<p><a href="../examples/licences.html">Licences and credits</a>: every source the pictures are made from, the licence each
picture takes from its sources, and the licence of the track files and the GPS traces (MIT).</p>
</footer>
<script src="guides.js"></script>
</body>
</html>
+35
View File
@@ -0,0 +1,35 @@
/*
* The guides' one behaviour: a Copy button on every box of text to copy (`.copy`), copying the text of its
* `code` element. Without the script the text stays selectable by hand.
*/
(function () {
'use strict';
async function copy(text, button) {
let done = false;
try {
await navigator.clipboard.writeText(text);
done = true;
} catch {
const area = document.createElement('textarea');
area.value = text;
area.style.cssText = 'position:fixed;opacity:0';
document.body.append(area);
area.select();
try { done = document.execCommand('copy'); } catch { done = false; }
area.remove();
}
button.textContent = done ? 'Copied' : 'Select it and copy';
setTimeout(() => { button.textContent = 'Copy'; }, 1500);
}
for (const box of document.querySelectorAll('.copy')) {
const code = box.querySelector('code');
if (!code) continue;
const button = document.createElement('button');
button.type = 'button';
button.textContent = 'Copy';
button.addEventListener('click', () => copy(code.textContent, button));
box.append(button);
}
})();
+78
View File
@@ -0,0 +1,78 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Guides · F1 Circuits</title>
<meta name="description" content="Step-by-step guides to show the F1 Circuits posters and thumbnails in your Formula 1 library in Plex or Emby.">
<link rel="icon" href="data:,">
<link rel="stylesheet" href="../examples/site.css">
</head>
<body>
<header class="site">
<a class="brand" href="../examples/index.html">F1 <span>Circuits</span> API</a>
<nav aria-label="Guides">
<a href="index.html" aria-current="page">Guides</a>
<a href="plex.html">Plex</a>
<a href="emby.html">Emby</a>
<a href="../examples/index.html">Examples</a>
</nav>
</header>
<main>
<h1>Guides</h1>
<p class="lead">
Give your Formula 1 library a poster for every season, a poster for every race weekend and a picture for every
session. These guides take you through it one step at a time. Pick the media server you use.
</p>
<div class="examples-row">
<figure>
<img src="https://f1-circuits.zurag.be/posters/season/2025.png?v=a1&amp;width=400&amp;format=jpg"
alt="The 2025 season poster" loading="lazy">
<figcaption>A season: the year over a photo of that season's cars.</figcaption>
</figure>
<figure>
<img src="https://f1-circuits.zurag.be/posters/race/Qatar%20Grand%20Prix/2025.png?v=a1&amp;width=400&amp;format=jpg"
alt="The 2025 Qatar Grand Prix poster" loading="lazy">
<figcaption>A race weekend: its round, name, date and track over its circuit.</figcaption>
</figure>
<figure>
<img src="https://f1-circuits.zurag.be/posters/session/Qatar%20Grand%20Prix/2025/race.png?v=a1&amp;width=640&amp;format=jpg"
alt="The thumbnail of the race session of the 2025 Qatar Grand Prix" loading="lazy">
<figcaption>A session: the race, a qualifying or a practice, over the circuit.</figcaption>
</figure>
</div>
<div class="pages">
<a class="page" href="plex.html">
<h3>Plex</h3>
<p>A free helper called Kometa puts every picture in your Plex library and keeps them up to date. You set it up
once.</p>
</a>
<a class="page" href="emby.html">
<h3>Emby</h3>
<p>Set the pictures by hand in Emby's own screens, or save them as picture files next to your videos.</p>
</a>
</div>
<p>
Every picture carries, at its bottom, the credit of the photo or map it is made from, and takes its licence from
them; the <a href="../examples/licences.html">licences page</a> lists every source and its licence.
</p>
</main>
<footer class="pager">
<a rel="prev" href="../examples/index.html">← Examples</a>
<span class="home"></span>
<a rel="next" href="plex.html">Plex →</a>
</footer>
<footer class="disclaimer">
<p>This website is unofficial and is not associated in any way with the Formula 1 companies. F1, FORMULA ONE,
FORMULA 1, FIA FORMULA ONE WORLD CHAMPIONSHIP, GRAND PRIX and related marks are trade marks of Formula One
Licensing B.V.</p>
<p><a href="../examples/licences.html">Licences and credits</a>: every source the pictures are made from, the licence each
picture takes from its sources, and the licence of the track files and the GPS traces (MIT).</p>
</footer>
</body>
</html>
+260
View File
@@ -0,0 +1,260 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Using the posters in Plex · Guides · F1 Circuits</title>
<meta name="description" content="Step by step: give every season, race weekend and session of your Formula 1 library in Plex its poster or thumbnail, set by Kometa from the F1 Circuits file.">
<link rel="icon" href="data:,">
<link rel="stylesheet" href="../examples/site.css">
</head>
<body>
<header class="site">
<a class="brand" href="../examples/index.html">F1 <span>Circuits</span> API</a>
<nav aria-label="Guides">
<a href="index.html">Guides</a>
<a href="plex.html" aria-current="page">Plex</a>
<a href="emby.html">Emby</a>
<a href="../examples/index.html">Examples</a>
</nav>
</header>
<main>
<h1>Using the posters in Plex</h1>
<p class="lead">
Plex can show your Formula 1 library with a poster for every season, a poster for every race weekend and a picture
for every session. A free helper called <a href="https://kometa.wiki/">Kometa</a> puts them there for you, and
keeps them up to date. This guide takes you through it one step at a time.
</p>
<h2>What you will get</h2>
<div class="examples-row">
<figure>
<img src="https://f1-circuits.zurag.be/posters/season/2025.png?v=a1&amp;width=400&amp;format=jpg"
alt="The 2025 season poster" loading="lazy">
<figcaption>The show “Season 2025” gets the season poster.</figcaption>
</figure>
<figure>
<img src="https://f1-circuits.zurag.be/posters/race/Qatar%20Grand%20Prix/2025.png?v=a1&amp;width=400&amp;format=jpg"
alt="The 2025 Qatar Grand Prix poster" loading="lazy">
<figcaption>Each race weekend gets its race poster: here round 23, Qatar.</figcaption>
</figure>
<figure>
<img src="https://f1-circuits.zurag.be/posters/session/Qatar%20Grand%20Prix/2025/race.png?v=a1&amp;width=640&amp;format=jpg"
alt="The thumbnail of the race session of the 2025 Qatar Grand Prix" loading="lazy">
<figcaption>Each session gets its thumbnail: here the race.</figcaption>
</figure>
</div>
<p>The <a href="../examples/library.html">Library page</a> shows a whole library this way, season by season.</p>
<h2>What you need</h2>
<ul>
<li>Plex Media Server, and the Plex Web App open in your browser.</li>
<li>Your Formula 1 videos, in folders as step 1 shows.</li>
<li>A computer to run Kometa on. It can be the computer Plex runs on. Kometa has no window of its own: you set it
up by filling in one text file and starting it with one command.</li>
<li>A free account at <a href="https://www.themoviedb.org/">The Movie Database</a> (TMDb). Kometa always asks for
its key, even though this guide does not use it.</li>
</ul>
<section class="guide-step">
<h2><span class="num">1.</span> Put your videos in folders</h2>
<p>Kometa's <a href="https://kometa.wiki/en/latest/kometa/guides/formula/">Formula 1 guide</a> shapes the library
like this. Plex calls the levels show, season and episode:</p>
<ul>
<li>Every Formula 1 season is a <strong>show</strong>, in a folder named <code>Season 2025</code>. Keep that name:
the pictures are matched to the show by it.</li>
<li>Every race weekend is a <strong>season</strong> of that show, in a folder that starts with its round:
<code>23 - Qatar GP</code>. Plex numbers it by the round.</li>
<li>Every session is an <strong>episode</strong>: one file, named with the round, the episode number and the
session, such as <code>23x12 - Qatar GP - Race Session.mkv</code>.</li>
</ul>
<pre class="code">Formula 1 ← the library's folder
└── Season 2025 ← a show: the 2025 season
├── 01 - Australian GP ← a season of the show: round 1
│ ├── 01x01 - Australian GP - Free Practice 1.mkv
│ ├── 01x05 - Australian GP - Qualifying Session.mkv
│ └── 01x08 - Australian GP - Race Session.mkv
└── 23 - Qatar GP ← round 23, a sprint weekend
├── 23x06 - Qatar GP - Sprint Race Session.mkv
└── 23x12 - Qatar GP - Race Session.mkv</pre>
<details class="more">
<summary>Which episode number is which session</summary>
<p>The pictures go to the episodes by their number. A sprint weekend has more sessions, so its numbers differ:</p>
<table>
<thead><tr><th>Episode</th><th>Standard weekend</th><th>Sprint weekend</th></tr></thead>
<tbody>
<tr><td>1</td><td>Free Practice 1</td><td>Free Practice 1</td></tr>
<tr><td>2</td><td>Free Practice 2</td><td>Pre-Sprint-Qualifying Buildup</td></tr>
<tr><td>3</td><td>Free Practice 3</td><td>Sprint Qualifying</td></tr>
<tr><td>4</td><td>Pre-Qualifying Buildup</td><td>Post-Sprint-Qualifying</td></tr>
<tr><td>5</td><td>Qualifying</td><td>Pre-Sprint Buildup</td></tr>
<tr><td>6</td><td>Post-Qualifying</td><td>Sprint</td></tr>
<tr><td>7</td><td>Pre-Race Buildup</td><td>Post-Sprint</td></tr>
<tr><td>8</td><td>Race</td><td>Pre-Qualifying Buildup</td></tr>
<tr><td>9</td><td>Post-Race</td><td>Qualifying</td></tr>
<tr><td>10</td><td>Highlights</td><td>Post-Qualifying</td></tr>
<tr><td>11</td><td></td><td>Pre-Race Buildup</td></tr>
<tr><td>12</td><td></td><td>Race</td></tr>
<tr><td>13</td><td></td><td>Post-Race</td></tr>
<tr><td>14</td><td></td><td>Highlights</td></tr>
<tr><td>15</td><td></td><td>Bonus Content</td></tr>
</tbody>
</table>
</details>
</section>
<section class="guide-step">
<h2><span class="num">2.</span> Make the Formula 1 library in Plex</h2>
<p>The library needs Plex's <em>Personal Media Shows</em> agent. An agent is the part of Plex that looks up titles
and pictures; this one does not look your videos up on the internet, which suits recordings no online database
lists. Since Plex Media Server 1.43.0, Plex hides it when you make a new library unless one setting is on.</p>
<ol class="steps">
<li>In the Plex Web App, open <strong>Settings</strong> and choose your server.</li>
<li>Choose <strong>Library</strong>, turn on <strong>Show Legacy Agent during library set up</strong>, and save
the change. (An older Plex Media Server does not have this setting and shows the agent anyway.)</li>
<li>Under <strong>Manage</strong>, choose <strong>Libraries</strong>, then <strong>Add Library</strong>.</li>
<li>Choose <strong>TV Shows</strong> and name the library, for example <code>Formula 1</code>. Note the exact
name: you will type it in step 4.</li>
<li>Add the folder that holds your season folders (<code>Formula 1</code> in the example above).</li>
<li>Choose <strong>Advanced</strong>, and under <strong>Agent</strong> choose
<strong>Personal Media Shows (Legacy)</strong>.</li>
<li>Finish adding the library.</li>
</ol>
<p class="see">You should see: one show per season folder, such as “Season 2025”, and inside it one season per race
weekend.</p>
<p class="hint">Already have a Formula 1 library with another agent? Plex's
<a href="https://support.plex.tv/articles/200241558-agents/">page on agents</a> shows how to change it, and says
the change applies only to videos added after it.</p>
</section>
<section class="guide-step">
<h2><span class="num">3.</span> Install Kometa</h2>
<ol class="steps">
<li>Open Kometa's <a href="https://kometa.wiki/en/latest/kometa/install/">installation walkthrough</a> and choose
the computer you will run it on. Kometa recommends its Docker version unless you already use Python.</li>
<li>Follow it until it asks for three things, and gather them as it says:
<ul>
<li><strong>Your Plex address</strong>: the address that computer uses to reach Plex directly, such as
<code>http://192.0.2.10:32400</code>. Not app.plex.tv.</li>
<li><strong>Your Plex token</strong>, a password for programs: in the Plex Web App, open any video's
<strong>⋯</strong> menu, choose <strong>Get Info</strong>, then the <strong>XML</strong> link at the bottom
(<a href="https://support.plex.tv/articles/204059436-finding-an-authentication-token-x-plex-token/">Plex's
page</a>). The token is the part after <code>X-Plex-Token=</code> in the address of the page that opens.</li>
<li><strong>Your TMDb key</strong>: sign in at themoviedb.org, open <strong>Settings</strong> from your account
menu, choose <strong>API</strong> and request a key. If it shows two keys, use the v3 one.</li>
</ul>
</li>
<li>Make the file <code>config.yml</code> as the walkthrough shows, with your Plex address, Plex token and TMDb
key in it. Then come back here for its <code>libraries</code> part.</li>
</ol>
</section>
<section class="guide-step">
<h2><span class="num">4.</span> Point Kometa at the Formula 1 file</h2>
<p>One file on this site tells Kometa which picture goes on which season, race weekend and session, for every
season from 1950 on.</p>
<ol class="steps">
<li>Open <code>config.yml</code> in a plain text editor, such as Notepad on Windows or TextEdit on a Mac.</li>
<li>Replace its <code>libraries:</code> part with the lines below. If it already lists libraries of your own,
keep them and add the <code>Formula 1:</code> lines under them.
<div class="copy"><code>libraries:
Formula 1:
metadata_files:
- url: https://f1-circuits.zurag.be/kometa/formula-1-metadata.yml</code></div>
</li>
<li>Change <code>Formula 1</code> to your library's exact name in Plex, if you named it otherwise.</li>
<li>Keep the spaces at the start of each line as shown: two per level. Kometa reads the levels from them.</li>
<li>Save the file. The <code>plex:</code> and <code>tmdb:</code> parts stay as you filled them in.</li>
</ol>
</section>
<section class="guide-step">
<h2><span class="num">5.</span> Run Kometa once</h2>
<p>Type the command for the way you installed Kometa, in the window the walkthrough had you use:</p>
<ul>
<li>Kometa with Python, from its folder:
<div class="copy"><code>uv run python kometa.py --run</code></div></li>
<li>Kometa with Docker (put the full path of the folder that holds <code>config.yml</code> in place of
<code>FULL_PATH_TO_CONFIG</code>):
<div class="copy"><code>docker run --rm -it -v "FULL_PATH_TO_CONFIG:/config:rw" kometateam/kometa --run</code></div></li>
<li>Kometa with Docker Compose, from the folder that holds <code>compose.yml</code>:
<div class="copy"><code>docker compose run --rm kometa --run</code></div></li>
</ul>
<p>Kometa writes what it does as it goes. Let it finish: the first time it sets a picture on every season, race
weekend and session it finds, so it takes a while.</p>
<p class="see">You should see: Kometa connect to TMDb and to Plex, work through your Formula 1 library, and end. In
Plex, after reloading the page, every season, race weekend and session has its picture.</p>
</section>
<section class="guide-step">
<h2><span class="num">6.</span> Keep it up to date</h2>
<p>Leave Kometa running in its normal way, without <code>--run</code>: the part “Scheduling and updates” of the
<a href="https://kometa.wiki/en/latest/kometa/install/">walkthrough</a> shows how for your installation. Then it
runs by itself once a day, at 05:00 unless you change it. Each time it reads the Formula 1 file again, so a new
race weekend gets its pictures.</p>
<p>When the pictures get a new look, the file names new addresses for them, and Kometa puts the new pictures in on
its next run. A picture it has already put in is not sent again. To get a new look at once, run step 5 again.</p>
</section>
<h2>If it doesn't work</h2>
<ul>
<li><strong>Nothing changed in Plex.</strong> Open the newest <code>meta.log</code> in the <code>logs</code> folder
next to <code>config.yml</code>, and read the lines marked CRITICAL, then ERROR.</li>
<li><strong>Kometa does not work on the library.</strong> The name under <code>libraries:</code> must be the
library's name in Plex, letter for letter.</li>
<li><strong>A season gets no pictures.</strong> Its show must be called exactly <code>Season 2025</code> (with its
own year) in Plex.</li>
<li><strong>A race poster sits on the wrong race weekend.</strong> In Plex, each race weekend's season number must be
its round. Check the number at the start of its folder.</li>
<li><strong>A thumbnail sits on the wrong session.</strong> Check the episode numbers against the table in step 1:
a sprint weekend is numbered differently from a standard one.</li>
<li><strong>Pictures stay empty.</strong> Plex fetches every picture from this site, so the computer Plex runs on
must reach <code>https://f1-circuits.zurag.be</code>. Open
<a href="https://f1-circuits.zurag.be/posters/season/2025.png?v=a1">a poster</a> in a browser on that computer to
check.</li>
<li>Kometa's own <a href="https://kometa.wiki/en/latest/kometa/help/">help page</a> explains its messages.</li>
</ul>
<h2>For the technically minded</h2>
<ul>
<li>The file is <a href="https://f1-circuits.zurag.be/kometa/formula-1-metadata.yml">/kometa/formula-1-metadata.yml</a>,
a Kometa metadata file, explained on the <a href="../examples/kometa.html">Kometa page</a>. Per show
(<code>"Season 2025"</code>) it sets <code>f1_season</code>, <code>round_prefix</code>, <code>shorten_gp</code>
and the season poster as <code>url_poster</code>; per season of the show (a round) the race poster; per episode
the session thumbnail. It covers every season from 1950 to next year; Kometa skips what the library does not
hold. The first request after the service starts can take minutes: it reads every season's schedule from
Jolpica.</li>
<li>Every address in it carries the address version, <code>?v=a1</code>. Such an address is kept by clients for
good; the version is raised when the look changes, which gives every picture a new address. Kometa (with its
cache on, the default) sets a poster only when its address differs from the one it set last, so the raise is
what brings a new look in.</li>
<li>The pictures are three routes, each a plain <code>GET</code>:
<code>/posters/season/{season}.png</code>, <code>/posters/race/{race name}/{season}.png</code> and
<code>/posters/session/{race name}/{season}/{session}.png</code>. A race name is Jolpica's, with its spaces and
other characters encoded: <code>Qatar%20Grand%20Prix</code>, <code>S%C3%A3o%20Paulo%20Grand%20Prix</code>.</li>
<li>They take options such as <code>style=minimal</code>, <code>bg=photo</code>, <code>width=600</code> and
<code>format=jpg</code>. Try every option in the <a href="../examples/builder.html">poster builder</a>; all of
them are listed in the <a href="https://f1-circuits.zurag.be/docs">API reference</a>. The file uses the default
look. For another look, save a copy of the file, add your options to its addresses, and give Kometa that copy
with a <code>- file:</code> line in place of the <code>- url:</code> line
(<a href="https://kometa.wiki/en/latest/config/files/">Kometa's page on files</a>); your copy then no longer
takes in new races by itself.</li>
</ul>
</main>
<footer class="pager">
<a rel="prev" href="index.html">← Guides</a>
<span class="home"></span>
<a rel="next" href="emby.html">Emby →</a>
</footer>
<footer class="disclaimer">
<p>This website is unofficial and is not associated in any way with the Formula 1 companies. F1, FORMULA ONE,
FORMULA 1, FIA FORMULA ONE WORLD CHAMPIONSHIP, GRAND PRIX and related marks are trade marks of Formula One
Licensing B.V.</p>
<p><a href="../examples/licences.html">Licences and credits</a>: every source the pictures are made from, the licence each
picture takes from its sources, and the licence of the track files and the GPS traces (MIT).</p>
</footer>
<script src="guides.js"></script>
</body>
</html>
+5 -3
View File
@@ -10,15 +10,17 @@
# What the image ships, compiled before the merge: every Python file the service's image copies, and the # What the image ships, compiled before the merge: every Python file the service's image copies, and the
# models it imports. Then the tests in tests/, which need the standard library only: every circuit in # models it imports. Then the tests in tests/, which need the standard library only: every circuit in
# circuits/circuits.json carries one unique ergastId, and a race's circuit resolves by that id, never by # circuits/circuits.json carries one unique ergastId, and a race's circuit resolves by that id, never by
# its name; a failed Jolpica fetch is never kept, a season that is over is read from disk, a throttled # its name; every layout a race from 2020 on draws has a traced line, never a point; a failed Jolpica
# request is asked again. # fetch is never kept, a season that is over is read from disk, a throttled request is asked again; a poster's options, keys, cache headers and store cap, its satellite source, credits and
# licence (poster_options.py and poster_sources.py, standard library only).
# #
# **Said, never passed silently**: the service's dependencies (service/requirements.txt) are the image's to # **Said, never passed silently**: the service's dependencies (service/requirements.txt) are the image's to
# install, so the service is not started. # install, so the service is not started.
set -eu set -eu
# Parsed, not compiled to files: a check leaves the tree as it found it. # Parsed, not compiled to files: a check leaves the tree as it found it.
find cdn-api.py access_log.py circuits_service.py ergast_service.py posters_service.py models -name '*.py' -print0 | find cdn-api.py access_log.py app_info.py circuits_service.py ergast_service.py posters_service.py poster_options.py \
poster_sources.py models -name '*.py' -print0 |
xargs -0 python3 -c 'import ast, sys xargs -0 python3 -c 'import ast, sys
for f in sys.argv[1:]: for f in sys.argv[1:]:
ast.parse(open(f, encoding="utf-8").read(), f) ast.parse(open(f, encoding="utf-8").read(), f)
+2 -2
View File
@@ -1,8 +1,6 @@
from dataclasses import dataclass from dataclasses import dataclass
from typing import List, Dict, Any from typing import List, Dict, Any
import numpy as np
@dataclass @dataclass
class GeoJSONGeometry: class GeoJSONGeometry:
@@ -18,6 +16,8 @@ class GeoJSONGeometry:
def find_longest_straight(self, window_size=5) -> (List[float], List[float]): def find_longest_straight(self, window_size=5) -> (List[float], List[float]):
"""Find the longest approximately straight section of the track, including wrap-around.""" """Find the longest approximately straight section of the track, including wrap-around."""
import numpy as np # only here: the models themselves load with the standard library (the service's tests)
max_distance = 0 max_distance = 0
best_start_idx = 0 best_start_idx = 0
n = len(self.coordinates) n = len(self.coordinates)
+27 -3
View File
@@ -23,7 +23,7 @@
"port": 8000, "port": 8000,
"protocol": "tcp", "protocol": "tcp",
"from": "mesh", "from": "mesh",
"why": "the track-layout CDN, the race posters and the Kometa metadata over http; its public name is a route grant and the proxy reaches it here. Kometa fetches the metadata and every poster by that public name" "why": "the track-layout CDN, the race posters, their licences and the Kometa metadata over http; its public name is a route grant and the proxy reaches it here. Kometa fetches the metadata and every poster by that public name"
} }
], ],
"data": { "data": {
@@ -32,7 +32,19 @@
"id": "cache", "id": "cache",
"path": "${dir:cache}", "path": "${dir:cache}",
"class": "cache", "class": "cache",
"why": "the generated track layouts and posters, rebuilt on demand" "why": "the race schedules asked from Jolpica, asked again when lost"
},
{
"id": "layers",
"path": "${dir:layers}",
"class": "rebuildable",
"why": "the kept layers of the posters: the map pictures, picked photos, world locators and track outlines, fetched once and kept for good; fetched again if lost"
},
{
"id": "posters",
"path": "${dir:posters}",
"class": "cache",
"why": "the finished posters and thumbnails, at most 2 GB, drawn again from the layers on demand"
} }
] ]
}, },
@@ -48,6 +60,16 @@
"type": "directory", "type": "directory",
"mode": "0700" "mode": "0700"
}, },
{
"id": "layers",
"type": "directory",
"mode": "0700"
},
{
"id": "posters",
"type": "directory",
"mode": "0700"
},
{ {
"id": "site-env", "id": "site-env",
"type": "file", "type": "file",
@@ -67,7 +89,9 @@
"${dir:state}/site.env" "${dir:state}/site.env"
], ],
"volumes": [ "volumes": [
"${dir:cache}:/app/cache" "${dir:cache}:/app/cache",
"${dir:layers}:/app/layers",
"${dir:posters}:/app/posters"
], ],
"restart-on": [ "restart-on": [
"site-env" "site-env"
+231
View File
@@ -0,0 +1,231 @@
"""What a caller may choose on a poster, a season poster or a session thumbnail, how a choice is checked, and the
keys pictures are kept under (docs/posters.md, Options, Layers and Finished images). Standard library only, so the
merge check tests it as it is.
"""
import hashlib
import math
import re
from dataclasses import dataclass
from typing import Iterable, Optional
# Part of every layer's and every finished picture's key: raised only when the drawing itself changes, so no
# picture made before is served again. r3: licensed sources, kept layers, options and credits.
RENDER_VERSION = "r3"
# Carried by the address clients are given (?v=), separate from RENDER_VERSION: raised when a look changes, so clients
# load the address again, served from the pictures already kept. a1: every season poster changed (the season photos).
ADDRESS_VERSION = "a1"
# A frame is the picture's own size: a poster (race and season) and a session thumbnail.
FRAMES = {"poster": (1000, 1500), "thumb": (1920, 1080)}
FRAME_OF = {"race": "poster", "season": "poster", "session": "thumb"}
SHOW_ITEMS = ("wordmark", "round", "name", "subtitle", "date", "circuit", "locality", "session")
BACKGROUNDS = ("satellite", "photo", "osm", "dark", "light", "none") # photo is never a style's default
BG_ALIASES = {"aerial": "satellite"} # kept for addresses already in use
PHOTO_TREATMENTS = ("bw", "natural")
FORMATS = {"png": "image/png", "jpg": "image/jpeg", "webp": "image/webp"}
STYLES = ("classic", "minimal")
ON_OFF = {"on": True, "off": False}
TRACK_WIDTHS = (1, 30)
MIN_WIDTH = 400 # the full credit line stays readable
# The accent the classic and minimal styles give the wordmark: F1 red. One place, mirrored by the picker page.
DEFAULT_ACCENT = "#dc1220"
DEFAULT_TRACK = ("#ffffff", 6)
# The style's values per kind of picture. classic is how each picture looked before options existed (a thumb had
# no checker and no locator); dim is the darkening behind the track, and its shape per kind keeps its proportions.
PRESETS = {
"classic": {
"race": {"show": ("wordmark", "round", "name", "subtitle", "date"), "checker": True, "locator": True, "dim": 0.43},
"season": {"show": ("wordmark", "name", "subtitle"), "checker": True, "locator": True, "dim": 0.24},
"session": {"show": ("wordmark", "round", "name", "subtitle", "session"), "checker": False, "locator": False,
"dim": 0.55},
},
"minimal": {
"race": {"show": ("name", "date"), "checker": False, "locator": False, "dim": 0.25},
"season": {"show": ("name", "date"), "checker": False, "locator": False, "dim": 0.25},
"session": {"show": ("name", "session"), "checker": False, "locator": False, "dim": 0.25},
},
}
# The dim each kind's darkening was drawn for: the shape is scaled by dim / CLASSIC_DIM[kind].
CLASSIC_DIM = {kind: values["dim"] for kind, values in PRESETS["classic"].items()}
OPTION_NAMES = ("style", "bg", "photo", "show", "locator", "checker", "track", "dim", "accent", "width", "format", "v")
_COLOUR = re.compile(r"^#[0-9a-fA-F]{6}$")
class OptionError(ValueError):
"""An unknown option or value: answered 422, naming it."""
@dataclass(frozen=True)
class Options:
style: str
bg: str
photo: str
show: frozenset
locator: bool
checker: bool
track: Optional[tuple[str, int]] # None: off
dim: float
accent: str
width: int
format: str
versioned: bool # the address carries the current address version (?v=)
def canonical(self) -> str:
"""The options as they are drawn, the style resolved: two addresses that draw the same picture match."""
track = f"{self.track[0]},{self.track[1]}" if self.track else "off"
return (f"bg={self.bg};photo={self.photo};show={','.join(sorted(self.show))};"
f"locator={'on' if self.locator else 'off'};checker={'on' if self.checker else 'off'};"
f"track={track};dim={self.dim:g};accent={self.accent};width={self.width};format={self.format}")
def _choice(name: str, value: str, allowed: Iterable[str]) -> str:
if value not in allowed:
raise OptionError(f"unknown value {value!r} for option {name!r}; it takes {', '.join(allowed)}")
return value
def _colour(name: str, value: str) -> str:
if not _COLOUR.match(value):
raise OptionError(f"unknown value {value!r} for option {name!r}; it takes a colour #rrggbb")
return value.lower()
def parse_options(items: Iterable[tuple[str, str]], kind: str) -> Options:
"""The query of a picture's address, checked: kind is race, season or session. Any option given overrides the
style's preset; an unknown option, a repeated one or an unknown value raises OptionError."""
given: dict[str, str] = {}
for name, value in items:
if name not in OPTION_NAMES:
raise OptionError(f"unknown option {name!r}; options are {', '.join(OPTION_NAMES)}")
if name in given:
raise OptionError(f"option {name!r} given more than once")
given[name] = value
style = _choice("style", given.get("style", "classic"), STYLES)
preset = PRESETS[style][kind]
frame_width = FRAMES[FRAME_OF[kind]][0]
bg = given.get("bg", "satellite")
bg = _choice("bg", BG_ALIASES.get(bg, bg), BACKGROUNDS + tuple(BG_ALIASES))
photo = _choice("photo", given.get("photo", "natural"), PHOTO_TREATMENTS)
if "show" in given:
show = frozenset(item for item in given["show"].split(",") if item)
unknown = sorted(show - set(SHOW_ITEMS))
if unknown:
raise OptionError(f"unknown value {unknown[0]!r} for option 'show'; it takes a comma list of "
f"{', '.join(SHOW_ITEMS)}")
else:
show = frozenset(preset["show"])
locator = ON_OFF[_choice("locator", given["locator"], ON_OFF)] if "locator" in given else preset["locator"]
checker = ON_OFF[_choice("checker", given["checker"], ON_OFF)] if "checker" in given else preset["checker"]
track: Optional[tuple[str, int]] = DEFAULT_TRACK
if "track" in given:
if given["track"] == "off":
track = None
else:
colour, _, width = given["track"].partition(",")
colour = _colour("track", colour)
if width:
if not width.isdigit() or not TRACK_WIDTHS[0] <= int(width) <= TRACK_WIDTHS[1]:
raise OptionError(f"unknown value {given['track']!r} for option 'track'; it takes off or "
f"#rrggbb with an optional width {TRACK_WIDTHS[0]} to {TRACK_WIDTHS[1]}, #ffffff,6")
track = (colour, int(width))
else:
track = (colour, DEFAULT_TRACK[1])
dim = preset["dim"]
if "dim" in given:
try:
dim = float(given["dim"])
except ValueError:
dim = math.nan
if not 0 <= dim <= 1: # also refuses nan
raise OptionError(f"unknown value {given['dim']!r} for option 'dim'; it takes a number from 0 to 1")
accent = _colour("accent", given["accent"]) if "accent" in given else DEFAULT_ACCENT
width = frame_width
if "width" in given:
if not given["width"].isdigit() or not MIN_WIDTH <= int(given["width"]) <= frame_width:
raise OptionError(f"unknown value {given['width']!r} for option 'width'; it takes {MIN_WIDTH} up to "
f"{frame_width}")
width = int(given["width"])
fmt = _choice("format", given.get("format", "png"), tuple(FORMATS))
return Options(style=style, bg=bg, photo=photo, show=show, locator=locator, checker=checker, track=track,
dim=dim, accent=accent, width=width, format=fmt, versioned=given.get("v") == ADDRESS_VERSION)
# ------------------------------------------------------------------ keys
def trace_hash(coordinates) -> str:
"""A layout's trace, as the layer keys name it: a changed trace makes a new key."""
return hashlib.sha256(repr(coordinates).encode()).hexdigest()[:16]
def map_layer_key(source_key: str, trace: str, frame: str, zoom: int) -> str:
return f"map/{source_key}/{trace}-{frame}-z{zoom}-{RENDER_VERSION}"
def photo_layer_key(file: str, sha1: str, frame: str) -> str:
name = hashlib.sha256(file.encode()).hexdigest()[:12] # a Commons title may hold any character
return f"photo/{name}-{sha1}-{frame}-{RENDER_VERSION}"
def locator_layer_key(lat: float, lon: float) -> str:
return f"locator/{round(lat, 2):.2f}_{round(lon, 2):.2f}-{RENDER_VERSION}"
def outline_layer_key(trace: str, frame: str, zoom: int) -> str:
return f"outline/{trace}-{frame}-z{zoom}"
def finished_key(route: str, options: Options, layer_keys: Iterable[str], picked: Iterable[str] = ()) -> str:
"""A finished picture's name in the store: its route, its options, the keys of the layers it was made from, and
every text it draws from a pick (a photo's credit), so a changed credit makes a new key (docs/posters.md,
principle 2). A picture drawn from no pick keeps the key it had before: nothing is added for it."""
made_of = "|".join(sorted(layer_keys))
texts = "\n".join(text for text in picked if text)
drawn = f"\n{texts}" if texts else ""
digest = hashlib.sha256(f"{RENDER_VERSION}\n{route}\n{options.canonical()}\n{made_of}{drawn}".encode()).hexdigest()
return f"{digest[:40]}.{options.format}"
# ------------------------------------------------------------------ what clients keep
def cache_headers(kept: bool, versioned: bool, etag: str) -> dict[str, str]:
"""An address with the current address version is kept for good; any other a day, asked again with its ETag;
a picture served without its layer five minutes, with no ETag."""
if not kept:
return {"Cache-Control": "public, max-age=300"}
if versioned:
return {"Cache-Control": "public, max-age=31536000, immutable", "ETag": etag}
return {"Cache-Control": "public, max-age=86400", "ETag": etag}
def etag_matches(if_none_match: str, etag: str) -> bool:
"""If-None-Match against our ETag by the weak comparison: W/ is ignored on both sides."""
tags = [tag.strip().removeprefix("W/") for tag in (if_none_match or "").split(",")]
return etag.removeprefix("W/") in tags or "*" in tags
# ------------------------------------------------------------------ the store's cap
def evictions(entries: dict[str, tuple[float, int]], cap: int) -> list[str]:
"""The stored pictures to remove, least recently used first, until the rest fit the cap.
entries: name → (last used, size in bytes)."""
total = sum(size for _, size in entries.values())
out = []
for name, (_, size) in sorted(entries.items(), key=lambda item: item[1][0]):
if total <= cap:
break
out.append(name)
total -= size
return out
+373
View File
@@ -0,0 +1,373 @@
"""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, 2.5, 3.0, 4.0 and the ported 2.0 DE, 3.0 DE, 3.0 NL: 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"),
],
}
+798 -673
View File
File diff suppressed because it is too large Load Diff
+547
View File
@@ -0,0 +1,547 @@
{
"$comment": "The picked Wikimedia Commons photo per season, matched to the operator's curated car of that season (docs/posters.md, Season posters and Picking photos; the match per season is in seasons/picks.md). A candidate comes from the \"<year> Formula One season cars\" category or from a search for the curated car by name; the match, in order: the same car, the same model in a livery it raced that season, the same team's car of that season, that season's champion car. Key: the year, such as \"2024\". Value: {\"file\": the Commons title without \"File:\", \"licence\": its LicenseShortName (CC0, public domain, CC BY or CC BY-SA only), \"author\", \"credit\": \"Photo: <author>, <licence>, via Wikimedia Commons\", \"date\": YYYY[-MM[-DD]], when the photo was taken, and, where the date Commons gives cannot be, \"date_from\": \"description\" or \"category\", where the date was read instead, or \"upload\", the month of the file's upload where neither says}. Written by the picking tool, read by the poster service; a key starting with \"$\" is a note, not a pick.",
"1950": {
"file": "Galleria Ferrari (9) (3955971032).jpg",
"licence": "CC BY-SA 2.0",
"author": "János Korom Dr. >11 Million views from Wien, Austria",
"credit": "Photo: János Korom Dr. >11 Million views from Wien, Austria, CC BY-SA 2.0, via Wikimedia Commons",
"date": "2002-04-13"
},
"1951": {
"file": "Ferrari 212 F1.jpg",
"licence": "CC BY 2.0",
"author": "andy carter from England",
"credit": "Photo: andy carter from England, CC BY 2.0, via Wikimedia Commons",
"date": "2008-08-31"
},
"1952": {
"file": "Grote Prijs Nederlandse autoraces Zandvoort. Finish Askari, Bestanddeelnr 905-2692.jpg",
"licence": "CC0",
"author": "Joop van Bilsen / Anefo",
"credit": "Photo: Joop van Bilsen / Anefo, CC0, via Wikimedia Commons",
"date": "1952-08-17"
},
"1953": {
"file": "Goodwood Festival of Speed 2024 (54254822116).jpg",
"licence": "CC BY 2.0",
"author": "Mark from Brighton",
"credit": "Photo: Mark from Brighton, CC BY 2.0, via Wikimedia Commons",
"date": "2024-07-12"
},
"1954": {
"file": "Großer Preis von Europa -1954 Nürburgring, Juan Manuel Fangio, Mercedes (3)x.JPG",
"licence": "CC BY-SA 3.0",
"author": "Agridecumantes",
"credit": "Photo: Agridecumantes, CC BY-SA 3.0, via Wikimedia Commons",
"date": "1954-08-01"
},
"1955": {
"file": "Goodwood Festival of Speed 2015 (26733252225).jpg",
"licence": "CC BY-SA 2.0",
"author": "christianb_7",
"credit": "Photo: christianb_7, CC BY-SA 2.0, via Wikimedia Commons",
"date": "2015-06-28"
},
"1956": {
"file": "Lancia D50 of Scuderia Ferrari.jpg",
"licence": "CC BY 2.0",
"author": "Simon Davison from Los Gatos, United States",
"credit": "Photo: Simon Davison from Los Gatos, United States, CC BY 2.0, via Wikimedia Commons",
"date": "2006-08-19"
},
"1957": {
"file": "1957 Maserati 250F (54834214403).jpg",
"licence": "CC BY 4.0",
"author": "David Merrett from Daventry, England",
"credit": "Photo: David Merrett from Daventry, England, CC BY 4.0, via Wikimedia Commons",
"date": "2025-08-22"
},
"1958": {
"file": "1958 Ferrari Dino 246 (54834214458).jpg",
"licence": "CC BY 4.0",
"author": "David Merrett from Daventry, England",
"credit": "Photo: David Merrett from Daventry, England, CC BY 4.0, via Wikimedia Commons",
"date": "2025-08-22"
},
"1959": {
"file": "Autoraces op het circuit van Zandvoort van de Grand Prix Stirling Moss (no.11) t, Bestanddeelnr 910-4129.jpg",
"licence": "CC0",
"author": "Harry Pot / Anefo",
"credit": "Photo: Harry Pot / Anefo, CC0, via Wikimedia Commons",
"date": "1959-05-31"
},
"1960": {
"file": "Millers at Milwaukee 2026 061 (1960 Scarab Formula 1 No. 48).jpg",
"licence": "CC BY-SA 4.0",
"author": "Michael Barera",
"credit": "Photo: Michael Barera, CC BY-SA 4.0, via Wikimedia Commons",
"date": "2026-07-11"
},
"1961": {
"file": "Von Trips and P. Hill at 1961 Dutch Grand Prix.jpg",
"licence": "CC BY-SA 3.0 nl",
"author": "Harry Pot",
"credit": "Photo: Harry Pot, CC BY-SA 3.0 nl, via Wikimedia Commons",
"date": "1961-05-22"
},
"1962": {
"file": "Porsche 804 Solitude Revival 2022 1X7A0078.jpg",
"licence": "CC BY-SA 4.0",
"author": "Alexander Migl",
"credit": "Photo: Alexander Migl, CC BY-SA 4.0, via Wikimedia Commons",
"date": "2022-07-17"
},
"1963": {
"file": "1963 Lotus 25 R4 (54833107267).jpg",
"licence": "CC BY 4.0",
"author": "David Merrett from Daventry, England",
"credit": "Photo: David Merrett from Daventry, England, CC BY 4.0, via Wikimedia Commons",
"date": "2025-08-22"
},
"1964": {
"file": "John Surtees Ferrari 158 at Goodwood 2014 001.jpg",
"licence": "CC BY-SA 2.0",
"author": "Nic Redhead",
"credit": "Photo: Nic Redhead, CC BY-SA 2.0, via Wikimedia Commons",
"date": "2014-06-29"
},
"1965": {
"file": "Honda RA272 (Hikaru Miyagi).jpg",
"licence": "CC BY 2.0",
"author": "Norimasa Hayashida",
"credit": "Photo: Norimasa Hayashida, CC BY 2.0, via Wikimedia Commons",
"date": "2012-10-07"
},
"1966": {
"file": "Brabham BT19, NSM, 2008 vertical.JPG",
"licence": "CC BY-SA 3.0",
"author": "Bahnfrend",
"credit": "Photo: Bahnfrend, CC BY-SA 3.0, via Wikimedia Commons",
"date": "2008-04-23"
},
"1967": {
"file": "1967 Cooper-Maserati T86 191599250.jpg",
"licence": "CC BY 2.0",
"author": "edvvc from London, UK",
"credit": "Photo: edvvc from London, UK, CC BY 2.0, via Wikimedia Commons",
"date": "2006-07-09"
},
"1968": {
"file": "Stewart, J., Matra MS10, 2. Rd 1968-08-04 v2.jpg",
"licence": "CC BY-SA 2.0 de",
"author": "Spurzem - Lothar Spurzem; Image modified by xavax",
"credit": "Photo: Spurzem - Lothar Spurzem; Image modified by xavax, CC BY-SA 2.0 de, via Wikimedia Commons",
"date": "1968-08-04"
},
"1969": {
"file": "Jochen Rindt 1969 German GP.jpg",
"licence": "CC BY-SA 2.0 de",
"author": "Lothar Spurzem",
"credit": "Photo: Lothar Spurzem, CC BY-SA 2.0 de, via Wikimedia Commons",
"date": "1969-08-01"
},
"1970": {
"file": "Rindt at 1970 Dutch Grand Prix.jpg",
"licence": "CC BY-SA 3.0 nl",
"author": "Evers, Joost / Anefo / neg. stroken, 1945-1989, 2.24.01.05, item number 923-6110",
"credit": "Photo: Evers, Joost / Anefo / neg. stroken, 1945-1989, 2.24.01.05, item number 923-6110, CC BY-SA 3.0 nl, via Wikimedia Commons",
"date": "1970-06-21"
},
"1971": {
"file": "1971 Emerson Fittipaldi, Lotus 72 (kl).JPG",
"licence": "CC BY-SA 3.0 de",
"author": "Lothar Spurzem",
"credit": "Photo: Lothar Spurzem, CC BY-SA 3.0 de, via Wikimedia Commons",
"date": "1971"
},
"1972": {
"file": "1972 Lotus 72D (54834288360).jpg",
"licence": "CC BY 4.0",
"author": "David Merrett from Daventry, England",
"credit": "Photo: David Merrett from Daventry, England, CC BY 4.0, via Wikimedia Commons",
"date": "2025-08-22"
},
"1973": {
"file": "Ferrari 312B2 Jacky Ickx 2010 Canada.jpg",
"licence": "CC BY-SA 2.0",
"author": "Mark McArdle",
"credit": "Photo: Mark McArdle, CC BY-SA 2.0, via Wikimedia Commons",
"date": "2010-06-11"
},
"1974": {
"file": "Franschhoek Motor Museum (30524452055).jpg",
"licence": "CC BY 2.0",
"author": "naeem mayet",
"credit": "Photo: naeem mayet, CC BY 2.0, via Wikimedia Commons",
"date": "2016-10-23"
},
"1975": {
"file": "Jean-Pierre Jarier Shadow DN5 2019 Silverstone Classic (48557920447).jpg",
"licence": "CC BY 2.0",
"author": "https://www.flickr.com/photos/davehamster/",
"credit": "Photo: https://www.flickr.com/photos/davehamster/, CC BY 2.0, via Wikimedia Commons",
"date": "2019-07-26"
},
"1976": {
"file": "James Hunt - McLaren M23 - 1976 Race of Champions, Brands Hatch.jpg",
"licence": "CC BY-SA 2.0",
"author": "Martin Lee",
"credit": "Photo: Martin Lee, CC BY-SA 2.0, via Wikimedia Commons",
"date": "1976-03-14"
},
"1977": {
"file": "Jean-Pierre Jarier - Penske PC4 at Tabac at the 1977 Monaco GP.jpg",
"licence": "CC BY-SA 2.0",
"author": "Martin Lee",
"credit": "Photo: Martin Lee, CC BY-SA 2.0, via Wikimedia Commons",
"date": "1977-05-22"
},
"1978": {
"file": "Riccardo Patrese - Arrows FA1 at Druids at the 1978 British Grand Prix (50050521097).jpg",
"licence": "CC BY-SA 2.0",
"author": "Martin Lee from London, UK",
"credit": "Photo: Martin Lee from London, UK, CC BY-SA 2.0, via Wikimedia Commons",
"date": "1978-07-16",
"date_from": "description"
},
"1979": {
"file": "FoS20162016 0624 103601AA (27851813796).jpg",
"licence": "CC BY-SA 2.0",
"author": "Matthew Lamb",
"credit": "Photo: Matthew Lamb, CC BY-SA 2.0, via Wikimedia Commons",
"date": "2016-06-24"
},
"1980": {
"file": "Ferrari 312T5 Gilles Villeneuve 2010 Canada 1.jpg",
"licence": "CC BY-SA 2.0",
"author": "Mark McArdle",
"credit": "Photo: Mark McArdle, CC BY-SA 2.0, via Wikimedia Commons",
"date": "2010-06-11"
},
"1981": {
"file": "McLaren MP4 at Silverstone Classic 2011 (1).jpg",
"licence": "CC BY 2.0",
"author": "David Merrett from Daventry, England",
"credit": "Photo: David Merrett from Daventry, England, CC BY 2.0, via Wikimedia Commons",
"date": "2011-07-22"
},
"1982": {
"file": "Rene Arnoux 1982 British GP.jpg",
"licence": "CC BY-SA 2.0",
"author": "Martin Lee",
"credit": "Photo: Martin Lee, CC BY-SA 2.0, via Wikimedia Commons",
"date": "1982-07-18"
},
"1983": {
"file": "Renault RE40 (30428152663).jpg",
"licence": "CC BY-SA 2.0",
"author": "Alexandre Prévot from Nancy, France",
"credit": "Photo: Alexandre Prévot from Nancy, France, CC BY-SA 2.0, via Wikimedia Commons",
"date": "2016-02-03"
},
"1984": {
"file": "Lotus 95T Classic-Days 2022 DSC 0141.jpg",
"licence": "CC BY-SA 4.0",
"author": "Alexander Migl",
"credit": "Photo: Alexander Migl, CC BY-SA 4.0, via Wikimedia Commons",
"date": "2022",
"date_from": "description"
},
"1985": {
"file": "1985 European GP Rosberg.jpg",
"licence": "CC BY-SA 2.0",
"author": "Jerry Lewis-Evans",
"credit": "Photo: Jerry Lewis-Evans, CC BY-SA 2.0, via Wikimedia Commons",
"date": "1985-10-04"
},
"1986": {
"file": "Lotus 98T Donington 2007.jpg",
"licence": "CC BY 2.0",
"author": "Darren",
"credit": "Photo: Darren, CC BY 2.0, via Wikimedia Commons",
"date": "2007-09-09"
},
"1987": {
"file": "Ferrari F187 (1987) (22031030520).jpg",
"licence": "CC BY-SA 2.0",
"author": "Takayuki Suzuki from Kanagawa, Japan",
"credit": "Photo: Takayuki Suzuki from Kanagawa, Japan, CC BY-SA 2.0, via Wikimedia Commons",
"date": "2015-09-27"
},
"1988": {
"file": "Ayrton Senna in 1988.jpg",
"licence": "CC BY 2.0",
"author": "Instituto Ayrton Senna",
"credit": "Photo: Instituto Ayrton Senna, CC BY 2.0, via Wikimedia Commons",
"date": "1988",
"date_from": "description"
},
"1989": {
"file": "Musée Lamborghini 0078.JPG",
"licence": "CC BY-SA 3.0",
"author": "Arnaud 25",
"credit": "Photo: Arnaud 25, CC BY-SA 3.0, via Wikimedia Commons",
"date": "2012-08",
"date_from": "upload"
},
"1990": {
"file": "McLaren MP4-5B front-right Honda Collection Hall.jpg",
"licence": "CC BY-SA 3.0",
"author": "Morio",
"credit": "Photo: Morio, CC BY-SA 3.0, via Wikimedia Commons",
"date": "2012-07-16"
},
"1991": {
"file": "Bertrand Gachot 1991 USA.jpg",
"licence": "CC BY 2.0",
"author": "Stuart Seeger from College Station, Texas, USA",
"credit": "Photo: Stuart Seeger from College Station, Texas, USA, CC BY 2.0, via Wikimedia Commons",
"date": "1991-03-10",
"date_from": "description"
},
"1992": {
"file": "Ayrton Senna 1992 Monaco.jpg",
"licence": "CC BY 2.0",
"author": "Iwao from Tokyo, Japan",
"credit": "Photo: Iwao from Tokyo, Japan, CC BY 2.0, via Wikimedia Commons",
"date": "1992-05-28"
},
"1993": {
"file": "Alain Prost - Williams FW15C during practice for the 1993 British Grand Prix (33557472711).jpg",
"licence": "CC BY-SA 2.0",
"author": "Martin Lee from London, UK",
"credit": "Photo: Martin Lee from London, UK, CC BY-SA 2.0, via Wikimedia Commons",
"date": "1993"
},
"1994": {
"file": "Williams FW16 front 2017 Williams Conference Centre.jpg",
"licence": "CC BY-SA 4.0",
"author": "Morio",
"credit": "Photo: Morio, CC BY-SA 4.0, via Wikimedia Commons",
"date": "2017-03-18"
},
"1995": {
"file": "Benetton B195 front-left1 2019 Michael Schumacher Private Collection.jpg",
"licence": "CC BY-SA 4.0",
"author": "Morio",
"credit": "Photo: Morio, CC BY-SA 4.0, via Wikimedia Commons",
"date": "2019-05-06"
},
"1996": {
"file": "Rubens Barrichello - Imola 1996.jpg",
"licence": "CC BY-SA 4.0",
"author": "Restu20",
"credit": "Photo: Restu20, CC BY-SA 4.0, via Wikimedia Commons",
"date": "1996-05-03"
},
"1997": {
"file": "Williams FW19 of Jacques Villeneuve, 1997.jpg",
"licence": "CC BY-SA 2.0",
"author": "Phil Guest",
"credit": "Photo: Phil Guest, CC BY-SA 2.0, via Wikimedia Commons",
"date": "2014-04-12"
},
"1998": {
"file": "1998 F1 car Ferrari F300 Goodwood 2009.jpg",
"licence": "CC BY 2.0",
"author": "Brian Snelson from Hockley, Essex, England",
"credit": "Photo: Brian Snelson from Hockley, Essex, England, CC BY 2.0, via Wikimedia Commons",
"date": "2009-07-05"
},
"1999": {
"file": "McLaren MP4-14, Mika Häkkinen (The Loh Collection) 2.jpg",
"licence": "CC BY 4.0",
"author": "MarcelBuehner",
"credit": "Photo: MarcelBuehner, CC BY 4.0, via Wikimedia Commons",
"date": "2024-05-02"
},
"2000": {
"file": "Ferrari F1-2000, Michael Schumacher (53277830647).jpg",
"licence": "CC BY 2.0",
"author": "Thomas Vogt from Paderborn, Deutschland",
"credit": "Photo: Thomas Vogt from Paderborn, Deutschland, CC BY 2.0, via Wikimedia Commons",
"date": "2023-10-01"
},
"2001": {
"file": "Minardi PS01 front 2017 Museo Fernando Alonso.jpg",
"licence": "CC BY-SA 4.0",
"author": "Morio",
"credit": "Photo: Morio, CC BY-SA 4.0, via Wikimedia Commons",
"date": "2017-03-03"
},
"2002": {
"file": "Ferrari F2002 front.jpg",
"licence": "CC BY 2.0",
"author": "pelican-actor",
"credit": "Photo: pelican-actor, CC BY 2.0, via Wikimedia Commons",
"date": "2022-04-29"
},
"2003": {
"file": "Juan Pablo Montoya 2003 Silverstone 10.jpg",
"licence": "CC BY-SA 2.0",
"author": "Martin Lee",
"credit": "Photo: Martin Lee, CC BY-SA 2.0, via Wikimedia Commons",
"date": "2003-07-28"
},
"2004": {
"file": "Renault R24 front 2017 Museo Fernando Alonso.jpg",
"licence": "CC BY-SA 4.0",
"author": "Morio",
"credit": "Photo: Morio, CC BY-SA 4.0, via Wikimedia Commons",
"date": "2017-03-03"
},
"2005": {
"file": "2005 Renault R25 (54834195219).jpg",
"licence": "CC BY 4.0",
"author": "David Merrett from Daventry, England",
"credit": "Photo: David Merrett from Daventry, England, CC BY 4.0, via Wikimedia Commons",
"date": "2025-08-22"
},
"2006": {
"file": "F1 car McLarenMercedes 2006 2.jpg",
"licence": "CC BY-SA 2.5",
"author": "user:AngMoKio",
"credit": "Photo: user:AngMoKio, CC BY-SA 2.5, via Wikimedia Commons",
"date": "2006-11-07"
},
"2007": {
"file": "Goodwood FOS 2008 (2661779792).jpg",
"licence": "CC BY 2.0",
"author": "Mark Woodbury from London, England",
"credit": "Photo: Mark Woodbury from London, England, CC BY 2.0, via Wikimedia Commons",
"date": "2008-07-11"
},
"2008": {
"file": "Red Bull RB4 front Donington Grand Prix Collection.jpg",
"licence": "CC BY-SA 3.0",
"author": "Morio",
"credit": "Photo: Morio, CC BY-SA 3.0, via Wikimedia Commons",
"date": "2013-03-07"
},
"2009": {
"file": "Nakajima 2009 Spain.jpg",
"licence": "CC BY 2.0",
"author": "Jose Mª Izquierdo Galiot",
"credit": "Photo: Jose Mª Izquierdo Galiot, CC BY 2.0, via Wikimedia Commons",
"date": "2009-05-08"
},
"2010": {
"file": "Jenson Button 2010 Britain.jpg",
"licence": "CC BY 2.0",
"author": "First Stop from UK",
"credit": "Photo: First Stop from UK, CC BY 2.0, via Wikimedia Commons",
"date": "2010-07-09"
},
"2011": {
"file": "Jenson Button 2011 Malaysia FP3.jpg",
"licence": "CC BY-SA 3.0",
"author": "Morio",
"credit": "Photo: Morio, CC BY-SA 3.0, via Wikimedia Commons",
"date": "2011-04-09"
},
"2012": {
"file": "Mark Webber (7448977618).jpg",
"licence": "CC BY-SA 2.0",
"author": "Nic Redhead from Birmingham, UK",
"credit": "Photo: Nic Redhead from Birmingham, UK, CC BY-SA 2.0, via Wikimedia Commons",
"date": "2012-06-09"
},
"2013": {
"file": "16 Maldonado (9186376054).jpg",
"licence": "CC BY 2.0",
"author": "Steven Jones",
"credit": "Photo: Steven Jones, CC BY 2.0, via Wikimedia Commons",
"date": "2013-06-28"
},
"2014": {
"file": "Lewis Hamilton 2014 Singapore Race(L02).jpg",
"licence": "CC BY-SA 4.0",
"author": "Morio",
"credit": "Photo: Morio, CC BY-SA 4.0, via Wikimedia Commons",
"date": "2014-09-21"
},
"2015": {
"file": "Sebastian Vettel 2015 Malaysia FP2 3.jpg",
"licence": "CC BY-SA 4.0",
"author": "Morio",
"credit": "Photo: Morio, CC BY-SA 4.0, via Wikimedia Commons",
"date": "2015-03-27"
},
"2016": {
"file": "F1 - Renault - Kevin Magnussen (28582684145).jpg",
"licence": "CC BY 2.0",
"author": "Jen_ross83",
"credit": "Photo: Jen_ross83, CC BY 2.0, via Wikimedia Commons",
"date": "2016-07-08"
},
"2017": {
"file": "Ferrari SF70H Vettel Barcelona Test.jpg",
"licence": "CC BY-SA 2.0",
"author": "Artes Max from Spain",
"credit": "Photo: Artes Max from Spain, CC BY-SA 2.0, via Wikimedia Commons",
"date": "2017-02-27"
},
"2018": {
"file": "FIA F1 Austria 2018 Nr. 16 Leclerc.jpg",
"licence": "CC BY-SA 4.0",
"author": "Lukas Raich",
"credit": "Photo: Lukas Raich, CC BY-SA 4.0, via Wikimedia Commons",
"date": "2018-06-29"
},
"2019": {
"file": "Lewis Hamilton's 2019 Mercedes AMG Petronas Motorsport M10 Formula 1 Car (49379927706).jpg",
"licence": "CC BY 2.0",
"author": "David Merrett from Daventry, England",
"credit": "Photo: David Merrett from Daventry, England, CC BY 2.0, via Wikimedia Commons",
"date": "2020-01-11"
},
"2020": {
"file": "Max Verstappen, 2020 pre-season testing (2).jpg",
"licence": "CC BY 2.0",
"author": "Jen Ross",
"credit": "Photo: Jen Ross, CC BY 2.0, via Wikimedia Commons",
"date": "2020-02-21"
},
"2021": {
"file": "FIA F1 Austria 2021 Nr. 5 Vettel.jpg",
"licence": "CC BY-SA 4.0",
"author": "Lukas Raich",
"credit": "Photo: Lukas Raich, CC BY-SA 4.0, via Wikimedia Commons",
"date": "2021-07-02"
},
"2022": {
"file": "FIA F1 Austria 2022 Nr. 1 Verstappen.jpg",
"licence": "CC BY-SA 4.0",
"author": "Lukas Raich",
"credit": "Photo: Lukas Raich, CC BY-SA 4.0, via Wikimedia Commons",
"date": "2022-07-08"
},
"2023": {
"file": "FIA F1 Austria 2023 Nr. 4 (2).jpg",
"licence": "CC BY-SA 4.0",
"author": "Lukas Raich",
"credit": "Photo: Lukas Raich, CC BY-SA 4.0, via Wikimedia Commons",
"date": "2023-06-30"
},
"2024": {
"file": "2024-08-25 Motorsport, Formel 1, Großer Preis der Niederlande 2024 STP 3923 by Stepro.jpg",
"licence": "CC BY-SA 4.0",
"author": "Steffen Prößdorf",
"credit": "Photo: Steffen Prößdorf, CC BY-SA 4.0, via Wikimedia Commons",
"date": "2024-08-25"
},
"2025": {
"file": "FIA F1 Imola 2025 No. 81 Piastri (3) (cropped).jpg",
"licence": "CC BY 4.0",
"author": "Jen_ross83",
"credit": "Photo: Jen_ross83, CC BY 4.0, via Wikimedia Commons",
"date": "2025-05-16"
},
"2026": {
"file": "2026-08-21 Motorsport, Formel 1, Großer Preis der Niederlande 2026 STP 2266.jpg",
"licence": "CC BY-SA 4.0",
"author": "Steffen Prößdorf",
"credit": "Photo: Steffen Prößdorf, CC BY-SA 4.0, via Wikimedia Commons",
"date": "2026-08-21"
}
}
+90
View File
@@ -0,0 +1,90 @@
# The table of picks: the season photos
The photo each season poster draws (`seasons/photos.json`) and how it matches the operator's curated car of that
season (docs/posters.md, Season posters). The match, in order: `same car`; `same model, other livery` (the same model
in a livery it raced that season); `same team and season` (the same team's car of that season); `champion` (that
season's champion car). A curated photo of another year's car gives way to that season's car. The curated photos
are a private reference: a row names and describes the curated car, never its photo. Licence, author and date of
each pick were read from Commons' own metadata.
Matches: same car 72; same model, other livery 1; same team and season 3; champion 1 (of 77 seasons).
| Year | Curated car | Picked file | Licence | Match | Why |
|:---|:---|:---|:---|:---|:---|
| 2026 | Red Bull with Honda power, #1 (a 2022-2025 car), Bahrain | 2026-08-21 Motorsport, Formel 1, Großer Preis der Niederlande 2026 STP 2266.jpg | CC BY-SA 4.0 | same team and season | The curated car is a pre-2026 Red Bull (Honda on the engine cover; Red Bull runs Ford power in 2026). The lead's answer: Red Bull's 2026 car instead, here Verstappen's RB22. Commons marks the file with a personality-rights notice. |
| 2025 | McLaren MCL39 #81, Oscar Piastri, night race | FIA F1 Imola 2025 No. 81 Piastri (3) (cropped).jpg | CC BY 4.0 | same car | Piastri's #81 MCL39 from the front three-quarters (MCL38 and MCL39 look alike; the operator's year holds). |
| 2024 | Red Bull (Verstappen) beside Aston Martin #14 (Fernando Alonso), Jeddah at night | 2024-08-25 Motorsport, Formel 1, Großer Preis der Niederlande 2024 STP 3923 by Stepro.jpg | CC BY-SA 4.0 | same car | Verstappen's RB20 head-on, the nearer of the two curated cars in the curated view. The 2023 and 2024 liveries are too alike to read the photo's year, so the operator's year holds. Commons marks the file with a personality-rights notice. |
| 2023 | McLaren MCL36 (2022 car), Lando Norris, Interlagos | FIA F1 Austria 2023 Nr. 4 (2).jpg | CC BY-SA 4.0 | same team and season | The curated photo shows a 2022 car: the 2022 São Paulo photos on Commons show the same livery (papaya with a blue band, Darktrace wing), while the 2023 MCL60 is darker with Chrome on the sidepods. By the lead's rule, McLaren's 2023 car instead: Norris's MCL60. |
| 2022 | Red Bull RB18 #1, Max Verstappen, Barcelona | FIA F1 Austria 2022 Nr. 1 Verstappen.jpg | CC BY-SA 4.0 | same car | Verstappen's #1 RB18 from the front three-quarters, the curated view. |
| 2021 | Aston Martin AMR21 #5, Sebastian Vettel, Monaco | FIA F1 Austria 2021 Nr. 5 Vettel.jpg | CC BY-SA 4.0 | same car | Vettel's #5 AMR21 at speed, Cognizant sidepod and helmet in the crop. |
| 2020 | Red Bull RB16 #33, Max Verstappen | Max Verstappen, 2020 pre-season testing (2).jpg | CC BY 2.0 | same car | Verstappen's RB16; the better-framed RB16 photo is Albon's car. |
| 2019 | Mercedes W10 #44, Lewis Hamilton, Melbourne | Lewis Hamilton's 2019 Mercedes AMG Petronas Motorsport M10 Formula 1 Car (49379927706).jpg | CC BY 2.0 | same car | Hamilton's own W10 head-on with its #44 nose (the title says "M10"; the car is the W10). |
| 2018 | Sauber C37 #16, Charles Leclerc (McLaren MCL33 #14 behind), Suzuka | FIA F1 Austria 2018 Nr. 16 Leclerc.jpg | CC BY-SA 4.0 | same car | Leclerc's #16 C37 with the Alfa Romeo engine cover; the Sauber is the curated photo's subject in front. |
| 2017 | Ferrari SF70H #5, Sebastian Vettel | Ferrari SF70H Vettel Barcelona Test.jpg | CC BY-SA 2.0 | same car | Vettel's SF70H from the front three-quarters, the curated view. |
| 2016 | Renault R.S.16 #20, Kevin Magnussen, Singapore | F1 - Renault - Kevin Magnussen (28582684145).jpg | CC BY 2.0 | same car | Magnussen's #20 R.S.16, whole in the crop. |
| 2015 | Ferrari SF15-T, Sebastian Vettel, Spa | Sebastian Vettel 2015 Malaysia FP2 3.jpg | CC BY-SA 4.0 | same car | Vettel's SF15-T: helmet, sidepod and front wheel in the crop. |
| 2014 | Mercedes F1 W05 Hybrid #44, Lewis Hamilton, head-on | Lewis Hamilton 2014 Singapore Race(L02).jpg | CC BY-SA 4.0 | same car | Hamilton's W05 head-on, the curated view. |
| 2013 | Williams FW35 #16, Pastor Maldonado, Jerez test | 16 Maldonado (9186376054).jpg | CC BY 2.0 | same car | Maldonado's #16 FW35 with its PDVSA livery. |
| 2012 | Red Bull RB8, Mark Webber, Barcelona | Mark Webber (7448977618).jpg | CC BY-SA 2.0 | same car | Webber's RB8 at speed; cockpit, helmet and Red Bull sidepod in the crop. |
| 2011 | McLaren MP4-26, Jenson Button | Jenson Button 2011 Malaysia FP3.jpg | CC BY-SA 3.0 | same car | Button's MP4-26 head-on with the Vodafone wing; 1600x923, upscaled 1.6x. |
| 2010 | McLaren MP4-25, Jenson Button | Jenson Button 2010 Britain.jpg | CC BY 2.0 | same car | Button in the MP4-25, helmet, cockpit and Vodafone wing filling the crop. |
| 2009 | Williams FW31 #17, Kazuki Nakajima, Barcelona | Nakajima 2009 Spain.jpg | CC BY 2.0 | same car | The curated photo is this Commons file itself (same picture, compared pixel by pixel at reduced size); taken exactly. 1416x852, upscaled 1.76x. |
| 2008 | Red Bull RB4 #10, Mark Webber | Red Bull RB4 front Donington Grand Prix Collection.jpg | CC BY-SA 3.0 | same car | The RB4 head-on, square 2560x2560, so almost the whole car stays in the crop. |
| 2007 | Ferrari F2007, Kimi Raikkonen | Goodwood FOS 2008 (2661779792).jpg | CC BY 2.0 | same car | An F2007 from the front three-quarters, whole in the crop; Raikkonen's own race photos on Commons are 637 to 1034 px wide. |
| 2006 | McLaren MP4-21 (Emirates, Siemens, Johnnie Walker), white and red helmet (Kimi Raikkonen) | F1 car McLarenMercedes 2006 2.jpg | CC BY-SA 2.5 | same car | The MP4-21 head-on, centred; its sponsors match the curated car's. |
| 2005 | Renault R25, Fernando Alonso | 2005 Renault R25 (54834195219).jpg | CC BY 4.0 | same car | The #5 R25 (Alonso's number) head-on, portrait, 3511x4037. |
| 2004 | Renault R24 #8, Fernando Alonso, Magny-Cours | Renault R24 front 2017 Museo Fernando Alonso.jpg | CC BY-SA 4.0 | same car | Alonso's #8 R24 head-on in his museum; no race photo of his car frames as well. |
| 2003 | Williams FW25, Juan Pablo Montoya, Monaco, head-on | Juan Pablo Montoya 2003 Silverstone 10.jpg | CC BY-SA 2.0 | same car | Montoya's FW25 head-on at speed, the curated view; 1156x937, upscaled 1.6x, still sharp enough at poster size. |
| 2002 | Ferrari F2002 #1, Michael Schumacher | Ferrari F2002 front.jpg | CC BY 2.0 | same car | The #1 F2002 head-on, a portrait photo that fits the poster whole. |
| 2001 | Minardi PS01 #21, Fernando Alonso (European livery) | Minardi PS01 front 2017 Museo Fernando Alonso.jpg | CC BY-SA 4.0 | same car | Alonso's own #21 PS01 head-on; the front view keeps the nose and livery in the crop, a three-quarter view cut into a wheel. |
| 2000 | Ferrari F1-2000 (Marlboro), Michael Schumacher or Rubens Barrichello, 2000 Brazilian GP (the reference's caption) | Ferrari F1-2000, Michael Schumacher (53277830647).jpg | CC BY 2.0 | same car | Schumacher's Ferrari F1-2000 #3 on display, from the front like the reference; nose with the 3, Shell and FedEx fill the crop. No free photo shows it racing |
| 1999 | McLaren MP4/14 Mercedes (West silver and black), probably Mika Häkkinen #1, 1999 Australian GP | McLaren MP4-14, Mika Häkkinen (The Loh Collection) 2.jpg | CC BY 4.0 | same car | Häkkinen's McLaren MP4/14 #1 in the Loh Collection, from the front like the reference, West on the rear wing; nose, the 1 and Mobil in the crop. No free photo shows it racing |
| 1998 | Ferrari F300 (Marlboro), probably Michael Schumacher, in action | 1998 F1 car Ferrari F300 Goodwood 2009.jpg | CC BY 2.0 | same car | a Ferrari F300 running at Goodwood in 2009, head-on in action; nose, Shell and the driver fill the crop. Schumacher's own F300 at the 1998 Spanish GP (12095605603) is a side view whose crop cuts the car |
| 1997 | Williams FW19 Renault (Rothmans), Jacques Villeneuve #3, in action | Williams FW19 of Jacques Villeneuve, 1997.jpg | CC BY-SA 2.0 | same car | Villeneuve's own Williams FW19 #3 in the Rothmans livery of the reference, head-on in a portrait photo: the whole car is in the crop |
| 1996 | Jordan 196 Peugeot (Benson & Hedges gold), Rubens Barrichello or Martin Brundle (helmet not readable), in action | Rubens Barrichello - Imola 1996.jpg | CC BY-SA 4.0 | same car | Barrichello's Jordan 196 at Imola in 1996, side view in action like the reference; the whole car with B&H in the crop, small in the frame |
| 1995 | Benetton B195 Renault (Mild Seven), Michael Schumacher #1, at Monaco | Benetton B195 front-left1 2019 Michael Schumacher Private Collection.jpg | CC BY-SA 4.0 | same car | Schumacher's Benetton B195 #1 in the Mild Seven livery of the reference, in his private collection; the race photos of 1995 (British GP, Bitburger livery) crop to half a car |
| 1994 | Williams FW16 Renault (Rothmans), Ayrton Senna #2, in action | Williams FW16 front 2017 Williams Conference Centre.jpg | CC BY-SA 4.0 | same car | the Williams FW16 #2 in its 1994 Rothmans livery at the Williams Conference Centre; no free photo shows Senna's car racing. Front view: Renault, elf and the 2 fill the crop |
| 1993 | Williams FW15C Renault (Camel, Canon, elf), Alain Prost #2, in action | Alain Prost - Williams FW15C during practice for the 1993 British Grand Prix (33557472711).jpg | CC BY-SA 2.0 | same car | Prost's own Williams FW15C #2 in practice for the 1993 British GP, from the front like the reference; nose with elf and the 2, Prost's helmet in the crop |
| 1992 | McLaren MP4/7A Honda (Marlboro), Ayrton Senna #1, leading Mansell's Williams FW14B #5 at Monaco | Ayrton Senna 1992 Monaco.jpg | CC BY 2.0 | same car | Senna's own McLaren MP4/7A in practice for the 1992 Monaco GP, the reference's race; his helmet and the red and white nose in the crop. Small original (1024x683), upscaled |
| 1991 | Jordan 191 Ford (7Up green and blue), #32 (Bertrand Gachot's number, which Michael Schumacher took at Spa), in action | Bertrand Gachot 1991 USA.jpg | CC BY 2.0 | same car | Gachot's own Jordan 191 #32 at the 1991 United States GP, side view in action like the reference; 7Up, Ireland and the cockpit in the crop. Small original (1229x819), upscaled |
| 1990 | McLaren MP4/5B Honda (Marlboro), Ayrton Senna #27, in action with Berger's car behind | McLaren MP4-5B front-right Honda Collection Hall.jpg | CC BY-SA 3.0 | same car | Senna's McLaren MP4/5B #27 at the Honda Collection Hall; no free photo shows it in action, this one keeps Marlboro, Honda and the 27 in the crop |
| 1989 | Lola LC89 Lamborghini (Larrousse; Camel, BP, Rhône-Poulenc, Espo), probably Philippe Alliot, in action | Musée Lamborghini 0078.JPG | CC BY-SA 3.0 | same car | a Larrousse Lola LC89 Lamborghini of 1989 in the Lamborghini museum, with the reference's Camel, BP, Rhône-Poulenc and Seine Maritime marks; its nose is green and red where the reference's is yellow (GEO/Espo). The only free LC89 photos besides two race starts where it is a speck |
| 1988 | McLaren MP4/4 Honda (Marlboro), Ayrton Senna #12, in action | Ayrton Senna in 1988.jpg | CC BY 2.0 | same car | Senna in his McLaren MP4/4 #12 in a 1988 race, posted by the Instituto Ayrton Senna; nose, 12 and helmet fill the crop. Small original (1219x789), upscaled |
| 1987 | Ferrari F1/87, Gerhard Berger #28, in action | Ferrari F187 (1987) (22031030520).jpg | CC BY-SA 2.0 | same car | Berger's Ferrari F1/87 #28 running at Suzuka in 2015, front three-quarter at a kerb like the reference; cockpit and the 28 nose in the crop |
| 1986 | Lotus 98T Renault (JPS black and gold), Ayrton Senna #12, in action at Spa | Lotus 98T Donington 2007.jpg | CC BY 2.0 | same car | the Lotus 98T #12 in Senna's 1986 JPS livery, running at Donington in 2007; side view in action like the reference. A 1986 race photo on Commons (Lotus 98T of Ayrton Senna, 1986.jpg) came via a 2009 Flickr upload of what looks like an agency shot, so it was not picked |
| 1985 | Williams FW10 Honda (Canon), Keke Rosberg #6, in action | 1985 European GP Rosberg.jpg | CC BY-SA 2.0 | same car | Rosberg's own Williams FW10 #6 at the 1985 European GP, a portrait photo: the whole car in action in the crop |
| 1984 | Lotus 95T (JPS black and gold), Nigel Mansell #12, in action | Lotus 95T Classic-Days 2022 DSC 0141.jpg | CC BY-SA 4.0 | same car | a Lotus 95T in Mansell's 1984 JPS livery (his name on the cockpit), a Commons quality image; the JPS nose and sidepod fill the crop. Mansell's car at the 1984 British GP (10241974846) sits behind the year in the crop |
| 1983 | Renault RE40 (yellow and white, Renault elf), Alain Prost #15, from the front | Renault RE40 (30428152663).jpg | CC BY-SA 2.0 | same car | Prost's Renault RE40 #15 on display, seen from the front like the reference: the nose with the Renault diamond, elf and the 15 fill the crop |
| 1982 | Renault RE30B (yellow and white, Renault elf), René Arnoux #16, in action | Rene Arnoux 1982 British GP.jpg | CC BY-SA 2.0 | same car | Arnoux's own Renault RE30B at the 1982 British GP, in action from the front-left like the reference; the car fills the crop |
| 1981 | McLaren MP4/1 (Marlboro), John Watson #7, 1981 British GP at Silverstone | McLaren MP4 at Silverstone Classic 2011 (1).jpg | CC BY 2.0 | same car | Watson's McLaren MP4/1 #7 (his name on the cockpit) running at Silverstone in 2011; a side view, so the crop keeps the cockpit and Marlboro sidepod, not the nose |
| 1980 | Ferrari 312T5, Gilles Villeneuve #2, in action (Monaco) | Ferrari 312T5 Gilles Villeneuve 2010 Canada 1.jpg | CC BY-SA 2.0 | same car | Villeneuve's Ferrari 312T5 #2 in its 1980 livery, run at Montreal in 2010; front three-quarter at a corner like the reference, nose and cockpit in the crop |
| 1979 | Wolf WR7 (Olympus Cameras black and gold), James Hunt #20, 1979 Argentine GP | FoS20162016 0624 103601AA (27851813796).jpg | CC BY-SA 2.0 | same car | the Wolf WR7 #20 in its 1979 Olympus livery, run at Goodwood 2016; front three-quarter as in the reference, whole car in the crop |
| 1978 | Arrows FA1 (Warsteiner gold and black), Riccardo Patrese #35, at Brands Hatch | Riccardo Patrese - Arrows FA1 at Druids at the 1978 British Grand Prix (50050521097).jpg | CC BY-SA 2.0 | same car | Patrese's own Arrows FA1 #35 at Druids, 1978 British GP, front three-quarter as in the reference; whole car in the crop |
| 1977 | ATS Penske PC4 (yellow ATS livery), Jean-Pierre Jarier #34 | Jean-Pierre Jarier - Penske PC4 at Tabac at the 1977 Monaco GP.jpg | CC BY-SA 2.0 | same car | Jarier's own yellow ATS Penske PC4 at the 1977 Monaco GP, the only free photo of that car; it sits small under a hoarding in the crop but is clearly the yellow ATS. Found by a search for the car by name: the file is not in the "1977 Formula One season cars" category |
| 1976 | McLaren M23 (Marlboro), James Hunt #11, in action; Lauda's Ferrari 312T2 #1 behind | James Hunt - McLaren M23 - 1976 Race of Champions, Brands Hatch.jpg | CC BY-SA 2.0 | same car | Hunt's own 1976 McLaren M23 #11 in action at the 1976 Race of Champions, front three-quarter like the reference; small original (1160x774), upscaled but the car is clear |
| 1975 | Shadow DN5, black UOP colours, number 16, Tom Pryce at the 1975 French Grand Prix (period colour photo) | Jean-Pierre Jarier Shadow DN5 2019 Silverstone Classic (48557920447).jpg | CC BY 2.0 | same car | The Shadow DN5 of Pryce's team-mate Jarier in the same 1975 UOP colours, at the Silverstone Classic 2019 (number 75 here); airbox, stripes and front wing fill the crop. Commons gives the author as the photographer's Flickr address. Found by a search for the car by name: the file is not in the "1975 Formula One season cars" category |
| 1974 | Tyrrell 007, blue Elf colours, number 3, Jody Scheckter (period colour photo) | Franschhoek Motor Museum (30524452055).jpg | CC BY 2.0 | same car | The Tyrrell 007 with number 3 in the Franschhoek Motor Museum (Scheckter's car, his name on its side in a sibling photo), nose-on; the Elf nose, number and Tyrrell Ford lettering fill the crop |
| 1973 | Ferrari 312B2, red and white, number 9, Jacky Ickx early in 1973 (period colour photo) | Ferrari 312B2 Jacky Ickx 2010 Canada.jpg | CC BY-SA 2.0 | same car | Jacky Ickx's Ferrari 312B2 in Scuderia Ferrari's red and white, at the historic race of the 2010 Canadian Grand Prix (number 4, his 1972 number); nose-on, the car fills the crop |
| 1972 | Lotus 72D, black and gold John Player Special, number 32, Emerson Fittipaldi (period colour photo) | 1972 Lotus 72D (54834288360).jpg | CC BY 4.0 | same car | Fittipaldi's 1972 championship Lotus 72D in the same JPS colours, at Silverstone 2025 (number 1 here); nose-on, the whole car in the portrait frame |
| 1971 | Lotus 72 in black and gold John Player Special colours, number 1, Ronnie Peterson at Monaco: a 1974 car (the 72E), not one of 1971 | 1971 Emerson Fittipaldi, Lotus 72 (kl).JPG | CC BY-SA 3.0 de | same model, other livery | The same model in the colours Team Lotus raced in 1971: Gold Leaf Team Lotus, Emerson Fittipaldi's 72D, number 8, in practice for the 1971 German Grand Prix (period colour). Only a 1217-pixel copy exists on Commons; soft on the poster but the livery, name and number read |
| 1970 | Lotus 72, Gold Leaf red and gold, number 10, Jochen Rindt at the 1970 Dutch Grand Prix (period colour photo) | Rindt at 1970 Dutch Grand Prix.jpg | CC BY-SA 3.0 nl | same car | Rindt's Lotus 72, number 10, at the same race, 21 June 1970 (black and white); the wedge nose, number and driver fill the crop |
| 1969 | Lotus 49B, Gold Leaf red, white and gold with its rear wing, airborne at the 1969 German Grand Prix (period colour photo) | Jochen Rindt 1969 German GP.jpg | CC BY-SA 2.0 de | same car | Rindt's Lotus 49B, number 2, in practice for the same race, 1 August 1969 (period colour); livery, wing and driver in the crop |
| 1968 | Matra MS10 of Matra International, blue, number 6, Jackie Stewart winning the wet 1968 German Grand Prix (period colour photo) | Stewart, J., Matra MS10, 2. Rd 1968-08-04 v2.jpg | CC BY-SA 2.0 de | same car | Stewart's MS10, number 6, on lap 2 of the same race, 4 August 1968 (period colour, grainy); the number, Elf decal, cockpit and wing read in the crop |
| 1967 | Cooper-Maserati T81 of the Cooper works team, dark green with white stripes, number 3, at the 1967 South African Grand Prix (period colour photo) | 1967 Cooper-Maserati T86 191599250.jpg | CC BY 2.0 | same team and season | The works Cooper-Maserati T86 Jochen Rindt drove in 1967, in the works green with a white stripe, at Goodwood 2006; engine, driver and number in the crop. The only works T81 photo (Rodriguez, Zandvoort 1967 practice, CC0) shows just the windscreen and driver; the blue T81 at Bologna 2016 is not named as Guy Ligier's 1967 entry on Commons or Wikipedia (Ligier raced a T81 at two 1967 rounds) |
| 1966 | Brabham-Repco BT19, green with a gold nose, number 3, Jack Brabham (period colour photo) | Brabham BT19, NSM, 2008 vertical.JPG | CC BY-SA 3.0 | same car | The Brabham BT19 (one chassis was built: Brabham's 1966 championship car) at the National Sports Museum, Melbourne; a portrait photo, nose-on, the whole car in frame |
| 1965 | Honda RA272, white with the red disc, number 12, in a demonstration run | Honda RA272 (Hikaru Miyagi).jpg | CC BY 2.0 | same car | The RA272 in its 1965 Mexican Grand Prix number 12, demonstrated at the 2012 Japanese Grand Prix; small in the frame but whole. (A larger whole-car portrait of number 11, "1965 Honda RA272 2.jpg", is the alternative) |
| 1964 | Ferrari 158, red with pale blue wheels, on track at Goodwood | John Surtees Ferrari 158 at Goodwood 2014 001.jpg | CC BY-SA 2.0 | same car | John Surtees driving his championship-winning 1964 Ferrari 158 at Goodwood 2014; one of the season's candidates; driver, number 2 and blue wheel in the crop |
| 1963 | Lotus 25, green with a yellow stripe and yellow wheels, number 4, Jim Clark at the 1963 British Grand Prix (period colour photo) | 1963 Lotus 25 R4 (54833107267).jpg | CC BY 4.0 | same car | Chassis R4, Clark's 1963 championship Lotus 25, at Silverstone 2025 (number 25 here); nose-on, the whole car in the portrait frame |
| 1962 | Porsche 804, silver, on the hill at the Goodwood Festival of Speed | Porsche 804 Solitude Revival 2022 1X7A0078.jpg | CC BY-SA 4.0 | same car | The Porsche 804 on the move at the Solitude Revival 2022, from the same front three-quarter angle; one of the season's candidates |
| 1961 | Ferrari 156 "sharknose", red, von Trips at the 1961 Dutch Grand Prix (period colour photo) | Von Trips and P. Hill at 1961 Dutch Grand Prix.jpg | CC BY-SA 3.0 nl | same car | Von Trips's Ferrari 156 at the same race, 22 May 1961, Phil Hill's behind (black and white); the sharknose nose and driver fill the crop |
| 1960 | Scarab F1 (Reventlow Automobiles), metallic blue, number 48 | Millers at Milwaukee 2026 061 (1960 Scarab Formula 1 No. 48).jpg | CC BY-SA 4.0 | same car | The 1960 Scarab Formula 1 car number 48 itself, at Milwaukee 2026; a portrait photo, nose-on, the whole car in frame |
| 1959 | Cooper T51 of Rob Walker Racing, dark blue with a white band, number 14, Stirling Moss on the 1959 Italian Grand Prix grid (beside Ferrari Dino 246s) | Autoraces op het circuit van Zandvoort van de Grand Prix Stirling Moss (no.11) t, Bestanddeelnr 910-4129.jpg | CC0 | same car | Moss's own Walker Cooper T51 at the 1959 Dutch Grand Prix (number 11, period black and white); the car comes head-on into the crop. A colour photo of an ex-Walker T51 lost its nose in the crop |
| 1958 | Ferrari 246 F1 (Dino), red, number 2, Mike Hawthorn at the 1958 British Grand Prix (period colour photo) | 1958 Ferrari Dino 246 (54834214458).jpg | CC BY 4.0 | same car | The Ferrari Dino 246 shown as Hawthorn's 1958 championship car at Silverstone 2025 (number 38 here); the car fills the portrait frame |
| 1957 | Maserati 250F, red, number 32, Fangio at the 1957 Monaco Grand Prix | 1957 Maserati 250F (54834214403).jpg | CC BY 4.0 | same car | A red 1957 Maserati 250F with number 32, shown as Fangio's championship-winning car at Silverstone 2025; the whole car fits the portrait frame. Found by a search for the car by name: the file is not in the "1957 Formula One season cars" category |
| 1956 | Lancia-Ferrari D50 of Scuderia Ferrari, red, number 10, Fangio at the 1956 French Grand Prix (period colour photo) | Lancia D50 of Scuderia Ferrari.jpg | CC BY 2.0 | same car | A Lancia D50 in Scuderia Ferrari's form (Commons: Lancia D50 of Scuderia Ferrari), side view: the Ferrari badge, the side pontoon with number 17 and the engine fill the crop. A sharper D50A at Goodwood 2024 wears a green nose band no source dates to 1956, so it was dropped |
| 1955 | Mercedes-Benz W196 (open wheels), silver, a colour photo of a demonstration run | Goodwood Festival of Speed 2015 (26733252225).jpg | CC BY-SA 2.0 | same car | The open-wheel W196 at speed, Stirling Moss driving at Goodwood 2015; its nose, star and driver fill the crop |
| 1954 | Mercedes-Benz W196 (open wheels), silver, number 18, Fangio at the 1954 German Grand Prix (period photo) | Großer Preis von Europa -1954 Nürburgring, Juan Manuel Fangio, Mercedes (3)x.JPG | CC BY-SA 3.0 | same car | Fangio's W196 number 18 at the same race, 1 August 1954, black and white like the curated one; car and driver in the crop's lower half |
| 1953 | Ferrari 500, red, a Swiss entrant's script on the nose, on track at a historic run | Goodwood Festival of Speed 2024 (54254822116).jpg | CC BY 2.0 | same car | A 1952 Ferrari 500 F2 (chassis 0482) on the move at Goodwood 2024, seen from the same front three-quarter angle; nose, wheel and cockpit stay in the crop |
| 1952 | Ferrari 375 Indianapolis "Ferrari Special", red, number 35: Johnny Mauro's Kennedy Tank entry, which failed to qualify for the 1952 Indianapolis 500 | Grote Prijs Nederlandse autoraces Zandvoort. Finish Askari, Bestanddeelnr 905-2692.jpg | CC0 | champion | Alberto Ascari's Ferrari 500, number 2, at the finish of the 1952 Dutch Grand Prix (black and white). The one Commons photo of the red Ferrari Special (Indianapolis Motor Speedway Museum) shows only its lettering in the crop; every other 375 Indy on Commons wears the cream Grant Piston Ring livery, which Wikipedia says Johnnie Parsons meant to race in 1952 but did not, so it is no confirmed 1952 entry; no other Kennedy Tank car exists |
| 1951 | Ferrari 212 F1, red with a white nose band, number 15, on track at a historic meeting | Ferrari 212 F1.jpg | CC BY 2.0 | same car | A 1951 Ferrari 212 F1 in the same red and white livery; the crop keeps its 212 badge, the Ferrari shield and the front wheel |
| 1950 | Ferrari 375 F1, red, on track at Silverstone (a 2011 demonstration) | Galleria Ferrari (9) (3955971032).jpg | CC BY-SA 2.0 | same car | Ascari's Ferrari 375 F1 in the Ferrari museum, seen from above: the whole car fits the portrait crop (Leclerc's 2021 Silverstone run of the same car showed only its middle) |
+6 -1
View File
@@ -22,11 +22,16 @@ RUN apk add --no-cache \
COPY service/requirements.txt ./requirements.txt COPY service/requirements.txt ./requirements.txt
RUN pip install --no-cache-dir -r requirements.txt RUN pip install --no-cache-dir -r requirements.txt
COPY cdn-api.py access_log.py circuits_service.py ergast_service.py posters_service.py ./ COPY cdn-api.py access_log.py app_info.py circuits_service.py ergast_service.py posters_service.py \
poster_options.py poster_sources.py ./
COPY models/ ./models/ COPY models/ ./models/
COPY circuits/ ./circuits/ COPY circuits/ ./circuits/
# The picked photo per season (the picks per layout are in circuits/photos.json).
COPY seasons/ ./seasons/
# The example site the app serves at /examples/. # The example site the app serves at /examples/.
COPY examples/ ./examples/ COPY examples/ ./examples/
# The guides the app serves at /guides/.
COPY guides/ ./guides/
EXPOSE 8000 EXPOSE 8000
+116
View File
@@ -0,0 +1,116 @@
"""The candidate tool reads a Commons file's date, licence and credit as docs/posters.md asks, and ranks marks first."""
import importlib.util
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
_spec = importlib.util.spec_from_file_location("commons_candidates", ROOT / "tools" / "commons_candidates.py")
cc = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(cc)
def page(title="File:A.jpg", mime="image/jpeg", width=3000, height=2000, **meta):
"""One page of an imageinfo answer, as the Action API gives it (formatversion 2)."""
return {"title": title, "imageinfo": [{
"mime": mime, "width": width, "height": height,
"thumburl": "https://upload.wikimedia.org/x/500px-A.jpg?utm_source=commons.wikimedia.org",
"descriptionurl": "https://commons.wikimedia.org/wiki/File:A.jpg",
"extmetadata": {k: {"value": v} for k, v in meta.items()},
}]}
class PhotoDateTest(unittest.TestCase):
def test_forms_seen_on_commons(self):
cases = {
"2018-04-22": "2018-04-22",
"2008-06-26 18:57:32": "2008-06-26",
"1983-01": "1983-01",
"Taken on 29 December 2016, 12:19:34": "2016-12-29",
"28 August 2011, 13:44 (according to Exif data)": "2011-08-28",
'<time class="dtstart" datetime="2016-12-29">29 December 2016</time>': "2016-12-29",
"circa 1930date QS:P,+1930-00-00T00:00:00Z/9": "1930",
"07-06-1954": "1954", # day and month order unknown: the year only
}
for raw, want in cases.items():
with self.subTest(raw=raw):
self.assertEqual(cc.photo_date(raw), want)
def test_what_does_not_say_when_it_was_taken(self):
for raw in ["1 December 2006 (original upload date)", "1960s", "between 1950 and 1955", ""]:
with self.subTest(raw=raw):
self.assertIsNone(cc.photo_date(raw))
class CandidateTest(unittest.TestCase):
def test_a_free_file_becomes_a_pick_with_the_designs_credit(self):
c, why = cc.candidate(page(LicenseShortName="CC BY-SA 2.0", License="cc-by-sa-2.0",
Artist='<a href="https://www.flickr.com/x">Nathanael&nbsp;Majoros</a>',
DateTimeOriginal="2008-06-26 18:57:32", Assessments="quality|featured"), "search: aerial")
self.assertEqual(why, "")
self.assertEqual(c["file"], "A.jpg")
self.assertEqual(c["author"], "Nathanael Majoros")
self.assertEqual(c["credit"], "Photo: Nathanael Majoros, CC BY-SA 2.0, via Wikimedia Commons")
self.assertEqual(c["date"], "2008-06-26")
self.assertEqual(c["marks"], ["quality", "featured"])
self.assertNotIn("utm_", c["thumb"])
def test_attribution_asked_by_the_source_wins_over_the_artist(self):
c, _ = cc.candidate(page(LicenseShortName="CC BY-SA 3.0 de", License="cc-by-sa-3.0-de", Artist="Engelbert Reineke",
Attribution="Bundesarchiv, B 145 Bild-F029226-0006 / Engelbert Reineke / CC-BY-SA 3.0"), "x")
self.assertEqual(c["author"], "Bundesarchiv, B 145 Bild-F029226-0006 / Engelbert Reineke / CC-BY-SA 3.0")
def test_only_cc0_public_domain_cc_by_and_cc_by_sa(self):
free = {"cc0": "CC0", "pd": "Public domain", "cc-by-2.0": "CC BY 2.0", "cc-by-sa-4.0": "CC BY-SA 4.0",
"cc-by-sa-3.0-de": "CC BY-SA 3.0 de", "": "Public domain"}
for code, short in free.items():
with self.subTest(code=code):
self.assertIsNotNone(cc.candidate(page(License=code, LicenseShortName=short), "x")[0])
for code, short in {"fal": "FAL", "gfdl": "GFDL", "attribution": "Attribution", "": "Copyrighted free use"}.items():
with self.subTest(code=code or short):
c, why = cc.candidate(page(License=code, LicenseShortName=short), "x")
self.assertIsNone(c)
self.assertTrue(why.startswith("licence"))
def test_maps_and_drawings_are_no_photos(self):
c, why = cc.candidate(page(mime="image/svg+xml", License="cc0", LicenseShortName="CC0"), "x")
self.assertIsNone(c)
self.assertIn("not a photo", why)
class SeasonDateTest(unittest.TestCase):
def test_an_undated_season_photo_takes_its_seasons_year_and_says_so(self):
c = cc.dated_by_season({"file": "Kubica spa.jpg", "date": None}, 2008)
self.assertEqual((c["date"], c["date_from"]), ("2008", "category"))
def test_a_dated_season_photo_keeps_its_own_date(self):
c = cc.dated_by_season({"file": "A.jpg", "date": "2009-05-01"}, 2008)
self.assertEqual(c["date"], "2009-05-01")
self.assertNotIn("date_from", c)
class AerialTest(unittest.TestCase):
def test_a_search_hit_is_aerial_only_when_commons_says_so(self):
def hit(file, cats, found):
return {"file": file, "categories": cats, "found": found}
self.assertTrue(cc.says_aerial(hit("Hungaroring, April 28, 2018 SkySat.jpg", [], ["search: aerial"])))
self.assertTrue(cc.says_aerial(hit("IMG 0211.JPG", ["Aerial photographs of Mogyoród"], ["search: aérienne"])))
self.assertTrue(cc.says_aerial(hit("Zolder racetrack.jpg", [], ["Wikidata aerial view (P8592)"])))
self.assertTrue(cc.says_aerial(hit("Bernhardjr2016.jpg", [], ["search: aerial", "search: drone"])))
self.assertFalse(cc.says_aerial(hit("FRECA 2025 Mogyoród Race (2).jpg", ["FRECA 2025"], ["search: aérienne"])))
class RankTest(unittest.TestCase):
def test_marks_then_size_then_landscape(self):
def cand(name, marks, w, h):
return {"file": name, "marks": marks, "width": w, "height": h}
ranked = sorted([
cand("small landscape", [], 2000, 1000),
cand("big portrait", [], 2000, 3000),
cand("big landscape", [], 3000, 2000),
cand("marked small", ["quality"], 800, 600),
], key=cc.rank_key)
self.assertEqual([c["file"] for c in ranked], ["marked small", "big landscape", "big portrait", "small landscape"])
if __name__ == "__main__":
unittest.main()
+23
View File
@@ -0,0 +1,23 @@
"""Every directory the service serves is copied into its image: a mount of a directory the image lacks stops the
service at its start (Starlette's StaticFiles checks its directory)."""
import re
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
class ImageTest(unittest.TestCase):
def test_every_served_directory_is_copied_into_the_image(self):
app = (ROOT / "cdn-api.py").read_text(encoding="utf-8")
served = re.findall(r'StaticFiles\(directory=Path\(__file__\)\.resolve\(\)\.parent / "([^"]+)"', app)
self.assertTrue(served, "cdn-api.py serves no directory")
dockerfile = (ROOT / "service" / "Dockerfile").read_text(encoding="utf-8")
copied = set(re.findall(r"^COPY (\S+)/ \./\1/$", dockerfile, re.M))
self.assertEqual(sorted(set(served) - copied), [], "served by cdn-api.py, not copied by service/Dockerfile")
for directory in served:
self.assertTrue((ROOT / directory / "index.html").is_file(), f"{directory}/ has no index.html")
if __name__ == "__main__":
unittest.main()
+35
View File
@@ -0,0 +1,35 @@
"""An unknown country, locality, circuit or layout, or a year no layout covers, is named (the API answers it 404).
Standard library only: the models load numpy only where a script uses it.
"""
import unittest
from pathlib import Path
from circuits_service import CircuitService, NotFound
ROOT = Path(__file__).resolve().parent.parent
class LookupTest(unittest.TestCase):
def test_the_first_unknown_part_is_named(self):
service = CircuitService(str(ROOT / "circuits" / "circuits.json"))
spa = ("belgium", "spa", "circuit-de-spa-francorchamps")
self.assertEqual(service.resolve(*spa, "1983-").slug, "1983-")
self.assertEqual(service.layout_for_year(*spa, 1960).slug, "1950-1970")
cases = {
("photos.json",): "No country 'photos.json'",
("belgium", "nowhere"): "No locality 'nowhere' in Belgium",
("belgium", "spa", "nothing"): "No circuit 'nothing' in Spa",
(*spa, "1999"): "No layout '1999' in Circuit de Spa-Francorchamps",
}
for slugs, named in cases.items():
with self.assertRaises(NotFound, msg=slugs) as caught:
service.resolve(*slugs)
self.assertEqual(str(caught.exception), named)
with self.assertRaises(NotFound) as caught:
service.layout_for_year(*spa, 1975) # Spa was not raced from 1971 to 1982
self.assertEqual(str(caught.exception), "No layout of Circuit de Spa-Francorchamps covers 1975")
if __name__ == "__main__":
unittest.main()
+246
View File
@@ -0,0 +1,246 @@
"""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 hashlib
import json
import os
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"}
both = {**photo, **use_map}
cases = [
# (country, circuit, layout, the layout's entry in circuits/photos.json) → (source, year, tint)
(("bahrain", "bahrain-international-circuit", "2004-", photo), ("eox", early, None)), # a pick is bg=photo's
(("united-states", "miami-international-autodrome", "2022-", photo), ("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
(("bahrain", "bahrain-international-circuit", "2004-", both), ("osm", None, "dark")), # a photo beside it
(("united-states", "miami-international-autodrome", "2022-", both), ("usgs", None, None)),
(("spain", "madring", "2026-", None), ("eox", 2025, None)),
]
for given, expected in cases:
chosen = ps.satellite_source(*given)
self.assertEqual((chosen.id, chosen.year, chosen.tint), expected, given)
self.assertEqual(ps.satellite_source("bahrain", "x", "2004-", use_map).credit, ps.OSM_CREDIT)
def test_bg_photo_takes_the_pick_else_the_satellite_chain(self):
photo = {"file": "A.jpg", "licence": "CC BY-SA 4.0"}
self.assertEqual(ps.photo_source("united-states", "miami-international-autodrome", "2022-", photo), ps.COMMONS)
self.assertEqual(ps.photo_source("bahrain", "bahrain-international-circuit", "2004-", {**photo, "use": "map"}),
ps.COMMONS) # with use: map beside the photo, bg=photo still draws the photo
for entry, source in ((None, "usgs"), ({"use": "map"}, "usgs")):
self.assertEqual(ps.photo_source("united-states", "miami-international-autodrome", "2022-", entry).id, source)
self.assertEqual(ps.photo_source("bahrain", "bahrain-international-circuit", "2004-", {"use": "map"}).tint, "dark")
options = po.parse_options([("bg", "photo")], "race")
self.assertEqual(options.bg, "photo")
self.assertTrue(all(po.parse_options([("style", style)], kind).bg == "satellite"
for style in po.STYLES for kind in po.FRAME_OF)) # never a style's default
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")
self.assertEqual(ps.ascii_header("Steffen Prößdorf, Søren Bækgaard, Œuvre, Đorđe"),
"Steffen Prossdorf, Soren Baekgaard, OEuvre, Dorde")
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])
# 2.5 and the ported licences allow a later version with the same elements, as 2.0 and 3.0 do
for licence in ("CC BY-SA 2.5", "CC BY-SA 2.0 de", "CC BY-SA 3.0 de", "CC BY-SA 3.0 nl"):
self.assertTrue(ps.is_free_licence(licence), licence)
self.assertEqual(ps.picture_licence([ps.pick_share({"licence": licence})]), "CC BY-SA 4.0", licence)
def test_picks_skip_notes_and_refuse_what_they_cannot_use(self):
with tempfile.TemporaryDirectory() as kept:
path = Path(kept) / "photos.json"
def photo(file, licence):
return {"file": file, "licence": licence, "author": "A", "credit": "Photo: A", "date": "2020"}
path.write_text(json.dumps({
"$comment": "a note",
"a/b/c/2004-": photo("A.jpg", "CC BY-SA 4.0"),
"a/b/c/2010": photo("C.jpg", "Public domain"),
"a/b/c/2020-": {"use": "map"},
"a/b/c/2021-": {**photo("D.jpg", "CC0"), "use": "map"},
"a/b/c/1950-": photo("B.jpg", "CC BY-NC-SA 2.0"), # refused: not a free licence
"a/b/c/1990": {"use": "satellite"}, # refused: an unknown use
"a/b/c/1991": {"use": "map", "file": "E.jpg", "licence": "CC0"}, # refused: incomplete photo fields
"a/b/c/1992": {}, # refused: neither
}))
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-", "a/b/c/2021-"])
self.assertEqual(len(logged.output), 4)
for name in ("circuits/photos.json", "seasons/photos.json"):
self.assertEqual(ps.read_picks(ROOT / name).get("$comment"), None, name)
# Every season from 1950 to 2026 has its picked photo, keyed in year order, and the reader accepts each one
written = json.loads((ROOT / "seasons/photos.json").read_text(encoding="utf-8"))
seasons = [str(year) for year in range(1950, 2027)]
self.assertEqual([key for key in written if not key.startswith("$")], seasons)
self.assertEqual(list(ps.read_picks(ROOT / "seasons/photos.json")), seasons)
for year in seasons: # where the date was read when Commons' own date cannot be when the photo was taken
self.assertIn(written[year].get("date_from", "description"), ("description", "category", "upload"), year)
def test_the_table_of_picks_names_the_match_per_season(self):
"""seasons/picks.md: one row per picked season, newest first, its file and licence those of
seasons/photos.json, its match one of the design's four (docs/posters.md, Season posters)."""
matches = ("same car", "same model, other livery", "same team and season", "champion")
picks = ps.read_picks(ROOT / "seasons/photos.json")
rows = []
for line in (ROOT / "seasons/picks.md").read_text(encoding="utf-8").splitlines():
if line.startswith("| ") and line[2:6].isdigit():
rows.append([cell.strip() for cell in line.strip().strip("|").split(" | ")])
self.assertEqual([row[0] for row in rows], sorted(picks, key=int, reverse=True))
for year, curated, file, licence, match, why in rows:
self.assertEqual((file, licence), (picks[year]["file"], picks[year]["licence"]), year)
self.assertIn(match, matches, year)
self.assertTrue(curated and why, year)
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"]],
["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())
# Kept for good: an address with the address version, never one with the render version it carried before
self.assertTrue(self.parse(f"v={po.ADDRESS_VERSION}").versioned)
self.assertNotEqual(po.ADDRESS_VERSION, po.RENDER_VERSION)
self.assertFalse(self.parse("v=r3").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=399": "takes 400", "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"))
# A changed credit with the same photo makes a new key; a picture drawn from no pick keeps the key it had
season, photo = self.parse("", "season"), ["photo/a1b2c3-sha1-poster-r3"]
credited = po.finished_key("season/1967", season, photo, ["Photo: A, CC BY 2.0, via Wikimedia Commons"])
self.assertNotEqual(credited, po.finished_key("season/1967", season, photo,
["Photo: B, CC BY 2.0, via Wikimedia Commons"]))
before = hashlib.sha256(f"{po.RENDER_VERSION}\nrace/Bahrain Grand Prix/2024\n{options.canonical()}\n"
"map/eox-2016/x-poster-z15-r3".encode()).hexdigest()
self.assertEqual(key, f"{before[:40]}.png")
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"})
for asked in ('"a", W/"e"', '"e"', 'W/"e"', "*"):
self.assertTrue(po.etag_matches(asked, 'W/"e"'), asked) # the weak comparison
self.assertFalse(po.etag_matches("", 'W/"e"'))
self.assertFalse(po.etag_matches('W/"a"', 'W/"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()
+43
View File
@@ -0,0 +1,43 @@
"""Every layout a race from 2020 on draws has a traced line: a layout whose trace is a point or empty is drawn without
a track (docs/posters.md, Layers), so such a trace for a current race fails the merge check.
The layouts are the ones the service picks for a season (CircuitService.find_layout_slug_for_year), read from
circuits.json, never from Jolpica's schedules. Standard library only, so the merge check runs it as it is.
"""
import json
import unittest
from datetime import date
from pathlib import Path
from circuits_service import CircuitService
ROOT = Path(__file__).resolve().parent.parent
FIRST_SEASON = 2020
MIN_POINTS = 10 # more than a few: a point, an empty line or a stub of a line fails
class TraceTest(unittest.TestCase):
def test_every_layout_raced_from_2020_on_has_a_traced_line(self):
service = CircuitService(str(ROOT / "circuits" / "circuits.json"))
drawn = set()
# This season and the next: a layout added for next season's calendar is held from the day it is added.
for season in range(FIRST_SEASON, date.today().year + 2):
for country in service.circuit_data.values():
for locality in country.localities.values():
for circuit in locality.circuits.values():
slug = service.find_layout_slug_for_year(circuit, season)
if slug is not None:
drawn.add(circuit.layouts[slug].relative_geojson_filepath)
self.assertIn(Path("spain/madrid/madring/2026-.geo.json"), drawn) # the newest layout is among them
for path in sorted(drawn):
with self.subTest(layout=str(path)):
geometry = json.loads((ROOT / "circuits" / path).read_text(encoding="utf-8"))["features"][0]["geometry"]
line = geometry["type"] == "LineString"
points = len(geometry["coordinates"]) if line else 0
found = f"a LineString of {points} points" if line else f"a {geometry['type']}"
self.assertGreater(points, MIN_POINTS, f"{path} is {found}, not a traced line of more than "
f"{MIN_POINTS} points")
if __name__ == "__main__":
unittest.main()
+498
View File
@@ -0,0 +1,498 @@
#!/usr/bin/env python3
"""Lists Wikimedia Commons photos the posters may use, for the picker page to show (docs/posters.md, "Picking photos").
For every layout in circuits/circuits.json: aerial photos of its circuit, dated within the layout's years. For every
season 1950-2026: the photos in "<year> Formula One season cars". Only CC0, public domain, CC BY and CC BY-SA; each
file's licence, author, credit, date and quality marks are read from the Action API's imageinfo extmetadata, 50
files a call. Commons' quality marks rank first, then size, then landscape.
It writes examples/data/candidates.json:
{"about": {...},
"layouts": {"<country>/<city>/<circuit>/<layout>": [candidate, ...]},
"seasons": {"<year>": [candidate, ...]}}
A search hit counts as an aerial photo only when its title or a category says so, or two search words found it: a
word in its description alone matched hundreds of race photos taken from the ground. A candidate holds the fields of a
pick (file, licence, author, credit, date) and what the picker shows beside them (thumb, page, width, height, marks,
restrictions, found). A layout's key is its path under circuits/ without an extension, the key circuits/photos.json
uses; a season's is its year. A season candidate whose file gives no date takes the season's year, marked
"date_from": "category".
Commons' rules, kept here: a descriptive User-Agent with the app's address and no person's; one API request at a
time and at most five a second (a request starts at least REQUEST_GAP after the one before); a 429 or a maxlag
answer waits its Retry-After; no image is downloaded, only thumbnail addresses written for the page. A call that
still fails after its retries stops the run, and nothing is written: a partial list is never kept.
Standard library only. Run from the repository root:
python3 tools/commons_candidates.py # every layout and season, writes the file
python3 tools/commons_candidates.py --only belgium/spa --seasons 2018-2019 --out - # a part, to stdout
"""
from __future__ import annotations
import argparse
import datetime as dt
import html
import json
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
CIRCUITS = ROOT / "circuits" / "circuits.json"
OUT = ROOT / "examples" / "data" / "candidates.json"
USER_AGENT = "f1-circuits-picker/1.0 (+https://f1-circuits.zurag.be)"
COMMONS = "https://commons.wikimedia.org/w/api.php"
WIKIDATA = "https://www.wikidata.org/w/api.php"
ENWIKI = "https://en.wikipedia.org/w/api.php"
REQUEST_GAP = 0.25 # seconds between request starts: at most four a second, under Commons' five
RETRIES = 4
THUMB_WIDTH = 500 # one of Commons' standard thumbnail widths
FIRST_SEASON, LAST_SEASON = 1950, 2026
THIS_YEAR = dt.date.today().year
# One word per query: an OR matched unrelated files worldwide (the licence research, 11.1).
# "SkySat" is read in titles only: as a word it stems to "sky" and matches race photos.
AERIAL_WORDS = ["aerial", "luchtfoto", "Luftbild", "aérienne", "aerea", "drone", "intitle:SkySat"]
MARKED = "incategory:Quality_images|Featured_pictures_on_Wikimedia_Commons|Valued_images_sorted_by_promotion_date"
MARK_WEIGHT = {"poty": 5, "potd": 4, "featured": 3, "valued": 2, "quality": 1}
# A search word may sit in a file's description only ("aérienne" alone matched hundreds of race photos taken from
# the ground), so a search hit counts as aerial when its title or a category says so, or two words found it.
AERIAL_SAYS = re.compile(
r"aerial|luchtfoto|luchtopname|overzicht|luftbild|luftaufnahme|a[ée]rienne|a[ée]re[ao]|drone|\bdji\b|skysat|satellite|"
r"bird.?s.?eye|vogelvlucht|from above|from the air|from (an )?(aircraft|airplane|plane|helicopter)|orthophoto|overview",
re.I)
PHOTO_MIME = {"image/jpeg", "image/tiff", "image/webp"} # maps and drawings come as SVG, PNG or GIF
NOT_A_PHOTO = re.compile(r"\bmaps?\b|\bdiagrams?\b|\blogos?\b|\bplans?\b|\bschemes?\b", re.I)
SEASON_KEEP = 40 # the best of a season's hundreds of files
LAYOUT_KEEP = 40
EXTMETA = ("LicenseShortName|License|LicenseUrl|UsageTerms|Artist|Credit|Attribution|AttributionRequired|"
"Restrictions|DateTimeOriginal|Assessments|Categories")
# The licences a pick may carry, by Commons' machine-readable code (extmetadata License).
FREE = re.compile(r"^(cc0|pd([-a-z0-9]*)?|cc-by-\d[\d.,]*([-a-z]+)?|cc-by-sa-\d[\d.,]*([-a-z]+)?)$", re.I)
class Fetcher:
"""One request at a time, paced, retried; the only way this tool reaches Wikimedia."""
def __init__(self) -> None:
self.last = 0.0
self.count = 0
def get(self, endpoint: str, params: dict) -> dict:
params = {"format": "json", "formatversion": "2", "maxlag": "5", **params}
url = endpoint + "?" + urllib.parse.urlencode(params)
wait = 2.0
for attempt in range(RETRIES + 1):
gap = self.last + REQUEST_GAP - time.monotonic()
if gap > 0:
time.sleep(gap)
self.last = time.monotonic()
self.count += 1
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/json"})
try:
with urllib.request.urlopen(req, timeout=90) as res:
body = json.load(res)
except urllib.error.HTTPError as e:
if attempt < RETRIES and (e.code == 429 or e.code >= 500):
time.sleep(_retry_after(e.headers.get("Retry-After"), wait))
wait *= 2
continue
raise SystemExit(f"commons_candidates: HTTP {e.code} for {url}") from e
except (urllib.error.URLError, TimeoutError) as e:
if attempt < RETRIES:
time.sleep(wait)
wait *= 2
continue
raise SystemExit(f"commons_candidates: no answer for {url}: {e}") from e
err = body.get("error")
if err and err.get("code") == "maxlag" and attempt < RETRIES:
time.sleep(max(5.0, wait))
wait *= 2
continue
if err:
raise SystemExit(f"commons_candidates: the API refused {url}: {err.get('code')}: {err.get('info')}")
return body
raise SystemExit(f"commons_candidates: gave up on {url}")
def _retry_after(value: str | None, default: float) -> float:
try:
return max(1.0, float(value))
except (TypeError, ValueError):
return default
# ---------------------------------------------------------------- reading a file's metadata
def plain(value: str) -> str:
"""Text of an extmetadata value: tags removed, entities decoded, whitespace folded."""
text = re.sub(r"<br\s*/?>", " ", value or "", flags=re.I)
text = re.sub(r"<[^>]+>", "", text)
return re.sub(r"\s+", " ", html.unescape(text)).strip()
MONTHS = {m: i for i, m in enumerate(
["january", "february", "march", "april", "may", "june", "july", "august", "september", "october",
"november", "december"], 1)}
MONTH_RE = "(" + "|".join(MONTHS) + ")"
def photo_date(raw: str) -> str | None:
"""When the photo was taken, as YYYY, YYYY-MM or YYYY-MM-DD; None when the value does not say (an upload date,
a decade, a range). Forms seen on Commons are in the licence research, 11.3."""
if not raw:
return None
qs = re.search(r"QS:P\d*,\+(\d{4})-(\d{2})-(\d{2})T[^/]*/(\d+)", raw)
if qs:
year, month, day, precision = qs.group(1), qs.group(2), qs.group(3), int(qs.group(4))
if precision >= 11 and day != "00":
return f"{year}-{month}-{day}"
if precision == 10 and month != "00":
return f"{year}-{month}"
return year if precision == 9 else None
attr = re.search(r'datetime="(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?', raw)
if attr:
return "-".join(p for p in attr.groups() if p)
text = plain(raw).lower()
if "upload" in text or re.search(r"\d{4}s\b", text) or re.search(r"\bbetween\b|\bor\b", text):
return None
m = re.search(r"\b(\d{4})[-:](\d{2})[-:](\d{2})\b", text)
if m and m.group(2) != "00":
return f"{m.group(1)}-{m.group(2)}" + (f"-{m.group(3)}" if m.group(3) != "00" else "")
m = re.search(r"\b(\d{1,2})(?:st|nd|rd|th)? " + MONTH_RE + r",? (\d{4})\b", text)
if m:
return f"{m.group(3)}-{MONTHS[m.group(2)]:02d}-{int(m.group(1)):02d}"
m = re.search(MONTH_RE + r" (\d{1,2}),? (\d{4})\b", text)
if m:
return f"{m.group(3)}-{MONTHS[m.group(1)]:02d}-{int(m.group(2)):02d}"
m = re.search(MONTH_RE + r",? (\d{4})\b", text)
if m:
return f"{m.group(2)}-{MONTHS[m.group(1)]:02d}"
m = re.search(r"\b(\d{4})-(\d{2})\b", text)
if m and 1 <= int(m.group(2)) <= 12:
return f"{m.group(1)}-{m.group(2)}"
years = set(re.findall(r"\b(1[89]\d{2}|20\d{2})\b", text))
if len(years) == 1: # "1983", "circa 1983", "07-06-1954" (day and month order unknown: the year only)
return years.pop()
return None
def licence_code(short: str) -> str:
"""Commons' machine code from a short licence name, for a file whose License field is empty."""
s = short.strip().lower()
if s in ("public domain", "pd"):
return "pd"
if s == "cc0":
return "cc0"
return re.sub(r"\s+", "-", s.replace("cc by", "cc-by"))
def candidate(page: dict, found: str) -> tuple[dict | None, str]:
"""A candidate from one page of an imageinfo answer, or None with the reason it is not one."""
info = (page.get("imageinfo") or [None])[0]
if not info:
return None, "no imageinfo"
meta = {k: (v or {}).get("value", "") for k, v in (info.get("extmetadata") or {}).items()}
if info.get("mime") not in PHOTO_MIME:
return None, f"not a photo ({info.get('mime')})"
short = plain(meta.get("LicenseShortName", ""))
code = plain(meta.get("License", "")) or licence_code(short)
if not FREE.match(code):
return None, f"licence {code or short or 'unknown'}"
title = page["title"].removeprefix("File:")
author = plain(meta.get("Attribution", "")) or plain(meta.get("Artist", "")) or plain(meta.get("Credit", ""))
author = author or "unknown author"
width, height = int(info.get("width") or 0), int(info.get("height") or 0)
marks = [m for m in plain(meta.get("Assessments", "")).split("|") if m]
thumb = (info.get("thumburl") or info.get("url") or "").split("?utm_")[0]
return {
"file": title,
"licence": short or code,
"author": author,
"credit": f"Photo: {author}, {short or code}, via Wikimedia Commons",
"date": photo_date(meta.get("DateTimeOriginal", "")),
"marks": marks,
"width": width,
"height": height,
"thumb": thumb,
"page": info.get("descriptionurl") or f"https://commons.wikimedia.org/wiki/File:{urllib.parse.quote(title)}",
"licence_url": plain(meta.get("LicenseUrl", "")) or None,
"restrictions": [r for r in plain(meta.get("Restrictions", "")).split("|") if r],
"categories": [c for c in plain(meta.get("Categories", "")).split("|") if c],
"found": [found],
}, ""
def rank_key(c: dict) -> tuple:
"""Commons' quality marks first, then size (tall enough for a 1500-px poster), then landscape, then pixels."""
score = sum(MARK_WEIGHT.get(m, 0) for m in c["marks"])
return (-score, -(c["height"] >= 1500), -(c["width"] > c["height"]), -(c["width"] * c["height"]), c["file"])
# ---------------------------------------------------------------- asking Commons
IMAGEINFO = {
"prop": "imageinfo",
"iiprop": "extmetadata|size|url|mime",
"iiurlwidth": str(THUMB_WIDTH),
"iiextmetadatafilter": EXTMETA,
"iiextmetadatalanguage": "en",
}
def pages_of(fetch: Fetcher, params: dict) -> list[dict]:
"""Every page of one generator answer, its imageinfo complete: a heavy batch may be cut, and is then continued."""
body = fetch.get(COMMONS, {"action": "query", **IMAGEINFO, **params})
pages = {p["pageid"]: p for p in body.get("query", {}).get("pages", []) if "pageid" in p}
cont = body.get("continue", {})
while "iicontinue" in cont:
more = fetch.get(COMMONS, {"action": "query", **IMAGEINFO, **params, **cont})
for p in more.get("query", {}).get("pages", []):
if "pageid" in p and p.get("imageinfo"):
pages.setdefault(p["pageid"], p)["imageinfo"] = p["imageinfo"]
cont = more.get("continue", {})
return list(pages.values())
def search(fetch: Fetcher, query: str, pages: int = 1) -> list[dict]:
"""Files matching a CirrusSearch query, in its order, 50 a call, with their metadata."""
out: list[dict] = []
offset = 0
for _ in range(pages):
params = {"generator": "search", "gsrnamespace": "6", "gsrlimit": "50", "gsrsearch": query,
"gsroffset": str(offset)}
body_pages = pages_of(fetch, params)
out.extend(sorted(body_pages, key=lambda p: p.get("index", 0)))
if len(body_pages) < 50:
break
offset += 50
return out
def files(fetch: Fetcher, titles: list[str]) -> list[dict]:
out: list[dict] = []
for i in range(0, len(titles), 50):
out.extend(pages_of(fetch, {"titles": "|".join(f"File:{t}" for t in titles[i:i + 50])}))
return out
def category_files(fetch: Fetcher, category: str) -> list[dict]:
return pages_of(fetch, {"generator": "categorymembers", "gcmtitle": f"Category:{category}",
"gcmtype": "file", "gcmlimit": "50"})
def wikidata(fetch: Fetcher, titles: list[str]) -> dict[str, dict]:
"""For each English Wikipedia title: its Commons category (P373) and its aerial view (P8592). A title is resolved
on Wikipedia first, its redirects followed: a third of circuits.json's links are redirects."""
item: dict[str, str] = {}
for i in range(0, len(titles), 50):
batch = titles[i:i + 50]
body = fetch.get(ENWIKI, {"action": "query", "titles": "|".join(batch), "redirects": "1",
"prop": "pageprops", "ppprop": "wikibase_item"})
q = body.get("query", {})
moved = {n["from"]: n["to"] for n in q.get("normalized", [])}
moved.update({r["from"]: r["to"] for r in q.get("redirects", [])})
found = {p["title"]: (p.get("pageprops") or {}).get("wikibase_item") for p in q.get("pages", [])}
for title in batch:
final, seen = title, set()
while final in moved and final not in seen:
seen.add(final)
final = moved[final]
if found.get(final):
item[title] = found[final]
out: dict[str, dict] = {}
ids = sorted(set(item.values()))
claims_of: dict[str, dict] = {}
for i in range(0, len(ids), 50):
body = fetch.get(WIKIDATA, {"action": "wbgetentities", "ids": "|".join(ids[i:i + 50]), "props": "claims"})
for qid, entity in body.get("entities", {}).items():
claims_of[qid] = entity.get("claims", {})
for title, qid in item.items():
claims = claims_of.get(qid, {})
value = lambda p: [c["mainsnak"]["datavalue"]["value"] for c in claims.get(p, []) # noqa: E731
if c.get("mainsnak", {}).get("datavalue")]
out[title] = {"id": qid, "category": (value("P373") or [None])[0], "aerial": value("P8592")}
return out
# ---------------------------------------------------------------- the circuits and seasons
def layouts(circuits: dict):
"""(circuit key, circuit, [(layout key, first year, last year)]) per circuit, in the file's order."""
for country, cv in circuits.items():
for city, lv in cv["localities"].items():
for slug, circuit in lv["circuits"].items():
rows = []
for layout in circuit["layouts"]:
first, _, last = layout.partition("-")
end = THIS_YEAR if layout.endswith("-") else int(last or first)
rows.append((f"{country}/{city}/{slug}/{layout}", int(first), end))
yield f"{country}/{city}/{slug}", circuit, rows
def wiki_title(circuit: dict) -> str | None:
url = (circuit.get("urls") or {}).get("wikipedia") or ""
if "/wiki/" not in url:
return None
return urllib.parse.unquote(url.split("/wiki/", 1)[1]).split("#")[0].replace("_", " ")
def gather_circuit(fetch: Fetcher, key: str, circuit: dict, wd: dict, skipped: dict) -> list[dict]:
"""Every aerial-photo candidate of one circuit, before the layouts' years are applied."""
found: dict[str, dict] = {}
def take(pages: list[dict], how: str, check_photo: bool = True) -> None:
for page in pages:
c, why = candidate(page, how)
if not c:
skipped[why] = skipped.get(why, 0) + 1
continue
if check_photo and any(NOT_A_PHOTO.search(cat) for cat in c["categories"]):
why = "in a maps, plans or logos category"
skipped[why] = skipped.get(why, 0) + 1
continue
if c["file"] in found:
if how not in found[c["file"]]["found"]:
found[c["file"]]["found"].append(how)
else:
found[c["file"]] = c
entry = wd.get(wiki_title(circuit) or "", {})
if entry.get("aerial"):
take(files(fetch, entry["aerial"]), "Wikidata aerial view (P8592)", check_photo=False)
category = entry.get("category")
if category:
take(category_files(fetch, f"Aerial photographs of {category}"), f"Category:Aerial photographs of {category}")
for word in AERIAL_WORDS:
take(search(fetch, f'deepcat:"{category}" {word}'), f"search: {word}")
else:
for word in AERIAL_WORDS:
take(search(fetch, f'"{circuit["name"]}" {word}'), f"search (no Commons category): {word}")
kept = [c for c in found.values() if says_aerial(c)]
if len(kept) < len(found):
why = "found by one search word only, and no aerial word in its title or categories"
skipped[why] = skipped.get(why, 0) + len(found) - len(kept)
return kept
def says_aerial(c: dict) -> bool:
"""An aerial photo by what Commons says of it: Wikidata's or the category's pick, an aerial word in its title or a
category, or two search words that found it."""
if any(not how.startswith("search") for how in c["found"]):
return True
if AERIAL_SAYS.search(c["file"]) or any(AERIAL_SAYS.search(cat) for cat in c["categories"]):
return True
return len(c["found"]) >= 2
def dated_by_season(c: dict, year: int) -> dict:
"""A season candidate is of its season: one with no date of its own takes the season's year, and says so. (A
layout candidate with no date stays out: a circuit's photo may show any of its layouts.)"""
if not c["date"]:
c["date"] = str(year)
c["date_from"] = "category"
return c
def in_years(c: dict, first: int, last: int) -> bool:
return bool(c["date"]) and first <= int(c["date"][:4]) <= last
def public(c: dict) -> dict:
"""A candidate as the file keeps it: the categories were only for the filter."""
return {k: v for k, v in c.items() if k != "categories"}
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--only", action="append", default=[],
help="only layouts whose key starts with this (country, country/city, …); may repeat")
ap.add_argument("--seasons", default=f"{FIRST_SEASON}-{LAST_SEASON}",
help="a year, a range such as 2018-2019, or 'none' (default: %(default)s)")
ap.add_argument("--no-layouts", action="store_true", help="list the seasons only")
ap.add_argument("--out", default=str(OUT), help="the file to write, or - for stdout (default: %(default)s)")
args = ap.parse_args()
fetch = Fetcher()
started = dt.datetime.now(dt.timezone.utc)
circuits = json.loads(CIRCUITS.read_text(encoding="utf-8"))
skipped: dict[str, int] = {}
out_layouts: dict[str, list[dict]] = {}
undated: dict[str, int] = {}
chosen = [] if args.no_layouts else [
(k, c, rows) for k, c, rows in layouts(circuits) if not args.only or any(k.startswith(o) for o in args.only)]
wd = wikidata(fetch, sorted({t for _, c, _ in chosen if (t := wiki_title(c))})) if chosen else {}
for n, (key, circuit, rows) in enumerate(chosen, 1):
cands = gather_circuit(fetch, key, circuit, wd, skipped)
undated[key] = sum(1 for c in cands if not c["date"])
for layout_key, first, last in rows:
fits = sorted((c for c in cands if in_years(c, first, last)), key=rank_key)
out_layouts[layout_key] = [public(c) for c in fits[:LAYOUT_KEEP]]
got = sum(1 for k, _, _ in rows if out_layouts[k])
print(f"[{n}/{len(chosen)}] {key}: {len(cands)} licensed photo(s), {undated[key]} undated; "
f"{got} of {len(rows)} layout(s) have a candidate ({fetch.count} requests)", file=sys.stderr)
if args.seasons == "none":
years: list[int] = []
else:
first, _, last = args.seasons.partition("-")
years = list(range(int(first), int(last or first) + 1))
out_seasons: dict[str, list[dict]] = {}
for year in years:
cat = f"{year} Formula One season cars"
found: dict[str, dict] = {}
for query, pages, how in ((f'deepcat:"{cat}" {MARKED}', 1, "marked"), (f'deepcat:"{cat}"', 2, f"Category:{cat}")):
for page in search(fetch, query, pages):
c, why = candidate(page, how)
if not c:
skipped[why] = skipped.get(why, 0) + 1
elif c["file"] not in found:
found[c["file"]] = dated_by_season(c, year)
out_seasons[str(year)] = [public(c) for c in sorted(found.values(), key=rank_key)[:SEASON_KEEP]]
print(f"season {year}: {len(found)} licensed photo(s), kept {len(out_seasons[str(year)])} "
f"({fetch.count} requests)", file=sys.stderr)
result = {
"about": {
"made": started.isoformat(timespec="seconds"),
"by": "tools/commons_candidates.py",
"requests": fetch.count,
"layouts": f"aerial photos of the circuit dated within the layout's years, at most {LAYOUT_KEEP} each",
"seasons": f"photos in '<year> Formula One season cars', at most {SEASON_KEEP} each",
"licences": "CC0, public domain, CC BY and CC BY-SA only",
"ranked": "Commons' quality marks, then size (at least 1500 px high), then landscape, then pixels",
"undated_per_circuit": undated,
"skipped": dict(sorted(skipped.items(), key=lambda kv: -kv[1])),
"check": "every candidate is checked by eye before it is picked: a search also finds ground photos and maps",
},
"layouts": out_layouts,
"seasons": out_seasons,
}
text = json.dumps(result, ensure_ascii=False, indent=1) + "\n"
if args.out == "-":
sys.stdout.write(text)
else:
path = Path(args.out)
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(".tmp")
tmp.write_text(text, encoding="utf-8")
tmp.replace(path)
with_l = sum(1 for v in out_layouts.values() if v)
with_s = sum(1 for v in out_seasons.values() if v)
print(f"{with_l} of {len(out_layouts)} layouts and {with_s} of {len(out_seasons)} seasons have a candidate; "
f"{len(out_layouts) - with_l} layouts have none ({fetch.count} requests)", file=sys.stderr)
return 0
if __name__ == "__main__":
sys.exit(main())