diff --git a/.gitignore b/.gitignore index bc9e7f2..c1caeeb 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,6 @@ __pycache__/ cache/ .idea/ .venv-site/ +# The poster service's kept layers and finished pictures, when run from here +/layers/ +/posters/ diff --git a/README.md b/README.md index f3e1cf3..c9c857e 100644 --- a/README.md +++ b/README.md @@ -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: ; 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/ (+)`. 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 diff --git a/app_info.py b/app_info.py new file mode 100644 index 0000000..b32e13e --- /dev/null +++ b/app_info.py @@ -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})" diff --git a/cdn-api.py b/cdn-api.py index 668d219..1e7a461 100644 --- a/cdn-api.py +++ b/cdn-api.py @@ -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'
{DISCLAIMER}
') + return HTMLResponse(page.replace("", f"{footer}")) + + +@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": '; 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= 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): diff --git a/circuits/photos.json b/circuits/photos.json new file mode 100644 index 0000000..b8959d3 --- /dev/null +++ b/circuits/photos.json @@ -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: , , 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." +} diff --git a/circuits_service.py b/circuits_service.py index 2f3cb05..34eebfb 100644 --- a/circuits_service.py +++ b/circuits_service.py @@ -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]: """ diff --git a/docs/posters.md b/docs/posters.md new file mode 100644 index 0000000..3b6c147 --- /dev/null +++ b/docs/posters.md @@ -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: , , 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 (+)`, 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 " · " 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: ; 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. diff --git a/ergast_service.py b/ergast_service.py index 8a1d861..0289c3c 100644 --- a/ergast_service.py +++ b/ergast_service.py @@ -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: diff --git a/examples/builder.html b/examples/builder.html new file mode 100644 index 0000000..27e99ff --- /dev/null +++ b/examples/builder.html @@ -0,0 +1,360 @@ + + + + + + Poster builder · F1 Circuits API examples + + + + + +
+ F1 Circuits API + +
+
+ +
+

Poster builder

+

+ 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. +

+ +
+

1. Which picture

+
+ +
+
+
+ + +
+
+
+
+ +
+

2. The options

+

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.

+
+
+ +
+

3. The picture

+
+ +
+
+
Not rendered yet.
+
+
+
+
+ + +
+

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.

+

Licences and credits: 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).

+
+ + + + + diff --git a/examples/circuits.html b/examples/circuits.html index ae465d7..68f31c5 100644 --- a/examples/circuits.html +++ b/examples/circuits.html @@ -18,8 +18,11 @@ GPS traces Grand prix lookup Posters + Poster builder Kometa Library + Photo picker + Licences
@@ -89,6 +92,13 @@ All examples +
+

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.

+

Licences and credits: 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).

+
diff --git a/examples/licences.html b/examples/licences.html new file mode 100644 index 0000000..caee185 --- /dev/null +++ b/examples/licences.html @@ -0,0 +1,176 @@ + + + + + + Licences · F1 Circuits API examples + + + + + +
+ F1 Circuits API + +
+
+ +
+

Licences

+

+ 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 X-Credits header, + and listed here. A picture’s licence follows its sources, and is sent in its X-License header. Its + Link: </licences>; rel="license" header points to this list. +

+ +
+

The sources

+

What /licences answers, as a table. A credit with <author> and + <licence> is filled in with the photo’s own; one with <year> with the mosaic’s + year. The last column is the licence a picture made from that source gets.

+
+
+
+
The answer as it came
+
+ +
+

What the API offers, and under which licence

+
+

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.

+
+ +
+

Formula 1

+

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.

+
+
+ + +
+

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.

+

Licences and credits: 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).

+
+ + + + + diff --git a/examples/map.html b/examples/map.html index 9bf9bb5..10c046e 100644 --- a/examples/map.html +++ b/examples/map.html @@ -20,8 +20,11 @@ GPS traces Grand prix lookup Posters + Poster builder Kometa Library + Photo picker + Licences
@@ -32,7 +35,7 @@ Each layout was traced by GPS along the track. Its geojson format is that trace: a GeoJSON FeatureCollection holding one LineString of [longitude, latitude] points. Any map library draws it as it comes; this page uses Leaflet. Switch to the - satellite layer to see the trace follow the tarmac. + satellite layer (EOxCloudless, Sentinel-2 at 10 m) to see the trace over the ground.

@@ -65,6 +68,13 @@ All examples +
+

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.

+

Licences and credits: 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).

+
@@ -88,13 +98,18 @@ maxZoom: 19, attribution: '© OpenStreetMap 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 https://cloudless.eox.at by EOX IT Services GmbH' + + ' (Contains modified Copernicus Sentinel data 2025),' + + ' CC BY-NC-SA 4.0', }); - 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()); diff --git a/examples/picker.html b/examples/picker.html new file mode 100644 index 0000000..93a84cc --- /dev/null +++ b/examples/picker.html @@ -0,0 +1,769 @@ + + + + + + Photo picker · F1 Circuits API examples + + + + + + +
+ F1 Circuits API + +
+
+ + + + +
+

Photo picker

+

+ Per layout, the main choice is what bg=satellite 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 + bg=photo, which falls back to what bg=satellite draws while none is picked; a season poster + shows that season’s cars only from a picked photo. The photos are the candidates + tools/commons_candidates.py 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. +

+

+ 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. +

+ +
+

1. The lists

+

The candidates come with the site; the picks are read from the repository, beside the page’s folder. + Run python3 -m http.server in the working copy and open /examples/picker.html there to + have both, or load a picks file from disk below.

+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+

2. What to pick for

+
+ + + +
+
+ +
+
+
+
+ + + +
+ +
+

Picks of the circuit’s other layouts

+
+

Candidates

+
+
+
+ + +
+

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.

+

Licences and credits: 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).

+
+ + + + + + diff --git a/examples/posters.html b/examples/posters.html index ba1de26..20f7282 100644 --- a/examples/posters.html +++ b/examples/posters.html @@ -18,8 +18,11 @@ GPS traces Grand prix lookup Posters + Poster builder Kometa Library + Photo picker + Licences
@@ -44,14 +47,15 @@

Race poster

-

/posters/race/{race name}/{season}.png?bg={background}, 1000×1500: the round, the race’s name, the track and its date over a map of the circuit.

+

/posters/race/{race name}/{season}.png?bg={background}, 1000×1500: the round, the race’s name, the track and its date over a map of the circuit. Every other option is on the poster builder.

@@ -101,7 +105,14 @@ +
+

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.

+

Licences and credits: 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).

diff --git a/examples/site.css b/examples/site.css index f246bc0..a5f8b7d 100644 --- a/examples/site.css +++ b/examples/site.css @@ -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; } diff --git a/examples/site.js b/examples/site.js index 7182355..9a98990 100644 --- a/examples/site.js +++ b/examples/site.js @@ -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('GPS traces Grand prix lookup Posters + Poster builder Kometa Library + Photo picker + Licences
@@ -80,6 +83,13 @@ All examples +
+

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.

+

Licences and credits: 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).

+