Draw posters from kept layers of licensed sources, credited on every picture
Esri's, Bing's and Google's terms forbid keeping or serving pictures made from their maps, so the posters move to sources whose licence allows a kept copy: a picked Wikimedia Commons photo, USGS, PDOK and IGN's frozen 2021-2023 mosaic by country, else EOxCloudless's newest mosaic, and OpenStreetMap for the maps and the locator. What needs the network is a layer fetched once and kept whole in layers/; texts, colours, size and format are drawn on every request, and finished pictures are kept in posters/ up to 2 GB. Every picture carries its sources' credit line, X-Credits, X-License (which follows its sources) and a link to /licences. Options are checked into a named 422; the Kometa file states Jolpica's licence and versions its addresses so clients keep them for good. A layout whose trace is a point (Madring) is drawn at the circuit's location instead of failing. Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
This commit is contained in:
+83
-45
@@ -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 app_info import APP_VERSION
|
||||
from circuits_service import CircuitService, Format
|
||||
from posters_service import PostersService, BackgroundStyle
|
||||
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,76 @@ 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, 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` (200 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}")
|
||||
etag = '"' + 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.
|
||||
|
||||
Reference in New Issue
Block a user