diff --git a/.gitignore b/.gitignore
index acbec81..bc9e7f2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,3 +3,4 @@ qgis
__pycache__/
cache/
.idea/
+.venv-site/
diff --git a/cdn-api.py b/cdn-api.py
index e38c9c7..316949f 100644
--- a/cdn-api.py
+++ b/cdn-api.py
@@ -1,6 +1,7 @@
from fastapi import FastAPI, HTTPException, Response
from fastapi.responses import FileResponse, Response as FastAPIResponse, PlainTextResponse
from fastapi.middleware.cors import CORSMiddleware
+from fastapi.staticfiles import StaticFiles
from pathlib import Path
import logging
@@ -79,10 +80,21 @@ async def root():
"/grand-prix/{grand_prix_name}/year/{year}",
"/posters/race/{grand_prix_name}/{season}.png",
"/posters/season/{season}.png",
- ]
+ "/posters/session/{grand_prix_name}/{season}/{session_slug}.png",
+ "/kometa/formula-1-metadata.yml",
+ ],
+ "examples": "/examples/",
}
+# The example site: one page per area of the API, each calling the routes above (examples/index.html).
+app.mount(
+ "/examples",
+ StaticFiles(directory=Path(__file__).resolve().parent / "examples", html=True),
+ name="examples",
+)
+
+
@app.get("/posters/race/{grand_prix_name}/{season}.png")
async def get_race_poster(grand_prix_name: str, season: int, bg: BackgroundStyle = BackgroundStyle.AERIAL):
"""Plex-ready 1000x1500 race poster (PNG). Cached on disk per (race, bg).
diff --git a/examples/circuits.html b/examples/circuits.html
new file mode 100644
index 0000000..86e98ae
--- /dev/null
+++ b/examples/circuits.html
@@ -0,0 +1,219 @@
+
+
+
+
+
+ Circuit browser · F1 Circuits API examples
+
+
+
+
+
+
+ F1 Circuits API
+
+
+
+
+
+
Circuit browser
+
+ The catalogue is a tree: a country holds cities, a city holds circuits, a circuit holds layouts. Each level has a
+ route; pick an entry to make the next call. Every layout shows its track image.
+
+
+
+
1. Countries
+
/circuits lists every country, and nests its whole tree inside each one.
+
+
+
+ The JSON answer
+
+
+
+
2. Cities of a country
+
/circuits/{country} answers {"cities": [...]}, each city with its circuits.
+ /circuits/{country}/{city}/{circuit} answers the circuit’s name, its Wikipedia and Fandom pages and
+ its layouts. Each layout’s image below is its own call,
+ /circuits/{country}/{city}/{circuit}/layout/{layout}/svg (see Track images).
+
+
+
Pick a circuit above.
+
+
+ The JSON answer
+
+
+
+
5. One layout
+
+ /circuits/{country}/{city}/{circuit}/layout/{layout} answers one layout: its slug, its description
+ and imageUrl, the source drawing on the F1 Fandom wiki.
+
+
+
Press “Details” on a layout above.
+
+
+
+
+
+
+
+
+
+
diff --git a/examples/grand-prix.html b/examples/grand-prix.html
new file mode 100644
index 0000000..4c7fa6c
--- /dev/null
+++ b/examples/grand-prix.html
@@ -0,0 +1,104 @@
+
+
+
+
+
+ Grand prix lookup · F1 Circuits API examples
+
+
+
+
+
+
+ F1 Circuits API
+
+
+
+
+
+
Grand prix lookup
+
+ Name a race and a season, and the API answers the track it was raced on: it reads that season’s schedule from
+ Jolpica, matches the race by its exact name, finds the circuit in its catalogue and picks the layout of that year.
+
+
+
+
1. The season’s races
+
+ This page lists the races by calling Jolpica itself, from the browser (Jolpica allows any origin). If it cannot
+ be reached, type the name: the API needs it exactly as Jolpica’s raceName, such as
+ British Grand Prix.
+
+
+
+
+
+
+
+
2. The race’s track
+
/grand-prix/{race name}/{season}/{format}, the race name percent-encoded (a space is %20).
+
+
+
+
Choose a race.
+
+
+
+
When the lookup finds nothing
+
+ The API answers 404 {"detail": "Circuit not found"} when the name is not in that season’s schedule,
+ when Jolpica cannot be reached from the server, or when the circuit or that year’s layout is not in the catalogue
+ yet (browse it in the circuit browser).
+
+
+
+
+
+
+
+
+
diff --git a/examples/index.html b/examples/index.html
new file mode 100644
index 0000000..da711c2
--- /dev/null
+++ b/examples/index.html
@@ -0,0 +1,134 @@
+
+
+
+
+
+ F1 Circuits API · examples
+
+
+
+
+
+
+ F1 Circuits API
+
+
+
+
+
+
The F1 Circuits API, by example
+
+ F1 Circuits serves the layout of every Formula 1 circuit, one per period the track was raced in, traced by GPS:
+ as an SVG drawing, a PNG image and the GeoJSON trace itself. On top of the layouts it renders race and season
+ posters, session thumbnails and a Kometa metadata file for a Formula 1 library in Plex.
+
+
+ The public address is https://f1-circuits.zurag.be. Every route is a
+ plain GET, needs no key, and allows any origin (CORS), so a page anywhere can call it from the browser.
+ Each page below makes real calls and shows the exact URL it sends next to the answer: copy it into a terminal
+ (curl -O <url>) or a page of your own.
+
+ One helper (site.js) picks the address for every page, in this order:
+
+
+
?api=<base> in the page’s address wins, such as ?api=http://127.0.0.1:8000. Links between the pages keep it.
+
A page opened from disk (file://) calls the public service, https://f1-circuits.zurag.be.
+
A page served over http(s), as the API serves these pages at /examples/, calls its own origin with relative URLs.
+
+
The address in use is in the header, top right; open it to change it.
+
+
+
The API’s own index
+
The root route lists the routes and where these examples live.
+
+
+
+
+
+
+
Words used here
+
+
Country, city, circuit
Slugs in lower case with hyphens, as the /circuits routes list them (belgium, spa, circuit-de-spa-francorchamps). A slug may hold accented letters; encode it in a URL.
+
Layout
One shape of a circuit, named by the years it was raced: 1950-1970, 1983- (1983 until today), or a single year.
+
Format
svg, png or geojson.
+
Race name
The race’s name exactly as Jolpica (the Ergast successor) writes it, such as Belgian Grand Prix; the API reads the season’s schedule there.
+
+
+
+
+
+
+
+
+
diff --git a/examples/kometa.html b/examples/kometa.html
new file mode 100644
index 0000000..1129269
--- /dev/null
+++ b/examples/kometa.html
@@ -0,0 +1,149 @@
+
+
+
+
+
+ Kometa metadata · F1 Circuits API examples
+
+
+
+
+
+
+ F1 Circuits API
+
+
+
+
+
+
Kometa metadata
+
+ Kometa (formerly Plex Meta Manager) sets titles and artwork in a Plex library
+ from YAML files. This route generates the file for a Formula 1 library: it gives every season, every round and every
+ session of a weekend its artwork, all of it rendered by this API.
+
+
+
What it is for
+
+
In a Formula 1 library as Kometa’s Formula 1 builder shapes it:
+
+
each F1 season is one show, titled like the file’s keys (Season 2024);
+
each round of that season is a Plex season of the show;
+
each session of the race weekend is an episode.
+
+
+ f1_season lets Kometa name the rounds and episodes from that year’s schedule. The file adds the
+ artwork: the show gets the season poster, each round its race poster, and each episode
+ its session thumbnail. It covers every season from 1950 to next year; Kometa skips a show or a round the library
+ does not hold.
+
+
+
f1_season
The year the show holds; Kometa’s Formula 1 builder reads its schedule.
+
round_prefix: true
Puts the round number in front of each round’s name.
+
shorten_gp: true
Shortens “Grand Prix” to “GP” in the names.
+
url_poster (show)
/posters/season/{season}.png
+
seasons.{round}.url_poster
/posters/race/{race name}/{season}.png
+
episodes.{n}.url_poster
/posters/session/{race name}/{season}/{session}.png, numbered as on the posters page: 10 episodes for a standard weekend, 15 for a sprint weekend.
+
+
Using it in Kometa
+
Point the library at the file’s URL in Kometa’s config.yml; Kometa fetches it on every run:
+
+
+ The poster addresses inside the file use the public name the service is served under, so Plex can fetch them.
+ The answer is text/yaml and may be cached for an hour (Cache-Control: public, max-age=3600).
+
+
+
+
The file
+
+
+ /kometa/formula-1-metadata.yml. The server builds it from the Jolpica schedule of every season; the
+ first call after a restart takes several seconds.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/examples/map.html b/examples/map.html
new file mode 100644
index 0000000..68ae286
--- /dev/null
+++ b/examples/map.html
@@ -0,0 +1,185 @@
+
+
+
+
+
+ GPS traces on a map · F1 Circuits API examples
+
+
+
+
+
+
+
+ F1 Circuits API
+
+
+
+
+
+
GPS traces on a map
+
+ Each layout was traced by GPS along the track. Its geojson format is that trace: a GeoJSON
+ FeatureCollection holding one LineString of [longitude, latitude] points. Any
+ map library draws it as it comes; this page uses Leaflet. Switch to the
+ satellite layer to see the trace follow the tarmac.
+
+
+
+
+
+
+
+
+
+
+
diff --git a/examples/posters.html b/examples/posters.html
new file mode 100644
index 0000000..1648753
--- /dev/null
+++ b/examples/posters.html
@@ -0,0 +1,221 @@
+
+
+
+
+
+ Posters · F1 Circuits API examples
+
+
+
+
+
+
+ F1 Circuits API
+
+
+
+
+
+
Posters
+
+ The API renders artwork for a Formula 1 library in Plex: a 1000×1500 poster per race and per season, and a
+ 1920×1080 thumbnail per session of a race weekend. The server draws each one on request, fetching map tiles for its
+ background, and keeps it on disk afterwards; so this page renders only the one you ask for, when you press its
+ button.
+
+
+
+
1. Choose a race
+
The race poster and the session thumbnails name the race as Jolpica’s raceName; this list comes from Jolpica.
+
+
+
+
+
+
+
+
Race poster
+
/posters/race/{race name}/{season}.png?bg={background}, 1000×1500: the round, the race’s name, the track and its date over a map of the circuit.
+
+
+
+
+
+
Not rendered yet.
+
+
+
+
+
Season poster
+
/posters/season/{season}.png, 1000×1500: the year over a photo of that season’s cars, or over black when the server has no photo for it.
+
+
+
+
+
+
Not rendered yet.
+
+
+
+
+
+
Session thumbnail
+
+ /posters/session/{race name}/{season}/{session}.png, 1920×1080: an aerial view of the circuit with
+ the race’s name and the session’s label. Kometa numbers a weekend’s episodes differently for a standard weekend
+ (10 episodes) and a sprint weekend (15); the list shows the chosen race’s format first, in episode order.
+
+
+
+
+
+
+
Not rendered yet.
+
+
+
+
Every session slug
+
+
Slug
Label on the thumbnail
Episode, standard weekend
Episode, sprint weekend
+
+
+
+
+
+
+
+
+
+
diff --git a/examples/site.css b/examples/site.css
new file mode 100644
index 0000000..3dc88ae
--- /dev/null
+++ b/examples/site.css
@@ -0,0 +1,299 @@
+/* Shared styles for the F1 Circuits API examples: one file, light and dark. */
+
+:root {
+ color-scheme: light dark;
+ --bg: #f4f4f7;
+ --card: #ffffff;
+ --text: #15151e;
+ --muted: #5d5d6c;
+ --line: #dcdce4;
+ --accent: #e10600;
+ --accent-text: #ffffff;
+ --code-bg: #f0f0f4;
+ --ok: #1a7f37;
+ --warn: #9a6700;
+ --error: #c62828;
+ --tile: #ffffff;
+ --json-key: #0b5cad;
+ --json-string: #1a7f37;
+ --json-number: #a3480b;
+ --json-literal: #8250df;
+ --radius: 10px;
+ --mono: ui-monospace, SFMono-Regular, "JetBrains Mono", Menlo, Consolas, monospace;
+}
+
+@media (prefers-color-scheme: dark) {
+ :root {
+ --bg: #111116;
+ --card: #1b1b23;
+ --text: #e9e9ef;
+ --muted: #a3a3b3;
+ --line: #2e2e3a;
+ --accent: #ff3b30;
+ --code-bg: #24242e;
+ --ok: #4ac26b;
+ --warn: #d29922;
+ --error: #ff6b6b;
+ --tile: #1b1b23;
+ --json-key: #79b8ff;
+ --json-string: #85e89d;
+ --json-number: #ffab70;
+ --json-literal: #d2a8ff;
+ }
+}
+
+* { box-sizing: border-box; }
+
+body {
+ margin: 0;
+ background: var(--bg);
+ color: var(--text);
+ font: 16px/1.55 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
+}
+
+a { color: var(--accent); }
+
+code, pre, kbd { font-family: var(--mono); font-size: 0.9em; }
+:not(pre) > code { background: var(--code-bg); padding: 0.1em 0.35em; border-radius: 4px; }
+
+/* ---- header and navigation ---- */
+
+header.site {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 0.5rem 1.25rem;
+ padding: 0.75rem 1.5rem;
+ background: var(--card);
+ border-bottom: 3px solid var(--accent);
+}
+
+header.site .brand {
+ font-weight: 800;
+ color: var(--text);
+ text-decoration: none;
+ letter-spacing: 0.02em;
+}
+header.site .brand span { color: var(--accent); }
+
+header.site nav { display: flex; flex-wrap: wrap; gap: 0.25rem; flex: 1; }
+header.site nav a {
+ color: var(--muted);
+ text-decoration: none;
+ padding: 0.3rem 0.6rem;
+ border-radius: 6px;
+}
+header.site nav a:hover { color: var(--text); background: var(--code-bg); }
+header.site nav a[aria-current="page"] { color: var(--accent-text); background: var(--accent); }
+
+.api-switch { font-size: 0.85rem; color: var(--muted); }
+.api-switch summary { cursor: pointer; }
+.api-switch summary code { color: var(--text); }
+.api-switch form { display: flex; gap: 0.4rem; margin-top: 0.4rem; }
+.api-switch input { width: 18rem; }
+
+main { max-width: 1200px; margin: 0 auto; padding: 1.5rem; }
+
+h1 { margin: 0.25rem 0 0.5rem; font-size: 1.9rem; }
+h2 { margin: 2rem 0 0.5rem; font-size: 1.35rem; }
+h3 { margin: 1.25rem 0 0.4rem; font-size: 1.1rem; }
+.lead { color: var(--muted); font-size: 1.08rem; max-width: 60rem; }
+
+footer.pager {
+ max-width: 1200px;
+ margin: 2rem auto 0;
+ padding: 1rem 1.5rem 2.5rem;
+ display: grid;
+ grid-template-columns: 1fr auto 1fr;
+ gap: 1rem;
+ border-top: 1px solid var(--line);
+}
+footer.pager a { text-decoration: none; font-weight: 600; }
+footer.pager [rel="next"] { justify-self: end; }
+footer.pager .home { justify-self: center; }
+
+/* ---- cards, calls and results ---- */
+
+.card {
+ background: var(--card);
+ border: 1px solid var(--line);
+ border-radius: var(--radius);
+ padding: 1rem 1.1rem;
+ margin: 1rem 0;
+}
+.card > h2:first-child, .card > h3:first-child { margin-top: 0; }
+
+.grid-2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(340px, 1fr)); gap: 1rem; }
+.grid-2 > .card { margin: 0; }
+
+/* The request bar: the exact URL a call sends, with Copy and Open. */
+.request {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ background: var(--code-bg);
+ border: 1px solid var(--line);
+ border-radius: 8px;
+ padding: 0.4rem 0.5rem;
+ min-height: 2.4rem;
+}
+.request .verb {
+ font: 700 0.75rem var(--mono);
+ color: var(--accent-text);
+ background: var(--ok);
+ border-radius: 4px;
+ padding: 0.15rem 0.4rem;
+}
+.request .url {
+ flex: 1;
+ overflow-x: auto;
+ white-space: nowrap;
+ font-size: 0.85rem;
+ scrollbar-width: thin;
+}
+.request .label { font-size: 0.75rem; color: var(--muted); white-space: nowrap; }
+.request:empty { display: none; }
+/* In a narrow card: the buttons on the first row, the whole URL wrapped below them. */
+.request.compact { flex-wrap: wrap; }
+.request.compact .url { order: 9; flex-basis: 100%; white-space: normal; overflow-wrap: anywhere; font-size: 0.75rem; }
+.request button, .request a.open { font-size: 0.8rem; padding: 0.2rem 0.55rem; }
+.request a.open {
+ border: 1px solid var(--line);
+ border-radius: 6px;
+ text-decoration: none;
+ color: var(--text);
+ background: var(--card);
+}
+
+.status { font-size: 0.85rem; margin: 0.4rem 0 0.6rem; color: var(--muted); min-height: 1.3em; }
+.status.ok::before { content: "● "; color: var(--ok); }
+.status.pending::before { content: "◌ "; color: var(--warn); }
+.status.error { color: var(--error); }
+.status.error::before { content: "✕ "; }
+.status.idle::before { content: "○ "; }
+
+.result:empty { display: none; }
+
+.hint { font-size: 0.85rem; color: var(--muted); margin: 0 0 0.6rem; }
+.hint.error { color: var(--error); }
+
+pre.code {
+ margin: 0;
+ background: var(--code-bg);
+ border: 1px solid var(--line);
+ border-radius: 8px;
+ padding: 0.75rem;
+ overflow: auto;
+ max-height: 32rem;
+ font-size: 0.82rem;
+ line-height: 1.45;
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+}
+pre.code.tall { max-height: 70vh; }
+.j-key { color: var(--json-key); }
+.j-str { color: var(--json-string); }
+.j-num { color: var(--json-number); }
+.j-lit { color: var(--json-literal); }
+
+.notice {
+ border-left: 4px solid var(--warn);
+ background: var(--code-bg);
+ padding: 0.6rem 0.8rem;
+ border-radius: 0 8px 8px 0;
+ margin: 0.6rem 0;
+}
+.notice.error { border-left-color: var(--error); }
+.notice.info { border-left-color: var(--json-key); }
+
+/* ---- forms ---- */
+
+.controls { display: flex; flex-wrap: wrap; gap: 0.75rem 1rem; align-items: end; margin: 0.5rem 0 0.75rem; }
+.controls label { display: flex; flex-direction: column; gap: 0.2rem; font-size: 0.8rem; color: var(--muted); }
+.controls label.inline { flex-direction: row; align-items: center; gap: 0.35rem; color: var(--text); font-size: 0.9rem; }
+.controls fieldset { border: none; padding: 0; margin: 0; display: flex; gap: 0.75rem; align-items: center; }
+.controls legend { font-size: 0.8rem; color: var(--muted); padding: 0; margin-bottom: 0.2rem; }
+
+select, input, button {
+ font: inherit;
+ font-size: 0.92rem;
+ color: var(--text);
+ background: var(--card);
+ border: 1px solid var(--line);
+ border-radius: 6px;
+ padding: 0.35rem 0.5rem;
+}
+input[type="number"] { width: 6.5rem; }
+input.wide { min-width: 16rem; }
+select { max-width: 30rem; }
+button { cursor: pointer; }
+button.primary { background: var(--accent); color: var(--accent-text); border-color: var(--accent); font-weight: 600; }
+button:disabled { opacity: 0.55; cursor: progress; }
+
+/* ---- lists of choices (circuit browser) ---- */
+
+.choices { display: flex; flex-wrap: wrap; gap: 0.4rem; margin: 0.5rem 0; }
+.choices button { font-size: 0.88rem; }
+.choices button[aria-pressed="true"] { background: var(--accent); color: var(--accent-text); border-color: var(--accent); }
+.choices button small { color: inherit; opacity: 0.7; }
+
+/* ---- images ---- */
+
+.track-tile {
+ background: var(--tile);
+ border: 1px solid var(--line);
+ border-radius: 8px;
+ display: grid;
+ place-items: center;
+ padding: 0.75rem;
+ min-height: 9rem;
+}
+.track-tile img { width: 100%; max-width: 480px; max-height: 320px; object-fit: contain; }
+@media (prefers-color-scheme: dark) {
+ /* The service's track images are a black line on a transparent ground. */
+ .track-tile img { filter: invert(1); }
+}
+
+.layouts { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 1rem; }
+.layout-card { border: 1px solid var(--line); border-radius: var(--radius); padding: 0.75rem; display: flex; flex-direction: column; gap: 0.5rem; }
+.layout-card h3 { margin: 0; }
+.layout-card p { margin: 0; font-size: 0.88rem; color: var(--muted); }
+.layout-card .links { font-size: 0.85rem; display: flex; gap: 0.75rem; flex-wrap: wrap; }
+.layout-card .track-tile { min-height: 7rem; }
+.layout-card .track-tile img { max-height: 160px; }
+.layout-card code.small { font-size: 0.72rem; word-break: break-all; }
+
+.poster { display: block; max-width: 100%; border-radius: 8px; border: 1px solid var(--line); }
+.poster.portrait { max-height: 640px; }
+.preview { margin-top: 0.75rem; }
+
+/* ---- tables ---- */
+
+table { border-collapse: collapse; width: 100%; font-size: 0.9rem; }
+th, td { text-align: left; padding: 0.4rem 0.6rem; border-bottom: 1px solid var(--line); vertical-align: top; }
+th { color: var(--muted); font-weight: 600; }
+td code { white-space: nowrap; }
+table.kv th { width: 12rem; }
+
+/* ---- map ---- */
+
+#map { height: 560px; border-radius: var(--radius); border: 1px solid var(--line); }
+.leaflet-container { font: inherit; }
+
+/* ---- index ---- */
+
+.pages { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 1rem; }
+.pages a.page {
+ display: block;
+ background: var(--card);
+ border: 1px solid var(--line);
+ border-radius: var(--radius);
+ padding: 1rem;
+ color: var(--text);
+ text-decoration: none;
+}
+.pages a.page:hover { border-color: var(--accent); }
+.pages a.page h3 { margin: 0 0 0.3rem; color: var(--accent); }
+.pages a.page p { margin: 0 0 0.5rem; color: var(--muted); font-size: 0.92rem; }
+.pages a.page ul { margin: 0; padding-left: 1.1rem; font-size: 0.78rem; }
+.pages a.page li code { background: none; padding: 0; overflow-wrap: anywhere; }
diff --git a/examples/site.js b/examples/site.js
new file mode 100644
index 0000000..ae9685e
--- /dev/null
+++ b/examples/site.js
@@ -0,0 +1,549 @@
+/*
+ * Shared helper for the F1 Circuits API examples.
+ *
+ * - Picks the API base for every page: `?api=` wins; a page opened from disk (file://) calls the
+ * public service; a page served over http(s), by the app itself, calls its own origin (relative URLs).
+ * - Shows the exact request URL of every call (copyable), fetches it, and renders the answer.
+ * - Fills the pickers: layouts from `/circuits`, races from Jolpica.
+ */
+(function () {
+ 'use strict';
+
+ const DEFAULT_API = 'https://f1-circuits.zurag.be';
+ const JOLPICA = 'https://api.jolpi.ca/ergast/f1';
+ const params = new URLSearchParams(location.search);
+ const apiParam = (params.get('api') || '').trim().replace(/\/+$/, '');
+ const base = apiParam || (location.protocol === 'file:' ? DEFAULT_API : '');
+
+ // Query parameters every internal link carries along, so a chosen base stays chosen.
+ const KEPT = ['api', 'raw'];
+
+ /** The URL to fetch for an API path such as `/circuits` (relative when same origin). */
+ function api(path) { return base + path; }
+
+ /** The absolute form of a URL, as the browser sends it. */
+ function absolute(url) { return new URL(url, location.href).href; }
+
+ /** Builds a path, percent-encoding every interpolated value: path`/circuits/${slug}`. */
+ function path(strings, ...values) {
+ return strings.reduce((out, s, i) => out + s + (i < values.length ? encodeURIComponent(values[i]) : ''), '');
+ }
+
+ /** document.createElement with attributes and children. */
+ function h(tag, attrs = {}, ...children) {
+ const el = document.createElement(tag);
+ for (const [k, v] of Object.entries(attrs)) {
+ if (v === null || v === undefined || v === false) continue;
+ if (k === 'class') el.className = v;
+ else if (k === 'text') el.textContent = v;
+ else if (k.startsWith('on')) el.addEventListener(k.slice(2), v);
+ else el.setAttribute(k, v === true ? '' : v);
+ }
+ for (const c of children.flat()) {
+ if (c === null || c === undefined || c === false) continue;
+ el.append(c instanceof Node ? c : document.createTextNode(String(c)));
+ }
+ return el;
+ }
+
+ function fmtSize(n) {
+ if (n < 1024) return `${n} B`;
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} kB`;
+ return `${(n / 1024 / 1024).toFixed(2)} MB`;
+ }
+
+ // ---------------------------------------------------------------- the page frame
+
+ function describeBase() {
+ if (apiParam) return { text: apiParam, why: 'chosen with ?api=' };
+ if (location.protocol === 'file:') return { text: DEFAULT_API, why: 'the page is opened from disk' };
+ return { text: location.origin, why: 'the page is served by the API itself (same origin)' };
+ }
+
+ function linkWithKept(href) {
+ const url = new URL(href, location.href);
+ for (const k of KEPT) {
+ if (params.has(k) && !url.searchParams.has(k)) url.searchParams.set(k, params.get(k));
+ }
+ return url.href;
+ }
+
+ function frame() {
+ // Carry ?api= and ?raw= on every link to another example page.
+ for (const a of document.querySelectorAll('a[href]')) {
+ const href = a.getAttribute('href');
+ if (/^[\w-]+\.html([?#].*)?$/.test(href)) a.href = linkWithKept(href);
+ }
+ const slot = document.getElementById('api-base');
+ if (!slot) return;
+ const d = describeBase();
+ const input = h('input', { name: 'api', type: 'url', placeholder: DEFAULT_API, value: apiParam });
+ slot.replaceChildren(h('details', { class: 'api-switch' },
+ h('summary', { title: d.why }, 'API: ', h('code', {}, d.text)),
+ h('div', {}, `Why: ${d.why}.`),
+ h('form', {
+ onsubmit: (e) => {
+ e.preventDefault();
+ const url = new URL(location.href);
+ const v = input.value.trim();
+ if (v) url.searchParams.set('api', v); else url.searchParams.delete('api');
+ location.href = url.href;
+ },
+ }, input, h('button', { type: 'submit' }, 'Use'))));
+ }
+
+ // ---------------------------------------------------------------- request bar and status
+
+ async function copyText(text, button) {
+ let done = false;
+ try {
+ await navigator.clipboard.writeText(text);
+ done = true;
+ } catch {
+ const ta = h('textarea', { style: 'position:fixed;opacity:0' });
+ ta.value = text;
+ document.body.append(ta);
+ ta.select();
+ try { done = document.execCommand('copy'); } catch { done = false; }
+ ta.remove();
+ }
+ const was = button.textContent;
+ button.textContent = done ? 'Copied' : 'Select and copy';
+ setTimeout(() => { button.textContent = was; }, 1500);
+ }
+
+ /** Shows the exact URL a call sends in a `.request` element. */
+ function setRequest(el, url, label) {
+ const abs = absolute(url);
+ const copy = h('button', { type: 'button', title: 'Copy the URL' }, 'Copy');
+ copy.addEventListener('click', () => copyText(abs, copy));
+ el.replaceChildren(...[
+ h('span', { class: 'verb' }, 'GET'),
+ h('code', { class: 'url', title: decodeURI(abs) }, abs),
+ label ? h('span', { class: 'label' }, label) : null,
+ copy,
+ h('a', { class: 'open', href: abs, target: '_blank', rel: 'noopener' }, 'Open'),
+ ].filter(Boolean));
+ }
+
+ function setStatus(el, kind, text) {
+ if (!el) return;
+ el.className = `status ${kind}`;
+ el.textContent = text;
+ }
+
+ /** A line of explanation under a control; never a call's status. */
+ function setHint(el, kind, text) {
+ el.className = `hint${kind ? ` ${kind}` : ''}`;
+ el.textContent = text;
+ }
+
+ async function errorDetail(blob) {
+ try {
+ const text = await blob.text();
+ try {
+ const j = JSON.parse(text);
+ if (j && j.detail) return typeof j.detail === 'string' ? j.detail : JSON.stringify(j.detail);
+ } catch { /* not JSON */ }
+ return text.slice(0, 160);
+ } catch { return ''; }
+ }
+
+ /**
+ * Calls a URL for a card holding `.request`, `.status` and `.result`: shows the URL, fetches it, says
+ * the answer's status, type, size and time. Returns the answer, or null when it failed (the status says
+ * why) or was replaced by a newer call on the same card.
+ */
+ async function call(card, url, opts = {}) {
+ setRequest(card.querySelector('.request'), url, opts.label);
+ const statusEl = card.querySelector('.status');
+ if (card._abort) card._abort.abort();
+ const ctl = new AbortController();
+ card._abort = ctl;
+ setStatus(statusEl, 'pending', opts.waiting || 'Waiting for the answer…');
+ const t0 = performance.now();
+ let res;
+ let blob;
+ try {
+ res = await fetch(url, { signal: ctl.signal });
+ blob = await res.blob();
+ } catch (e) {
+ if (e.name === 'AbortError') return null;
+ setStatus(statusEl, 'error', `No answer: ${e.message}. The address is unreachable, offline, or the browser blocked it (CORS).`);
+ return null;
+ }
+ if (ctl.signal.aborted) return null;
+ const ms = Math.round(performance.now() - t0);
+ const type = res.headers.get('content-type') || 'no content type';
+ const summary = `HTTP ${res.status} · ${type} · ${fmtSize(blob.size)} · ${ms} ms`;
+ if (!res.ok) {
+ const detail = await errorDetail(blob);
+ setStatus(statusEl, 'error', detail ? `${summary} — ${detail}` : summary);
+ return null;
+ }
+ setStatus(statusEl, 'ok', summary);
+ return { status: res.status, type, blob, ms, size: blob.size, url };
+ }
+
+ /** Fetches JSON for a card and shows it in its `.result`; returns the parsed value or null. */
+ async function callJSON(card, url, opts = {}) {
+ const answer = await call(card, url, opts);
+ const out = card.querySelector('.result');
+ if (!answer) { if (out && !opts.keep) out.replaceChildren(); return null; }
+ let value;
+ try {
+ value = JSON.parse(await answer.blob.text());
+ } catch (e) {
+ setStatus(card.querySelector('.status'), 'error', `The answer is not JSON: ${e.message}`);
+ return null;
+ }
+ if (out && opts.show !== false) showJSON(out, value);
+ return value;
+ }
+
+ // ---------------------------------------------------------------- renderers
+
+ function escapeHTML(s) {
+ return s.replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
+ }
+
+ /** JSON text with arrays of plain numbers kept on one line (coordinates, bounding boxes). */
+ function prettyJSON(value) {
+ return JSON.stringify(value, null, 2)
+ .replace(/\[\s+(-?\d[\d.eE+-]*(?:,\s+-?\d[\d.eE+-]*)*)\s+\]/g, (_, inner) => `[${inner.replace(/\s+/g, ' ')}]`);
+ }
+
+ /** JSON text as HTML with keys, strings, numbers and literals marked; tokenised first, then escaped. */
+ function highlightJSON(text) {
+ const re = /("(?:\\.|[^"\\])*")(\s*:)?|\b(true|false|null)\b|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/g;
+ let out = '';
+ let last = 0;
+ let m;
+ while ((m = re.exec(text))) {
+ out += escapeHTML(text.slice(last, m.index));
+ const [, str, colon, lit, num] = m;
+ if (str) out += colon ? `${escapeHTML(str)}${colon}` : `${escapeHTML(str)}`;
+ else if (lit) out += `${lit}`;
+ else out += `${num}`;
+ last = re.lastIndex;
+ }
+ return out + escapeHTML(text.slice(last));
+ }
+
+ function showJSON(el, value, opts = {}) {
+ const pre = h('pre', { class: `code${opts.tall ? ' tall' : ''}` });
+ pre.innerHTML = highlightJSON(typeof value === 'string' ? value : prettyJSON(value));
+ el.replaceChildren(pre);
+ return pre;
+ }
+
+ function showText(el, text, opts = {}) {
+ const pre = h('pre', { class: `code${opts.tall ? ' tall' : ''}` }, text);
+ el.replaceChildren(pre);
+ return pre;
+ }
+
+ /** What the first bytes of a body are: 'png', 'svg', 'json' or 'unknown'. */
+ async function sniff(blob) {
+ 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';
+ const text = new TextDecoder().decode(head).trimStart();
+ if (text.startsWith(' { if (opts.status) setStatus(opts.status, 'error', `${opts.status.textContent} — not GeoJSON`); };
+ const text = await answer.blob.text();
+ let data;
+ try {
+ data = JSON.parse(text);
+ } catch {
+ fail();
+ const kind = await sniff(answer.blob);
+ el.replaceChildren(
+ notice('error', `Asked for GeoJSON, but the body is ${kind === 'svg' ? 'an SVG document' : 'not JSON'} (the Content-Type header says ${answer.type}). It starts with:`),
+ h('pre', { class: 'code' }, text.slice(0, 400)));
+ return null;
+ }
+ const summary = geoSummary(data);
+ if (!summary.ok) fail();
+ el.replaceChildren(summary.ok
+ ? notice('info', summary.text)
+ : notice('error', summary.text));
+ showJSON(el.appendChild(h('div')), data);
+ return summary.ok ? data : null;
+ }
+
+ function lineOf(data) {
+ const feature = data && data.type === 'FeatureCollection' && Array.isArray(data.features)
+ ? data.features.find((f) => f && f.geometry && f.geometry.type === 'LineString')
+ : null;
+ return feature || null;
+ }
+
+ function geoSummary(data) {
+ if (!data || data.type !== 'FeatureCollection') return { ok: false, text: `Not a GeoJSON FeatureCollection (its type is ${data && data.type}).` };
+ const line = lineOf(data);
+ if (!line) return { ok: false, text: `A FeatureCollection of ${data.features.length} feature(s), none of them a LineString.` };
+ const n = line.geometry.coordinates.length;
+ return { ok: true, text: `A FeatureCollection of ${data.features.length} feature(s); its LineString has ${n} GPS points [longitude, latitude].` };
+ }
+
+ /** Length of a [lon, lat] line in metres (haversine). */
+ function lineLength(coords) {
+ const R = 6371008.8;
+ const rad = (d) => (d * Math.PI) / 180;
+ let m = 0;
+ for (let i = 1; i < coords.length; i++) {
+ const [lon1, lat1] = coords[i - 1];
+ const [lon2, lat2] = coords[i];
+ const a = Math.sin(rad(lat2 - lat1) / 2) ** 2 + Math.cos(rad(lat1)) * Math.cos(rad(lat2)) * Math.sin(rad(lon2 - lon1) / 2) ** 2;
+ m += 2 * R * Math.asin(Math.sqrt(a));
+ }
+ return m;
+ }
+
+ // ---------------------------------------------------------------- the layout picker (from /circuits)
+
+ let treePromise = null;
+
+ /** The whole circuit tree from one `/circuits` call, shown in `card` the first time. */
+ function circuitTree(card) {
+ if (!treePromise) {
+ treePromise = callJSON(card, api('/circuits'), { show: false }).then((v) => {
+ if (!v) return null;
+ const out = card.querySelector('.result');
+ if (out) {
+ const n = { countries: 0, cities: 0, circuits: 0, layouts: 0 };
+ for (const c of v.countries) {
+ n.countries++;
+ for (const l of Object.values(c.localities)) {
+ n.cities++;
+ for (const ci of Object.values(l.circuits)) { n.circuits++; n.layouts += Object.keys(ci.layouts).length; }
+ }
+ }
+ out.replaceChildren(h('p', {}, `${n.countries} countries, ${n.cities} cities, ${n.circuits} circuits and ${n.layouts} layouts. The answer nests the whole tree: country → localities → circuits → layouts.`));
+ }
+ return v;
+ });
+ }
+ return treePromise;
+ }
+
+ const byName = (a, b) => a.name.localeCompare(b.name);
+
+ /** A layout's slug in years: "1983-" → "1983 – today". */
+ function layoutYears(slug) {
+ const [from, to] = slug.split('-');
+ if (slug.endsWith('-')) return `${from} – today`;
+ return to ? `${from} – ${to}` : from;
+ }
+
+ /** The first year a layout slug covers. */
+ function layoutStart(slug) { return parseInt(slug, 10); }
+
+ const DEFAULT_PICK = { country: 'belgium', city: 'spa', circuit: 'circuit-de-spa-francorchamps', layout: '1983-' };
+
+ /**
+ * Four selects (country, city, circuit and, with `layout: true`, layout) filled from the tree.
+ * `sync: true` keeps the choice in the page's query string. Calls onChange(pick) on every change.
+ */
+ async function layoutPicker(root, { treeCard, layout = true, sync = false, onChange }) {
+ const sel = {
+ country: h('select', { 'aria-label': 'Country' }),
+ city: h('select', { 'aria-label': 'City' }),
+ circuit: h('select', { 'aria-label': 'Circuit' }),
+ layout: layout ? h('select', { 'aria-label': 'Layout' }) : null,
+ };
+ root.replaceChildren(...[
+ h('label', {}, 'Country', sel.country),
+ h('label', {}, 'City', sel.city),
+ h('label', {}, 'Circuit', sel.circuit),
+ layout ? h('label', {}, 'Layout (years)', sel.layout) : null,
+ ].filter(Boolean));
+ const tree = await circuitTree(treeCard);
+ if (!tree) { root.append(notice('error', 'The picker could not be filled: the /circuits call failed (see above).')); return null; }
+
+ const countries = [...tree.countries].sort(byName);
+ const want = {};
+ for (const k of Object.keys(DEFAULT_PICK)) want[k] = params.get(k) || DEFAULT_PICK[k];
+
+ const fill = (select, items, wanted) => {
+ select.replaceChildren(...items.map((it) => h('option', { value: it.value }, it.label)));
+ select.value = items.some((it) => it.value === wanted) ? wanted : (items[0] ? items[0].value : '');
+ };
+
+ const pick = () => {
+ const country = countries.find((c) => c.slug === sel.country.value);
+ const city = country && country.localities[sel.city.value];
+ const circuit = city && city.circuits[sel.circuit.value];
+ return {
+ country: sel.country.value, city: sel.city.value, circuit: sel.circuit.value,
+ layout: layout ? sel.layout.value : null,
+ countryName: country && country.name, cityName: city && city.name, circuitName: circuit && circuit.name,
+ layouts: circuit ? Object.keys(circuit.layouts).sort((a, b) => layoutStart(a) - layoutStart(b)) : [],
+ circuitData: circuit || null,
+ };
+ };
+
+ const refill = (level) => {
+ if (level <= 0) fill(sel.country, countries.map((c) => ({ value: c.slug, label: c.name })), want.country);
+ const country = countries.find((c) => c.slug === sel.country.value);
+ if (level <= 1) fill(sel.city, Object.values(country.localities).sort(byName).map((l) => ({ value: l.slug, label: l.name })), want.city);
+ const city = country.localities[sel.city.value];
+ if (level <= 2) fill(sel.circuit, Object.values(city.circuits).sort(byName).map((c) => ({ value: c.slug, label: c.name })), want.circuit);
+ if (layout && level <= 3) {
+ const circuit = city.circuits[sel.circuit.value];
+ const slugs = Object.keys(circuit.layouts).sort((a, b) => layoutStart(a) - layoutStart(b));
+ fill(sel.layout, slugs.map((s) => ({ value: s, label: layoutYears(s) })), want.layout);
+ }
+ };
+
+ const changed = () => {
+ const p = pick();
+ if (sync) {
+ const url = new URL(location.href);
+ for (const k of ['country', 'city', 'circuit', 'layout']) if (p[k]) url.searchParams.set(k, p[k]);
+ history.replaceState(null, '', url.href);
+ }
+ onChange(p);
+ };
+
+ sel.country.addEventListener('change', () => { refill(1); changed(); });
+ sel.city.addEventListener('change', () => { refill(2); changed(); });
+ sel.circuit.addEventListener('change', () => { refill(3); changed(); });
+ if (layout) sel.layout.addEventListener('change', changed);
+
+ refill(0);
+ changed();
+ return { pick };
+ }
+
+ // ---------------------------------------------------------------- the race picker (from Jolpica)
+
+ const seasonCache = new Map();
+
+ function jolpicaURL(season) { return `${JOLPICA}/${season}.json?limit=100`; }
+
+ /** True when a Jolpica race entry is a sprint weekend (it has a Sprint section). */
+ function isSprint(race) { return !!race && Object.keys(race).some((k) => k.toLowerCase().startsWith('sprint')); }
+
+ /**
+ * A season input, a race select filled from Jolpica (called from the browser; it allows any origin)
+ * and the race name as it goes into the URL, editable: when Jolpica cannot be reached the reader types it.
+ */
+ function racePicker(root, { card, defaultSeason = 2024, onChange }) {
+ const thisYear = new Date().getFullYear();
+ const season = h('input', { type: 'number', min: 1950, max: thisYear + 1, value: params.get('season') || defaultSeason, 'aria-label': 'Season' });
+ const race = h('select', { 'aria-label': 'Race' });
+ const name = h('input', { type: 'text', class: 'wide', value: params.get('race') || '', placeholder: 'Belgian Grand Prix', 'aria-label': 'Race name' });
+ const hint = h('p', { class: 'hint' });
+ root.replaceChildren(
+ h('label', {}, 'Season', season),
+ h('label', {}, 'Race (from Jolpica)', race),
+ h('label', {}, 'Race name, as it goes into the URL', name));
+ root.after(hint);
+
+ let races = [];
+ let wanted = params.get('race') || '';
+
+ const current = () => {
+ const r = races.find((x) => x.raceName === name.value) || null;
+ return { season: parseInt(season.value, 10), name: name.value.trim(), race: r, sprint: isSprint(r) };
+ };
+ const sync = () => {
+ const url = new URL(location.href);
+ url.searchParams.set('season', season.value);
+ url.searchParams.set('race', name.value.trim());
+ history.replaceState(null, '', url.href);
+ };
+ const changed = () => { sync(); onChange(current()); };
+
+ async function load() {
+ const s = parseInt(season.value, 10);
+ if (!(s >= 1950)) return;
+ let list = seasonCache.get(s);
+ if (!list) {
+ const value = await callJSON(card, jolpicaURL(s), { show: false, label: 'Jolpica, not this API', waiting: 'Asking Jolpica for the season’s races…' });
+ list = value && value.MRData && value.MRData.RaceTable ? value.MRData.RaceTable.Races : null;
+ if (list) seasonCache.set(s, list);
+ } else {
+ setRequest(card.querySelector('.request'), jolpicaURL(s), 'Jolpica, not this API');
+ }
+ if (!list) {
+ races = [];
+ race.replaceChildren(h('option', { value: '' }, 'Jolpica did not answer'));
+ race.disabled = true;
+ setHint(hint, 'error', 'The race list could not be loaded from Jolpica. Type the race name exactly as Jolpica writes it, such as “Belgian Grand Prix”.');
+ if (!name.value) name.value = wanted || 'Belgian Grand Prix';
+ changed();
+ return;
+ }
+ races = list;
+ race.disabled = false;
+ race.replaceChildren(...list.map((r) => h('option', { value: r.raceName },
+ `R${r.round} · ${r.raceName} · ${r.date}${isSprint(r) ? ' · sprint' : ''}`)));
+ const keep = list.find((r) => r.raceName === (wanted || name.value));
+ race.value = keep ? keep.raceName : (list[0] ? list[0].raceName : '');
+ name.value = race.value;
+ wanted = '';
+ setHint(hint, '', `${list.length} races in ${s}. The API matches the name exactly as Jolpica’s raceName, then finds the circuit and the layout of that year.`);
+ changed();
+ }
+
+ season.addEventListener('change', () => { wanted = name.value; load(); });
+ race.addEventListener('change', () => { name.value = race.value; changed(); });
+ name.addEventListener('change', changed);
+ load();
+ return { current };
+ }
+
+ window.F1 = {
+ DEFAULT_API, JOLPICA, params, base,
+ api, absolute, path, h, fmtSize, notice,
+ setRequest, setStatus, setHint, call, callJSON,
+ prettyJSON, showJSON, showText, showImage, showGeoJSON, sniff, lineOf, lineLength,
+ circuitTree, layoutPicker, layoutYears, layoutStart,
+ racePicker, isSprint, jolpicaURL, linkWithKept,
+ };
+
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', frame);
+ else frame();
+})();
diff --git a/examples/tracks.html b/examples/tracks.html
new file mode 100644
index 0000000..b03dee1
--- /dev/null
+++ b/examples/tracks.html
@@ -0,0 +1,151 @@
+
+
+
+
+
+ Track images · F1 Circuits API examples
+
+
+
+
+
+
+ F1 Circuits API
+
+
+
+
+
+
Track images
+
+ Every layout comes in three formats: svg (a vector drawing), png (an image) and
+ geojson (the GPS trace it was drawn from). Ask for one by its layout, or by a year: the API then picks
+ the layout that was raced that year.
+
+ /tracks/{country}/{city}/{circuit}/year/{year}/{format}. A year no layout of the circuit covers has
+ no track; the list under the picker shows the years each layout covers.
+
+
+
+
+
+
+
+
+
Choose a circuit and a year.
+
+
+
+
About the answers
+
+
svg
image/svg+xml, sent as an attachment: an <img> shows it, a browser tab opening the URL saves it. A black line on a transparent ground.
+
png
image/png, shown inline.
+
geojson
application/geo+json: a FeatureCollection whose LineString is the trace as [longitude, latitude] points; see GPS traces to draw one.
+
Caching
Every file answers Cache-Control: public, max-age=31536000 and an ETag.
+
+
+
+
+
+
+
+
+
diff --git a/service/Dockerfile b/service/Dockerfile
index 3c6217e..b249c89 100644
--- a/service/Dockerfile
+++ b/service/Dockerfile
@@ -25,6 +25,8 @@ 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 models/ ./models/
COPY circuits/ ./circuits/
+# The example site the app serves at /examples/.
+COPY examples/ ./examples/
EXPOSE 8000