Merge pull request 'Posters from licensed sources only: kept layers, options, credits on every picture' (#8) from feat/poster-layers into master
This commit was merged in pull request #8.
This commit is contained in:
@@ -4,3 +4,6 @@ __pycache__/
|
||||
cache/
|
||||
.idea/
|
||||
.venv-site/
|
||||
# The poster service's kept layers and finished pictures, when run from here
|
||||
/layers/
|
||||
/posters/
|
||||
|
||||
@@ -10,6 +10,8 @@ Kometa.
|
||||
* **The data**: [circuits/circuits.json](circuits/circuits.json) and one folder per circuit under
|
||||
[circuits/](circuits/) — 77 circuits, 122 layouts
|
||||
|
||||
How posters are made (sources and their licences, kept layers, options, credits): [docs/posters.md](docs/posters.md).
|
||||
|
||||
## The API
|
||||
|
||||
| Request | Answers |
|
||||
@@ -22,10 +24,25 @@ Kometa.
|
||||
| `GET /circuits/{country}/{locality}/{circuit}/layout/{layout}/{format}` | the layout's file: `geojson`, `svg` or `png` |
|
||||
| `GET /tracks/{country}/{locality}/{circuit}/year/{year}/{format}` | the layout the circuit used that year |
|
||||
| `GET /grand-prix/{race}/{season}/{format}` | the layout a race ran on, such as `/grand-prix/Qatar Grand Prix/2025/geojson` |
|
||||
| `GET /posters/race/{race}/{season}.png?bg=…` | a 1000×1500 race poster; `bg` is `aerial` (default), `osm`, `dark`, `light` or `none` |
|
||||
| `GET /posters/season/{season}.png` | a 1000×1500 season poster |
|
||||
| `GET /posters/session/{race}/{season}/{session}.png` | a 1920×1080 thumbnail for one session, such as `fp1`, `qualifying`, `sprint` or `race` |
|
||||
| `GET /posters/race/{race}/{season}.png?…` | a 1000×1500 race poster: the round, the race's name and date and its track over a picture of its circuit |
|
||||
| `GET /posters/season/{season}.png?…` | a 1000×1500 season poster: the year over a picked photo of that season's cars, or over black |
|
||||
| `GET /posters/session/{race}/{season}/{session}.png?…` | a 1920×1080 thumbnail for one session, such as `fp1`, `qualifying`, `sprint` or `race` |
|
||||
| `GET /kometa/formula-1-metadata.yml` | [Kometa](https://kometa.wiki/) metadata that sets these posters on a Plex Formula 1 library |
|
||||
| `GET /licences` | every source a picture may be made from: its licence, its credit and its terms, and how a picture's licence follows from them |
|
||||
|
||||
The three picture routes take the same options as query parameters ([docs/posters.md](docs/posters.md) lists
|
||||
them): `style` (`classic`, `minimal`), `bg` (`satellite`, its alias `aerial`, `photo`, `osm`, `dark`, `light`, `none`),
|
||||
`photo` (`natural`, `bw`), `show` (a comma list of `wordmark`, `round`, `name`, `subtitle`, `date`, `circuit`,
|
||||
`locality`, `session`), `locator` and `checker` (`on`, `off`), `track` (`off`, or a colour with an optional width,
|
||||
`#ffffff,6`), `dim` (0 to 1), `accent` (a colour), `width` (400 up to the picture's own) and `format` (`png`, `jpg`,
|
||||
`webp`). An unknown option or value is answered 422, naming it. `bg=satellite` takes the national aerial photo
|
||||
(USGS in the United States, PDOK in the Netherlands, IGN in France), else EOxCloudless; `{"use": "map"}` for a
|
||||
layout in [circuits/photos.json](circuits/photos.json) makes it draw the dark map instead of EOxCloudless. `bg=photo`
|
||||
takes the layout's picked Wikimedia Commons photo from that file, with the track as an inset, and without a pick
|
||||
falls back to `bg=satellite`; no style takes it by default. Every picture carries the credit line of its sources at its
|
||||
bottom and in `X-Credits`, its licence in `X-License` (it follows its sources), and `Link: </licences>; rel="license"`.
|
||||
|
||||
An unknown country, locality, circuit or layout, or a year no layout of the circuit covers, is answered 404, naming it.
|
||||
|
||||
A race is named as [Jolpica](https://github.com/jolpica/jolpica-f1) (the Ergast API's successor) names it in
|
||||
its schedule, and its circuit is found by Jolpica's circuit id (`ergastId` in `circuits.json`), never by the
|
||||
@@ -131,18 +148,26 @@ rate limit and kept in `cache/jolpica/`; a throttled or failed fetch is said in
|
||||
|
||||
## Caching
|
||||
|
||||
What the service fetches or renders is kept in `cache/` (the module's cache volume): race schedules from Jolpica
|
||||
in `cache/jolpica/` (a season that is over for good, the running one for six hours), and every poster and thumbnail
|
||||
in `cache/posters/` once every map tile and photo it needs came. A poster is sent with an `ETag` and a day's
|
||||
`Cache-Control`; one whose map or photo failed is not kept, and is sent with five minutes', so it is rendered again
|
||||
once its source answers. Map tiles are fetched in parallel, at most six at once from Esri and two from
|
||||
OpenStreetMap.
|
||||
Race schedules from Jolpica are kept in `cache/jolpica/` (a season that is over for good, the running one for six
|
||||
hours). What a picture needs from the network is a layer, kept for good in `layers/` (the module's `layers` directory,
|
||||
backed up and fetched again if lost): the map picture of one source around a layout, a picked photo cropped to the
|
||||
picture, the world locator and the track's outline. A layer is kept only whole, when every tile came and they are
|
||||
not all one picture. Every finished picture is kept in `posters/` under a key of its route, its options and its
|
||||
layers, at most 2 GB, the least recently used going first; a second season of a circuit draws from the kept layers
|
||||
and fetches nothing. A picture whose map or photo did not arrive is served without it, kept nowhere, and sent with
|
||||
five minutes' `Cache-Control` and no `ETag`.
|
||||
|
||||
Clients keep an address that carries the render version (`?v=r3`, as the Kometa file writes it) for good
|
||||
(`immutable`); any other address a day, then ask again with its `ETag` and get a 304 while it is unchanged. Every
|
||||
request the service makes carries the User-Agent `f1-circuits/<version> (+<its public address>)`. OpenStreetMap tiles
|
||||
are fetched only when a picture asks for them, at most two at once; Wikimedia Commons is asked one request at a time.
|
||||
|
||||
## Checks
|
||||
|
||||
`merge-check.sh` runs before a change merges: every Python file the service ships must parse, and the tests in
|
||||
`tests/` must pass (every circuit has one unique `ergastId`, a race resolves by it, a failed Jolpica fetch is never
|
||||
kept, every link in this README leads to a file).
|
||||
kept, every link in this README leads to a file, an unknown circuit or layout is named; a poster's satellite source,
|
||||
credits and licence, its options, keys and cache headers, and the picture store's cap).
|
||||
|
||||
## Acknowledgment
|
||||
|
||||
@@ -150,8 +175,9 @@ kept, every link in this README leads to a file).
|
||||
[initial data source](https://www.google.com/maps/d/u/0/viewer?mid=1nv6ugq4H67CSzKUauW92-pPstYw&ll=-37.84579005412956%2C144.96881158570557&z=16)
|
||||
and altitudes (from [Highs and lows - which F1 track has the most elevation changes?](https://www.formula1.com/en/latest/features/2016/10/highs-and-lows---which-f1-track-has-the-most-elevation-changes-.html))
|
||||
are kept in the upstream files.
|
||||
* Race schedules from [Jolpica](https://github.com/jolpica/jolpica-f1); poster backgrounds from Esri (World Imagery
|
||||
and the grey canvases) and OpenStreetMap.
|
||||
* Race schedules from [Jolpica](https://github.com/jolpica/jolpica-f1) (CC BY-NC-SA 4.0); the posters' pictures from
|
||||
Wikimedia Commons, USGS, PDOK (Beeldmateriaal Nederland), IGN, EOX (EOxCloudless) and OpenStreetMap, each under
|
||||
its licence and with its credit: `/licences` and [docs/posters.md](docs/posters.md).
|
||||
|
||||
## Disclaimer
|
||||
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
"""Who this service is to the outside: its version, its public address and the User-Agent it sends.
|
||||
|
||||
Standard library only: the Jolpica client, the poster sources and the API share it.
|
||||
"""
|
||||
import os
|
||||
|
||||
# The API's own version (cdn-api.py's FastAPI app says the same).
|
||||
APP_VERSION = "1.0.0"
|
||||
|
||||
# The address this service is reached at, which the Kometa metadata links every poster to and every outgoing
|
||||
# request names. The mesh writes it from the name the route is served under (F1_CIRCUITS_BASE_URL); the fallback
|
||||
# is the address HAL served it at, so a deployment that sets nothing behaves as before.
|
||||
PUBLIC_BASE_URL = os.environ.get("F1_CIRCUITS_BASE_URL", "https://f1-circuits.zurag.be").rstrip("/")
|
||||
|
||||
# Every outgoing request carries it (Jolpica, the map and photo sources): the app's name and its public address,
|
||||
# never a person's address.
|
||||
USER_AGENT = f"f1-circuits/{APP_VERSION} (+{PUBLIC_BASE_URL})"
|
||||
+99
-73
@@ -1,32 +1,42 @@
|
||||
import hashlib
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Request, Response
|
||||
from fastapi.responses import FileResponse, Response as FastAPIResponse, PlainTextResponse
|
||||
from fastapi.openapi.docs import get_swagger_ui_html
|
||||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, PlainTextResponse
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
import logging
|
||||
|
||||
# Import our CircuitService
|
||||
from circuits_service import CircuitService, Format
|
||||
from posters_service import PostersService, BackgroundStyle
|
||||
from app_info import APP_VERSION
|
||||
from circuits_service import CircuitService, Format, NotFound
|
||||
from posters_service import PostersService, Rendered
|
||||
import poster_options
|
||||
import poster_sources
|
||||
from access_log import log_request
|
||||
from models.track_layout import TrackLayout
|
||||
|
||||
# Initialize FastAPI app
|
||||
# The unofficial-use disclaimer for the Formula 1 marks, at the foot of / and /docs (and of the example site).
|
||||
DISCLAIMER = ("This service is unofficial and is not associated in any way with the Formula 1 companies. F1, FORMULA "
|
||||
"ONE, FORMULA 1, FIA FORMULA ONE WORLD CHAMPIONSHIP, GRAND PRIX, and related marks are trademarks of "
|
||||
"Formula One Licensing B.V.")
|
||||
|
||||
# Initialize FastAPI app; /docs is served below, with the disclaimer at its foot
|
||||
app = FastAPI(
|
||||
title="F1 Track Layouts API",
|
||||
description="API serving F1 track layout images, vectors and GeoJSON files",
|
||||
version="1.0.0"
|
||||
version=APP_VERSION,
|
||||
docs_url=None,
|
||||
)
|
||||
|
||||
# Add CORS middleware
|
||||
# Add CORS middleware. The example pages, opened from another origin, read a picture's credits and licence.
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
expose_headers=["X-Credits", "X-License", "Link", "ETag"],
|
||||
)
|
||||
|
||||
# Configure logging
|
||||
@@ -84,11 +94,29 @@ async def root():
|
||||
"/posters/season/{season}.png",
|
||||
"/posters/session/{grand_prix_name}/{season}/{session_slug}.png",
|
||||
"/kometa/formula-1-metadata.yml",
|
||||
"/licences",
|
||||
],
|
||||
"examples": "/examples/",
|
||||
"disclaimer": DISCLAIMER,
|
||||
}
|
||||
|
||||
|
||||
@app.get("/docs", include_in_schema=False)
|
||||
async def docs() -> HTMLResponse:
|
||||
"""The OpenAPI docs, with the disclaimer at their foot."""
|
||||
page = get_swagger_ui_html(openapi_url=app.openapi_url, title=f"{app.title} - docs").body.decode()
|
||||
footer = (f'<footer style="font-family: sans-serif; font-size: 12px; color: #666; margin: 2em; '
|
||||
f'text-align: center">{DISCLAIMER}</footer>')
|
||||
return HTMLResponse(page.replace("</body>", f"{footer}</body>"))
|
||||
|
||||
|
||||
@app.get("/licences")
|
||||
async def get_licences():
|
||||
"""Every source a picture may be made from: its licence, its credit and its terms' address, and how a picture's
|
||||
licence follows from them."""
|
||||
return poster_sources.licences()
|
||||
|
||||
|
||||
# The example site: one page per area of the API, each calling the routes above (examples/index.html).
|
||||
app.mount(
|
||||
"/examples",
|
||||
@@ -100,66 +128,77 @@ app.mount(
|
||||
# The poster routes are plain defs, not async: a render fetches map tiles and a schedule and draws for
|
||||
# seconds, so it runs in the threadpool instead of holding up every other request on the event loop.
|
||||
|
||||
def poster_response(request: Request, png: bytes, kept: bool) -> Response:
|
||||
"""A stored poster: clients keep it a day, then ask again with its ETag and get a 304 while it is
|
||||
unchanged, so a poster whose look changed reaches them within a day, not a year. A poster whose map
|
||||
or photo failed is kept by clients for five minutes, with no ETag, so they ask again soon."""
|
||||
if not kept:
|
||||
return FastAPIResponse(content=png, media_type="image/png", headers={"Cache-Control": "public, max-age=300"})
|
||||
etag = '"' + hashlib.sha256(png).hexdigest()[:32] + '"'
|
||||
headers = {"Cache-Control": "public, max-age=86400", "ETag": etag}
|
||||
if etag in [tag.strip().removeprefix("W/") for tag in request.headers.get("if-none-match", "").split(",")]:
|
||||
POSTER_OPTIONS_DOC = """Options are query parameters, the same on every poster route (docs/posters.md); an unknown option
|
||||
or value is answered 422, naming it: `style` (classic, minimal), `bg` (satellite, its alias aerial, photo, osm,
|
||||
dark, light, none), `photo` (natural, bw), `show` (a comma list of wordmark, round, name, subtitle, date, circuit,
|
||||
locality, session), `locator` and `checker` (on, off), `track` (off, or #rrggbb with an optional width:
|
||||
#ffffff,6), `dim` (0 to 1), `accent` (#rrggbb), `width` (400 up to the frame's), `format` (png, jpg, webp), and
|
||||
`v`, the render version, which the Kometa file adds so clients keep the picture for good."""
|
||||
|
||||
|
||||
def render_poster(request: Request, kind: str, grand_prix_name: Optional[str] = None, season: Optional[int] = None,
|
||||
session_slug: Optional[str] = None) -> Response:
|
||||
"""A picture with its credits, its licence and what clients may keep of it.
|
||||
|
||||
An address with the current render version (?v=) is kept for good; any other a day, then asked again with its
|
||||
ETag (a 304 while it is unchanged); a picture served without its map or photo five minutes, with no ETag."""
|
||||
try:
|
||||
options = poster_options.parse_options(request.query_params.multi_items(), kind)
|
||||
except poster_options.OptionError as e:
|
||||
return JSONResponse(status_code=422, content={"detail": str(e)})
|
||||
try:
|
||||
rendered: Optional[Rendered] = posters_service.render(kind, options, grand_prix_name, season, session_slug)
|
||||
except poster_sources.LicenceClash as e:
|
||||
logger.error(f"Picture refused, {kind} {grand_prix_name} {season} {session_slug}: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"Picture refused: {e}")
|
||||
if rendered is None:
|
||||
what = " ".join(str(part) for part in (grand_prix_name, season, session_slug) if part is not None)
|
||||
raise HTTPException(status_code=404, detail=f"No {kind} picture available for {what}")
|
||||
# Weak: two first renders of one key side by side may differ in their bytes, never in what they show.
|
||||
etag = 'W/"' + rendered.name.split(".")[0][:32] + '"'
|
||||
headers = poster_options.cache_headers(rendered.kept, options.versioned, etag)
|
||||
headers.update({"X-Credits": poster_sources.ascii_header(rendered.credit), "X-License": rendered.licence,
|
||||
"Link": '</licences>; rel="license"'})
|
||||
if rendered.kept and poster_options.etag_matches(request.headers.get("if-none-match", ""), etag):
|
||||
return Response(status_code=304, headers=headers)
|
||||
return FastAPIResponse(content=png, media_type="image/png", headers=headers)
|
||||
return Response(content=rendered.data, media_type=rendered.media_type, headers=headers)
|
||||
|
||||
|
||||
@app.get("/posters/race/{grand_prix_name}/{season}.png")
|
||||
def get_race_poster(request: Request, grand_prix_name: str, season: int, bg: BackgroundStyle = BackgroundStyle.AERIAL):
|
||||
"""Plex-ready 1000x1500 race poster (PNG). Cached on disk per (race, bg).
|
||||
|
||||
`?bg=` selects the backdrop:
|
||||
- aerial (default) — Esri World Imagery satellite at the circuit's coords
|
||||
- osm — OpenStreetMap Carto street-map at the circuit's coords
|
||||
- dark — Esri Dark Gray Canvas
|
||||
- light — Esri Light Gray Canvas
|
||||
- none — plain black background (skip tile fetch)
|
||||
"""
|
||||
rendered = posters_service.render_race_poster(grand_prix_name, season, bg=bg)
|
||||
if not rendered:
|
||||
raise HTTPException(status_code=404, detail=f"No poster available for {grand_prix_name} {season}")
|
||||
return poster_response(request, *rendered)
|
||||
@app.get("/posters/race/{grand_prix_name}/{season}.png", description=POSTER_OPTIONS_DOC)
|
||||
def get_race_poster(request: Request, grand_prix_name: str, season: int):
|
||||
"""Plex-ready 1000x1500 race poster: the round, the race's name and date and its track over a map or photo of
|
||||
its circuit."""
|
||||
return render_poster(request, "race", grand_prix_name, season)
|
||||
|
||||
|
||||
@app.get("/posters/season/{season}.png")
|
||||
@app.get("/posters/season/{season}.png", description=POSTER_OPTIONS_DOC)
|
||||
def get_season_poster(request: Request, season: int):
|
||||
"""Plex-ready 1000x1500 season poster (PNG). Cached on disk."""
|
||||
return poster_response(request, *posters_service.render_season_poster(season))
|
||||
"""Plex-ready 1000x1500 season poster: the year over a picked photo of that season's cars, or over black."""
|
||||
return render_poster(request, "season", season=season)
|
||||
|
||||
|
||||
@app.get("/posters/session/{grand_prix_name}/{season}/{session_slug}.png")
|
||||
@app.get("/posters/session/{grand_prix_name}/{season}/{session_slug}.png", description=POSTER_OPTIONS_DOC)
|
||||
def get_session_thumb(request: Request, grand_prix_name: str, season: int, session_slug: str):
|
||||
"""Plex episode-thumb (1920x1080) for a specific session of a race weekend.
|
||||
"""Plex episode-thumb (1920x1080) for one session of a race weekend.
|
||||
|
||||
`session_slug` is one of: fp1, fp2, fp3, pre-qualifying, qualifying,
|
||||
post-qualifying, pre-race, race, post-race, highlights, pre-sprint,
|
||||
sprint, post-sprint, pre-sprint-qualifying, sprint-qualifying,
|
||||
post-sprint-qualifying, bonus.
|
||||
"""
|
||||
rendered = posters_service.render_session_thumb(grand_prix_name, season, session_slug)
|
||||
if not rendered:
|
||||
raise HTTPException(status_code=404, detail=f"No session thumb for {grand_prix_name} {season} {session_slug}")
|
||||
return poster_response(request, *rendered)
|
||||
return render_poster(request, "session", grand_prix_name, season, session_slug)
|
||||
|
||||
|
||||
@app.get("/kometa/formula-1-metadata.yml")
|
||||
def get_kometa_metadata():
|
||||
"""Generate a Kometa-compatible metadata YAML for the Formula 1 library.
|
||||
|
||||
One entry per F1 season from 1950..current+1. Each entry:
|
||||
Its first lines say where its data comes from (Jolpica, CC BY-NC-SA 4.0). One entry per F1 season from
|
||||
1950..current+1. Each entry:
|
||||
- uses Kometa's f1_season builder for round/episode names
|
||||
- sets url_poster on the show (per-season hero from files-api)
|
||||
- sets url_poster on each Plex 'season' (== each F1 round) from the
|
||||
f1-circuits race poster endpoint
|
||||
- sets url_poster on the show (the season poster)
|
||||
- sets url_poster on each Plex 'season' (== each F1 round) from the race poster route, and on each episode
|
||||
from the session thumbnail route; every address carries ?v=<render version>
|
||||
|
||||
Kometa harmlessly skips shows / seasons that don't exist in the Plex
|
||||
library, so we can emit the full schedule and let Kometa do the matching.
|
||||
@@ -182,37 +221,31 @@ async def get_countries():
|
||||
"countries": [c.to_dict() for c in circuit_service.get_countries_list()]
|
||||
}
|
||||
|
||||
@app.exception_handler(NotFound)
|
||||
async def not_found(request: Request, error: NotFound) -> JSONResponse:
|
||||
"""A country, locality, circuit or layout circuits.json does not hold, or a year no layout covers: named."""
|
||||
return JSONResponse(status_code=404, content={"detail": str(error)})
|
||||
|
||||
|
||||
@app.get("/circuits/{country_slug}")
|
||||
async def get_cities(country_slug: str):
|
||||
"""Get list of cities for a specific country"""
|
||||
cities = circuit_service.get_localities_list(country_slug)
|
||||
if not cities:
|
||||
raise HTTPException(status_code=404, detail="Country not found")
|
||||
return {"cities": [c.to_dict() for c in cities]}
|
||||
return {"cities": [c.to_dict() for c in circuit_service.get_localities_list(country_slug)]}
|
||||
|
||||
@app.get("/circuits/{country_slug}/{city_slug}")
|
||||
async def get_circuits(country_slug: str, city_slug: str):
|
||||
"""Get list of circuits for a specific city"""
|
||||
circuits = circuit_service.get_circuits_list(country_slug, city_slug)
|
||||
if not circuits:
|
||||
raise HTTPException(status_code=404, detail="City not found")
|
||||
return {"circuits": [c.to_dict() for c in circuits]}
|
||||
return {"circuits": [c.to_dict() for c in circuit_service.get_circuits_list(country_slug, city_slug)]}
|
||||
|
||||
@app.get("/circuits/{country_slug}/{city_slug}/{circuit_slug}")
|
||||
async def get_circuit_details(country_slug: str, city_slug: str, circuit_slug: str):
|
||||
"""Get circuit details and available formats"""
|
||||
circuit_details = circuit_service.get_circuit_details(country_slug, city_slug, circuit_slug)
|
||||
if not circuit_details:
|
||||
raise HTTPException(status_code=404, detail="Circuit not found")
|
||||
return circuit_details.to_dict()
|
||||
return circuit_service.resolve(country_slug, city_slug, circuit_slug).to_dict()
|
||||
|
||||
@app.get("/circuits/{country_slug}/{city_slug}/{circuit_slug}/layout/{layout_slug}")
|
||||
async def get_layout_details(country_slug: str, city_slug: str, circuit_slug: str, layout_slug: str):
|
||||
"""Get details for a specific layout"""
|
||||
layout_details = circuit_service.get_layout_details(country_slug, city_slug, circuit_slug, layout_slug)
|
||||
if not layout_details:
|
||||
raise HTTPException(status_code=404, detail="Layout not found")
|
||||
return layout_details.to_dict()
|
||||
return circuit_service.resolve(country_slug, city_slug, circuit_slug, layout_slug).to_dict()
|
||||
|
||||
@app.get("/tracks/{country_slug}/{city_slug}/{circuit_slug}/year/{year}/{image_format}")
|
||||
async def get_track_by_year(
|
||||
@@ -224,16 +257,8 @@ async def get_track_by_year(
|
||||
response: Response
|
||||
):
|
||||
"""Get track layout for a specific year"""
|
||||
circuit_details = circuit_service.get_circuit_details(country_slug, city_slug, circuit_slug)
|
||||
if not circuit_details:
|
||||
raise HTTPException(status_code=404, detail="Circuit not found")
|
||||
|
||||
try:
|
||||
layout_slug = circuit_service.find_layout_slug_for_year(circuit_details, year)
|
||||
return get_file_response(circuit_service.get_layout_details(country_slug, city_slug, circuit_slug, layout_slug), image_format, response)
|
||||
except KeyError as e:
|
||||
logger.error(f"KeyError in get_track_by_year: {str(e)}")
|
||||
raise HTTPException(status_code=404, detail="Circuit or layout not found")
|
||||
return get_file_response(circuit_service.layout_for_year(country_slug, city_slug, circuit_slug, year),
|
||||
image_format, response)
|
||||
|
||||
@app.get("/circuits/{country_slug}/{city_slug}/{circuit_slug}/layout/{layout_slug}/{image_format}")
|
||||
async def get_track_by_layout(
|
||||
@@ -245,7 +270,8 @@ async def get_track_by_layout(
|
||||
response: Response
|
||||
):
|
||||
"""Get specific track layout"""
|
||||
return get_file_response(circuit_service.get_layout_details(country_slug, city_slug, circuit_slug, layout_slug), image_format, response)
|
||||
return get_file_response(circuit_service.resolve(country_slug, city_slug, circuit_slug, layout_slug),
|
||||
image_format, response)
|
||||
|
||||
@app.get("/grand-prix/{grand_prix_name}/{season}/{image_format}")
|
||||
def get_grand_prix_circuit(grand_prix_name: str, season: int, image_format: Format, response: Response):
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"$comment": "The picked Wikimedia Commons aerial photo per layout (docs/posters.md, Picking photos). Key: the layout's path under circuits/ without extension, country/city/circuit/layout, such as \"belgium/spa/circuit-de-spa-francorchamps/1983-\". Value: the photo fields {\"file\": the Commons title without \"File:\", \"licence\": its LicenseShortName (CC0, public domain, CC BY or CC BY-SA only), \"author\", \"credit\": \"Photo: <author>, <licence>, via Wikimedia Commons\", \"date\": YYYY[-MM[-DD]]}, which bg=photo draws; \"use\": \"map\", which makes bg=satellite draw the dark OpenStreetMap map instead of EOxCloudless (a national aerial photo still comes first); or both. Written by the picking tool, read by the poster service; a key starting with \"$\" is a note, not a pick."
|
||||
}
|
||||
+51
-13
@@ -12,6 +12,11 @@ from models.model_builder import parse_circuits_json
|
||||
from models.track_layout import TrackLayout
|
||||
|
||||
|
||||
class NotFound(LookupError):
|
||||
"""A country, locality, circuit or layout circuits.json does not hold, or a year no layout covers: answered 404,
|
||||
naming it."""
|
||||
|
||||
|
||||
# Define supported formats
|
||||
class Format(str, Enum):
|
||||
PNG = "png"
|
||||
@@ -69,6 +74,31 @@ class CircuitService:
|
||||
return layout_slug
|
||||
return None
|
||||
|
||||
def resolve(self, country_slug: str, locality_slug: Optional[str] = None, circuit_slug: Optional[str] = None,
|
||||
layout_slug: Optional[str] = None):
|
||||
"""The country, locality, circuit or layout the given slugs lead to (the deepest one given); NotFound names
|
||||
the first that circuits.json does not hold."""
|
||||
found = self.circuit_data.get(country_slug)
|
||||
if found is None:
|
||||
raise NotFound(f"No country {country_slug!r}")
|
||||
for kind, slug, children in (("locality", locality_slug, "localities"), ("circuit", circuit_slug, "circuits"),
|
||||
("layout", layout_slug, "layouts")):
|
||||
if slug is None:
|
||||
return found
|
||||
parent = found
|
||||
found = getattr(parent, children).get(slug)
|
||||
if found is None:
|
||||
raise NotFound(f"No {kind} {slug!r} in {getattr(parent, 'name', None) or getattr(parent, 'slug', '')}")
|
||||
return found
|
||||
|
||||
def layout_for_year(self, country_slug: str, locality_slug: str, circuit_slug: str, year: int) -> TrackLayout:
|
||||
"""The layout a circuit used in a year; NotFound when the circuit is unknown or no layout covers the year."""
|
||||
circuit = self.resolve(country_slug, locality_slug, circuit_slug)
|
||||
layout_slug = self.find_layout_slug_for_year(circuit, year)
|
||||
if layout_slug is None:
|
||||
raise NotFound(f"No layout of {circuit.name} covers {year}")
|
||||
return circuit.layouts[layout_slug]
|
||||
|
||||
def get_countries_list(self) -> Optional[list[Country]]:
|
||||
"""Get list of all available countries with their slugs"""
|
||||
return [country for _, country in self.circuit_data.items()]
|
||||
@@ -77,26 +107,34 @@ class CircuitService:
|
||||
"""Get details for a specific country"""
|
||||
return self.circuit_data.get(country_slug)
|
||||
|
||||
def get_localities_list(self, country_slug: str) -> Optional[list[Locality]]:
|
||||
"""Get list of cities for a specific country"""
|
||||
return [locality for _, locality in self.circuit_data[country_slug].localities.items()]
|
||||
def get_localities_list(self, country_slug: str) -> list[Locality]:
|
||||
"""The localities of a country; NotFound when it is unknown"""
|
||||
return list(self.resolve(country_slug).localities.values())
|
||||
|
||||
def get_locality_details(self, country_slug: str, locality_slug: str) -> Optional[Locality]:
|
||||
"""Get details for a specific city"""
|
||||
return self.circuit_data[country_slug].localities.get(locality_slug)
|
||||
"""Get details for a specific city; None when it is unknown"""
|
||||
try:
|
||||
return self.resolve(country_slug, locality_slug)
|
||||
except NotFound:
|
||||
return None
|
||||
|
||||
def get_circuits_list(self, country_slug: str, locality_slug: str) -> Optional[list[Circuit]]:
|
||||
"""Get list of circuits for a specific city"""
|
||||
return [circuit_data for _, circuit_data in self.circuit_data[country_slug].localities.get(locality_slug).circuits.items()]
|
||||
def get_circuits_list(self, country_slug: str, locality_slug: str) -> list[Circuit]:
|
||||
"""The circuits of a locality; NotFound when it is unknown"""
|
||||
return list(self.resolve(country_slug, locality_slug).circuits.values())
|
||||
|
||||
def get_circuit_details(self, country_slug: str, locality_slug: str, circuit_slug: str) -> Optional[Circuit]:
|
||||
"""Get circuit details and available formats"""
|
||||
return self.circuit_data[country_slug].localities.get(locality_slug).circuits.get(circuit_slug)
|
||||
"""Get circuit details and available formats; None when it is unknown"""
|
||||
try:
|
||||
return self.resolve(country_slug, locality_slug, circuit_slug)
|
||||
except NotFound:
|
||||
return None
|
||||
|
||||
def get_layout_details(self, country_slug: str, locality_slug: str, circuit_slug: str, layout_slug: str) -> Optional[TrackLayout]:
|
||||
"""Get details for a specific layout"""
|
||||
return self.circuit_data[country_slug].localities.get(locality_slug).circuits.get(circuit_slug).layouts.get(
|
||||
layout_slug)
|
||||
"""Get details for a specific layout; None when it is unknown"""
|
||||
try:
|
||||
return self.resolve(country_slug, locality_slug, circuit_slug, layout_slug)
|
||||
except NotFound:
|
||||
return None
|
||||
|
||||
def get_circuit_layout_by_ergast_data(self, grand_prix_name: str, season: int) -> Optional[TrackLayout]:
|
||||
"""
|
||||
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
# Posters: sources, layers, options and credits
|
||||
|
||||
How F1 Circuits makes its race posters, season posters and session thumbnails: where every picture comes
|
||||
from and under which licence, what it fetches once and keeps, what it draws on every request, which options a
|
||||
caller has, and how every image says where it comes from. Decided with the operator on 2026-11-27, after
|
||||
reading each source's own terms; the lead's answers to the builders' questions are written in where they
|
||||
belong.
|
||||
|
||||
## Principles
|
||||
|
||||
1. **Every source is used only as its terms allow, and says so.** The credit each source asks for is drawn on
|
||||
every image made from it, sent in a header, and listed on the licences page. A caller cannot switch it off.
|
||||
2. **Static is kept.** The circuits, their layouts and finished seasons do not change, so what is made from
|
||||
them is fetched or rendered once and kept. Nothing expires; a changed input makes a new key.
|
||||
3. **Heavy once, light every time.** What needs the network (a map, a photo) is a kept layer. What a caller
|
||||
can choose (texts, colours, treatment, size, format) is drawn on the fly from the kept layers.
|
||||
4. **Whole or not at all.** A layer is kept only when every part of it arrived. A picture whose layer did not
|
||||
arrive is served without it, for five minutes, and not kept.
|
||||
|
||||
## Sources
|
||||
|
||||
Only sources whose licence allows keeping a copy for good are used. Esri, Bing, Azure Maps, Google, Mapbox and
|
||||
MapTiler are not: their terms forbid automated fetching, keeping, or serving images made from their maps to the
|
||||
public.
|
||||
|
||||
| Source | Used for | Licence | Credit drawn on the image |
|
||||
|:---|:---|:---|:---|
|
||||
| USGS imagery (USGSImageryOnly, to zoom 16), United States | `bg=satellite` for circuits in the US | public domain | `USDA, USGS The National Map: Orthoimagery` |
|
||||
| PDOK aerial photo (Actueel_orthoHR), the Netherlands | `bg=satellite` for circuits in the Netherlands | CC BY 4.0 | `Luchtfoto: PDOK / Samenwerkingsverband Beeldmateriaal, CC BY 4.0` |
|
||||
| IGN, the frozen mosaic ORTHOIMAGERY.ORTHOPHOTOS2021-2023, France | `bg=satellite` for circuits in France | Licence Ouverte (Etalab) 2.0 | `© IGN – BD ORTHO, 2021–2023` |
|
||||
| EOxCloudless, the newest mosaic (2025) | `bg=satellite` everywhere else | CC BY-NC-SA 4.0 | `EOxCloudless https://cloudless.eox.at by EOX IT Services GmbH (Contains modified Copernicus Sentinel data 2025)` |
|
||||
| OpenStreetMap standard tiles | `bg=osm`, `bg=dark`, `bg=light` (recoloured), the world locator, and a layout switched to the map | ODbL (data), tile usage policy | `© OpenStreetMap contributors` |
|
||||
| Wikimedia Commons photo, picked per layout or per season | `bg=photo`; season posters | per file: CC0, public domain, CC BY or CC BY-SA only | `Photo: <author>, <licence>, via Wikimedia Commons` |
|
||||
| Jolpica F1 API | race schedules: names, rounds, dates | CC BY-NC-SA 4.0 | in the docs and the Kometa file |
|
||||
| The circuits' GPS traces and layouts | track outlines, track files | MIT (LICENSE.md) | in the docs |
|
||||
|
||||
IGN's yearly layers cover only the départements flown that year, so a frame near a border falls into a hole;
|
||||
the 2021–2023 mosaic covers the whole country, and its frozen date range is the date the Etalab licence asks
|
||||
for. EOX's 2016 mosaic (CC BY 4.0) was rejected by the operator: too soft to read a circuit. (EOX's
|
||||
capabilities also mark 2017 as CC BY 4.0.)
|
||||
|
||||
**`bg=satellite`** (and `aerial`, kept for addresses already in use) takes, per layout, the national aerial
|
||||
photo of the circuit's country, else EOX's newest mosaic. The operator can switch a layout to the dark
|
||||
OpenStreetMap map, where EOX is too soft to read the circuit: `"use": "map"` in its entry of
|
||||
`circuits/photos.json`; a national source still wins, as it is sharper. **`bg=photo`** draws the layout's picked
|
||||
Commons photo, with the track as an inset; without a picked photo it draws what `bg=satellite` draws for that
|
||||
layout. No style takes `bg=photo` by default: a photo is not placed on the map, so its crop need not show the
|
||||
circuit, and the operator judged it unfit as a default.
|
||||
|
||||
**Fetching.** Every request carries the app's own User-Agent, `f1-circuits/1.0.0 (+<public address>)`, never a
|
||||
person's address; Jolpica's included. OpenStreetMap tiles are fetched only when a picture is asked for, never
|
||||
ahead (its policy forbids pre-seeding). At most 2 requests at once go to OpenStreetMap and to IGN, 4 to the
|
||||
others. Commons: one API request at a time, at most five a second, at most two downloads at once.
|
||||
|
||||
## Layers (kept for good)
|
||||
|
||||
| Layer | Made from | Key | Class |
|
||||
|:---|:---|:---|:---|
|
||||
| Map picture | the tiles of one source around a layout's trace, at its zoom (at most the source's deepest), for one frame (poster 1000×1500, thumb 1920×1080) | source, source year, trace hash, frame, zoom, render version | `rebuildable` |
|
||||
| Photo picture | one picked Commons file, cropped to the frame, untreated | file name, file's SHA-1 from Commons, frame, render version | `rebuildable` |
|
||||
| World locator | OpenStreetMap tiles at zoom 5 around the circuit, dark | latitude and longitude rounded to 0.01°, render version | `rebuildable` |
|
||||
| Track outline points | the layout's trace projected for the frame and zoom | trace hash, frame, zoom | `rebuildable` |
|
||||
|
||||
A map is kept only when every tile came and the tiles are not all one picture (a provider's placeholder).
|
||||
`dark` and `light` are made from the kept OpenStreetMap layer. A layout whose trace is a point or empty is drawn
|
||||
at the circuit's location, without a track. Layers live in the module's directory `layers`, class `rebuildable`
|
||||
(backed up; fetched again if lost).
|
||||
|
||||
## Finished images (kept, capped)
|
||||
|
||||
Every finished picture is stored under a key made of its route, its resolved options and the keys of the layers
|
||||
it was made from, in the directory `posters`, class `cache`, at most 2 GB; the least recently used go first when
|
||||
it is full. A picture whose layer did not arrive is not stored. The render version is `r3`: no poster stored
|
||||
before it is served again.
|
||||
|
||||
**What clients keep.** An address that carries the render version (`?v=r3`, as the Kometa file writes it) is
|
||||
sent `Cache-Control: public, max-age=31536000, immutable`. Any other address is sent an ETag and
|
||||
`max-age=86400`, and a matching `If-None-Match` (weak or strong) gets a 304. A picture served without its layer
|
||||
is sent `max-age=300` and no ETag.
|
||||
|
||||
## Options
|
||||
|
||||
Query parameters, the same on `/posters/race/…`, `/posters/season/…` and `/posters/session/…`. An unknown
|
||||
option or value is answered 422, naming it.
|
||||
|
||||
| Option | Values | Default | Drawn |
|
||||
|:---|:---|:---|:---|
|
||||
| `style` | `classic`, `minimal` | `classic` | a preset per frame of the options below; any option given overrides it |
|
||||
| `bg` | `satellite` (alias `aerial`), `photo`, `osm`, `dark`, `light`, `none` | `satellite` | the kept map or photo layer |
|
||||
| `photo` | `bw`, `natural` | `natural` | the treatment of a photo layer, applied when the picture is assembled (`bw`: luminance greyscale) |
|
||||
| `show` | a comma list of `wordmark`, `round`, `name`, `subtitle`, `date`, `circuit`, `locality`, `session` | the style's | on the fly |
|
||||
| `locator` | `on`, `off` | the style's | the kept locator layer |
|
||||
| `checker` | `on`, `off` | the style's | on the fly |
|
||||
| `track` | `off`, or a colour `#rrggbb` with an optional width 1 to 30, `#ffffff,6` | white, 6 | on the fly from the kept outline points; over a photo, an inset |
|
||||
| `dim` | 0 to 1: the darkening behind the track; the bands behind the texts keep their proportion | the style's | on the fly |
|
||||
| `accent` | `#rrggbb` | the style's | the wordmark's colour |
|
||||
| `width` | 400 up to the frame's own width | the frame's | scaled down at encoding |
|
||||
| `format` | `png`, `jpg`, `webp` | `png` | encoding, with its Content-Type, on the same `.png` addresses |
|
||||
|
||||
**The presets.** `classic` reproduces the earlier look per frame: on a poster checker and locator on, dim 0.43;
|
||||
on a thumb checker and locator off, dim 0.55; on a season poster dim 0.24. `minimal`: on a poster
|
||||
`show=name,date`, on a thumb `show=name,session`; checker off, locator off, dim 0.25; accent and track as
|
||||
`classic`.
|
||||
|
||||
**Placement.** `circuit` and `locality`, when asked for, are one grey 28 px line "<circuit> · <locality>" above
|
||||
the date on a poster, under the subtitle on a thumb. A `date` asked for on a thumb goes under the session label,
|
||||
grey, 36 px. The track inset over a photo is the trace fitted to 220×220 px (300×300 on a thumb), bottom right
|
||||
above the date strip, on a 50% black panel. A locator on a thumb sits top right, 220 px, 60 px from the edges.
|
||||
|
||||
**Season posters.** `wordmark` is "FORMULA 1", `name` the year, `subtitle` "WORLD CHAMPIONSHIP"; `round`, `date`,
|
||||
`circuit`, `locality`, `session`, `locator` and `track` are accepted and draw nothing. `bg=none` draws no photo;
|
||||
any other `bg` draws the season's picked photo, if any.
|
||||
|
||||
## Season posters
|
||||
|
||||
A season poster shows a season's cars only from a photo picked from Wikimedia Commons, credited like any
|
||||
Commons photo; until one is picked, it is drawn without a photo. Photos without a free licence are never used:
|
||||
the operator's earlier, hand-curated season photos carry agency credits (Getty Images, Motorsport Images/LAT
|
||||
and others) and stay private, as the reference for finding a freely licensed photo of the same car.
|
||||
|
||||
## Picking photos
|
||||
|
||||
`tools/commons_candidates.py` lists candidates from Commons per layout (aerial photos of the circuit dated in the
|
||||
layout's years) and per season (that season's cars): only CC0, public domain, CC BY and CC BY-SA; quality marks,
|
||||
size and landscape first; written to `examples/data/candidates.json`. The picker page shows, per layout, the
|
||||
`bg=satellite` decision first (the national photo and EOX next to each other; keep the satellite, or use the map
|
||||
instead), then the optional photo candidates for `bg=photo`, beside the picks of the circuit's other layouts; per
|
||||
season, its candidates beside the nearest seasons' picks. It gives the entry to copy; it writes nothing.
|
||||
|
||||
The picks live in the repository. `circuits/photos.json` is keyed by the layout's path under `circuits/`
|
||||
without extension (`belgium/spa/circuit-de-spa-francorchamps/1983-`), `seasons/photos.json` by the year as text.
|
||||
An entry holds the photo fields (`file`, the Commons title without "File:"; `licence`; `author`; `credit`;
|
||||
`date`, `YYYY[-MM[-DD]]`), `"use": "map"`, or both. A key starting with `$` is a note and is skipped. Refused and
|
||||
logged when read: an unknown `use`, incomplete photo fields, an entry with neither, a licence that is not free.
|
||||
|
||||
## Licences, stated
|
||||
|
||||
- On every picture: the credit line of each source it was made from, joined with " · ", at least 12 px high
|
||||
after scaling, wrapping when needed, on a dark band above the bottom strip.
|
||||
- **A picture's licence follows its sources:** CC BY-SA 4.0 when made from a CC BY-SA photo (2.0, 3.0 and
|
||||
3.0 DE allow a later version with the same elements); CC BY-NC-SA 4.0 when made from EOX's mosaic; CC BY 4.0
|
||||
otherwise. Jolpica's race names and dates are single facts and do not set it. The satellite chain takes one
|
||||
source, so a BY-SA photo and an NC-SA mosaic never meet on one picture; a picture that would combine them is
|
||||
refused.
|
||||
- In every picture's response: `X-Credits` (the credit line folded to ASCII: ß→ss, æ→ae, ø→o, œ→oe, đ→d, then
|
||||
accents dropped, "©" as "(c)", sources joined with " | "), `X-License`, and `Link: </licences>; rel="license"`;
|
||||
CORS exposes them and the ETag.
|
||||
- `/licences`: `pictures` (the rule and its licences), `tracks` (MIT), and every source with its licence, credit,
|
||||
terms' address and the licence a picture made from it gets; the example site's licences page shows it.
|
||||
- The Kometa file says in its first lines that its data comes from Jolpica under CC BY-NC-SA 4.0.
|
||||
- The unofficial-use disclaimer for the Formula 1 marks is shown at the foot of `/`, `/docs` and every example
|
||||
page.
|
||||
|
||||
## Not in this change
|
||||
|
||||
The disk tile store (replaced by kept layers); renaming the service away from "F1"; the four layouts whose trace
|
||||
is empty or a point, and the Bahrain and Donington traces that sit off their real track (traced separately); the
|
||||
season photos matched to the operator's curated cars.
|
||||
+4
-1
@@ -9,6 +9,8 @@ from datetime import date
|
||||
from pathlib import Path
|
||||
from typing import Optional, TYPE_CHECKING
|
||||
|
||||
from app_info import USER_AGENT
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from circuits_service import CircuitService
|
||||
|
||||
@@ -112,7 +114,8 @@ class ErgastService:
|
||||
time.sleep(wait)
|
||||
self._last_request = time.monotonic()
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=self.REQUEST_TIMEOUT) as resp:
|
||||
request = urllib.request.Request(url, headers={'User-Agent': USER_AGENT})
|
||||
with urllib.request.urlopen(request, timeout=self.REQUEST_TIMEOUT) as resp:
|
||||
return json.loads(resp.read())['MRData']['RaceTable']['Races']
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code != 429 or attempt == self.RETRIES:
|
||||
|
||||
@@ -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,769 @@
|
||||
<!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(2)}`) : null,
|
||||
].filter(Boolean);
|
||||
const chosen = opts.choose && state.chosen && state.chosen.cand && state.chosen.cand.file === c.file;
|
||||
const card = h('article', { class: `photo-card${opts.picked ? ' picked' : ''}${chosen ? ' chosen' : ''}` },
|
||||
h('div', { class: 'photo-frame' },
|
||||
h('img', { src: c.thumb || thumbOf(c.file), alt: c.file, loading: 'lazy', decoding: 'async', referrerpolicy: 'no-referrer' })),
|
||||
opts.label ? h('div', { class: 'meta' }, h('b', {}, opts.label)) : null,
|
||||
h('div', { class: 'name' }, c.file),
|
||||
h('div', { class: 'meta' },
|
||||
h('b', { title: c.date_from === 'category' ? 'The file gives no date: the season it is filed under' : null },
|
||||
c.date ? `${c.date}${c.date_from === 'category' ? ' (its season)' : ''}` : 'undated'),
|
||||
c.width ? ` · ${c.width}×${c.height}` : '',
|
||||
' · ', c.licence_url ? h('a', { href: c.licence_url, target: '_blank', rel: 'noopener' }, c.licence) : c.licence,
|
||||
h('br'), c.author),
|
||||
tags.length ? h('div', { class: 'tags' }, ...tags) : null,
|
||||
c.found ? h('div', { class: 'meta', title: 'How the tool found it' },
|
||||
`Found by ${c.found.map((f) => (f === 'marked' ? 'a search for its category’s quality-marked files' : f)).join('; ')}`) : null,
|
||||
h('div', { class: 'actions' },
|
||||
opts.choose ? h('button', { type: 'button', class: 'primary', onclick: () => opts.choose(card) }, 'Choose') : null,
|
||||
h('a', { href: c.page || pageOf(c.file), target: '_blank', rel: 'noopener' }, 'On Commons')));
|
||||
return card;
|
||||
}
|
||||
|
||||
/** A pick as the picks file holds it: a photo, or {"use": "map"}. */
|
||||
function pickCard(entry, label, picked) {
|
||||
if (typeof entry.file === 'string' && entry.use === 'map') {
|
||||
const card = photoCard({ ...entry, thumb: thumbOf(entry.file) }, { label, picked });
|
||||
card.querySelector('.name').after(h('div', { class: 'tags' }, h('span', { class: 'tag', title: 'Its entry also says "use": "map"' }, 'the dark map for bg=satellite')));
|
||||
return card;
|
||||
}
|
||||
if (entry.use === 'map') {
|
||||
return h('article', { class: `photo-card${picked ? ' picked' : ''}` },
|
||||
h('div', { class: 'map-frame plain' }, h('span', {}, 'The dark map')),
|
||||
h('div', { class: 'meta' }, h('b', {}, label)),
|
||||
h('div', { class: 'name' }, '{"use": "map"}: the dark map for bg=satellite'));
|
||||
}
|
||||
return photoCard({ ...entry, thumb: thumbOf(entry.file) }, { label, picked });
|
||||
}
|
||||
|
||||
function grid(cards, extra = '') {
|
||||
const cls = `photos${frameNow() === 'thumb' ? ' thumb' : ''}${extra ? ` ${extra}` : ''}`;
|
||||
return h('div', { class: cls }, ...cards);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ the entry to copy
|
||||
|
||||
function entryOf(c) {
|
||||
const e = {};
|
||||
for (const k of PICK_FIELDS) e[k] = c[k] === undefined ? null : c[k];
|
||||
return e;
|
||||
}
|
||||
|
||||
/**
|
||||
* The picks file's text with one entry set: its "$" keys first as they stand, then every pick by key. Written from
|
||||
* a list of pairs, not an object: an object lists keys such as "2024" before "$comment", whatever their order.
|
||||
*/
|
||||
function withPick(file, key, entry) {
|
||||
const notes = Object.entries(file).filter(([k]) => k.startsWith('$'));
|
||||
const picks = new Map(Object.entries(file).filter(([k]) => !k.startsWith('$')));
|
||||
if (entry === null) picks.delete(key); else picks.set(key, entry);
|
||||
const sorted = [...picks.keys()].sort((a, b) => a.localeCompare(b, 'en', { numeric: true })).map((k) => [k, picks.get(k)]);
|
||||
const pairs = [...notes, ...sorted];
|
||||
const indent = (text) => text.replace(/\n/g, '\n ');
|
||||
return pairs.length
|
||||
? `{\n${pairs.map(([k, v]) => ` ${JSON.stringify(k)}: ${indent(JSON.stringify(v, null, 2))}`).join(',\n')}\n}`
|
||||
: '{}';
|
||||
}
|
||||
|
||||
function copyBlock(title, text) {
|
||||
const button = h('button', { type: 'button' }, 'Copy');
|
||||
button.addEventListener('click', async () => {
|
||||
try { await navigator.clipboard.writeText(text); button.textContent = 'Copied'; } catch { button.textContent = 'Select and copy'; }
|
||||
setTimeout(() => { button.textContent = 'Copy'; }, 1500);
|
||||
});
|
||||
const body = h('div');
|
||||
showJSON(body, text);
|
||||
return h('div', { class: 'copy-block' }, h('div', { class: 'head' }, h('span', {}, title), button), body);
|
||||
}
|
||||
|
||||
/**
|
||||
* The entry a choice leaves for a key, from the one there now: one entry may carry the photo fields (bg=photo),
|
||||
* "use": "map" (bg=satellite), or both. Choosing a photo keeps "use": "map"; the map keeps the photo; keeping the
|
||||
* satellite drops only "use". null: no entry is left.
|
||||
*/
|
||||
function entryFor(existing, kind, cand) {
|
||||
const photo = existing && typeof existing.file === 'string'
|
||||
? Object.fromEntries(PICK_FIELDS.filter((k) => k in existing).map((k) => [k, existing[k]])) : null;
|
||||
const map = !!existing && existing.use === 'map';
|
||||
if (kind === 'photo') return { ...entryOf(cand), ...(map ? { use: 'map' } : {}) };
|
||||
if (kind === 'map') return { ...(photo || {}), use: 'map' };
|
||||
return photo;
|
||||
}
|
||||
|
||||
/** What of the entry there now a choice keeps, said in one sentence. */
|
||||
function keeps(existing, kind) {
|
||||
if (!existing) return '';
|
||||
if (kind === 'photo' && existing.use === 'map') return ' It keeps "use": "map" for bg=satellite.';
|
||||
if (kind === 'map' && typeof existing.file === 'string') return ' It keeps the photo picked for bg=photo.';
|
||||
if (kind === 'satellite') return ' It keeps the photo picked for bg=photo, without "use".';
|
||||
return '';
|
||||
}
|
||||
|
||||
function showEntry() {
|
||||
const section = $('entry');
|
||||
const body = $('entry-body');
|
||||
if (!state.chosen) { section.hidden = true; return; }
|
||||
const { key, cand, fileName, fileKey, kind } = state.chosen;
|
||||
const file = state.picks[fileKey];
|
||||
const existing = file && Object.prototype.hasOwnProperty.call(file, key) ? file[key] : null;
|
||||
if (kind === 'photo' && !cand.date) {
|
||||
body.replaceChildren(notice('error', `${cand.file} has no date, and the service refuses an entry without one: run tools/commons_candidates.py again, or choose another.`));
|
||||
section.hidden = false;
|
||||
return;
|
||||
}
|
||||
const entry = entryFor(existing, kind, cand);
|
||||
const rule = [' ', h('a', { href: F1.linkWithKept('licences.html') }, 'The licences page'), ' states the rule.'];
|
||||
const what = kind === 'satellite' ? 'the satellite, not the map' : kind === 'map' ? 'the dark map instead of the satellite' : cand.file;
|
||||
const parts = [h('p', {}, 'For ', h('code', {}, key), ': ', h('b', {}, what), '.')];
|
||||
if (entry) {
|
||||
parts.push(
|
||||
h('p', {}, 'Copy the entry into ', h('code', {}, fileName), ', or the whole file below with the entry in place.', keeps(existing, kind)),
|
||||
copyBlock(`The entry, for ${fileName}`, `${JSON.stringify(key)}: ${JSON.stringify(entry, null, 2)}`));
|
||||
} else if (!file) {
|
||||
parts.push(h('p', {}, 'No entry is needed for it.'));
|
||||
} else if (existing) {
|
||||
parts.push(h('p', {}, `No entry is left for it: remove the one ${fileName} has now.`));
|
||||
} else {
|
||||
parts.push(h('p', { class: 'hint' }, `No entry is needed for it, and ${fileName} has none: nothing to change.`));
|
||||
}
|
||||
if (kind === 'satellite') {
|
||||
const src = satelliteSource(key);
|
||||
parts.push(notice('info', `bg=satellite draws ${src.name} for this layout; a poster from it is ${src.poster}. A picture’s licence follows its sources.`, ...rule));
|
||||
} else if (kind === 'map') {
|
||||
parts.push(notice('info', 'The service draws the dark OpenStreetMap map for this layout in place of the satellite: for bg=satellite, and for bg=photo while no photo is picked. A poster on it is CC BY 4.0.', ...rule));
|
||||
} else {
|
||||
const sa = /\bBY-SA\b/i.test(cand.licence);
|
||||
parts.push(notice('info', fileKey === 'circuits' ? 'This photo serves bg=photo only; bg=satellite does not change. ' : '', sa
|
||||
? `${cand.licence} is share-alike: a poster made from it is adapted material, shared under CC BY-SA terms. Such a poster is CC BY-SA 4.0.`
|
||||
: `A poster made from it is CC BY 4.0: a picture’s licence follows its sources, and ${cand.licence} asks no share-alike.`, ...rule));
|
||||
if ((cand.restrictions || []).length) {
|
||||
parts.push(notice('', `Commons names ${cand.restrictions.join(' and ')} rights for this file: rights beside its copyright licence, such as a person’s likeness or a trade mark shown in it.`));
|
||||
}
|
||||
}
|
||||
if (!file) parts.push(notice('error', `${fileName} was not read, so the whole file cannot be shown${kind === 'photo' ? '' : ', nor whether it has an entry for this layout now'}: load it from disk above.`));
|
||||
else if (entry || existing) parts.push(copyBlock(`The whole of ${fileName} ${entry ? 'with this entry' : 'without an entry for it'}`, withPick(file, key, entry)));
|
||||
body.replaceChildren(...parts);
|
||||
section.hidden = false;
|
||||
}
|
||||
|
||||
function choose(key, cand, card, fileName, fileKey) {
|
||||
for (const el of document.querySelectorAll('.photo-card.chosen')) el.classList.remove('chosen');
|
||||
card.classList.add('chosen');
|
||||
state.chosen = { key, cand, fileName, fileKey, mode: state.mode, kind: 'photo' };
|
||||
markChoices();
|
||||
showEntry();
|
||||
$('entry').scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
}
|
||||
|
||||
/** "Keep the satellite" (no entry) or "use the map instead" ({"use": "map"}) for a layout. */
|
||||
function chooseSurface(key, kind) {
|
||||
for (const el of document.querySelectorAll('.photo-card.chosen')) el.classList.remove('chosen');
|
||||
state.chosen = { key, kind, fileName: 'circuits/photos.json', fileKey: 'circuits', mode: 'layout' };
|
||||
markChoices();
|
||||
showEntry();
|
||||
$('entry').scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
}
|
||||
|
||||
function markChoices() {
|
||||
for (const b of document.querySelectorAll('#sat .choices button')) {
|
||||
b.setAttribute('aria-pressed', String(!!state.chosen && state.chosen.kind === b.dataset.kind));
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ without a photo: the satellite, or the map
|
||||
|
||||
// What bg=satellite draws (the operator, 2026-11-27): the country's own aerial photo, else EOxCloudless 2025; a
|
||||
// Commons photo only ever for bg=photo. The layers the service uses; past maxNativeZoom (the deepest level every
|
||||
// circuit of that country has, checked 2026-11-27) Leaflet scales the deepest tiles up.
|
||||
const NATIONAL = {
|
||||
netherlands: { name: 'PDOK’s aerial photo', url: 'https://service.pdok.nl/hwh/luchtfotorgb/wmts/v1_0/Actueel_orthoHR/EPSG:3857/{z}/{x}/{y}.jpeg',
|
||||
maxNativeZoom: 19, credit: 'Luchtfoto: PDOK / Samenwerkingsverband Beeldmateriaal, CC BY 4.0', licence: 'CC BY 4.0', poster: 'CC BY 4.0' },
|
||||
france: { name: 'IGN’s BD ORTHO 2021–2023', url: 'https://data.geopf.fr/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ORTHOIMAGERY.ORTHOPHOTOS2021-2023&STYLE=normal&TILEMATRIXSET=PM&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=image/jpeg',
|
||||
maxNativeZoom: 18, credit: '© IGN – BD ORTHO, 2021–2023', licence: 'Licence Ouverte (Etalab) 2.0', poster: 'CC BY 4.0' },
|
||||
'united-states': { name: 'USGS imagery', url: 'https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}',
|
||||
maxNativeZoom: 16, credit: 'USDA, USGS The National Map: Orthoimagery', licence: 'public domain', poster: 'CC BY 4.0' },
|
||||
};
|
||||
const EOX = {
|
||||
name: 'EOxCloudless 2025',
|
||||
url: 'https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-2025_3857/default/g/{z}/{y}/{x}.jpg',
|
||||
maxNativeZoom: 15,
|
||||
credit: 'EOxCloudless https://cloudless.eox.at by EOX IT Services GmbH (Contains modified Copernicus Sentinel data 2025)',
|
||||
licence: 'CC BY-NC-SA 4.0',
|
||||
poster: 'CC BY-NC-SA 4.0',
|
||||
};
|
||||
|
||||
/** What bg=satellite draws for a layout that does not ask for the map. */
|
||||
function satelliteSource(key) {
|
||||
return NATIONAL[key.split('/')[0]] || EOX;
|
||||
}
|
||||
|
||||
const traces = new Map();
|
||||
const races = new Map();
|
||||
let satMaps = [];
|
||||
let satShown = '';
|
||||
|
||||
/** A layout's GPS trace as [lat, lon] points, or null when it has none. */
|
||||
async function traceOf(p) {
|
||||
const key = `${p.country}/${p.city}/${p.circuit}/${p.layout}`;
|
||||
if (!traces.has(key)) {
|
||||
traces.set(key, (async () => {
|
||||
const res = await fetch(api(path`/circuits/${p.country}/${p.city}/${p.circuit}/layout/${p.layout}/geojson`));
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const line = F1.lineOf(await res.json());
|
||||
const pts = line ? line.geometry.coordinates.map(([lon, lat]) => [lat, lon]) : [];
|
||||
return pts.length > 1 ? pts : null;
|
||||
})());
|
||||
}
|
||||
return traces.get(key);
|
||||
}
|
||||
|
||||
/** The latest race at a circuit within a layout's years, from Jolpica; null when none. */
|
||||
async function raceOn(p) {
|
||||
const id = p.circuitData && p.circuitData.ergastId;
|
||||
if (!id) return null;
|
||||
if (!races.has(id)) {
|
||||
races.set(id, (async () => {
|
||||
const all = [];
|
||||
for (let offset = 0; ; offset += 100) {
|
||||
const res = await fetch(`${F1.JOLPICA}/circuits/${encodeURIComponent(id)}/races.json?limit=100&offset=${offset}`);
|
||||
if (!res.ok) throw new Error(`Jolpica answered HTTP ${res.status}`);
|
||||
const d = (await res.json()).MRData;
|
||||
all.push(...d.RaceTable.Races);
|
||||
if (offset + 100 >= Number(d.total)) return all;
|
||||
}
|
||||
})());
|
||||
}
|
||||
const list = await races.get(id);
|
||||
const first = parseInt(p.layout, 10);
|
||||
const last = p.layout.endsWith('-') ? Infinity : parseInt(p.layout.split('-')[1] || p.layout, 10);
|
||||
const fit = list.filter((r) => Number(r.season) >= first && Number(r.season) <= last);
|
||||
return fit.length ? fit[fit.length - 1] : null;
|
||||
}
|
||||
|
||||
function mapCard(src, note) {
|
||||
const box = h('div', { class: 'map-box' });
|
||||
const card = h('article', { class: 'photo-card' },
|
||||
h('div', { class: 'map-frame' }, box),
|
||||
note ? h('div', { class: 'meta' }, h('b', {}, note)) : null,
|
||||
h('div', { class: 'name' }, src.name),
|
||||
h('div', { class: 'meta' }, src.credit, h('br'), `${src.licence}; a poster from it: `, h('b', {}, src.poster)));
|
||||
card._box = box;
|
||||
card._src = src;
|
||||
return card;
|
||||
}
|
||||
|
||||
function serviceCard(p) {
|
||||
const route = frameNow() === 'thumb' ? 'session thumbnail' : 'race poster';
|
||||
const button = h('button', { type: 'button' }, `Render the service’s ${route}`);
|
||||
const card = h('article', { class: 'photo-card' },
|
||||
h('div', { class: 'map-frame plain result' }, h('span', {}, 'What the service draws now, on demand: it renders and may fetch tiles first.')),
|
||||
h('div', { class: 'name' }, `The service’s ${route}, bg=satellite`),
|
||||
h('div', { class: 'request compact' }),
|
||||
h('div', { class: 'status idle' }, 'Not rendered yet.'),
|
||||
h('div', { class: 'actions' }, button));
|
||||
button.addEventListener('click', async () => {
|
||||
button.disabled = true;
|
||||
const st = card.querySelector('.status');
|
||||
try {
|
||||
setStatus(st, 'pending', 'Finding a race on this layout at Jolpica…');
|
||||
const race = await raceOn(p);
|
||||
if (!race) { setStatus(st, 'error', `Jolpica lists no race at this circuit in ${layoutYears(p.layout)}.`); return; }
|
||||
const url = frameNow() === 'thumb'
|
||||
? api(path`/posters/session/${race.raceName}/${race.season}/race.png`) + '?bg=satellite'
|
||||
: api(path`/posters/race/${race.raceName}/${race.season}.png`) + '?bg=satellite';
|
||||
const answer = await call(card, url, { label: `${race.raceName} ${race.season}`, waiting: 'Rendering on the server…' });
|
||||
const frame = card.querySelector('.map-frame');
|
||||
if (!answer) { frame.replaceChildren(h('span', {}, 'No picture: see the status below.')); return; }
|
||||
frame.classList.remove('plain');
|
||||
await showImage(frame, answer, 'png', { alt: `${race.raceName} ${race.season}, bg=satellite`, tile: false, status: st });
|
||||
} catch (e) {
|
||||
setStatus(st, 'error', e.message);
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
return card;
|
||||
}
|
||||
|
||||
function renderSat(p, key, current) {
|
||||
const sig = `${key}|${frameNow()}`;
|
||||
const src = satelliteSource(key);
|
||||
const status = !state.picks.circuits ? 'circuits/photos.json was not read, so what this layout uses now is not known.'
|
||||
: current && current.use === 'map' ? 'Its entry says "use": "map": bg=satellite draws the dark map for it now.'
|
||||
: `Its entry does not ask for the map: bg=satellite draws ${src.name} for it now.`;
|
||||
const head = h('p', { class: 'hint' }, `bg=satellite draws ${src.name} for this layout, and bg=photo does too while it has no picked photo. Judge it below, its trace drawn in white: keep the satellite, or have the service draw the dark map instead. `, h('b', {}, status));
|
||||
const choices = h('div', { class: 'choices' },
|
||||
h('button', { type: 'button', 'data-kind': 'satellite', onclick: () => chooseSurface(key, 'satellite') }, 'Keep the satellite (no entry)'),
|
||||
h('button', { type: 'button', 'data-kind': 'map', onclick: () => chooseSurface(key, 'map') }, 'Use the map instead'));
|
||||
if (sig === satShown && satMaps.length) {
|
||||
$('sat').firstChild.replaceWith(head);
|
||||
$('sat').querySelector('.choices').replaceWith(choices);
|
||||
markChoices();
|
||||
return;
|
||||
}
|
||||
for (const m of satMaps) m.remove();
|
||||
satMaps = [];
|
||||
satShown = sig;
|
||||
const country = p.country;
|
||||
const cards = [];
|
||||
if (NATIONAL[country]) cards.push(mapCard(NATIONAL[country], 'What bg=satellite draws for this country'));
|
||||
cards.push(mapCard(EOX, NATIONAL[country] ? 'What bg=satellite draws where the national photo has no tiles' : 'What bg=satellite draws here'));
|
||||
cards.push(serviceCard(p));
|
||||
$('sat').replaceChildren(head, grid(cards), choices);
|
||||
markChoices();
|
||||
traceOf(p).then((pts) => {
|
||||
if (satShown !== sig) return;
|
||||
for (const card of cards.filter((c) => c._box)) {
|
||||
// Whole zoom levels: at a fractional one the browser draws seams between tiles that read as flaws in the imagery.
|
||||
const m = L.map(card._box, { attributionControl: false, scrollWheelZoom: false });
|
||||
L.tileLayer(card._src.url, { maxZoom: 19, maxNativeZoom: card._src.maxNativeZoom }).addTo(m);
|
||||
if (pts) {
|
||||
const line = L.polyline(pts, { color: '#ffffff', weight: 2, opacity: 0.9 }).addTo(m);
|
||||
m.fitBounds(line.getBounds(), { padding: [14, 14] });
|
||||
} else {
|
||||
m.setView([0, 0], 2);
|
||||
card._box.after(h('div', { class: 'meta' }, 'This layout has no trace to frame.'));
|
||||
}
|
||||
satMaps.push(m);
|
||||
}
|
||||
}).catch((err) => {
|
||||
for (const card of cards.filter((c) => c._box)) card._box.replaceWith(notice('error', `The layout’s trace could not be read: ${err.message}`));
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ rendering a layout or a season
|
||||
|
||||
function picksOf(name) {
|
||||
const file = state.picks[name];
|
||||
return file ? Object.fromEntries(Object.entries(file).filter(([k]) => !k.startsWith('$'))) : null;
|
||||
}
|
||||
|
||||
function render() {
|
||||
syncURL();
|
||||
$('photos-root').className = state.treat === 'bw' ? 'treat-bw' : '';
|
||||
$('frame-label').hidden = state.mode === 'season';
|
||||
$('layout-picker').hidden = state.mode !== 'layout';
|
||||
$('season-picker').hidden = state.mode !== 'season';
|
||||
// The /circuits call fills the layout picker only.
|
||||
for (const sel of ['.request', '.status', '.result']) $('choose').querySelector(`:scope > ${sel}`).hidden = state.mode !== 'layout';
|
||||
for (const [id, v] of [['mode', state.mode], ['treat', state.treat], ['frame', state.frame]]) {
|
||||
for (const b of $(id).querySelectorAll('button')) b.setAttribute('aria-pressed', String(b.dataset.v === v));
|
||||
}
|
||||
if (state.chosen && state.chosen.mode !== state.mode) { state.chosen = null; showEntry(); }
|
||||
if (!state.candidates) {
|
||||
$('others-title').hidden = true;
|
||||
$('others').replaceChildren();
|
||||
$('cands-title').textContent = 'Candidates';
|
||||
$('cands').replaceChildren(notice('error', 'The candidates were not read (see 1).'));
|
||||
return;
|
||||
}
|
||||
if (state.mode === 'layout') renderLayout(); else renderSeason();
|
||||
}
|
||||
|
||||
function renderLayout() {
|
||||
const p = state.pick;
|
||||
if (!p || !p.layout) return;
|
||||
const circuitKey = `${p.country}/${p.city}/${p.circuit}`;
|
||||
const key = `${circuitKey}/${p.layout}`;
|
||||
const picks = picksOf('circuits');
|
||||
const list = state.candidates.layouts[key];
|
||||
const current = picks && picks[key];
|
||||
if (state.chosen && state.chosen.key !== key) { state.chosen = null; showEntry(); }
|
||||
$('sat-title').hidden = false;
|
||||
renderSat(p, key, current);
|
||||
|
||||
// The circuit's other layouts, and this one's pick when it has one.
|
||||
$('others-title').hidden = false;
|
||||
$('others-title').textContent = `For bg=photo (optional): the picks of ${p.circuitName || 'this circuit'}’s layouts`;
|
||||
if (!picks) {
|
||||
$('others').replaceChildren(notice('error', 'circuits/photos.json was not read (see 1), so the picks are not shown.'));
|
||||
} else {
|
||||
const cards = p.layouts.filter((l) => picks[`${circuitKey}/${l}`]).map((l) => {
|
||||
const k = `${circuitKey}/${l}`;
|
||||
const label = `${layoutYears(l)}${l === p.layout ? ' (this layout, picked now)' : ''}`;
|
||||
return pickCard(picks[k], label, l === p.layout);
|
||||
});
|
||||
$('others').replaceChildren(cards.length ? grid(cards, 'small')
|
||||
: h('p', { class: 'hint' }, `None of its ${p.layouts.length} layout${p.layouts.length === 1 ? '' : 's'} has a pick yet.`));
|
||||
}
|
||||
|
||||
const undated = ((state.candidates.about || {}).undated_per_circuit || {})[circuitKey];
|
||||
$('cands-title').textContent = `Candidates for bg=photo (optional), ${layoutYears(p.layout)}${list ? ` (${list.length})` : ''}`;
|
||||
if (!list) {
|
||||
$('cands').replaceChildren(notice('error', `The candidates file has no entry for ${key}: run tools/commons_candidates.py again.`));
|
||||
return;
|
||||
}
|
||||
const why = undated ? ` The tool found ${undated} more photo${undated === 1 ? '' : 's'} of this circuit with no date it can read; a layout lists only photos dated within its years.` : '';
|
||||
if (!list.length) {
|
||||
$('cands').replaceChildren(notice('', `Commons has no freely licensed aerial photo of this circuit dated ${layoutYears(p.layout)} that the tool found: bg=photo draws what bg=satellite draws for it (above).${why}`));
|
||||
return;
|
||||
}
|
||||
$('cands').replaceChildren(
|
||||
why ? h('p', { class: 'hint' }, why.trim()) : '',
|
||||
grid(list.map((c) => photoCard(c, {
|
||||
picked: current && current.file === c.file,
|
||||
label: current && current.file === c.file ? 'Picked now' : null,
|
||||
choose: (card) => choose(key, c, card, 'circuits/photos.json', 'circuits'),
|
||||
}))));
|
||||
}
|
||||
|
||||
function renderSeason() {
|
||||
const year = $('season').value;
|
||||
if (!year) return;
|
||||
$('sat-title').hidden = true;
|
||||
$('sat').replaceChildren();
|
||||
for (const m of satMaps) m.remove();
|
||||
satMaps = [];
|
||||
satShown = '';
|
||||
const picks = picksOf('seasons');
|
||||
const list = state.candidates.seasons[year] || null;
|
||||
const current = picks && picks[year];
|
||||
|
||||
$('others-title').hidden = false;
|
||||
$('others-title').textContent = 'Picks of the seasons nearest to it';
|
||||
if (!picks) {
|
||||
$('others').replaceChildren(notice('error', 'seasons/photos.json was not read (see 1), so the picks are not shown.'));
|
||||
} else {
|
||||
const near = Object.keys(picks).sort((a, b) => Math.abs(a - year) - Math.abs(b - year) || a - b).slice(0, 10);
|
||||
$('others').replaceChildren(near.length
|
||||
? grid(near.map((y) => pickCard(picks[y], `${y}${y === year ? ' (this season, picked now)' : ''}`, y === year)), 'small')
|
||||
: h('p', { class: 'hint' }, 'No season has a pick yet.'));
|
||||
}
|
||||
|
||||
$('cands-title').textContent = `Candidates for ${year}${list ? ` (${list.length})` : ''}`;
|
||||
if (!list) {
|
||||
$('cands').replaceChildren(notice('error', `The candidates file has no entry for ${year}: run tools/commons_candidates.py again.`));
|
||||
return;
|
||||
}
|
||||
if (!list.length) {
|
||||
$('cands').replaceChildren(notice('', `No freely licensed photo in “${year} Formula One season cars” was found; until one is picked, the season poster is drawn without a photo.`));
|
||||
return;
|
||||
}
|
||||
state.chosen = state.chosen && state.chosen.key === year ? state.chosen : null;
|
||||
$('cands').replaceChildren(h('p', { class: 'hint' }, `From Commons’ “${year} Formula One season cars”, the best ${list.length} by quality marks, size and landscape.`),
|
||||
grid(list.map((c) => photoCard(c, {
|
||||
picked: current && current.file === c.file,
|
||||
label: current && current.file === c.file ? 'Picked now' : null,
|
||||
choose: (card) => choose(year, c, card, 'seasons/photos.json', 'seasons'),
|
||||
}))));
|
||||
if (!state.chosen) showEntry();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ controls
|
||||
|
||||
function seg(id, key) {
|
||||
$(id).addEventListener('click', (e) => {
|
||||
const b = e.target.closest('button');
|
||||
if (!b) return;
|
||||
state[key] = b.dataset.v;
|
||||
render();
|
||||
if (state.chosen) showEntry();
|
||||
});
|
||||
}
|
||||
seg('mode', 'mode');
|
||||
seg('treat', 'treat');
|
||||
seg('frame', 'frame');
|
||||
$('season').addEventListener('change', () => { state.chosen = null; render(); });
|
||||
|
||||
function fillSeasons() {
|
||||
const years = Object.keys(state.candidates.seasons).sort();
|
||||
const want = params.get('season') || '2024';
|
||||
$('season').replaceChildren(...years.map((y) => h('option', { value: y }, `${y} · ${state.candidates.seasons[y].length} candidate${state.candidates.seasons[y].length === 1 ? '' : 's'}`)));
|
||||
$('season').value = years.includes(want) ? want : years[years.length - 1];
|
||||
}
|
||||
|
||||
render();
|
||||
readFile('candidates', () => { fillSeasons(); render(); });
|
||||
readFile('circuits', render);
|
||||
readFile('seasons', render);
|
||||
layoutPicker($('layout-picker'), {
|
||||
treeCard: $('choose'),
|
||||
sync: true,
|
||||
onChange: (p) => { state.pick = p; state.chosen = null; render(); },
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+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>
|
||||
|
||||
+4
-2
@@ -11,14 +11,16 @@
|
||||
# models it imports. Then the tests in tests/, which need the standard library only: every circuit in
|
||||
# circuits/circuits.json carries one unique ergastId, and a race's circuit resolves by that id, never by
|
||||
# its name; a failed Jolpica fetch is never kept, a season that is over is read from disk, a throttled
|
||||
# request is asked again.
|
||||
# request is asked again; a poster's options, keys, cache headers and store cap, its satellite source, credits and
|
||||
# licence (poster_options.py and poster_sources.py, standard library only).
|
||||
#
|
||||
# **Said, never passed silently**: the service's dependencies (service/requirements.txt) are the image's to
|
||||
# install, so the service is not started.
|
||||
set -eu
|
||||
|
||||
# Parsed, not compiled to files: a check leaves the tree as it found it.
|
||||
find cdn-api.py access_log.py circuits_service.py ergast_service.py posters_service.py models -name '*.py' -print0 |
|
||||
find cdn-api.py access_log.py app_info.py circuits_service.py ergast_service.py posters_service.py poster_options.py \
|
||||
poster_sources.py models -name '*.py' -print0 |
|
||||
xargs -0 python3 -c 'import ast, sys
|
||||
for f in sys.argv[1:]:
|
||||
ast.parse(open(f, encoding="utf-8").read(), f)
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Dict, Any
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
@dataclass
|
||||
class GeoJSONGeometry:
|
||||
@@ -18,6 +16,8 @@ class GeoJSONGeometry:
|
||||
|
||||
def find_longest_straight(self, window_size=5) -> (List[float], List[float]):
|
||||
"""Find the longest approximately straight section of the track, including wrap-around."""
|
||||
import numpy as np # only here: the models themselves load with the standard library (the service's tests)
|
||||
|
||||
max_distance = 0
|
||||
best_start_idx = 0
|
||||
n = len(self.coordinates)
|
||||
|
||||
+27
-3
@@ -23,7 +23,7 @@
|
||||
"port": 8000,
|
||||
"protocol": "tcp",
|
||||
"from": "mesh",
|
||||
"why": "the track-layout CDN, the race posters and the Kometa metadata over http; its public name is a route grant and the proxy reaches it here. Kometa fetches the metadata and every poster by that public name"
|
||||
"why": "the track-layout CDN, the race posters, their licences and the Kometa metadata over http; its public name is a route grant and the proxy reaches it here. Kometa fetches the metadata and every poster by that public name"
|
||||
}
|
||||
],
|
||||
"data": {
|
||||
@@ -32,7 +32,19 @@
|
||||
"id": "cache",
|
||||
"path": "${dir:cache}",
|
||||
"class": "cache",
|
||||
"why": "the generated track layouts and posters, rebuilt on demand"
|
||||
"why": "the race schedules asked from Jolpica, asked again when lost"
|
||||
},
|
||||
{
|
||||
"id": "layers",
|
||||
"path": "${dir:layers}",
|
||||
"class": "rebuildable",
|
||||
"why": "the kept layers of the posters: the map pictures, picked photos, world locators and track outlines, fetched once and kept for good; fetched again if lost"
|
||||
},
|
||||
{
|
||||
"id": "posters",
|
||||
"path": "${dir:posters}",
|
||||
"class": "cache",
|
||||
"why": "the finished posters and thumbnails, at most 2 GB, drawn again from the layers on demand"
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -48,6 +60,16 @@
|
||||
"type": "directory",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "layers",
|
||||
"type": "directory",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "posters",
|
||||
"type": "directory",
|
||||
"mode": "0700"
|
||||
},
|
||||
{
|
||||
"id": "site-env",
|
||||
"type": "file",
|
||||
@@ -67,7 +89,9 @@
|
||||
"${dir:state}/site.env"
|
||||
],
|
||||
"volumes": [
|
||||
"${dir:cache}:/app/cache"
|
||||
"${dir:cache}:/app/cache",
|
||||
"${dir:layers}:/app/layers",
|
||||
"${dir:posters}:/app/posters"
|
||||
],
|
||||
"restart-on": [
|
||||
"site-env"
|
||||
|
||||
@@ -0,0 +1,224 @@
|
||||
"""What a caller may choose on a poster, a season poster or a session thumbnail, how a choice is checked, and the
|
||||
keys pictures are kept under (docs/posters.md, Options, Layers and Finished images). Standard library only, so the
|
||||
merge check tests it as it is.
|
||||
"""
|
||||
import hashlib
|
||||
import math
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Iterable, Optional
|
||||
|
||||
# Part of every layer's and every finished picture's key: raised when what a picture looks like changes, so no
|
||||
# picture made before is served again. r3: licensed sources, kept layers, options and credits.
|
||||
RENDER_VERSION = "r3"
|
||||
|
||||
# A frame is the picture's own size: a poster (race and season) and a session thumbnail.
|
||||
FRAMES = {"poster": (1000, 1500), "thumb": (1920, 1080)}
|
||||
FRAME_OF = {"race": "poster", "season": "poster", "session": "thumb"}
|
||||
|
||||
SHOW_ITEMS = ("wordmark", "round", "name", "subtitle", "date", "circuit", "locality", "session")
|
||||
BACKGROUNDS = ("satellite", "photo", "osm", "dark", "light", "none") # photo is never a style's default
|
||||
BG_ALIASES = {"aerial": "satellite"} # kept for addresses already in use
|
||||
PHOTO_TREATMENTS = ("bw", "natural")
|
||||
FORMATS = {"png": "image/png", "jpg": "image/jpeg", "webp": "image/webp"}
|
||||
STYLES = ("classic", "minimal")
|
||||
ON_OFF = {"on": True, "off": False}
|
||||
TRACK_WIDTHS = (1, 30)
|
||||
MIN_WIDTH = 400 # the full credit line stays readable
|
||||
|
||||
# The accent the classic and minimal styles give the wordmark: F1 red. One place, mirrored by the picker page.
|
||||
DEFAULT_ACCENT = "#dc1220"
|
||||
DEFAULT_TRACK = ("#ffffff", 6)
|
||||
|
||||
# The style's values per kind of picture. classic is how each picture looked before options existed (a thumb had
|
||||
# no checker and no locator); dim is the darkening behind the track, and its shape per kind keeps its proportions.
|
||||
PRESETS = {
|
||||
"classic": {
|
||||
"race": {"show": ("wordmark", "round", "name", "subtitle", "date"), "checker": True, "locator": True, "dim": 0.43},
|
||||
"season": {"show": ("wordmark", "name", "subtitle"), "checker": True, "locator": True, "dim": 0.24},
|
||||
"session": {"show": ("wordmark", "round", "name", "subtitle", "session"), "checker": False, "locator": False,
|
||||
"dim": 0.55},
|
||||
},
|
||||
"minimal": {
|
||||
"race": {"show": ("name", "date"), "checker": False, "locator": False, "dim": 0.25},
|
||||
"season": {"show": ("name", "date"), "checker": False, "locator": False, "dim": 0.25},
|
||||
"session": {"show": ("name", "session"), "checker": False, "locator": False, "dim": 0.25},
|
||||
},
|
||||
}
|
||||
# The dim each kind's darkening was drawn for: the shape is scaled by dim / CLASSIC_DIM[kind].
|
||||
CLASSIC_DIM = {kind: values["dim"] for kind, values in PRESETS["classic"].items()}
|
||||
|
||||
OPTION_NAMES = ("style", "bg", "photo", "show", "locator", "checker", "track", "dim", "accent", "width", "format", "v")
|
||||
_COLOUR = re.compile(r"^#[0-9a-fA-F]{6}$")
|
||||
|
||||
|
||||
class OptionError(ValueError):
|
||||
"""An unknown option or value: answered 422, naming it."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Options:
|
||||
style: str
|
||||
bg: str
|
||||
photo: str
|
||||
show: frozenset
|
||||
locator: bool
|
||||
checker: bool
|
||||
track: Optional[tuple[str, int]] # None: off
|
||||
dim: float
|
||||
accent: str
|
||||
width: int
|
||||
format: str
|
||||
versioned: bool # the address carries the current render version (?v=)
|
||||
|
||||
def canonical(self) -> str:
|
||||
"""The options as they are drawn, the style resolved: two addresses that draw the same picture match."""
|
||||
track = f"{self.track[0]},{self.track[1]}" if self.track else "off"
|
||||
return (f"bg={self.bg};photo={self.photo};show={','.join(sorted(self.show))};"
|
||||
f"locator={'on' if self.locator else 'off'};checker={'on' if self.checker else 'off'};"
|
||||
f"track={track};dim={self.dim:g};accent={self.accent};width={self.width};format={self.format}")
|
||||
|
||||
|
||||
def _choice(name: str, value: str, allowed: Iterable[str]) -> str:
|
||||
if value not in allowed:
|
||||
raise OptionError(f"unknown value {value!r} for option {name!r}; it takes {', '.join(allowed)}")
|
||||
return value
|
||||
|
||||
|
||||
def _colour(name: str, value: str) -> str:
|
||||
if not _COLOUR.match(value):
|
||||
raise OptionError(f"unknown value {value!r} for option {name!r}; it takes a colour #rrggbb")
|
||||
return value.lower()
|
||||
|
||||
|
||||
def parse_options(items: Iterable[tuple[str, str]], kind: str) -> Options:
|
||||
"""The query of a picture's address, checked: kind is race, season or session. Any option given overrides the
|
||||
style's preset; an unknown option, a repeated one or an unknown value raises OptionError."""
|
||||
given: dict[str, str] = {}
|
||||
for name, value in items:
|
||||
if name not in OPTION_NAMES:
|
||||
raise OptionError(f"unknown option {name!r}; options are {', '.join(OPTION_NAMES)}")
|
||||
if name in given:
|
||||
raise OptionError(f"option {name!r} given more than once")
|
||||
given[name] = value
|
||||
|
||||
style = _choice("style", given.get("style", "classic"), STYLES)
|
||||
preset = PRESETS[style][kind]
|
||||
frame_width = FRAMES[FRAME_OF[kind]][0]
|
||||
|
||||
bg = given.get("bg", "satellite")
|
||||
bg = _choice("bg", BG_ALIASES.get(bg, bg), BACKGROUNDS + tuple(BG_ALIASES))
|
||||
photo = _choice("photo", given.get("photo", "natural"), PHOTO_TREATMENTS)
|
||||
|
||||
if "show" in given:
|
||||
show = frozenset(item for item in given["show"].split(",") if item)
|
||||
unknown = sorted(show - set(SHOW_ITEMS))
|
||||
if unknown:
|
||||
raise OptionError(f"unknown value {unknown[0]!r} for option 'show'; it takes a comma list of "
|
||||
f"{', '.join(SHOW_ITEMS)}")
|
||||
else:
|
||||
show = frozenset(preset["show"])
|
||||
|
||||
locator = ON_OFF[_choice("locator", given["locator"], ON_OFF)] if "locator" in given else preset["locator"]
|
||||
checker = ON_OFF[_choice("checker", given["checker"], ON_OFF)] if "checker" in given else preset["checker"]
|
||||
|
||||
track: Optional[tuple[str, int]] = DEFAULT_TRACK
|
||||
if "track" in given:
|
||||
if given["track"] == "off":
|
||||
track = None
|
||||
else:
|
||||
colour, _, width = given["track"].partition(",")
|
||||
colour = _colour("track", colour)
|
||||
if width:
|
||||
if not width.isdigit() or not TRACK_WIDTHS[0] <= int(width) <= TRACK_WIDTHS[1]:
|
||||
raise OptionError(f"unknown value {given['track']!r} for option 'track'; it takes off or "
|
||||
f"#rrggbb with an optional width {TRACK_WIDTHS[0]} to {TRACK_WIDTHS[1]}, #ffffff,6")
|
||||
track = (colour, int(width))
|
||||
else:
|
||||
track = (colour, DEFAULT_TRACK[1])
|
||||
|
||||
dim = preset["dim"]
|
||||
if "dim" in given:
|
||||
try:
|
||||
dim = float(given["dim"])
|
||||
except ValueError:
|
||||
dim = math.nan
|
||||
if not 0 <= dim <= 1: # also refuses nan
|
||||
raise OptionError(f"unknown value {given['dim']!r} for option 'dim'; it takes a number from 0 to 1")
|
||||
|
||||
accent = _colour("accent", given["accent"]) if "accent" in given else DEFAULT_ACCENT
|
||||
|
||||
width = frame_width
|
||||
if "width" in given:
|
||||
if not given["width"].isdigit() or not MIN_WIDTH <= int(given["width"]) <= frame_width:
|
||||
raise OptionError(f"unknown value {given['width']!r} for option 'width'; it takes {MIN_WIDTH} up to "
|
||||
f"{frame_width}")
|
||||
width = int(given["width"])
|
||||
|
||||
fmt = _choice("format", given.get("format", "png"), tuple(FORMATS))
|
||||
return Options(style=style, bg=bg, photo=photo, show=show, locator=locator, checker=checker, track=track,
|
||||
dim=dim, accent=accent, width=width, format=fmt, versioned=given.get("v") == RENDER_VERSION)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ keys
|
||||
|
||||
def trace_hash(coordinates) -> str:
|
||||
"""A layout's trace, as the layer keys name it: a changed trace makes a new key."""
|
||||
return hashlib.sha256(repr(coordinates).encode()).hexdigest()[:16]
|
||||
|
||||
|
||||
def map_layer_key(source_key: str, trace: str, frame: str, zoom: int) -> str:
|
||||
return f"map/{source_key}/{trace}-{frame}-z{zoom}-{RENDER_VERSION}"
|
||||
|
||||
|
||||
def photo_layer_key(file: str, sha1: str, frame: str) -> str:
|
||||
name = hashlib.sha256(file.encode()).hexdigest()[:12] # a Commons title may hold any character
|
||||
return f"photo/{name}-{sha1}-{frame}-{RENDER_VERSION}"
|
||||
|
||||
|
||||
def locator_layer_key(lat: float, lon: float) -> str:
|
||||
return f"locator/{round(lat, 2):.2f}_{round(lon, 2):.2f}-{RENDER_VERSION}"
|
||||
|
||||
|
||||
def outline_layer_key(trace: str, frame: str, zoom: int) -> str:
|
||||
return f"outline/{trace}-{frame}-z{zoom}"
|
||||
|
||||
|
||||
def finished_key(route: str, options: Options, layer_keys: Iterable[str]) -> str:
|
||||
"""A finished picture's name in the store: its route, its options and the keys of the layers it was made from."""
|
||||
made_of = "|".join(sorted(layer_keys))
|
||||
digest = hashlib.sha256(f"{RENDER_VERSION}\n{route}\n{options.canonical()}\n{made_of}".encode()).hexdigest()
|
||||
return f"{digest[:40]}.{options.format}"
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ what clients keep
|
||||
|
||||
def cache_headers(kept: bool, versioned: bool, etag: str) -> dict[str, str]:
|
||||
"""An address with the current render version is kept for good; any other a day, asked again with its ETag;
|
||||
a picture served without its layer five minutes, with no ETag."""
|
||||
if not kept:
|
||||
return {"Cache-Control": "public, max-age=300"}
|
||||
if versioned:
|
||||
return {"Cache-Control": "public, max-age=31536000, immutable", "ETag": etag}
|
||||
return {"Cache-Control": "public, max-age=86400", "ETag": etag}
|
||||
|
||||
|
||||
def etag_matches(if_none_match: str, etag: str) -> bool:
|
||||
"""If-None-Match against our ETag by the weak comparison: W/ is ignored on both sides."""
|
||||
tags = [tag.strip().removeprefix("W/") for tag in (if_none_match or "").split(",")]
|
||||
return etag.removeprefix("W/") in tags or "*" in tags
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ the store's cap
|
||||
|
||||
def evictions(entries: dict[str, tuple[float, int]], cap: int) -> list[str]:
|
||||
"""The stored pictures to remove, least recently used first, until the rest fit the cap.
|
||||
entries: name → (last used, size in bytes)."""
|
||||
total = sum(size for _, size in entries.values())
|
||||
out = []
|
||||
for name, (_, size) in sorted(entries.items(), key=lambda item: item[1][0]):
|
||||
if total <= cap:
|
||||
break
|
||||
out.append(name)
|
||||
total -= size
|
||||
return out
|
||||
@@ -0,0 +1,325 @@
|
||||
"""Where every poster picture comes from, under which licence, and the credit each source asks for (docs/posters.md,
|
||||
Sources). Standard library only, so the merge check tests it as it is.
|
||||
|
||||
bg=satellite takes, per layout, the national aerial photo of the circuit's country, else EOxCloudless (or the dark
|
||||
map where the operator set {"use": "map"}). bg=photo takes the layout's picked Wikimedia Commons photo, and without a
|
||||
pick falls back to bg=satellite. The national credit lines and tile
|
||||
addresses were read from each provider's own pages and confirmed against real tiles on 2026-11-27:
|
||||
|
||||
- USGS: the service description of USGSImageryOnly (its copyright text is the credit; cached to level 16, 17 is a
|
||||
404); USGS-produced data are in the U.S. public domain.
|
||||
- PDOK: the WMTS capabilities of luchtfotorgb (Actueel_orthoHR, EPSG:3857, column before row); PDOK asks to refer
|
||||
to "het Samenwerkingsverband Beeldmateriaal en naar de CC-BY-licentie".
|
||||
- IGN: the Géoplateforme WMTS (Licence Ouverte / Etalab 2.0, whose credit needs the producer and the date of the
|
||||
last update). A yearly layer holds only the départements flown that year, so a frame near a border falls into a
|
||||
hole; the frozen mosaic of 2021-2023 covers all of France (every French layout's frame corners answered), and its
|
||||
dates never change.
|
||||
- EOX: the WMTS capabilities (s2cloudless_3857 is 2016, CC BY 4.0; the newest is 2025, CC BY-NC-SA 4.0); its
|
||||
levels go to 21, its own picture's detail stops at about 14 (2016) and 16 (2025).
|
||||
"""
|
||||
import dataclasses
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import unicodedata
|
||||
import urllib.parse
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Optional, Union
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MapSource:
|
||||
"""One tiled map source, in one year where it has years."""
|
||||
id: str # usgs, pdok, ign, eox, osm
|
||||
year: Optional[Union[int, str]] # the mosaic's year or years (EOX, IGN); None for a source without years
|
||||
tiles: str # the tile address, with {z}, {x} and {y}
|
||||
max_zoom: int # its deepest level: a picture never asks deeper
|
||||
slots: int # requests to its host at once, over every render side by side
|
||||
credit: str # drawn on every picture made from it
|
||||
tint: Optional[str] = None # its tiles recoloured when drawn (dark), whatever bg asked; None: as bg says
|
||||
|
||||
@property
|
||||
def host(self) -> str:
|
||||
return urllib.parse.urlsplit(self.tiles).hostname or ""
|
||||
|
||||
@property
|
||||
def key(self) -> str:
|
||||
"""The source and its year, as a layer key names them."""
|
||||
return f"{self.id}-{self.year if self.year is not None else 'current'}"
|
||||
|
||||
@property
|
||||
def share(self) -> Optional[str]:
|
||||
"""What it asks of a picture made from it: EOX's mosaics after 2016 are NC-SA; the others only a credit."""
|
||||
return NC_SA if self.id == "eox" and self.year != EOX_FREE_YEAR else None
|
||||
|
||||
|
||||
COMMONS = "commons" # bg=photo: the layout's picked Commons photo
|
||||
MAP_OVERRIDE = "map" # a layout's entry {"use": "map"}: its satellite background is the dark map, not EOX
|
||||
|
||||
# What a source asks of a picture made from it, beyond its credit: share-alike (a CC BY-SA photo) or
|
||||
# non-commercial share-alike (EOX's mosaics after 2016). The two can never meet on one picture.
|
||||
BY_SA, NC_SA = "by-sa", "nc-sa"
|
||||
PICTURE_LICENCES = { # what a source asks → the picture's licence, its address, and when it applies
|
||||
BY_SA: ("CC BY-SA 4.0", "https://creativecommons.org/licenses/by-sa/4.0/", "made from a CC BY-SA photo"),
|
||||
NC_SA: ("CC BY-NC-SA 4.0", "https://creativecommons.org/licenses/by-nc-sa/4.0/",
|
||||
"made from EOX's mosaics after 2016"),
|
||||
None: ("CC BY 4.0", "https://creativecommons.org/licenses/by/4.0/", "otherwise"),
|
||||
}
|
||||
|
||||
# EOxCloudless: the 2016 mosaic is CC BY 4.0, later ones CC BY-NC-SA 4.0.
|
||||
EOX_FREE_YEAR = 2016
|
||||
EOX_NEWEST = 2025
|
||||
# The one switch for EOX's year. True: a layout first raced in or before 2016 takes the 2016 mosaic (its track is on
|
||||
# it, and the picture stays free of share-alike), a later one the newest. False: every layout takes the newest
|
||||
# mosaic. A picture's licence (X-License) follows from the mosaic it was made from. The operator chose the newest
|
||||
# (2026-11-27): the 2016 mosaic is too soft at a circuit's zoom.
|
||||
EOX_2016_FOR_EARLY_LAYOUTS = False
|
||||
|
||||
# IGN's frozen mosaic of the photos flown in 2021 to 2023: France is flown every three years, so it covers all of
|
||||
# it, and its dates are the credit's.
|
||||
IGN_PERIOD = "2021-2023"
|
||||
|
||||
EOX_CREDIT = ("EOxCloudless https://cloudless.eox.at by EOX IT Services GmbH "
|
||||
"(Contains modified Copernicus Sentinel data {year})")
|
||||
IGN_CREDIT = "© IGN – BD ORTHO, {years}"
|
||||
OSM_CREDIT = "© OpenStreetMap contributors"
|
||||
COMMONS_CREDIT = "Photo: {author}, {licence}, via Wikimedia Commons"
|
||||
JOLPICA_CREDIT = "Race schedules: Jolpica F1 API (https://github.com/jolpica/jolpica-f1), CC BY-NC-SA 4.0"
|
||||
|
||||
|
||||
def usgs() -> MapSource:
|
||||
return MapSource("usgs", None,
|
||||
"https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}",
|
||||
max_zoom=16, slots=4, credit="USDA, USGS The National Map: Orthoimagery")
|
||||
|
||||
|
||||
def pdok() -> MapSource:
|
||||
return MapSource("pdok", None,
|
||||
"https://service.pdok.nl/hwh/luchtfotorgb/wmts/v1_0/Actueel_orthoHR/EPSG:3857/{z}/{x}/{y}.jpeg",
|
||||
max_zoom=21, slots=4, credit="Luchtfoto: PDOK / Samenwerkingsverband Beeldmateriaal, CC BY 4.0")
|
||||
|
||||
|
||||
def ign() -> MapSource:
|
||||
# Two requests at once: at four, IGN reset connections.
|
||||
return MapSource("ign", IGN_PERIOD,
|
||||
"https://data.geopf.fr/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0"
|
||||
f"&LAYER=ORTHOIMAGERY.ORTHOPHOTOS{IGN_PERIOD}&STYLE=normal&TILEMATRIXSET=PM_6_19"
|
||||
"&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=image/jpeg",
|
||||
max_zoom=19, slots=2, credit=IGN_CREDIT.format(years=IGN_PERIOD.replace("-", "–")))
|
||||
|
||||
|
||||
def eox(year: int) -> MapSource:
|
||||
layer = "s2cloudless_3857" if year == EOX_FREE_YEAR else f"s2cloudless-{year}_3857"
|
||||
return MapSource("eox", year,
|
||||
f"https://tiles.maps.eox.at/wmts/1.0.0/{layer}/default/g/{{z}}/{{y}}/{{x}}.jpg",
|
||||
max_zoom=21, slots=4, credit=EOX_CREDIT.format(year=year))
|
||||
|
||||
|
||||
def osm() -> MapSource:
|
||||
# OpenStreetMap's tile usage policy: at most two connections, only when a picture is asked for, never ahead.
|
||||
return MapSource("osm", None, "https://tile.openstreetmap.org/{z}/{x}/{y}.png",
|
||||
max_zoom=19, slots=2, credit=OSM_CREDIT)
|
||||
|
||||
|
||||
def layout_first_year(layout_slug: str) -> int:
|
||||
"""A layout is named by its years: "2004-", "1950-1970" or "2010"."""
|
||||
return int(layout_slug.split("-")[0])
|
||||
|
||||
|
||||
def dark_map() -> MapSource:
|
||||
"""OpenStreetMap drawn dark, credited as OpenStreetMap: a layout's satellite background where the operator set
|
||||
{"use": "map"}."""
|
||||
return dataclasses.replace(osm(), tint="dark")
|
||||
|
||||
|
||||
def satellite_source(country_slug: str, circuit_slug: str, layout_slug: str,
|
||||
entry: Optional[dict] = None) -> MapSource:
|
||||
"""The satellite chain (bg=satellite, aerial): the national aerial photo of the circuit's country, else the
|
||||
chain's last link (satellite_fallback). "use": "map" in the layout's entry in circuits/photos.json makes that last
|
||||
link the dark map, whether or not the entry also holds a photo; a national source still wins over it (it is
|
||||
sharper). A picked photo is not in this chain."""
|
||||
if country_slug == "united-states":
|
||||
return usgs()
|
||||
if country_slug == "netherlands":
|
||||
return pdok()
|
||||
if country_slug == "france":
|
||||
return ign()
|
||||
if entry and entry.get("use") == MAP_OVERRIDE:
|
||||
return dark_map()
|
||||
return satellite_fallback(layout_slug)
|
||||
|
||||
|
||||
def photo_source(country_slug: str, circuit_slug: str, layout_slug: str,
|
||||
entry: Optional[dict] = None) -> Union[str, MapSource]:
|
||||
"""bg=photo: the layout's picked Commons photo (COMMONS), drawn with the track as an inset; without the photo
|
||||
fields, whatever bg=satellite draws for the layout (the dark map where "use": "map" is set). Never the default of
|
||||
any style."""
|
||||
return COMMONS if is_photo(entry) else satellite_source(country_slug, circuit_slug, layout_slug, entry)
|
||||
|
||||
|
||||
def satellite_fallback(layout_slug: str) -> MapSource:
|
||||
"""The satellite chain's last link, for a layout no picked photo and no national aerial photo has: EOxCloudless.
|
||||
The one place that decides it."""
|
||||
early = EOX_2016_FOR_EARLY_LAYOUTS and layout_first_year(layout_slug) <= EOX_FREE_YEAR
|
||||
return eox(EOX_FREE_YEAR if early else EOX_NEWEST)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ picks
|
||||
|
||||
_FREE_LICENCE = re.compile(r"^(CC0|PUBLIC DOMAIN|PD\b|PD-|CC[- ]BY(-SA)?[- ]\d)", re.IGNORECASE)
|
||||
|
||||
|
||||
def is_free_licence(licence: str) -> bool:
|
||||
"""Only CC0, public domain, CC BY and CC BY-SA: never NC or ND, never a photo without a free licence."""
|
||||
return bool(_FREE_LICENCE.match((licence or "").strip()))
|
||||
|
||||
|
||||
PHOTO_FIELDS = ("file", "licence", "author", "credit", "date")
|
||||
|
||||
|
||||
def entry_problem(entry) -> Optional[str]:
|
||||
"""Why a picks file's entry is refused, or None. An entry carries the photo fields (all of PHOTO_FIELDS, under a
|
||||
free licence), which decide bg=photo; the override {"use": "map"}, which decides bg=satellite; or both."""
|
||||
if not isinstance(entry, dict):
|
||||
return "not an object"
|
||||
if "use" in entry and entry["use"] != MAP_OVERRIDE:
|
||||
return f"unknown use {entry['use']!r}; it takes {MAP_OVERRIDE!r}"
|
||||
given = [field for field in PHOTO_FIELDS if entry.get(field)]
|
||||
if given and len(given) < len(PHOTO_FIELDS):
|
||||
return f"incomplete photo fields: no {', '.join(f for f in PHOTO_FIELDS if f not in given)}"
|
||||
if not given and "use" not in entry:
|
||||
return "neither the photo fields nor a use"
|
||||
if given and not is_free_licence(entry["licence"]):
|
||||
return f"licence {entry['licence']!r} is not CC0, public domain, CC BY or CC BY-SA"
|
||||
return None
|
||||
|
||||
|
||||
def is_photo(entry: Optional[dict]) -> bool:
|
||||
return bool(entry and entry.get("file"))
|
||||
|
||||
|
||||
def read_picks(path: Path) -> dict[str, dict]:
|
||||
"""A picks file (circuits/photos.json, seasons/photos.json): key → its entry. Keys starting with "$" are notes;
|
||||
an entry entry_problem refuses is left out and logged."""
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
picks = {}
|
||||
for key, entry in data.items():
|
||||
if key.startswith("$"):
|
||||
continue
|
||||
problem = entry_problem(entry)
|
||||
if problem:
|
||||
logger.error(f"{path}: the entry {key!r} is refused: {problem}")
|
||||
continue
|
||||
picks[key] = entry
|
||||
return picks
|
||||
|
||||
|
||||
def pick_credit(pick: dict) -> str:
|
||||
return pick.get("credit") or COMMONS_CREDIT.format(author=pick.get("author", "unknown"),
|
||||
licence=pick.get("licence", ""))
|
||||
|
||||
|
||||
def pick_share(pick: dict) -> Optional[str]:
|
||||
"""A CC BY-SA photo (2.0, 3.0, 3.0 DE, 4.0: each allows a later version) makes its picture CC BY-SA 4.0."""
|
||||
return BY_SA if re.match(r"^CC[- ]BY-SA\b", (pick.get("licence") or "").strip(), re.IGNORECASE) else None
|
||||
|
||||
|
||||
class LicenceClash(ValueError):
|
||||
"""A picture that would be made from a CC BY-SA photo and an NC-SA mosaic: refused, never drawn."""
|
||||
|
||||
|
||||
def picture_licence(shares: list[Optional[str]]) -> str:
|
||||
"""A picture's licence follows its sources: CC BY-SA 4.0 when made from a CC BY-SA photo, CC BY-NC-SA 4.0 when
|
||||
made from an EOX mosaic after 2016, CC BY 4.0 otherwise (CC0, public domain or CC BY photos, the 2016 mosaic,
|
||||
USGS, PDOK, IGN, OpenStreetMap). Jolpica's names and dates are single facts and set no licence."""
|
||||
asked = set(s for s in shares if s)
|
||||
if asked == {BY_SA, NC_SA}:
|
||||
raise LicenceClash("a CC BY-SA photo and an NC-SA mosaic cannot make one picture")
|
||||
return PICTURE_LICENCES[asked.pop() if asked else None][0]
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ credits
|
||||
|
||||
def credit_line(credits: list[str]) -> str:
|
||||
"""Every source a picture was made from, each once, in order, joined with " · "."""
|
||||
return " · ".join(dict.fromkeys(c for c in credits if c))
|
||||
|
||||
|
||||
_SPELLED = {"ß": "ss", "æ": "ae", "Æ": "AE", "ø": "o", "Ø": "O", "œ": "oe", "Œ": "OE", "đ": "d", "Đ": "D"}
|
||||
|
||||
|
||||
def ascii_header(text: str) -> str:
|
||||
"""The credit line as an ASCII header value (many clients read headers as Latin-1): "©" as "(c)", the " · "
|
||||
between sources as " | ", ß, æ, ø, œ and đ spelled out, accents folded, en and em dashes as "-", any other
|
||||
character outside ASCII as "?".
|
||||
The drawn line and /licences keep the exact text."""
|
||||
text = text.replace("©", "(c)").replace(" · ", " | ")
|
||||
for letter, spelled in _SPELLED.items(): # letters NFKD does not take apart, spelled out so names stay readable
|
||||
text = text.replace(letter, spelled)
|
||||
folded = "".join(c for c in unicodedata.normalize("NFKD", text) if not unicodedata.combining(c))
|
||||
folded = folded.replace("–", "-").replace("—", "-")
|
||||
return "".join(c if ord(c) < 128 else "?" for c in folded)
|
||||
|
||||
|
||||
def licences() -> dict:
|
||||
"""/licences: every source, its licence, its credit and its terms' address."""
|
||||
by_licence = PICTURE_LICENCES[None][0]
|
||||
picture_licence_of = {"commons": f"{PICTURE_LICENCES[BY_SA][0]} from a CC BY-SA photo, else {by_licence}",
|
||||
"eox": PICTURE_LICENCES[NC_SA][0], "jolpica": "does not set a picture's licence",
|
||||
"traces": "does not set a picture's licence"}
|
||||
|
||||
def source(id, name, used_for, licence, licence_url, credit, terms):
|
||||
return {"id": id, "name": name, "used_for": used_for, "licence": licence, "licence_url": licence_url,
|
||||
"credit": credit, "terms": terms, "picture_licence": picture_licence_of.get(id, by_licence)}
|
||||
nc_sa, by = PICTURE_LICENCES[NC_SA][1], PICTURE_LICENCES[None][1]
|
||||
return {
|
||||
"pictures": {
|
||||
"rule": "A picture's licence follows its sources, and is sent with it as X-License: CC BY-SA 4.0 when it "
|
||||
"is made from a CC BY-SA photo; CC BY-NC-SA 4.0 when it is made from an EOxCloudless mosaic after "
|
||||
"2016; CC BY 4.0 otherwise. The satellite chain takes one source, so the first two never meet.",
|
||||
"licences": [{"licence": name, "licence_url": url, "when": when}
|
||||
for name, url, when in PICTURE_LICENCES.values()],
|
||||
},
|
||||
"tracks": {"licence": "MIT", "licence_url": "https://opensource.org/license/mit"},
|
||||
"sources": [
|
||||
source("commons", "Wikimedia Commons aerial and car photos, picked per layout and per season",
|
||||
"bg=photo where a photo is picked for the layout; season posters",
|
||||
"per file: CC0, public domain, CC BY or CC BY-SA only",
|
||||
"https://commons.wikimedia.org/wiki/Commons:Licensing",
|
||||
COMMONS_CREDIT.format(author="<author>", licence="<licence>"),
|
||||
"https://commons.wikimedia.org/wiki/Commons:Reusing_content_outside_Wikimedia"),
|
||||
source("usgs", "USGS The National Map: Orthoimagery (NAIP)", "bg=satellite for circuits in the United States",
|
||||
"public domain", "https://www.usgs.gov/information-policies-and-instructions/copyrights-and-credits",
|
||||
usgs().credit, "https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer"),
|
||||
source("pdok", "PDOK aerial photo (Beeldmateriaal Nederland)", "bg=satellite for circuits in the Netherlands",
|
||||
"CC BY 4.0", by, pdok().credit,
|
||||
"https://www.pdok.nl/-/hoge-resolutie-luchtfoto-2026-nu-beschikbaar-bij-pdok"),
|
||||
source("ign", f"IGN BD ORTHO, the aerial photos of {IGN_PERIOD}", "bg=satellite for circuits in France",
|
||||
"Licence Ouverte (Etalab) 2.0", "https://www.etalab.gouv.fr/licence-ouverte-open-licence/",
|
||||
ign().credit, "https://cartes.gouv.fr/cgu"),
|
||||
] + ([
|
||||
source("eox-2016", "EOxCloudless 2016 (Sentinel-2, 10 m)",
|
||||
"bg=satellite elsewhere, for a layout first raced in or before 2016",
|
||||
"CC BY 4.0", by, eox(EOX_FREE_YEAR).credit, "https://cloudless.eox.at/documentation/license"),
|
||||
] if EOX_2016_FOR_EARLY_LAYOUTS else []) + [
|
||||
source("eox", f"EOxCloudless {EOX_NEWEST} (Sentinel-2, 10 m)",
|
||||
"bg=satellite elsewhere, for a layout first raced after 2016" if EOX_2016_FOR_EARLY_LAYOUTS
|
||||
else "bg=satellite elsewhere",
|
||||
"CC BY-NC-SA 4.0", nc_sa, eox(EOX_NEWEST).credit, "https://cloudless.eox.at/documentation/license"),
|
||||
source("osm", "OpenStreetMap standard tiles",
|
||||
"bg=osm, bg=dark and bg=light (recoloured), the world locator, and a layout switched to the map",
|
||||
"ODbL (data), tile usage policy", "https://www.openstreetmap.org/copyright", OSM_CREDIT,
|
||||
"https://operations.osmfoundation.org/policies/tiles/"),
|
||||
source("jolpica", "Jolpica F1 API", "race schedules: names, rounds, dates", "CC BY-NC-SA 4.0", nc_sa,
|
||||
JOLPICA_CREDIT, "https://github.com/jolpica/jolpica-f1"),
|
||||
source("traces", "The circuits' GPS traces and layouts", "track outlines, track files", "MIT",
|
||||
"https://opensource.org/license/mit", "Circuit traces and layouts: f1-circuits, MIT License",
|
||||
"https://github.com/bacinger/f1-circuits"),
|
||||
],
|
||||
}
|
||||
+813
-673
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"$comment": "The picked Wikimedia Commons photo per season, from the \"<year> Formula One season cars\" category (docs/posters.md, Season posters and Picking photos). Key: the year, such as \"2024\". Value: {\"file\": the Commons title without \"File:\", \"licence\": its LicenseShortName (CC0, public domain, CC BY or CC BY-SA only), \"author\", \"credit\": \"Photo: <author>, <licence>, via Wikimedia Commons\", \"date\": YYYY[-MM[-DD]]}. Written by the picking tool, read by the poster service; a key starting with \"$\" is a note, not a pick."
|
||||
}
|
||||
+4
-1
@@ -22,9 +22,12 @@ RUN apk add --no-cache \
|
||||
COPY service/requirements.txt ./requirements.txt
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY cdn-api.py access_log.py circuits_service.py ergast_service.py posters_service.py ./
|
||||
COPY cdn-api.py access_log.py app_info.py circuits_service.py ergast_service.py posters_service.py \
|
||||
poster_options.py poster_sources.py ./
|
||||
COPY models/ ./models/
|
||||
COPY circuits/ ./circuits/
|
||||
# The picked photo per season (the picks per layout are in circuits/photos.json).
|
||||
COPY seasons/ ./seasons/
|
||||
# The example site the app serves at /examples/.
|
||||
COPY examples/ ./examples/
|
||||
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
"""The candidate tool reads a Commons file's date, licence and credit as docs/posters.md asks, and ranks marks first."""
|
||||
import importlib.util
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
_spec = importlib.util.spec_from_file_location("commons_candidates", ROOT / "tools" / "commons_candidates.py")
|
||||
cc = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(cc)
|
||||
|
||||
|
||||
def page(title="File:A.jpg", mime="image/jpeg", width=3000, height=2000, **meta):
|
||||
"""One page of an imageinfo answer, as the Action API gives it (formatversion 2)."""
|
||||
return {"title": title, "imageinfo": [{
|
||||
"mime": mime, "width": width, "height": height,
|
||||
"thumburl": "https://upload.wikimedia.org/x/500px-A.jpg?utm_source=commons.wikimedia.org",
|
||||
"descriptionurl": "https://commons.wikimedia.org/wiki/File:A.jpg",
|
||||
"extmetadata": {k: {"value": v} for k, v in meta.items()},
|
||||
}]}
|
||||
|
||||
|
||||
class PhotoDateTest(unittest.TestCase):
|
||||
def test_forms_seen_on_commons(self):
|
||||
cases = {
|
||||
"2018-04-22": "2018-04-22",
|
||||
"2008-06-26 18:57:32": "2008-06-26",
|
||||
"1983-01": "1983-01",
|
||||
"Taken on 29 December 2016, 12:19:34": "2016-12-29",
|
||||
"28 August 2011, 13:44 (according to Exif data)": "2011-08-28",
|
||||
'<time class="dtstart" datetime="2016-12-29">29 December 2016</time>': "2016-12-29",
|
||||
"circa 1930date QS:P,+1930-00-00T00:00:00Z/9": "1930",
|
||||
"07-06-1954": "1954", # day and month order unknown: the year only
|
||||
}
|
||||
for raw, want in cases.items():
|
||||
with self.subTest(raw=raw):
|
||||
self.assertEqual(cc.photo_date(raw), want)
|
||||
|
||||
def test_what_does_not_say_when_it_was_taken(self):
|
||||
for raw in ["1 December 2006 (original upload date)", "1960s", "between 1950 and 1955", ""]:
|
||||
with self.subTest(raw=raw):
|
||||
self.assertIsNone(cc.photo_date(raw))
|
||||
|
||||
|
||||
class CandidateTest(unittest.TestCase):
|
||||
def test_a_free_file_becomes_a_pick_with_the_designs_credit(self):
|
||||
c, why = cc.candidate(page(LicenseShortName="CC BY-SA 2.0", License="cc-by-sa-2.0",
|
||||
Artist='<a href="https://www.flickr.com/x">Nathanael Majoros</a>',
|
||||
DateTimeOriginal="2008-06-26 18:57:32", Assessments="quality|featured"), "search: aerial")
|
||||
self.assertEqual(why, "")
|
||||
self.assertEqual(c["file"], "A.jpg")
|
||||
self.assertEqual(c["author"], "Nathanael Majoros")
|
||||
self.assertEqual(c["credit"], "Photo: Nathanael Majoros, CC BY-SA 2.0, via Wikimedia Commons")
|
||||
self.assertEqual(c["date"], "2008-06-26")
|
||||
self.assertEqual(c["marks"], ["quality", "featured"])
|
||||
self.assertNotIn("utm_", c["thumb"])
|
||||
|
||||
def test_attribution_asked_by_the_source_wins_over_the_artist(self):
|
||||
c, _ = cc.candidate(page(LicenseShortName="CC BY-SA 3.0 de", License="cc-by-sa-3.0-de", Artist="Engelbert Reineke",
|
||||
Attribution="Bundesarchiv, B 145 Bild-F029226-0006 / Engelbert Reineke / CC-BY-SA 3.0"), "x")
|
||||
self.assertEqual(c["author"], "Bundesarchiv, B 145 Bild-F029226-0006 / Engelbert Reineke / CC-BY-SA 3.0")
|
||||
|
||||
def test_only_cc0_public_domain_cc_by_and_cc_by_sa(self):
|
||||
free = {"cc0": "CC0", "pd": "Public domain", "cc-by-2.0": "CC BY 2.0", "cc-by-sa-4.0": "CC BY-SA 4.0",
|
||||
"cc-by-sa-3.0-de": "CC BY-SA 3.0 de", "": "Public domain"}
|
||||
for code, short in free.items():
|
||||
with self.subTest(code=code):
|
||||
self.assertIsNotNone(cc.candidate(page(License=code, LicenseShortName=short), "x")[0])
|
||||
for code, short in {"fal": "FAL", "gfdl": "GFDL", "attribution": "Attribution", "": "Copyrighted free use"}.items():
|
||||
with self.subTest(code=code or short):
|
||||
c, why = cc.candidate(page(License=code, LicenseShortName=short), "x")
|
||||
self.assertIsNone(c)
|
||||
self.assertTrue(why.startswith("licence"))
|
||||
|
||||
def test_maps_and_drawings_are_no_photos(self):
|
||||
c, why = cc.candidate(page(mime="image/svg+xml", License="cc0", LicenseShortName="CC0"), "x")
|
||||
self.assertIsNone(c)
|
||||
self.assertIn("not a photo", why)
|
||||
|
||||
|
||||
class SeasonDateTest(unittest.TestCase):
|
||||
def test_an_undated_season_photo_takes_its_seasons_year_and_says_so(self):
|
||||
c = cc.dated_by_season({"file": "Kubica spa.jpg", "date": None}, 2008)
|
||||
self.assertEqual((c["date"], c["date_from"]), ("2008", "category"))
|
||||
|
||||
def test_a_dated_season_photo_keeps_its_own_date(self):
|
||||
c = cc.dated_by_season({"file": "A.jpg", "date": "2009-05-01"}, 2008)
|
||||
self.assertEqual(c["date"], "2009-05-01")
|
||||
self.assertNotIn("date_from", c)
|
||||
|
||||
|
||||
class AerialTest(unittest.TestCase):
|
||||
def test_a_search_hit_is_aerial_only_when_commons_says_so(self):
|
||||
def hit(file, cats, found):
|
||||
return {"file": file, "categories": cats, "found": found}
|
||||
self.assertTrue(cc.says_aerial(hit("Hungaroring, April 28, 2018 SkySat.jpg", [], ["search: aerial"])))
|
||||
self.assertTrue(cc.says_aerial(hit("IMG 0211.JPG", ["Aerial photographs of Mogyoród"], ["search: aérienne"])))
|
||||
self.assertTrue(cc.says_aerial(hit("Zolder racetrack.jpg", [], ["Wikidata aerial view (P8592)"])))
|
||||
self.assertTrue(cc.says_aerial(hit("Bernhardjr2016.jpg", [], ["search: aerial", "search: drone"])))
|
||||
self.assertFalse(cc.says_aerial(hit("FRECA 2025 Mogyoród Race (2).jpg", ["FRECA 2025"], ["search: aérienne"])))
|
||||
|
||||
|
||||
class RankTest(unittest.TestCase):
|
||||
def test_marks_then_size_then_landscape(self):
|
||||
def cand(name, marks, w, h):
|
||||
return {"file": name, "marks": marks, "width": w, "height": h}
|
||||
ranked = sorted([
|
||||
cand("small landscape", [], 2000, 1000),
|
||||
cand("big portrait", [], 2000, 3000),
|
||||
cand("big landscape", [], 3000, 2000),
|
||||
cand("marked small", ["quality"], 800, 600),
|
||||
], key=cc.rank_key)
|
||||
self.assertEqual([c["file"] for c in ranked], ["marked small", "big landscape", "big portrait", "small landscape"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,35 @@
|
||||
"""An unknown country, locality, circuit or layout, or a year no layout covers, is named (the API answers it 404).
|
||||
|
||||
Standard library only: the models load numpy only where a script uses it.
|
||||
"""
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from circuits_service import CircuitService, NotFound
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
class LookupTest(unittest.TestCase):
|
||||
def test_the_first_unknown_part_is_named(self):
|
||||
service = CircuitService(str(ROOT / "circuits" / "circuits.json"))
|
||||
spa = ("belgium", "spa", "circuit-de-spa-francorchamps")
|
||||
self.assertEqual(service.resolve(*spa, "1983-").slug, "1983-")
|
||||
self.assertEqual(service.layout_for_year(*spa, 1960).slug, "1950-1970")
|
||||
cases = {
|
||||
("photos.json",): "No country 'photos.json'",
|
||||
("belgium", "nowhere"): "No locality 'nowhere' in Belgium",
|
||||
("belgium", "spa", "nothing"): "No circuit 'nothing' in Spa",
|
||||
(*spa, "1999"): "No layout '1999' in Circuit de Spa-Francorchamps",
|
||||
}
|
||||
for slugs, named in cases.items():
|
||||
with self.assertRaises(NotFound, msg=slugs) as caught:
|
||||
service.resolve(*slugs)
|
||||
self.assertEqual(str(caught.exception), named)
|
||||
with self.assertRaises(NotFound) as caught:
|
||||
service.layout_for_year(*spa, 1975) # Spa was not raced from 1971 to 1982
|
||||
self.assertEqual(str(caught.exception), "No layout of Circuit de Spa-Francorchamps covers 1975")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,180 @@
|
||||
"""A poster's sources, credits, licence, options, keys and cache headers (docs/posters.md).
|
||||
|
||||
Standard library only (no PIL, no numpy), so the merge check runs it as it is.
|
||||
"""
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import poster_options as po
|
||||
import poster_sources as ps
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
class SatelliteChainTest(unittest.TestCase):
|
||||
def test_the_first_source_that_has_the_layout(self):
|
||||
early = 2016 if ps.EOX_2016_FOR_EARLY_LAYOUTS else 2025 # the one switch for EOX's year
|
||||
photo, use_map = {"file": "A.jpg", "licence": "CC BY 4.0"}, {"use": "map"}
|
||||
both = {**photo, **use_map}
|
||||
cases = [
|
||||
# (country, circuit, layout, the layout's entry in circuits/photos.json) → (source, year, tint)
|
||||
(("bahrain", "bahrain-international-circuit", "2004-", photo), ("eox", early, None)), # a pick is bg=photo's
|
||||
(("united-states", "miami-international-autodrome", "2022-", photo), ("usgs", None, None)),
|
||||
(("netherlands", "circuit-park-zandvoort", "2020-", use_map), ("pdok", None, None)), # national wins
|
||||
(("france", "circuit-paul-ricard", "2018-", None), ("ign", "2021-2023", None)),
|
||||
(("bahrain", "bahrain-international-circuit", "2004-", None), ("eox", early, None)), # first raced by 2016
|
||||
(("bahrain", "bahrain-international-circuit", "2004-", use_map), ("osm", None, "dark")), # the override
|
||||
(("bahrain", "bahrain-international-circuit", "2004-", both), ("osm", None, "dark")), # a photo beside it
|
||||
(("united-states", "miami-international-autodrome", "2022-", both), ("usgs", None, None)),
|
||||
(("spain", "madring", "2026-", None), ("eox", 2025, None)),
|
||||
]
|
||||
for given, expected in cases:
|
||||
chosen = ps.satellite_source(*given)
|
||||
self.assertEqual((chosen.id, chosen.year, chosen.tint), expected, given)
|
||||
self.assertEqual(ps.satellite_source("bahrain", "x", "2004-", use_map).credit, ps.OSM_CREDIT)
|
||||
|
||||
def test_bg_photo_takes_the_pick_else_the_satellite_chain(self):
|
||||
photo = {"file": "A.jpg", "licence": "CC BY-SA 4.0"}
|
||||
self.assertEqual(ps.photo_source("united-states", "miami-international-autodrome", "2022-", photo), ps.COMMONS)
|
||||
self.assertEqual(ps.photo_source("bahrain", "bahrain-international-circuit", "2004-", {**photo, "use": "map"}),
|
||||
ps.COMMONS) # with use: map beside the photo, bg=photo still draws the photo
|
||||
for entry, source in ((None, "usgs"), ({"use": "map"}, "usgs")):
|
||||
self.assertEqual(ps.photo_source("united-states", "miami-international-autodrome", "2022-", entry).id, source)
|
||||
self.assertEqual(ps.photo_source("bahrain", "bahrain-international-circuit", "2004-", {"use": "map"}).tint, "dark")
|
||||
options = po.parse_options([("bg", "photo")], "race")
|
||||
self.assertEqual(options.bg, "photo")
|
||||
self.assertTrue(all(po.parse_options([("style", style)], kind).bg == "satellite"
|
||||
for style in po.STYLES for kind in po.FRAME_OF)) # never a style's default
|
||||
|
||||
def test_every_french_layout_takes_ign(self):
|
||||
france = json.loads((ROOT / "circuits" / "circuits.json").read_text(encoding="utf-8"))["france"]
|
||||
layouts = [(slug, layout) for locality in france["localities"].values()
|
||||
for slug, circuit in locality["circuits"].items() for layout in circuit["layouts"]]
|
||||
self.assertTrue(layouts)
|
||||
for slug, layout in layouts:
|
||||
self.assertEqual(ps.satellite_source("france", slug, layout).id, "ign", (slug, layout))
|
||||
|
||||
|
||||
class CreditAndLicenceTest(unittest.TestCase):
|
||||
def test_credit_line_and_its_header(self):
|
||||
line = ps.credit_line([ps.ign().credit, ps.OSM_CREDIT, ps.OSM_CREDIT, ""])
|
||||
self.assertEqual(line, "© IGN – BD ORTHO, 2021–2023 · © OpenStreetMap contributors")
|
||||
self.assertEqual(ps.ascii_header(line), "(c) IGN - BD ORTHO, 2021-2023 | (c) OpenStreetMap contributors")
|
||||
self.assertEqual(ps.ascii_header("Photo: José Müller — 王 CC BY-SA 4.0"), "Photo: Jose Muller - ? CC BY-SA 4.0")
|
||||
self.assertEqual(ps.ascii_header("Steffen Prößdorf, Søren Bækgaard, Œuvre, Đorđe"),
|
||||
"Steffen Prossdorf, Soren Baekgaard, OEuvre, Dorde")
|
||||
|
||||
def test_a_pictures_licence_follows_its_sources(self):
|
||||
by_sa = ps.pick_share({"licence": "CC BY-SA 3.0 de"})
|
||||
cases = [
|
||||
([by_sa, ps.osm().share], "CC BY-SA 4.0"),
|
||||
([ps.eox(2025).share, ps.osm().share], "CC BY-NC-SA 4.0"),
|
||||
([ps.eox(2016).share, ps.osm().share], "CC BY 4.0"),
|
||||
([ps.pick_share({"licence": "CC BY 2.0"}), ps.usgs().share, ps.pdok().share, ps.ign().share], "CC BY 4.0"),
|
||||
([], "CC BY 4.0"),
|
||||
]
|
||||
for shares, licence in cases:
|
||||
self.assertEqual(ps.picture_licence(shares), licence, shares)
|
||||
with self.assertRaises(ps.LicenceClash):
|
||||
ps.picture_licence([by_sa, ps.eox(2025).share])
|
||||
|
||||
def test_picks_skip_notes_and_refuse_what_they_cannot_use(self):
|
||||
with tempfile.TemporaryDirectory() as kept:
|
||||
path = Path(kept) / "photos.json"
|
||||
def photo(file, licence):
|
||||
return {"file": file, "licence": licence, "author": "A", "credit": "Photo: A", "date": "2020"}
|
||||
path.write_text(json.dumps({
|
||||
"$comment": "a note",
|
||||
"a/b/c/2004-": photo("A.jpg", "CC BY-SA 4.0"),
|
||||
"a/b/c/2010": photo("C.jpg", "Public domain"),
|
||||
"a/b/c/2020-": {"use": "map"},
|
||||
"a/b/c/2021-": {**photo("D.jpg", "CC0"), "use": "map"},
|
||||
"a/b/c/1950-": photo("B.jpg", "CC BY-NC-SA 2.0"), # refused: not a free licence
|
||||
"a/b/c/1990": {"use": "satellite"}, # refused: an unknown use
|
||||
"a/b/c/1991": {"use": "map", "file": "E.jpg", "licence": "CC0"}, # refused: incomplete photo fields
|
||||
"a/b/c/1992": {}, # refused: neither
|
||||
}))
|
||||
with self.assertLogs(ps.logger, "ERROR") as logged:
|
||||
self.assertEqual(sorted(ps.read_picks(path)), ["a/b/c/2004-", "a/b/c/2010", "a/b/c/2020-", "a/b/c/2021-"])
|
||||
self.assertEqual(len(logged.output), 4)
|
||||
for name in ("circuits/photos.json", "seasons/photos.json"):
|
||||
self.assertEqual(ps.read_picks(ROOT / name).get("$comment"), None, name)
|
||||
|
||||
def test_licences_name_every_source_and_the_pictures_rule(self):
|
||||
licences = ps.licences()
|
||||
self.assertEqual([entry["licence"] for entry in licences["pictures"]["licences"]],
|
||||
["CC BY-SA 4.0", "CC BY-NC-SA 4.0", "CC BY 4.0"])
|
||||
self.assertEqual([source["id"] for source in licences["sources"]],
|
||||
["commons", "usgs", "pdok", "ign"] + (["eox-2016"] if ps.EOX_2016_FOR_EARLY_LAYOUTS else [])
|
||||
+ ["eox", "osm", "jolpica", "traces"])
|
||||
for source in licences["sources"]:
|
||||
for field in ("name", "used_for", "licence", "licence_url", "credit", "terms", "picture_licence"):
|
||||
self.assertTrue(source[field], f"{source['id']} has no {field}")
|
||||
|
||||
|
||||
class OptionsTest(unittest.TestCase):
|
||||
def parse(self, query: str, kind: str = "race") -> po.Options:
|
||||
return po.parse_options([tuple(part.split("=", 1)) for part in query.split("&") if part], kind)
|
||||
|
||||
def test_presets_per_kind(self):
|
||||
race, thumb, season = self.parse(""), self.parse("", "session"), self.parse("", "season")
|
||||
self.assertEqual((race.bg, race.photo, race.checker, race.locator, race.dim, race.track, race.width),
|
||||
("satellite", "natural", True, True, 0.43, ("#ffffff", 6), 1000))
|
||||
self.assertEqual((thumb.checker, thumb.locator, thumb.width), (False, False, 1920)) # classic: as before
|
||||
self.assertEqual(sorted(self.parse("style=minimal", "session").show), ["name", "session"])
|
||||
self.assertEqual(sorted(self.parse("style=minimal").show), ["date", "name"])
|
||||
self.assertEqual(sorted(season.show), ["name", "subtitle", "wordmark"])
|
||||
# Any option given overrides the style; equal pictures share one canonical form, whatever their address
|
||||
self.assertEqual(self.parse("style=minimal&checker=on").checker, True)
|
||||
self.assertEqual(self.parse("bg=aerial&v=r1").canonical(), self.parse("").canonical())
|
||||
self.assertTrue(self.parse(f"v={po.RENDER_VERSION}").versioned)
|
||||
self.assertFalse(self.parse("v=r2").versioned)
|
||||
|
||||
def test_an_unknown_option_or_value_is_named(self):
|
||||
cases = {
|
||||
"colour=red": "'colour'", "bg=esri": "'esri'", "photo=duotone": "'duotone'", "show=name,logo": "'logo'",
|
||||
"track=#fff": "'#fff'", "track=#ffffff,31": "'#ffffff,31'", "dim=1.5": "'1.5'", "dim=nan": "'nan'",
|
||||
"width=399": "takes 400", "width=1001": "'1001'", "format=gif": "'gif'", "bg=osm&bg=dark": "'bg'",
|
||||
"locator=yes": "'yes'", "accent=red": "'red'",
|
||||
}
|
||||
for query, named in cases.items():
|
||||
with self.assertRaises(po.OptionError, msg=query) as caught:
|
||||
self.parse(query)
|
||||
self.assertIn(named, str(caught.exception), query)
|
||||
self.assertEqual(self.parse("width=1920", "session").width, 1920)
|
||||
|
||||
def test_keys(self):
|
||||
options = self.parse("")
|
||||
key = po.finished_key("race/Bahrain Grand Prix/2024", options, ["map/eox-2016/x-poster-z15-r3"])
|
||||
self.assertNotEqual(key, po.finished_key("race/Bahrain Grand Prix/2024", self.parse("photo=bw"),
|
||||
["map/eox-2016/x-poster-z15-r3"]))
|
||||
self.assertNotEqual(key, po.finished_key("race/Bahrain Grand Prix/2023", options,
|
||||
["map/eox-2016/x-poster-z15-r3"]))
|
||||
self.assertTrue(key.endswith(".png"))
|
||||
self.assertTrue(po.finished_key("race/Bahrain Grand Prix/2024", self.parse("format=webp"), []).endswith(".webp"))
|
||||
self.assertEqual(po.locator_layer_key(26.0325, 50.5106), f"locator/26.03_50.51-{po.RENDER_VERSION}")
|
||||
self.assertIn(po.RENDER_VERSION, po.map_layer_key("eox-2025", po.trace_hash([[1, 2]]), "thumb", 15))
|
||||
|
||||
|
||||
class CachingTest(unittest.TestCase):
|
||||
def test_what_clients_keep(self):
|
||||
self.assertEqual(po.cache_headers(True, True, '"e"'),
|
||||
{"Cache-Control": "public, max-age=31536000, immutable", "ETag": '"e"'})
|
||||
self.assertEqual(po.cache_headers(True, False, '"e"'), {"Cache-Control": "public, max-age=86400", "ETag": '"e"'})
|
||||
self.assertEqual(po.cache_headers(False, True, '"e"'), {"Cache-Control": "public, max-age=300"})
|
||||
for asked in ('"a", W/"e"', '"e"', 'W/"e"', "*"):
|
||||
self.assertTrue(po.etag_matches(asked, 'W/"e"'), asked) # the weak comparison
|
||||
self.assertFalse(po.etag_matches("", 'W/"e"'))
|
||||
self.assertFalse(po.etag_matches('W/"a"', 'W/"e"'))
|
||||
|
||||
def test_the_least_recently_used_go_first(self):
|
||||
entries = {"old": (1.0, 600), "new": (3.0, 600), "mid": (2.0, 600)}
|
||||
self.assertEqual(po.evictions(entries, 1300), ["old"])
|
||||
self.assertEqual(po.evictions(entries, 600), ["old", "mid"])
|
||||
self.assertEqual(po.evictions(entries, 1800), [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,498 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lists Wikimedia Commons photos the posters may use, for the picker page to show (docs/posters.md, "Picking photos").
|
||||
|
||||
For every layout in circuits/circuits.json: aerial photos of its circuit, dated within the layout's years. For every
|
||||
season 1950-2026: the photos in "<year> Formula One season cars". Only CC0, public domain, CC BY and CC BY-SA; each
|
||||
file's licence, author, credit, date and quality marks are read from the Action API's imageinfo extmetadata, 50
|
||||
files a call. Commons' quality marks rank first, then size, then landscape.
|
||||
|
||||
It writes examples/data/candidates.json:
|
||||
|
||||
{"about": {...},
|
||||
"layouts": {"<country>/<city>/<circuit>/<layout>": [candidate, ...]},
|
||||
"seasons": {"<year>": [candidate, ...]}}
|
||||
|
||||
A search hit counts as an aerial photo only when its title or a category says so, or two search words found it: a
|
||||
word in its description alone matched hundreds of race photos taken from the ground. A candidate holds the fields of a
|
||||
pick (file, licence, author, credit, date) and what the picker shows beside them (thumb, page, width, height, marks,
|
||||
restrictions, found). A layout's key is its path under circuits/ without an extension, the key circuits/photos.json
|
||||
uses; a season's is its year. A season candidate whose file gives no date takes the season's year, marked
|
||||
"date_from": "category".
|
||||
|
||||
Commons' rules, kept here: a descriptive User-Agent with the app's address and no person's; one API request at a
|
||||
time and at most five a second (a request starts at least REQUEST_GAP after the one before); a 429 or a maxlag
|
||||
answer waits its Retry-After; no image is downloaded, only thumbnail addresses written for the page. A call that
|
||||
still fails after its retries stops the run, and nothing is written: a partial list is never kept.
|
||||
|
||||
Standard library only. Run from the repository root:
|
||||
|
||||
python3 tools/commons_candidates.py # every layout and season, writes the file
|
||||
python3 tools/commons_candidates.py --only belgium/spa --seasons 2018-2019 --out - # a part, to stdout
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import html
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
CIRCUITS = ROOT / "circuits" / "circuits.json"
|
||||
OUT = ROOT / "examples" / "data" / "candidates.json"
|
||||
|
||||
USER_AGENT = "f1-circuits-picker/1.0 (+https://f1-circuits.zurag.be)"
|
||||
COMMONS = "https://commons.wikimedia.org/w/api.php"
|
||||
WIKIDATA = "https://www.wikidata.org/w/api.php"
|
||||
ENWIKI = "https://en.wikipedia.org/w/api.php"
|
||||
REQUEST_GAP = 0.25 # seconds between request starts: at most four a second, under Commons' five
|
||||
RETRIES = 4
|
||||
THUMB_WIDTH = 500 # one of Commons' standard thumbnail widths
|
||||
FIRST_SEASON, LAST_SEASON = 1950, 2026
|
||||
THIS_YEAR = dt.date.today().year
|
||||
|
||||
# One word per query: an OR matched unrelated files worldwide (the licence research, 11.1).
|
||||
# "SkySat" is read in titles only: as a word it stems to "sky" and matches race photos.
|
||||
AERIAL_WORDS = ["aerial", "luchtfoto", "Luftbild", "aérienne", "aerea", "drone", "intitle:SkySat"]
|
||||
MARKED = "incategory:Quality_images|Featured_pictures_on_Wikimedia_Commons|Valued_images_sorted_by_promotion_date"
|
||||
MARK_WEIGHT = {"poty": 5, "potd": 4, "featured": 3, "valued": 2, "quality": 1}
|
||||
# A search word may sit in a file's description only ("aérienne" alone matched hundreds of race photos taken from
|
||||
# the ground), so a search hit counts as aerial when its title or a category says so, or two words found it.
|
||||
AERIAL_SAYS = re.compile(
|
||||
r"aerial|luchtfoto|luchtopname|overzicht|luftbild|luftaufnahme|a[ée]rienne|a[ée]re[ao]|drone|\bdji\b|skysat|satellite|"
|
||||
r"bird.?s.?eye|vogelvlucht|from above|from the air|from (an )?(aircraft|airplane|plane|helicopter)|orthophoto|overview",
|
||||
re.I)
|
||||
PHOTO_MIME = {"image/jpeg", "image/tiff", "image/webp"} # maps and drawings come as SVG, PNG or GIF
|
||||
NOT_A_PHOTO = re.compile(r"\bmaps?\b|\bdiagrams?\b|\blogos?\b|\bplans?\b|\bschemes?\b", re.I)
|
||||
SEASON_KEEP = 40 # the best of a season's hundreds of files
|
||||
LAYOUT_KEEP = 40
|
||||
|
||||
EXTMETA = ("LicenseShortName|License|LicenseUrl|UsageTerms|Artist|Credit|Attribution|AttributionRequired|"
|
||||
"Restrictions|DateTimeOriginal|Assessments|Categories")
|
||||
|
||||
# The licences a pick may carry, by Commons' machine-readable code (extmetadata License).
|
||||
FREE = re.compile(r"^(cc0|pd([-a-z0-9]*)?|cc-by-\d[\d.,]*([-a-z]+)?|cc-by-sa-\d[\d.,]*([-a-z]+)?)$", re.I)
|
||||
|
||||
|
||||
class Fetcher:
|
||||
"""One request at a time, paced, retried; the only way this tool reaches Wikimedia."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.last = 0.0
|
||||
self.count = 0
|
||||
|
||||
def get(self, endpoint: str, params: dict) -> dict:
|
||||
params = {"format": "json", "formatversion": "2", "maxlag": "5", **params}
|
||||
url = endpoint + "?" + urllib.parse.urlencode(params)
|
||||
wait = 2.0
|
||||
for attempt in range(RETRIES + 1):
|
||||
gap = self.last + REQUEST_GAP - time.monotonic()
|
||||
if gap > 0:
|
||||
time.sleep(gap)
|
||||
self.last = time.monotonic()
|
||||
self.count += 1
|
||||
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "application/json"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=90) as res:
|
||||
body = json.load(res)
|
||||
except urllib.error.HTTPError as e:
|
||||
if attempt < RETRIES and (e.code == 429 or e.code >= 500):
|
||||
time.sleep(_retry_after(e.headers.get("Retry-After"), wait))
|
||||
wait *= 2
|
||||
continue
|
||||
raise SystemExit(f"commons_candidates: HTTP {e.code} for {url}") from e
|
||||
except (urllib.error.URLError, TimeoutError) as e:
|
||||
if attempt < RETRIES:
|
||||
time.sleep(wait)
|
||||
wait *= 2
|
||||
continue
|
||||
raise SystemExit(f"commons_candidates: no answer for {url}: {e}") from e
|
||||
err = body.get("error")
|
||||
if err and err.get("code") == "maxlag" and attempt < RETRIES:
|
||||
time.sleep(max(5.0, wait))
|
||||
wait *= 2
|
||||
continue
|
||||
if err:
|
||||
raise SystemExit(f"commons_candidates: the API refused {url}: {err.get('code')}: {err.get('info')}")
|
||||
return body
|
||||
raise SystemExit(f"commons_candidates: gave up on {url}")
|
||||
|
||||
|
||||
def _retry_after(value: str | None, default: float) -> float:
|
||||
try:
|
||||
return max(1.0, float(value))
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- reading a file's metadata
|
||||
|
||||
def plain(value: str) -> str:
|
||||
"""Text of an extmetadata value: tags removed, entities decoded, whitespace folded."""
|
||||
text = re.sub(r"<br\s*/?>", " ", value or "", flags=re.I)
|
||||
text = re.sub(r"<[^>]+>", "", text)
|
||||
return re.sub(r"\s+", " ", html.unescape(text)).strip()
|
||||
|
||||
|
||||
MONTHS = {m: i for i, m in enumerate(
|
||||
["january", "february", "march", "april", "may", "june", "july", "august", "september", "october",
|
||||
"november", "december"], 1)}
|
||||
MONTH_RE = "(" + "|".join(MONTHS) + ")"
|
||||
|
||||
|
||||
def photo_date(raw: str) -> str | None:
|
||||
"""When the photo was taken, as YYYY, YYYY-MM or YYYY-MM-DD; None when the value does not say (an upload date,
|
||||
a decade, a range). Forms seen on Commons are in the licence research, 11.3."""
|
||||
if not raw:
|
||||
return None
|
||||
qs = re.search(r"QS:P\d*,\+(\d{4})-(\d{2})-(\d{2})T[^/]*/(\d+)", raw)
|
||||
if qs:
|
||||
year, month, day, precision = qs.group(1), qs.group(2), qs.group(3), int(qs.group(4))
|
||||
if precision >= 11 and day != "00":
|
||||
return f"{year}-{month}-{day}"
|
||||
if precision == 10 and month != "00":
|
||||
return f"{year}-{month}"
|
||||
return year if precision == 9 else None
|
||||
attr = re.search(r'datetime="(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?', raw)
|
||||
if attr:
|
||||
return "-".join(p for p in attr.groups() if p)
|
||||
text = plain(raw).lower()
|
||||
if "upload" in text or re.search(r"\d{4}s\b", text) or re.search(r"\bbetween\b|\bor\b", text):
|
||||
return None
|
||||
m = re.search(r"\b(\d{4})[-:](\d{2})[-:](\d{2})\b", text)
|
||||
if m and m.group(2) != "00":
|
||||
return f"{m.group(1)}-{m.group(2)}" + (f"-{m.group(3)}" if m.group(3) != "00" else "")
|
||||
m = re.search(r"\b(\d{1,2})(?:st|nd|rd|th)? " + MONTH_RE + r",? (\d{4})\b", text)
|
||||
if m:
|
||||
return f"{m.group(3)}-{MONTHS[m.group(2)]:02d}-{int(m.group(1)):02d}"
|
||||
m = re.search(MONTH_RE + r" (\d{1,2}),? (\d{4})\b", text)
|
||||
if m:
|
||||
return f"{m.group(3)}-{MONTHS[m.group(1)]:02d}-{int(m.group(2)):02d}"
|
||||
m = re.search(MONTH_RE + r",? (\d{4})\b", text)
|
||||
if m:
|
||||
return f"{m.group(2)}-{MONTHS[m.group(1)]:02d}"
|
||||
m = re.search(r"\b(\d{4})-(\d{2})\b", text)
|
||||
if m and 1 <= int(m.group(2)) <= 12:
|
||||
return f"{m.group(1)}-{m.group(2)}"
|
||||
years = set(re.findall(r"\b(1[89]\d{2}|20\d{2})\b", text))
|
||||
if len(years) == 1: # "1983", "circa 1983", "07-06-1954" (day and month order unknown: the year only)
|
||||
return years.pop()
|
||||
return None
|
||||
|
||||
|
||||
def licence_code(short: str) -> str:
|
||||
"""Commons' machine code from a short licence name, for a file whose License field is empty."""
|
||||
s = short.strip().lower()
|
||||
if s in ("public domain", "pd"):
|
||||
return "pd"
|
||||
if s == "cc0":
|
||||
return "cc0"
|
||||
return re.sub(r"\s+", "-", s.replace("cc by", "cc-by"))
|
||||
|
||||
|
||||
def candidate(page: dict, found: str) -> tuple[dict | None, str]:
|
||||
"""A candidate from one page of an imageinfo answer, or None with the reason it is not one."""
|
||||
info = (page.get("imageinfo") or [None])[0]
|
||||
if not info:
|
||||
return None, "no imageinfo"
|
||||
meta = {k: (v or {}).get("value", "") for k, v in (info.get("extmetadata") or {}).items()}
|
||||
if info.get("mime") not in PHOTO_MIME:
|
||||
return None, f"not a photo ({info.get('mime')})"
|
||||
short = plain(meta.get("LicenseShortName", ""))
|
||||
code = plain(meta.get("License", "")) or licence_code(short)
|
||||
if not FREE.match(code):
|
||||
return None, f"licence {code or short or 'unknown'}"
|
||||
title = page["title"].removeprefix("File:")
|
||||
author = plain(meta.get("Attribution", "")) or plain(meta.get("Artist", "")) or plain(meta.get("Credit", ""))
|
||||
author = author or "unknown author"
|
||||
width, height = int(info.get("width") or 0), int(info.get("height") or 0)
|
||||
marks = [m for m in plain(meta.get("Assessments", "")).split("|") if m]
|
||||
thumb = (info.get("thumburl") or info.get("url") or "").split("?utm_")[0]
|
||||
return {
|
||||
"file": title,
|
||||
"licence": short or code,
|
||||
"author": author,
|
||||
"credit": f"Photo: {author}, {short or code}, via Wikimedia Commons",
|
||||
"date": photo_date(meta.get("DateTimeOriginal", "")),
|
||||
"marks": marks,
|
||||
"width": width,
|
||||
"height": height,
|
||||
"thumb": thumb,
|
||||
"page": info.get("descriptionurl") or f"https://commons.wikimedia.org/wiki/File:{urllib.parse.quote(title)}",
|
||||
"licence_url": plain(meta.get("LicenseUrl", "")) or None,
|
||||
"restrictions": [r for r in plain(meta.get("Restrictions", "")).split("|") if r],
|
||||
"categories": [c for c in plain(meta.get("Categories", "")).split("|") if c],
|
||||
"found": [found],
|
||||
}, ""
|
||||
|
||||
|
||||
def rank_key(c: dict) -> tuple:
|
||||
"""Commons' quality marks first, then size (tall enough for a 1500-px poster), then landscape, then pixels."""
|
||||
score = sum(MARK_WEIGHT.get(m, 0) for m in c["marks"])
|
||||
return (-score, -(c["height"] >= 1500), -(c["width"] > c["height"]), -(c["width"] * c["height"]), c["file"])
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- asking Commons
|
||||
|
||||
IMAGEINFO = {
|
||||
"prop": "imageinfo",
|
||||
"iiprop": "extmetadata|size|url|mime",
|
||||
"iiurlwidth": str(THUMB_WIDTH),
|
||||
"iiextmetadatafilter": EXTMETA,
|
||||
"iiextmetadatalanguage": "en",
|
||||
}
|
||||
|
||||
|
||||
def pages_of(fetch: Fetcher, params: dict) -> list[dict]:
|
||||
"""Every page of one generator answer, its imageinfo complete: a heavy batch may be cut, and is then continued."""
|
||||
body = fetch.get(COMMONS, {"action": "query", **IMAGEINFO, **params})
|
||||
pages = {p["pageid"]: p for p in body.get("query", {}).get("pages", []) if "pageid" in p}
|
||||
cont = body.get("continue", {})
|
||||
while "iicontinue" in cont:
|
||||
more = fetch.get(COMMONS, {"action": "query", **IMAGEINFO, **params, **cont})
|
||||
for p in more.get("query", {}).get("pages", []):
|
||||
if "pageid" in p and p.get("imageinfo"):
|
||||
pages.setdefault(p["pageid"], p)["imageinfo"] = p["imageinfo"]
|
||||
cont = more.get("continue", {})
|
||||
return list(pages.values())
|
||||
|
||||
|
||||
def search(fetch: Fetcher, query: str, pages: int = 1) -> list[dict]:
|
||||
"""Files matching a CirrusSearch query, in its order, 50 a call, with their metadata."""
|
||||
out: list[dict] = []
|
||||
offset = 0
|
||||
for _ in range(pages):
|
||||
params = {"generator": "search", "gsrnamespace": "6", "gsrlimit": "50", "gsrsearch": query,
|
||||
"gsroffset": str(offset)}
|
||||
body_pages = pages_of(fetch, params)
|
||||
out.extend(sorted(body_pages, key=lambda p: p.get("index", 0)))
|
||||
if len(body_pages) < 50:
|
||||
break
|
||||
offset += 50
|
||||
return out
|
||||
|
||||
|
||||
def files(fetch: Fetcher, titles: list[str]) -> list[dict]:
|
||||
out: list[dict] = []
|
||||
for i in range(0, len(titles), 50):
|
||||
out.extend(pages_of(fetch, {"titles": "|".join(f"File:{t}" for t in titles[i:i + 50])}))
|
||||
return out
|
||||
|
||||
|
||||
def category_files(fetch: Fetcher, category: str) -> list[dict]:
|
||||
return pages_of(fetch, {"generator": "categorymembers", "gcmtitle": f"Category:{category}",
|
||||
"gcmtype": "file", "gcmlimit": "50"})
|
||||
|
||||
|
||||
def wikidata(fetch: Fetcher, titles: list[str]) -> dict[str, dict]:
|
||||
"""For each English Wikipedia title: its Commons category (P373) and its aerial view (P8592). A title is resolved
|
||||
on Wikipedia first, its redirects followed: a third of circuits.json's links are redirects."""
|
||||
item: dict[str, str] = {}
|
||||
for i in range(0, len(titles), 50):
|
||||
batch = titles[i:i + 50]
|
||||
body = fetch.get(ENWIKI, {"action": "query", "titles": "|".join(batch), "redirects": "1",
|
||||
"prop": "pageprops", "ppprop": "wikibase_item"})
|
||||
q = body.get("query", {})
|
||||
moved = {n["from"]: n["to"] for n in q.get("normalized", [])}
|
||||
moved.update({r["from"]: r["to"] for r in q.get("redirects", [])})
|
||||
found = {p["title"]: (p.get("pageprops") or {}).get("wikibase_item") for p in q.get("pages", [])}
|
||||
for title in batch:
|
||||
final, seen = title, set()
|
||||
while final in moved and final not in seen:
|
||||
seen.add(final)
|
||||
final = moved[final]
|
||||
if found.get(final):
|
||||
item[title] = found[final]
|
||||
out: dict[str, dict] = {}
|
||||
ids = sorted(set(item.values()))
|
||||
claims_of: dict[str, dict] = {}
|
||||
for i in range(0, len(ids), 50):
|
||||
body = fetch.get(WIKIDATA, {"action": "wbgetentities", "ids": "|".join(ids[i:i + 50]), "props": "claims"})
|
||||
for qid, entity in body.get("entities", {}).items():
|
||||
claims_of[qid] = entity.get("claims", {})
|
||||
for title, qid in item.items():
|
||||
claims = claims_of.get(qid, {})
|
||||
value = lambda p: [c["mainsnak"]["datavalue"]["value"] for c in claims.get(p, []) # noqa: E731
|
||||
if c.get("mainsnak", {}).get("datavalue")]
|
||||
out[title] = {"id": qid, "category": (value("P373") or [None])[0], "aerial": value("P8592")}
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the circuits and seasons
|
||||
|
||||
def layouts(circuits: dict):
|
||||
"""(circuit key, circuit, [(layout key, first year, last year)]) per circuit, in the file's order."""
|
||||
for country, cv in circuits.items():
|
||||
for city, lv in cv["localities"].items():
|
||||
for slug, circuit in lv["circuits"].items():
|
||||
rows = []
|
||||
for layout in circuit["layouts"]:
|
||||
first, _, last = layout.partition("-")
|
||||
end = THIS_YEAR if layout.endswith("-") else int(last or first)
|
||||
rows.append((f"{country}/{city}/{slug}/{layout}", int(first), end))
|
||||
yield f"{country}/{city}/{slug}", circuit, rows
|
||||
|
||||
|
||||
def wiki_title(circuit: dict) -> str | None:
|
||||
url = (circuit.get("urls") or {}).get("wikipedia") or ""
|
||||
if "/wiki/" not in url:
|
||||
return None
|
||||
return urllib.parse.unquote(url.split("/wiki/", 1)[1]).split("#")[0].replace("_", " ")
|
||||
|
||||
|
||||
def gather_circuit(fetch: Fetcher, key: str, circuit: dict, wd: dict, skipped: dict) -> list[dict]:
|
||||
"""Every aerial-photo candidate of one circuit, before the layouts' years are applied."""
|
||||
found: dict[str, dict] = {}
|
||||
|
||||
def take(pages: list[dict], how: str, check_photo: bool = True) -> None:
|
||||
for page in pages:
|
||||
c, why = candidate(page, how)
|
||||
if not c:
|
||||
skipped[why] = skipped.get(why, 0) + 1
|
||||
continue
|
||||
if check_photo and any(NOT_A_PHOTO.search(cat) for cat in c["categories"]):
|
||||
why = "in a maps, plans or logos category"
|
||||
skipped[why] = skipped.get(why, 0) + 1
|
||||
continue
|
||||
if c["file"] in found:
|
||||
if how not in found[c["file"]]["found"]:
|
||||
found[c["file"]]["found"].append(how)
|
||||
else:
|
||||
found[c["file"]] = c
|
||||
|
||||
entry = wd.get(wiki_title(circuit) or "", {})
|
||||
if entry.get("aerial"):
|
||||
take(files(fetch, entry["aerial"]), "Wikidata aerial view (P8592)", check_photo=False)
|
||||
category = entry.get("category")
|
||||
if category:
|
||||
take(category_files(fetch, f"Aerial photographs of {category}"), f"Category:Aerial photographs of {category}")
|
||||
for word in AERIAL_WORDS:
|
||||
take(search(fetch, f'deepcat:"{category}" {word}'), f"search: {word}")
|
||||
else:
|
||||
for word in AERIAL_WORDS:
|
||||
take(search(fetch, f'"{circuit["name"]}" {word}'), f"search (no Commons category): {word}")
|
||||
kept = [c for c in found.values() if says_aerial(c)]
|
||||
if len(kept) < len(found):
|
||||
why = "found by one search word only, and no aerial word in its title or categories"
|
||||
skipped[why] = skipped.get(why, 0) + len(found) - len(kept)
|
||||
return kept
|
||||
|
||||
|
||||
def says_aerial(c: dict) -> bool:
|
||||
"""An aerial photo by what Commons says of it: Wikidata's or the category's pick, an aerial word in its title or a
|
||||
category, or two search words that found it."""
|
||||
if any(not how.startswith("search") for how in c["found"]):
|
||||
return True
|
||||
if AERIAL_SAYS.search(c["file"]) or any(AERIAL_SAYS.search(cat) for cat in c["categories"]):
|
||||
return True
|
||||
return len(c["found"]) >= 2
|
||||
|
||||
|
||||
def dated_by_season(c: dict, year: int) -> dict:
|
||||
"""A season candidate is of its season: one with no date of its own takes the season's year, and says so. (A
|
||||
layout candidate with no date stays out: a circuit's photo may show any of its layouts.)"""
|
||||
if not c["date"]:
|
||||
c["date"] = str(year)
|
||||
c["date_from"] = "category"
|
||||
return c
|
||||
|
||||
|
||||
def in_years(c: dict, first: int, last: int) -> bool:
|
||||
return bool(c["date"]) and first <= int(c["date"][:4]) <= last
|
||||
|
||||
|
||||
def public(c: dict) -> dict:
|
||||
"""A candidate as the file keeps it: the categories were only for the filter."""
|
||||
return {k: v for k, v in c.items() if k != "categories"}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
||||
ap.add_argument("--only", action="append", default=[],
|
||||
help="only layouts whose key starts with this (country, country/city, …); may repeat")
|
||||
ap.add_argument("--seasons", default=f"{FIRST_SEASON}-{LAST_SEASON}",
|
||||
help="a year, a range such as 2018-2019, or 'none' (default: %(default)s)")
|
||||
ap.add_argument("--no-layouts", action="store_true", help="list the seasons only")
|
||||
ap.add_argument("--out", default=str(OUT), help="the file to write, or - for stdout (default: %(default)s)")
|
||||
args = ap.parse_args()
|
||||
|
||||
fetch = Fetcher()
|
||||
started = dt.datetime.now(dt.timezone.utc)
|
||||
circuits = json.loads(CIRCUITS.read_text(encoding="utf-8"))
|
||||
skipped: dict[str, int] = {}
|
||||
out_layouts: dict[str, list[dict]] = {}
|
||||
undated: dict[str, int] = {}
|
||||
|
||||
chosen = [] if args.no_layouts else [
|
||||
(k, c, rows) for k, c, rows in layouts(circuits) if not args.only or any(k.startswith(o) for o in args.only)]
|
||||
wd = wikidata(fetch, sorted({t for _, c, _ in chosen if (t := wiki_title(c))})) if chosen else {}
|
||||
for n, (key, circuit, rows) in enumerate(chosen, 1):
|
||||
cands = gather_circuit(fetch, key, circuit, wd, skipped)
|
||||
undated[key] = sum(1 for c in cands if not c["date"])
|
||||
for layout_key, first, last in rows:
|
||||
fits = sorted((c for c in cands if in_years(c, first, last)), key=rank_key)
|
||||
out_layouts[layout_key] = [public(c) for c in fits[:LAYOUT_KEEP]]
|
||||
got = sum(1 for k, _, _ in rows if out_layouts[k])
|
||||
print(f"[{n}/{len(chosen)}] {key}: {len(cands)} licensed photo(s), {undated[key]} undated; "
|
||||
f"{got} of {len(rows)} layout(s) have a candidate ({fetch.count} requests)", file=sys.stderr)
|
||||
|
||||
if args.seasons == "none":
|
||||
years: list[int] = []
|
||||
else:
|
||||
first, _, last = args.seasons.partition("-")
|
||||
years = list(range(int(first), int(last or first) + 1))
|
||||
out_seasons: dict[str, list[dict]] = {}
|
||||
for year in years:
|
||||
cat = f"{year} Formula One season cars"
|
||||
found: dict[str, dict] = {}
|
||||
for query, pages, how in ((f'deepcat:"{cat}" {MARKED}', 1, "marked"), (f'deepcat:"{cat}"', 2, f"Category:{cat}")):
|
||||
for page in search(fetch, query, pages):
|
||||
c, why = candidate(page, how)
|
||||
if not c:
|
||||
skipped[why] = skipped.get(why, 0) + 1
|
||||
elif c["file"] not in found:
|
||||
found[c["file"]] = dated_by_season(c, year)
|
||||
out_seasons[str(year)] = [public(c) for c in sorted(found.values(), key=rank_key)[:SEASON_KEEP]]
|
||||
print(f"season {year}: {len(found)} licensed photo(s), kept {len(out_seasons[str(year)])} "
|
||||
f"({fetch.count} requests)", file=sys.stderr)
|
||||
|
||||
result = {
|
||||
"about": {
|
||||
"made": started.isoformat(timespec="seconds"),
|
||||
"by": "tools/commons_candidates.py",
|
||||
"requests": fetch.count,
|
||||
"layouts": f"aerial photos of the circuit dated within the layout's years, at most {LAYOUT_KEEP} each",
|
||||
"seasons": f"photos in '<year> Formula One season cars', at most {SEASON_KEEP} each",
|
||||
"licences": "CC0, public domain, CC BY and CC BY-SA only",
|
||||
"ranked": "Commons' quality marks, then size (at least 1500 px high), then landscape, then pixels",
|
||||
"undated_per_circuit": undated,
|
||||
"skipped": dict(sorted(skipped.items(), key=lambda kv: -kv[1])),
|
||||
"check": "every candidate is checked by eye before it is picked: a search also finds ground photos and maps",
|
||||
},
|
||||
"layouts": out_layouts,
|
||||
"seasons": out_seasons,
|
||||
}
|
||||
text = json.dumps(result, ensure_ascii=False, indent=1) + "\n"
|
||||
if args.out == "-":
|
||||
sys.stdout.write(text)
|
||||
else:
|
||||
path = Path(args.out)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_suffix(".tmp")
|
||||
tmp.write_text(text, encoding="utf-8")
|
||||
tmp.replace(path)
|
||||
with_l = sum(1 for v in out_layouts.values() if v)
|
||||
with_s = sum(1 for v in out_seasons.values() if v)
|
||||
print(f"{with_l} of {len(out_layouts)} layouts and {with_s} of {len(out_seasons)} seasons have a candidate; "
|
||||
f"{len(out_layouts) - with_l} layouts have none ({fetch.count} requests)", file=sys.stderr)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user