Join the photo picker and the example pages into the poster layers
Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
This commit is contained in:
@@ -0,0 +1,360 @@
|
||||
<!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>
|
||||
</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>
|
||||
@@ -18,8 +18,11 @@
|
||||
<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">Licences</a>
|
||||
</nav>
|
||||
<div id="api-base"></div>
|
||||
</header>
|
||||
@@ -89,6 +92,13 @@
|
||||
<a class="home" href="index.html">All examples</a>
|
||||
<a rel="next" href="tracks.html">Track images →</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>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -18,8 +18,11 @@
|
||||
<a href="map.html">GPS traces</a>
|
||||
<a href="grand-prix.html" aria-current="page">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">Licences</a>
|
||||
</nav>
|
||||
<div id="api-base"></div>
|
||||
</header>
|
||||
@@ -66,6 +69,13 @@
|
||||
<a class="home" href="index.html">All examples</a>
|
||||
<a rel="next" href="posters.html">Posters →</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>
|
||||
|
||||
+34
-2
@@ -18,8 +18,11 @@
|
||||
<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">Licences</a>
|
||||
</nav>
|
||||
<div id="api-base"></div>
|
||||
</header>
|
||||
@@ -75,13 +78,20 @@
|
||||
</a>
|
||||
<a class="page" href="posters.html">
|
||||
<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>
|
||||
<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/session/{race name}/{season}/{session}.png</code></li>
|
||||
</ul>
|
||||
</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=…&bg=…&photo=…&show=…</code></li>
|
||||
</ul>
|
||||
</a>
|
||||
<a class="page" href="kometa.html">
|
||||
<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>
|
||||
@@ -99,6 +109,21 @@
|
||||
<li><code>/posters/session/{race name}/{season}/{session}.png</code></li>
|
||||
</ul>
|
||||
</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>circuits/photos.json</code>, <code>seasons/photos.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>
|
||||
|
||||
<h2>Choosing which API a page calls</h2>
|
||||
@@ -136,6 +161,13 @@
|
||||
<a class="home" href="index.html">All examples</a>
|
||||
<a rel="next" href="circuits.html">Circuit browser →</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>
|
||||
|
||||
+11
-1
@@ -18,8 +18,11 @@
|
||||
<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" aria-current="page">Kometa</a>
|
||||
<a href="library.html">Library</a>
|
||||
<a href="picker.html">Photo picker</a>
|
||||
<a href="licences.html">Licences</a>
|
||||
</nav>
|
||||
<div id="api-base"></div>
|
||||
</header>
|
||||
@@ -80,10 +83,17 @@
|
||||
</main>
|
||||
|
||||
<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 rel="next" href="library.html">Library →</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>
|
||||
|
||||
+11
-1
@@ -18,8 +18,11 @@
|
||||
<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" aria-current="page">Library</a>
|
||||
<a href="picker.html">Photo picker</a>
|
||||
<a href="licences.html">Licences</a>
|
||||
</nav>
|
||||
<div id="api-base"></div>
|
||||
</header>
|
||||
@@ -50,7 +53,14 @@
|
||||
<footer class="pager">
|
||||
<a rel="prev" href="kometa.html">← Kometa</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>
|
||||
|
||||
<script src="site.js"></script>
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
<!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>
|
||||
</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: </licences>; 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><author></code> and
|
||||
<code><licence></code> is filled in with the photo’s own; one with <code><year></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>
|
||||
+21
-6
@@ -20,8 +20,11 @@
|
||||
<a href="map.html" aria-current="page">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">Licences</a>
|
||||
</nav>
|
||||
<div id="api-base"></div>
|
||||
</header>
|
||||
@@ -32,7 +35,7 @@
|
||||
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
|
||||
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>
|
||||
|
||||
<div class="card" id="tree">
|
||||
@@ -65,6 +68,13 @@
|
||||
<a class="home" href="index.html">All examples</a>
|
||||
<a rel="next" href="grand-prix.html">Grand prix lookup →</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>
|
||||
@@ -88,13 +98,18 @@
|
||||
maxZoom: 19,
|
||||
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
|
||||
}).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,
|
||||
maxNativeZoom: 18,
|
||||
attribution: 'Imagery © Esri, Maxar, Earthstar Geographics',
|
||||
maxNativeZoom: 15,
|
||||
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.scale({ imperial: false }).addTo(map);
|
||||
L.control.layers({ 'OpenStreetMap': osm, 'Satellite (EOxCloudless 2025)': satellite }).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('blur', () => map.scrollWheelZoom.disable());
|
||||
|
||||
|
||||
@@ -0,0 +1,763 @@
|
||||
<!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>
|
||||
</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 read from the repository, beside the page’s folder.
|
||||
Run <code>python3 -m http.server</code> in the working copy and open <code>/examples/picker.html</code> there to
|
||||
have both, 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'];
|
||||
const FILES = {
|
||||
candidates: { card: $('cand-file'), url: 'data/candidates.json', what: 'the candidates (examples/data/candidates.json)' },
|
||||
circuits: { card: $('picks-circuits'), url: '../circuits/photos.json', what: 'the layouts’ picks (circuits/photos.json)' },
|
||||
seasons: { card: $('picks-seasons'), url: '../seasons/photos.json', what: 'the seasons’ picks (seasons/photos.json)' },
|
||||
};
|
||||
|
||||
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 '';
|
||||
}
|
||||
|
||||
/** Reads one file over http, or offers to load it from disk when that fails; calls done(value) once read. */
|
||||
async function readFile(name, done) {
|
||||
const f = FILES[name];
|
||||
const card = f.card;
|
||||
const out = card.querySelector('.result');
|
||||
const url = new URL(f.url, location.href).href;
|
||||
setRequest(card.querySelector('.request'), url, name === 'candidates' ? 'a file of the site, not the API' : 'a file of the repository, not the API');
|
||||
setStatus(card.querySelector('.status'), 'pending', `Reading ${f.what}…`);
|
||||
const check = name === 'candidates' ? validCandidates : validPicks;
|
||||
let why = '';
|
||||
try {
|
||||
const res = await fetch(url, { cache: 'no-cache' });
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const value = JSON.parse(await res.text());
|
||||
why = check(value);
|
||||
if (!why) {
|
||||
accept(name, value, `Read ${f.what} from ${url}.`);
|
||||
done(value);
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
why = e instanceof SyntaxError ? 'it is not JSON' : e.message;
|
||||
}
|
||||
setStatus(card.querySelector('.status'), 'error', `Could not read ${f.what}: ${why}.`);
|
||||
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. ',
|
||||
'The page reads it relative to itself; served by the API only /examples/ is there. 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(1)}`) : 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', {}, c.date || '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;
|
||||
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 / Beeldmateriaal Nederland', 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: 'Imagery: USGS', 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>
|
||||
+16
-5
@@ -18,8 +18,11 @@
|
||||
<a href="map.html">GPS traces</a>
|
||||
<a href="grand-prix.html">Grand prix lookup</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="library.html">Library</a>
|
||||
<a href="picker.html">Photo picker</a>
|
||||
<a href="licences.html">Licences</a>
|
||||
</nav>
|
||||
<div id="api-base"></div>
|
||||
</header>
|
||||
@@ -44,14 +47,15 @@
|
||||
<div class="grid-2">
|
||||
<section class="card" id="race-poster">
|
||||
<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">
|
||||
<label><span>Background (<code>bg</code>)</span>
|
||||
<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="dark">dark: Esri Dark Gray Canvas</option>
|
||||
<option value="light">light: Esri Light Gray Canvas</option>
|
||||
<option value="dark">dark: OpenStreetMap, recoloured dark</option>
|
||||
<option value="light">light: OpenStreetMap, recoloured light</option>
|
||||
<option value="none">none: plain black, no tiles (fastest)</option>
|
||||
</select>
|
||||
</label>
|
||||
@@ -101,7 +105,14 @@
|
||||
<footer class="pager">
|
||||
<a rel="prev" href="grand-prix.html">← Grand prix lookup</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>
|
||||
|
||||
<script src="site.js"></script>
|
||||
|
||||
@@ -44,6 +44,9 @@
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
/* An element hidden by the page stays hidden, whatever display its class gives it. */
|
||||
[hidden] { display: none !important; }
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
@@ -353,3 +356,92 @@ a.tile-link:hover .tile-frame { outline: 3px solid var(--accent); }
|
||||
@media (prefers-reduced-motion: reduce) { .spinner { animation-duration: 4s; } }
|
||||
.waiting { display: flex; gap: 1rem; align-items: center; }
|
||||
.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; }
|
||||
|
||||
+11
-5
@@ -182,7 +182,7 @@
|
||||
return null;
|
||||
}
|
||||
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. */
|
||||
@@ -243,10 +243,13 @@
|
||||
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) {
|
||||
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] === 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();
|
||||
if (text.startsWith('<?xml') || text.startsWith('<svg')) return 'svg';
|
||||
if (text.startsWith('{') || text.startsWith('[')) return 'json';
|
||||
@@ -261,9 +264,11 @@
|
||||
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
|
||||
* (loudly) and shows what came back.
|
||||
* Shows an image answer. `expected` is 'png', 'jpg', 'webp' or 'svg'; when the body is something else,
|
||||
* says so first (loudly) and shows what came back.
|
||||
*/
|
||||
async function showImage(el, answer, expected, opts = {}) {
|
||||
const got = await sniff(answer.blob);
|
||||
@@ -273,7 +278,8 @@
|
||||
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}).`));
|
||||
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:'));
|
||||
} else if (expected === 'svg') {
|
||||
blob = new Blob([blob], { type: 'image/svg+xml' });
|
||||
|
||||
@@ -18,8 +18,11 @@
|
||||
<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">Licences</a>
|
||||
</nav>
|
||||
<div id="api-base"></div>
|
||||
</header>
|
||||
@@ -80,6 +83,13 @@
|
||||
<a class="home" href="index.html">All examples</a>
|
||||
<a rel="next" href="map.html">GPS traces →</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>
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
"""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 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 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()
|
||||
@@ -0,0 +1,488 @@
|
||||
#!/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.
|
||||
|
||||
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 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"]] = c
|
||||
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())
|
||||
Reference in New Issue
Block a user