Files
f1-circuits/ergast_service.py
T
jschoubben db5c19f0d4 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
2026-11-27 15:13:29 +01:00

174 lines
8.3 KiB
Python

import re
import logging
import threading
import time
import urllib.error
import urllib.request
import json
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
def slugify(text: str) -> str:
text = text.lower().strip()
replacements = {
'ü': 'u', 'ö': 'o', 'ä': 'a', 'é': 'e', 'è': 'e', 'ê': 'e', 'ë': 'e',
'à': 'a', 'â': 'a', 'î': 'i', 'ï': 'i', 'ô': 'o', 'û': 'u', 'ñ': 'n',
'ã': 'a', 'á': 'a', 'í': 'i', 'ó': 'o', 'ú': 'u',
}
for k, v in replacements.items():
text = text.replace(k, v)
text = re.sub(r'[^a-z0-9]+', '-', text)
return text.strip('-')
class ErgastService:
JOLPICA_BASE = 'https://api.jolpi.ca/ergast/f1'
# Jolpica allows 4 requests a second and 500 an hour without a token, and asks its clients to cache
# (https://github.com/jolpica/jolpica-f1/blob/main/docs/rate_limits.md).
REQUEST_INTERVAL = 0.3 # seconds between two requests: under the 4 a second
RETRIES = 3 # a throttled request (429) is asked again after a pause, at most this often
OPEN_SEASON_TTL = 6 * 3600 # a season not yet over is asked again after six hours
FAILED_BACKOFF = 600 # after a failed ask, a season is not asked again for ten minutes
REQUEST_TIMEOUT = 30 # Jolpica answers a season it has not served lately in over 10 s (13.5 s seen)
# Country name normalization: Jolpica country → our country slug
country_map = {
'UK': 'uk',
'UAE': 'united-arab-emirates',
'USA': 'united-states',
'Korea': 'korea',
}
def __init__(self, circuits_service: 'CircuitService' = None, cache_dir: Path = Path("cache/jolpica")):
self.circuits_service = circuits_service
self.logger = logging.getLogger(__name__)
self._circuit_id_index = self._build_circuit_id_index()
self.cache_dir = cache_dir
self._schedules: dict[int, tuple[float, list[dict]]] = {} # season → (fetched at, races)
self._failed_at: dict[int, float] = {} # season → when its last ask failed (monotonic)
self._fetch_lock = threading.Lock()
self._last_request = 0.0
def _build_circuit_id_index(self) -> dict[str, tuple[str, str, str]]:
"""Build a lookup from Jolpica's circuitId → (country_slug, locality_slug, circuit_slug).
A race's circuit is matched on its circuitId, never on its name: Jolpica renames
circuits (Losail became Lusail) while the id stays the same."""
index = {}
if not self.circuits_service:
return index
for country_slug, country in self.circuits_service.circuit_data.items():
for locality_slug, locality in country.localities.items():
for circuit_slug, circuit in locality.circuits.items():
if not circuit.ergast_id:
self.logger.error(f"Circuit '{circuit_slug}' has no ergastId: no race can resolve to it")
continue
index[circuit.ergast_id] = (country_slug, locality_slug, circuit_slug)
return index
def _fetch_season_schedule(self, season: int) -> list[dict]:
"""The race schedule of a season: from memory, then from disk, then from Jolpica.
A season that is over never changes, so it is kept on disk for good; a season not yet over is
asked again after OPEN_SEASON_TTL. A failed fetch is never kept as a schedule, only its time: the
season is not asked again for FAILED_BACKOFF, and meanwhile the schedule kept last is answered, or
none. A schedule held in memory is answered without waiting for an ask under way."""
kept = self._schedules.get(season)
if kept and self._fresh(season, kept):
return kept[1]
with self._fetch_lock:
kept = self._schedules.get(season) or self._read_kept(season)
if kept and self._fresh(season, kept):
self._schedules[season] = kept
return kept[1]
failed = self._failed_at.get(season)
if failed is not None and time.monotonic() - failed < self.FAILED_BACKOFF:
return kept[1] if kept else []
races = self._ask_jolpica(season)
if races is None:
self._failed_at[season] = time.monotonic()
return kept[1] if kept else []
self._failed_at.pop(season, None)
kept = (time.time(), races)
self._schedules[season] = kept
self._write_kept(season, kept)
return races
def _fresh(self, season: int, kept: tuple[float, list[dict]]) -> bool:
return season < date.today().year or time.time() - kept[0] < self.OPEN_SEASON_TTL
def _ask_jolpica(self, season: int) -> Optional[list[dict]]:
"""Ask Jolpica for a season's races, paced under its rate limit; None when it does not answer."""
url = f'{self.JOLPICA_BASE}/{season}.json?limit=100'
for attempt in range(1, self.RETRIES + 1):
wait = self._last_request + self.REQUEST_INTERVAL - time.monotonic()
if wait > 0:
time.sleep(wait)
self._last_request = time.monotonic()
try:
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:
self.logger.error(f"Failed to fetch Jolpica schedule for {season}: {e}")
return None
retry_after = e.headers.get('Retry-After', '') if e.headers else ''
pause = min(float(retry_after), 30.0) if retry_after.isdigit() else 2.0 ** attempt
self.logger.warning(f"Jolpica throttled the schedule for {season} (429): asking again in {pause:.0f}s")
time.sleep(pause)
except Exception as e:
self.logger.error(f"Failed to fetch Jolpica schedule for {season}: {e}")
return None
return None
def _read_kept(self, season: int) -> Optional[tuple[float, list[dict]]]:
path = self.cache_dir / f'{season}.json'
try:
kept = json.loads(path.read_text(encoding='utf-8'))
return kept['fetched'], kept['races']
except FileNotFoundError:
return None
except (OSError, ValueError, KeyError) as e:
self.logger.warning(f"Could not read the kept Jolpica schedule {path}: {e}")
return None
def _write_kept(self, season: int, kept: tuple[float, list[dict]]) -> None:
path = self.cache_dir / f'{season}.json'
try:
self.cache_dir.mkdir(parents=True, exist_ok=True)
partial = path.with_suffix('.partial')
partial.write_text(json.dumps({'fetched': kept[0], 'races': kept[1]}), encoding='utf-8')
partial.replace(path)
except OSError as e:
self.logger.warning(f"Could not keep the Jolpica schedule {path}: {e}")
def find_slugs_for_grand_prix(self, grand_prix_name: str, season: int) -> Optional[tuple[str, str, str]]:
"""Resolve a grand prix name + season to (country_slug, locality_slug, circuit_slug)."""
races = self._fetch_season_schedule(season)
# Find the matching race
race = next((r for r in races if r['raceName'] == grand_prix_name), None)
if not race:
self.logger.error(f"Race '{grand_prix_name}' not found in {season} schedule")
return None, None, None
return self.find_slugs_for_circuit(race["Circuit"])
def find_slugs_for_circuit(self, circuit: dict) -> tuple[Optional[str], Optional[str], Optional[str]]:
"""Resolve a Jolpica race's Circuit object to (country_slug, locality_slug, circuit_slug)."""
slugs = self._circuit_id_index.get(circuit.get('circuitId'))
if slugs:
return slugs
self.logger.warning(f"Circuit '{circuit.get('circuitName')}' (circuitId: {circuit.get('circuitId')}) "
f"has no circuit with that ergastId in circuits.json")
return None, None, None