Pit-Lane-Project / backend /test_backend.py
Interact-ai's picture
Upload folder using huggingface_hub
267266e verified
Raw History Blame Contribute Delete
24 kB
"""
Fast F1 replay streamer for frontend/backend integration testing.
Goals:
- Do NOT hit unavailable 2026 FastF1 archives by default.
- Use a stable historical source session (2024 by default).
- Build a compact local JSON replay cache once, then reuse it on later runs.
- Auto-start the FastAPI backend when needed.
- Stream lap-by-lap data quickly to the frontend/backend.
- Exit cleanly after the replay instead of hanging forever.
Typical usage:
python fast_replay.py --gp Monza --laps 3
python fast_replay.py --gp Bahrain --laps 10
python fast_replay.py --gp Monza --laps 5 --interval 0
python fast_replay.py --gp Monza --refresh-cache
"""
from __future__ import annotations
import argparse
import inspect
import json
import os
import re
import subprocess
import sys
import time
import urllib.request
from pathlib import Path
from typing import Any
PROJECT_ROOT = Path(__file__).resolve().parent
TESTING_DIR = PROJECT_ROOT / "testing_pipeline"
TEST_ENV_PYTHON = TESTING_DIR / ".venv" / "Scripts" / "python.exe"
BACKEND_ENV_PYTHON = PROJECT_ROOT / ".venv" / "Scripts" / "python.exe"
REPLAY_CACHE_DIR = TESTING_DIR / ".cache" / "replays"
FASTF1_CACHE_DIR = TESTING_DIR / ".cache" / "fastf1"
REENTRY_FLAG = "F1_REPLAY_TEST_ENV"
# This is only a frontend/demo roster.
# It is intentionally independent from the historical source session.
TEST_GRID = [
{"DriverNumber": 1, "Driver": "VER", "FullName": "Max Verstappen", "TeamName": "Red Bull Racing"},
{"DriverNumber": 4, "Driver": "NOR", "FullName": "Lando Norris", "TeamName": "McLaren"},
{"DriverNumber": 81, "Driver": "PIA", "FullName": "Oscar Piastri", "TeamName": "McLaren"},
{"DriverNumber": 16, "Driver": "LEC", "FullName": "Charles Leclerc", "TeamName": "Ferrari"},
{"DriverNumber": 44, "Driver": "HAM", "FullName": "Lewis Hamilton", "TeamName": "Ferrari"},
{"DriverNumber": 63, "Driver": "RUS", "FullName": "George Russell", "TeamName": "Mercedes"},
{"DriverNumber": 12, "Driver": "ANT", "FullName": "Andrea Kimi Antonelli", "TeamName": "Mercedes"},
{"DriverNumber": 55, "Driver": "SAI", "FullName": "Carlos Sainz", "TeamName": "Williams"},
{"DriverNumber": 23, "Driver": "ALB", "FullName": "Alexander Albon", "TeamName": "Williams"},
{"DriverNumber": 14, "Driver": "ALO", "FullName": "Fernando Alonso", "TeamName": "Aston Martin"},
{"DriverNumber": 18, "Driver": "STR", "FullName": "Lance Stroll", "TeamName": "Aston Martin"},
{"DriverNumber": 10, "Driver": "GAS", "FullName": "Pierre Gasly", "TeamName": "Alpine"},
{"DriverNumber": 7, "Driver": "DOO", "FullName": "Jack Doohan", "TeamName": "Alpine"},
{"DriverNumber": 22, "Driver": "TSU", "FullName": "Yuki Tsunoda", "TeamName": "RB"},
{"DriverNumber": 30, "Driver": "LAW", "FullName": "Liam Lawson", "TeamName": "RB"},
{"DriverNumber": 27, "Driver": "HUL", "FullName": "Nico Hulkenberg", "TeamName": "Kick Sauber"},
{"DriverNumber": 5, "Driver": "BOR", "FullName": "Gabriel Bortoleto", "TeamName": "Kick Sauber"},
{"DriverNumber": 31, "Driver": "OCO", "FullName": "Esteban Ocon", "TeamName": "Haas"},
{"DriverNumber": 87, "Driver": "BEA", "FullName": "Oliver Bearman", "TeamName": "Haas"},
{"DriverNumber": 11, "Driver": "PER", "FullName": "Sergio Perez", "TeamName": "Red Bull Racing"},
]
DEFAULT_WEATHER = {
"AirTemp": 27.5,
"TrackTemp": 39.2,
"Rainfall": 0,
"Humidity": 48.0,
"Pressure": 1012.0,
"WindSpeed": 7.5,
"WindDirection": 110.0,
}
def _safe_float(value: Any, default: float) -> float:
try:
if value is None:
return default
value = float(value)
if value != value: # NaN
return default
return value
except (TypeError, ValueError):
return default
def _safe_int(value: Any, default: int = 1) -> int:
try:
if value is None:
return default
value = float(value)
if value != value:
return default
return int(value)
except (TypeError, ValueError):
return default
def _slug(text: str) -> str:
return re.sub(r"[^a-zA-Z0-9_-]+", "_", text.strip()).strip("_") or "race"
def _cache_path(source_year: int, source_gp: str) -> Path:
return REPLAY_CACHE_DIR / f"{source_year}_{_slug(source_gp)}.json"
def _request_json(
method: str,
url: str,
data: dict[str, Any] | list[Any] | None = None,
timeout: float = 3.0,
) -> dict[str, Any] | None:
body = None
headers = {"Accept": "application/json"}
if data is not None:
body = json.dumps(data).encode("utf-8")
headers["Content-Type"] = "application/json"
request = urllib.request.Request(
url,
data=body,
headers=headers,
method=method,
)
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
raw = response.read()
if not raw:
return {}
return json.loads(raw.decode("utf-8"))
except Exception:
return None
def _get_json(url: str, timeout: float = 2.0) -> dict[str, Any] | None:
return _request_json("GET", url, timeout=timeout)
def _post_json(
url: str,
data: dict[str, Any] | list[Any],
timeout: float = 3.0,
) -> dict[str, Any] | None:
return _request_json("POST", url, data=data, timeout=timeout)
def _backend_python() -> str:
if BACKEND_ENV_PYTHON.is_file():
return str(BACKEND_ENV_PYTHON)
return sys.executable
def _ensure_backend_running(
backend_url: str,
auto_start: bool = True,
) -> subprocess.Popen[Any] | None:
health = _get_json(f"{backend_url}/health", timeout=1.0)
if health and health.get("status") in {"ok", "degraded"}:
print(f"[Backend] Connected: {backend_url}")
return None
if not auto_start:
raise RuntimeError(
f"Backend is not running at {backend_url}. "
"Start it manually or remove --no-auto-backend."
)
print(f"[Backend] Not running. Starting FastAPI at {backend_url}...")
creationflags = 0
if os.name == "nt" and hasattr(subprocess, "CREATE_NEW_PROCESS_GROUP"):
creationflags = subprocess.CREATE_NEW_PROCESS_GROUP
process = subprocess.Popen(
[
_backend_python(),
"-m",
"uvicorn",
"app.main:app",
"--host",
"127.0.0.1",
"--port",
"8000",
],
cwd=PROJECT_ROOT,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
creationflags=creationflags,
)
# Fast polling; no long 15-second retry loop.
deadline = time.monotonic() + 12.0
while time.monotonic() < deadline:
health = _get_json(f"{backend_url}/health", timeout=0.8)
if health and health.get("status") in {"ok", "degraded"}:
print(f"[Backend] Started (PID {process.pid})")
return process
if process.poll() is not None:
raise RuntimeError(
"Backend process exited during startup. "
"Run uvicorn manually once to inspect the backend error."
)
time.sleep(0.25)
raise RuntimeError(
f"Backend did not become healthy at {backend_url} within 12 seconds."
)
def _fastf1_importable() -> bool:
try:
import fastf1 # noqa: F401
return True
except Exception:
return False
def _reenter_test_env_if_needed() -> None:
if _fastf1_importable():
return
if os.environ.get(REENTRY_FLAG):
raise RuntimeError("FastF1 is not importable inside the testing environment.")
if not TEST_ENV_PYTHON.is_file():
raise RuntimeError(
"FastF1 environment is missing.\n"
"Create it with:\n"
" python -m venv testing_pipeline\\.venv\n"
" testing_pipeline\\.venv\\Scripts\\python -m pip install -r testing_pipeline\\requirements.txt"
)
env = os.environ.copy()
env[REENTRY_FLAG] = "1"
completed = subprocess.run(
[str(TEST_ENV_PYTHON), str(Path(__file__).resolve()), *sys.argv[1:]],
cwd=PROJECT_ROOT,
env=env,
check=False,
)
raise SystemExit(completed.returncode)
def _load_source_session(source_year: int, source_gp: str):
import fastf1
FASTF1_CACHE_DIR.mkdir(parents=True, exist_ok=True)
fastf1.Cache.enable_cache(str(FASTF1_CACHE_DIR))
print(f"[FastF1] Loading stable source: {source_year} {source_gp} Race")
session = fastf1.get_session(source_year, source_gp, "R")
# Keep the call compatible across FastF1 versions.
# We intentionally do NOT load telemetry/weather/messages for this frontend test.
supported = inspect.signature(session.load).parameters
kwargs: dict[str, Any] = {}
if "laps" in supported:
kwargs["laps"] = True
if "telemetry" in supported:
kwargs["telemetry"] = False
if "weather" in supported:
kwargs["weather"] = False
if "messages" in supported:
kwargs["messages"] = False
started = time.perf_counter()
session.load(**kwargs)
elapsed = time.perf_counter() - started
if not hasattr(session, "laps") or session.laps.empty:
raise RuntimeError(
f"No lap data available for {source_year} {source_gp}."
)
print(f"[FastF1] Source loaded in {elapsed:.2f}s")
return session
def _build_replay_cache(
source_year: int,
source_gp: str,
cache_file: Path,
) -> dict[str, Any]:
session = _load_source_session(source_year, source_gp)
laps = session.laps
source_drivers = [
str(driver).strip().upper()
for driver in laps["Driver"].dropna().unique().tolist()
if str(driver).strip()
]
if not source_drivers:
raise RuntimeError("Source session contains no drivers.")
# Stable source-driver -> demo-driver mapping.
driver_map: dict[str, dict[str, Any]] = {}
for index, source_driver in enumerate(source_drivers):
driver_map[source_driver] = TEST_GRID[index % len(TEST_GRID)]
max_lap = _safe_int(laps["LapNumber"].max(), 1)
replay_laps: list[dict[str, Any]] = []
# Group once. This avoids repeatedly filtering the full DataFrame for every lap.
grouped = laps.groupby("LapNumber", sort=True)
for lap_number_raw, frame in grouped:
lap_number = _safe_int(lap_number_raw, 0)
if lap_number <= 0:
continue
car_batch: list[dict[str, Any]] = []
timing_batch: list[dict[str, Any]] = []
for _, row in frame.iterrows():
source_driver = str(row.get("Driver", "")).strip().upper()
target = driver_map.get(source_driver)
if target is None:
continue
position = max(1, _safe_int(row.get("Position"), 1))
compound = str(row.get("Compound", "MEDIUM") or "MEDIUM").upper()
tyre_life = _safe_float(row.get("TyreLife"), float(lap_number))
speed_st = _safe_float(row.get("SpeedST"), 315.0)
is_braking = (position % 3 == 0) and (lap_number % 2 == 0)
rpm = 8400 if is_braking else max(9000, 11500 - position * 12)
gear = 4 if is_braking else 8
throttle = 0 if is_braking else 100
brake = 85 if is_braking else 0
drs = 1 if position > 1 and not is_braking else 0
car_batch.append(
{
"Driver": target["Driver"],
"DriverNumber": target["DriverNumber"],
"LapNumber": lap_number,
"Speed": speed_st,
"RPM": rpm,
"nGear": gear,
"Throttle": throttle,
"Brake": brake,
"DRS": drs,
"Compound": compound,
"TyreLife": tyre_life,
"Position": position,
**DEFAULT_WEATHER,
}
)
timing_batch.append(
{
"Driver": target["Driver"],
"DriverNumber": target["DriverNumber"],
"LapNumber": lap_number,
"Position": position,
}
)
if car_batch and timing_batch:
replay_laps.append(
{
"lap": lap_number,
"car": car_batch,
"timing": timing_batch,
}
)
replay = {
"schema_version": 1,
"source_year": source_year,
"source_gp": source_gp,
"source_max_lap": max_lap,
"grid": TEST_GRID,
"weather": DEFAULT_WEATHER,
"laps": replay_laps,
}
cache_file.parent.mkdir(parents=True, exist_ok=True)
temp_file = cache_file.with_suffix(".tmp")
temp_file.write_text(
json.dumps(replay, separators=(",", ":"), ensure_ascii=False),
encoding="utf-8",
)
temp_file.replace(cache_file)
print(
f"[Cache] Built {cache_file.name}: "
f"{len(replay_laps)} replay laps, {len(source_drivers)} source drivers"
)
return replay
def _load_or_build_replay(
source_year: int,
source_gp: str,
refresh_cache: bool,
) -> dict[str, Any]:
cache_file = _cache_path(source_year, source_gp)
if cache_file.is_file() and not refresh_cache:
started = time.perf_counter()
replay = json.loads(cache_file.read_text(encoding="utf-8"))
elapsed = time.perf_counter() - started
print(f"[Cache] Loaded {cache_file.name} in {elapsed:.3f}s")
return replay
_reenter_test_env_if_needed()
return _build_replay_cache(source_year, source_gp, cache_file)
def _leader_text(snapshot: dict[str, Any] | None) -> tuple[str, str]:
if not snapshot:
return "Calculating...", ""
prediction = snapshot.get("prediction") or {}
leaderboard = prediction.get("leaderboard") or []
if not leaderboard:
return "Calculating...", ""
leader = leaderboard[0]
probability = _safe_float(leader.get("normalized_probability"), 0.0) * 100
leader_text = f"{leader.get('driver', '?')} ({probability:.1f}%)"
top3 = ", ".join(
f"P{i + 1}:{item.get('driver', '?')}"
for i, item in enumerate(leaderboard[:3])
)
return leader_text, top3
def run_replay(
*,
display_year: int,
display_gp: str,
source_year: int,
source_gp: str,
max_laps: int | None,
interval: float,
backend_url: str,
refresh_cache: bool,
auto_backend: bool,
snapshot_every: int,
hold: bool,
stop_backend_after: bool,
) -> int:
replay = _load_or_build_replay(
source_year=source_year,
source_gp=source_gp,
refresh_cache=refresh_cache,
)
backend_proc: subprocess.Popen[Any] | None = None
try:
backend_proc = _ensure_backend_running(
backend_url=backend_url,
auto_start=auto_backend,
)
available_laps = replay.get("laps") or []
if not available_laps:
raise RuntimeError("Replay cache contains no laps.")
target_laps = len(available_laps)
if max_laps is not None:
target_laps = min(max(1, max_laps), target_laps)
selected = available_laps[:target_laps]
print()
print("=" * 72)
print(" FAST F1 FRONTEND/BACKEND REPLAY")
print(f" Display race : {display_year} {display_gp}")
print(f" Data source : {source_year} {source_gp} historical race")
print(f" Laps : {target_laps}")
print(f" Interval : {interval:.2f}s")
print(f" Backend : {backend_url}")
print("=" * 72)
print()
# Reset once.
if _post_json(f"{backend_url}/live/reset", {}) is None:
raise RuntimeError("Backend /live/reset request failed.")
driver_records = [
{
"DriverNumber": d["DriverNumber"],
"Driver": d["Driver"],
"BroadcastName": d["FullName"],
"TeamName": d["TeamName"],
}
for d in replay.get("grid", TEST_GRID)
]
if _post_json(
f"{backend_url}/live/feed",
{"DriverList": driver_records},
) is None:
raise RuntimeError("Failed to register driver list.")
weather = replay.get("weather") or DEFAULT_WEATHER
_post_json(
f"{backend_url}/live/feed",
{
"WeatherData": [weather],
"TrackStatus": [{"TrackStatus": "1"}],
"LapCount": [{"CurrentLap": 0, "TotalLaps": target_laps}],
"SessionStatus": [{"Status": "Started"}],
},
)
_post_json(
f"{backend_url}/live/feed",
{
"TimingData": [
{
"DriverNumber": d["DriverNumber"],
"Driver": d["Driver"],
"LapNumber": 0,
}
for d in driver_records
]
},
)
replay_started = time.perf_counter()
for index, lap_data in enumerate(selected, start=1):
lap_number = index
# Copy only because we need the displayed lap numbering to be contiguous
# even if the source had any missing lap groups.
car_batch = [dict(row, LapNumber=lap_number) for row in lap_data["car"]]
timing_batch = [dict(row, LapNumber=lap_number) for row in lap_data["timing"]]
payload = {
"LapCount": [{"CurrentLap": lap_number, "TotalLaps": target_laps}],
"CarData.z": car_batch,
"TimingData": timing_batch,
}
if _post_json(f"{backend_url}/live/feed", payload) is None:
print(f"[Warning] Lap {lap_number} feed failed")
continue
should_snapshot = (
snapshot_every > 0
and (
lap_number == 1
or lap_number == target_laps
or lap_number % snapshot_every == 0
)
)
if should_snapshot:
snapshot = _get_json(
f"{backend_url}/live/frontend",
timeout=1.5,
)
leader, top3 = _leader_text(snapshot)
print(
f"[Lap {lap_number:>2}/{target_laps}] "
f"Leader: {leader:<18} Top 3: [{top3}]"
)
else:
print(f"[Lap {lap_number:>2}/{target_laps}] streamed")
if interval > 0:
time.sleep(interval)
_post_json(
f"{backend_url}/live/feed",
{"SessionStatus": [{"Status": "Finished"}]},
)
elapsed = time.perf_counter() - replay_started
final_snapshot = _get_json(f"{backend_url}/live/frontend", timeout=2.0) or {}
prediction = final_snapshot.get("prediction") or {}
leaderboard = prediction.get("leaderboard") or []
winner = prediction.get("final_predicted_winner")
if not winner and leaderboard:
winner = leaderboard[0].get("driver")
print()
print("=" * 72)
print(" REPLAY FINISHED")
print(f" Predicted winner : {winner or 'N/A'}")
print(f" Stream time : {elapsed:.2f}s")
print(" Frontend : http://localhost:5173")
print("=" * 72)
if hold:
print("\n[Hold] Keeping this process alive. Press Ctrl+C to stop.")
while True:
time.sleep(1)
return 0
except KeyboardInterrupt:
print("\n[Replay] Stopped by user.")
return 130
except Exception as exc:
print(f"\n[Error] {exc}", file=sys.stderr)
return 1
finally:
if stop_backend_after and backend_proc is not None:
try:
backend_proc.terminate()
except Exception:
pass
def _parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description=(
"Fast local F1 replay streamer for frontend/backend integration testing."
)
)
parser.add_argument(
"--gp",
default="Monza",
help="Displayed/test Grand Prix name. Also used as source GP unless --source-gp is set.",
)
parser.add_argument(
"--year",
type=int,
default=2026,
help="Displayed/test season year (default: 2026).",
)
parser.add_argument(
"--source-year",
type=int,
default=2024,
help="Historical FastF1 source year (default: 2024).",
)
parser.add_argument(
"--source-gp",
default=None,
help="Historical FastF1 source GP. Defaults to the value of --gp.",
)
parser.add_argument(
"--laps",
type=int,
default=None,
help="Number of laps to replay. Default: all cached source laps.",
)
parser.add_argument(
"--interval",
type=float,
default=0.25,
help="Seconds between streamed laps. Use 0 for maximum speed. Default: 0.25.",
)
parser.add_argument(
"--backend-url",
default="http://127.0.0.1:8000",
help="Backend base URL.",
)
parser.add_argument(
"--refresh-cache",
action="store_true",
help="Ignore local replay JSON and rebuild it from FastF1.",
)
parser.add_argument(
"--no-auto-backend",
action="store_true",
help="Do not auto-start the FastAPI backend.",
)
parser.add_argument(
"--snapshot-every",
type=int,
default=1,
help="Read /live/frontend every N laps. Use 0 to disable snapshot polling.",
)
parser.add_argument(
"--hold",
action="store_true",
help="Keep this replay process alive after the race finishes.",
)
parser.add_argument(
"--stop-backend-after",
action="store_true",
help="Stop the backend only if this script started it.",
)
return parser.parse_args()
def main() -> int:
args = _parse_args()
if args.interval < 0:
print("[Error] --interval cannot be negative.", file=sys.stderr)
return 2
if args.snapshot_every < 0:
print("[Error] --snapshot-every cannot be negative.", file=sys.stderr)
return 2
source_gp = args.source_gp or args.gp
return run_replay(
display_year=args.year,
display_gp=args.gp,
source_year=args.source_year,
source_gp=source_gp,
max_laps=args.laps,
interval=args.interval,
backend_url=args.backend_url.rstrip("/"),
refresh_cache=args.refresh_cache,
auto_backend=not args.no_auto_backend,
snapshot_every=args.snapshot_every,
hold=args.hold,
stop_backend_after=args.stop_backend_after,
)
if __name__ == "__main__":
raise SystemExit(main())