Interact-ai commited on
Commit
267266e
·
verified ·
1 Parent(s): d53afd2

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +17 -0
  2. README.md +99 -0
  3. backend/.env.example +19 -0
  4. backend/app/api/routes_health.py +0 -0
  5. backend/app/api/routes_live.py +220 -0
  6. backend/app/api/routes_race.py +0 -0
  7. backend/app/api/websocket.py +104 -0
  8. backend/app/config.py +64 -0
  9. backend/app/main.py +128 -0
  10. backend/app/providers/base.py +0 -0
  11. backend/app/providers/fastf1_replay.py +0 -0
  12. backend/app/providers/livef1_provider.py +487 -0
  13. backend/app/providers/openf1_provider.py +282 -0
  14. backend/app/schemas.py +98 -0
  15. backend/app/services/driver_registry.py +154 -0
  16. backend/app/services/feature_contract.py +46 -0
  17. backend/app/services/feature_coverage.py +82 -0
  18. backend/app/services/feature_engineer.py +142 -0
  19. backend/app/services/inference_gateway.py +67 -0
  20. backend/app/services/live_compressor.py +149 -0
  21. backend/app/services/live_pipeline.py +326 -0
  22. backend/app/services/live_state.py +265 -0
  23. backend/app/services/model_service.py +204 -0
  24. backend/app/services/prediction_service.py +209 -0
  25. backend/app/services/raw_normalizer.py +136 -0
  26. backend/app/services/raw_schema.py +105 -0
  27. backend/app/services/remote_model_client.py +69 -0
  28. backend/app/utils/driver_mapping.py +50 -0
  29. backend/app/utils/logger.py +124 -0
  30. backend/data/F1_2026_model_training_data.csv +0 -0
  31. backend/data/benchmark_latency.py +514 -0
  32. backend/data/compressor.py +1507 -0
  33. backend/data/f1_live_winner_best_params.json +15 -0
  34. backend/data/f1_live_winner_feature_importance.csv +86 -0
  35. backend/data/f1_live_winner_feature_schema.json +179 -0
  36. backend/data/f1_live_winner_model.pkl +3 -0
  37. backend/data/f1_live_winner_optuna_study.pkl +3 -0
  38. backend/data/feature_eng.py +929 -0
  39. backend/data/model_training.py +2050 -0
  40. backend/data/test_race_audit.csv +4 -0
  41. backend/docs/feature-contract.md +139 -0
  42. backend/models/f1_live_winner_feature_schema.json +179 -0
  43. backend/models/f1_live_winner_model.pkl +3 -0
  44. backend/pytest.ini +9 -0
  45. backend/requirements.txt +14 -0
  46. backend/test_backend.py +732 -0
  47. backend/testing_pipeline/.gitignore +2 -0
  48. backend/testing_pipeline/README.md +44 -0
  49. backend/testing_pipeline/__init__.py +2 -0
  50. backend/testing_pipeline/cli.py +147 -0
.gitignore ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .venv/
2
+ backend/.venv/
3
+ node_modules/
4
+ **/node_modules/
5
+ dist/
6
+ **/dist/
7
+ __pycache__/
8
+ *.py[cod]
9
+ .env
10
+ backend/.env
11
+ .pytest_cache/
12
+ .mypy_cache/
13
+ .ruff_cache/
14
+ .idea/
15
+ .vscode/
16
+ *.log
17
+ backend/logs.txt
README.md ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # F1 Live Race & Winner Prediction Platform
2
+
3
+ Full-stack application for live Formula 1 race tracking, lap-level telemetry ingestion, and real-time winner prediction using machine learning (XGBoost).
4
+
5
+ ## Project Structure
6
+
7
+ ```text
8
+ f1-live-backend/
9
+ ├── backend/ # FastAPI backend service
10
+ │ ├── app/ # Application code (routes, services, providers)
11
+ │ ├── models/ # XGBoost model pickle & feature schema
12
+ │ ├── tests/ # Automated pytest suite
13
+ │ ├── testing_pipeline/ # FastF1 historical replay & probe test harness
14
+ │ ├── test_backend.py # Standalone replay test runner
15
+ │ ├── requirements.txt # Python dependencies
16
+ │ ├── pytest.ini # Pytest discovery config
17
+ │ ├── .env # Backend environment configuration
18
+ │ └── docs/ # Feature contract & architecture docs
19
+ │
20
+ └── frontend/ # React + TypeScript + Vite Dashboard
21
+ └── Dashboard/ # F1 live telemetry & prediction dashboard
22
+ ├── src/
23
+ │ ├── components/ # Track map, leaderboard, vitals, telemetry panels
24
+ │ ├── hooks/ # usePredictions (WebSocket & REST live connection)
25
+ │ ├── types/ # TypeScript schemas & contracts
26
+ │ └── App.tsx # Main application layout
27
+ ├── package.json
28
+ └── vite.config.ts # Dev server with proxy to backend
29
+ ```
30
+
31
+ ---
32
+
33
+ ## Quick Start
34
+
35
+ ### 1. Backend Setup & Run
36
+
37
+ ```powershell
38
+ # Navigate to backend
39
+ cd backend
40
+
41
+ # Setup virtual environment (if not already created)
42
+ python -m venv .venv
43
+ .\.venv\Scripts\Activate.ps1
44
+ pip install -r requirements.txt
45
+
46
+ # Run FastAPI backend with Uvicorn (port 8000)
47
+ uvicorn app.main:app --reload --host 127.0.0.1 --port 8000
48
+ ```
49
+
50
+ - API Docs / Swagger UI: `http://127.0.0.1:8000/docs`
51
+ - Health check: `http://127.0.0.1:8000/health`
52
+ - Frontend snapshot: `http://127.0.0.1:8000/live/frontend`
53
+ - WebSocket stream: `ws://127.0.0.1:8000/live/ws`
54
+
55
+ ### 2. Frontend Setup & Run
56
+
57
+ ```powershell
58
+ # Navigate to frontend dashboard
59
+ cd frontend\Dashboard
60
+
61
+ # Install dependencies (Node 18+)
62
+ npm install
63
+
64
+ # Run Vite dev server (port 5173 with proxy to backend)
65
+ npm run dev
66
+ ```
67
+
68
+ Open `http://localhost:5173` in your browser.
69
+
70
+ ---
71
+
72
+ ## Live Features & Wiring
73
+
74
+ - **WebSocket Stream (`/live/ws`)**: Streams real-time snapshot every second directly to the dashboard.
75
+ - **REST Snapshot (`/live/frontend`)**: Provides zero-delay initial load and automatic polling fallback if the socket disconnects.
76
+ - **Live Leaderboard & Win Probabilities**: Real-time XGBoost winner probabilities updated lap-by-lap.
77
+ - **Live Driver Vitals**: Speed (km/h), RPM, Gear, Throttle %, Brake, DRS status.
78
+ - **Live Track & Weather Strip**: Dynamic track temperature, air temperature, rain probability, and track status flags (Clear, Caution, Safety Car).
79
+ - **Interactive Controls**: Header includes live connection status indicator, "Simulate Lap" action to trigger test predictions, and race reset.
80
+
81
+ ---
82
+
83
+ ## Running Tests
84
+
85
+ ### Backend Tests
86
+ ```powershell
87
+ cd backend
88
+ python -m pytest
89
+ ```
90
+
91
+ ### Frontend Build & Typecheck
92
+ ```powershell
93
+ cd frontend\Dashboard
94
+ npm run build
95
+ ```
96
+
97
+ ---
98
+
99
+ Copyright © 2026 NexInteract Systems Pvt. Ltd. All rights reserved.
backend/.env.example ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ APP_NAME=F1 Live Winner Backend
2
+ APP_ENV=development
3
+ APP_HOST=0.0.0.0
4
+ APP_PORT=8000
5
+ APP_LOG_LEVEL=INFO
6
+
7
+ MODEL_BACKEND=local
8
+ MODEL_PATH=models/f1_live_winner_model.pkl
9
+ MODEL_SCHEMA_PATH=models/f1_live_winner_feature_schema.json
10
+
11
+ # Set true to use the isolated OpenF1 REST adapter instead of LiveF1.
12
+ # Real-time OpenF1 data requires a paid access token; historical data is public.
13
+ OPENF1_ENABLED=false
14
+ OPENF1_BASE_URL=https://api.openf1.org/v1
15
+ OPENF1_API_TOKEN=
16
+ OPENF1_SESSION_KEY=latest
17
+ OPENF1_POLL_INTERVAL_SECONDS=3
18
+ OPENF1_TIMEOUT_SECONDS=15
19
+
backend/app/api/routes_health.py ADDED
File without changes
backend/app/api/routes_live.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime, timezone
2
+ from functools import lru_cache
3
+ from typing import Any
4
+
5
+ from fastapi import (
6
+ APIRouter,
7
+ Body,
8
+ HTTPException,
9
+ )
10
+
11
+ from app.config import get_settings
12
+ from app.providers.livef1_provider import LiveF1Provider
13
+ from app.providers.openf1_provider import OpenF1Provider
14
+ from app.services.driver_registry import DriverRegistry
15
+ from app.services.feature_engineer import LiveFeatureEngineer
16
+ from app.services.inference_gateway import get_inference_gateway
17
+ from app.services.live_compressor import LiveLapCompressor
18
+ from app.services.live_pipeline import LivePipeline
19
+ from app.services.live_state import LiveRaceState
20
+ from app.services.prediction_service import PredictionService
21
+ from app.services.raw_normalizer import RawNormalizer
22
+ from app.utils.logger import log_stream_event
23
+
24
+
25
+ router = APIRouter(prefix="/live", tags=["live race"])
26
+
27
+
28
+ class LiveRuntime:
29
+ def __init__(self) -> None:
30
+ self.predictions = PredictionService(
31
+ compressor=LiveLapCompressor(),
32
+ feature_engineer=LiveFeatureEngineer(get_settings()),
33
+ gateway=get_inference_gateway(),
34
+ )
35
+
36
+ self.pipeline = LivePipeline(
37
+ normalizer=RawNormalizer(),
38
+ registry=DriverRegistry(),
39
+ state=LiveRaceState(),
40
+ predictions=self.predictions,
41
+ )
42
+
43
+ settings = get_settings()
44
+ if settings.openf1_enabled:
45
+ self.provider = OpenF1Provider(
46
+ self.pipeline.handle_records,
47
+ base_url=settings.openf1_base_url,
48
+ api_token=settings.openf1_api_token,
49
+ session_key=settings.openf1_session_key,
50
+ poll_interval_seconds=settings.openf1_poll_interval_seconds,
51
+ timeout_seconds=settings.openf1_timeout_seconds,
52
+ )
53
+ else:
54
+ self.provider = LiveF1Provider(self.pipeline.handle_records)
55
+
56
+
57
+ @lru_cache(maxsize=1)
58
+ def get_live_runtime() -> LiveRuntime:
59
+ return LiveRuntime()
60
+
61
+
62
+ @router.post("/start")
63
+ async def start_live_feed() -> dict[str, Any]:
64
+ runtime = get_live_runtime()
65
+ log_stream_event("API request to start live feed received")
66
+ await runtime.provider.start()
67
+
68
+ return {
69
+ "message": f"{runtime.provider.status()['provider']} feed started",
70
+ **runtime.provider.status(),
71
+ }
72
+
73
+
74
+ @router.post("/stop")
75
+ async def stop_live_feed() -> dict[str, Any]:
76
+ runtime = get_live_runtime()
77
+ log_stream_event("API request to stop live feed received")
78
+ await runtime.provider.stop()
79
+
80
+ return {
81
+ "message": f"{runtime.provider.status()['provider']} feed stopped",
82
+ **runtime.provider.status(),
83
+ }
84
+
85
+
86
+ @router.post("/reset")
87
+ async def reset_live_state() -> dict[str, str]:
88
+ runtime = get_live_runtime()
89
+ log_stream_event("Live race state and predictions cleared")
90
+ await runtime.pipeline.reset()
91
+
92
+ return {
93
+ "message": "Live race state and predictions cleared",
94
+ }
95
+
96
+
97
+ @router.get("/status")
98
+ async def live_status() -> dict[str, Any]:
99
+ runtime = get_live_runtime()
100
+
101
+ return {
102
+ "provider": runtime.provider.status(),
103
+ "pipeline": runtime.pipeline.status(),
104
+ }
105
+
106
+
107
+ @router.get("/predictions")
108
+ async def live_predictions() -> dict[str, Any]:
109
+ predictions = get_live_runtime().predictions
110
+ leaderboard = await predictions.leaderboard()
111
+ final_state = await predictions.final_state()
112
+
113
+ return {
114
+ "predicted_winner": (
115
+ leaderboard[0]["driver"]
116
+ if leaderboard
117
+ else None
118
+ ),
119
+ "leaderboard": leaderboard,
120
+ **final_state,
121
+ }
122
+
123
+
124
+ async def build_frontend_snapshot() -> dict[str, Any]:
125
+ runtime = get_live_runtime()
126
+
127
+ provider = runtime.provider.status()
128
+ pipeline = runtime.pipeline.status()
129
+ race = await runtime.pipeline.frontend_state()
130
+ leaderboard = await runtime.predictions.leaderboard()
131
+ final_state = await runtime.predictions.final_state()
132
+
133
+ if provider.get("last_error"):
134
+ feed_status = "error"
135
+
136
+ elif pipeline.get("session_status") == "finished":
137
+ feed_status = "finished"
138
+
139
+ elif provider.get("running") and provider.get("is_stale", True):
140
+ feed_status = "waiting_for_data" if provider.get("last_received_at") is None else "stale"
141
+
142
+ elif provider.get("running") and leaderboard:
143
+ feed_status = "live"
144
+
145
+ elif provider.get("running"):
146
+ feed_status = "waiting_for_completed_lap"
147
+
148
+ elif leaderboard:
149
+ feed_status = "stopped_with_cached_predictions"
150
+
151
+ else:
152
+ feed_status = "offline"
153
+
154
+ predicted_winner = leaderboard[0] if leaderboard else None
155
+ lifecycle = runtime.pipeline.lifecycle()
156
+
157
+ return {
158
+ "status": feed_status,
159
+ "generated_at": datetime.now(timezone.utc).isoformat(),
160
+ "source": provider.get("provider"),
161
+ "provider": provider,
162
+ "pipeline": pipeline,
163
+ "race": {
164
+ **lifecycle,
165
+ **race,
166
+ },
167
+ "prediction": {
168
+ "predicted_winner": predicted_winner,
169
+ "leaderboard": leaderboard,
170
+ "driver_count": len(leaderboard),
171
+ **final_state,
172
+ },
173
+ }
174
+
175
+
176
+ @router.get("/frontend")
177
+ async def frontend_snapshot() -> dict[str, Any]:
178
+ return await build_frontend_snapshot()
179
+
180
+
181
+ @router.post("/test-lap")
182
+ async def test_completed_lap(
183
+ samples: list[dict[str, Any]] = Body(
184
+ ...,
185
+ min_length=1,
186
+ ),
187
+ ) -> dict[str, Any]:
188
+ try:
189
+ prediction = await (
190
+ get_live_runtime()
191
+ .predictions
192
+ .process_samples(samples)
193
+ )
194
+
195
+ except (ValueError, TypeError) as exc:
196
+ raise HTTPException(
197
+ status_code=422,
198
+ detail=str(exc),
199
+ ) from exc
200
+
201
+ return {
202
+ "prediction": prediction,
203
+ "leaderboard": (
204
+ await get_live_runtime()
205
+ .predictions
206
+ .leaderboard()
207
+ ),
208
+ }
209
+
210
+
211
+ @router.post("/feed")
212
+ async def ingest_live_feed(
213
+ records: dict[str, list[dict[str, Any]]] = Body(...),
214
+ ) -> dict[str, Any]:
215
+ runtime = get_live_runtime()
216
+ await runtime.pipeline.handle_records(records)
217
+ return {
218
+ "message": "Records ingested",
219
+ "pipeline": runtime.pipeline.status(),
220
+ }
backend/app/api/routes_race.py ADDED
File without changes
backend/app/api/websocket.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+ from typing import Any
4
+
5
+ from fastapi import APIRouter, WebSocket, WebSocketDisconnect
6
+
7
+ from app.api.routes_live import build_frontend_snapshot, get_live_runtime
8
+ from app.utils.logger import log_stream_event
9
+
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ router = APIRouter(prefix="/live", tags=["live websocket"])
14
+
15
+
16
+ class LiveWebSocketManager:
17
+ """
18
+ Decouples LiveF1Provider lifecycle from individual frontend WebSocket connections.
19
+
20
+ - Starts the LiveF1 provider on the first frontend connection (if not already running).
21
+ - Prevents rapid start/stop cycles caused by React StrictMode double-mount in dev mode.
22
+ - Keeps provider running through short client disconnects / page refreshes.
23
+ - Only initiates provider shutdown after ALL clients remain disconnected for the grace period (45s).
24
+ """
25
+
26
+ def __init__(self, grace_period_seconds: float = 45.0) -> None:
27
+ self._active_connections: set[WebSocket] = set()
28
+ self._grace_period_seconds = grace_period_seconds
29
+ self._delayed_stop_task: asyncio.Task | None = None
30
+ self._lock = asyncio.Lock()
31
+
32
+ async def connect(self, websocket: WebSocket) -> None:
33
+ await websocket.accept()
34
+ async with self._lock:
35
+ self._active_connections.add(websocket)
36
+ count = len(self._active_connections)
37
+
38
+ # Cancel any pending grace period stop task
39
+ if self._delayed_stop_task is not None and not self._delayed_stop_task.done():
40
+ self._delayed_stop_task.cancel()
41
+ self._delayed_stop_task = None
42
+ log_stream_event("Delayed stop cancelled: frontend client connected within grace period")
43
+
44
+ log_stream_event(f"Frontend WebSocket connected (active clients: {count})")
45
+
46
+ # Auto-start provider on first connection if not running
47
+ runtime = get_live_runtime()
48
+ if not runtime.provider.status()["running"]:
49
+ log_stream_event("First frontend client connected: initiating LiveF1Provider in background")
50
+ await runtime.provider.start()
51
+
52
+ async def disconnect(self, websocket: WebSocket) -> None:
53
+ async with self._lock:
54
+ self._active_connections.discard(websocket)
55
+ count = len(self._active_connections)
56
+ log_stream_event(f"Frontend WebSocket disconnected (active clients remaining: {count})")
57
+
58
+ # Ingestion must survive closed tabs and REST-only monitoring.
59
+ # Stop explicitly through /live/stop or application shutdown.
60
+
61
+ async def _grace_period_stop(self, delay: float) -> None:
62
+ try:
63
+ await asyncio.sleep(delay)
64
+ async with self._lock:
65
+ if len(self._active_connections) == 0:
66
+ log_stream_event(
67
+ f"Grace period ({int(delay)}s) expired with 0 connected clients. Stopping LiveF1Provider."
68
+ )
69
+ runtime = get_live_runtime()
70
+ await runtime.provider.stop()
71
+ except asyncio.CancelledError:
72
+ pass
73
+
74
+ async def shutdown(self) -> None:
75
+ """Called on FastAPI shutdown to terminate pending tasks."""
76
+ async with self._lock:
77
+ if self._delayed_stop_task is not None and not self._delayed_stop_task.done():
78
+ self._delayed_stop_task.cancel()
79
+ self._delayed_stop_task = None
80
+
81
+
82
+ manager = LiveWebSocketManager(grace_period_seconds=45.0)
83
+
84
+
85
+ @router.websocket("/ws")
86
+ async def live_websocket(websocket: WebSocket) -> None:
87
+ await manager.connect(websocket)
88
+
89
+ try:
90
+ while True:
91
+ snapshot = await build_frontend_snapshot()
92
+ await websocket.send_json(snapshot)
93
+ await asyncio.sleep(1)
94
+
95
+ except WebSocketDisconnect:
96
+ await manager.disconnect(websocket)
97
+
98
+ except Exception:
99
+ logger.exception("Frontend WebSocket encountered an error")
100
+ await manager.disconnect(websocket)
101
+ try:
102
+ await websocket.close(code=1011)
103
+ except RuntimeError:
104
+ pass
backend/app/config.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import lru_cache
2
+ from pathlib import Path
3
+
4
+ from pydantic import Field, field_validator
5
+ from pydantic_settings import BaseSettings, SettingsConfigDict
6
+
7
+
8
+ PROJECT_ROOT = Path(__file__).resolve().parents[1]
9
+
10
+
11
+ class Settings(BaseSettings):
12
+ """Application configuration loaded from environment variables."""
13
+
14
+ model_config = SettingsConfigDict(
15
+ env_file=PROJECT_ROOT / ".env",
16
+ env_file_encoding="utf-8",
17
+ case_sensitive=False,
18
+ extra="ignore",
19
+ )
20
+
21
+ app_name: str = "F1 Live Winner Backend"
22
+ app_env: str = "development"
23
+ app_host: str = "0.0.0.0"
24
+ app_port: int = Field(default=8000, ge=1, le=65535)
25
+ app_log_level: str = "INFO"
26
+
27
+ model_backend: str = "local"
28
+ remote_model_url: str | None = None
29
+ remote_model_api_token: str | None = None
30
+ remote_model_timeout_seconds: float = 30.0
31
+
32
+ model_path: Path = Path("models/f1_live_winner_model.pkl")
33
+ model_schema_path: Path = Path(
34
+ "models/f1_live_winner_feature_schema.json"
35
+ )
36
+
37
+ openf1_enabled: bool = False
38
+ openf1_base_url: str = "https://api.openf1.org/v1"
39
+ openf1_api_token: str | None = None
40
+ openf1_session_key: str = "latest"
41
+ openf1_poll_interval_seconds: float = Field(default=3.0, ge=1.0)
42
+ openf1_timeout_seconds: float = Field(default=15.0, gt=0)
43
+
44
+ @field_validator("app_log_level")
45
+ @classmethod
46
+ def normalize_log_level(cls, value: str) -> str:
47
+ normalized = value.strip().upper()
48
+ allowed = {"CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"}
49
+ if normalized not in allowed:
50
+ raise ValueError(f"APP_LOG_LEVEL must be one of {sorted(allowed)}")
51
+ return normalized
52
+
53
+ @field_validator("model_path", "model_schema_path", mode="after")
54
+ @classmethod
55
+ def resolve_project_path(cls, value: Path) -> Path:
56
+ if value.is_absolute():
57
+ return value.resolve()
58
+ return (PROJECT_ROOT / value).resolve()
59
+
60
+
61
+ @lru_cache(maxsize=1)
62
+ def get_settings() -> Settings:
63
+ return Settings()
64
+
backend/app/main.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from contextlib import asynccontextmanager
3
+ from typing import Any
4
+
5
+ from fastapi import FastAPI
6
+ from fastapi.middleware.cors import CORSMiddleware
7
+
8
+ from app.api.routes_live import get_live_runtime, router as live_router
9
+ from app.api.websocket import router as websocket_router
10
+ from app.config import get_settings
11
+ from app.schemas import HealthResponse
12
+ from app.services.inference_gateway import get_inference_gateway
13
+ from app.services.model_service import ModelLoadError, get_model_service
14
+ from app.utils.logger import LOG_FILE_PATH, setup_logging
15
+
16
+
17
+ settings = get_settings()
18
+ setup_logging(settings.app_log_level)
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+
23
+ @asynccontextmanager
24
+ async def lifespan(_: FastAPI):
25
+ gateway = get_inference_gateway()
26
+ await gateway.startup()
27
+ if gateway.mode != "remote":
28
+ model_service = get_model_service()
29
+ logger.info(
30
+ "Model loaded with %d input features",
31
+ model_service.metadata.feature_count,
32
+ )
33
+ logger.info("Inference backend mode: %s", gateway.mode)
34
+ try:
35
+ yield
36
+ finally:
37
+ from app.api.websocket import manager
38
+ await manager.shutdown()
39
+ await get_live_runtime().provider.stop()
40
+ await get_live_runtime().pipeline.shutdown()
41
+
42
+
43
+ app = FastAPI(
44
+ title=settings.app_name,
45
+ version="0.1.0",
46
+ description="Live F1 lap ingestion and winner-prediction backend.",
47
+ lifespan=lifespan,
48
+ )
49
+
50
+ app.add_middleware(
51
+ CORSMiddleware,
52
+ allow_origins=["*"],
53
+ allow_credentials=False,
54
+ allow_methods=["*"],
55
+ allow_headers=["*"],
56
+ )
57
+
58
+ app.include_router(websocket_router)
59
+ app.include_router(live_router)
60
+
61
+
62
+ @app.get("/", tags=["system"])
63
+ async def root() -> dict[str, str]:
64
+ return {
65
+ "service": settings.app_name,
66
+ "docs": "/docs",
67
+ "health": "/health",
68
+ }
69
+
70
+
71
+ @app.get("/health", response_model=HealthResponse, tags=["system"])
72
+ async def health() -> HealthResponse:
73
+ gateway = get_inference_gateway()
74
+
75
+ if gateway.mode == "remote":
76
+ return HealthResponse(
77
+ status="ok",
78
+ service=settings.app_name,
79
+ environment=settings.app_env,
80
+ model_loaded=False,
81
+ inference_backend="remote",
82
+ detail="Hosted model mode configured; local model is not loaded.",
83
+ )
84
+
85
+ model_service = get_model_service()
86
+
87
+ try:
88
+ metadata = model_service.metadata
89
+ except ModelLoadError as exc:
90
+ return HealthResponse(
91
+ status="degraded",
92
+ service=settings.app_name,
93
+ environment=settings.app_env,
94
+ model_loaded=False,
95
+ inference_backend=gateway.mode,
96
+ detail=str(exc),
97
+ )
98
+
99
+ return HealthResponse(
100
+ status="ok",
101
+ service=settings.app_name,
102
+ environment=settings.app_env,
103
+ model_loaded=True,
104
+ model_feature_count=metadata.feature_count,
105
+ pipeline_version=metadata.pipeline_version,
106
+ inference_backend=gateway.mode,
107
+ )
108
+
109
+
110
+ @app.get("/logs", tags=["system"])
111
+ async def get_logs(lines: int = 100) -> dict[str, Any]:
112
+ """Retrieve the most recent log lines from logs.txt."""
113
+ if not LOG_FILE_PATH.exists():
114
+ return {"log_file": str(LOG_FILE_PATH), "lines": [], "count": 0}
115
+
116
+ try:
117
+ content = LOG_FILE_PATH.read_text(encoding="utf-8", errors="replace")
118
+ all_lines = content.strip().splitlines()
119
+ recent = all_lines[-max(1, min(lines, 1000)):]
120
+ return {
121
+ "log_file": str(LOG_FILE_PATH),
122
+ "lines": recent,
123
+ "count": len(recent),
124
+ "total_lines": len(all_lines),
125
+ }
126
+ except Exception as exc:
127
+ return {"error": f"Failed to read logs: {exc}", "lines": []}
128
+
backend/app/providers/base.py ADDED
File without changes
backend/app/providers/fastf1_replay.py ADDED
File without changes
backend/app/providers/livef1_provider.py ADDED
@@ -0,0 +1,487 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+ import threading
4
+ from collections.abc import Awaitable, Callable
5
+ from datetime import datetime, timezone
6
+ from typing import Any, Mapping
7
+
8
+ import requests
9
+ from livef1.data_processing.etl import function_map
10
+ from signalrcore.hub_connection_builder import HubConnectionBuilder
11
+ from signalrcore.messages.completion_message import CompletionMessage
12
+
13
+ from app.utils.logger import log_connection_event
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ LIVEF1_TOPICS = [
19
+ "Heartbeat",
20
+ "DriverList",
21
+ "CarData.z",
22
+ "Position.z",
23
+ "TimingData",
24
+ "TimingStats",
25
+ "TimingAppData",
26
+ "WeatherData",
27
+ "TrackStatus",
28
+ "SessionStatus",
29
+ "SessionData",
30
+ "RaceControlMessages",
31
+ "LapCount",
32
+ ]
33
+
34
+
35
+ class LiveF1Provider:
36
+ """F1 SignalR Core provider with authentication and async bridging."""
37
+
38
+ NEGOTIATE_URL = (
39
+ "https://livetiming.formula1.com/signalrcore/negotiate"
40
+ )
41
+ CONNECTION_URL = (
42
+ "wss://livetiming.formula1.com/signalrcore"
43
+ )
44
+
45
+ def __init__(
46
+ self,
47
+ on_records: Callable[
48
+ [Mapping[str, list[Any]]],
49
+ Awaitable[None],
50
+ ],
51
+ retry_delay_seconds: int = 5,
52
+ max_retry_delay_seconds: int = 30,
53
+ ) -> None:
54
+ self._on_records = on_records
55
+
56
+ self._initial_retry_delay = retry_delay_seconds
57
+ self._max_retry_delay = max_retry_delay_seconds
58
+ self._retry_delay_seconds = retry_delay_seconds
59
+
60
+ self._task: asyncio.Task | None = None
61
+ self._control_lock = asyncio.Lock()
62
+
63
+ self._running = False
64
+ self._connected = False
65
+ self._retrying = False
66
+ self._retry_count = 0
67
+
68
+ self._last_error: str | None = None
69
+ self._last_received_at: datetime | None = None
70
+
71
+ self._parse_errors = 0
72
+ self._last_parse_error: str | None = None
73
+
74
+ self._hub: Any | None = None
75
+ self._message_queue: asyncio.Queue[Any] | None = None
76
+ self._event_loop: asyncio.AbstractEventLoop | None = None
77
+
78
+ self._connected_event = threading.Event()
79
+ self._closed_event = threading.Event()
80
+
81
+ async def start(self) -> None:
82
+ async with self._control_lock:
83
+ if self._task is not None and not self._task.done():
84
+ return
85
+
86
+ self._running = True
87
+ self._connected = False
88
+ self._retrying = False
89
+ self._last_error = None
90
+ self._retry_count = 0
91
+ self._last_received_at = None
92
+
93
+ self._task = asyncio.create_task(
94
+ self._run_forever(),
95
+ name="livef1-feed",
96
+ )
97
+
98
+ async def stop(self) -> None:
99
+ async with self._control_lock:
100
+ self._running = False
101
+
102
+ if self._hub is not None:
103
+ try:
104
+ await asyncio.to_thread(self._hub.stop)
105
+ except Exception:
106
+ logger.warning(
107
+ "Failed to stop SignalR connection",
108
+ exc_info=True,
109
+ )
110
+
111
+ if self._task is not None:
112
+ self._task.cancel()
113
+
114
+ try:
115
+ await self._task
116
+ except asyncio.CancelledError:
117
+ pass
118
+
119
+ self._task = None
120
+
121
+ self._hub = None
122
+ self._connected = False
123
+ self._retrying = False
124
+
125
+ def status(self) -> dict[str, Any]:
126
+ age = None
127
+
128
+ if self._last_received_at is not None:
129
+ age = (
130
+ datetime.now(timezone.utc)
131
+ - self._last_received_at
132
+ ).total_seconds()
133
+
134
+ return {
135
+ "provider": "LiveF1-SignalRCore",
136
+ "running": self._running,
137
+ "connected": self._connected,
138
+ "thread_alive": self._hub is not None,
139
+ "task_alive": bool(
140
+ self._task and not self._task.done()
141
+ ),
142
+ "retrying": self._retrying,
143
+ "retry_count": self._retry_count,
144
+ "retry_delay_seconds": self._retry_delay_seconds,
145
+ "topics": LIVEF1_TOPICS,
146
+ "last_error": self._last_error,
147
+ "last_received_at": (
148
+ self._last_received_at.isoformat()
149
+ if self._last_received_at
150
+ else None
151
+ ),
152
+ "data_age_seconds": age,
153
+ "is_stale": age is None or age > 15,
154
+ "parse_errors": self._parse_errors,
155
+ "last_parse_error": self._last_parse_error,
156
+ }
157
+
158
+ async def _run_forever(self) -> None:
159
+ failures = 0
160
+
161
+ try:
162
+ while self._running:
163
+ received_before_attempt = self._last_received_at
164
+
165
+ try:
166
+ await self._run_client_once()
167
+
168
+ if self._running:
169
+ raise ConnectionError(
170
+ "LiveF1 stream ended"
171
+ )
172
+
173
+ except asyncio.CancelledError:
174
+ raise
175
+
176
+ except Exception as exc:
177
+ self._connected = False
178
+ self._retrying = True
179
+ self._retry_count += 1
180
+
181
+ if (
182
+ self._last_received_at
183
+ != received_before_attempt
184
+ ):
185
+ failures = 1
186
+ else:
187
+ failures += 1
188
+
189
+ self._last_error = (
190
+ f"{type(exc).__name__}: {exc}"
191
+ )
192
+
193
+ delay = (
194
+ self._initial_retry_delay
195
+ * 1.5 ** min(failures - 1, 8)
196
+ )
197
+
198
+ self._retry_delay_seconds = min(
199
+ self._max_retry_delay,
200
+ max(1, int(delay)),
201
+ )
202
+
203
+ log_connection_event(
204
+ "LiveF1 connection failure",
205
+ self._last_error,
206
+ )
207
+
208
+ await asyncio.sleep(
209
+ self._retry_delay_seconds
210
+ )
211
+
212
+ finally:
213
+ self._running = False
214
+ self._connected = False
215
+ self._retrying = False
216
+
217
+ async def _run_client_once(self) -> None:
218
+ self._event_loop = asyncio.get_running_loop()
219
+ self._message_queue = asyncio.Queue()
220
+
221
+ self._connected_event.clear()
222
+ self._closed_event.clear()
223
+
224
+ headers = await asyncio.to_thread(
225
+ self._get_connection_headers
226
+ )
227
+
228
+ options = {
229
+ "verify_ssl": True,
230
+ "headers": headers,
231
+ }
232
+
233
+ hub = (
234
+ HubConnectionBuilder()
235
+ .with_url(self.CONNECTION_URL, options=options)
236
+ .configure_logging(logging.WARNING)
237
+ .build()
238
+ )
239
+
240
+ self._hub = hub
241
+
242
+ hub.on_open(self._on_open)
243
+ hub.on_close(self._on_close)
244
+ hub.on_error(self._on_error)
245
+ hub.on("feed", self._on_signalr_message)
246
+
247
+ try:
248
+ await asyncio.to_thread(hub.start)
249
+
250
+ connected = await asyncio.to_thread(
251
+ self._connected_event.wait,
252
+ 15,
253
+ )
254
+
255
+ if not connected:
256
+ raise TimeoutError(
257
+ "SignalR Core connection timed out"
258
+ )
259
+
260
+ hub.send(
261
+ "Subscribe",
262
+ [LIVEF1_TOPICS],
263
+ on_invocation=self._on_signalr_message,
264
+ )
265
+
266
+ while self._running and not self._closed_event.is_set():
267
+ try:
268
+ message = await asyncio.wait_for(
269
+ self._message_queue.get(),
270
+ timeout=20,
271
+ )
272
+ except asyncio.TimeoutError:
273
+ if self._closed_event.is_set():
274
+ break
275
+
276
+ logger.debug(
277
+ "SignalR connected but no message received"
278
+ )
279
+ continue
280
+
281
+ if isinstance(message, Exception):
282
+ raise message
283
+
284
+ await self._process_message(message)
285
+
286
+ if self._running:
287
+ raise ConnectionError(
288
+ "SignalR Core connection closed"
289
+ )
290
+
291
+ finally:
292
+ try:
293
+ await asyncio.to_thread(hub.stop)
294
+ except Exception:
295
+ logger.debug(
296
+ "SignalR connection already stopped",
297
+ exc_info=True,
298
+ )
299
+
300
+ self._hub = None
301
+ self._connected = False
302
+
303
+ def _get_connection_headers(self) -> dict[str, str]:
304
+ """Obtain the AWS load-balancer cookie required by F1."""
305
+
306
+ request_headers = {
307
+ "User-Agent": (
308
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
309
+ "AppleWebKit/537.36 Chrome/131 Safari/537.36"
310
+ ),
311
+ "Origin": "https://www.formula1.com",
312
+ "Referer": "https://www.formula1.com/",
313
+ }
314
+
315
+ aws_cookie = None
316
+ try:
317
+ response = requests.options(
318
+ self.NEGOTIATE_URL,
319
+ headers=request_headers,
320
+ timeout=15,
321
+ )
322
+ # F1 negotiate endpoint returns 405 on OPTIONS but sets AWSALBCORS cookie
323
+ aws_cookie = response.cookies.get("AWSALBCORS") or response.cookies.get("AWSALB")
324
+ except Exception as exc:
325
+ logger.warning("F1 negotiate preflight request error: %s", exc)
326
+
327
+ if not aws_cookie:
328
+ try:
329
+ get_response = requests.get(
330
+ self.NEGOTIATE_URL,
331
+ headers=request_headers,
332
+ timeout=15,
333
+ )
334
+ aws_cookie = get_response.cookies.get("AWSALBCORS") or get_response.cookies.get("AWSALB")
335
+ except Exception:
336
+ pass
337
+
338
+ headers = dict(request_headers)
339
+ if aws_cookie:
340
+ headers["Cookie"] = f"AWSALBCORS={aws_cookie}"
341
+ return headers
342
+
343
+ def _on_open(self) -> None:
344
+ self._connected = True
345
+ self._retrying = False
346
+ self._last_error = None
347
+
348
+ self._connected_event.set()
349
+
350
+ log_connection_event(
351
+ "LiveF1 SignalR Core connected"
352
+ )
353
+
354
+ def _on_close(self) -> None:
355
+ self._connected = False
356
+ self._closed_event.set()
357
+
358
+ if self._running:
359
+ self._push_to_async_queue(
360
+ ConnectionError(
361
+ "LiveF1 SignalR Core connection closed"
362
+ )
363
+ )
364
+
365
+ def _on_error(self, error: Any) -> None:
366
+ self._connected = False
367
+
368
+ if self._running:
369
+ self._push_to_async_queue(
370
+ ConnectionError(
371
+ f"SignalR Core error: {error}"
372
+ )
373
+ )
374
+
375
+ def _on_signalr_message(self, message: Any) -> None:
376
+ self._push_to_async_queue(message)
377
+
378
+ def _push_to_async_queue(self, message: Any) -> None:
379
+ loop = self._event_loop
380
+ queue = self._message_queue
381
+
382
+ if loop is None or queue is None or loop.is_closed():
383
+ return
384
+
385
+ loop.call_soon_threadsafe(
386
+ queue.put_nowait,
387
+ message,
388
+ )
389
+
390
+ async def _process_message(self, message: Any) -> None:
391
+ updates: list[tuple[str, Any, Any]] = []
392
+
393
+ if isinstance(message, CompletionMessage):
394
+ result = message.result
395
+
396
+ if isinstance(result, dict):
397
+ updates.extend(
398
+ (topic, data, None)
399
+ for topic, data in result.items()
400
+ )
401
+
402
+ elif isinstance(message, list):
403
+ # Live updates normally arrive as:
404
+ # [topic, payload, timestamp]
405
+ if (
406
+ len(message) >= 2
407
+ and isinstance(message[0], str)
408
+ ):
409
+ timestamp = (
410
+ message[2]
411
+ if len(message) >= 3
412
+ else None
413
+ )
414
+
415
+ updates.append(
416
+ (message[0], message[1], timestamp)
417
+ )
418
+
419
+ else:
420
+ # Be tolerant if the client returns multiple
421
+ # updates inside one list.
422
+ for item in message:
423
+ if (
424
+ isinstance(item, list)
425
+ and len(item) >= 2
426
+ and isinstance(item[0], str)
427
+ ):
428
+ timestamp = (
429
+ item[2]
430
+ if len(item) >= 3
431
+ else None
432
+ )
433
+
434
+ updates.append(
435
+ (item[0], item[1], timestamp)
436
+ )
437
+
438
+ elif isinstance(message, dict):
439
+ updates.extend(
440
+ (topic, data, None)
441
+ for topic, data in message.items()
442
+ )
443
+
444
+ # Process SessionStatus last so final timing updates
445
+ # are handled before session completion.
446
+ updates.sort(
447
+ key=lambda update: update[0] == "SessionStatus"
448
+ )
449
+
450
+ for topic, data, timestamp in updates:
451
+ parser = function_map.get(topic)
452
+
453
+ if parser is None:
454
+ continue
455
+
456
+ try:
457
+ records = list(
458
+ parser(
459
+ [(timestamp, data)],
460
+ None,
461
+ )
462
+ )
463
+
464
+ except Exception as exc:
465
+ self._parse_errors += 1
466
+ self._last_parse_error = (
467
+ f"{topic}: {type(exc).__name__}: {exc}"
468
+ )
469
+
470
+ logger.warning(
471
+ "LiveF1 parser failed for %s",
472
+ topic,
473
+ exc_info=True,
474
+ )
475
+
476
+ continue
477
+
478
+ if not records:
479
+ continue
480
+
481
+ self._last_received_at = datetime.now(
482
+ timezone.utc
483
+ )
484
+
485
+ await self._on_records(
486
+ {topic: records}
487
+ )
backend/app/providers/openf1_provider.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import json
3
+ from collections.abc import Awaitable, Callable
4
+ from datetime import datetime, timedelta, timezone
5
+ from typing import Any, Mapping
6
+
7
+ import httpx
8
+
9
+ from app.utils.logger import log_connection_event
10
+
11
+
12
+ _ENDPOINT_TOPICS = {
13
+ "car_data": "CarData.z",
14
+ "location": "CarData.z",
15
+ "position": "Position.z",
16
+ "laps": "TimingData",
17
+ "weather": "WeatherData",
18
+ "stints": "TyreStintSeries",
19
+ "pit": "PitStopSeries",
20
+ "race_control": "RaceControlMessages",
21
+ }
22
+
23
+
24
+ class OpenF1Provider:
25
+ """Poll OpenF1 REST data and adapt it to the existing live-pipeline topics."""
26
+
27
+ def __init__(
28
+ self,
29
+ on_records: Callable[[Mapping[str, list[Any]]], Awaitable[None]],
30
+ *,
31
+ base_url: str = "https://api.openf1.org/v1",
32
+ api_token: str | None = None,
33
+ session_key: str = "latest",
34
+ poll_interval_seconds: float = 3.0,
35
+ timeout_seconds: float = 15.0,
36
+ ) -> None:
37
+ self._on_records = on_records
38
+ self._base_url = base_url.rstrip("/")
39
+ self._api_token = api_token
40
+ self._session_key = session_key
41
+ self._poll_interval_seconds = poll_interval_seconds
42
+ self._timeout_seconds = timeout_seconds
43
+ self._task: asyncio.Task | None = None
44
+ self._control_lock = asyncio.Lock()
45
+ self._running = False
46
+ self._connected = False
47
+ self._retrying = False
48
+ self._retry_count = 0
49
+ self._last_error: str | None = None
50
+ self._last_received_at: datetime | None = None
51
+ self._records_received = 0
52
+ self._seen: dict[str, set[str]] = {
53
+ endpoint: set() for endpoint in _ENDPOINT_TOPICS
54
+ }
55
+
56
+ async def start(self) -> None:
57
+ async with self._control_lock:
58
+ if self._task is not None and not self._task.done():
59
+ return
60
+ self._running = True
61
+ self._connected = False
62
+ self._retrying = False
63
+ self._retry_count = 0
64
+ self._last_error = None
65
+ self._last_received_at = None
66
+ self._records_received = 0
67
+ self._seen = {endpoint: set() for endpoint in _ENDPOINT_TOPICS}
68
+ self._task = asyncio.create_task(
69
+ self._run_forever(), name="openf1-feed"
70
+ )
71
+
72
+ async def stop(self) -> None:
73
+ async with self._control_lock:
74
+ if self._task is not None:
75
+ self._task.cancel()
76
+ try:
77
+ await self._task
78
+ except asyncio.CancelledError:
79
+ pass
80
+ self._task = None
81
+ self._running = self._connected = self._retrying = False
82
+
83
+ def status(self) -> dict[str, Any]:
84
+ age = (
85
+ (datetime.now(timezone.utc) - self._last_received_at).total_seconds()
86
+ if self._last_received_at
87
+ else None
88
+ )
89
+ return {
90
+ "provider": "OpenF1",
91
+ "running": self._running,
92
+ "connected": self._connected,
93
+ "thread_alive": False,
94
+ "task_alive": bool(self._task and not self._task.done()),
95
+ "retrying": self._retrying,
96
+ "retry_count": self._retry_count,
97
+ "retry_delay_seconds": self._poll_interval_seconds,
98
+ "session_key": self._session_key,
99
+ "topics": list(_ENDPOINT_TOPICS.values()),
100
+ "last_error": self._last_error,
101
+ "last_received_at": (
102
+ self._last_received_at.isoformat()
103
+ if self._last_received_at
104
+ else None
105
+ ),
106
+ "data_age_seconds": age,
107
+ "is_stale": age is None or age > max(15.0, self._poll_interval_seconds * 3),
108
+ "records_received": self._records_received,
109
+ "parse_errors": 0,
110
+ "last_parse_error": None,
111
+ }
112
+
113
+ async def _run_forever(self) -> None:
114
+ headers = {"Accept": "application/json"}
115
+ if self._api_token:
116
+ headers["Authorization"] = f"Bearer {self._api_token}"
117
+
118
+ # Prevent the first poll from downloading an entire historical session.
119
+ cursor = datetime.now(timezone.utc) - timedelta(seconds=10)
120
+ drivers_loaded = False
121
+ try:
122
+ async with httpx.AsyncClient(
123
+ timeout=self._timeout_seconds,
124
+ follow_redirects=True,
125
+ headers=headers,
126
+ ) as client:
127
+ while True:
128
+ try:
129
+ if not drivers_loaded:
130
+ await self._load_drivers(client)
131
+ drivers_loaded = True
132
+ await self._poll(client, cursor)
133
+ cursor = datetime.now(timezone.utc) - timedelta(seconds=2)
134
+ self._connected = True
135
+ self._retrying = False
136
+ self._last_error = None
137
+ await asyncio.sleep(self._poll_interval_seconds)
138
+ except asyncio.CancelledError:
139
+ raise
140
+ except Exception as exc:
141
+ self._connected = False
142
+ self._retrying = True
143
+ self._retry_count += 1
144
+ self._last_error = f"{type(exc).__name__}: {exc}"
145
+ log_connection_event("OpenF1 polling failure", self._last_error)
146
+ await asyncio.sleep(
147
+ min(30.0, self._poll_interval_seconds * 2 ** min(self._retry_count, 4))
148
+ )
149
+ finally:
150
+ self._running = self._connected = self._retrying = False
151
+
152
+ async def _load_drivers(self, client: httpx.AsyncClient) -> None:
153
+ records = await self._fetch(
154
+ client, "drivers", {"session_key": self._session_key}
155
+ )
156
+ if records:
157
+ adapted = [
158
+ {
159
+ **record,
160
+ "DriverNumber": record.get("driver_number"),
161
+ "Driver": record.get("name_acronym"),
162
+ "Team": record.get("team_name"),
163
+ }
164
+ for record in records
165
+ ]
166
+ await self._on_records({"DriverList": adapted})
167
+
168
+ async def _poll(self, client: httpx.AsyncClient, cursor: datetime) -> None:
169
+ since = cursor.isoformat()
170
+
171
+ async def fetch_endpoint(endpoint: str) -> tuple[str, list[dict[str, Any]]]:
172
+ date_field = "date_start>=" if endpoint == "laps" else "date>="
173
+ params = {"session_key": self._session_key, date_field: since}
174
+ if endpoint == "stints":
175
+ params.pop(date_field)
176
+ return endpoint, await self._fetch(client, endpoint, params)
177
+
178
+ results = await asyncio.gather(
179
+ *(fetch_endpoint(endpoint) for endpoint in _ENDPOINT_TOPICS)
180
+ )
181
+ batches: dict[str, list[dict[str, Any]]] = {}
182
+ for endpoint, records in results:
183
+ fresh = self._deduplicate(endpoint, records)
184
+ for topic, adapted in self._adapt(endpoint, fresh).items():
185
+ batches.setdefault(topic, []).extend(adapted)
186
+
187
+ if batches:
188
+ count = sum(len(records) for records in batches.values())
189
+ self._last_received_at = datetime.now(timezone.utc)
190
+ self._records_received += count
191
+ await self._on_records(batches)
192
+
193
+ async def _fetch(
194
+ self,
195
+ client: httpx.AsyncClient,
196
+ endpoint: str,
197
+ params: Mapping[str, Any],
198
+ ) -> list[dict[str, Any]]:
199
+ response = await client.get(f"{self._base_url}/{endpoint}", params=params)
200
+ response.raise_for_status()
201
+ payload = response.json()
202
+ if not isinstance(payload, list):
203
+ raise ValueError(f"OpenF1 {endpoint} returned a non-list payload")
204
+ return [item for item in payload if isinstance(item, dict)]
205
+
206
+ def _deduplicate(
207
+ self, endpoint: str, records: list[dict[str, Any]]
208
+ ) -> list[dict[str, Any]]:
209
+ fresh: list[dict[str, Any]] = []
210
+ seen = self._seen[endpoint]
211
+ for record in records:
212
+ key = str(record.get("_id") or json.dumps(record, sort_keys=True, default=str))
213
+ if key not in seen:
214
+ seen.add(key)
215
+ fresh.append(record)
216
+ if len(seen) > 50_000:
217
+ seen.clear()
218
+ return fresh
219
+
220
+ @staticmethod
221
+ def _adapt(
222
+ endpoint: str, records: list[dict[str, Any]]
223
+ ) -> dict[str, list[dict[str, Any]]]:
224
+ if not records:
225
+ return {}
226
+ if endpoint == "race_control":
227
+ return OpenF1Provider._adapt_race_control(records)
228
+
229
+ topic = _ENDPOINT_TOPICS[endpoint]
230
+ adapted: list[dict[str, Any]] = []
231
+ for source in records:
232
+ record = dict(source)
233
+ if endpoint == "laps":
234
+ if source.get("lap_duration") is None:
235
+ continue
236
+ record.update({
237
+ "LapNumber": source.get("lap_number"),
238
+ "LapTime": source.get("lap_duration"),
239
+ "Sector1Time": source.get("duration_sector_1"),
240
+ "Sector2Time": source.get("duration_sector_2"),
241
+ "Sector3Time": source.get("duration_sector_3"),
242
+ "SpeedI1": source.get("i1_speed"),
243
+ "SpeedI2": source.get("i2_speed"),
244
+ "SpeedST": source.get("st_speed"),
245
+ "IsPersonalBest": source.get("is_personal_best"),
246
+ })
247
+ elif endpoint == "stints":
248
+ tyre_age = source.get("tyre_age_at_start")
249
+ lap_start = source.get("lap_start")
250
+ lap_end = source.get("lap_end")
251
+ if tyre_age is not None and lap_start is not None and lap_end is not None:
252
+ try:
253
+ tyre_age = float(tyre_age) + max(
254
+ 0.0, float(lap_end) - float(lap_start)
255
+ )
256
+ except (TypeError, ValueError):
257
+ tyre_age = source.get("tyre_age_at_start")
258
+ record.update({
259
+ "Stint": source.get("stint_number"),
260
+ "Compound": source.get("compound"),
261
+ "TyreLife": tyre_age,
262
+ })
263
+ elif endpoint == "pit":
264
+ record["PitInTime"] = source.get("date")
265
+ adapted.append(record)
266
+ return {topic: adapted}
267
+
268
+ @staticmethod
269
+ def _adapt_race_control(
270
+ records: list[dict[str, Any]],
271
+ ) -> dict[str, list[dict[str, Any]]]:
272
+ batches: dict[str, list[dict[str, Any]]] = {}
273
+ for source in records:
274
+ message = str(source.get("message") or "").casefold()
275
+ flag = str(source.get("flag") or "").upper()
276
+ if "session started" in message:
277
+ batches.setdefault("SessionStatus", []).append({"Status": "Started"})
278
+ elif flag == "CHEQUERED" or "session ended" in message:
279
+ batches.setdefault("SessionStatus", []).append({"Status": "Finished"})
280
+ if flag:
281
+ batches.setdefault("TrackStatus", []).append({"Status": flag})
282
+ return batches
backend/app/schemas.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime, timezone
2
+ from typing import Any, Literal
3
+
4
+ from pydantic import BaseModel, ConfigDict, Field, field_validator
5
+
6
+
7
+ class HealthResponse(BaseModel):
8
+ status: Literal["ok", "degraded"]
9
+ service: str
10
+ environment: str
11
+ inference_backend: str
12
+ model_loaded: bool
13
+ model_feature_count: int | None = None
14
+ pipeline_version: str | None = None
15
+ checked_at: datetime = Field(
16
+ default_factory=lambda: datetime.now(timezone.utc)
17
+ )
18
+ detail: str | None = None
19
+
20
+
21
+ class ModelFeatureRow(BaseModel):
22
+ """One completed driver's lap after compression and feature engineering."""
23
+
24
+ model_config = ConfigDict(populate_by_name=True, extra="forbid")
25
+
26
+ driver: str = Field(alias="Driver", min_length=1)
27
+ lap_number: float | None = Field(default=None, alias="LapNumber")
28
+ driver_number: float | None = Field(default=None, alias="DriverNumber")
29
+ rpm_mean: float | None = Field(default=None, alias="RPM_Mean")
30
+ speed_mean: float | None = Field(default=None, alias="Speed_Mean")
31
+ gear_mean: float | None = Field(default=None, alias="nGear_Mean")
32
+ throttle_mean: float | None = Field(default=None, alias="Throttle_Mean")
33
+ brake_mean: float | None = Field(default=None, alias="Brake_Mean")
34
+ drs_mean: float | None = Field(default=None, alias="DRS_Mean")
35
+ x_mean: float | None = Field(default=None, alias="X_Mean")
36
+ y_mean: float | None = Field(default=None, alias="Y_Mean")
37
+ z_mean: float | None = Field(default=None, alias="Z_Mean")
38
+ distance_to_driver_ahead_mean: float | None = Field(
39
+ default=None,
40
+ alias="DistanceToDriverAhead_Mean",
41
+ )
42
+ air_temp_mean: float | None = Field(default=None, alias="AirTemp_Mean")
43
+ track_temp_mean: float | None = Field(default=None, alias="TrackTemp_Mean")
44
+ humidity_mean: float | None = Field(default=None, alias="Humidity_Mean")
45
+ pressure_mean: float | None = Field(default=None, alias="Pressure_Mean")
46
+ wind_direction_mean: float | None = Field(
47
+ default=None,
48
+ alias="WindDirection_Mean",
49
+ )
50
+ wind_speed_mean: float | None = Field(default=None, alias="WindSpeed_Mean")
51
+ differential_distance_sum: float | None = Field(
52
+ default=None,
53
+ alias="DifferentialDistance_Sum",
54
+ )
55
+ distance: float | None = Field(default=None, alias="Distance")
56
+ relative_distance: float | None = Field(default=None, alias="RelativeDistance")
57
+ driver_ahead: str | None = Field(default=None, alias="DriverAhead")
58
+ track_status: float | None = Field(default=None, alias="TrackStatus")
59
+ stint: float | None = Field(default=None, alias="Stint")
60
+ compound: str | None = Field(default=None, alias="Compound")
61
+ tyre_life: float | None = Field(default=None, alias="TyreLife")
62
+ fresh_tyre: float | None = Field(default=None, alias="FreshTyre")
63
+ speed_i1: float | None = Field(default=None, alias="SpeedI1")
64
+ speed_i2: float | None = Field(default=None, alias="SpeedI2")
65
+ speed_fl: float | None = Field(default=None, alias="SpeedFL")
66
+ speed_st: float | None = Field(default=None, alias="SpeedST")
67
+ is_personal_best: float | None = Field(default=None, alias="IsPersonalBest")
68
+ position: float | None = Field(default=None, alias="Position")
69
+ rainfall: float | None = Field(default=None, alias="Rainfall")
70
+ tyre_life_squared: float | None = Field(default=None, alias="TyreLifeSquared")
71
+ track_air_temp_difference: float | None = Field(
72
+ default=None,
73
+ alias="TrackAirTempDifference",
74
+ )
75
+ wind_x: float | None = Field(default=None, alias="WindX")
76
+ wind_y: float | None = Field(default=None, alias="WindY")
77
+
78
+ @field_validator("driver", "driver_ahead", "compound", mode="before")
79
+ @classmethod
80
+ def normalize_categories(cls, value: Any) -> Any:
81
+ if value is None:
82
+ return value
83
+ normalized = str(value).strip().upper()
84
+ return normalized or None
85
+
86
+
87
+ class DriverPrediction(BaseModel):
88
+ driver: str
89
+ lap_number: float | None
90
+ raw_win_probability: float = Field(ge=0.0, le=1.0)
91
+
92
+
93
+ class PredictionBatchResponse(BaseModel):
94
+ predictions: list[DriverPrediction]
95
+ model_feature_count: int
96
+ generated_at: datetime = Field(
97
+ default_factory=lambda: datetime.now(timezone.utc)
98
+ )
backend/app/services/driver_registry.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from dataclasses import dataclass
3
+ from typing import Any, Mapping
4
+
5
+ from app.utils.driver_mapping import lookup_driver_by_number
6
+ from app.utils.logger import log_driver_status
7
+
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ @dataclass(frozen=True, slots=True)
13
+ class DriverIdentity:
14
+ number: int
15
+ acronym: str
16
+ team: str | None = None
17
+
18
+
19
+ class DriverRegistry:
20
+ """Maps racing numbers to the 3-letter acronyms used during model training."""
21
+
22
+ def __init__(self) -> None:
23
+ self._by_number: dict[int, DriverIdentity] = {}
24
+ self._by_acronym: dict[str, DriverIdentity] = {}
25
+
26
+ def update(self, record: Mapping[str, Any]) -> DriverIdentity | None:
27
+ if not isinstance(record, Mapping):
28
+ return None
29
+
30
+ flattened = self._flatten(record)
31
+ number = self._first_int(
32
+ flattened,
33
+ "DriverNumber",
34
+ "DriverNo",
35
+ "RacingNumber",
36
+ "driver_number",
37
+ )
38
+
39
+ acronym = self._first_text(
40
+ flattened,
41
+ "Driver",
42
+ "Tla",
43
+ "NameAcronym",
44
+ "BroadcastName",
45
+ )
46
+
47
+ team = self._first_text(flattened, "TeamName", "Team", "team_name")
48
+
49
+ # If number is known but acronym is missing, use grid fallback
50
+ if number is not None and (acronym is None or not acronym.strip()):
51
+ fallback = lookup_driver_by_number(number)
52
+ if fallback is not None:
53
+ acronym = fallback.acronym
54
+ team = team or fallback.team
55
+ logger.info(
56
+ "[REGISTRY] Driver #%s missing acronym in DriverList -> Auto-resolved to %s (%s) via fallback grid",
57
+ number, acronym, team,
58
+ )
59
+
60
+ if number is None or acronym is None:
61
+ logger.warning(
62
+ "[REGISTRY WARNING] Missing/null driver identity in DriverList record (number=%s, acronym=%s)",
63
+ number, acronym,
64
+ )
65
+ return None
66
+
67
+ acronym = acronym.strip().upper()
68
+ if len(acronym) != 3:
69
+ # Check grid lookup first
70
+ fallback = lookup_driver_by_number(number)
71
+ if fallback is not None:
72
+ acronym = fallback.acronym
73
+ else:
74
+ # BroadcastName may look like "L NORRIS" -> take surname prefix
75
+ surname = acronym.split()[-1]
76
+ acronym = surname[:3] if len(surname) >= 3 else surname.ljust(3, "X")
77
+
78
+ identity = DriverIdentity(number=number, acronym=acronym, team=team)
79
+ self._by_number[number] = identity
80
+ self._by_acronym[acronym] = identity
81
+
82
+ log_driver_status(
83
+ identity.acronym,
84
+ f"Registered #{identity.number}",
85
+ identity.team or "Unknown Team",
86
+ )
87
+ return identity
88
+
89
+ def resolve(self, value: Any) -> DriverIdentity | None:
90
+ if value is None:
91
+ return None
92
+
93
+ # Try resolving as numeric driver number
94
+ try:
95
+ number = int(float(value))
96
+ if number in self._by_number:
97
+ return self._by_number[number]
98
+
99
+ # Fallback to driver mapping table
100
+ fallback = lookup_driver_by_number(number)
101
+ if fallback is not None:
102
+ identity = DriverIdentity(
103
+ number=fallback.number,
104
+ acronym=fallback.acronym,
105
+ team=fallback.team,
106
+ )
107
+ self._by_number[number] = identity
108
+ self._by_acronym[identity.acronym] = identity
109
+ return identity
110
+ except (TypeError, ValueError):
111
+ pass
112
+
113
+ # Try resolving as 3-letter acronym string
114
+ text = str(value).strip().upper()
115
+ if text in self._by_acronym:
116
+ return self._by_acronym[text]
117
+
118
+ return None
119
+
120
+ def snapshot(self) -> list[DriverIdentity]:
121
+ return [self._by_number[key] for key in sorted(self._by_number)]
122
+
123
+ @staticmethod
124
+ def _flatten(record: Mapping[str, Any]) -> dict[str, Any]:
125
+ result: dict[str, Any] = {}
126
+
127
+ def visit(value: Any) -> None:
128
+ if not isinstance(value, Mapping):
129
+ return
130
+ for key, child in value.items():
131
+ if isinstance(child, Mapping):
132
+ visit(child)
133
+ else:
134
+ result.setdefault(str(key), child)
135
+
136
+ visit(record)
137
+ return result
138
+
139
+ @staticmethod
140
+ def _first_text(record: Mapping[str, Any], *keys: str) -> str | None:
141
+ for key in keys:
142
+ value = record.get(key)
143
+ if value is not None and str(value).strip():
144
+ return str(value).strip()
145
+ return None
146
+
147
+ @staticmethod
148
+ def _first_int(record: Mapping[str, Any], *keys: str) -> int | None:
149
+ for key in keys:
150
+ try:
151
+ return int(float(record[key]))
152
+ except (KeyError, TypeError, ValueError):
153
+ continue
154
+ return None
backend/app/services/feature_contract.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+ from typing import Any, Mapping
4
+
5
+
6
+ MODEL_FEATURE_COUNT = 39
7
+
8
+
9
+ class FeatureContractError(ValueError):
10
+ """Raised when a row or schema differs from the saved model contract."""
11
+
12
+
13
+ def load_feature_contract(schema_path: Path) -> tuple[dict[str, Any], tuple[str, ...]]:
14
+ try:
15
+ with schema_path.open("r", encoding="utf-8") as file:
16
+ schema = json.load(file)
17
+ except (OSError, ValueError) as exc:
18
+ raise FeatureContractError(f"Unable to read feature schema: {exc}") from exc
19
+
20
+ features = tuple(schema.get("model_features", ()))
21
+ declared_count = schema.get("raw_feature_count")
22
+ if len(features) != MODEL_FEATURE_COUNT or declared_count != MODEL_FEATURE_COUNT:
23
+ raise FeatureContractError(
24
+ "Saved schema must declare exactly 39 ordered model features"
25
+ )
26
+ if len(set(features)) != len(features) or not all(
27
+ isinstance(feature, str) and feature for feature in features
28
+ ):
29
+ raise FeatureContractError("Saved schema model_features are invalid")
30
+ return schema, features
31
+
32
+
33
+ def validate_feature_row(
34
+ row: Mapping[str, Any],
35
+ expected_features: tuple[str, ...] | list[str],
36
+ ) -> None:
37
+ actual = tuple(row.keys())
38
+ expected = tuple(expected_features)
39
+ if len(actual) != MODEL_FEATURE_COUNT:
40
+ raise FeatureContractError(
41
+ f"Model inference requires exactly 39 features; received {len(actual)}"
42
+ )
43
+ if actual != expected:
44
+ raise FeatureContractError(
45
+ "Model feature names or order differ from the saved schema"
46
+ )
backend/app/services/feature_coverage.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Any, Mapping
3
+
4
+
5
+ CORE_TELEMETRY_FEATURES = frozenset({
6
+ "Speed_Mean",
7
+ "RPM_Mean",
8
+ "Throttle_Mean",
9
+ "TyreLife",
10
+ "Position",
11
+ })
12
+
13
+ MIN_COVERAGE_THRESHOLD = 0.25 # Below 25% is almost certainly an incomplete out-lap
14
+
15
+
16
+ @dataclass(frozen=True, slots=True)
17
+ class FeatureQualityReport:
18
+ total_features: int
19
+ present_features: int
20
+ coverage: float
21
+ core_present: int
22
+ core_total: int
23
+ confidence: str # "high", "medium", "low", "provisional"
24
+ is_usable: bool
25
+ reason: str | None = None
26
+
27
+
28
+ def evaluate_feature_coverage(row: Mapping[str, Any]) -> FeatureQualityReport:
29
+ """Analyze a 39-feature row to determine completeness and prediction confidence."""
30
+ total = len(row)
31
+ if total == 0:
32
+ return FeatureQualityReport(
33
+ total_features=0,
34
+ present_features=0,
35
+ coverage=0.0,
36
+ core_present=0,
37
+ core_total=len(CORE_TELEMETRY_FEATURES),
38
+ confidence="provisional",
39
+ is_usable=False,
40
+ reason="Empty feature row",
41
+ )
42
+
43
+ present = sum(
44
+ 1 for value in row.values()
45
+ if value is not None and value != "UNKNOWN" and str(value).strip() != ""
46
+ )
47
+ coverage = round(present / total, 4)
48
+
49
+ core_present = sum(
50
+ 1 for feat in CORE_TELEMETRY_FEATURES
51
+ if row.get(feat) is not None
52
+ )
53
+ core_total = len(CORE_TELEMETRY_FEATURES)
54
+
55
+ # Determine confidence level
56
+ if coverage >= 0.70 and core_present >= 4:
57
+ confidence = "high"
58
+ is_usable = True
59
+ reason = None
60
+ elif coverage >= 0.40 and core_present >= 2:
61
+ confidence = "medium"
62
+ is_usable = True
63
+ reason = None
64
+ elif coverage >= MIN_COVERAGE_THRESHOLD and core_present >= 2:
65
+ confidence = "low"
66
+ is_usable = True
67
+ reason = "Partial telemetry; provisional prediction"
68
+ else:
69
+ confidence = "provisional"
70
+ is_usable = False
71
+ reason = f"Coverage too low ({coverage:.1%}); out-lap or pit lane idle"
72
+
73
+ return FeatureQualityReport(
74
+ total_features=total,
75
+ present_features=present,
76
+ coverage=coverage,
77
+ core_present=core_present,
78
+ core_total=core_total,
79
+ confidence=confidence,
80
+ is_usable=is_usable,
81
+ reason=reason,
82
+ )
backend/app/services/feature_engineer.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import math
3
+ from typing import Any, Mapping
4
+
5
+ from app.config import Settings, get_settings
6
+ from app.services.feature_contract import load_feature_contract, validate_feature_row
7
+
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ class FeatureEngineeringError(ValueError):
13
+ pass
14
+
15
+
16
+ class LiveFeatureEngineer:
17
+ """Convert a compressed lap into the exact 39-feature model contract."""
18
+
19
+ def __init__(self, settings: Settings) -> None:
20
+ _, features = load_feature_contract(settings.model_schema_path)
21
+ self._feature_columns = features
22
+
23
+ def transform(self, compressed: Mapping[str, Any]) -> dict[str, Any]:
24
+ tyre_life = self._number(compressed.get("TyreLife_Last"))
25
+ track_temp = self._number(compressed.get("TrackTemp_Mean"))
26
+ air_temp = self._number(compressed.get("AirTemp_Mean"))
27
+ wind_speed = self._number(compressed.get("WindSpeed_Mean"))
28
+ wind_direction = self._number(compressed.get("WindDirection_Mean"))
29
+
30
+ row: dict[str, Any] = {
31
+ "Driver": self._category(compressed.get("Driver")),
32
+ "LapNumber": self._number(compressed.get("LapNumber")),
33
+ "DriverNumber": self._number(compressed.get("DriverNumber_Last")),
34
+ "RPM_Mean": self._number(compressed.get("RPM_Mean")),
35
+ "Speed_Mean": self._number(compressed.get("Speed_Mean")),
36
+ "nGear_Mean": self._number(compressed.get("nGear_Mean")),
37
+ "Throttle_Mean": self._number(compressed.get("Throttle_Mean")),
38
+ "Brake_Mean": self._number(compressed.get("Brake_Mean")),
39
+ "DRS_Mean": self._number(compressed.get("DRS_Mean")),
40
+ "X_Mean": self._number(compressed.get("X_Mean")),
41
+ "Y_Mean": self._number(compressed.get("Y_Mean")),
42
+ "Z_Mean": self._number(compressed.get("Z_Mean")),
43
+ "DistanceToDriverAhead_Mean": self._number(
44
+ compressed.get("DistanceToDriverAhead_Mean")
45
+ ),
46
+ "AirTemp_Mean": air_temp,
47
+ "TrackTemp_Mean": track_temp,
48
+ "Humidity_Mean": self._number(compressed.get("Humidity_Mean")),
49
+ "Pressure_Mean": self._number(compressed.get("Pressure_Mean")),
50
+ "WindDirection_Mean": wind_direction,
51
+ "WindSpeed_Mean": wind_speed,
52
+ "DifferentialDistance_Sum": self._number(
53
+ compressed.get("DifferentialDistance_Sum")
54
+ ),
55
+ "Distance": self._number(compressed.get("Distance_Last")),
56
+ "RelativeDistance": self._number(compressed.get("RelativeDistance_Last")),
57
+ "DriverAhead": self._category(compressed.get("DriverAhead_Last")),
58
+ "TrackStatus": self._number(compressed.get("TrackStatus_Last")),
59
+ "Stint": self._number(compressed.get("Stint_Last")),
60
+ "Compound": self._category(compressed.get("Compound_Last")),
61
+ "TyreLife": tyre_life,
62
+ "FreshTyre": self._number(compressed.get("FreshTyre_Last")),
63
+ "SpeedI1": self._number(compressed.get("SpeedI1_Last")),
64
+ "SpeedI2": self._number(compressed.get("SpeedI2_Last")),
65
+ "SpeedFL": self._number(compressed.get("SpeedFL_Last")),
66
+ "SpeedST": self._number(compressed.get("SpeedST_Last")),
67
+ "IsPersonalBest": self._number(compressed.get("IsPersonalBest_Last")),
68
+ "Position": self._number(compressed.get("Position_Last")),
69
+ "Rainfall": self._number(compressed.get("Rainfall_Any")),
70
+ "TyreLifeSquared": tyre_life**2 if tyre_life is not None else None,
71
+ "TrackAirTempDifference": (
72
+ track_temp - air_temp
73
+ if track_temp is not None and air_temp is not None
74
+ else None
75
+ ),
76
+ "WindX": None,
77
+ "WindY": None,
78
+ }
79
+
80
+ if wind_speed is not None and wind_direction is not None:
81
+ radians = math.radians(wind_direction)
82
+ row["WindX"] = wind_speed * math.cos(radians)
83
+ row["WindY"] = wind_speed * math.sin(radians)
84
+
85
+ if row["Driver"] == "UNKNOWN":
86
+ from app.utils.driver_mapping import lookup_driver_by_number
87
+ fallback = lookup_driver_by_number(row.get("DriverNumber"))
88
+ if fallback is not None:
89
+ row["Driver"] = fallback.acronym
90
+ logger.info(
91
+ "[FEATURE] Driver acronym resolved to %s from DriverNumber %s",
92
+ fallback.acronym, row.get("DriverNumber"),
93
+ )
94
+ else:
95
+ row["Driver"] = "UNK"
96
+ logger.warning(
97
+ "[FEATURE WARNING] Driver with number %s could not be identified -> using UNK",
98
+ row.get("DriverNumber"),
99
+ )
100
+
101
+ # Log if driver has missing telemetry fields (common in FP1 out-laps)
102
+ missing_fields = [
103
+ col for col in ("Speed_Mean", "RPM_Mean", "Throttle_Mean", "Brake_Mean", "TyreLife", "Position")
104
+ if row.get(col) is None
105
+ ]
106
+ if missing_fields:
107
+ logger.info(
108
+ "[FEATURE] Driver %s lap %s has missing telemetry: %s (car may be in pit lane or out-lap)",
109
+ row["Driver"],
110
+ row.get("LapNumber"),
111
+ ", ".join(missing_fields),
112
+ )
113
+
114
+ try:
115
+ validate_feature_row(row, self._feature_columns)
116
+ except ValueError as exc:
117
+ raise FeatureEngineeringError(str(exc)) from exc
118
+ return row
119
+
120
+ @staticmethod
121
+ def _number(value: Any) -> float | None:
122
+ if value is None:
123
+ return None
124
+ try:
125
+ number = float(value)
126
+ except (TypeError, ValueError):
127
+ return None
128
+ return number if math.isfinite(number) else None
129
+
130
+ @staticmethod
131
+ def _category(value: Any) -> str:
132
+ if value is None:
133
+ return "UNKNOWN"
134
+ if isinstance(value, float) and not math.isfinite(value):
135
+ return "UNKNOWN"
136
+ text = str(value).strip().upper()
137
+ return text or "UNKNOWN"
138
+
139
+
140
+ def get_feature_engineer() -> LiveFeatureEngineer:
141
+ return LiveFeatureEngineer(get_settings())
142
+
backend/app/services/inference_gateway.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+ from functools import lru_cache
4
+ from typing import Any, Mapping
5
+
6
+ from app.config import Settings, get_settings
7
+ from app.services.feature_contract import load_feature_contract, validate_feature_row
8
+ from app.services.model_service import ModelService, get_model_service
9
+ from app.services.remote_model_client import RemoteModelClient, RemoteModelError
10
+
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ class InferenceGateway:
16
+ """Route inference to local .pkl or a compatible hosted endpoint."""
17
+
18
+ def __init__(
19
+ self,
20
+ settings: Settings,
21
+ local_model: ModelService,
22
+ remote_model: RemoteModelClient,
23
+ ) -> None:
24
+ self._settings = settings
25
+ self._local = local_model
26
+ self._remote = remote_model
27
+ _, self._feature_columns = load_feature_contract(settings.model_schema_path)
28
+
29
+ @property
30
+ def mode(self) -> str:
31
+ return self._settings.model_backend
32
+
33
+ async def startup(self) -> None:
34
+ if self.mode == "remote":
35
+ if not self._remote.configured:
36
+ raise RemoteModelError("Remote mode requires REMOTE_MODEL_URL")
37
+ return
38
+ await asyncio.to_thread(self._local.load)
39
+
40
+ async def predict(self, rows: list[Mapping[str, Any]]) -> list[float]:
41
+ if not rows:
42
+ raise ValueError("At least one model feature row is required")
43
+ for row in rows:
44
+ validate_feature_row(row, self._feature_columns)
45
+
46
+ if self.mode == "remote":
47
+ return await self._remote.predict(rows)
48
+
49
+ if self.mode == "auto" and self._remote.configured:
50
+ try:
51
+ return await self._remote.predict(rows)
52
+ except RemoteModelError:
53
+ logger.exception("Hosted model failed; using local fallback")
54
+
55
+ probabilities = await asyncio.to_thread(self._local.predict, rows)
56
+ return probabilities.tolist()
57
+
58
+
59
+ @lru_cache(maxsize=1)
60
+ def get_inference_gateway() -> InferenceGateway:
61
+ settings = get_settings()
62
+ return InferenceGateway(
63
+ settings=settings,
64
+ local_model=get_model_service(),
65
+ remote_model=RemoteModelClient(settings),
66
+ )
67
+
backend/app/services/live_compressor.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import math
3
+ import time
4
+ from datetime import date, datetime, timezone
5
+ from typing import Any, Iterable, Mapping
6
+
7
+ from app.services.raw_schema import LAST_COLUMNS, MAX_COLUMNS, MEAN_COLUMNS, SUM_COLUMNS
8
+
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ class LapCompressionError(ValueError):
14
+ pass
15
+
16
+
17
+ class LiveLapCompressor:
18
+ """Apply high-performance single-pass aggregations to one completed lap."""
19
+
20
+ def compress(self, samples: Iterable[Mapping[str, Any]]) -> dict[str, Any]:
21
+ start_time = time.perf_counter()
22
+ rows = [dict(sample) for sample in samples]
23
+ if not rows:
24
+ raise LapCompressionError("Cannot compress an empty lap")
25
+
26
+ # Reverse pass for LAST_COLUMNS (breaks early once all columns found)
27
+ remaining_last = set(LAST_COLUMNS)
28
+ last_values: dict[str, Any] = {col: None for col in LAST_COLUMNS}
29
+ driver = None
30
+ lap_number = None
31
+ race_date_val = None
32
+
33
+ for row in reversed(rows):
34
+ if driver is None:
35
+ driver_candidate = row.get("Driver")
36
+ if driver_candidate is not None:
37
+ driver = driver_candidate
38
+ if lap_number is None:
39
+ lap_candidate = row.get("LapNumber")
40
+ if lap_candidate is not None:
41
+ lap_number = lap_candidate
42
+ if race_date_val is None:
43
+ date_candidate = row.get("Date")
44
+ if date_candidate is not None:
45
+ race_date_val = date_candidate
46
+
47
+ if remaining_last:
48
+ found = []
49
+ for col in remaining_last:
50
+ val = row.get(col)
51
+ if val is not None:
52
+ last_values[col] = val
53
+ found.append(col)
54
+ for col in found:
55
+ remaining_last.remove(col)
56
+
57
+ if driver is not None and lap_number is not None and not remaining_last and race_date_val is not None:
58
+ break
59
+
60
+ if driver is None or lap_number is None:
61
+ raise LapCompressionError("Driver and LapNumber are required")
62
+
63
+ result: dict[str, Any] = {
64
+ "_RaceDate": self._format_date(race_date_val),
65
+ "Driver": str(driver).strip().upper(),
66
+ "LapNumber": float(lap_number),
67
+ "TelemetryRecords": len(rows),
68
+ }
69
+
70
+ # Single forward pass for MEAN, SUM, and MAX columns
71
+ mean_sums = {col: 0.0 for col in MEAN_COLUMNS}
72
+ mean_counts = {col: 0 for col in MEAN_COLUMNS}
73
+
74
+ sum_totals = {col: 0.0 for col in SUM_COLUMNS}
75
+ sum_has_val = {col: False for col in SUM_COLUMNS}
76
+
77
+ max_values = {col: -float("inf") for col in MAX_COLUMNS}
78
+ max_has_val = {col: False for col in MAX_COLUMNS}
79
+
80
+ for row in rows:
81
+ # Mean columns
82
+ for col in MEAN_COLUMNS:
83
+ val = row.get(col)
84
+ if val is not None:
85
+ try:
86
+ num = float(val)
87
+ if math.isfinite(num):
88
+ mean_sums[col] += num
89
+ mean_counts[col] += 1
90
+ except (TypeError, ValueError):
91
+ pass
92
+
93
+ # Sum columns
94
+ for col in SUM_COLUMNS:
95
+ val = row.get(col)
96
+ if val is not None:
97
+ try:
98
+ num = float(val)
99
+ if math.isfinite(num):
100
+ sum_totals[col] += num
101
+ sum_has_val[col] = True
102
+ except (TypeError, ValueError):
103
+ pass
104
+
105
+ # Max columns
106
+ for col in MAX_COLUMNS:
107
+ val = row.get(col)
108
+ if val is not None:
109
+ try:
110
+ num = float(val)
111
+ if math.isfinite(num):
112
+ if num > max_values[col]:
113
+ max_values[col] = num
114
+ max_has_val[col] = True
115
+ except (TypeError, ValueError):
116
+ pass
117
+
118
+ # Populate final values
119
+ for col in MEAN_COLUMNS:
120
+ count = mean_counts[col]
121
+ result[f"{col}_Mean"] = float(mean_sums[col] / count) if count > 0 else None
122
+
123
+ for col in SUM_COLUMNS:
124
+ result[f"{col}_Sum"] = float(sum_totals[col]) if sum_has_val[col] else None
125
+
126
+ for col in LAST_COLUMNS:
127
+ result[f"{col}_Last"] = last_values[col]
128
+
129
+ for col in MAX_COLUMNS:
130
+ result[f"{col}_Any"] = float(max_values[col]) if max_has_val[col] else None
131
+
132
+ elapsed = time.perf_counter() - start_time
133
+ if elapsed > 0.5:
134
+ logger.warning(
135
+ "[PERF LATENCY WARNING] LiveLapCompressor took %.3fs (> 0.5s threshold) for driver %s lap %s (%d samples)",
136
+ elapsed, result["Driver"], result["LapNumber"], len(rows),
137
+ )
138
+
139
+ return result
140
+
141
+ @staticmethod
142
+ def _format_date(value: Any) -> str:
143
+ if isinstance(value, datetime):
144
+ return value.date().isoformat()
145
+ if isinstance(value, date):
146
+ return value.isoformat()
147
+ if isinstance(value, str) and len(value) >= 10:
148
+ return value[:10]
149
+ return datetime.now(timezone.utc).date().isoformat()
backend/app/services/live_pipeline.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+ from collections import Counter
4
+ from datetime import datetime, timezone
5
+ from typing import Any, Mapping
6
+
7
+ from app.services.driver_registry import DriverRegistry
8
+ from app.services.live_state import LiveRaceState
9
+ from app.services.prediction_service import PredictionService
10
+ from app.services.raw_normalizer import RawNormalizer
11
+ from app.utils.logger import (
12
+ log_driver_status,
13
+ log_ingest_event,
14
+ log_lap_completed,
15
+ log_stream_event,
16
+ )
17
+
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+ SHARED_TOPICS = {"WeatherData", "TrackStatus", "SessionStatus", "SessionInfo"}
22
+ TIMING_TOPICS = {"TimingData", "TimingDataF1", "TimingStats", "LapSeries"}
23
+
24
+
25
+ class LivePipeline:
26
+ def __init__(
27
+ self,
28
+ normalizer: RawNormalizer,
29
+ registry: DriverRegistry,
30
+ state: LiveRaceState,
31
+ predictions: PredictionService,
32
+ ) -> None:
33
+ self._normalizer = normalizer
34
+ self._registry = registry
35
+ self._state = state
36
+ self._predictions = predictions
37
+ self._completed_laps: dict[str, int] = {}
38
+ self._counts: Counter[str] = Counter()
39
+ self._lock = asyncio.Lock()
40
+ self._ingest_lock = asyncio.Lock()
41
+ self._finish_task: asyncio.Task | None = None
42
+ self._session_status = "waiting"
43
+ self._current_lap: int | None = None
44
+ self._total_laps: int | None = None
45
+ self._started_at: str | None = None
46
+ self._finished_at: str | None = None
47
+ self._first_batch_received: bool = False
48
+ self._total_records_processed: int = 0
49
+
50
+ async def handle_records(self, records: Mapping[str, list[Any]]) -> None:
51
+ async with self._ingest_lock:
52
+ await self._handle_records(records)
53
+
54
+ async def _handle_records(self, records: Mapping[str, list[Any]]) -> None:
55
+ for topic, topic_records in records.items():
56
+ if not topic_records:
57
+ continue
58
+
59
+ count = len(topic_records)
60
+ prev_total = self._total_records_processed
61
+ self._total_records_processed += count
62
+
63
+ if not self._first_batch_received:
64
+ self._first_batch_received = True
65
+ log_stream_event(
66
+ f"FIRST BATCH RECEIVED from LiveF1! Topic: '{topic}' | Count: {count} record(s). Live race data is flowing!"
67
+ )
68
+ elif (prev_total // 50) < (self._total_records_processed // 50):
69
+ log_stream_event(
70
+ f"Steady live stream progress: {self._total_records_processed} total records received across topics (Latest: '{topic}' with {count} records)"
71
+ )
72
+
73
+ for record in topic_records:
74
+ if not isinstance(record, Mapping):
75
+ self._counts["ignored_non_mapping"] += 1
76
+ continue
77
+ try:
78
+ await self._handle_record(topic, record)
79
+ self._counts[f"topic:{topic}"] += 1
80
+ except Exception:
81
+ self._counts["record_errors"] += 1
82
+ logger.exception("Failed to process LiveF1 topic %s", topic)
83
+
84
+ async def _handle_record(self, topic: str, record: Mapping[str, Any]) -> None:
85
+ if self._session_status == "finished":
86
+ self._counts["ignored_after_finish"] += 1
87
+ return
88
+
89
+ if topic == "DriverList":
90
+ self._registry.update(record)
91
+
92
+ event = self._normalizer.normalize(topic, record)
93
+ fields = event.fields
94
+ if not fields:
95
+ return
96
+
97
+ if topic in {"LapCount", "SessionStatus"}:
98
+ await self._update_lifecycle(fields)
99
+ if self._session_status == "finished":
100
+ return
101
+
102
+ if topic in SHARED_TOPICS and "DriverNumber" not in fields:
103
+ await self._state.update_shared(fields)
104
+ return
105
+
106
+ driver_number = fields.get("DriverNumber")
107
+ identity = self._registry.resolve(driver_number)
108
+ if identity is not None:
109
+ fields["Driver"] = identity.acronym
110
+ fields.setdefault("Team", identity.team)
111
+ elif "Driver" not in fields and driver_number is not None:
112
+ fields["Driver"] = f"UNKNOWN_{int(float(driver_number))}"
113
+
114
+ state_key = str(int(float(driver_number))) if driver_number is not None else fields.get("Driver")
115
+ if state_key is None:
116
+ await self._state.update_shared(fields)
117
+ return
118
+
119
+
120
+ if topic != "DriverList":
121
+ await self._mark_live()
122
+
123
+ if topic in TIMING_TOPICS and fields.get("LapNumber") is not None:
124
+ await self._handle_timing_lap(str(state_key), fields)
125
+ return
126
+
127
+ # Check if driver is stopped or entering pits
128
+ if fields.get("PitInTime") is not None:
129
+ log_driver_status(str(fields.get("Driver") or state_key), "entered pit lane")
130
+ elif fields.get("Speed") == 0 and fields.get("Position") is not None:
131
+ log_driver_status(str(fields.get("Driver") or state_key), "car stopped")
132
+
133
+ await self._state.ingest(fields, state_key=str(state_key))
134
+
135
+ async def _handle_timing_lap(self, state_key: str, fields: dict[str, Any]) -> None:
136
+ completed_laps = max(0, int(float(fields["LapNumber"])))
137
+ previous = self._completed_laps.get(state_key)
138
+
139
+ if previous is None:
140
+ self._completed_laps[state_key] = completed_laps
141
+ await self._state.set_active_lap(state_key, completed_laps + 1)
142
+ current_fields = dict(fields)
143
+ current_fields["LapNumber"] = completed_laps + 1
144
+ await self._state.ingest(current_fields, state_key=state_key)
145
+ await self._record_lap_progress(completed_laps)
146
+ await self._state.set_active_lap(
147
+ state_key,
148
+ self._driver_current_lap(completed_laps),
149
+ )
150
+ return
151
+
152
+ if completed_laps < previous:
153
+ self._counts["ignored_old_timing"] += 1
154
+ return
155
+ if completed_laps == previous:
156
+ current_fields = dict(fields)
157
+ current_fields["LapNumber"] = previous + 1
158
+ await self._state.ingest(current_fields, state_key=state_key)
159
+ return
160
+ if completed_laps > previous + 1:
161
+ # Reconnect snapshots cannot reconstruct the laps missed offline.
162
+ self._counts["laps_skipped_after_gap"] += completed_laps - previous
163
+ await self._state.discard_laps(state_key)
164
+ self._completed_laps[state_key] = completed_laps
165
+ current_fields = dict(fields)
166
+ current_fields["LapNumber"] = completed_laps + 1
167
+ await self._state.ingest(current_fields, state_key=state_key)
168
+ await self._record_lap_progress(completed_laps)
169
+ return
170
+
171
+ final_fields = dict(fields)
172
+ final_fields["LapNumber"] = completed_laps
173
+ await self._state.ingest(final_fields, state_key=state_key)
174
+
175
+ for lap_number in range(previous + 1, completed_laps + 1):
176
+ completed = await self._state.complete_lap(state_key, lap_number)
177
+ if completed is not None:
178
+ log_lap_completed(completed.driver, lap_number)
179
+ prediction = await self._predictions.process_completed_lap(completed)
180
+ if prediction is not None:
181
+ self._counts["predictions"] += 1
182
+ else:
183
+ self._counts["predictions_skipped"] += 1
184
+
185
+ self._completed_laps[state_key] = completed_laps
186
+ await self._record_lap_progress(completed_laps)
187
+ await self._state.set_active_lap(
188
+ state_key,
189
+ self._driver_current_lap(completed_laps),
190
+ )
191
+
192
+ def _driver_current_lap(self, completed_laps: int) -> int:
193
+ current = completed_laps + 1
194
+ return min(current, self._total_laps) if self._total_laps else current
195
+
196
+ async def _update_lifecycle(self, fields: Mapping[str, Any]) -> None:
197
+ total_laps = self._positive_int(fields.get("TotalLaps"))
198
+ current_lap = self._positive_int(fields.get("CurrentLap"))
199
+ status = str(fields.get("SessionStatus") or "").strip().casefold()
200
+
201
+ # Fast return if no lifecycle fields exist in this record
202
+ if total_laps is None and current_lap is None and not status:
203
+ return
204
+
205
+ async with self._lock:
206
+ if total_laps is not None:
207
+ self._total_laps = total_laps
208
+ if current_lap is not None:
209
+ self._current_lap = max(self._current_lap or 0, current_lap)
210
+
211
+ if status in {"started", "live", "active", "green"}:
212
+ await self._mark_live()
213
+ if status in {"finalised", "finalized", "ended", "complete", "completed"}:
214
+ await self._finish()
215
+ return
216
+ if status == "finished" and self._finish_task is None:
217
+ # The flag can precede trailing cars and their final timing messages.
218
+ self._finish_task = asyncio.create_task(self._finish_after_grace())
219
+ await self._refresh_final_lap_state()
220
+
221
+ async def _finish_after_grace(self) -> None:
222
+ await asyncio.sleep(120)
223
+ async with self._ingest_lock:
224
+ await self._finish()
225
+
226
+ async def _mark_live(self) -> None:
227
+ async with self._lock:
228
+ if self._session_status == "waiting":
229
+ self._session_status = "live"
230
+ self._started_at = datetime.now(timezone.utc).isoformat()
231
+
232
+ async def _record_lap_progress(self, completed_laps: int) -> None:
233
+ async with self._lock:
234
+ next_lap = completed_laps + 1
235
+ if self._total_laps is not None:
236
+ next_lap = min(next_lap, self._total_laps)
237
+ self._current_lap = max(self._current_lap or 0, next_lap)
238
+ await self._refresh_final_lap_state()
239
+
240
+ async def _refresh_final_lap_state(self) -> None:
241
+ async with self._lock:
242
+ if (
243
+ self._session_status in {"live", "final_lap"}
244
+ and self._current_lap is not None
245
+ and self._total_laps is not None
246
+ and self._current_lap >= self._total_laps
247
+ ):
248
+ self._session_status = "final_lap"
249
+
250
+ async def _finish(self) -> None:
251
+ if self._finish_task is not None and self._finish_task is not asyncio.current_task():
252
+ self._finish_task.cancel()
253
+ self._finish_task = None
254
+ async with self._lock:
255
+ if self._session_status == "finished":
256
+ return
257
+ now = datetime.now(timezone.utc).isoformat()
258
+ if self._started_at is None:
259
+ self._started_at = now
260
+ self._session_status = "finished"
261
+ self._finished_at = now
262
+ if self._total_laps is not None:
263
+ self._current_lap = self._total_laps
264
+ await self._predictions.freeze()
265
+
266
+ @staticmethod
267
+ def _positive_int(value: Any) -> int | None:
268
+ try:
269
+ result = int(float(value))
270
+ except (TypeError, ValueError):
271
+ return None
272
+ return result if result > 0 else None
273
+
274
+ def status(self) -> dict[str, Any]:
275
+ return {
276
+ "drivers_registered": len(self._registry.snapshot()),
277
+ "drivers_with_timing": len(self._completed_laps),
278
+ "counters": dict(self._counts),
279
+ **self.lifecycle(),
280
+ }
281
+
282
+ def lifecycle(self) -> dict[str, Any]:
283
+ laps_remaining = None
284
+ if self._current_lap is not None and self._total_laps is not None:
285
+ laps_remaining = max(0, self._total_laps - self._current_lap)
286
+ return {
287
+ "session_status": self._session_status,
288
+ "current_lap": self._current_lap,
289
+ "total_laps": self._total_laps,
290
+ "laps_remaining": laps_remaining,
291
+ "started_at": self._started_at,
292
+ "finished_at": self._finished_at,
293
+ }
294
+
295
+ async def frontend_state(self) -> dict[str, Any]:
296
+ return await self._state.snapshot()
297
+
298
+ async def reset(self) -> None:
299
+ async with self._ingest_lock:
300
+ await self._reset()
301
+
302
+ async def shutdown(self) -> None:
303
+ if self._finish_task is not None:
304
+ self._finish_task.cancel()
305
+ try:
306
+ await self._finish_task
307
+ except asyncio.CancelledError:
308
+ pass
309
+ self._finish_task = None
310
+
311
+ async def _reset(self) -> None:
312
+ if self._finish_task is not None:
313
+ self._finish_task.cancel()
314
+ self._finish_task = None
315
+ async with self._lock:
316
+ self._completed_laps.clear()
317
+ self._counts.clear()
318
+ self._session_status = "waiting"
319
+ self._current_lap = None
320
+ self._total_laps = None
321
+ self._started_at = None
322
+ self._finished_at = None
323
+ self._first_batch_received = False
324
+ self._total_records_processed = 0
325
+ await self._state.reset()
326
+ await self._predictions.reset()
backend/app/services/live_state.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+ import time
4
+ from collections import defaultdict, deque
5
+ from dataclasses import dataclass
6
+ from datetime import datetime, timezone
7
+ from typing import Any, Mapping
8
+
9
+ from app.services.raw_schema import MEAN_COLUMNS, SUM_COLUMNS
10
+
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ @dataclass(frozen=True, slots=True)
16
+ class CompletedLap:
17
+ driver: str
18
+ driver_number: int | None
19
+ lap_number: int
20
+ samples: tuple[dict[str, Any], ...]
21
+ completed_at: datetime
22
+
23
+
24
+ class LiveRaceState:
25
+ """Concurrent in-memory lap buffers for all active drivers."""
26
+
27
+ def __init__(
28
+ self,
29
+ max_samples_per_lap: int = 5_000,
30
+ stale_after_seconds: float = 10.0,
31
+ ) -> None:
32
+ self._lock = asyncio.Lock()
33
+ self._max_samples = max_samples_per_lap
34
+ self._stale_after_seconds = stale_after_seconds
35
+ self._active_laps: dict[str, int] = {}
36
+ self._driver_latest: dict[str, dict[str, Any]] = defaultdict(dict)
37
+ self._shared_latest: dict[str, Any] = {}
38
+ self._lap_samples: dict[tuple[str, int], deque[dict[str, Any]]] = defaultdict(
39
+ lambda: deque(maxlen=self._max_samples)
40
+ )
41
+
42
+ async def update_shared(self, fields: Mapping[str, Any]) -> None:
43
+ async with self._lock:
44
+ self._merge_non_null(self._shared_latest, fields)
45
+ self._shared_latest["_last_updated"] = (
46
+ datetime.now(timezone.utc).isoformat()
47
+ )
48
+
49
+ async def set_active_lap(self, driver: str, lap_number: int) -> None:
50
+ if lap_number < 1:
51
+ raise ValueError("lap_number must be at least 1")
52
+ async with self._lock:
53
+ self._active_laps[self._driver_key(driver)] = lap_number
54
+
55
+ async def ingest(
56
+ self,
57
+ fields: Mapping[str, Any],
58
+ state_key: str | None = None,
59
+ ) -> bool:
60
+ driver_value = state_key or fields.get("Driver") or fields.get("DriverNumber")
61
+ if driver_value is None:
62
+ await self.update_shared(fields)
63
+ return False
64
+
65
+ driver = self._driver_key(driver_value)
66
+ async with self._lock:
67
+ latest = self._driver_latest[driver]
68
+ self._merge_non_null(latest, fields)
69
+ latest["_last_updated"] = datetime.now(timezone.utc).isoformat()
70
+ if any(fields.get(key) is not None for key in ("Speed", "RPM", "Throttle")):
71
+ latest["_last_telemetry"] = latest["_last_updated"]
72
+
73
+ explicit_lap = self._as_positive_int(fields.get("LapNumber"))
74
+ lap_number = explicit_lap or self._active_laps.get(driver)
75
+ if lap_number is None:
76
+ return False
77
+
78
+ self._active_laps[driver] = lap_number
79
+ sample = dict(self._shared_latest)
80
+ sample.update(latest)
81
+ # Timing/position updates must not re-count the last car sample.
82
+ # Shared weather remains available, but per-driver measurements are
83
+ # aggregated only when actually present in the incoming record.
84
+ for column in MEAN_COLUMNS + SUM_COLUMNS:
85
+ if column not in self._shared_latest and column not in fields:
86
+ sample.pop(column, None)
87
+ sample["LapNumber"] = lap_number
88
+ sample.setdefault("Driver", str(fields.get("Driver") or driver).upper())
89
+
90
+ buffer = self._lap_samples[(driver, lap_number)]
91
+ buffer.append(sample)
92
+ return True
93
+
94
+ async def complete_lap(self, driver: str, lap_number: int) -> CompletedLap | None:
95
+ start_time = time.perf_counter()
96
+ key = self._driver_key(driver)
97
+ async with self._lock:
98
+ samples = self._lap_samples.pop((key, lap_number), None)
99
+ self._active_laps[key] = lap_number + 1
100
+ if not samples:
101
+ return None
102
+
103
+ driver_number = self._as_positive_int(
104
+ self._driver_latest.get(key, {}).get("DriverNumber")
105
+ )
106
+ lap = CompletedLap(
107
+ driver=key,
108
+ driver_number=driver_number,
109
+ lap_number=lap_number,
110
+ samples=tuple(samples),
111
+ completed_at=datetime.now(timezone.utc),
112
+ )
113
+
114
+ elapsed = time.perf_counter() - start_time
115
+ if elapsed > 0.5:
116
+ logger.warning(
117
+ "[PERF LATENCY WARNING] LiveRaceState.complete_lap took %.3fs (> 0.5s threshold) for driver %s lap %s (%d samples)",
118
+ elapsed, key, lap_number, len(samples),
119
+ )
120
+
121
+ return lap
122
+
123
+ async def discard_laps(self, driver: str) -> None:
124
+ async with self._lock:
125
+ key = self._driver_key(driver)
126
+ for buffer_key in list(self._lap_samples):
127
+ if buffer_key[0] == key:
128
+ del self._lap_samples[buffer_key]
129
+
130
+ async def snapshot(self) -> dict[str, Any]:
131
+ """Return only the stable, provider-independent frontend contract."""
132
+ async with self._lock:
133
+ now = datetime.now(timezone.utc)
134
+ shared_last_updated = self._shared_latest.get("_last_updated")
135
+ shared_age = self._age_seconds(shared_last_updated, now)
136
+ shared = {
137
+ "session_time": self._json_scalar(
138
+ self._shared_latest.get("SessionTime")
139
+ ),
140
+ "track_status": self._json_scalar(
141
+ self._shared_latest.get("TrackStatus")
142
+ ),
143
+ "air_temperature": self._json_scalar(
144
+ self._shared_latest.get("AirTemp")
145
+ ),
146
+ "track_temperature": self._json_scalar(
147
+ self._shared_latest.get("TrackTemp")
148
+ ),
149
+ "humidity": self._json_scalar(
150
+ self._shared_latest.get("Humidity")
151
+ ),
152
+ "pressure": self._json_scalar(
153
+ self._shared_latest.get("Pressure")
154
+ ),
155
+ "wind_direction": self._json_scalar(
156
+ self._shared_latest.get("WindDirection")
157
+ ),
158
+ "wind_speed": self._json_scalar(
159
+ self._shared_latest.get("WindSpeed")
160
+ ),
161
+ "rainfall": self._json_scalar(
162
+ self._shared_latest.get("Rainfall")
163
+ ),
164
+ "last_updated": shared_last_updated,
165
+ "data_age_seconds": shared_age,
166
+ "is_stale": (
167
+ shared_age is None
168
+ or shared_age > self._stale_after_seconds
169
+ ),
170
+ }
171
+ drivers: list[dict[str, Any]] = []
172
+ for state_key, latest in self._driver_latest.items():
173
+ last_updated = latest.get("_last_telemetry") or latest.get("_last_updated")
174
+ age = self._age_seconds(last_updated, now)
175
+ row = {
176
+ "driver": latest.get("Driver") or state_key,
177
+ "driver_number": self._as_positive_int(
178
+ latest.get("DriverNumber")
179
+ ),
180
+ "team": latest.get("Team"),
181
+ "position": self._as_positive_int(latest.get("Position")),
182
+ "current_lap": self._active_laps.get(state_key),
183
+ "speed": latest.get("Speed"),
184
+ "rpm": latest.get("RPM"),
185
+ "gear": latest.get("nGear"),
186
+ "throttle": latest.get("Throttle"),
187
+ "brake": latest.get("Brake"),
188
+ "drs": latest.get("DRS"),
189
+ "compound": latest.get("Compound"),
190
+ "tyre_life": latest.get("TyreLife"),
191
+ "stint": latest.get("Stint"),
192
+ "driver_ahead": latest.get("DriverAhead"),
193
+ "distance_to_driver_ahead": latest.get(
194
+ "DistanceToDriverAhead"
195
+ ),
196
+ "x": latest.get("X"),
197
+ "y": latest.get("Y"),
198
+ "z": latest.get("Z"),
199
+ "last_updated": last_updated,
200
+ "data_age_seconds": age,
201
+ "is_stale": (
202
+ age is None or age > self._stale_after_seconds
203
+ ),
204
+ }
205
+ drivers.append(row)
206
+
207
+ drivers.sort(
208
+ key=lambda row: self._position_sort_key(row.get("position"))
209
+ )
210
+ return {
211
+ "shared": shared,
212
+ "drivers": drivers,
213
+ "driver_count": len(drivers),
214
+ }
215
+
216
+ @staticmethod
217
+ def _json_scalar(value: Any) -> Any:
218
+ if value is None or isinstance(value, (str, int, float, bool)):
219
+ return value
220
+ return str(value)
221
+
222
+ @staticmethod
223
+ def _age_seconds(value: Any, now: datetime) -> float | None:
224
+ if not isinstance(value, str):
225
+ return None
226
+ try:
227
+ updated = datetime.fromisoformat(value.replace("Z", "+00:00"))
228
+ if updated.tzinfo is None:
229
+ updated = updated.replace(tzinfo=timezone.utc)
230
+ except ValueError:
231
+ return None
232
+ return round(max(0.0, (now - updated).total_seconds()), 3)
233
+
234
+ async def reset(self) -> None:
235
+ async with self._lock:
236
+ self._active_laps.clear()
237
+ self._driver_latest.clear()
238
+ self._shared_latest.clear()
239
+ self._lap_samples.clear()
240
+
241
+ @staticmethod
242
+ def _merge_non_null(target: dict[str, Any], source: Mapping[str, Any]) -> None:
243
+ target.update({key: value for key, value in source.items() if value is not None})
244
+
245
+ @staticmethod
246
+ def _driver_key(value: Any) -> str:
247
+ key = str(value).strip().upper()
248
+ if not key:
249
+ raise ValueError("driver cannot be empty")
250
+ return key
251
+
252
+ @staticmethod
253
+ def _as_positive_int(value: Any) -> int | None:
254
+ try:
255
+ result = int(float(value))
256
+ except (TypeError, ValueError):
257
+ return None
258
+ return result if result > 0 else None
259
+
260
+ @staticmethod
261
+ def _position_sort_key(value: Any) -> float:
262
+ try:
263
+ return float(value)
264
+ except (TypeError, ValueError):
265
+ return float("inf")
backend/app/services/model_service.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from functools import lru_cache
3
+ from pathlib import Path
4
+ from threading import RLock
5
+ from typing import Any, Iterable, Mapping
6
+
7
+ import joblib
8
+ import numpy as np
9
+ import pandas as pd
10
+
11
+ from app.config import Settings, get_settings
12
+ from app.services.feature_contract import (
13
+ FeatureContractError,
14
+ load_feature_contract,
15
+ validate_feature_row,
16
+ )
17
+
18
+
19
+ REQUIRED_BUNDLE_KEYS = {
20
+ "model",
21
+ "preprocessor",
22
+ "feature_columns",
23
+ "numeric_features",
24
+ "categorical_features",
25
+ }
26
+
27
+
28
+ class ModelLoadError(RuntimeError):
29
+ """Raised when the saved model bundle is missing or incompatible."""
30
+
31
+
32
+ class ModelInputError(ValueError):
33
+ """Raised when an inference row cannot be converted safely."""
34
+
35
+
36
+ @dataclass(frozen=True, slots=True)
37
+ class ModelMetadata:
38
+ feature_count: int
39
+ pipeline_version: str | None
40
+ target: str | None
41
+
42
+
43
+ class ModelService:
44
+ """Loads and serves the saved preprocessing + XGBoost bundle."""
45
+
46
+ def __init__(self, settings: Settings) -> None:
47
+ self._settings = settings
48
+ self._lock = RLock()
49
+ self._loaded = False
50
+ self._model: Any = None
51
+ self._preprocessor: Any = None
52
+ self._feature_columns: list[str] = []
53
+ self._numeric_features: list[str] = []
54
+ self._categorical_features: list[str] = []
55
+ self._schema: dict[str, Any] = {}
56
+
57
+ @property
58
+ def loaded(self) -> bool:
59
+ return self._loaded
60
+
61
+ @property
62
+ def metadata(self) -> ModelMetadata:
63
+ if not self._loaded:
64
+ raise ModelLoadError("Model has not been loaded")
65
+ return ModelMetadata(
66
+ feature_count=len(self._feature_columns),
67
+ pipeline_version=self._schema.get("pipeline_version"),
68
+ target=self._schema.get("target"),
69
+ )
70
+
71
+ def load(self) -> None:
72
+ """Load once and fail if the bundle/schema contract does not match."""
73
+
74
+ with self._lock:
75
+ if self._loaded:
76
+ return
77
+
78
+ model_path = self._settings.model_path
79
+ schema_path = self._settings.model_schema_path
80
+ self._assert_file(model_path, "model")
81
+ self._assert_file(schema_path, "model schema")
82
+
83
+ try:
84
+ schema, saved_features = load_feature_contract(schema_path)
85
+ bundle = joblib.load(model_path)
86
+ except Exception as exc:
87
+ raise ModelLoadError(f"Unable to load model artifacts: {exc}") from exc
88
+
89
+ if not isinstance(bundle, dict):
90
+ raise ModelLoadError("Model bundle must be a dictionary")
91
+
92
+ missing_keys = REQUIRED_BUNDLE_KEYS.difference(bundle)
93
+ if missing_keys:
94
+ raise ModelLoadError(
95
+ f"Model bundle is missing keys: {sorted(missing_keys)}"
96
+ )
97
+
98
+ bundle_features = list(bundle["feature_columns"])
99
+ schema_features = list(saved_features)
100
+ if bundle_features != schema_features:
101
+ raise ModelLoadError(
102
+ "Feature order mismatch between .pkl bundle and schema JSON"
103
+ )
104
+
105
+ numeric_features = list(bundle["numeric_features"])
106
+ categorical_features = list(bundle["categorical_features"])
107
+ typed_features = numeric_features + categorical_features
108
+ if set(typed_features) != set(bundle_features):
109
+ raise ModelLoadError(
110
+ "Numeric/categorical feature lists do not cover model features"
111
+ )
112
+
113
+ preprocessor_features = list(
114
+ getattr(bundle["preprocessor"], "feature_names_in_", [])
115
+ )
116
+ if preprocessor_features != schema_features:
117
+ raise ModelLoadError(
118
+ "Saved preprocessor feature order differs from schema JSON"
119
+ )
120
+
121
+ model = bundle["model"]
122
+ preprocessor = bundle["preprocessor"]
123
+ if not callable(getattr(model, "predict_proba", None)):
124
+ raise ModelLoadError("Saved model has no predict_proba method")
125
+ if not callable(getattr(preprocessor, "transform", None)):
126
+ raise ModelLoadError("Saved preprocessor has no transform method")
127
+
128
+ self._model = model
129
+ self._preprocessor = preprocessor
130
+ self._feature_columns = bundle_features
131
+ self._numeric_features = numeric_features
132
+ self._categorical_features = categorical_features
133
+ self._schema = schema
134
+ self._loaded = True
135
+
136
+ def predict(self, rows: Iterable[Mapping[str, Any]]) -> np.ndarray:
137
+ """Return the raw positive-class probability for every input row."""
138
+
139
+ if not self._loaded:
140
+ self.load()
141
+
142
+ row_list = [dict(row) for row in rows]
143
+ if not row_list:
144
+ raise ModelInputError("At least one feature row is required")
145
+
146
+ try:
147
+ for row in row_list:
148
+ validate_feature_row(row, self._feature_columns)
149
+ except FeatureContractError as exc:
150
+ raise ModelInputError(str(exc)) from exc
151
+
152
+ frame = self._prepare_frame(row_list)
153
+
154
+ try:
155
+ with self._lock:
156
+ processed = self._preprocessor.transform(frame)
157
+ probabilities = self._model.predict_proba(processed)
158
+ except Exception as exc:
159
+ raise ModelInputError(f"Model inference failed: {exc}") from exc
160
+
161
+ classes = list(getattr(self._model, "classes_", []))
162
+ if 1 not in classes:
163
+ raise ModelLoadError("Saved classifier does not contain positive class 1")
164
+
165
+ positive_index = classes.index(1)
166
+ result = np.asarray(probabilities[:, positive_index], dtype=float)
167
+ if result.shape != (len(row_list),) or not np.isfinite(result).all():
168
+ raise ModelInputError("Model returned invalid probabilities")
169
+ return result
170
+
171
+ def _prepare_frame(self, rows: list[dict[str, Any]]) -> pd.DataFrame:
172
+ frame = pd.DataFrame(rows)
173
+
174
+ unknown = sorted(set(frame.columns).difference(self._feature_columns))
175
+ if unknown:
176
+ raise ModelInputError(f"Unexpected model features: {unknown}")
177
+
178
+ if "Driver" not in frame.columns or frame["Driver"].isna().any():
179
+ raise ModelInputError("Every row must contain Driver")
180
+
181
+ frame = frame[self._feature_columns].copy()
182
+
183
+ for column in self._numeric_features:
184
+ frame[column] = pd.to_numeric(frame[column], errors="coerce")
185
+
186
+ for column in self._categorical_features:
187
+ frame[column] = frame[column].map(
188
+ lambda value: np.nan
189
+ if value is None or pd.isna(value)
190
+ else str(value).strip().upper()
191
+ )
192
+
193
+ return frame.replace([np.inf, -np.inf], np.nan)
194
+
195
+ @staticmethod
196
+ def _assert_file(path: Path, label: str) -> None:
197
+ if not path.is_file():
198
+ raise ModelLoadError(f"{label.capitalize()} file not found: {path}")
199
+
200
+
201
+ @lru_cache(maxsize=1)
202
+ def get_model_service() -> ModelService:
203
+ return ModelService(get_settings())
204
+
backend/app/services/prediction_service.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+ import math
4
+ from dataclasses import asdict, dataclass
5
+ from datetime import datetime, timezone
6
+ from typing import Any, Iterable, Mapping
7
+
8
+ from app.services.feature_coverage import evaluate_feature_coverage
9
+ from app.services.feature_engineer import LiveFeatureEngineer
10
+ from app.services.inference_gateway import InferenceGateway
11
+ from app.services.live_compressor import LiveLapCompressor
12
+ from app.services.live_state import CompletedLap
13
+ from app.utils.logger import log_prediction_event
14
+
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ @dataclass(frozen=True, slots=True)
20
+ class LatestPrediction:
21
+ driver: str
22
+ driver_number: int | None
23
+ lap_number: int
24
+ raw_probability: float
25
+ feature_coverage: float
26
+ updated_at: str
27
+ confidence: str = "high"
28
+
29
+
30
+ class PredictionService:
31
+ def __init__(
32
+ self,
33
+ compressor: LiveLapCompressor,
34
+ feature_engineer: LiveFeatureEngineer,
35
+ gateway: InferenceGateway,
36
+ ) -> None:
37
+ self._compressor = compressor
38
+ self._features = feature_engineer
39
+ self._gateway = gateway
40
+ self._lock = asyncio.Lock()
41
+ self._latest: dict[str, LatestPrediction] = {}
42
+ self._frozen_leaderboard: list[dict[str, Any]] | None = None
43
+ self._final_predicted_winner: str | None = None
44
+ self._is_final = False
45
+ self._generation = 0
46
+ self._skipped = 0
47
+ self._errors = 0
48
+ self._last_error: str | None = None
49
+
50
+ async def process_completed_lap(
51
+ self,
52
+ completed: CompletedLap,
53
+ ) -> LatestPrediction | None:
54
+ async with self._lock:
55
+ if self._is_final:
56
+ return None
57
+ generation = self._generation
58
+
59
+ try:
60
+ compressed = self._compressor.compress(completed.samples)
61
+ feature_row = self._features.transform(compressed)
62
+ quality = evaluate_feature_coverage(feature_row)
63
+ if not quality.is_usable:
64
+ self._skipped += 1
65
+ self._last_error = quality.reason
66
+ logger.warning("Prediction skipped for %s: %s", completed.driver, quality.reason)
67
+ return None
68
+ probability = (await self._gateway.predict([feature_row]))[0]
69
+ if not math.isfinite(float(probability)) or not 0 <= probability <= 1:
70
+ raise ValueError("Model returned a probability outside [0, 1]")
71
+ except Exception as exc:
72
+ self._errors += 1
73
+ self._last_error = str(exc)
74
+ logger.warning(
75
+ "Prediction skipped for %s lap %s due to incomplete/malformed data: %s",
76
+ completed.driver,
77
+ completed.lap_number,
78
+ exc,
79
+ )
80
+ return None
81
+
82
+ prediction = LatestPrediction(
83
+ driver=str(feature_row["Driver"]),
84
+ driver_number=completed.driver_number,
85
+ lap_number=completed.lap_number,
86
+ raw_probability=float(probability),
87
+ feature_coverage=quality.coverage,
88
+ confidence=quality.confidence,
89
+ updated_at=datetime.now(timezone.utc).isoformat(),
90
+ )
91
+
92
+ if quality.confidence in ("low", "provisional") or quality.coverage < 0.65:
93
+ from app.services.feature_coverage import CORE_TELEMETRY_FEATURES
94
+ missing_core = [k for k in CORE_TELEMETRY_FEATURES if feature_row.get(k) is None]
95
+ logger.warning(
96
+ "[PREDICTION INCOMPLETE DATA] Running prediction for driver %s (Lap %s) with low feature coverage (%.1f%%, missing core: %s) -> Confidence: %s",
97
+ prediction.driver,
98
+ prediction.lap_number,
99
+ prediction.feature_coverage * 100,
100
+ ", ".join(missing_core) if missing_core else "none",
101
+ prediction.confidence.upper(),
102
+ )
103
+
104
+ log_prediction_event(
105
+ driver=prediction.driver,
106
+ lap_number=prediction.lap_number,
107
+ win_probability=prediction.raw_probability,
108
+ coverage=prediction.feature_coverage,
109
+ confidence=prediction.confidence,
110
+ )
111
+
112
+ async with self._lock:
113
+ if self._is_final or generation != self._generation:
114
+ return None
115
+ previous = self._latest.get(prediction.driver)
116
+ if previous is not None and previous.lap_number > prediction.lap_number:
117
+ return None
118
+ self._latest[prediction.driver] = prediction
119
+ self._last_error = None
120
+
121
+ return prediction
122
+
123
+ async def process_samples(
124
+ self,
125
+ samples: Iterable[Mapping[str, Any]],
126
+ ) -> LatestPrediction:
127
+ rows = tuple(dict(row) for row in samples)
128
+ if not rows:
129
+ raise ValueError("samples cannot be empty")
130
+ if len({(row.get("Driver"), row.get("LapNumber")) for row in rows}) != 1:
131
+ raise ValueError("Samples must belong to exactly one driver and one lap")
132
+ driver = str(rows[-1].get("Driver", "")).strip().upper()
133
+ lap_number = int(float(rows[-1].get("LapNumber", 0)))
134
+ driver_number_value = rows[-1].get("DriverNumber")
135
+ driver_number = int(float(driver_number_value)) if driver_number_value else None
136
+ prediction = await self.process_completed_lap(
137
+ CompletedLap(
138
+ driver=driver,
139
+ driver_number=driver_number,
140
+ lap_number=lap_number,
141
+ samples=rows,
142
+ completed_at=datetime.now(timezone.utc),
143
+ )
144
+ )
145
+ if prediction is None:
146
+ raise ValueError("Final prediction is frozen or sample data was insufficient")
147
+ return prediction
148
+
149
+ async def leaderboard(self) -> list[dict[str, Any]]:
150
+ async with self._lock:
151
+ if self._frozen_leaderboard is not None:
152
+ return [dict(row) for row in self._frozen_leaderboard]
153
+ return self._build_leaderboard()
154
+
155
+ def _build_leaderboard(self) -> list[dict[str, Any]]:
156
+ predictions = sorted(
157
+ self._latest.values(),
158
+ key=lambda item: item.raw_probability,
159
+ reverse=True,
160
+ )
161
+ total = sum(item.raw_probability for item in predictions)
162
+ result: list[dict[str, Any]] = []
163
+
164
+ for rank, item in enumerate(predictions, start=1):
165
+ row = asdict(item)
166
+ row["rank"] = rank
167
+
168
+ # Safeguard: if only 1 driver recorded an incomplete out-lap, avoid falsely showing 100%
169
+ if len(predictions) == 1:
170
+ normalized = min(1.0, item.raw_probability)
171
+ else:
172
+ normalized = item.raw_probability / total if total > 0 else 0.0
173
+
174
+ row["normalized_probability"] = normalized
175
+ result.append(row)
176
+
177
+ return result
178
+
179
+ async def freeze(self) -> None:
180
+ async with self._lock:
181
+ if self._is_final:
182
+ return
183
+ self._frozen_leaderboard = self._build_leaderboard()
184
+ self._final_predicted_winner = (
185
+ self._frozen_leaderboard[0]["driver"]
186
+ if self._frozen_leaderboard
187
+ else None
188
+ )
189
+ self._is_final = True
190
+
191
+ async def final_state(self) -> dict[str, Any]:
192
+ async with self._lock:
193
+ return {
194
+ "is_final": self._is_final,
195
+ "final_predicted_winner": self._final_predicted_winner,
196
+ "skipped_predictions": self._skipped,
197
+ "prediction_errors": self._errors,
198
+ "last_prediction_error": self._last_error,
199
+ }
200
+
201
+ async def reset(self) -> None:
202
+ async with self._lock:
203
+ self._generation += 1
204
+ self._skipped = self._errors = 0
205
+ self._last_error = None
206
+ self._latest.clear()
207
+ self._frozen_leaderboard = None
208
+ self._final_predicted_winner = None
209
+ self._is_final = False
backend/app/services/raw_normalizer.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from datetime import datetime, timezone
3
+ from typing import Any, Mapping
4
+
5
+ import numpy as np
6
+
7
+ from app.services.raw_schema import (
8
+ BOOLEAN_RAW_COLUMNS,
9
+ FIELD_ALIASES,
10
+ NUMERIC_RAW_COLUMNS,
11
+ NORMALIZED_RAW_COLUMNS,
12
+ STRING_RAW_COLUMNS,
13
+ )
14
+
15
+
16
+ _MISSING = object()
17
+
18
+
19
+ @dataclass(frozen=True, slots=True)
20
+ class NormalizedEvent:
21
+ topic: str
22
+ fields: dict[str, Any]
23
+ received_at: datetime
24
+ source_fields: tuple[str, ...]
25
+
26
+
27
+ class RawNormalizer:
28
+ """Map one flattened provider record to canonical FastF1-style fields."""
29
+
30
+ def normalize(self, topic: str, record: Mapping[str, Any]) -> NormalizedEvent:
31
+ flattened = self._flatten(record)
32
+ casefold_lookup = {key.casefold(): key for key in flattened}
33
+ normalized: dict[str, Any] = {}
34
+
35
+ for canonical in NORMALIZED_RAW_COLUMNS:
36
+ if canonical in {"TotalLaps", "CurrentLap"} and topic != "LapCount":
37
+ continue
38
+ aliases = FIELD_ALIASES.get(canonical, (canonical,))
39
+ if topic in {"TyreStintSeries", "CurrentTyres"}:
40
+ aliases += {
41
+ "TyreLife": ("TotalLaps",),
42
+ "FreshTyre": ("New",),
43
+ }.get(canonical, ())
44
+ if topic in {"TimingData", "TimingStats", "TimingDataF1"}:
45
+ aliases += {
46
+ "SpeedI1": ("Speeds_I1_Value",),
47
+ "SpeedI2": ("Speeds_I2_Value",),
48
+ "SpeedFL": ("Speeds_FL_Value",),
49
+ "SpeedST": ("Speeds_ST_Value",),
50
+ "LapTime": ("LastLapTime_Value",),
51
+ "IsPersonalBest": ("LastLapTime_PersonalFastest",),
52
+ }.get(canonical, ())
53
+ if topic == "SessionStatus" and canonical == "SessionStatus":
54
+ aliases = aliases + ("Status",)
55
+ elif topic == "TrackStatus" and canonical == "TrackStatus":
56
+ aliases = aliases + ("Status",)
57
+ value = self._first_present(flattened, casefold_lookup, aliases)
58
+ if value is not _MISSING:
59
+ normalized[canonical] = self._coerce(canonical, value)
60
+
61
+ if topic == "TyreStintSeries" and "PitCount" in flattened:
62
+ pit_count = self._coerce("Stint", flattened["PitCount"])
63
+ if pit_count is not None:
64
+ normalized["Stint"] = pit_count + 1
65
+
66
+ return NormalizedEvent(
67
+ topic=topic,
68
+ fields=normalized,
69
+ received_at=datetime.now(timezone.utc),
70
+ source_fields=tuple(sorted(flattened)),
71
+ )
72
+
73
+ @staticmethod
74
+ def _flatten(record: Mapping[str, Any]) -> dict[str, Any]:
75
+ result: dict[str, Any] = {}
76
+
77
+ def visit(value: Any, prefix: str = "") -> None:
78
+ if not isinstance(value, Mapping):
79
+ if prefix:
80
+ result[prefix] = value
81
+ result.setdefault(prefix.rsplit(".", 1)[-1], value)
82
+ return
83
+ for key, child in value.items():
84
+ visit(child, f"{prefix}.{key}" if prefix else str(key))
85
+
86
+ visit(record)
87
+ return result
88
+
89
+ @staticmethod
90
+ def _first_present(
91
+ flattened: Mapping[str, Any],
92
+ casefold_lookup: Mapping[str, str],
93
+ aliases: tuple[str, ...],
94
+ ) -> Any:
95
+ for alias in aliases:
96
+ if alias in flattened:
97
+ return flattened[alias]
98
+ actual = casefold_lookup.get(alias.casefold())
99
+ if actual is not None:
100
+ return flattened[actual]
101
+ return _MISSING
102
+
103
+ @staticmethod
104
+ def _coerce(column: str, value: Any) -> Any:
105
+ if value is None:
106
+ return None
107
+
108
+ if column in BOOLEAN_RAW_COLUMNS:
109
+ if isinstance(value, bool):
110
+ return int(value)
111
+ text = str(value).strip().casefold()
112
+ if text in {"true", "yes", "1"}:
113
+ return 1
114
+ if text in {"false", "no", "0"}:
115
+ return 0
116
+
117
+ if column in NUMERIC_RAW_COLUMNS:
118
+ try:
119
+ if column in {"LapTime", "Sector1Time", "Sector2Time", "Sector3Time"} and isinstance(value, str) and ":" in value:
120
+ number = 0.0
121
+ for part in value.split(":"):
122
+ number = number * 60 + float(part)
123
+ else:
124
+ number = float(value)
125
+ except (TypeError, ValueError):
126
+ return None
127
+ return number if np.isfinite(number) else None
128
+
129
+ if column in STRING_RAW_COLUMNS:
130
+ text = str(value).strip()
131
+ if not text:
132
+ return None
133
+ return text.upper() if column in {"Driver", "Compound"} else text
134
+
135
+ return value
136
+
backend/app/services/raw_schema.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Canonical raw names consumed by the supplied training compressor."""
2
+
3
+ from types import MappingProxyType
4
+
5
+
6
+ MEAN_COLUMNS: tuple[str, ...] = (
7
+ "RPM", "Speed", "nGear", "Throttle", "Brake", "DRS", "X", "Y", "Z",
8
+ "DistanceToDriverAhead", "AirTemp", "TrackTemp", "Humidity", "Pressure",
9
+ "WindDirection", "WindSpeed",
10
+ )
11
+
12
+ LAST_COLUMNS: tuple[str, ...] = (
13
+ "Date", "SessionTime", "Time", "Distance", "RelativeDistance",
14
+ "DriverAhead", "TrackStatus", "Driver", "DriverNumber", "Team",
15
+ "LapNumber", "Stint", "Compound", "TyreLife", "FreshTyre", "LapTime",
16
+ "Sector1Time", "Sector2Time", "Sector3Time", "Sector1SessionTime",
17
+ "Sector2SessionTime", "Sector3SessionTime", "SpeedI1", "SpeedI2",
18
+ "SpeedFL", "SpeedST", "IsPersonalBest", "Position", "PitInTime",
19
+ "PitOutTime", "LapStartTime", "LapStartDate",
20
+ )
21
+
22
+ SUM_COLUMNS: tuple[str, ...] = ("DifferentialDistance",)
23
+ MAX_COLUMNS: tuple[str, ...] = ("Rainfall",)
24
+
25
+ # The compressor contract contains 50 unique fields. The source artifact that
26
+ # proves the names of all 54 original CSV columns is not stored in this repo, so
27
+ # the four unused names must remain explicitly unknown rather than guessed.
28
+ PIPELINE_RAW_COLUMNS: tuple[str, ...] = tuple(
29
+ dict.fromkeys(MEAN_COLUMNS + LAST_COLUMNS + SUM_COLUMNS + MAX_COLUMNS)
30
+ )
31
+ ORIGINAL_RAW_COLUMN_COUNT = 54
32
+ UNIDENTIFIED_UNUSED_RAW_COLUMN_COUNT = (
33
+ ORIGINAL_RAW_COLUMN_COUNT - len(PIPELINE_RAW_COLUMNS)
34
+ )
35
+
36
+ # Live-only state fields are normalized for lifecycle tracking but are not part
37
+ # of the compressor or model feature contract.
38
+ LIVE_STATE_COLUMNS: tuple[str, ...] = (
39
+ "SessionStatus",
40
+ "CurrentLap",
41
+ "TotalLaps",
42
+ )
43
+ NORMALIZED_RAW_COLUMNS: tuple[str, ...] = PIPELINE_RAW_COLUMNS + LIVE_STATE_COLUMNS
44
+
45
+ NUMERIC_RAW_COLUMNS: frozenset[str] = frozenset(
46
+ MEAN_COLUMNS
47
+ + SUM_COLUMNS
48
+ + MAX_COLUMNS
49
+ + (
50
+ "Distance", "RelativeDistance", "DriverNumber", "LapNumber", "Stint",
51
+ "TyreLife", "LapTime", "Sector1Time", "Sector2Time", "Sector3Time",
52
+ "Sector1SessionTime", "Sector2SessionTime", "Sector3SessionTime",
53
+ "SpeedI1", "SpeedI2", "SpeedFL", "SpeedST", "IsPersonalBest",
54
+ "Position",
55
+ "CurrentLap", "TotalLaps",
56
+ )
57
+ )
58
+
59
+ BOOLEAN_RAW_COLUMNS: frozenset[str] = frozenset(
60
+ {"FreshTyre", "IsPersonalBest", "Rainfall"}
61
+ )
62
+
63
+ STRING_RAW_COLUMNS: frozenset[str] = frozenset(
64
+ {
65
+ "Driver", "DriverAhead", "Team", "Compound", "TrackStatus",
66
+ "SessionStatus",
67
+ }
68
+ )
69
+
70
+ # Add provider-specific aliases here after inspecting real LiveF1 samples.
71
+ FIELD_ALIASES = MappingProxyType(
72
+ {
73
+ "Date": ("Date", "Utc", "UTC", "date", "timestamp"),
74
+ "Driver": ("Driver", "Tla", "NameAcronym", "driver"),
75
+ "DriverNumber": (
76
+ "DriverNumber", "DriverNo", "RacingNumber", "driver_number",
77
+ ),
78
+ "LapNumber": ("LapNumber", "NumberOfLaps", "lap_number"),
79
+ "RPM": ("RPM", "Rpm", "rpm"),
80
+ "Speed": ("Speed", "speed"),
81
+ "nGear": ("nGear", "Gear", "gear", "n_gear"),
82
+ "Throttle": ("Throttle", "throttle"),
83
+ "Brake": ("Brake", "brake"),
84
+ "DRS": ("DRS", "Drs", "drs"),
85
+ "X": ("X", "x"),
86
+ "Y": ("Y", "y"),
87
+ "Z": ("Z", "z"),
88
+ "AirTemp": ("AirTemp", "air_temperature", "air_temp"),
89
+ "TrackTemp": ("TrackTemp", "track_temperature", "track_temp"),
90
+ "Humidity": ("Humidity", "humidity"),
91
+ "Pressure": ("Pressure", "pressure"),
92
+ "WindDirection": ("WindDirection", "wind_direction"),
93
+ "WindSpeed": ("WindSpeed", "wind_speed"),
94
+ "Rainfall": ("Rainfall", "rainfall"),
95
+ "Position": ("Position", "position"),
96
+ "Compound": ("Compound", "compound"),
97
+ "TyreLife": ("TyreLife", "tyre_age"),
98
+ "Stint": ("Stint", "StintNumber", "stint_number"),
99
+ "TrackStatus": ("TrackStatus", "track_status"),
100
+ "SessionStatus": ("SessionStatus", "session_status"),
101
+ "CurrentLap": ("CurrentLap", "current_lap"),
102
+ "TotalLaps": ("TotalLaps", "total_laps"),
103
+ }
104
+ )
105
+
backend/app/services/remote_model_client.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Any, Mapping
3
+
4
+ import httpx
5
+
6
+ from app.config import Settings
7
+
8
+
9
+ class RemoteModelError(RuntimeError):
10
+ pass
11
+
12
+
13
+ class RemoteModelClient:
14
+ """Hosted-model transport; adjust only this file when its API is known."""
15
+
16
+ def __init__(self, settings: Settings) -> None:
17
+ self._url = settings.remote_model_url
18
+ self._token = settings.remote_model_api_token
19
+ self._timeout = settings.remote_model_timeout_seconds
20
+
21
+ @property
22
+ def configured(self) -> bool:
23
+ return bool(self._url)
24
+
25
+ async def predict(self, rows: list[Mapping[str, Any]]) -> list[float]:
26
+ if not self._url:
27
+ raise RemoteModelError("REMOTE_MODEL_URL is not configured")
28
+
29
+ headers = {"Accept": "application/json"}
30
+ if self._token:
31
+ headers["Authorization"] = f"Bearer {self._token}"
32
+
33
+ payload = {"rows": [self._json_safe(dict(row)) for row in rows]}
34
+ try:
35
+ async with httpx.AsyncClient(timeout=self._timeout) as client:
36
+ response = await client.post(self._url, json=payload, headers=headers)
37
+ response.raise_for_status()
38
+ body = response.json()
39
+ except (httpx.HTTPError, ValueError) as exc:
40
+ raise RemoteModelError(f"Hosted model request failed: {exc}") from exc
41
+
42
+ probabilities = body.get("probabilities") if isinstance(body, dict) else None
43
+ if not isinstance(probabilities, list) or len(probabilities) != len(rows):
44
+ raise RemoteModelError(
45
+ "Hosted model must return {'probabilities': [..]} in input order"
46
+ )
47
+
48
+ try:
49
+ result = [float(value) for value in probabilities]
50
+ except (TypeError, ValueError) as exc:
51
+ raise RemoteModelError("Hosted model returned non-numeric probabilities") from exc
52
+
53
+ if any(not math.isfinite(value) or not 0.0 <= value <= 1.0 for value in result):
54
+ raise RemoteModelError("Hosted probabilities must be finite and between 0 and 1")
55
+ return result
56
+
57
+ @staticmethod
58
+ def _json_safe(row: dict[str, Any]) -> dict[str, Any]:
59
+ safe: dict[str, Any] = {}
60
+ for key, value in row.items():
61
+ if value is None:
62
+ safe[key] = None
63
+ continue
64
+ try:
65
+ value = value.item()
66
+ except AttributeError:
67
+ pass
68
+ safe[key] = value if not isinstance(value, float) or math.isfinite(value) else None
69
+ return safe
backend/app/utils/driver_mapping.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """F1 driver fallback registry mapping numbers to acronyms, names, and teams."""
2
+
3
+ from typing import Any, NamedTuple
4
+
5
+
6
+ class DriverMeta(NamedTuple):
7
+ number: int
8
+ acronym: str
9
+ name: str
10
+ team: str
11
+
12
+
13
+ # 2024-2026 grid numbers and recent reserve drivers
14
+ DRIVER_GRID: dict[int, DriverMeta] = {
15
+ 1: DriverMeta(1, "VER", "Max Verstappen", "Red Bull Racing"),
16
+ 11: DriverMeta(11, "PER", "Sergio Perez", "Red Bull Racing"),
17
+ 4: DriverMeta(4, "NOR", "Lando Norris", "McLaren"),
18
+ 81: DriverMeta(81, "PIA", "Oscar Piastri", "McLaren"),
19
+ 16: DriverMeta(16, "LEC", "Charles Leclerc", "Ferrari"),
20
+ 55: DriverMeta(55, "SAI", "Carlos Sainz", "Ferrari"),
21
+ 44: DriverMeta(44, "HAM", "Lewis Hamilton", "Mercedes"),
22
+ 63: DriverMeta(63, "RUS", "George Russell", "Mercedes"),
23
+ 14: DriverMeta(14, "ALO", "Fernando Alonso", "Aston Martin"),
24
+ 18: DriverMeta(18, "STR", "Lance Stroll", "Aston Martin"),
25
+ 10: DriverMeta(10, "GAS", "Pierre Gasly", "Alpine"),
26
+ 31: DriverMeta(31, "OCO", "Esteban Ocon", "Alpine"),
27
+ 23: DriverMeta(23, "ALB", "Alexander Albon", "Williams"),
28
+ 2: DriverMeta(2, "SAR", "Logan Sargeant", "Williams"),
29
+ 43: DriverMeta(43, "COL", "Franco Colapinto", "Williams"),
30
+ 3: DriverMeta(3, "RIC", "Daniel Ricciardo", "RB"),
31
+ 22: DriverMeta(22, "TSU", "Yuki Tsunoda", "RB"),
32
+ 30: DriverMeta(30, "LAW", "Liam Lawson", "RB"),
33
+ 77: DriverMeta(77, "BOT", "Valtteri Bottas", "Kick Sauber"),
34
+ 24: DriverMeta(24, "ZHO", "Zhou Guanyu", "Kick Sauber"),
35
+ 27: DriverMeta(27, "HUL", "Nico Hulkenberg", "Haas"),
36
+ 20: DriverMeta(20, "MAG", "Kevin Magnussen", "Haas"),
37
+ 38: DriverMeta(38, "BEA", "Oliver Bearman", "Haas"),
38
+ 12: DriverMeta(12, "ANT", "Andrea Kimi Antonelli", "Mercedes"),
39
+ 7: DriverMeta(7, "DOO", "Jack Doohan", "Alpine"),
40
+ 5: DriverMeta(5, "BOR", "Gabriel Bortoleto", "Kick Sauber"),
41
+ }
42
+
43
+
44
+ def lookup_driver_by_number(number: Any) -> DriverMeta | None:
45
+ """Resolve a driver number (int, float, or str) to DriverMeta if known."""
46
+ try:
47
+ num = int(float(number))
48
+ return DRIVER_GRID.get(num)
49
+ except (TypeError, ValueError):
50
+ return None
backend/app/utils/logger.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from logging.handlers import RotatingFileHandler
3
+ from pathlib import Path
4
+ from typing import Any
5
+
6
+ from app.config import PROJECT_ROOT
7
+
8
+
9
+ # Path to logs.txt in project root and backend directory
10
+ LOG_FILE_PATH = PROJECT_ROOT / "logs.txt"
11
+
12
+ # Dedicated logger for human-readable narrative events
13
+ narrative_logger = logging.getLogger("f1.live.events")
14
+
15
+
16
+ class CleanFormatter(logging.Formatter):
17
+ """Clean, high-precision timestamped formatter for professional logs."""
18
+
19
+ def format(self, record: logging.LogRecord) -> str:
20
+ s = super().format(record)
21
+ return s
22
+
23
+
24
+ def setup_logging(
25
+ log_level: str = "INFO",
26
+ log_file: Path | None = None,
27
+ ) -> None:
28
+ """Configure console and persistent logs.txt file logging."""
29
+ if log_file is None:
30
+ log_file = LOG_FILE_PATH
31
+
32
+ log_file.parent.mkdir(parents=True, exist_ok=True)
33
+
34
+ level = getattr(logging, log_level.upper(), logging.INFO)
35
+ formatter = logging.Formatter(
36
+ "%(asctime)s.%(msecs)03d | %(levelname)-7s | %(name)s | %(message)s",
37
+ datefmt="%Y-%m-%d %H:%M:%S",
38
+ )
39
+
40
+ root_logger = logging.getLogger()
41
+ root_logger.setLevel(level)
42
+
43
+ # Check if a file handler already exists to avoid duplicates
44
+ has_file_handler = any(
45
+ isinstance(h, (logging.FileHandler, RotatingFileHandler))
46
+ for h in root_logger.handlers
47
+ )
48
+
49
+ if not has_file_handler:
50
+ file_handler = RotatingFileHandler(
51
+ str(log_file),
52
+ maxBytes=20 * 1024 * 1024, # 20 MB
53
+ backupCount=3,
54
+ encoding="utf-8",
55
+ )
56
+ file_handler.setLevel(level)
57
+ file_handler.setFormatter(formatter)
58
+ root_logger.addHandler(file_handler)
59
+
60
+ # Ensure console handler exists
61
+ has_stream_handler = any(
62
+ isinstance(h, logging.StreamHandler) and not isinstance(h, (logging.FileHandler, RotatingFileHandler))
63
+ for h in root_logger.handlers
64
+ )
65
+ if not has_stream_handler:
66
+ console_handler = logging.StreamHandler()
67
+ console_handler.setLevel(level)
68
+ console_handler.setFormatter(formatter)
69
+ root_logger.addHandler(console_handler)
70
+
71
+
72
+ # --- Narrative Event Helpers ---
73
+
74
+ def log_stream_event(event: str, detail: str = "") -> None:
75
+ msg = f"[STREAM] {event}"
76
+ if detail:
77
+ msg += f" - {detail}"
78
+ narrative_logger.info(msg)
79
+
80
+
81
+ def log_connection_event(status: str, detail: str = "") -> None:
82
+ msg = f"[CONNECTION] {status}"
83
+ if detail:
84
+ msg += f" | {detail}"
85
+ narrative_logger.warning(msg) if "drop" in status.casefold() or "fail" in status.casefold() else narrative_logger.info(msg)
86
+
87
+
88
+ def log_ingest_event(topic: str, record_count: int, driver_count: int | None = None) -> None:
89
+ msg = f"[INGEST] Topic '{topic}' fetched: {record_count} record(s)"
90
+ if driver_count is not None:
91
+ msg += f" across {driver_count} driver(s)"
92
+ narrative_logger.info(msg)
93
+
94
+
95
+ def log_driver_status(driver: str, status: str, detail: str = "") -> None:
96
+ msg = f"[DRIVER] {driver} -> {status}"
97
+ if detail:
98
+ msg += f" ({detail})"
99
+ narrative_logger.info(msg)
100
+
101
+
102
+ def log_lap_completed(driver: str, lap_number: int, detail: str = "") -> None:
103
+ msg = f"[LAP] Driver {driver} completed Lap {lap_number}"
104
+ if detail:
105
+ msg += f" | {detail}"
106
+ narrative_logger.info(msg)
107
+
108
+
109
+ def log_prediction_event(
110
+ driver: str,
111
+ lap_number: int,
112
+ win_probability: float,
113
+ coverage: float,
114
+ confidence: str,
115
+ rank: int | None = None,
116
+ ) -> None:
117
+ rank_str = f"Rank #{rank} | " if rank is not None else ""
118
+ msg = (
119
+ f"[PREDICTION] {rank_str}Driver {driver} (Lap {lap_number}): "
120
+ f"Win Prob = {win_probability:.1%} | "
121
+ f"Coverage = {coverage:.1%} | "
122
+ f"Confidence = {confidence.upper()}"
123
+ )
124
+ narrative_logger.info(msg)
backend/data/F1_2026_model_training_data.csv ADDED
The diff for this file is too large to render. See raw diff
 
backend/data/benchmark_latency.py ADDED
@@ -0,0 +1,514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # F1 PIT LANE - MODEL LATENCY BENCHMARK
3
+ #
4
+ # Measures:
5
+ # 1. XGBoost inference only
6
+ # 2. Preprocessing + XGBoost inference
7
+ # 3. Batch prediction for 20 drivers
8
+ #
9
+ # IMPORTANT:
10
+ # The benchmark loads the SAME .pkl used by the backend.
11
+ # ============================================================
12
+
13
+ import time
14
+ from pathlib import Path
15
+
16
+ import joblib
17
+ import numpy as np
18
+ import pandas as pd
19
+
20
+
21
+ # ============================================================
22
+ # CONFIGURATION
23
+ # ============================================================
24
+
25
+ MODEL_PATH = (
26
+ "C:\\Users\\Admin\\Desktop\\PitLane\\F1_Model\\f1_live_winner_model.pkl"
27
+ )
28
+
29
+ DATASET_PATH = (
30
+ "C:\\Users\\Admin\\Desktop\\PitLane\\F1_Model\\F1_2026_model_training_data.csv"
31
+ )
32
+
33
+ # Number of measured repetitions
34
+ N_RUNS = 1000
35
+
36
+ # Warm-up predictions are NOT included in the measurements.
37
+ WARMUP_RUNS = 100
38
+
39
+
40
+ # ============================================================
41
+ # LOAD MODEL
42
+ # ============================================================
43
+
44
+ print("=" * 80)
45
+ print("F1 PIT LANE - MODEL LATENCY BENCHMARK")
46
+ print("=" * 80)
47
+
48
+ if not Path(MODEL_PATH).exists():
49
+
50
+ raise FileNotFoundError(
51
+ f"Model not found:\n{MODEL_PATH}"
52
+ )
53
+
54
+
55
+ print("\nLoading model bundle...")
56
+
57
+ bundle = joblib.load(
58
+ MODEL_PATH
59
+ )
60
+
61
+ model = bundle["model"]
62
+ preprocessor = bundle["preprocessor"]
63
+ feature_columns = bundle["feature_columns"]
64
+
65
+ print(
66
+ f"Model loaded successfully."
67
+ )
68
+
69
+ print(
70
+ f"Expected features: "
71
+ f"{len(feature_columns)}"
72
+ )
73
+
74
+
75
+ # ============================================================
76
+ # LOAD REAL DATA
77
+ #
78
+ # We use your actual model-training dataset rather than
79
+ # synthetic/random values.
80
+ # ============================================================
81
+
82
+ if not Path(DATASET_PATH).exists():
83
+
84
+ raise FileNotFoundError(
85
+ f"Dataset not found:\n{DATASET_PATH}"
86
+ )
87
+
88
+
89
+ print("\nLoading real feature data...")
90
+
91
+ df = pd.read_csv(
92
+ DATASET_PATH,
93
+ low_memory=False
94
+ )
95
+
96
+
97
+ # ============================================================
98
+ # PREPARE ONE REAL MODEL INPUT ROW
99
+ # ============================================================
100
+
101
+ # ------------------------------------------------------------
102
+ # Remove target / metadata exactly as the training pipeline
103
+ # does.
104
+ # ------------------------------------------------------------
105
+
106
+ DROP_COLUMNS = [
107
+ "Winner",
108
+ "RaceDate",
109
+
110
+ "winning_driver_number",
111
+ "WinningDriver",
112
+ "WinningDriverName",
113
+
114
+ "RaceID",
115
+ "session_key",
116
+ "meeting_key",
117
+ "location",
118
+ "country_name",
119
+ "RoundNumber",
120
+ "EventName",
121
+
122
+ "_RaceDate"
123
+ ]
124
+
125
+
126
+ X = df.drop(
127
+ columns=[
128
+ column
129
+ for column in DROP_COLUMNS
130
+ if column in df.columns
131
+ ],
132
+ errors="ignore"
133
+ )
134
+
135
+
136
+ # ------------------------------------------------------------
137
+ # Ensure exact feature order
138
+ # ------------------------------------------------------------
139
+
140
+ for column in feature_columns:
141
+
142
+ if column not in X.columns:
143
+
144
+ X[column] = np.nan
145
+
146
+
147
+ X = X[
148
+ feature_columns
149
+ ]
150
+
151
+
152
+ # Take one real driver/lap row
153
+ one_row = X.iloc[[0]].copy()
154
+
155
+
156
+ print(
157
+ f"\nOne-row shape: "
158
+ f"{one_row.shape}"
159
+ )
160
+
161
+
162
+ # ============================================================
163
+ # PREPROCESS ONCE
164
+ #
165
+ # This allows us to measure pure XGBoost inference separately.
166
+ # ============================================================
167
+
168
+ one_row_processed = (
169
+ preprocessor.transform(
170
+ one_row
171
+ )
172
+ )
173
+
174
+
175
+ # ============================================================
176
+ # 1. XGBOOST-ONLY LATENCY
177
+ # ============================================================
178
+
179
+ print("\n")
180
+ print("=" * 80)
181
+ print("1. XGBOOST INFERENCE ONLY")
182
+ print("=" * 80)
183
+
184
+
185
+ # Warm-up
186
+ for _ in range(WARMUP_RUNS):
187
+
188
+ model.predict_proba(
189
+ one_row_processed
190
+ )
191
+
192
+
193
+ latencies_ms = []
194
+
195
+
196
+ for _ in range(N_RUNS):
197
+
198
+ start = time.perf_counter_ns()
199
+
200
+ model.predict_proba(
201
+ one_row_processed
202
+ )
203
+
204
+ end = time.perf_counter_ns()
205
+
206
+ latency = (
207
+ end - start
208
+ ) / 1_000_000
209
+
210
+ latencies_ms.append(
211
+ latency
212
+ )
213
+
214
+
215
+ latencies_ms = np.array(
216
+ latencies_ms
217
+ )
218
+
219
+
220
+ print(
221
+ f"Mean : "
222
+ f"{latencies_ms.mean():.4f} ms"
223
+ )
224
+
225
+ print(
226
+ f"Min : "
227
+ f"{latencies_ms.min():.4f} ms"
228
+ )
229
+
230
+ print(
231
+ f"Max : "
232
+ f"{latencies_ms.max():.4f} ms"
233
+ )
234
+
235
+ print(
236
+ f"P50 : "
237
+ f"{np.percentile(latencies_ms, 50):.4f} ms"
238
+ )
239
+
240
+ print(
241
+ f"P95 : "
242
+ f"{np.percentile(latencies_ms, 95):.4f} ms"
243
+ )
244
+
245
+ print(
246
+ f"P99 : "
247
+ f"{np.percentile(latencies_ms, 99):.4f} ms"
248
+ )
249
+
250
+
251
+ # ============================================================
252
+ # 2. PREPROCESSING + XGBOOST
253
+ # ============================================================
254
+
255
+ print("\n")
256
+ print("=" * 80)
257
+ print("2. PREPROCESSING + XGBOOST")
258
+ print("=" * 80)
259
+
260
+
261
+ # Warm-up
262
+ for _ in range(WARMUP_RUNS):
263
+
264
+ processed = (
265
+ preprocessor.transform(
266
+ one_row
267
+ )
268
+ )
269
+
270
+ model.predict_proba(
271
+ processed
272
+ )
273
+
274
+
275
+ latencies_ms = []
276
+
277
+
278
+ for _ in range(N_RUNS):
279
+
280
+ start = time.perf_counter_ns()
281
+
282
+ processed = (
283
+ preprocessor.transform(
284
+ one_row
285
+ )
286
+ )
287
+
288
+ model.predict_proba(
289
+ processed
290
+ )
291
+
292
+ end = time.perf_counter_ns()
293
+
294
+ latency = (
295
+ end - start
296
+ ) / 1_000_000
297
+
298
+ latencies_ms.append(
299
+ latency
300
+ )
301
+
302
+
303
+ latencies_ms = np.array(
304
+ latencies_ms
305
+ )
306
+
307
+
308
+ print(
309
+ f"Mean : "
310
+ f"{latencies_ms.mean():.4f} ms"
311
+ )
312
+
313
+ print(
314
+ f"Min : "
315
+ f"{latencies_ms.min():.4f} ms"
316
+ )
317
+
318
+ print(
319
+ f"Max : "
320
+ f"{latencies_ms.max():.4f} ms"
321
+ )
322
+
323
+ print(
324
+ f"P50 : "
325
+ f"{np.percentile(latencies_ms, 50):.4f} ms"
326
+ )
327
+
328
+ print(
329
+ f"P95 : "
330
+ f"{np.percentile(latencies_ms, 95):.4f} ms"
331
+ )
332
+
333
+ print(
334
+ f"P99 : "
335
+ f"{np.percentile(latencies_ms, 99):.4f} ms"
336
+ )
337
+
338
+
339
+ # ============================================================
340
+ # 3. 20-DRIVER BATCH LATENCY
341
+ #
342
+ # This is much more relevant to your actual Pit Lane system.
343
+ #
344
+ # We take 20 real rows and predict all 20 together.
345
+ # ============================================================
346
+
347
+ print("\n")
348
+ print("=" * 80)
349
+ print("3. 20-DRIVER BATCH LATENCY")
350
+ print("=" * 80)
351
+
352
+
353
+ # ------------------------------------------------------------
354
+ # Take up to 20 real rows
355
+ # ------------------------------------------------------------
356
+
357
+ batch_size = min(
358
+ 20,
359
+ len(X)
360
+ )
361
+
362
+ batch = X.iloc[
363
+ :batch_size
364
+ ].copy()
365
+
366
+
367
+ # Warm-up
368
+ for _ in range(WARMUP_RUNS):
369
+
370
+ processed = (
371
+ preprocessor.transform(
372
+ batch
373
+ )
374
+ )
375
+
376
+ model.predict_proba(
377
+ processed
378
+ )
379
+
380
+
381
+ latencies_ms = []
382
+
383
+
384
+ for _ in range(N_RUNS):
385
+
386
+ start = time.perf_counter_ns()
387
+
388
+ processed = (
389
+ preprocessor.transform(
390
+ batch
391
+ )
392
+ )
393
+
394
+ model.predict_proba(
395
+ processed
396
+ )
397
+
398
+ end = time.perf_counter_ns()
399
+
400
+ latency = (
401
+ end - start
402
+ ) / 1_000_000
403
+
404
+ latencies_ms.append(
405
+ latency
406
+ )
407
+
408
+
409
+ latencies_ms = np.array(
410
+ latencies_ms
411
+ )
412
+
413
+
414
+ print(
415
+ f"Drivers measured: "
416
+ f"{batch_size}"
417
+ )
418
+
419
+ print(
420
+ f"Mean total : "
421
+ f"{latencies_ms.mean():.4f} ms"
422
+ )
423
+
424
+ print(
425
+ f"P50 total : "
426
+ f"{np.percentile(latencies_ms, 50):.4f} ms"
427
+ )
428
+
429
+ print(
430
+ f"P95 total : "
431
+ f"{np.percentile(latencies_ms, 95):.4f} ms"
432
+ )
433
+
434
+ print(
435
+ f"P99 total : "
436
+ f"{np.percentile(latencies_ms, 99):.4f} ms"
437
+ )
438
+
439
+ print(
440
+ f"\nApprox. per-driver mean: "
441
+ f"{latencies_ms.mean() / batch_size:.4f} ms"
442
+ )
443
+
444
+
445
+ # ============================================================
446
+ # 4. PREDICTION OUTPUT CHECK
447
+ # ============================================================
448
+
449
+ print("\n")
450
+ print("=" * 80)
451
+ print("PREDICTION CHECK")
452
+ print("=" * 80)
453
+
454
+
455
+ processed = (
456
+ preprocessor.transform(
457
+ batch
458
+ )
459
+ )
460
+
461
+ probabilities = (
462
+ model.predict_proba(
463
+ processed
464
+ )[:, 1]
465
+ )
466
+
467
+
468
+ print(
469
+ "\nPredicted probabilities:"
470
+ )
471
+
472
+ for i, probability in enumerate(
473
+ probabilities
474
+ ):
475
+
476
+ print(
477
+ f"Driver row {i + 1:02d}: "
478
+ f"{probability * 100:.4f}%"
479
+ )
480
+
481
+
482
+ # ============================================================
483
+ # 5. FINAL SUMMARY
484
+ # ============================================================
485
+
486
+ print("\n")
487
+ print("=" * 80)
488
+ print("LATENCY BENCHMARK COMPLETE")
489
+ print("=" * 80)
490
+
491
+ print(
492
+ "\nThese measurements exclude:"
493
+ )
494
+
495
+ print(
496
+ " - network latency"
497
+ )
498
+
499
+ print(
500
+ " - API/FastF1 latency"
501
+ )
502
+
503
+ print(
504
+ " - raw telemetry acquisition"
505
+ )
506
+
507
+ print(
508
+ " - raw telemetry → compressed-lap processing"
509
+ )
510
+
511
+ print(
512
+ "\nTherefore the 20-driver batch number is the "
513
+ "model-side latency, NOT the total backend latency."
514
+ )
backend/data/compressor.py ADDED
@@ -0,0 +1,1507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # F1 LAP-LEVEL COMPRESSION + WINNER TARGET
3
+ #
4
+ # INPUT:
5
+ # Raw merged telemetry CSV
6
+ # WITHOUT Winner column
7
+ #
8
+ # OUTPUT:
9
+ # 1 row = 1 Race + 1 Driver + 1 Lap
10
+ #
11
+ # Example:
12
+ # 50 laps × 10 drivers = 500 rows
13
+ #
14
+ # Winner:
15
+ # 1 = driver eventually won that race
16
+ # 0 = driver did not win
17
+ #
18
+ # IMPORTANT:
19
+ # Drivers are NEVER hardcoded.
20
+ # They are taken directly from the input CSV.
21
+ # ============================================================
22
+
23
+
24
+ # ============================================================
25
+ # 1. INSTALL / IMPORT
26
+ # ============================================================
27
+
28
+ # In Colab, uncomment this if FastF1 is not installed:
29
+ # !pip install -q fastf1
30
+
31
+ import json
32
+ import os
33
+ from pathlib import Path
34
+
35
+ import fastf1
36
+ import numpy as np
37
+ import pandas as pd
38
+
39
+
40
+ # ============================================================
41
+ # 2. CONFIGURATION
42
+ # ============================================================
43
+
44
+ YEAR = 2026
45
+
46
+ INPUT_FILE = "C:\\Users\\Admin\\Desktop\\PitLane\\cleaned_data_sidh.csv"
47
+
48
+ OUTPUT_FILE = "F1_2026_compressed_training_data_SIDH.csv"
49
+
50
+ SCHEMA_FILE = "F1_2026_compression_schema_SIDH.json"
51
+
52
+ CACHE_DIR = "fastf1_cache"
53
+
54
+
55
+ # Number of raw telemetry rows processed at a time.
56
+ #
57
+ # This prevents the entire raw dataset from having to live
58
+ # in memory during compression.
59
+ CHUNK_SIZE = 250_000
60
+
61
+
62
+ # ============================================================
63
+ # 3. FASTF1 CACHE
64
+ # ============================================================
65
+
66
+ Path(CACHE_DIR).mkdir(
67
+ parents=True,
68
+ exist_ok=True
69
+ )
70
+
71
+ fastf1.Cache.enable_cache(
72
+ CACHE_DIR
73
+ )
74
+
75
+
76
+ # ============================================================
77
+ # 4. INPUT VALIDATION
78
+ # ============================================================
79
+
80
+ if not Path(INPUT_FILE).exists():
81
+
82
+ raise FileNotFoundError(
83
+ f"\nInput file not found:\n{INPUT_FILE}"
84
+ )
85
+
86
+
87
+ # ============================================================
88
+ # 5. COLUMNS
89
+ # ============================================================
90
+
91
+ # These columns describe the instantaneous telemetry stream.
92
+ #
93
+ # We compress them using statistical summaries over the
94
+ # entire lap.
95
+ MEAN_COLUMNS = [
96
+ "RPM",
97
+ "Speed",
98
+ "nGear",
99
+ "Throttle",
100
+ "Brake",
101
+ "DRS",
102
+ "X",
103
+ "Y",
104
+ "Z",
105
+ "DistanceToDriverAhead",
106
+ "AirTemp",
107
+ "TrackTemp",
108
+ "Humidity",
109
+ "Pressure",
110
+ "WindDirection",
111
+ "WindSpeed"
112
+ ]
113
+
114
+
115
+ # For these we want the state at the END of the completed lap.
116
+ LAST_COLUMNS = [
117
+ "Date",
118
+ "SessionTime",
119
+ "Time",
120
+ "Distance",
121
+ "RelativeDistance",
122
+ "DriverAhead",
123
+ "TrackStatus",
124
+ "Driver",
125
+ "DriverNumber",
126
+ "Team",
127
+ "LapNumber",
128
+ "Stint",
129
+ "Compound",
130
+ "TyreLife",
131
+ "FreshTyre",
132
+ "LapTime",
133
+ "Sector1Time",
134
+ "Sector2Time",
135
+ "Sector3Time",
136
+ "Sector1SessionTime",
137
+ "Sector2SessionTime",
138
+ "Sector3SessionTime",
139
+ "SpeedI1",
140
+ "SpeedI2",
141
+ "SpeedFL",
142
+ "SpeedST",
143
+ "IsPersonalBest",
144
+ "Position",
145
+ "PitInTime",
146
+ "PitOutTime",
147
+ "LapStartTime",
148
+ "LapStartDate"
149
+ ]
150
+
151
+
152
+ # Rainfall is a state/event indicator.
153
+ # Maximum is effectively "did rain occur during this lap?"
154
+ RAIN_COLUMN = "Rainfall"
155
+
156
+
157
+ # DifferentialDistance represents incremental distance.
158
+ # Summing it over a lap gives the distance accumulated.
159
+ SUM_COLUMNS = [
160
+ "DifferentialDistance"
161
+ ]
162
+
163
+
164
+ # ============================================================
165
+ # 6. COLUMNS REQUIRED FROM THE RAW DATA
166
+ # ============================================================
167
+
168
+ REQUIRED_COLUMNS = [
169
+ "Date",
170
+ "Driver",
171
+ "DriverNumber",
172
+ "LapNumber"
173
+ ]
174
+
175
+
176
+ # ============================================================
177
+ # 7. HELPER FUNCTIONS
178
+ # ============================================================
179
+
180
+ def last_valid(series):
181
+ """
182
+ Return the last non-null value in a group.
183
+ """
184
+
185
+ valid = series.dropna()
186
+
187
+ if len(valid) == 0:
188
+ return np.nan
189
+
190
+ return valid.iloc[-1]
191
+
192
+
193
+ def first_valid(series):
194
+ """
195
+ Return the first non-null value in a group.
196
+ """
197
+
198
+ valid = series.dropna()
199
+
200
+ if len(valid) == 0:
201
+ return np.nan
202
+
203
+ return valid.iloc[0]
204
+
205
+
206
+ def safe_numeric(series):
207
+ return pd.to_numeric(
208
+ series,
209
+ errors="coerce"
210
+ )
211
+
212
+
213
+ # ============================================================
214
+ # 8. PREPARE A CHUNK
215
+ # ============================================================
216
+
217
+ def prepare_chunk(chunk):
218
+
219
+ chunk = chunk.copy()
220
+
221
+ # --------------------------------------------------------
222
+ # Date
223
+ # --------------------------------------------------------
224
+
225
+ chunk["Date"] = pd.to_datetime(
226
+ chunk["Date"],
227
+ errors="coerce"
228
+ )
229
+
230
+ # Race date = calendar date of the race.
231
+ chunk["_RaceDate"] = (
232
+ chunk["Date"]
233
+ .dt.normalize()
234
+ )
235
+
236
+ # --------------------------------------------------------
237
+ # Numeric conversion
238
+ # --------------------------------------------------------
239
+
240
+ numeric_columns = list(
241
+ set(
242
+ MEAN_COLUMNS
243
+ + SUM_COLUMNS
244
+ + [
245
+ "DriverNumber",
246
+ "LapNumber",
247
+ "Stint",
248
+ "TyreLife",
249
+ "Position"
250
+ ]
251
+ )
252
+ )
253
+
254
+ for column in numeric_columns:
255
+
256
+ if column in chunk.columns:
257
+
258
+ chunk[column] = safe_numeric(
259
+ chunk[column]
260
+ )
261
+
262
+ # --------------------------------------------------------
263
+ # Boolean conversion
264
+ # --------------------------------------------------------
265
+
266
+ boolean_columns = [
267
+ "Brake",
268
+ "FreshTyre",
269
+ "IsPersonalBest",
270
+ "Rainfall"
271
+ ]
272
+
273
+ for column in boolean_columns:
274
+
275
+ if column not in chunk.columns:
276
+ continue
277
+
278
+ if pd.api.types.is_bool_dtype(
279
+ chunk[column]
280
+ ):
281
+
282
+ chunk[column] = (
283
+ chunk[column]
284
+ .astype(float)
285
+ )
286
+
287
+ else:
288
+
289
+ chunk[column] = (
290
+ chunk[column]
291
+ .astype(str)
292
+ .str.strip()
293
+ .str.lower()
294
+ .map({
295
+ "true": 1,
296
+ "false": 0,
297
+ "1": 1,
298
+ "0": 0
299
+ })
300
+ )
301
+
302
+ # --------------------------------------------------------
303
+ # Driver
304
+ # --------------------------------------------------------
305
+
306
+ chunk["Driver"] = (
307
+ chunk["Driver"]
308
+ .fillna("UNKNOWN")
309
+ .astype(str)
310
+ )
311
+
312
+ # --------------------------------------------------------
313
+ # Sort chronological
314
+ # --------------------------------------------------------
315
+
316
+ sort_columns = [
317
+ "_RaceDate",
318
+ "Driver",
319
+ "LapNumber"
320
+ ]
321
+
322
+ for column in [
323
+ "SessionTime",
324
+ "Time",
325
+ "Date"
326
+ ]:
327
+
328
+ if column in chunk.columns:
329
+ sort_columns.append(column)
330
+
331
+ chunk = chunk.sort_values(
332
+ sort_columns,
333
+ kind="stable"
334
+ )
335
+
336
+ return chunk
337
+
338
+
339
+ # ============================================================
340
+ # 9. COMPRESS ONE CHUNK
341
+ # ============================================================
342
+
343
+ def compress_chunk(chunk):
344
+
345
+ chunk = prepare_chunk(
346
+ chunk
347
+ )
348
+
349
+ group_columns = [
350
+ "_RaceDate",
351
+ "Driver",
352
+ "LapNumber"
353
+ ]
354
+
355
+ grouped = chunk.groupby(
356
+ group_columns,
357
+ sort=False,
358
+ dropna=False
359
+ )
360
+
361
+ compressed_parts = []
362
+
363
+ # --------------------------------------------------------
364
+ # Base information
365
+ # --------------------------------------------------------
366
+
367
+ base = grouped.size().rename(
368
+ "TelemetryRecords"
369
+ ).reset_index()
370
+
371
+ compressed_parts.append(
372
+ base
373
+ )
374
+
375
+ # --------------------------------------------------------
376
+ # MEAN FEATURES
377
+ # --------------------------------------------------------
378
+
379
+ for column in MEAN_COLUMNS:
380
+
381
+ if column not in chunk.columns:
382
+ continue
383
+
384
+ result = (
385
+ grouped[column]
386
+ .mean()
387
+ .rename(
388
+ f"{column}_Mean"
389
+ )
390
+ .reset_index()
391
+ )
392
+
393
+ compressed_parts.append(
394
+ result
395
+ )
396
+
397
+ # --------------------------------------------------------
398
+ # SUM FEATURES
399
+ # --------------------------------------------------------
400
+
401
+ for column in SUM_COLUMNS:
402
+
403
+ if column not in chunk.columns:
404
+ continue
405
+
406
+ result = (
407
+ grouped[column]
408
+ .sum(
409
+ min_count=1
410
+ )
411
+ .rename(
412
+ f"{column}_Sum"
413
+ )
414
+ .reset_index()
415
+ )
416
+
417
+ compressed_parts.append(
418
+ result
419
+ )
420
+
421
+ # --------------------------------------------------------
422
+ # LAST VALUE FEATURES
423
+ # --------------------------------------------------------
424
+
425
+ for column in LAST_COLUMNS:
426
+
427
+ if column not in chunk.columns:
428
+ continue
429
+
430
+ result = (
431
+ grouped[column]
432
+ .agg(last_valid)
433
+ .rename(
434
+ f"{column}_Last"
435
+ )
436
+ .reset_index()
437
+ )
438
+
439
+ compressed_parts.append(
440
+ result
441
+ )
442
+
443
+ # --------------------------------------------------------
444
+ # RAINFALL
445
+ # --------------------------------------------------------
446
+
447
+ if RAIN_COLUMN in chunk.columns:
448
+
449
+ result = (
450
+ grouped[RAIN_COLUMN]
451
+ .max()
452
+ .rename(
453
+ "Rainfall_Any"
454
+ )
455
+ .reset_index()
456
+ )
457
+
458
+ compressed_parts.append(
459
+ result
460
+ )
461
+
462
+ # --------------------------------------------------------
463
+ # Merge partial compressed pieces
464
+ # --------------------------------------------------------
465
+
466
+ result = compressed_parts[0]
467
+
468
+ for part in compressed_parts[1:]:
469
+
470
+ result = result.merge(
471
+ part,
472
+ on=group_columns,
473
+ how="left"
474
+ )
475
+
476
+ return result
477
+
478
+
479
+ # ============================================================
480
+ # 10. MERGE PARTIAL CHUNKS
481
+ # ============================================================
482
+
483
+ def merge_compressed_chunks(
484
+ partial_results
485
+ ):
486
+
487
+ """
488
+ A single race/lap may cross CSV chunk boundaries.
489
+
490
+ Therefore we compress each chunk first, then recompute
491
+ the final aggregation from those partial results.
492
+ """
493
+
494
+ if not partial_results:
495
+
496
+ return pd.DataFrame()
497
+
498
+ df = pd.concat(
499
+ partial_results,
500
+ ignore_index=True
501
+ )
502
+
503
+ group_columns = [
504
+ "_RaceDate",
505
+ "Driver",
506
+ "LapNumber"
507
+ ]
508
+
509
+ final_rows = []
510
+
511
+ for group_key, group in df.groupby(
512
+ group_columns,
513
+ sort=False,
514
+ dropna=False
515
+ ):
516
+
517
+ row = {
518
+ "_RaceDate":
519
+ group_key[0],
520
+
521
+ "Driver":
522
+ group_key[1],
523
+
524
+ "LapNumber":
525
+ group_key[2]
526
+ }
527
+
528
+ # ----------------------------------------------------
529
+ # Number of telemetry records
530
+ # ----------------------------------------------------
531
+
532
+ if "TelemetryRecords" in group:
533
+
534
+ row["TelemetryRecords"] = (
535
+ group["TelemetryRecords"]
536
+ .sum()
537
+ )
538
+
539
+ # ----------------------------------------------------
540
+ # MEAN COLUMNS
541
+ #
542
+ # Weighted average using raw record counts.
543
+ # ----------------------------------------------------
544
+
545
+ for column in MEAN_COLUMNS:
546
+
547
+ mean_column = (
548
+ f"{column}_Mean"
549
+ )
550
+
551
+ if mean_column not in group.columns:
552
+ continue
553
+
554
+ weights = (
555
+ group["TelemetryRecords"]
556
+ .fillna(0)
557
+ )
558
+
559
+ values = (
560
+ pd.to_numeric(
561
+ group[mean_column],
562
+ errors="coerce"
563
+ )
564
+ )
565
+
566
+ valid = (
567
+ values.notna()
568
+ &
569
+ (weights > 0)
570
+ )
571
+
572
+ if valid.any():
573
+
574
+ row[
575
+ mean_column
576
+ ] = np.average(
577
+ values[valid],
578
+ weights=weights[valid]
579
+ )
580
+
581
+ else:
582
+
583
+ row[
584
+ mean_column
585
+ ] = np.nan
586
+
587
+ # ----------------------------------------------------
588
+ # SUM COLUMNS
589
+ # ----------------------------------------------------
590
+
591
+ for column in SUM_COLUMNS:
592
+
593
+ sum_column = (
594
+ f"{column}_Sum"
595
+ )
596
+
597
+ if sum_column in group.columns:
598
+
599
+ row[
600
+ sum_column
601
+ ] = (
602
+ group[sum_column]
603
+ .sum(
604
+ min_count=1
605
+ )
606
+ )
607
+
608
+ # ----------------------------------------------------
609
+ # LAST COLUMNS
610
+ #
611
+ # The raw CSV is chronological; sort by race/lap and
612
+ # then choose the latest non-null value.
613
+ # ----------------------------------------------------
614
+
615
+ for column in LAST_COLUMNS:
616
+
617
+ last_column = (
618
+ f"{column}_Last"
619
+ )
620
+
621
+ if last_column not in group.columns:
622
+ continue
623
+
624
+ row[
625
+ last_column
626
+ ] = last_valid(
627
+ group[last_column]
628
+ )
629
+
630
+ # ----------------------------------------------------
631
+ # Rain
632
+ # ----------------------------------------------------
633
+
634
+ if "Rainfall_Any" in group.columns:
635
+
636
+ row[
637
+ "Rainfall_Any"
638
+ ] = group[
639
+ "Rainfall_Any"
640
+ ].max()
641
+
642
+ final_rows.append(
643
+ row
644
+ )
645
+
646
+ return pd.DataFrame(
647
+ final_rows
648
+ )
649
+
650
+
651
+ # ============================================================
652
+ # 11. COMPRESS ENTIRE DATASET
653
+ # ============================================================
654
+
655
+ def compress_dataset():
656
+
657
+ print("=" * 80)
658
+ print("STARTING LAP-LEVEL COMPRESSION")
659
+ print("=" * 80)
660
+
661
+ partial_results = []
662
+
663
+ total_raw_rows = 0
664
+ chunk_number = 0
665
+
666
+ # --------------------------------------------------------
667
+ # Read CSV in chunks
668
+ # --------------------------------------------------------
669
+
670
+ reader = pd.read_csv(
671
+ INPUT_FILE,
672
+ chunksize=CHUNK_SIZE,
673
+ low_memory=False
674
+ )
675
+
676
+ for chunk in reader:
677
+
678
+ chunk_number += 1
679
+
680
+ total_raw_rows += len(
681
+ chunk
682
+ )
683
+
684
+ print(
685
+ f"\nProcessing chunk "
686
+ f"{chunk_number}: "
687
+ f"{len(chunk):,} raw rows"
688
+ )
689
+
690
+ # ----------------------------------------------------
691
+ # Validate columns on first chunk
692
+ # ----------------------------------------------------
693
+
694
+ if chunk_number == 1:
695
+
696
+ missing = [
697
+ column
698
+ for column in REQUIRED_COLUMNS
699
+ if column not in chunk.columns
700
+ ]
701
+
702
+ if missing:
703
+
704
+ raise ValueError(
705
+ "Missing required columns:\n"
706
+ + "\n".join(missing)
707
+ )
708
+
709
+ print(
710
+ f"Raw columns detected: "
711
+ f"{len(chunk.columns)}"
712
+ )
713
+
714
+ # ----------------------------------------------------
715
+ # Compress this chunk
716
+ # ----------------------------------------------------
717
+
718
+ compressed = compress_chunk(
719
+ chunk
720
+ )
721
+
722
+ print(
723
+ f"Compressed to "
724
+ f"{len(compressed):,} "
725
+ f"partial lap groups"
726
+ )
727
+
728
+ partial_results.append(
729
+ compressed
730
+ )
731
+
732
+ # Free the chunk immediately
733
+ del chunk
734
+
735
+ print("\n")
736
+ print("=" * 80)
737
+ print("COMBINING COMPRESSED CHUNKS")
738
+ print("=" * 80)
739
+
740
+ compressed_df = (
741
+ merge_compressed_chunks(
742
+ partial_results
743
+ )
744
+ )
745
+
746
+ del partial_results
747
+
748
+ print(
749
+ f"\nRaw telemetry rows: "
750
+ f"{total_raw_rows:,}"
751
+ )
752
+
753
+ print(
754
+ f"Compressed rows: "
755
+ f"{len(compressed_df):,}"
756
+ )
757
+
758
+ return compressed_df
759
+
760
+
761
+ # ============================================================
762
+ # 12. GET FASTF1 RACE SCHEDULE
763
+ # ============================================================
764
+
765
+ def get_schedule():
766
+
767
+ print("\n")
768
+ print("=" * 80)
769
+ print("LOADING FASTF1 SCHEDULE")
770
+ print("=" * 80)
771
+
772
+ schedule = fastf1.get_event_schedule(
773
+ YEAR
774
+ )
775
+
776
+ schedule = schedule[
777
+ schedule["RoundNumber"] > 0
778
+ ].copy()
779
+
780
+ schedule["EventDate"] = pd.to_datetime(
781
+ schedule["EventDate"],
782
+ errors="coerce"
783
+ )
784
+
785
+ schedule["_RaceDate"] = (
786
+ schedule["EventDate"]
787
+ .dt.normalize()
788
+ )
789
+
790
+ return schedule
791
+
792
+
793
+ # ============================================================
794
+ # 13. FETCH WINNERS
795
+ # ============================================================
796
+
797
+ def get_winners(
798
+ compressed_df,
799
+ schedule
800
+ ):
801
+
802
+ print("\n")
803
+ print("=" * 80)
804
+ print("FETCHING RACE WINNERS FROM FASTF1")
805
+ print("=" * 80)
806
+
807
+ race_dates = (
808
+ compressed_df["_RaceDate"]
809
+ .dropna()
810
+ .drop_duplicates()
811
+ .sort_values()
812
+ .tolist()
813
+ )
814
+
815
+ winner_records = []
816
+
817
+ for race_date in race_dates:
818
+
819
+ race_date = pd.Timestamp(
820
+ race_date
821
+ ).normalize()
822
+
823
+ print("\n")
824
+ print("-" * 70)
825
+
826
+ print(
827
+ f"Race date: "
828
+ f"{race_date.date()}"
829
+ )
830
+
831
+ # ----------------------------------------------------
832
+ # Match race date to schedule
833
+ # ----------------------------------------------------
834
+
835
+ matches = schedule[
836
+ schedule["_RaceDate"]
837
+ == race_date
838
+ ]
839
+
840
+ if matches.empty:
841
+
842
+ print(
843
+ "WARNING: No FastF1 race "
844
+ "matched this date."
845
+ )
846
+
847
+ continue
848
+
849
+ event = matches.iloc[0]
850
+
851
+ round_number = int(
852
+ event["RoundNumber"]
853
+ )
854
+
855
+ event_name = event["EventName"]
856
+
857
+ print(
858
+ f"Round: {round_number}"
859
+ )
860
+
861
+ print(
862
+ f"Race : {event_name}"
863
+ )
864
+
865
+ # ----------------------------------------------------
866
+ # Load race results
867
+ # ----------------------------------------------------
868
+
869
+ try:
870
+
871
+ session = fastf1.get_session(
872
+ YEAR,
873
+ round_number,
874
+ "R"
875
+ )
876
+
877
+ session.load(
878
+ telemetry=False,
879
+ weather=False
880
+ )
881
+
882
+ except Exception as e:
883
+
884
+ print(
885
+ f"ERROR loading results: {e}"
886
+ )
887
+
888
+ continue
889
+
890
+ # ----------------------------------------------------
891
+ # Results
892
+ # ----------------------------------------------------
893
+
894
+ if (
895
+ session.results is None
896
+ or session.results.empty
897
+ ):
898
+
899
+ print(
900
+ "WARNING: No results found."
901
+ )
902
+
903
+ continue
904
+
905
+ results = session.results.copy()
906
+
907
+ results["Position"] = pd.to_numeric(
908
+ results["Position"],
909
+ errors="coerce"
910
+ )
911
+
912
+ results["DriverNumber"] = pd.to_numeric(
913
+ results["DriverNumber"],
914
+ errors="coerce"
915
+ )
916
+
917
+ winner_rows = results[
918
+ results["Position"] == 1
919
+ ]
920
+
921
+ if winner_rows.empty:
922
+
923
+ print(
924
+ "WARNING: No P1 driver found."
925
+ )
926
+
927
+ continue
928
+
929
+ winner = winner_rows.iloc[0]
930
+
931
+ winner_number = winner[
932
+ "DriverNumber"
933
+ ]
934
+
935
+ winner_abbreviation = winner.get(
936
+ "Abbreviation",
937
+ "UNKNOWN"
938
+ )
939
+
940
+ winner_name = winner.get(
941
+ "FullName",
942
+ "UNKNOWN"
943
+ )
944
+
945
+ print(
946
+ f"Winner: #{int(winner_number)} "
947
+ f"{winner_abbreviation} "
948
+ f"({winner_name})"
949
+ )
950
+
951
+ winner_records.append(
952
+ {
953
+ "_RaceDate":
954
+ race_date,
955
+
956
+ "WinningDriverNumber":
957
+ winner_number,
958
+
959
+ "WinningDriver":
960
+ winner_abbreviation,
961
+
962
+ "WinningDriverName":
963
+ winner_name,
964
+
965
+ "RoundNumber":
966
+ round_number,
967
+
968
+ "EventName":
969
+ event_name
970
+ }
971
+ )
972
+
973
+ winners_df = pd.DataFrame(
974
+ winner_records
975
+ )
976
+
977
+ if winners_df.empty:
978
+
979
+ raise RuntimeError(
980
+ "No race winners were successfully retrieved."
981
+ )
982
+
983
+ return winners_df
984
+
985
+
986
+ # ============================================================
987
+ # 14. ADD WINNER TARGET
988
+ # ============================================================
989
+
990
+ def add_winner_column(
991
+ compressed_df,
992
+ winners_df
993
+ ):
994
+
995
+ print("\n")
996
+ print("=" * 80)
997
+ print("ADDING WINNER TARGET")
998
+ print("=" * 80)
999
+
1000
+ compressed_df[
1001
+ "DriverNumber"
1002
+ ] = pd.to_numeric(
1003
+ compressed_df[
1004
+ "DriverNumber_Last"
1005
+ ],
1006
+ errors="coerce"
1007
+ )
1008
+
1009
+ winners_df[
1010
+ "WinningDriverNumber"
1011
+ ] = pd.to_numeric(
1012
+ winners_df[
1013
+ "WinningDriverNumber"
1014
+ ],
1015
+ errors="coerce"
1016
+ )
1017
+
1018
+ # --------------------------------------------------------
1019
+ # Merge race winner information
1020
+ # --------------------------------------------------------
1021
+
1022
+ compressed_df = compressed_df.merge(
1023
+ winners_df[
1024
+ [
1025
+ "_RaceDate",
1026
+ "WinningDriverNumber",
1027
+ "WinningDriver",
1028
+ "WinningDriverName",
1029
+ "RoundNumber",
1030
+ "EventName"
1031
+ ]
1032
+ ],
1033
+ on="_RaceDate",
1034
+ how="left"
1035
+ )
1036
+
1037
+ # --------------------------------------------------------
1038
+ # Winner target
1039
+ #
1040
+ # Only drivers actually present in the CSV exist here,
1041
+ # so no hardcoded driver is added.
1042
+ # --------------------------------------------------------
1043
+
1044
+ compressed_df["Winner"] = (
1045
+ compressed_df["DriverNumber"]
1046
+ ==
1047
+ compressed_df["WinningDriverNumber"]
1048
+ ).astype(int)
1049
+
1050
+ return compressed_df
1051
+
1052
+
1053
+ # ============================================================
1054
+ # 15. FINAL CLEANUP / COLUMN ORDER
1055
+ # ============================================================
1056
+
1057
+ def final_cleanup(
1058
+ compressed_df
1059
+ ):
1060
+
1061
+ # --------------------------------------------------------
1062
+ # Sort
1063
+ # --------------------------------------------------------
1064
+
1065
+ compressed_df = (
1066
+ compressed_df
1067
+ .sort_values(
1068
+ [
1069
+ "_RaceDate",
1070
+ "Driver",
1071
+ "LapNumber"
1072
+ ],
1073
+ kind="stable"
1074
+ )
1075
+ .reset_index(
1076
+ drop=True
1077
+ )
1078
+ )
1079
+
1080
+ # --------------------------------------------------------
1081
+ # Put useful identifiers at the front
1082
+ # --------------------------------------------------------
1083
+
1084
+ preferred_front = [
1085
+ "_RaceDate",
1086
+ "Driver",
1087
+ "DriverNumber",
1088
+ "LapNumber",
1089
+ "TelemetryRecords",
1090
+ "Winner"
1091
+ ]
1092
+
1093
+ remaining_columns = [
1094
+ column
1095
+ for column in compressed_df.columns
1096
+ if column not in preferred_front
1097
+ ]
1098
+
1099
+ compressed_df = compressed_df[
1100
+ [
1101
+ column
1102
+ for column in preferred_front
1103
+ if column in compressed_df.columns
1104
+ ]
1105
+ +
1106
+ remaining_columns
1107
+ ]
1108
+
1109
+ # --------------------------------------------------------
1110
+ # Remove technical winner metadata from model dataset
1111
+ #
1112
+ # They have already served their purpose.
1113
+ # --------------------------------------------------------
1114
+
1115
+ compressed_df = compressed_df.drop(
1116
+ columns=[
1117
+ "WinningDriverNumber",
1118
+ "WinningDriver",
1119
+ "WinningDriverName",
1120
+ "RoundNumber",
1121
+ "EventName"
1122
+ ],
1123
+ errors="ignore"
1124
+ )
1125
+
1126
+ # --------------------------------------------------------
1127
+ # Rename internal race date
1128
+ # --------------------------------------------------------
1129
+
1130
+ compressed_df = (
1131
+ compressed_df
1132
+ .rename(
1133
+ columns={
1134
+ "_RaceDate":
1135
+ "RaceDate"
1136
+ }
1137
+ )
1138
+ )
1139
+
1140
+ return compressed_df
1141
+
1142
+
1143
+ # ============================================================
1144
+ # 16. CREATE COMPRESSION SCHEMA
1145
+ # ============================================================
1146
+
1147
+ def create_schema(
1148
+ compressed_df
1149
+ ):
1150
+
1151
+ model_candidate_columns = [
1152
+ column
1153
+ for column in compressed_df.columns
1154
+ if column not in [
1155
+ "RaceDate",
1156
+ "Winner"
1157
+ ]
1158
+ ]
1159
+
1160
+ categorical_candidates = [
1161
+ "Driver",
1162
+ "DriverNumber",
1163
+ "LapNumber",
1164
+ "TrackStatus_Last",
1165
+ "DriverAhead_Last",
1166
+ "Team_Last",
1167
+ "Compound_Last"
1168
+ ]
1169
+
1170
+ categorical_candidates = [
1171
+ column
1172
+ for column in categorical_candidates
1173
+ if column in compressed_df.columns
1174
+ ]
1175
+
1176
+ schema = {
1177
+
1178
+ "description":
1179
+ "One row per Race + Driver + LapNumber",
1180
+
1181
+ "input_file":
1182
+ INPUT_FILE,
1183
+
1184
+ "output_file":
1185
+ OUTPUT_FILE,
1186
+
1187
+ "target":
1188
+ "Winner",
1189
+
1190
+ "row_definition":
1191
+ "One completed lap of one driver in one race",
1192
+
1193
+ "grouping_columns": [
1194
+ "RaceDate",
1195
+ "Driver",
1196
+ "LapNumber"
1197
+ ],
1198
+
1199
+ "aggregation_rules": {
1200
+
1201
+ "mean":
1202
+ MEAN_COLUMNS,
1203
+
1204
+ "sum":
1205
+ SUM_COLUMNS,
1206
+
1207
+ "last_non_null":
1208
+ LAST_COLUMNS,
1209
+
1210
+ "rainfall_any":
1211
+ [RAIN_COLUMN]
1212
+ },
1213
+
1214
+ "model_candidate_features":
1215
+ model_candidate_columns,
1216
+
1217
+ "categorical_candidates":
1218
+ categorical_candidates,
1219
+
1220
+ "total_output_columns":
1221
+ len(compressed_df.columns),
1222
+
1223
+ "total_model_candidate_features":
1224
+ len(model_candidate_columns)
1225
+ }
1226
+
1227
+ return schema
1228
+
1229
+
1230
+ # ============================================================
1231
+ # 17. VALIDATE RESULT
1232
+ # ============================================================
1233
+
1234
+ def validate_result(
1235
+ df
1236
+ ):
1237
+
1238
+ print("\n")
1239
+ print("=" * 80)
1240
+ print("VALIDATING COMPRESSED DATASET")
1241
+ print("=" * 80)
1242
+
1243
+ # --------------------------------------------------------
1244
+ # Duplicate race/driver/lap check
1245
+ # --------------------------------------------------------
1246
+
1247
+ duplicates = df.duplicated(
1248
+ subset=[
1249
+ "RaceDate",
1250
+ "Driver",
1251
+ "LapNumber"
1252
+ ]
1253
+ ).sum()
1254
+
1255
+ print(
1256
+ f"\nDuplicate Race+Driver+Lap rows: "
1257
+ f"{duplicates}"
1258
+ )
1259
+
1260
+ if duplicates != 0:
1261
+
1262
+ raise RuntimeError(
1263
+ "Compression produced duplicate "
1264
+ "Race + Driver + Lap rows."
1265
+ )
1266
+
1267
+ # --------------------------------------------------------
1268
+ # Winner check per race
1269
+ # --------------------------------------------------------
1270
+
1271
+ winner_counts = (
1272
+ df.groupby("RaceDate")["Winner"]
1273
+ .sum()
1274
+ )
1275
+
1276
+ invalid = winner_counts[
1277
+ winner_counts != 1
1278
+ ]
1279
+
1280
+ if invalid.empty:
1281
+
1282
+ print(
1283
+ "Winner validation: PASSED"
1284
+ )
1285
+
1286
+ else:
1287
+
1288
+ print(
1289
+ "\nWARNING: These races do not have "
1290
+ "exactly one Winner=1:"
1291
+ )
1292
+
1293
+ print(
1294
+ invalid
1295
+ )
1296
+
1297
+ # --------------------------------------------------------
1298
+ # Rows per race
1299
+ # --------------------------------------------------------
1300
+
1301
+ race_summary = (
1302
+ df.groupby(
1303
+ "RaceDate"
1304
+ )
1305
+ .agg(
1306
+ Drivers=(
1307
+ "Driver",
1308
+ "nunique"
1309
+ ),
1310
+
1311
+ Laps=(
1312
+ "LapNumber",
1313
+ "nunique"
1314
+ ),
1315
+
1316
+ Rows=(
1317
+ "Winner",
1318
+ "size"
1319
+ )
1320
+ )
1321
+ .reset_index()
1322
+ )
1323
+
1324
+ race_summary[
1325
+ "ExpectedMaximumRows"
1326
+ ] = (
1327
+ race_summary["Drivers"]
1328
+ *
1329
+ race_summary["Laps"]
1330
+ )
1331
+
1332
+ print(
1333
+ "\nRace compression summary:"
1334
+ )
1335
+
1336
+ print(
1337
+ race_summary
1338
+ .to_string(
1339
+ index=False
1340
+ )
1341
+ )
1342
+
1343
+ # --------------------------------------------------------
1344
+ # Winner distribution
1345
+ # --------------------------------------------------------
1346
+
1347
+ print(
1348
+ "\nWinner distribution:"
1349
+ )
1350
+
1351
+ print(
1352
+ df["Winner"]
1353
+ .value_counts(
1354
+ dropna=False
1355
+ )
1356
+ .sort_index()
1357
+ )
1358
+
1359
+
1360
+ # ============================================================
1361
+ # 18. MAIN
1362
+ # ============================================================
1363
+
1364
+ def main():
1365
+
1366
+ print("\n")
1367
+ print("=" * 80)
1368
+ print("F1 LAP-LEVEL TRAINING DATA CREATOR")
1369
+ print("=" * 80)
1370
+
1371
+ # --------------------------------------------------------
1372
+ # Step 1
1373
+ # --------------------------------------------------------
1374
+
1375
+ compressed_df = compress_dataset()
1376
+
1377
+ # --------------------------------------------------------
1378
+ # Step 2
1379
+ # --------------------------------------------------------
1380
+
1381
+ schedule = get_schedule()
1382
+
1383
+ # --------------------------------------------------------
1384
+ # Step 3
1385
+ # --------------------------------------------------------
1386
+
1387
+ winners_df = get_winners(
1388
+ compressed_df,
1389
+ schedule
1390
+ )
1391
+
1392
+ # --------------------------------------------------------
1393
+ # Step 4
1394
+ # --------------------------------------------------------
1395
+
1396
+ compressed_df = add_winner_column(
1397
+ compressed_df,
1398
+ winners_df
1399
+ )
1400
+
1401
+ # --------------------------------------------------------
1402
+ # Step 5
1403
+ # --------------------------------------------------------
1404
+
1405
+ compressed_df = final_cleanup(
1406
+ compressed_df
1407
+ )
1408
+
1409
+ # --------------------------------------------------------
1410
+ # Step 6
1411
+ # --------------------------------------------------------
1412
+
1413
+ validate_result(
1414
+ compressed_df
1415
+ )
1416
+
1417
+ # --------------------------------------------------------
1418
+ # Step 7
1419
+ # --------------------------------------------------------
1420
+
1421
+ schema = create_schema(
1422
+ compressed_df
1423
+ )
1424
+
1425
+ # --------------------------------------------------------
1426
+ # Step 8
1427
+ # --------------------------------------------------------
1428
+
1429
+ compressed_df.to_csv(
1430
+ OUTPUT_FILE,
1431
+ index=False
1432
+ )
1433
+
1434
+ with open(
1435
+ SCHEMA_FILE,
1436
+ "w",
1437
+ encoding="utf-8"
1438
+ ) as file:
1439
+
1440
+ json.dump(
1441
+ schema,
1442
+ file,
1443
+ indent=4
1444
+ )
1445
+
1446
+ # --------------------------------------------------------
1447
+ # Final output
1448
+ # --------------------------------------------------------
1449
+
1450
+ print("\n")
1451
+ print("=" * 80)
1452
+ print("COMPRESSION COMPLETE")
1453
+ print("=" * 80)
1454
+
1455
+ print(
1456
+ f"\nRaw input:"
1457
+ f" {INPUT_FILE}"
1458
+ )
1459
+
1460
+ print(
1461
+ f"Raw telemetry rows:"
1462
+ f" {len(compressed_df):,} compressed rows"
1463
+ )
1464
+
1465
+ print(
1466
+ f"Final rows:"
1467
+ f" {len(compressed_df):,}"
1468
+ )
1469
+
1470
+ print(
1471
+ f"Final columns:"
1472
+ f" {len(compressed_df.columns)}"
1473
+ )
1474
+
1475
+ print(
1476
+ f"\nOutput:"
1477
+ f" {OUTPUT_FILE}"
1478
+ )
1479
+
1480
+ print(
1481
+ f"Schema:"
1482
+ f" {SCHEMA_FILE}"
1483
+ )
1484
+
1485
+ print(
1486
+ "\nRow meaning:"
1487
+ )
1488
+
1489
+ print(
1490
+ "ONE ROW = ONE DRIVER + ONE LAP + ONE RACE"
1491
+ )
1492
+
1493
+ print(
1494
+ "\nExample:"
1495
+ )
1496
+
1497
+ print(
1498
+ "50 laps × 10 drivers = 500 rows"
1499
+ )
1500
+
1501
+
1502
+ # ============================================================
1503
+ # RUN
1504
+ # ============================================================
1505
+
1506
+ if __name__ == "__main__":
1507
+ main()
backend/data/f1_live_winner_best_params.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "max_depth": 7,
3
+ "min_child_weight": 19,
4
+ "n_estimators": 288,
5
+ "learning_rate": 0.009737791153147714,
6
+ "subsample": 0.6658295511186884,
7
+ "colsample_bytree": 0.7638656157671425,
8
+ "gamma": 1.9433864484474102,
9
+ "reg_alpha": 2.7678419414850017e-06,
10
+ "reg_lambda": 0.5106371777919967,
11
+ "objective": "binary:logistic",
12
+ "eval_metric": "logloss",
13
+ "tree_method": "hist",
14
+ "random_state": 42
15
+ }
backend/data/f1_live_winner_feature_importance.csv ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Feature,Importance
2
+ numeric__Position,0.13453437
3
+ categorical__Driver_ANT,0.108132206
4
+ numeric__DistanceToDriverAhead_Mean,0.075147495
5
+ categorical__DriverAhead_UNKNOWN,0.059115756
6
+ categorical__Driver_RUS,0.057650063
7
+ numeric__DriverNumber,0.049615767
8
+ numeric__SpeedFL,0.046806503
9
+ numeric__Humidity_Mean,0.046269853
10
+ numeric__Pressure_Mean,0.03996773
11
+ numeric__AirTemp_Mean,0.037406094
12
+ numeric__X_Mean,0.03210651
13
+ numeric__LapNumber,0.031175822
14
+ numeric__Stint,0.026367566
15
+ numeric__SpeedI1,0.023658281
16
+ numeric__TrackAirTempDifference,0.02041052
17
+ numeric__DifferentialDistance_Sum,0.019689498
18
+ numeric__Distance,0.01825057
19
+ numeric__TrackTemp_Mean,0.01792295
20
+ numeric__Y_Mean,0.016583225
21
+ numeric__RPM_Mean,0.016220853
22
+ numeric__Speed_Mean,0.015746737
23
+ numeric__SpeedST,0.01552592
24
+ numeric__Brake_Mean,0.014375504
25
+ numeric__nGear_Mean,0.014335799
26
+ numeric__Throttle_Mean,0.012823616
27
+ numeric__TyreLife,0.011897684
28
+ numeric__SpeedI2,0.01159914
29
+ categorical__Compound_HARD,0.0115040615
30
+ numeric__TyreLifeSquared,0.010815946
31
+ numeric__Z_Mean,0.0043439767
32
+ numeric__WindSpeed_Mean,0.0
33
+ numeric__WindDirection_Mean,0.0
34
+ numeric__DRS_Mean,0.0
35
+ numeric__RelativeDistance,0.0
36
+ numeric__Rainfall,0.0
37
+ numeric__TrackStatus,0.0
38
+ numeric__FreshTyre,0.0
39
+ categorical__Driver_ALB,0.0
40
+ categorical__Driver_ALO,0.0
41
+ categorical__Driver_BEA,0.0
42
+ categorical__Driver_BOR,0.0
43
+ categorical__Driver_BOT,0.0
44
+ categorical__Driver_COL,0.0
45
+ categorical__Driver_GAS,0.0
46
+ categorical__Driver_HAD,0.0
47
+ categorical__Driver_HAM,0.0
48
+ categorical__Driver_HUL,0.0
49
+ categorical__Driver_LAW,0.0
50
+ categorical__Driver_LEC,0.0
51
+ categorical__Driver_LIN,0.0
52
+ numeric__WindX,0.0
53
+ numeric__WindY,0.0
54
+ numeric__IsPersonalBest,0.0
55
+ categorical__Driver_PER,0.0
56
+ categorical__Driver_OCO,0.0
57
+ categorical__Driver_NOR,0.0
58
+ categorical__Driver_PIA,0.0
59
+ categorical__Driver_VER,0.0
60
+ categorical__DriverAhead_1.0,0.0
61
+ categorical__Driver_SAI,0.0
62
+ categorical__Driver_STR,0.0
63
+ categorical__DriverAhead_12.0,0.0
64
+ categorical__DriverAhead_14.0,0.0
65
+ categorical__DriverAhead_16.0,0.0
66
+ categorical__DriverAhead_18.0,0.0
67
+ categorical__DriverAhead_23.0,0.0
68
+ categorical__DriverAhead_27.0,0.0
69
+ categorical__DriverAhead_10.0,0.0
70
+ categorical__DriverAhead_11.0,0.0
71
+ categorical__DriverAhead_30.0,0.0
72
+ categorical__DriverAhead_3.0,0.0
73
+ categorical__DriverAhead_31.0,0.0
74
+ categorical__DriverAhead_41.0,0.0
75
+ categorical__DriverAhead_5.0,0.0
76
+ categorical__DriverAhead_55.0,0.0
77
+ categorical__DriverAhead_43.0,0.0
78
+ categorical__DriverAhead_44.0,0.0
79
+ categorical__DriverAhead_63.0,0.0
80
+ categorical__DriverAhead_6.0,0.0
81
+ categorical__DriverAhead_81.0,0.0
82
+ categorical__DriverAhead_77.0,0.0
83
+ categorical__DriverAhead_87.0,0.0
84
+ categorical__Compound_INTERMEDIATE,0.0
85
+ categorical__Compound_MEDIUM,0.0
86
+ categorical__Compound_SOFT,0.0
backend/data/f1_live_winner_feature_schema.json ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "target": "Winner",
3
+ "race_column": "RaceDate",
4
+ "driver_column": "Driver",
5
+ "model_features": [
6
+ "Driver",
7
+ "LapNumber",
8
+ "DriverNumber",
9
+ "RPM_Mean",
10
+ "Speed_Mean",
11
+ "nGear_Mean",
12
+ "Throttle_Mean",
13
+ "Brake_Mean",
14
+ "DRS_Mean",
15
+ "X_Mean",
16
+ "Y_Mean",
17
+ "Z_Mean",
18
+ "DistanceToDriverAhead_Mean",
19
+ "AirTemp_Mean",
20
+ "TrackTemp_Mean",
21
+ "Humidity_Mean",
22
+ "Pressure_Mean",
23
+ "WindDirection_Mean",
24
+ "WindSpeed_Mean",
25
+ "DifferentialDistance_Sum",
26
+ "Distance",
27
+ "RelativeDistance",
28
+ "DriverAhead",
29
+ "TrackStatus",
30
+ "Stint",
31
+ "Compound",
32
+ "TyreLife",
33
+ "FreshTyre",
34
+ "SpeedI1",
35
+ "SpeedI2",
36
+ "SpeedFL",
37
+ "SpeedST",
38
+ "IsPersonalBest",
39
+ "Position",
40
+ "Rainfall",
41
+ "TyreLifeSquared",
42
+ "TrackAirTempDifference",
43
+ "WindX",
44
+ "WindY"
45
+ ],
46
+ "numeric_features": [
47
+ "LapNumber",
48
+ "DriverNumber",
49
+ "RPM_Mean",
50
+ "Speed_Mean",
51
+ "nGear_Mean",
52
+ "Throttle_Mean",
53
+ "Brake_Mean",
54
+ "DRS_Mean",
55
+ "X_Mean",
56
+ "Y_Mean",
57
+ "Z_Mean",
58
+ "DistanceToDriverAhead_Mean",
59
+ "AirTemp_Mean",
60
+ "TrackTemp_Mean",
61
+ "Humidity_Mean",
62
+ "Pressure_Mean",
63
+ "WindDirection_Mean",
64
+ "WindSpeed_Mean",
65
+ "DifferentialDistance_Sum",
66
+ "Distance",
67
+ "RelativeDistance",
68
+ "TrackStatus",
69
+ "Stint",
70
+ "TyreLife",
71
+ "FreshTyre",
72
+ "SpeedI1",
73
+ "SpeedI2",
74
+ "SpeedFL",
75
+ "SpeedST",
76
+ "IsPersonalBest",
77
+ "Position",
78
+ "Rainfall",
79
+ "TyreLifeSquared",
80
+ "TrackAirTempDifference",
81
+ "WindX",
82
+ "WindY"
83
+ ],
84
+ "categorical_features": [
85
+ "Driver",
86
+ "DriverAhead",
87
+ "Compound"
88
+ ],
89
+ "processed_feature_names": [
90
+ "numeric__LapNumber",
91
+ "numeric__DriverNumber",
92
+ "numeric__RPM_Mean",
93
+ "numeric__Speed_Mean",
94
+ "numeric__nGear_Mean",
95
+ "numeric__Throttle_Mean",
96
+ "numeric__Brake_Mean",
97
+ "numeric__DRS_Mean",
98
+ "numeric__X_Mean",
99
+ "numeric__Y_Mean",
100
+ "numeric__Z_Mean",
101
+ "numeric__DistanceToDriverAhead_Mean",
102
+ "numeric__AirTemp_Mean",
103
+ "numeric__TrackTemp_Mean",
104
+ "numeric__Humidity_Mean",
105
+ "numeric__Pressure_Mean",
106
+ "numeric__WindDirection_Mean",
107
+ "numeric__WindSpeed_Mean",
108
+ "numeric__DifferentialDistance_Sum",
109
+ "numeric__Distance",
110
+ "numeric__RelativeDistance",
111
+ "numeric__TrackStatus",
112
+ "numeric__Stint",
113
+ "numeric__TyreLife",
114
+ "numeric__FreshTyre",
115
+ "numeric__SpeedI1",
116
+ "numeric__SpeedI2",
117
+ "numeric__SpeedFL",
118
+ "numeric__SpeedST",
119
+ "numeric__IsPersonalBest",
120
+ "numeric__Position",
121
+ "numeric__Rainfall",
122
+ "numeric__TyreLifeSquared",
123
+ "numeric__TrackAirTempDifference",
124
+ "numeric__WindX",
125
+ "numeric__WindY",
126
+ "categorical__Driver_ALB",
127
+ "categorical__Driver_ALO",
128
+ "categorical__Driver_ANT",
129
+ "categorical__Driver_BEA",
130
+ "categorical__Driver_BOR",
131
+ "categorical__Driver_BOT",
132
+ "categorical__Driver_COL",
133
+ "categorical__Driver_GAS",
134
+ "categorical__Driver_HAD",
135
+ "categorical__Driver_HAM",
136
+ "categorical__Driver_HUL",
137
+ "categorical__Driver_LAW",
138
+ "categorical__Driver_LEC",
139
+ "categorical__Driver_LIN",
140
+ "categorical__Driver_NOR",
141
+ "categorical__Driver_OCO",
142
+ "categorical__Driver_PER",
143
+ "categorical__Driver_PIA",
144
+ "categorical__Driver_RUS",
145
+ "categorical__Driver_SAI",
146
+ "categorical__Driver_STR",
147
+ "categorical__Driver_VER",
148
+ "categorical__DriverAhead_1.0",
149
+ "categorical__DriverAhead_10.0",
150
+ "categorical__DriverAhead_11.0",
151
+ "categorical__DriverAhead_12.0",
152
+ "categorical__DriverAhead_14.0",
153
+ "categorical__DriverAhead_16.0",
154
+ "categorical__DriverAhead_18.0",
155
+ "categorical__DriverAhead_23.0",
156
+ "categorical__DriverAhead_27.0",
157
+ "categorical__DriverAhead_3.0",
158
+ "categorical__DriverAhead_30.0",
159
+ "categorical__DriverAhead_31.0",
160
+ "categorical__DriverAhead_41.0",
161
+ "categorical__DriverAhead_43.0",
162
+ "categorical__DriverAhead_44.0",
163
+ "categorical__DriverAhead_5.0",
164
+ "categorical__DriverAhead_55.0",
165
+ "categorical__DriverAhead_6.0",
166
+ "categorical__DriverAhead_63.0",
167
+ "categorical__DriverAhead_77.0",
168
+ "categorical__DriverAhead_81.0",
169
+ "categorical__DriverAhead_87.0",
170
+ "categorical__DriverAhead_UNKNOWN",
171
+ "categorical__Compound_HARD",
172
+ "categorical__Compound_INTERMEDIATE",
173
+ "categorical__Compound_MEDIUM",
174
+ "categorical__Compound_SOFT"
175
+ ],
176
+ "raw_feature_count": 39,
177
+ "processed_feature_count": 85,
178
+ "pipeline_version": "f1_lap_level_xgboost_v1"
179
+ }
backend/data/f1_live_winner_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d45b657b2f60cf0971b6a0e990cd8d0d668a28d98fecd9a86806f1545d50adbb
3
+ size 300178
backend/data/f1_live_winner_optuna_study.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d0b655a276cd9bdc23f2115c4f78d10c9d39584c3e60225db960ef9354332f42
3
+ size 38350
backend/data/feature_eng.py ADDED
@@ -0,0 +1,929 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # F1 MODEL-READY TRAINING DATASET
3
+ #
4
+ # INPUT:
5
+ # Compressed lap-level dataset
6
+ #
7
+ # OUTPUT:
8
+ # Clean dataset ready for XGBoost training
9
+ #
10
+ # ONE ROW =
11
+ # ONE RACE + ONE DRIVER + ONE LAP
12
+ #
13
+ # IMPORTANT:
14
+ # RaceDate is retained as metadata so the model-training
15
+ # script can perform race-level chronological splitting.
16
+ #
17
+ # RaceDate is NOT intended to be used as an XGBoost feature.
18
+ # ============================================================
19
+
20
+
21
+ import pandas as pd
22
+ import numpy as np
23
+ from pathlib import Path
24
+
25
+
26
+ # ============================================================
27
+ # CONFIGURATION
28
+ # ============================================================
29
+
30
+ INPUT_FILE = (
31
+ "C:\\Users\\Admin\\Desktop\\PitLane\\"
32
+ "F1_2026_compressed_merged.csv"
33
+ )
34
+
35
+ OUTPUT_FILE = (
36
+ "F1_2026_model_training_data.csv"
37
+ )
38
+
39
+
40
+ # ============================================================
41
+ # 1. LOAD DATA
42
+ # ============================================================
43
+
44
+ print("=" * 80)
45
+ print("F1 MODEL-READY DATASET CREATION")
46
+ print("=" * 80)
47
+
48
+
49
+ if not Path(INPUT_FILE).exists():
50
+
51
+ raise FileNotFoundError(
52
+ f"\nInput file not found:\n"
53
+ f"{INPUT_FILE}"
54
+ )
55
+
56
+
57
+ print("\nLoading compressed dataset...")
58
+
59
+
60
+ df = pd.read_csv(
61
+ INPUT_FILE,
62
+ low_memory=False
63
+ )
64
+
65
+
66
+ print(
67
+ f"Input shape: "
68
+ f"{df.shape[0]:,} rows × "
69
+ f"{df.shape[1]} columns"
70
+ )
71
+
72
+
73
+ # ============================================================
74
+ # 2. CHECK REQUIRED COLUMNS
75
+ # ============================================================
76
+
77
+ required_columns = [
78
+ "RaceDate",
79
+ "Driver",
80
+ "LapNumber",
81
+ "Winner"
82
+ ]
83
+
84
+
85
+ missing_columns = [
86
+ column
87
+ for column in required_columns
88
+ if column not in df.columns
89
+ ]
90
+
91
+
92
+ if missing_columns:
93
+
94
+ raise ValueError(
95
+ "Required columns are missing:\n"
96
+ + "\n".join(missing_columns)
97
+ )
98
+
99
+
100
+ # ============================================================
101
+ # 3. SORT DATA
102
+ # ============================================================
103
+
104
+ df["RaceDate"] = pd.to_datetime(
105
+ df["RaceDate"],
106
+ errors="coerce"
107
+ )
108
+
109
+
110
+ if df["RaceDate"].isna().any():
111
+
112
+ invalid_dates = (
113
+ df["RaceDate"]
114
+ .isna()
115
+ .sum()
116
+ )
117
+
118
+ print(
119
+ f"\nWARNING: {invalid_dates:,} rows "
120
+ f"have invalid RaceDate values."
121
+ )
122
+
123
+
124
+ df = (
125
+ df
126
+ .sort_values(
127
+ [
128
+ "RaceDate",
129
+ "Driver",
130
+ "LapNumber"
131
+ ],
132
+ kind="stable"
133
+ )
134
+ .reset_index(
135
+ drop=True
136
+ )
137
+ )
138
+
139
+
140
+ # ============================================================
141
+ # 4. TARGET CLEANUP
142
+ # ============================================================
143
+
144
+ df["Winner"] = pd.to_numeric(
145
+ df["Winner"],
146
+ errors="coerce"
147
+ )
148
+
149
+
150
+ # Keep only valid targets
151
+
152
+ df = df[
153
+ df["Winner"].isin([0, 1])
154
+ ].copy()
155
+
156
+
157
+ df["Winner"] = (
158
+ df["Winner"]
159
+ .astype(int)
160
+ )
161
+
162
+
163
+ # ============================================================
164
+ # 5. VERIFY ONE WINNER PER RACE
165
+ # ============================================================
166
+
167
+ winner_check = (
168
+ df
169
+ .groupby("RaceDate")["Winner"]
170
+ .sum()
171
+ )
172
+
173
+
174
+ invalid_races = (
175
+ winner_check[
176
+ winner_check != 1
177
+ ]
178
+ )
179
+
180
+
181
+ if not invalid_races.empty:
182
+
183
+ print("\nWARNING:")
184
+ print(
185
+ "These races do not contain exactly "
186
+ "one Winner=1:"
187
+ )
188
+
189
+ print(
190
+ invalid_races
191
+ )
192
+
193
+ else:
194
+
195
+ print(
196
+ "\nWinner validation passed:"
197
+ " exactly one winner per race."
198
+ )
199
+
200
+
201
+ # ============================================================
202
+ # 6. CONVERT CATEGORICAL COLUMNS
203
+ # ============================================================
204
+
205
+ # These should NOT be treated as continuous numbers.
206
+ #
207
+ # The XGBoost training pipeline can later encode
208
+ # these columns appropriately.
209
+
210
+ categorical_columns = [
211
+ "Driver",
212
+ "Team_Last",
213
+ "Compound_Last",
214
+ "DriverAhead_Last"
215
+ ]
216
+
217
+
218
+ for column in categorical_columns:
219
+
220
+ if column in df.columns:
221
+
222
+ df[column] = (
223
+ df[column]
224
+ .fillna("UNKNOWN")
225
+ .astype(str)
226
+ )
227
+
228
+
229
+ # ============================================================
230
+ # 7. DRIVER NUMBER
231
+ # ============================================================
232
+
233
+ # DriverNumber_Last is an identifier,
234
+ # not a meaningful continuous measurement.
235
+ #
236
+ # Convert it to string so the training pipeline
237
+ # can treat it categorically.
238
+
239
+ if "DriverNumber_Last" in df.columns:
240
+
241
+ df["DriverNumber_Last"] = (
242
+ df["DriverNumber_Last"]
243
+ .fillna(-1)
244
+ .astype(str)
245
+ )
246
+
247
+
248
+ # ============================================================
249
+ # 8. DROP REDUNDANT / BOOKKEEPING COLUMNS
250
+ # ============================================================
251
+
252
+ # IMPORTANT:
253
+ #
254
+ # RaceDate is intentionally NOT dropped.
255
+ #
256
+ # It is retained as metadata because the model-training
257
+ # script needs it to split complete races chronologically.
258
+ #
259
+ # RaceDate itself should NOT be passed to XGBoost as a
260
+ # predictive feature.
261
+
262
+ DROP_COLUMNS = [
263
+
264
+ # --------------------------------------------------------
265
+ # Compression bookkeeping
266
+ # --------------------------------------------------------
267
+
268
+ "TelemetryRecords",
269
+
270
+ # --------------------------------------------------------
271
+ # Duplicate identifiers
272
+ # --------------------------------------------------------
273
+
274
+ "Date_Last",
275
+ "Driver_Last",
276
+ "DriverNumber_Last",
277
+ "LapNumber_Last",
278
+ "Team_Last",
279
+
280
+ # --------------------------------------------------------
281
+ # Redundant timestamp
282
+ # --------------------------------------------------------
283
+
284
+ "Time_Last",
285
+
286
+ # --------------------------------------------------------
287
+ # Raw last-value field that is not required
288
+ # --------------------------------------------------------
289
+
290
+ "LapStartDate_Last"
291
+ ]
292
+
293
+
294
+ df = df.drop(
295
+ columns=[
296
+ column
297
+ for column in DROP_COLUMNS
298
+ if column in df.columns
299
+ ],
300
+ errors="ignore"
301
+ )
302
+
303
+
304
+ # ============================================================
305
+ # 9. RENAME USEFUL _LAST COLUMNS
306
+ # ============================================================
307
+
308
+ RENAME_COLUMNS = {
309
+
310
+ "Stint_Last":
311
+ "Stint",
312
+
313
+ "Compound_Last":
314
+ "Compound",
315
+
316
+ "TyreLife_Last":
317
+ "TyreLife",
318
+
319
+ "FreshTyre_Last":
320
+ "FreshTyre",
321
+
322
+ "LapTime_Last":
323
+ "LapTime",
324
+
325
+ "Sector1Time_Last":
326
+ "Sector1Time",
327
+
328
+ "Sector2Time_Last":
329
+ "Sector2Time",
330
+
331
+ "Sector3Time_Last":
332
+ "Sector3Time",
333
+
334
+ "Sector1SessionTime_Last":
335
+ "Sector1SessionTime",
336
+
337
+ "Sector2SessionTime_Last":
338
+ "Sector2SessionTime",
339
+
340
+ "Sector3SessionTime_Last":
341
+ "Sector3SessionTime",
342
+
343
+ "SpeedI1_Last":
344
+ "SpeedI1",
345
+
346
+ "SpeedI2_Last":
347
+ "SpeedI2",
348
+
349
+ "SpeedFL_Last":
350
+ "SpeedFL",
351
+
352
+ "SpeedST_Last":
353
+ "SpeedST",
354
+
355
+ "IsPersonalBest_Last":
356
+ "IsPersonalBest",
357
+
358
+ "Position_Last":
359
+ "Position",
360
+
361
+ "PitInTime_Last":
362
+ "PitInTime",
363
+
364
+ "PitOutTime_Last":
365
+ "PitOutTime",
366
+
367
+ "SessionTime_Last":
368
+ "SessionTime",
369
+
370
+ "Distance_Last":
371
+ "Distance",
372
+
373
+ "RelativeDistance_Last":
374
+ "RelativeDistance",
375
+
376
+ "DriverAhead_Last":
377
+ "DriverAhead",
378
+
379
+ "TrackStatus_Last":
380
+ "TrackStatus",
381
+
382
+ "Rainfall_Any":
383
+ "Rainfall"
384
+ }
385
+
386
+
387
+ df = df.rename(
388
+ columns={
389
+ old: new
390
+ for old, new in RENAME_COLUMNS.items()
391
+ if old in df.columns
392
+ }
393
+ )
394
+
395
+
396
+ # ============================================================
397
+ # 10. REMOVE CURRENT-LAP FIELDS THAT ARE NOT NEEDED
398
+ # ============================================================
399
+
400
+ DROP_TIME_FEATURES = [
401
+
402
+ "Time_Last",
403
+ "LapStartTime_Last",
404
+ "LapStartDate_Last"
405
+ ]
406
+
407
+
408
+ df = df.drop(
409
+ columns=[
410
+ column
411
+ for column in DROP_TIME_FEATURES
412
+ if column in df.columns
413
+ ],
414
+ errors="ignore"
415
+ )
416
+
417
+
418
+ # ============================================================
419
+ # 11. NUMERIC CONVERSION
420
+ # ============================================================
421
+
422
+ numeric_columns = [
423
+
424
+ "RPM_Mean",
425
+ "Speed_Mean",
426
+ "nGear_Mean",
427
+ "Throttle_Mean",
428
+ "Brake_Mean",
429
+ "DRS_Mean",
430
+
431
+ "X_Mean",
432
+ "Y_Mean",
433
+ "Z_Mean",
434
+
435
+ "DistanceToDriverAhead_Mean",
436
+
437
+ "AirTemp_Mean",
438
+ "TrackTemp_Mean",
439
+ "Humidity_Mean",
440
+ "Pressure_Mean",
441
+ "WindDirection_Mean",
442
+ "WindSpeed_Mean",
443
+
444
+ "DifferentialDistance_Sum",
445
+
446
+ "SessionTime",
447
+ "Distance",
448
+ "RelativeDistance",
449
+
450
+ "TrackStatus",
451
+
452
+ "LapNumber",
453
+ "Stint",
454
+ "TyreLife",
455
+
456
+ "LapTime",
457
+ "Sector1Time",
458
+ "Sector2Time",
459
+ "Sector3Time",
460
+
461
+ "Sector1SessionTime",
462
+ "Sector2SessionTime",
463
+ "Sector3SessionTime",
464
+
465
+ "SpeedI1",
466
+ "SpeedI2",
467
+ "SpeedFL",
468
+ "SpeedST",
469
+
470
+ "IsPersonalBest",
471
+ "Position",
472
+
473
+ "PitInTime",
474
+ "PitOutTime",
475
+
476
+ "Rainfall"
477
+ ]
478
+
479
+
480
+ for column in numeric_columns:
481
+
482
+ if column in df.columns:
483
+
484
+ df[column] = pd.to_numeric(
485
+ df[column],
486
+ errors="coerce"
487
+ )
488
+
489
+
490
+ # ============================================================
491
+ # 12. BOOLEAN CLEANUP
492
+ # ============================================================
493
+
494
+ for column in [
495
+ "FreshTyre"
496
+ ]:
497
+
498
+ if column in df.columns:
499
+
500
+ if not pd.api.types.is_numeric_dtype(
501
+ df[column]
502
+ ):
503
+
504
+ df[column] = (
505
+ df[column]
506
+ .astype(str)
507
+ .str.lower()
508
+ .map(
509
+ {
510
+ "true": 1,
511
+ "false": 0,
512
+ "1": 1,
513
+ "0": 0
514
+ }
515
+ )
516
+ )
517
+
518
+ else:
519
+
520
+ df[column] = pd.to_numeric(
521
+ df[column],
522
+ errors="coerce"
523
+ )
524
+
525
+
526
+ # ============================================================
527
+ # 13. ADD SIMPLE LAP-LEVEL FEATURES
528
+ # ============================================================
529
+
530
+ # ------------------------------------------------------------
531
+ # Race progress
532
+ #
533
+ # IMPORTANT:
534
+ #
535
+ # Do NOT calculate:
536
+ #
537
+ # LapNumber / max(LapNumber)
538
+ #
539
+ # because max(LapNumber) is only known after the race.
540
+ #
541
+ # LapNumber itself is safe.
542
+ # ------------------------------------------------------------
543
+
544
+
545
+ # ------------------------------------------------------------
546
+ # Tyre degradation proxy
547
+ # ------------------------------------------------------------
548
+
549
+ if "TyreLife" in df.columns:
550
+
551
+ df["TyreLifeSquared"] = (
552
+ df["TyreLife"] ** 2
553
+ )
554
+
555
+
556
+ # ------------------------------------------------------------
557
+ # Track vs air temperature
558
+ # ------------------------------------------------------------
559
+
560
+ if (
561
+ "TrackTemp_Mean" in df.columns
562
+ and
563
+ "AirTemp_Mean" in df.columns
564
+ ):
565
+
566
+ df["TrackAirTempDifference"] = (
567
+ df["TrackTemp_Mean"]
568
+ -
569
+ df["AirTemp_Mean"]
570
+ )
571
+
572
+
573
+ # ------------------------------------------------------------
574
+ # Wind vector
575
+ # ------------------------------------------------------------
576
+
577
+ if (
578
+ "WindSpeed_Mean" in df.columns
579
+ and
580
+ "WindDirection_Mean" in df.columns
581
+ ):
582
+
583
+ wind_radians = np.deg2rad(
584
+ df["WindDirection_Mean"]
585
+ )
586
+
587
+
588
+ df["WindX"] = (
589
+ df["WindSpeed_Mean"]
590
+ *
591
+ np.cos(wind_radians)
592
+ )
593
+
594
+
595
+ df["WindY"] = (
596
+ df["WindSpeed_Mean"]
597
+ *
598
+ np.sin(wind_radians)
599
+ )
600
+
601
+
602
+ # ============================================================
603
+ # 14. REMOVE COLUMNS WE KNOW SHOULD NOT BE FEATURES
604
+ # ============================================================
605
+
606
+ FINAL_DROP = [
607
+
608
+ # --------------------------------------------------------
609
+ # Original bookkeeping
610
+ # --------------------------------------------------------
611
+
612
+ "Date_Last",
613
+
614
+ # --------------------------------------------------------
615
+ # Raw pit timestamps
616
+ # --------------------------------------------------------
617
+
618
+ "PitInTime",
619
+ "PitOutTime",
620
+
621
+ # --------------------------------------------------------
622
+ # Absolute session timestamps
623
+ # --------------------------------------------------------
624
+
625
+ "SessionTime",
626
+
627
+ "Sector1SessionTime",
628
+ "Sector2SessionTime",
629
+ "Sector3SessionTime"
630
+ ]
631
+
632
+
633
+ df = df.drop(
634
+ columns=[
635
+ column
636
+ for column in FINAL_DROP
637
+ if column in df.columns
638
+ ],
639
+ errors="ignore"
640
+ )
641
+
642
+
643
+ # ============================================================
644
+ # 15. HANDLE INFINITE VALUES
645
+ # ============================================================
646
+
647
+ df = df.replace(
648
+ [np.inf, -np.inf],
649
+ np.nan
650
+ )
651
+
652
+
653
+ # ============================================================
654
+ # 16. REMOVE COMPLETELY EMPTY FEATURES
655
+ # ============================================================
656
+
657
+ empty_columns = [
658
+
659
+ column
660
+ for column in df.columns
661
+
662
+ if (
663
+ column != "Winner"
664
+ and
665
+ column != "RaceDate"
666
+ and
667
+ df[column].isna().all()
668
+ )
669
+ ]
670
+
671
+
672
+ if empty_columns:
673
+
674
+ print(
675
+ "\nDropping completely empty columns:"
676
+ )
677
+
678
+ for column in empty_columns:
679
+
680
+ print(
681
+ f" {column}"
682
+ )
683
+
684
+ df = df.drop(
685
+ columns=empty_columns
686
+ )
687
+
688
+
689
+ # ============================================================
690
+ # 17. FINAL COLUMN ORDER
691
+ # ============================================================
692
+
693
+ # Keep RaceDate as metadata.
694
+ #
695
+ # Keep:
696
+ #
697
+ # RaceDate
698
+ # Driver
699
+ # LapNumber
700
+ # Winner
701
+ #
702
+ # first so the training pipeline can easily identify them.
703
+
704
+ preferred_columns = [
705
+
706
+ "RaceDate",
707
+ "Driver",
708
+ "LapNumber",
709
+ "Winner"
710
+ ]
711
+
712
+
713
+ preferred_columns = [
714
+ column
715
+ for column in preferred_columns
716
+ if column in df.columns
717
+ ]
718
+
719
+
720
+ remaining_columns = [
721
+ column
722
+ for column in df.columns
723
+ if column not in preferred_columns
724
+ ]
725
+
726
+
727
+ df = df[
728
+ preferred_columns
729
+ +
730
+ remaining_columns
731
+ ]
732
+
733
+
734
+ # ============================================================
735
+ # 18. FINAL VALIDATION
736
+ # ============================================================
737
+
738
+ print("\n")
739
+ print("=" * 80)
740
+ print("FINAL VALIDATION")
741
+ print("=" * 80)
742
+
743
+
744
+ print(
745
+ f"\nRows:"
746
+ f" {len(df):,}"
747
+ )
748
+
749
+
750
+ print(
751
+ f"Columns:"
752
+ f" {len(df.columns)}"
753
+ )
754
+
755
+
756
+ # ------------------------------------------------------------
757
+ # Race count
758
+ # ------------------------------------------------------------
759
+
760
+ if "RaceDate" in df.columns:
761
+
762
+ print(
763
+ f"Unique races:"
764
+ f" {df['RaceDate'].nunique():,}"
765
+ )
766
+
767
+
768
+ # ------------------------------------------------------------
769
+ # Driver count
770
+ # ------------------------------------------------------------
771
+
772
+ if "Driver" in df.columns:
773
+
774
+ print(
775
+ f"Unique drivers:"
776
+ f" {df['Driver'].nunique():,}"
777
+ )
778
+
779
+
780
+ # ------------------------------------------------------------
781
+ # Winner count
782
+ # ------------------------------------------------------------
783
+
784
+ print(
785
+ f"Winner=1 rows:"
786
+ f" {(df['Winner'] == 1).sum():,}"
787
+ )
788
+
789
+
790
+ print(
791
+ f"Winner=0 rows:"
792
+ f" {(df['Winner'] == 0).sum():,}"
793
+ )
794
+
795
+
796
+ # ------------------------------------------------------------
797
+ # Validate one winner per race again
798
+ # ------------------------------------------------------------
799
+
800
+ if "RaceDate" in df.columns:
801
+
802
+ final_winner_check = (
803
+ df
804
+ .groupby("RaceDate")["Winner"]
805
+ .sum()
806
+ )
807
+
808
+ invalid_final_races = (
809
+ final_winner_check[
810
+ final_winner_check != 1
811
+ ]
812
+ )
813
+
814
+ if invalid_final_races.empty:
815
+
816
+ print(
817
+ "\nFinal winner validation:"
818
+ " PASSED"
819
+ )
820
+
821
+ else:
822
+
823
+ print(
824
+ "\nFinal winner validation:"
825
+ " WARNING"
826
+ )
827
+
828
+ print(
829
+ invalid_final_races
830
+ )
831
+
832
+
833
+ # ------------------------------------------------------------
834
+ # Validate unique Race + Driver + Lap
835
+ # ------------------------------------------------------------
836
+
837
+ if all(
838
+ column in df.columns
839
+ for column in [
840
+ "RaceDate",
841
+ "Driver",
842
+ "LapNumber"
843
+ ]
844
+ ):
845
+
846
+ duplicate_laps = (
847
+ df
848
+ .duplicated(
849
+ subset=[
850
+ "RaceDate",
851
+ "Driver",
852
+ "LapNumber"
853
+ ]
854
+ )
855
+ .sum()
856
+ )
857
+
858
+ print(
859
+ f"Duplicate Race+Driver+Lap rows:"
860
+ f" {duplicate_laps:,}"
861
+ )
862
+
863
+
864
+ # ============================================================
865
+ # 19. SAVE
866
+ # ============================================================
867
+
868
+ df.to_csv(
869
+ OUTPUT_FILE,
870
+ index=False
871
+ )
872
+
873
+
874
+ # ============================================================
875
+ # 20. SHOW FINAL FEATURES
876
+ # ============================================================
877
+
878
+ print("\n")
879
+ print("=" * 80)
880
+ print("FINAL TRAINING DATASET COLUMNS")
881
+ print("=" * 80)
882
+
883
+
884
+ for number, column in enumerate(
885
+ df.columns,
886
+ start=1
887
+ ):
888
+
889
+ print(
890
+ f"{number:03d}. {column}"
891
+ )
892
+
893
+
894
+ # ============================================================
895
+ # 21. FINAL SUMMARY
896
+ # ============================================================
897
+
898
+ print("\n")
899
+ print("=" * 80)
900
+ print("DONE")
901
+ print("=" * 80)
902
+
903
+
904
+ print(
905
+ f"\nSaved to:"
906
+ f"\n{Path(OUTPUT_FILE).resolve()}"
907
+ )
908
+
909
+
910
+ print(
911
+ "\nIMPORTANT:"
912
+ )
913
+
914
+
915
+ print(
916
+ "RaceDate is retained as metadata for "
917
+ "race-level chronological splitting."
918
+ )
919
+
920
+
921
+ print(
922
+ "RaceDate must NOT be passed directly "
923
+ "to the XGBoost model as a predictive feature."
924
+ )
925
+
926
+
927
+ print(
928
+ "\nDataset is ready for the model-training pipeline."
929
+ )
backend/data/model_training.py ADDED
@@ -0,0 +1,2050 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # F1 LIVE WINNER PREDICTION
3
+ # COMPRESSED LAP-LEVEL DATA
4
+ # XGBOOST + OPTUNA
5
+ #
6
+ # ENVIRONMENT:
7
+ # VS CODE / LOCAL PYTHON
8
+ #
9
+ # INPUT:
10
+ # F1_2026_compressed_merged.csv
11
+ #
12
+ # OUTPUT:
13
+ # F1_Model/
14
+ # f1_live_winner_model.pkl
15
+ # f1_live_winner_best_params.json
16
+ # f1_live_winner_optuna_study.pkl
17
+ # f1_live_winner_feature_importance.csv
18
+ # f1_live_winner_feature_schema.json
19
+ # ============================================================
20
+
21
+
22
+ # ============================================================
23
+ # 1. INSTALL REQUIRED PACKAGES
24
+ # ============================================================
25
+
26
+ # Run this ONCE in your VS Code terminal if required:
27
+ #
28
+ # pip install pandas numpy scikit-learn xgboost optuna joblib
29
+ #
30
+ # Do NOT put the pip command inside the Python script.
31
+
32
+
33
+ # ============================================================
34
+ # 2. IMPORTS
35
+ # ============================================================
36
+
37
+ import json
38
+ import warnings
39
+ from pathlib import Path
40
+
41
+ import joblib
42
+ import numpy as np
43
+ import optuna
44
+ import pandas as pd
45
+ import xgboost as xgb
46
+
47
+ from sklearn.compose import ColumnTransformer
48
+ from sklearn.impute import SimpleImputer
49
+ from sklearn.metrics import (
50
+ accuracy_score,
51
+ log_loss,
52
+ roc_auc_score
53
+ )
54
+ from sklearn.pipeline import Pipeline
55
+ from sklearn.preprocessing import OneHotEncoder
56
+
57
+
58
+ warnings.filterwarnings("ignore")
59
+
60
+
61
+ # ============================================================
62
+ # 3. CONFIGURATION
63
+ # ============================================================
64
+
65
+ # ------------------------------------------------------------
66
+ # INPUT DATASET
67
+ #
68
+ # Keep the CSV in the same folder as this Python script.
69
+ # ------------------------------------------------------------
70
+
71
+ DATASET_PATH = "C:\\Users\\Admin\\Desktop\\PitLane\\F1_2026_model_training_data.csv"
72
+
73
+
74
+ # ------------------------------------------------------------
75
+ # OUTPUT DIRECTORY
76
+ # ------------------------------------------------------------
77
+
78
+ OUTPUT_DIR = "F1_Model"
79
+
80
+ Path(
81
+ OUTPUT_DIR
82
+ ).mkdir(
83
+ parents=True,
84
+ exist_ok=True
85
+ )
86
+
87
+
88
+ # ------------------------------------------------------------
89
+ # OUTPUT FILES
90
+ # ------------------------------------------------------------
91
+
92
+ MODEL_OUTPUT = (
93
+ f"{OUTPUT_DIR}/f1_live_winner_model.pkl"
94
+ )
95
+
96
+ PARAMS_OUTPUT = (
97
+ f"{OUTPUT_DIR}/f1_live_winner_best_params.json"
98
+ )
99
+
100
+ STUDY_OUTPUT = (
101
+ f"{OUTPUT_DIR}/f1_live_winner_optuna_study.pkl"
102
+ )
103
+
104
+ FEATURE_IMPORTANCE_OUTPUT = (
105
+ f"{OUTPUT_DIR}/f1_live_winner_feature_importance.csv"
106
+ )
107
+
108
+ FEATURE_SCHEMA_OUTPUT = (
109
+ f"{OUTPUT_DIR}/f1_live_winner_feature_schema.json"
110
+ )
111
+
112
+
113
+ # ------------------------------------------------------------
114
+ # GENERAL SETTINGS
115
+ # ------------------------------------------------------------
116
+
117
+ RANDOM_STATE = 42
118
+
119
+ # Increase this after the pipeline is working correctly.
120
+ N_TRIALS = 50
121
+
122
+ TARGET_COLUMN = "Winner"
123
+
124
+ RACE_COLUMN = "RaceDate"
125
+
126
+ DRIVER_COLUMN = "Driver"
127
+
128
+
129
+ # ============================================================
130
+ # 4. LOAD DATASET
131
+ # ============================================================
132
+
133
+ print("=" * 80)
134
+ print("F1 LIVE WINNER MODEL TRAINING")
135
+ print("=" * 80)
136
+
137
+ dataset_path = Path(
138
+ DATASET_PATH
139
+ )
140
+
141
+ if not dataset_path.exists():
142
+
143
+ raise FileNotFoundError(
144
+ "\nDataset not found:\n"
145
+ f"{dataset_path.resolve()}\n\n"
146
+ "Place the CSV in the same folder as this script "
147
+ "or change DATASET_PATH."
148
+ )
149
+
150
+
151
+ print("\nLoading compressed dataset...")
152
+
153
+ df = pd.read_csv(
154
+ dataset_path,
155
+ low_memory=False
156
+ )
157
+
158
+ print(
159
+ f"Rows : {len(df):,}"
160
+ )
161
+
162
+ print(
163
+ f"Columns : {len(df.columns)}"
164
+ )
165
+
166
+
167
+ # ============================================================
168
+ # 5. REQUIRED COLUMN VALIDATION
169
+ # ============================================================
170
+
171
+ required_columns = [
172
+ RACE_COLUMN,
173
+ DRIVER_COLUMN,
174
+ TARGET_COLUMN
175
+ ]
176
+
177
+ missing_columns = [
178
+ column
179
+ for column in required_columns
180
+ if column not in df.columns
181
+ ]
182
+
183
+ if missing_columns:
184
+
185
+ raise ValueError(
186
+ "\nMissing required columns:\n"
187
+ + "\n".join(missing_columns)
188
+ )
189
+
190
+
191
+ # ============================================================
192
+ # 6. PARSE RACE DATE
193
+ # ============================================================
194
+
195
+ print("\nPreparing race dates...")
196
+
197
+ df[RACE_COLUMN] = pd.to_datetime(
198
+ df[RACE_COLUMN],
199
+ errors="coerce"
200
+ )
201
+
202
+ invalid_dates = (
203
+ df[RACE_COLUMN]
204
+ .isna()
205
+ .sum()
206
+ )
207
+
208
+ if invalid_dates > 0:
209
+
210
+ print(
211
+ f"WARNING: {invalid_dates:,} rows have invalid RaceDate."
212
+ )
213
+
214
+ df = df[
215
+ df[RACE_COLUMN].notna()
216
+ ].copy()
217
+
218
+
219
+ # ============================================================
220
+ # 7. CLEAN DRIVER
221
+ # ============================================================
222
+
223
+ df[DRIVER_COLUMN] = (
224
+ df[DRIVER_COLUMN]
225
+ .fillna("UNKNOWN")
226
+ .astype(str)
227
+ )
228
+
229
+
230
+ # ============================================================
231
+ # 8. CLEAN TARGET
232
+ # ============================================================
233
+
234
+ df[TARGET_COLUMN] = pd.to_numeric(
235
+ df[TARGET_COLUMN],
236
+ errors="coerce"
237
+ )
238
+
239
+ invalid_targets = (
240
+ ~df[TARGET_COLUMN].isin([0, 1])
241
+ )
242
+
243
+ if invalid_targets.any():
244
+
245
+ print(
246
+ f"WARNING: Removing "
247
+ f"{invalid_targets.sum():,} rows "
248
+ "with invalid Winner values."
249
+ )
250
+
251
+ df = df[
252
+ ~invalid_targets
253
+ ].copy()
254
+
255
+ df[TARGET_COLUMN] = (
256
+ df[TARGET_COLUMN]
257
+ .astype(int)
258
+ )
259
+
260
+
261
+ # ============================================================
262
+ # 9. SORT DATA CHRONOLOGICALLY
263
+ # ============================================================
264
+
265
+ sort_columns = [
266
+ RACE_COLUMN,
267
+ DRIVER_COLUMN
268
+ ]
269
+
270
+ if "LapNumber" in df.columns:
271
+
272
+ sort_columns.append(
273
+ "LapNumber"
274
+ )
275
+
276
+ df = (
277
+ df
278
+ .sort_values(
279
+ sort_columns,
280
+ kind="stable"
281
+ )
282
+ .reset_index(
283
+ drop=True
284
+ )
285
+ )
286
+
287
+
288
+ # ============================================================
289
+ # 10. CHECK AVAILABLE RACES
290
+ # ============================================================
291
+
292
+ race_dates = (
293
+ df[RACE_COLUMN]
294
+ .drop_duplicates()
295
+ .sort_values()
296
+ .to_numpy()
297
+ )
298
+
299
+ number_of_races = len(
300
+ race_dates
301
+ )
302
+
303
+ print(
304
+ f"\nUnique races: "
305
+ f"{number_of_races}"
306
+ )
307
+
308
+ if number_of_races < 5:
309
+
310
+ raise ValueError(
311
+ f"Only {number_of_races} races were found.\n"
312
+ "You need more races for a meaningful "
313
+ "train/validation/test split."
314
+ )
315
+
316
+
317
+ # ============================================================
318
+ # 11. VALIDATE ONE WINNER PER RACE
319
+ # ============================================================
320
+
321
+ print("\n")
322
+ print("=" * 80)
323
+ print("VALIDATING TARGET")
324
+ print("=" * 80)
325
+
326
+ winner_counts = (
327
+ df
328
+ .groupby(
329
+ RACE_COLUMN
330
+ )[TARGET_COLUMN]
331
+ .sum()
332
+ )
333
+
334
+ invalid_races = winner_counts[
335
+ winner_counts != 1
336
+ ]
337
+
338
+ if not invalid_races.empty:
339
+
340
+ print(
341
+ "\nWARNING:"
342
+ )
343
+
344
+ print(
345
+ "The following races do not have exactly "
346
+ "one Winner=1:"
347
+ )
348
+
349
+ for race, count in (
350
+ invalid_races.items()
351
+ ):
352
+
353
+ print(
354
+ f" {race.date()} -> "
355
+ f"{count}"
356
+ )
357
+
358
+ else:
359
+
360
+ print(
361
+ "Target validation PASSED."
362
+ )
363
+
364
+ print(
365
+ "Every race has exactly one Winner=1."
366
+ )
367
+
368
+
369
+ # ============================================================
370
+ # 12. CHRONOLOGICAL RACE SPLIT
371
+ # ============================================================
372
+
373
+ print("\n")
374
+ print("=" * 80)
375
+ print("CREATING CHRONOLOGICAL RACE SPLIT")
376
+ print("=" * 80)
377
+
378
+
379
+ # ------------------------------------------------------------
380
+ # 70% TRAIN
381
+ # 15% VALIDATION
382
+ # 15% TEST
383
+ #
384
+ # Split by WHOLE RACES, never individual rows.
385
+ # ------------------------------------------------------------
386
+
387
+ train_count = max(
388
+ 1,
389
+ int(
390
+ number_of_races * 0.70
391
+ )
392
+ )
393
+
394
+ validation_count = max(
395
+ 1,
396
+ int(
397
+ number_of_races * 0.15
398
+ )
399
+ )
400
+
401
+ # Guarantee test races
402
+ if (
403
+ train_count
404
+ + validation_count
405
+ >= number_of_races
406
+ ):
407
+
408
+ train_count = (
409
+ number_of_races - 2
410
+ )
411
+
412
+ validation_count = 1
413
+
414
+
415
+ train_races = race_dates[
416
+ :train_count
417
+ ]
418
+
419
+ validation_races = race_dates[
420
+ train_count:
421
+ train_count + validation_count
422
+ ]
423
+
424
+ test_races = race_dates[
425
+ train_count + validation_count:
426
+ ]
427
+
428
+
429
+ print(
430
+ f"\nTraining races : "
431
+ f"{len(train_races)}"
432
+ )
433
+
434
+ print(
435
+ f"Validation races : "
436
+ f"{len(validation_races)}"
437
+ )
438
+
439
+ print(
440
+ f"Test races : "
441
+ f"{len(test_races)}"
442
+ )
443
+
444
+
445
+ print("\nTRAINING RACES")
446
+
447
+ for race in train_races:
448
+
449
+ print(
450
+ f" {pd.Timestamp(race).date()}"
451
+ )
452
+
453
+
454
+ print("\nVALIDATION RACES")
455
+
456
+ for race in validation_races:
457
+
458
+ print(
459
+ f" {pd.Timestamp(race).date()}"
460
+ )
461
+
462
+
463
+ print("\nTEST RACES")
464
+
465
+ for race in test_races:
466
+
467
+ print(
468
+ f" {pd.Timestamp(race).date()}"
469
+ )
470
+
471
+
472
+ # ============================================================
473
+ # 13. CREATE SPLIT DATASETS
474
+ # ============================================================
475
+
476
+ train_df = df[
477
+ df[RACE_COLUMN]
478
+ .isin(train_races)
479
+ ].copy()
480
+
481
+ validation_df = df[
482
+ df[RACE_COLUMN]
483
+ .isin(validation_races)
484
+ ].copy()
485
+
486
+ test_df = df[
487
+ df[RACE_COLUMN]
488
+ .isin(test_races)
489
+ ].copy()
490
+
491
+
492
+ print("\nSplit sizes:")
493
+
494
+ print(
495
+ f"Training : "
496
+ f"{len(train_df):,}"
497
+ )
498
+
499
+ print(
500
+ f"Validation : "
501
+ f"{len(validation_df):,}"
502
+ )
503
+
504
+ print(
505
+ f"Test : "
506
+ f"{len(test_df):,}"
507
+ )
508
+
509
+
510
+ # ============================================================
511
+ # 14. RACE-BALANCED SAMPLE WEIGHTS
512
+ # ============================================================
513
+
514
+ def create_race_balanced_weights(
515
+ dataframe
516
+ ):
517
+
518
+ """
519
+ Each driver receives approximately equal total weight
520
+ within each race.
521
+
522
+ This prevents a driver/race with more telemetry/lap rows
523
+ from dominating the training objective simply because it
524
+ has more observations.
525
+ """
526
+
527
+ weights = pd.Series(
528
+ 0.0,
529
+ index=dataframe.index,
530
+ dtype=float
531
+ )
532
+
533
+ for race_date, race_group in (
534
+ dataframe.groupby(
535
+ RACE_COLUMN
536
+ )
537
+ ):
538
+
539
+ drivers = (
540
+ race_group[
541
+ DRIVER_COLUMN
542
+ ]
543
+ .nunique()
544
+ )
545
+
546
+ if drivers <= 0:
547
+ continue
548
+
549
+ for driver, driver_group in (
550
+ race_group.groupby(
551
+ DRIVER_COLUMN
552
+ )
553
+ ):
554
+
555
+ row_count = len(
556
+ driver_group
557
+ )
558
+
559
+ if row_count <= 0:
560
+ continue
561
+
562
+ weight = (
563
+ 1.0
564
+ /
565
+ drivers
566
+ /
567
+ row_count
568
+ )
569
+
570
+ weights.loc[
571
+ driver_group.index
572
+ ] = weight
573
+
574
+ mean_weight = (
575
+ weights.mean()
576
+ )
577
+
578
+ if mean_weight > 0:
579
+
580
+ weights = (
581
+ weights
582
+ /
583
+ mean_weight
584
+ )
585
+
586
+ return weights.to_numpy()
587
+
588
+
589
+ train_weights = (
590
+ create_race_balanced_weights(
591
+ train_df
592
+ )
593
+ )
594
+
595
+ validation_weights = (
596
+ create_race_balanced_weights(
597
+ validation_df
598
+ )
599
+ )
600
+
601
+ test_weights = (
602
+ create_race_balanced_weights(
603
+ test_df
604
+ )
605
+ )
606
+
607
+
608
+ # ============================================================
609
+ # 15. PREPARE MODEL INPUT
610
+ # ============================================================
611
+
612
+ def prepare_X(
613
+ dataframe
614
+ ):
615
+
616
+ data = dataframe.copy()
617
+
618
+ # --------------------------------------------------------
619
+ # TARGET / METADATA / LEAKAGE
620
+ # --------------------------------------------------------
621
+
622
+ drop_columns = [
623
+
624
+ # Target
625
+ TARGET_COLUMN,
626
+
627
+ # Used only for chronological splitting
628
+ RACE_COLUMN,
629
+
630
+ # Defensive protection against accidental leakage
631
+ "winning_driver_number",
632
+ "WinningDriver",
633
+ "WinningDriverName",
634
+
635
+ # Race/session metadata
636
+ "RaceID",
637
+ "session_key",
638
+ "meeting_key",
639
+ "location",
640
+ "country_name",
641
+ "RoundNumber",
642
+ "EventName",
643
+
644
+ # Internal fields
645
+ "_RaceDate",
646
+ "RaceDate"
647
+ ]
648
+
649
+ data = data.drop(
650
+ columns=[
651
+ column
652
+ for column in drop_columns
653
+ if column in data.columns
654
+ ],
655
+ errors="ignore"
656
+ )
657
+
658
+ return data
659
+
660
+
661
+ X_train = prepare_X(
662
+ train_df
663
+ )
664
+
665
+ X_validation = prepare_X(
666
+ validation_df
667
+ )
668
+
669
+ X_test = prepare_X(
670
+ test_df
671
+ )
672
+
673
+ y_train = (
674
+ train_df[TARGET_COLUMN]
675
+ )
676
+
677
+ y_validation = (
678
+ validation_df[TARGET_COLUMN]
679
+ )
680
+
681
+ y_test = (
682
+ test_df[TARGET_COLUMN]
683
+ )
684
+
685
+
686
+ # ============================================================
687
+ # 16. FORCE IDENTICAL FEATURE ORDER
688
+ # ============================================================
689
+
690
+ feature_columns = (
691
+ X_train.columns.tolist()
692
+ )
693
+
694
+ X_validation = (
695
+ X_validation
696
+ .reindex(
697
+ columns=feature_columns
698
+ )
699
+ )
700
+
701
+ X_test = (
702
+ X_test
703
+ .reindex(
704
+ columns=feature_columns
705
+ )
706
+ )
707
+
708
+
709
+ print("\n")
710
+ print("=" * 80)
711
+ print("MODEL FEATURE SCHEMA")
712
+ print("=" * 80)
713
+
714
+ print(
715
+ f"\nRaw model features: "
716
+ f"{len(feature_columns)}"
717
+ )
718
+
719
+
720
+ # ============================================================
721
+ # 17. IDENTIFY NUMERIC / CATEGORICAL FEATURES
722
+ # ============================================================
723
+
724
+ numeric_features = (
725
+ X_train
726
+ .select_dtypes(
727
+ include=[
728
+ "number",
729
+ "bool"
730
+ ]
731
+ )
732
+ .columns
733
+ .tolist()
734
+ )
735
+
736
+ categorical_features = [
737
+ column
738
+ for column in feature_columns
739
+ if column not in numeric_features
740
+ ]
741
+
742
+
743
+ print(
744
+ f"Numeric features : "
745
+ f"{len(numeric_features)}"
746
+ )
747
+
748
+ print(
749
+ f"Categorical features : "
750
+ f"{len(categorical_features)}"
751
+ )
752
+
753
+
754
+ # ============================================================
755
+ # 18. PREPROCESSING PIPELINE
756
+ # ============================================================
757
+
758
+ print(
759
+ "\nCreating preprocessing pipeline..."
760
+ )
761
+
762
+
763
+ numeric_pipeline = Pipeline(
764
+ steps=[
765
+ (
766
+ "imputer",
767
+ SimpleImputer(
768
+ strategy="median"
769
+ )
770
+ )
771
+ ]
772
+ )
773
+
774
+
775
+ categorical_pipeline = Pipeline(
776
+ steps=[
777
+ (
778
+ "imputer",
779
+ SimpleImputer(
780
+ strategy="most_frequent"
781
+ )
782
+ ),
783
+ (
784
+ "encoder",
785
+ OneHotEncoder(
786
+ handle_unknown="ignore",
787
+ sparse_output=True
788
+ )
789
+ )
790
+ ]
791
+ )
792
+
793
+
794
+ preprocessor = ColumnTransformer(
795
+ transformers=[
796
+ (
797
+ "numeric",
798
+ numeric_pipeline,
799
+ numeric_features
800
+ ),
801
+ (
802
+ "categorical",
803
+ categorical_pipeline,
804
+ categorical_features
805
+ )
806
+ ],
807
+ remainder="drop"
808
+ )
809
+
810
+
811
+ # ============================================================
812
+ # 19. FIT PREPROCESSOR ONLY ON TRAINING DATA
813
+ # ============================================================
814
+
815
+ print(
816
+ "Fitting preprocessing pipeline "
817
+ "on training data..."
818
+ )
819
+
820
+
821
+ X_train_processed = (
822
+ preprocessor
823
+ .fit_transform(
824
+ X_train
825
+ )
826
+ )
827
+
828
+ X_validation_processed = (
829
+ preprocessor
830
+ .transform(
831
+ X_validation
832
+ )
833
+ )
834
+
835
+ X_test_processed = (
836
+ preprocessor
837
+ .transform(
838
+ X_test
839
+ )
840
+ )
841
+
842
+
843
+ print(
844
+ f"Processed training features: "
845
+ f"{X_train_processed.shape[1]}"
846
+ )
847
+
848
+
849
+ # ============================================================
850
+ # 20. OPTUNA OBJECTIVE
851
+ # ============================================================
852
+
853
+ def objective(
854
+ trial
855
+ ):
856
+
857
+ # --------------------------------------------------------
858
+ # Hyperparameter search space
859
+ # --------------------------------------------------------
860
+
861
+ params = {
862
+
863
+ "objective":
864
+ "binary:logistic",
865
+
866
+ "eval_metric":
867
+ "logloss",
868
+
869
+ "tree_method":
870
+ "hist",
871
+
872
+ "random_state":
873
+ RANDOM_STATE,
874
+
875
+ # ----------------------------------------------------
876
+ # Tree depth / complexity
877
+ # ----------------------------------------------------
878
+
879
+ "max_depth":
880
+ trial.suggest_int(
881
+ "max_depth",
882
+ 3,
883
+ 10
884
+ ),
885
+
886
+ "min_child_weight":
887
+ trial.suggest_int(
888
+ "min_child_weight",
889
+ 1,
890
+ 20
891
+ ),
892
+
893
+ # ----------------------------------------------------
894
+ # Boosting
895
+ # ----------------------------------------------------
896
+
897
+ "n_estimators":
898
+ trial.suggest_int(
899
+ "n_estimators",
900
+ 200,
901
+ 1200
902
+ ),
903
+
904
+ "learning_rate":
905
+ trial.suggest_float(
906
+ "learning_rate",
907
+ 0.005,
908
+ 0.15,
909
+ log=True
910
+ ),
911
+
912
+ # ----------------------------------------------------
913
+ # Sampling
914
+ # ----------------------------------------------------
915
+
916
+ "subsample":
917
+ trial.suggest_float(
918
+ "subsample",
919
+ 0.65,
920
+ 1.0
921
+ ),
922
+
923
+ "colsample_bytree":
924
+ trial.suggest_float(
925
+ "colsample_bytree",
926
+ 0.65,
927
+ 1.0
928
+ ),
929
+
930
+ # ----------------------------------------------------
931
+ # Regularization
932
+ # ----------------------------------------------------
933
+
934
+ "gamma":
935
+ trial.suggest_float(
936
+ "gamma",
937
+ 0.0,
938
+ 5.0
939
+ ),
940
+
941
+ "reg_alpha":
942
+ trial.suggest_float(
943
+ "reg_alpha",
944
+ 1e-8,
945
+ 10.0,
946
+ log=True
947
+ ),
948
+
949
+ "reg_lambda":
950
+ trial.suggest_float(
951
+ "reg_lambda",
952
+ 1e-8,
953
+ 20.0,
954
+ log=True
955
+ )
956
+ }
957
+
958
+ model = xgb.XGBClassifier(
959
+ **params
960
+ )
961
+
962
+ model.fit(
963
+ X_train_processed,
964
+ y_train,
965
+
966
+ sample_weight=train_weights,
967
+
968
+ eval_set=[
969
+ (
970
+ X_validation_processed,
971
+ y_validation
972
+ )
973
+ ],
974
+
975
+ verbose=False
976
+ )
977
+
978
+ validation_probabilities = (
979
+ model
980
+ .predict_proba(
981
+ X_validation_processed
982
+ )[:, 1]
983
+ )
984
+
985
+ # Optimize probability quality rather than
986
+ # simple classification accuracy.
987
+ score = log_loss(
988
+ y_validation,
989
+ validation_probabilities,
990
+ labels=[0, 1],
991
+ sample_weight=validation_weights
992
+ )
993
+
994
+ return score
995
+
996
+
997
+ # ============================================================
998
+ # 21. RUN OPTUNA
999
+ # ============================================================
1000
+
1001
+ print("\n")
1002
+ print("=" * 80)
1003
+ print("OPTUNA HYPERPARAMETER OPTIMIZATION")
1004
+ print("=" * 80)
1005
+
1006
+ print(
1007
+ f"\nNumber of trials: "
1008
+ f"{N_TRIALS}"
1009
+ )
1010
+
1011
+
1012
+ study = optuna.create_study(
1013
+ study_name=(
1014
+ "F1_Live_Winner_XGBoost"
1015
+ ),
1016
+ direction="minimize",
1017
+ sampler=(
1018
+ optuna.samplers.TPESampler(
1019
+ seed=RANDOM_STATE
1020
+ )
1021
+ )
1022
+ )
1023
+
1024
+
1025
+ study.optimize(
1026
+ objective,
1027
+ n_trials=N_TRIALS,
1028
+ show_progress_bar=True
1029
+ )
1030
+
1031
+
1032
+ # ============================================================
1033
+ # 22. EXTRACT BEST PARAMETERS
1034
+ # ============================================================
1035
+
1036
+ best_params = (
1037
+ study
1038
+ .best_params
1039
+ .copy()
1040
+ )
1041
+
1042
+ best_params.update(
1043
+ {
1044
+ "objective":
1045
+ "binary:logistic",
1046
+
1047
+ "eval_metric":
1048
+ "logloss",
1049
+
1050
+ "tree_method":
1051
+ "hist",
1052
+
1053
+ "random_state":
1054
+ RANDOM_STATE
1055
+ }
1056
+ )
1057
+
1058
+
1059
+ print("\n")
1060
+ print("=" * 80)
1061
+ print("OPTUNA COMPLETE")
1062
+ print("=" * 80)
1063
+
1064
+ print(
1065
+ f"\nBest validation log loss: "
1066
+ f"{study.best_value:.6f}"
1067
+ )
1068
+
1069
+ print("\nBest parameters:")
1070
+
1071
+ for parameter, value in (
1072
+ study.best_params.items()
1073
+ ):
1074
+
1075
+ print(
1076
+ f" {parameter}: {value}"
1077
+ )
1078
+
1079
+
1080
+ # ============================================================
1081
+ # 23. TRAIN FINAL MODEL
1082
+ # ============================================================
1083
+
1084
+ print("\n")
1085
+ print("=" * 80)
1086
+ print("TRAINING FINAL XGBOOST MODEL")
1087
+ print("=" * 80)
1088
+
1089
+
1090
+ final_model = xgb.XGBClassifier(
1091
+ **best_params
1092
+ )
1093
+
1094
+
1095
+ final_model.fit(
1096
+ X_train_processed,
1097
+ y_train,
1098
+
1099
+ sample_weight=train_weights,
1100
+
1101
+ eval_set=[
1102
+ (
1103
+ X_validation_processed,
1104
+ y_validation
1105
+ )
1106
+ ],
1107
+
1108
+ verbose=False
1109
+ )
1110
+
1111
+
1112
+ # ============================================================
1113
+ # 24. GENERATE PREDICTIONS
1114
+ # ============================================================
1115
+
1116
+ validation_probabilities = (
1117
+ final_model
1118
+ .predict_proba(
1119
+ X_validation_processed
1120
+ )[:, 1]
1121
+ )
1122
+
1123
+ test_probabilities = (
1124
+ final_model
1125
+ .predict_proba(
1126
+ X_test_processed
1127
+ )[:, 1]
1128
+ )
1129
+
1130
+ # ============================================================
1131
+ # TEST RACE AUDIT
1132
+ # ============================================================
1133
+
1134
+ audit_df = test_df.copy()
1135
+
1136
+ audit_df["PredictedProbability"] = test_probabilities
1137
+
1138
+ audit_results = []
1139
+
1140
+ for race_date, race_group in audit_df.groupby("RaceDate"):
1141
+
1142
+ race_group = race_group.copy()
1143
+
1144
+ # --------------------------------------------------------
1145
+ # Driver predicted most likely to win
1146
+ # --------------------------------------------------------
1147
+
1148
+ predicted_idx = (
1149
+ race_group[
1150
+ "PredictedProbability"
1151
+ ].idxmax()
1152
+ )
1153
+
1154
+ predicted_row = race_group.loc[
1155
+ predicted_idx
1156
+ ]
1157
+
1158
+ # --------------------------------------------------------
1159
+ # Actual winner
1160
+ # --------------------------------------------------------
1161
+
1162
+ actual_rows = race_group[
1163
+ race_group["Winner"] == 1
1164
+ ]
1165
+
1166
+ if actual_rows.empty:
1167
+ continue
1168
+
1169
+ actual_row = actual_rows.iloc[0]
1170
+
1171
+ # --------------------------------------------------------
1172
+ # Rank every driver in this race
1173
+ # --------------------------------------------------------
1174
+
1175
+ race_group["PredictionRank"] = (
1176
+ race_group[
1177
+ "PredictedProbability"
1178
+ ]
1179
+ .rank(
1180
+ ascending=False,
1181
+ method="min"
1182
+ )
1183
+ )
1184
+
1185
+ actual_winner_index = (
1186
+ actual_rows.index[0]
1187
+ )
1188
+
1189
+ actual_rank = (
1190
+ race_group.loc[
1191
+ actual_winner_index,
1192
+ "PredictionRank"
1193
+ ]
1194
+ )
1195
+
1196
+ # --------------------------------------------------------
1197
+ # Save result
1198
+ # --------------------------------------------------------
1199
+
1200
+ audit_results.append({
1201
+
1202
+ "RaceDate":
1203
+ race_date,
1204
+
1205
+ "ActualWinner":
1206
+ actual_row["Driver"],
1207
+
1208
+ "ActualWinnerProbability":
1209
+ actual_row[
1210
+ "PredictedProbability"
1211
+ ],
1212
+
1213
+ "ActualWinnerRank":
1214
+ int(actual_rank),
1215
+
1216
+ "PredictedWinner":
1217
+ predicted_row["Driver"],
1218
+
1219
+ "PredictedWinnerProbability":
1220
+ predicted_row[
1221
+ "PredictedProbability"
1222
+ ],
1223
+
1224
+ "Correct":
1225
+ (
1226
+ predicted_row["Driver"]
1227
+ ==
1228
+ actual_row["Driver"]
1229
+ )
1230
+ })
1231
+
1232
+
1233
+ # ============================================================
1234
+ # CREATE AUDIT TABLE
1235
+ # ============================================================
1236
+
1237
+ audit_results = pd.DataFrame(
1238
+ audit_results
1239
+ )
1240
+
1241
+
1242
+ print("\n")
1243
+ print("=" * 100)
1244
+ print("TEST RACE AUDIT")
1245
+ print("=" * 100)
1246
+
1247
+
1248
+ if audit_results.empty:
1249
+
1250
+ print(
1251
+ "No test-race results available."
1252
+ )
1253
+
1254
+ else:
1255
+
1256
+ print(
1257
+ audit_results.to_string(
1258
+ index=False
1259
+ )
1260
+ )
1261
+
1262
+
1263
+ # ============================================================
1264
+ # SAVE AUDIT
1265
+ # ============================================================
1266
+
1267
+ audit_results.to_csv(
1268
+ "F1_Model/test_race_audit.csv",
1269
+ index=False
1270
+ )
1271
+
1272
+
1273
+ # ============================================================
1274
+ # ACTUAL WINNER RANK DISTRIBUTION
1275
+ # ============================================================
1276
+
1277
+ if not audit_results.empty:
1278
+
1279
+ print("\n")
1280
+ print("=" * 100)
1281
+ print("ACTUAL WINNER PREDICTION RANK")
1282
+ print("=" * 100)
1283
+
1284
+ print(
1285
+ audit_results[
1286
+ "ActualWinnerRank"
1287
+ ]
1288
+ .value_counts()
1289
+ .sort_index()
1290
+ )
1291
+
1292
+
1293
+ # ============================================================
1294
+ # TOP-3 ACCURACY
1295
+ # ============================================================
1296
+
1297
+ if not audit_results.empty:
1298
+
1299
+ top3_accuracy = (
1300
+ audit_results[
1301
+ "ActualWinnerRank"
1302
+ ]
1303
+ <= 3
1304
+ ).mean()
1305
+
1306
+ print(
1307
+ f"\nTop-3 race winner accuracy: "
1308
+ f"{top3_accuracy:.4f}"
1309
+ )
1310
+
1311
+
1312
+ # Binary predictions at 0.5
1313
+ validation_predictions = (
1314
+ validation_probabilities >= 0.5
1315
+ ).astype(int)
1316
+
1317
+ test_predictions = (
1318
+ test_probabilities >= 0.5
1319
+ ).astype(int)
1320
+
1321
+
1322
+ # ============================================================
1323
+ # 25. STANDARD METRICS
1324
+ # ============================================================
1325
+
1326
+ validation_logloss = log_loss(
1327
+ y_validation,
1328
+ validation_probabilities,
1329
+ labels=[0, 1],
1330
+ sample_weight=validation_weights
1331
+ )
1332
+
1333
+ validation_auc = roc_auc_score(
1334
+ y_validation,
1335
+ validation_probabilities,
1336
+ sample_weight=validation_weights
1337
+ )
1338
+
1339
+ validation_accuracy = accuracy_score(
1340
+ y_validation,
1341
+ validation_predictions
1342
+ )
1343
+
1344
+
1345
+ test_logloss = log_loss(
1346
+ y_test,
1347
+ test_probabilities,
1348
+ labels=[0, 1],
1349
+ sample_weight=test_weights
1350
+ )
1351
+
1352
+ test_auc = roc_auc_score(
1353
+ y_test,
1354
+ test_probabilities,
1355
+ sample_weight=test_weights
1356
+ )
1357
+
1358
+ test_accuracy = accuracy_score(
1359
+ y_test,
1360
+ test_predictions
1361
+ )
1362
+
1363
+
1364
+ print("\n")
1365
+ print("=" * 80)
1366
+ print("STANDARD METRICS")
1367
+ print("=" * 80)
1368
+
1369
+ print("\nVALIDATION")
1370
+
1371
+ print(
1372
+ f"Log Loss : "
1373
+ f"{validation_logloss:.6f}"
1374
+ )
1375
+
1376
+ print(
1377
+ f"ROC AUC : "
1378
+ f"{validation_auc:.6f}"
1379
+ )
1380
+
1381
+ print(
1382
+ f"Accuracy : "
1383
+ f"{validation_accuracy:.6f}"
1384
+ )
1385
+
1386
+
1387
+ print("\nUNSEEN TEST RACES")
1388
+
1389
+ print(
1390
+ f"Log Loss : "
1391
+ f"{test_logloss:.6f}"
1392
+ )
1393
+
1394
+ print(
1395
+ f"ROC AUC : "
1396
+ f"{test_auc:.6f}"
1397
+ )
1398
+
1399
+ print(
1400
+ f"Accuracy : "
1401
+ f"{test_accuracy:.6f}"
1402
+ )
1403
+
1404
+
1405
+ # ============================================================
1406
+ # 26. RACE-LEVEL EVALUATION
1407
+ # ============================================================
1408
+
1409
+ def evaluate_race_winners(
1410
+ dataframe,
1411
+ probabilities
1412
+ ):
1413
+
1414
+ evaluation_columns = [
1415
+ RACE_COLUMN,
1416
+ DRIVER_COLUMN,
1417
+ TARGET_COLUMN
1418
+ ]
1419
+
1420
+ if "DriverNumber" in dataframe.columns:
1421
+
1422
+ evaluation_columns.append(
1423
+ "DriverNumber"
1424
+ )
1425
+
1426
+ evaluation = dataframe[
1427
+ evaluation_columns
1428
+ ].copy()
1429
+
1430
+ evaluation[
1431
+ "WinProbability"
1432
+ ] = probabilities
1433
+
1434
+ results = []
1435
+
1436
+ for race_date, race_group in (
1437
+ evaluation
1438
+ .groupby(
1439
+ RACE_COLUMN
1440
+ )
1441
+ ):
1442
+
1443
+ # ----------------------------------------------------
1444
+ # Predicted winner = highest probability
1445
+ # ----------------------------------------------------
1446
+
1447
+ predicted_index = (
1448
+ race_group[
1449
+ "WinProbability"
1450
+ ].idxmax()
1451
+ )
1452
+
1453
+ predicted_row = (
1454
+ race_group.loc[
1455
+ predicted_index
1456
+ ]
1457
+ )
1458
+
1459
+ # ----------------------------------------------------
1460
+ # Actual winner
1461
+ # ----------------------------------------------------
1462
+
1463
+ actual_rows = race_group[
1464
+ race_group[
1465
+ TARGET_COLUMN
1466
+ ] == 1
1467
+ ]
1468
+
1469
+ if actual_rows.empty:
1470
+ continue
1471
+
1472
+ actual_row = (
1473
+ actual_rows.iloc[0]
1474
+ )
1475
+
1476
+ result = {
1477
+
1478
+ "RaceDate":
1479
+ race_date,
1480
+
1481
+ "PredictedWinner":
1482
+ predicted_row[
1483
+ DRIVER_COLUMN
1484
+ ],
1485
+
1486
+ "PredictedProbability":
1487
+ float(
1488
+ predicted_row[
1489
+ "WinProbability"
1490
+ ]
1491
+ ),
1492
+
1493
+ "ActualWinner":
1494
+ actual_row[
1495
+ DRIVER_COLUMN
1496
+ ],
1497
+
1498
+ "Correct":
1499
+ (
1500
+ predicted_row[
1501
+ DRIVER_COLUMN
1502
+ ]
1503
+ ==
1504
+ actual_row[
1505
+ DRIVER_COLUMN
1506
+ ]
1507
+ )
1508
+ }
1509
+
1510
+ if "DriverNumber" in evaluation.columns:
1511
+
1512
+ result[
1513
+ "PredictedDriverNumber"
1514
+ ] = predicted_row[
1515
+ "DriverNumber"
1516
+ ]
1517
+
1518
+ results.append(
1519
+ result
1520
+ )
1521
+
1522
+ results_df = pd.DataFrame(
1523
+ results
1524
+ )
1525
+
1526
+ if results_df.empty:
1527
+
1528
+ return (
1529
+ results_df,
1530
+ np.nan
1531
+ )
1532
+
1533
+ accuracy = (
1534
+ results_df[
1535
+ "Correct"
1536
+ ]
1537
+ .mean()
1538
+ )
1539
+
1540
+ return (
1541
+ results_df,
1542
+ accuracy
1543
+ )
1544
+
1545
+
1546
+ # ============================================================
1547
+ # 27. VALIDATION RACE ACCURACY
1548
+ # ============================================================
1549
+
1550
+ (
1551
+ validation_race_results,
1552
+ validation_race_accuracy
1553
+ ) = evaluate_race_winners(
1554
+ validation_df,
1555
+ validation_probabilities
1556
+ )
1557
+
1558
+
1559
+ # ============================================================
1560
+ # 28. TEST RACE ACCURACY
1561
+ # ============================================================
1562
+
1563
+ (
1564
+ test_race_results,
1565
+ test_race_accuracy
1566
+ ) = evaluate_race_winners(
1567
+ test_df,
1568
+ test_probabilities
1569
+ )
1570
+
1571
+
1572
+ print("\n")
1573
+ print("=" * 80)
1574
+ print("RACE-LEVEL WINNER PERFORMANCE")
1575
+ print("=" * 80)
1576
+
1577
+ print(
1578
+ f"\nValidation race winner accuracy:"
1579
+ f" {validation_race_accuracy:.4f}"
1580
+ )
1581
+
1582
+ print(
1583
+ f"Test race winner accuracy:"
1584
+ f" {test_race_accuracy:.4f}"
1585
+ )
1586
+
1587
+
1588
+ # ============================================================
1589
+ # 29. SHOW TEST RESULTS
1590
+ # ============================================================
1591
+
1592
+ if not test_race_results.empty:
1593
+
1594
+ print("\n")
1595
+ print(
1596
+ "UNSEEN TEST RACE RESULTS"
1597
+ )
1598
+
1599
+ print(
1600
+ test_race_results
1601
+ .sort_values(
1602
+ "RaceDate"
1603
+ )
1604
+ .to_string(
1605
+ index=False
1606
+ )
1607
+ )
1608
+
1609
+
1610
+ # ============================================================
1611
+ # 30. FEATURE IMPORTANCE
1612
+ # ============================================================
1613
+
1614
+ try:
1615
+
1616
+ processed_feature_names = (
1617
+ preprocessor
1618
+ .get_feature_names_out()
1619
+ .tolist()
1620
+ )
1621
+
1622
+ except Exception:
1623
+
1624
+ processed_feature_names = []
1625
+
1626
+
1627
+ if processed_feature_names:
1628
+
1629
+ feature_importance_df = pd.DataFrame(
1630
+ {
1631
+ "Feature":
1632
+ processed_feature_names,
1633
+
1634
+ "Importance":
1635
+ final_model
1636
+ .feature_importances_
1637
+ }
1638
+ )
1639
+
1640
+ feature_importance_df = (
1641
+ feature_importance_df
1642
+ .sort_values(
1643
+ "Importance",
1644
+ ascending=False
1645
+ )
1646
+ .reset_index(
1647
+ drop=True
1648
+ )
1649
+ )
1650
+
1651
+ print("\n")
1652
+ print("=" * 80)
1653
+ print("TOP 30 FEATURES")
1654
+ print("=" * 80)
1655
+
1656
+ print(
1657
+ feature_importance_df
1658
+ .head(30)
1659
+ .to_string(
1660
+ index=False
1661
+ )
1662
+ )
1663
+
1664
+ feature_importance_df.to_csv(
1665
+ FEATURE_IMPORTANCE_OUTPUT,
1666
+ index=False
1667
+ )
1668
+
1669
+ print(
1670
+ f"\nFeature importance saved:"
1671
+ f"\n{FEATURE_IMPORTANCE_OUTPUT}"
1672
+ )
1673
+
1674
+
1675
+ # ============================================================
1676
+ # 31. SAVE FEATURE SCHEMA
1677
+ # ============================================================
1678
+
1679
+ feature_schema = {
1680
+
1681
+ "target":
1682
+ TARGET_COLUMN,
1683
+
1684
+ "race_column":
1685
+ RACE_COLUMN,
1686
+
1687
+ "driver_column":
1688
+ DRIVER_COLUMN,
1689
+
1690
+ "model_features":
1691
+ feature_columns,
1692
+
1693
+ "numeric_features":
1694
+ numeric_features,
1695
+
1696
+ "categorical_features":
1697
+ categorical_features,
1698
+
1699
+ "processed_feature_names":
1700
+ processed_feature_names,
1701
+
1702
+ "raw_feature_count":
1703
+ len(feature_columns),
1704
+
1705
+ "processed_feature_count":
1706
+ len(processed_feature_names),
1707
+
1708
+ "pipeline_version":
1709
+ "f1_lap_level_xgboost_v1"
1710
+ }
1711
+
1712
+
1713
+ with open(
1714
+ FEATURE_SCHEMA_OUTPUT,
1715
+ "w",
1716
+ encoding="utf-8"
1717
+ ) as file:
1718
+
1719
+ json.dump(
1720
+ feature_schema,
1721
+ file,
1722
+ indent=4
1723
+ )
1724
+
1725
+
1726
+ # ============================================================
1727
+ # 32. BUILD MODEL BUNDLE
1728
+ # ============================================================
1729
+
1730
+ model_bundle = {
1731
+
1732
+ # --------------------------------------------------------
1733
+ # Model
1734
+ # --------------------------------------------------------
1735
+
1736
+ "model":
1737
+ final_model,
1738
+
1739
+ # --------------------------------------------------------
1740
+ # Preprocessor
1741
+ # --------------------------------------------------------
1742
+
1743
+ "preprocessor":
1744
+ preprocessor,
1745
+
1746
+ # --------------------------------------------------------
1747
+ # EXACT FEATURE ORDER
1748
+ # --------------------------------------------------------
1749
+
1750
+ "feature_columns":
1751
+ feature_columns,
1752
+
1753
+ # --------------------------------------------------------
1754
+ # FEATURE TYPES
1755
+ # --------------------------------------------------------
1756
+
1757
+ "numeric_features":
1758
+ numeric_features,
1759
+
1760
+ "categorical_features":
1761
+ categorical_features,
1762
+
1763
+ # --------------------------------------------------------
1764
+ # ENCODED FEATURE NAMES
1765
+ # --------------------------------------------------------
1766
+
1767
+ "processed_feature_names":
1768
+ processed_feature_names,
1769
+
1770
+ # --------------------------------------------------------
1771
+ # TARGET
1772
+ # --------------------------------------------------------
1773
+
1774
+ "target_column":
1775
+ TARGET_COLUMN,
1776
+
1777
+ # --------------------------------------------------------
1778
+ # BEST OPTUNA PARAMETERS
1779
+ # --------------------------------------------------------
1780
+
1781
+ "best_params":
1782
+ best_params,
1783
+
1784
+ # --------------------------------------------------------
1785
+ # RACE SPLIT INFORMATION
1786
+ # --------------------------------------------------------
1787
+
1788
+ "training_races":
1789
+ [
1790
+ str(
1791
+ pd.Timestamp(
1792
+ race
1793
+ ).date()
1794
+ )
1795
+ for race in train_races
1796
+ ],
1797
+
1798
+ "validation_races":
1799
+ [
1800
+ str(
1801
+ pd.Timestamp(
1802
+ race
1803
+ ).date()
1804
+ )
1805
+ for race in validation_races
1806
+ ],
1807
+
1808
+ "test_races":
1809
+ [
1810
+ str(
1811
+ pd.Timestamp(
1812
+ race
1813
+ ).date()
1814
+ )
1815
+ for race in test_races
1816
+ ],
1817
+
1818
+ # --------------------------------------------------------
1819
+ # VALIDATION METRICS
1820
+ # --------------------------------------------------------
1821
+
1822
+ "validation_logloss":
1823
+ float(
1824
+ validation_logloss
1825
+ ),
1826
+
1827
+ "validation_auc":
1828
+ float(
1829
+ validation_auc
1830
+ ),
1831
+
1832
+ "validation_accuracy":
1833
+ float(
1834
+ validation_accuracy
1835
+ ),
1836
+
1837
+ "validation_race_accuracy":
1838
+ (
1839
+ float(
1840
+ validation_race_accuracy
1841
+ )
1842
+ if not pd.isna(
1843
+ validation_race_accuracy
1844
+ )
1845
+ else None
1846
+ ),
1847
+
1848
+ # --------------------------------------------------------
1849
+ # TEST METRICS
1850
+ # --------------------------------------------------------
1851
+
1852
+ "test_logloss":
1853
+ float(
1854
+ test_logloss
1855
+ ),
1856
+
1857
+ "test_auc":
1858
+ float(
1859
+ test_auc
1860
+ ),
1861
+
1862
+ "test_accuracy":
1863
+ float(
1864
+ test_accuracy
1865
+ ),
1866
+
1867
+ "test_race_accuracy":
1868
+ (
1869
+ float(
1870
+ test_race_accuracy
1871
+ )
1872
+ if not pd.isna(
1873
+ test_race_accuracy
1874
+ )
1875
+ else None
1876
+ ),
1877
+
1878
+ # --------------------------------------------------------
1879
+ # VERSION
1880
+ # --------------------------------------------------------
1881
+
1882
+ "xgboost_version":
1883
+ xgb.__version__,
1884
+
1885
+ "pipeline_version":
1886
+ "f1_lap_level_xgboost_v1",
1887
+
1888
+ "random_state":
1889
+ RANDOM_STATE
1890
+ }
1891
+
1892
+
1893
+ # ============================================================
1894
+ # 33. SAVE MODEL
1895
+ # ============================================================
1896
+
1897
+ print("\n")
1898
+ print("=" * 80)
1899
+ print("SAVING MODEL")
1900
+ print("=" * 80)
1901
+
1902
+
1903
+ joblib.dump(
1904
+ model_bundle,
1905
+ MODEL_OUTPUT
1906
+ )
1907
+
1908
+ print(
1909
+ f"\nModel saved to:"
1910
+ f"\n{MODEL_OUTPUT}"
1911
+ )
1912
+
1913
+
1914
+ # ============================================================
1915
+ # 34. SAVE BEST PARAMETERS
1916
+ # ============================================================
1917
+
1918
+ with open(
1919
+ PARAMS_OUTPUT,
1920
+ "w",
1921
+ encoding="utf-8"
1922
+ ) as file:
1923
+
1924
+ json.dump(
1925
+ best_params,
1926
+ file,
1927
+ indent=4
1928
+ )
1929
+
1930
+ print(
1931
+ f"\nBest parameters saved to:"
1932
+ f"\n{PARAMS_OUTPUT}"
1933
+ )
1934
+
1935
+
1936
+ # ============================================================
1937
+ # 35. SAVE OPTUNA STUDY
1938
+ # ============================================================
1939
+
1940
+ joblib.dump(
1941
+ study,
1942
+ STUDY_OUTPUT
1943
+ )
1944
+
1945
+ print(
1946
+ f"\nOptuna study saved to:"
1947
+ f"\n{STUDY_OUTPUT}"
1948
+ )
1949
+
1950
+
1951
+ # ============================================================
1952
+ # 36. VERIFY MODEL FILE
1953
+ # ============================================================
1954
+
1955
+ if not Path(
1956
+ MODEL_OUTPUT
1957
+ ).exists():
1958
+
1959
+ raise RuntimeError(
1960
+ "Model file was not created."
1961
+ )
1962
+
1963
+
1964
+ # ============================================================
1965
+ # 37. FINAL SUMMARY
1966
+ # ============================================================
1967
+
1968
+ print("\n")
1969
+ print("=" * 80)
1970
+ print("TRAINING COMPLETE")
1971
+ print("=" * 80)
1972
+
1973
+ print(
1974
+ f"\nInput dataset:"
1975
+ f"\n{dataset_path.resolve()}"
1976
+ )
1977
+
1978
+ print(
1979
+ f"\nTotal rows:"
1980
+ f" {len(df):,}"
1981
+ )
1982
+
1983
+ print(
1984
+ f"Total races:"
1985
+ f" {number_of_races}"
1986
+ )
1987
+
1988
+ print(
1989
+ f"Raw model features:"
1990
+ f" {len(feature_columns)}"
1991
+ )
1992
+
1993
+ print(
1994
+ f"Encoded features:"
1995
+ f" {len(processed_feature_names)}"
1996
+ )
1997
+
1998
+ print(
1999
+ f"\nTest ROC AUC:"
2000
+ f" {test_auc:.4f}"
2001
+ )
2002
+
2003
+ print(
2004
+ f"Test Log Loss:"
2005
+ f" {test_logloss:.4f}"
2006
+ )
2007
+
2008
+ print(
2009
+ f"Test row accuracy:"
2010
+ f" {test_accuracy:.4f}"
2011
+ )
2012
+
2013
+ print(
2014
+ f"Test race winner accuracy:"
2015
+ f" {test_race_accuracy:.4f}"
2016
+ )
2017
+
2018
+ print(
2019
+ "\nSaved artifacts:"
2020
+ )
2021
+
2022
+ print(
2023
+ f" Model:"
2024
+ f"\n {MODEL_OUTPUT}"
2025
+ )
2026
+
2027
+ print(
2028
+ f" Parameters:"
2029
+ f"\n {PARAMS_OUTPUT}"
2030
+ )
2031
+
2032
+ print(
2033
+ f" Optuna study:"
2034
+ f"\n {STUDY_OUTPUT}"
2035
+ )
2036
+
2037
+ print(
2038
+ f" Feature importance:"
2039
+ f"\n {FEATURE_IMPORTANCE_OUTPUT}"
2040
+ )
2041
+
2042
+ print(
2043
+ f" Feature schema:"
2044
+ f"\n {FEATURE_SCHEMA_OUTPUT}"
2045
+ )
2046
+
2047
+ print("\n")
2048
+ print("=" * 80)
2049
+ print("READY FOR LIVE INFERENCE")
2050
+ print("=" * 80)
backend/data/test_race_audit.csv ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ RaceDate,ActualWinner,ActualWinnerProbability,ActualWinnerRank,PredictedWinner,PredictedWinnerProbability,Correct
2
+ 2026-07-19,ANT,0.818568,16,ANT,0.86089206,True
3
+ 2026-07-26,NOR,0.108918205,106,ANT,0.65481,False
4
+ 2026-08-23,NOR,0.103961535,115,ANT,0.85160017,False
backend/docs/feature-contract.md ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Telemetry-to-model feature contract
2
+
3
+ ## Audit boundary
4
+
5
+ The repository contains the current compressor, current feature engineer, saved
6
+ schema JSON, and saved model bundle. It does **not** contain the original
7
+ 54-column CSV, its header, the original offline compressor source, or a separate
8
+ original feature-engineering source file. Therefore the exact names of all 54
9
+ source columns cannot be proven from the available artifacts. Do not infer the
10
+ four unused names.
11
+
12
+ To finish that historical part of the audit, provide either the original CSV
13
+ header (a header-only file is sufficient) or the original 1.66 GB CSV, plus the
14
+ original compressor/training script or notebook. The large CSV can be inspected
15
+ with `pandas.read_csv(..., nrows=0)` and sampled in chunks; it does not need to be
16
+ loaded into memory.
17
+
18
+ The saved bundle and JSON independently agree on the exact 39 ordered raw model
19
+ features. The bundle's preprocessor also records the same input order and emits
20
+ 85 processed features.
21
+
22
+ ## Available 54-to-50 evidence
23
+
24
+ `ORIGINAL_RAW_COLUMN_COUNT` records a historical count of 54. The current
25
+ compressor consumes these 50 unique raw columns, in contract order:
26
+
27
+ ```text
28
+ RPM, Speed, nGear, Throttle, Brake, DRS, X, Y, Z,
29
+ DistanceToDriverAhead, AirTemp, TrackTemp, Humidity, Pressure,
30
+ WindDirection, WindSpeed, Date, SessionTime, Time, Distance,
31
+ RelativeDistance, DriverAhead, TrackStatus, Driver, DriverNumber, Team,
32
+ LapNumber, Stint, Compound, TyreLife, FreshTyre, LapTime, Sector1Time,
33
+ Sector2Time, Sector3Time, Sector1SessionTime, Sector2SessionTime,
34
+ Sector3SessionTime, SpeedI1, SpeedI2, SpeedFL, SpeedST, IsPersonalBest,
35
+ Position, PitInTime, PitOutTime, LapStartTime, LapStartDate,
36
+ DifferentialDistance, Rainfall
37
+ ```
38
+
39
+ The names of the other four original columns are unavailable. `SessionStatus`,
40
+ `CurrentLap`, and `TotalLaps` are live lifecycle inputs only; they are not among
41
+ the 50 compressor inputs and are not model features.
42
+
43
+ ## Lap compression
44
+
45
+ Each completed driver lap produces `_RaceDate`, `Driver`, `LapNumber`, and
46
+ `TelemetryRecords`, followed by these aggregated columns:
47
+
48
+ - Arithmetic mean of all finite numeric samples: `RPM_Mean`, `Speed_Mean`,
49
+ `nGear_Mean`, `Throttle_Mean`, `Brake_Mean`, `DRS_Mean`, `X_Mean`, `Y_Mean`,
50
+ `Z_Mean`, `DistanceToDriverAhead_Mean`, `AirTemp_Mean`, `TrackTemp_Mean`,
51
+ `Humidity_Mean`, `Pressure_Mean`, `WindDirection_Mean`, `WindSpeed_Mean`.
52
+ - Sum of all finite numeric samples: `DifferentialDistance_Sum`.
53
+ - Last non-`None` sample: `Date_Last`, `SessionTime_Last`, `Time_Last`,
54
+ `Distance_Last`, `RelativeDistance_Last`, `DriverAhead_Last`,
55
+ `TrackStatus_Last`, `Driver_Last`, `DriverNumber_Last`, `Team_Last`,
56
+ `LapNumber_Last`, `Stint_Last`, `Compound_Last`, `TyreLife_Last`,
57
+ `FreshTyre_Last`, `LapTime_Last`, `Sector1Time_Last`, `Sector2Time_Last`,
58
+ `Sector3Time_Last`, `Sector1SessionTime_Last`, `Sector2SessionTime_Last`,
59
+ `Sector3SessionTime_Last`, `SpeedI1_Last`, `SpeedI2_Last`, `SpeedFL_Last`,
60
+ `SpeedST_Last`, `IsPersonalBest_Last`, `Position_Last`, `PitInTime_Last`,
61
+ `PitOutTime_Last`, `LapStartTime_Last`, `LapStartDate_Last`.
62
+ - Maximum of all finite numeric samples: `Rainfall_Any`.
63
+
64
+ `_RaceDate` is the date portion of the last `Date`, or the current UTC date when
65
+ no usable date is present. `Driver` is the uppercased last driver value.
66
+ `LapNumber` is numeric. Empty laps and laps without a driver or lap number fail.
67
+
68
+ ## Exact ordered 39-feature model input
69
+
70
+ | # | Model feature | Compressed source / formula | Aggregation |
71
+ |---:|---|---|---|
72
+ | 1 | `Driver` | `Driver` | last valid, uppercased |
73
+ | 2 | `LapNumber` | `LapNumber` | last/current completed lap |
74
+ | 3 | `DriverNumber` | `DriverNumber_Last` | last valid |
75
+ | 4 | `RPM_Mean` | `RPM_Mean` | mean |
76
+ | 5 | `Speed_Mean` | `Speed_Mean` | mean |
77
+ | 6 | `nGear_Mean` | `nGear_Mean` | mean |
78
+ | 7 | `Throttle_Mean` | `Throttle_Mean` | mean |
79
+ | 8 | `Brake_Mean` | `Brake_Mean` | mean |
80
+ | 9 | `DRS_Mean` | `DRS_Mean` | mean |
81
+ | 10 | `X_Mean` | `X_Mean` | mean |
82
+ | 11 | `Y_Mean` | `Y_Mean` | mean |
83
+ | 12 | `Z_Mean` | `Z_Mean` | mean |
84
+ | 13 | `DistanceToDriverAhead_Mean` | same | mean |
85
+ | 14 | `AirTemp_Mean` | same | mean |
86
+ | 15 | `TrackTemp_Mean` | same | mean |
87
+ | 16 | `Humidity_Mean` | same | mean |
88
+ | 17 | `Pressure_Mean` | same | mean |
89
+ | 18 | `WindDirection_Mean` | same | mean |
90
+ | 19 | `WindSpeed_Mean` | same | mean |
91
+ | 20 | `DifferentialDistance_Sum` | same | sum |
92
+ | 21 | `Distance` | `Distance_Last` | last valid |
93
+ | 22 | `RelativeDistance` | `RelativeDistance_Last` | last valid |
94
+ | 23 | `DriverAhead` | `DriverAhead_Last` | last valid, category |
95
+ | 24 | `TrackStatus` | `TrackStatus_Last` | last valid, numeric |
96
+ | 25 | `Stint` | `Stint_Last` | last valid |
97
+ | 26 | `Compound` | `Compound_Last` | last valid, uppercased |
98
+ | 27 | `TyreLife` | `TyreLife_Last` | last valid |
99
+ | 28 | `FreshTyre` | `FreshTyre_Last` | last valid |
100
+ | 29 | `SpeedI1` | `SpeedI1_Last` | last valid |
101
+ | 30 | `SpeedI2` | `SpeedI2_Last` | last valid |
102
+ | 31 | `SpeedFL` | `SpeedFL_Last` | last valid |
103
+ | 32 | `SpeedST` | `SpeedST_Last` | last valid |
104
+ | 33 | `IsPersonalBest` | `IsPersonalBest_Last` | last valid |
105
+ | 34 | `Position` | `Position_Last` | last valid |
106
+ | 35 | `Rainfall` | `Rainfall_Any` | maximum / any-rain indicator |
107
+ | 36 | `TyreLifeSquared` | `TyreLife ** 2` | derived |
108
+ | 37 | `TrackAirTempDifference` | `TrackTemp_Mean - AirTemp_Mean` | derived |
109
+ | 38 | `WindX` | `WindSpeed_Mean * cos(radians(WindDirection_Mean))` | derived |
110
+ | 39 | `WindY` | `WindSpeed_Mean * sin(radians(WindDirection_Mean))` | derived |
111
+
112
+ ## Missing values and validation
113
+
114
+ - Raw numeric `None`, non-numeric, NaN, and infinity values are ignored by
115
+ numeric aggregation. An aggregate with no finite values becomes `None`.
116
+ - Last-value aggregation skips `None`. A non-finite numeric last value is later
117
+ converted to `None` by feature engineering.
118
+ - Derived features become `None` when any required input is missing.
119
+ - Missing `DriverAhead` or `Compound` becomes `UNKNOWN`. A missing driver fails
120
+ inference.
121
+ - The saved local preprocessor median-imputes numeric missing values,
122
+ most-frequent-imputes actual missing categorical values, and one-hot encodes
123
+ categories with unknown categories ignored. Remote models must implement the
124
+ same training-time preprocessing semantics when receiving JSON `null`.
125
+ - Schema loading fails unless `raw_feature_count` is exactly 39. Every local,
126
+ remote, or auto inference call fails before prediction unless each row has
127
+ exactly the saved 39 names in the saved order. The model bundle, schema, and
128
+ preprocessor input order are also compared during local model loading.
129
+
130
+ ## Real-data validation status
131
+
132
+ No old telemetry CSV or other real telemetry sample is present in the project or
133
+ the inspected project/user data locations. Consequently a real-lap chunked
134
+ end-to-end prediction could not be run in this audit. The focused tests exercise
135
+ the identical compressor-to-feature-to-saved-model path with bounded synthetic
136
+ lap samples. Once the source CSV is provided, select training drivers from the
137
+ saved encoder (for example `VER`, `HAM`, or `NOR`), stream chunks, retain only a
138
+ few complete `(Driver, LapNumber)` groups, and pass those groups through the
139
+ same three production services.
backend/models/f1_live_winner_feature_schema.json ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "target": "Winner",
3
+ "race_column": "RaceDate",
4
+ "driver_column": "Driver",
5
+ "model_features": [
6
+ "Driver",
7
+ "LapNumber",
8
+ "DriverNumber",
9
+ "RPM_Mean",
10
+ "Speed_Mean",
11
+ "nGear_Mean",
12
+ "Throttle_Mean",
13
+ "Brake_Mean",
14
+ "DRS_Mean",
15
+ "X_Mean",
16
+ "Y_Mean",
17
+ "Z_Mean",
18
+ "DistanceToDriverAhead_Mean",
19
+ "AirTemp_Mean",
20
+ "TrackTemp_Mean",
21
+ "Humidity_Mean",
22
+ "Pressure_Mean",
23
+ "WindDirection_Mean",
24
+ "WindSpeed_Mean",
25
+ "DifferentialDistance_Sum",
26
+ "Distance",
27
+ "RelativeDistance",
28
+ "DriverAhead",
29
+ "TrackStatus",
30
+ "Stint",
31
+ "Compound",
32
+ "TyreLife",
33
+ "FreshTyre",
34
+ "SpeedI1",
35
+ "SpeedI2",
36
+ "SpeedFL",
37
+ "SpeedST",
38
+ "IsPersonalBest",
39
+ "Position",
40
+ "Rainfall",
41
+ "TyreLifeSquared",
42
+ "TrackAirTempDifference",
43
+ "WindX",
44
+ "WindY"
45
+ ],
46
+ "numeric_features": [
47
+ "LapNumber",
48
+ "DriverNumber",
49
+ "RPM_Mean",
50
+ "Speed_Mean",
51
+ "nGear_Mean",
52
+ "Throttle_Mean",
53
+ "Brake_Mean",
54
+ "DRS_Mean",
55
+ "X_Mean",
56
+ "Y_Mean",
57
+ "Z_Mean",
58
+ "DistanceToDriverAhead_Mean",
59
+ "AirTemp_Mean",
60
+ "TrackTemp_Mean",
61
+ "Humidity_Mean",
62
+ "Pressure_Mean",
63
+ "WindDirection_Mean",
64
+ "WindSpeed_Mean",
65
+ "DifferentialDistance_Sum",
66
+ "Distance",
67
+ "RelativeDistance",
68
+ "TrackStatus",
69
+ "Stint",
70
+ "TyreLife",
71
+ "FreshTyre",
72
+ "SpeedI1",
73
+ "SpeedI2",
74
+ "SpeedFL",
75
+ "SpeedST",
76
+ "IsPersonalBest",
77
+ "Position",
78
+ "Rainfall",
79
+ "TyreLifeSquared",
80
+ "TrackAirTempDifference",
81
+ "WindX",
82
+ "WindY"
83
+ ],
84
+ "categorical_features": [
85
+ "Driver",
86
+ "DriverAhead",
87
+ "Compound"
88
+ ],
89
+ "processed_feature_names": [
90
+ "numeric__LapNumber",
91
+ "numeric__DriverNumber",
92
+ "numeric__RPM_Mean",
93
+ "numeric__Speed_Mean",
94
+ "numeric__nGear_Mean",
95
+ "numeric__Throttle_Mean",
96
+ "numeric__Brake_Mean",
97
+ "numeric__DRS_Mean",
98
+ "numeric__X_Mean",
99
+ "numeric__Y_Mean",
100
+ "numeric__Z_Mean",
101
+ "numeric__DistanceToDriverAhead_Mean",
102
+ "numeric__AirTemp_Mean",
103
+ "numeric__TrackTemp_Mean",
104
+ "numeric__Humidity_Mean",
105
+ "numeric__Pressure_Mean",
106
+ "numeric__WindDirection_Mean",
107
+ "numeric__WindSpeed_Mean",
108
+ "numeric__DifferentialDistance_Sum",
109
+ "numeric__Distance",
110
+ "numeric__RelativeDistance",
111
+ "numeric__TrackStatus",
112
+ "numeric__Stint",
113
+ "numeric__TyreLife",
114
+ "numeric__FreshTyre",
115
+ "numeric__SpeedI1",
116
+ "numeric__SpeedI2",
117
+ "numeric__SpeedFL",
118
+ "numeric__SpeedST",
119
+ "numeric__IsPersonalBest",
120
+ "numeric__Position",
121
+ "numeric__Rainfall",
122
+ "numeric__TyreLifeSquared",
123
+ "numeric__TrackAirTempDifference",
124
+ "numeric__WindX",
125
+ "numeric__WindY",
126
+ "categorical__Driver_ALB",
127
+ "categorical__Driver_ALO",
128
+ "categorical__Driver_ANT",
129
+ "categorical__Driver_BEA",
130
+ "categorical__Driver_BOR",
131
+ "categorical__Driver_BOT",
132
+ "categorical__Driver_COL",
133
+ "categorical__Driver_GAS",
134
+ "categorical__Driver_HAD",
135
+ "categorical__Driver_HAM",
136
+ "categorical__Driver_HUL",
137
+ "categorical__Driver_LAW",
138
+ "categorical__Driver_LEC",
139
+ "categorical__Driver_LIN",
140
+ "categorical__Driver_NOR",
141
+ "categorical__Driver_OCO",
142
+ "categorical__Driver_PER",
143
+ "categorical__Driver_PIA",
144
+ "categorical__Driver_RUS",
145
+ "categorical__Driver_SAI",
146
+ "categorical__Driver_STR",
147
+ "categorical__Driver_VER",
148
+ "categorical__DriverAhead_1.0",
149
+ "categorical__DriverAhead_10.0",
150
+ "categorical__DriverAhead_11.0",
151
+ "categorical__DriverAhead_12.0",
152
+ "categorical__DriverAhead_14.0",
153
+ "categorical__DriverAhead_16.0",
154
+ "categorical__DriverAhead_18.0",
155
+ "categorical__DriverAhead_23.0",
156
+ "categorical__DriverAhead_27.0",
157
+ "categorical__DriverAhead_3.0",
158
+ "categorical__DriverAhead_30.0",
159
+ "categorical__DriverAhead_31.0",
160
+ "categorical__DriverAhead_41.0",
161
+ "categorical__DriverAhead_43.0",
162
+ "categorical__DriverAhead_44.0",
163
+ "categorical__DriverAhead_5.0",
164
+ "categorical__DriverAhead_55.0",
165
+ "categorical__DriverAhead_6.0",
166
+ "categorical__DriverAhead_63.0",
167
+ "categorical__DriverAhead_77.0",
168
+ "categorical__DriverAhead_81.0",
169
+ "categorical__DriverAhead_87.0",
170
+ "categorical__DriverAhead_UNKNOWN",
171
+ "categorical__Compound_HARD",
172
+ "categorical__Compound_INTERMEDIATE",
173
+ "categorical__Compound_MEDIUM",
174
+ "categorical__Compound_SOFT"
175
+ ],
176
+ "raw_feature_count": 39,
177
+ "processed_feature_count": 85,
178
+ "pipeline_version": "f1_lap_level_xgboost_v1"
179
+ }
backend/models/f1_live_winner_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d45b657b2f60cf0971b6a0e990cd8d0d668a28d98fecd9a86806f1545d50adbb
3
+ size 300178
backend/pytest.ini ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ [pytest]
2
+ pythonpath = .
3
+ testpaths = tests
4
+ python_files = test_*.py
5
+ python_classes = Test*
6
+ python_functions = test_*
7
+ filterwarnings =
8
+ ignore::DeprecationWarning
9
+ ignore::starlette.exceptions.StarletteDeprecationWarning
backend/requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi>=0.116,<1.0
2
+ uvicorn[standard]>=0.35,<1.0
3
+ pydantic>=2.11,<3.0
4
+ pydantic-settings>=2.10,<3.0
5
+ pandas>=3.0.3,<4.0
6
+ numpy>=2.1,<3.0
7
+ joblib>=1.5,<2.0
8
+ scikit-learn==1.9.0
9
+ xgboost==3.4.1
10
+ livef1==1.2.9
11
+ websockets>=13.0.1,<18
12
+ httpx>=0.28,<1.0
13
+ python-dotenv>=1.1,<2.0
14
+ signalrcore>=1.0.2,<2.0
backend/test_backend.py ADDED
@@ -0,0 +1,732 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Fast F1 replay streamer for frontend/backend integration testing.
3
+
4
+ Goals:
5
+ - Do NOT hit unavailable 2026 FastF1 archives by default.
6
+ - Use a stable historical source session (2024 by default).
7
+ - Build a compact local JSON replay cache once, then reuse it on later runs.
8
+ - Auto-start the FastAPI backend when needed.
9
+ - Stream lap-by-lap data quickly to the frontend/backend.
10
+ - Exit cleanly after the replay instead of hanging forever.
11
+
12
+ Typical usage:
13
+ python fast_replay.py --gp Monza --laps 3
14
+ python fast_replay.py --gp Bahrain --laps 10
15
+ python fast_replay.py --gp Monza --laps 5 --interval 0
16
+ python fast_replay.py --gp Monza --refresh-cache
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import inspect
23
+ import json
24
+ import os
25
+ import re
26
+ import subprocess
27
+ import sys
28
+ import time
29
+ import urllib.request
30
+ from pathlib import Path
31
+ from typing import Any
32
+
33
+
34
+ PROJECT_ROOT = Path(__file__).resolve().parent
35
+ TESTING_DIR = PROJECT_ROOT / "testing_pipeline"
36
+ TEST_ENV_PYTHON = TESTING_DIR / ".venv" / "Scripts" / "python.exe"
37
+ BACKEND_ENV_PYTHON = PROJECT_ROOT / ".venv" / "Scripts" / "python.exe"
38
+ REPLAY_CACHE_DIR = TESTING_DIR / ".cache" / "replays"
39
+ FASTF1_CACHE_DIR = TESTING_DIR / ".cache" / "fastf1"
40
+ REENTRY_FLAG = "F1_REPLAY_TEST_ENV"
41
+
42
+
43
+ # This is only a frontend/demo roster.
44
+ # It is intentionally independent from the historical source session.
45
+ TEST_GRID = [
46
+ {"DriverNumber": 1, "Driver": "VER", "FullName": "Max Verstappen", "TeamName": "Red Bull Racing"},
47
+ {"DriverNumber": 4, "Driver": "NOR", "FullName": "Lando Norris", "TeamName": "McLaren"},
48
+ {"DriverNumber": 81, "Driver": "PIA", "FullName": "Oscar Piastri", "TeamName": "McLaren"},
49
+ {"DriverNumber": 16, "Driver": "LEC", "FullName": "Charles Leclerc", "TeamName": "Ferrari"},
50
+ {"DriverNumber": 44, "Driver": "HAM", "FullName": "Lewis Hamilton", "TeamName": "Ferrari"},
51
+ {"DriverNumber": 63, "Driver": "RUS", "FullName": "George Russell", "TeamName": "Mercedes"},
52
+ {"DriverNumber": 12, "Driver": "ANT", "FullName": "Andrea Kimi Antonelli", "TeamName": "Mercedes"},
53
+ {"DriverNumber": 55, "Driver": "SAI", "FullName": "Carlos Sainz", "TeamName": "Williams"},
54
+ {"DriverNumber": 23, "Driver": "ALB", "FullName": "Alexander Albon", "TeamName": "Williams"},
55
+ {"DriverNumber": 14, "Driver": "ALO", "FullName": "Fernando Alonso", "TeamName": "Aston Martin"},
56
+ {"DriverNumber": 18, "Driver": "STR", "FullName": "Lance Stroll", "TeamName": "Aston Martin"},
57
+ {"DriverNumber": 10, "Driver": "GAS", "FullName": "Pierre Gasly", "TeamName": "Alpine"},
58
+ {"DriverNumber": 7, "Driver": "DOO", "FullName": "Jack Doohan", "TeamName": "Alpine"},
59
+ {"DriverNumber": 22, "Driver": "TSU", "FullName": "Yuki Tsunoda", "TeamName": "RB"},
60
+ {"DriverNumber": 30, "Driver": "LAW", "FullName": "Liam Lawson", "TeamName": "RB"},
61
+ {"DriverNumber": 27, "Driver": "HUL", "FullName": "Nico Hulkenberg", "TeamName": "Kick Sauber"},
62
+ {"DriverNumber": 5, "Driver": "BOR", "FullName": "Gabriel Bortoleto", "TeamName": "Kick Sauber"},
63
+ {"DriverNumber": 31, "Driver": "OCO", "FullName": "Esteban Ocon", "TeamName": "Haas"},
64
+ {"DriverNumber": 87, "Driver": "BEA", "FullName": "Oliver Bearman", "TeamName": "Haas"},
65
+ {"DriverNumber": 11, "Driver": "PER", "FullName": "Sergio Perez", "TeamName": "Red Bull Racing"},
66
+ ]
67
+
68
+
69
+ DEFAULT_WEATHER = {
70
+ "AirTemp": 27.5,
71
+ "TrackTemp": 39.2,
72
+ "Rainfall": 0,
73
+ "Humidity": 48.0,
74
+ "Pressure": 1012.0,
75
+ "WindSpeed": 7.5,
76
+ "WindDirection": 110.0,
77
+ }
78
+
79
+
80
+ def _safe_float(value: Any, default: float) -> float:
81
+ try:
82
+ if value is None:
83
+ return default
84
+ value = float(value)
85
+ if value != value: # NaN
86
+ return default
87
+ return value
88
+ except (TypeError, ValueError):
89
+ return default
90
+
91
+
92
+ def _safe_int(value: Any, default: int = 1) -> int:
93
+ try:
94
+ if value is None:
95
+ return default
96
+ value = float(value)
97
+ if value != value:
98
+ return default
99
+ return int(value)
100
+ except (TypeError, ValueError):
101
+ return default
102
+
103
+
104
+ def _slug(text: str) -> str:
105
+ return re.sub(r"[^a-zA-Z0-9_-]+", "_", text.strip()).strip("_") or "race"
106
+
107
+
108
+ def _cache_path(source_year: int, source_gp: str) -> Path:
109
+ return REPLAY_CACHE_DIR / f"{source_year}_{_slug(source_gp)}.json"
110
+
111
+
112
+ def _request_json(
113
+ method: str,
114
+ url: str,
115
+ data: dict[str, Any] | list[Any] | None = None,
116
+ timeout: float = 3.0,
117
+ ) -> dict[str, Any] | None:
118
+ body = None
119
+ headers = {"Accept": "application/json"}
120
+
121
+ if data is not None:
122
+ body = json.dumps(data).encode("utf-8")
123
+ headers["Content-Type"] = "application/json"
124
+
125
+ request = urllib.request.Request(
126
+ url,
127
+ data=body,
128
+ headers=headers,
129
+ method=method,
130
+ )
131
+
132
+ try:
133
+ with urllib.request.urlopen(request, timeout=timeout) as response:
134
+ raw = response.read()
135
+ if not raw:
136
+ return {}
137
+ return json.loads(raw.decode("utf-8"))
138
+ except Exception:
139
+ return None
140
+
141
+
142
+ def _get_json(url: str, timeout: float = 2.0) -> dict[str, Any] | None:
143
+ return _request_json("GET", url, timeout=timeout)
144
+
145
+
146
+ def _post_json(
147
+ url: str,
148
+ data: dict[str, Any] | list[Any],
149
+ timeout: float = 3.0,
150
+ ) -> dict[str, Any] | None:
151
+ return _request_json("POST", url, data=data, timeout=timeout)
152
+
153
+
154
+ def _backend_python() -> str:
155
+ if BACKEND_ENV_PYTHON.is_file():
156
+ return str(BACKEND_ENV_PYTHON)
157
+ return sys.executable
158
+
159
+
160
+ def _ensure_backend_running(
161
+ backend_url: str,
162
+ auto_start: bool = True,
163
+ ) -> subprocess.Popen[Any] | None:
164
+ health = _get_json(f"{backend_url}/health", timeout=1.0)
165
+ if health and health.get("status") in {"ok", "degraded"}:
166
+ print(f"[Backend] Connected: {backend_url}")
167
+ return None
168
+
169
+ if not auto_start:
170
+ raise RuntimeError(
171
+ f"Backend is not running at {backend_url}. "
172
+ "Start it manually or remove --no-auto-backend."
173
+ )
174
+
175
+ print(f"[Backend] Not running. Starting FastAPI at {backend_url}...")
176
+
177
+ creationflags = 0
178
+ if os.name == "nt" and hasattr(subprocess, "CREATE_NEW_PROCESS_GROUP"):
179
+ creationflags = subprocess.CREATE_NEW_PROCESS_GROUP
180
+
181
+ process = subprocess.Popen(
182
+ [
183
+ _backend_python(),
184
+ "-m",
185
+ "uvicorn",
186
+ "app.main:app",
187
+ "--host",
188
+ "127.0.0.1",
189
+ "--port",
190
+ "8000",
191
+ ],
192
+ cwd=PROJECT_ROOT,
193
+ stdout=subprocess.DEVNULL,
194
+ stderr=subprocess.DEVNULL,
195
+ creationflags=creationflags,
196
+ )
197
+
198
+ # Fast polling; no long 15-second retry loop.
199
+ deadline = time.monotonic() + 12.0
200
+ while time.monotonic() < deadline:
201
+ health = _get_json(f"{backend_url}/health", timeout=0.8)
202
+ if health and health.get("status") in {"ok", "degraded"}:
203
+ print(f"[Backend] Started (PID {process.pid})")
204
+ return process
205
+ if process.poll() is not None:
206
+ raise RuntimeError(
207
+ "Backend process exited during startup. "
208
+ "Run uvicorn manually once to inspect the backend error."
209
+ )
210
+ time.sleep(0.25)
211
+
212
+ raise RuntimeError(
213
+ f"Backend did not become healthy at {backend_url} within 12 seconds."
214
+ )
215
+
216
+
217
+ def _fastf1_importable() -> bool:
218
+ try:
219
+ import fastf1 # noqa: F401
220
+ return True
221
+ except Exception:
222
+ return False
223
+
224
+
225
+ def _reenter_test_env_if_needed() -> None:
226
+ if _fastf1_importable():
227
+ return
228
+
229
+ if os.environ.get(REENTRY_FLAG):
230
+ raise RuntimeError("FastF1 is not importable inside the testing environment.")
231
+
232
+ if not TEST_ENV_PYTHON.is_file():
233
+ raise RuntimeError(
234
+ "FastF1 environment is missing.\n"
235
+ "Create it with:\n"
236
+ " python -m venv testing_pipeline\\.venv\n"
237
+ " testing_pipeline\\.venv\\Scripts\\python -m pip install -r testing_pipeline\\requirements.txt"
238
+ )
239
+
240
+ env = os.environ.copy()
241
+ env[REENTRY_FLAG] = "1"
242
+
243
+ completed = subprocess.run(
244
+ [str(TEST_ENV_PYTHON), str(Path(__file__).resolve()), *sys.argv[1:]],
245
+ cwd=PROJECT_ROOT,
246
+ env=env,
247
+ check=False,
248
+ )
249
+ raise SystemExit(completed.returncode)
250
+
251
+
252
+ def _load_source_session(source_year: int, source_gp: str):
253
+ import fastf1
254
+
255
+ FASTF1_CACHE_DIR.mkdir(parents=True, exist_ok=True)
256
+ fastf1.Cache.enable_cache(str(FASTF1_CACHE_DIR))
257
+
258
+ print(f"[FastF1] Loading stable source: {source_year} {source_gp} Race")
259
+ session = fastf1.get_session(source_year, source_gp, "R")
260
+
261
+ # Keep the call compatible across FastF1 versions.
262
+ # We intentionally do NOT load telemetry/weather/messages for this frontend test.
263
+ supported = inspect.signature(session.load).parameters
264
+ kwargs: dict[str, Any] = {}
265
+
266
+ if "laps" in supported:
267
+ kwargs["laps"] = True
268
+ if "telemetry" in supported:
269
+ kwargs["telemetry"] = False
270
+ if "weather" in supported:
271
+ kwargs["weather"] = False
272
+ if "messages" in supported:
273
+ kwargs["messages"] = False
274
+
275
+ started = time.perf_counter()
276
+ session.load(**kwargs)
277
+ elapsed = time.perf_counter() - started
278
+
279
+ if not hasattr(session, "laps") or session.laps.empty:
280
+ raise RuntimeError(
281
+ f"No lap data available for {source_year} {source_gp}."
282
+ )
283
+
284
+ print(f"[FastF1] Source loaded in {elapsed:.2f}s")
285
+ return session
286
+
287
+
288
+ def _build_replay_cache(
289
+ source_year: int,
290
+ source_gp: str,
291
+ cache_file: Path,
292
+ ) -> dict[str, Any]:
293
+ session = _load_source_session(source_year, source_gp)
294
+
295
+ laps = session.laps
296
+ source_drivers = [
297
+ str(driver).strip().upper()
298
+ for driver in laps["Driver"].dropna().unique().tolist()
299
+ if str(driver).strip()
300
+ ]
301
+
302
+ if not source_drivers:
303
+ raise RuntimeError("Source session contains no drivers.")
304
+
305
+ # Stable source-driver -> demo-driver mapping.
306
+ driver_map: dict[str, dict[str, Any]] = {}
307
+ for index, source_driver in enumerate(source_drivers):
308
+ driver_map[source_driver] = TEST_GRID[index % len(TEST_GRID)]
309
+
310
+ max_lap = _safe_int(laps["LapNumber"].max(), 1)
311
+ replay_laps: list[dict[str, Any]] = []
312
+
313
+ # Group once. This avoids repeatedly filtering the full DataFrame for every lap.
314
+ grouped = laps.groupby("LapNumber", sort=True)
315
+
316
+ for lap_number_raw, frame in grouped:
317
+ lap_number = _safe_int(lap_number_raw, 0)
318
+ if lap_number <= 0:
319
+ continue
320
+
321
+ car_batch: list[dict[str, Any]] = []
322
+ timing_batch: list[dict[str, Any]] = []
323
+
324
+ for _, row in frame.iterrows():
325
+ source_driver = str(row.get("Driver", "")).strip().upper()
326
+ target = driver_map.get(source_driver)
327
+ if target is None:
328
+ continue
329
+
330
+ position = max(1, _safe_int(row.get("Position"), 1))
331
+ compound = str(row.get("Compound", "MEDIUM") or "MEDIUM").upper()
332
+ tyre_life = _safe_float(row.get("TyreLife"), float(lap_number))
333
+ speed_st = _safe_float(row.get("SpeedST"), 315.0)
334
+
335
+ is_braking = (position % 3 == 0) and (lap_number % 2 == 0)
336
+ rpm = 8400 if is_braking else max(9000, 11500 - position * 12)
337
+ gear = 4 if is_braking else 8
338
+ throttle = 0 if is_braking else 100
339
+ brake = 85 if is_braking else 0
340
+ drs = 1 if position > 1 and not is_braking else 0
341
+
342
+ car_batch.append(
343
+ {
344
+ "Driver": target["Driver"],
345
+ "DriverNumber": target["DriverNumber"],
346
+ "LapNumber": lap_number,
347
+ "Speed": speed_st,
348
+ "RPM": rpm,
349
+ "nGear": gear,
350
+ "Throttle": throttle,
351
+ "Brake": brake,
352
+ "DRS": drs,
353
+ "Compound": compound,
354
+ "TyreLife": tyre_life,
355
+ "Position": position,
356
+ **DEFAULT_WEATHER,
357
+ }
358
+ )
359
+
360
+ timing_batch.append(
361
+ {
362
+ "Driver": target["Driver"],
363
+ "DriverNumber": target["DriverNumber"],
364
+ "LapNumber": lap_number,
365
+ "Position": position,
366
+ }
367
+ )
368
+
369
+ if car_batch and timing_batch:
370
+ replay_laps.append(
371
+ {
372
+ "lap": lap_number,
373
+ "car": car_batch,
374
+ "timing": timing_batch,
375
+ }
376
+ )
377
+
378
+ replay = {
379
+ "schema_version": 1,
380
+ "source_year": source_year,
381
+ "source_gp": source_gp,
382
+ "source_max_lap": max_lap,
383
+ "grid": TEST_GRID,
384
+ "weather": DEFAULT_WEATHER,
385
+ "laps": replay_laps,
386
+ }
387
+
388
+ cache_file.parent.mkdir(parents=True, exist_ok=True)
389
+ temp_file = cache_file.with_suffix(".tmp")
390
+ temp_file.write_text(
391
+ json.dumps(replay, separators=(",", ":"), ensure_ascii=False),
392
+ encoding="utf-8",
393
+ )
394
+ temp_file.replace(cache_file)
395
+
396
+ print(
397
+ f"[Cache] Built {cache_file.name}: "
398
+ f"{len(replay_laps)} replay laps, {len(source_drivers)} source drivers"
399
+ )
400
+
401
+ return replay
402
+
403
+
404
+ def _load_or_build_replay(
405
+ source_year: int,
406
+ source_gp: str,
407
+ refresh_cache: bool,
408
+ ) -> dict[str, Any]:
409
+ cache_file = _cache_path(source_year, source_gp)
410
+
411
+ if cache_file.is_file() and not refresh_cache:
412
+ started = time.perf_counter()
413
+ replay = json.loads(cache_file.read_text(encoding="utf-8"))
414
+ elapsed = time.perf_counter() - started
415
+ print(f"[Cache] Loaded {cache_file.name} in {elapsed:.3f}s")
416
+ return replay
417
+
418
+ _reenter_test_env_if_needed()
419
+ return _build_replay_cache(source_year, source_gp, cache_file)
420
+
421
+
422
+ def _leader_text(snapshot: dict[str, Any] | None) -> tuple[str, str]:
423
+ if not snapshot:
424
+ return "Calculating...", ""
425
+
426
+ prediction = snapshot.get("prediction") or {}
427
+ leaderboard = prediction.get("leaderboard") or []
428
+
429
+ if not leaderboard:
430
+ return "Calculating...", ""
431
+
432
+ leader = leaderboard[0]
433
+ probability = _safe_float(leader.get("normalized_probability"), 0.0) * 100
434
+ leader_text = f"{leader.get('driver', '?')} ({probability:.1f}%)"
435
+ top3 = ", ".join(
436
+ f"P{i + 1}:{item.get('driver', '?')}"
437
+ for i, item in enumerate(leaderboard[:3])
438
+ )
439
+ return leader_text, top3
440
+
441
+
442
+ def run_replay(
443
+ *,
444
+ display_year: int,
445
+ display_gp: str,
446
+ source_year: int,
447
+ source_gp: str,
448
+ max_laps: int | None,
449
+ interval: float,
450
+ backend_url: str,
451
+ refresh_cache: bool,
452
+ auto_backend: bool,
453
+ snapshot_every: int,
454
+ hold: bool,
455
+ stop_backend_after: bool,
456
+ ) -> int:
457
+ replay = _load_or_build_replay(
458
+ source_year=source_year,
459
+ source_gp=source_gp,
460
+ refresh_cache=refresh_cache,
461
+ )
462
+
463
+ backend_proc: subprocess.Popen[Any] | None = None
464
+
465
+ try:
466
+ backend_proc = _ensure_backend_running(
467
+ backend_url=backend_url,
468
+ auto_start=auto_backend,
469
+ )
470
+
471
+ available_laps = replay.get("laps") or []
472
+ if not available_laps:
473
+ raise RuntimeError("Replay cache contains no laps.")
474
+
475
+ target_laps = len(available_laps)
476
+ if max_laps is not None:
477
+ target_laps = min(max(1, max_laps), target_laps)
478
+
479
+ selected = available_laps[:target_laps]
480
+
481
+ print()
482
+ print("=" * 72)
483
+ print(" FAST F1 FRONTEND/BACKEND REPLAY")
484
+ print(f" Display race : {display_year} {display_gp}")
485
+ print(f" Data source : {source_year} {source_gp} historical race")
486
+ print(f" Laps : {target_laps}")
487
+ print(f" Interval : {interval:.2f}s")
488
+ print(f" Backend : {backend_url}")
489
+ print("=" * 72)
490
+ print()
491
+
492
+ # Reset once.
493
+ if _post_json(f"{backend_url}/live/reset", {}) is None:
494
+ raise RuntimeError("Backend /live/reset request failed.")
495
+
496
+ driver_records = [
497
+ {
498
+ "DriverNumber": d["DriverNumber"],
499
+ "Driver": d["Driver"],
500
+ "BroadcastName": d["FullName"],
501
+ "TeamName": d["TeamName"],
502
+ }
503
+ for d in replay.get("grid", TEST_GRID)
504
+ ]
505
+
506
+ if _post_json(
507
+ f"{backend_url}/live/feed",
508
+ {"DriverList": driver_records},
509
+ ) is None:
510
+ raise RuntimeError("Failed to register driver list.")
511
+
512
+ weather = replay.get("weather") or DEFAULT_WEATHER
513
+ _post_json(
514
+ f"{backend_url}/live/feed",
515
+ {
516
+ "WeatherData": [weather],
517
+ "TrackStatus": [{"TrackStatus": "1"}],
518
+ "LapCount": [{"CurrentLap": 0, "TotalLaps": target_laps}],
519
+ "SessionStatus": [{"Status": "Started"}],
520
+ },
521
+ )
522
+
523
+ _post_json(
524
+ f"{backend_url}/live/feed",
525
+ {
526
+ "TimingData": [
527
+ {
528
+ "DriverNumber": d["DriverNumber"],
529
+ "Driver": d["Driver"],
530
+ "LapNumber": 0,
531
+ }
532
+ for d in driver_records
533
+ ]
534
+ },
535
+ )
536
+
537
+ replay_started = time.perf_counter()
538
+
539
+ for index, lap_data in enumerate(selected, start=1):
540
+ lap_number = index
541
+
542
+ # Copy only because we need the displayed lap numbering to be contiguous
543
+ # even if the source had any missing lap groups.
544
+ car_batch = [dict(row, LapNumber=lap_number) for row in lap_data["car"]]
545
+ timing_batch = [dict(row, LapNumber=lap_number) for row in lap_data["timing"]]
546
+
547
+ payload = {
548
+ "LapCount": [{"CurrentLap": lap_number, "TotalLaps": target_laps}],
549
+ "CarData.z": car_batch,
550
+ "TimingData": timing_batch,
551
+ }
552
+
553
+ if _post_json(f"{backend_url}/live/feed", payload) is None:
554
+ print(f"[Warning] Lap {lap_number} feed failed")
555
+ continue
556
+
557
+ should_snapshot = (
558
+ snapshot_every > 0
559
+ and (
560
+ lap_number == 1
561
+ or lap_number == target_laps
562
+ or lap_number % snapshot_every == 0
563
+ )
564
+ )
565
+
566
+ if should_snapshot:
567
+ snapshot = _get_json(
568
+ f"{backend_url}/live/frontend",
569
+ timeout=1.5,
570
+ )
571
+ leader, top3 = _leader_text(snapshot)
572
+ print(
573
+ f"[Lap {lap_number:>2}/{target_laps}] "
574
+ f"Leader: {leader:<18} Top 3: [{top3}]"
575
+ )
576
+ else:
577
+ print(f"[Lap {lap_number:>2}/{target_laps}] streamed")
578
+
579
+ if interval > 0:
580
+ time.sleep(interval)
581
+
582
+ _post_json(
583
+ f"{backend_url}/live/feed",
584
+ {"SessionStatus": [{"Status": "Finished"}]},
585
+ )
586
+
587
+ elapsed = time.perf_counter() - replay_started
588
+ final_snapshot = _get_json(f"{backend_url}/live/frontend", timeout=2.0) or {}
589
+ prediction = final_snapshot.get("prediction") or {}
590
+ leaderboard = prediction.get("leaderboard") or []
591
+ winner = prediction.get("final_predicted_winner")
592
+ if not winner and leaderboard:
593
+ winner = leaderboard[0].get("driver")
594
+
595
+ print()
596
+ print("=" * 72)
597
+ print(" REPLAY FINISHED")
598
+ print(f" Predicted winner : {winner or 'N/A'}")
599
+ print(f" Stream time : {elapsed:.2f}s")
600
+ print(" Frontend : http://localhost:5173")
601
+ print("=" * 72)
602
+
603
+ if hold:
604
+ print("\n[Hold] Keeping this process alive. Press Ctrl+C to stop.")
605
+ while True:
606
+ time.sleep(1)
607
+
608
+ return 0
609
+
610
+ except KeyboardInterrupt:
611
+ print("\n[Replay] Stopped by user.")
612
+ return 130
613
+
614
+ except Exception as exc:
615
+ print(f"\n[Error] {exc}", file=sys.stderr)
616
+ return 1
617
+
618
+ finally:
619
+ if stop_backend_after and backend_proc is not None:
620
+ try:
621
+ backend_proc.terminate()
622
+ except Exception:
623
+ pass
624
+
625
+
626
+ def _parse_args() -> argparse.Namespace:
627
+ parser = argparse.ArgumentParser(
628
+ description=(
629
+ "Fast local F1 replay streamer for frontend/backend integration testing."
630
+ )
631
+ )
632
+
633
+ parser.add_argument(
634
+ "--gp",
635
+ default="Monza",
636
+ help="Displayed/test Grand Prix name. Also used as source GP unless --source-gp is set.",
637
+ )
638
+ parser.add_argument(
639
+ "--year",
640
+ type=int,
641
+ default=2026,
642
+ help="Displayed/test season year (default: 2026).",
643
+ )
644
+ parser.add_argument(
645
+ "--source-year",
646
+ type=int,
647
+ default=2024,
648
+ help="Historical FastF1 source year (default: 2024).",
649
+ )
650
+ parser.add_argument(
651
+ "--source-gp",
652
+ default=None,
653
+ help="Historical FastF1 source GP. Defaults to the value of --gp.",
654
+ )
655
+ parser.add_argument(
656
+ "--laps",
657
+ type=int,
658
+ default=None,
659
+ help="Number of laps to replay. Default: all cached source laps.",
660
+ )
661
+ parser.add_argument(
662
+ "--interval",
663
+ type=float,
664
+ default=0.25,
665
+ help="Seconds between streamed laps. Use 0 for maximum speed. Default: 0.25.",
666
+ )
667
+ parser.add_argument(
668
+ "--backend-url",
669
+ default="http://127.0.0.1:8000",
670
+ help="Backend base URL.",
671
+ )
672
+ parser.add_argument(
673
+ "--refresh-cache",
674
+ action="store_true",
675
+ help="Ignore local replay JSON and rebuild it from FastF1.",
676
+ )
677
+ parser.add_argument(
678
+ "--no-auto-backend",
679
+ action="store_true",
680
+ help="Do not auto-start the FastAPI backend.",
681
+ )
682
+ parser.add_argument(
683
+ "--snapshot-every",
684
+ type=int,
685
+ default=1,
686
+ help="Read /live/frontend every N laps. Use 0 to disable snapshot polling.",
687
+ )
688
+ parser.add_argument(
689
+ "--hold",
690
+ action="store_true",
691
+ help="Keep this replay process alive after the race finishes.",
692
+ )
693
+ parser.add_argument(
694
+ "--stop-backend-after",
695
+ action="store_true",
696
+ help="Stop the backend only if this script started it.",
697
+ )
698
+
699
+ return parser.parse_args()
700
+
701
+
702
+ def main() -> int:
703
+ args = _parse_args()
704
+
705
+ if args.interval < 0:
706
+ print("[Error] --interval cannot be negative.", file=sys.stderr)
707
+ return 2
708
+
709
+ if args.snapshot_every < 0:
710
+ print("[Error] --snapshot-every cannot be negative.", file=sys.stderr)
711
+ return 2
712
+
713
+ source_gp = args.source_gp or args.gp
714
+
715
+ return run_replay(
716
+ display_year=args.year,
717
+ display_gp=args.gp,
718
+ source_year=args.source_year,
719
+ source_gp=source_gp,
720
+ max_laps=args.laps,
721
+ interval=args.interval,
722
+ backend_url=args.backend_url.rstrip("/"),
723
+ refresh_cache=args.refresh_cache,
724
+ auto_backend=not args.no_auto_backend,
725
+ snapshot_every=args.snapshot_every,
726
+ hold=args.hold,
727
+ stop_backend_after=args.stop_backend_after,
728
+ )
729
+
730
+
731
+ if __name__ == "__main__":
732
+ raise SystemExit(main())
backend/testing_pipeline/.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ .cache/
2
+ .venv/
backend/testing_pipeline/README.md ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Temporary backend replay and live test harness
2
+
3
+ This directory is intentionally isolated from the production application.
4
+ Production modules do not import it, and no production `app/` file needs to be
5
+ changed to add or remove the harness.
6
+
7
+ ## One-time historical test setup
8
+
9
+ FastF1 requires Pandas 2 while the production LiveF1 dependency requires
10
+ Pandas 3. Keep them in separate environments:
11
+
12
+ ```powershell
13
+ python -m venv testing_pipeline\.venv
14
+ testing_pipeline\.venv\Scripts\python -m pip install -r testing_pipeline\requirements.txt
15
+ ```
16
+
17
+ ## Historical replay
18
+
19
+ ```powershell
20
+ python test_backend.py
21
+ python test_backend.py --year 2024 --gp Bahrain --max-laps 3
22
+ python test_backend.py --year 2024 --gp Bahrain
23
+ ```
24
+
25
+ The launcher automatically delegates historical replay to the isolated test
26
+ environment. Omit `--max-laps` to process the full race.
27
+
28
+ ## Existing live-provider probe
29
+
30
+ Run this from the normal production environment during an F1 session:
31
+
32
+ ```powershell
33
+ python test_backend.py --live --duration 120
34
+ ```
35
+
36
+ The probe observes the existing LiveF1 provider, unchanged production pipeline,
37
+ model path, race state, and frontend snapshot builder. It does not modify the
38
+ production provider or routes.
39
+
40
+ ## Removal
41
+
42
+ The harness consists of `test_backend.py`, `testing_pipeline/`, and
43
+ `tests/test_testing_pipeline.py`. Removing those paths removes the temporary
44
+ testing feature. FastF1 is not added to the production `requirements.txt`.
backend/testing_pipeline/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ """Isolated historical replay tooling; production code never imports this package."""
2
+
backend/testing_pipeline/cli.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import asyncio
5
+ import sys
6
+ import traceback
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from app.config import get_settings
11
+ from app.services.driver_registry import DriverRegistry
12
+ from app.services.feature_engineer import LiveFeatureEngineer
13
+ from app.services.inference_gateway import InferenceGateway
14
+ from app.services.live_compressor import LiveLapCompressor
15
+ from app.services.live_pipeline import LivePipeline
16
+ from app.services.live_state import LiveRaceState
17
+ from app.services.model_service import ModelService
18
+ from app.services.prediction_service import PredictionService
19
+ from app.services.raw_normalizer import RawNormalizer
20
+ from app.services.remote_model_client import RemoteModelClient
21
+ from testing_pipeline.fastf1_replay import FastF1Replay, ReplayConfig, ReplayResult
22
+ from testing_pipeline.report import print_report
23
+
24
+
25
+ def build_parser() -> argparse.ArgumentParser:
26
+ parser = argparse.ArgumentParser(
27
+ description=(
28
+ "Replay a historical FastF1 race through the unchanged production "
29
+ "normalization, lap, feature, and model pipeline."
30
+ )
31
+ )
32
+ parser.add_argument("--year", type=int, default=2024)
33
+ parser.add_argument("--gp", default="Bahrain", help="Grand Prix name or round")
34
+ parser.add_argument("--session", default="R", help="FastF1 session code; default R")
35
+ parser.add_argument(
36
+ "--speed",
37
+ type=float,
38
+ default=0.0,
39
+ help="0 runs instantly; positive values replay at that speed multiplier",
40
+ )
41
+ parser.add_argument(
42
+ "--max-laps",
43
+ type=int,
44
+ default=None,
45
+ help="Optional bounded smoke test; omitted means the complete race",
46
+ )
47
+ parser.add_argument(
48
+ "--cache-dir",
49
+ type=Path,
50
+ default=Path("testing_pipeline/.cache/fastf1"),
51
+ )
52
+ parser.add_argument(
53
+ "--traceback",
54
+ action="store_true",
55
+ help="Print a Python traceback when setup or replay fails",
56
+ )
57
+ return parser
58
+
59
+
60
+ def main(argv: list[str] | None = None) -> int:
61
+ args = build_parser().parse_args(argv)
62
+ if args.speed < 0:
63
+ print("ERROR: --speed cannot be negative", file=sys.stderr)
64
+ return 2
65
+ if args.max_laps is not None and args.max_laps < 1:
66
+ print("ERROR: --max-laps must be at least 1", file=sys.stderr)
67
+ return 2
68
+ try:
69
+ return asyncio.run(_run(args))
70
+ except KeyboardInterrupt:
71
+ print("\nReplay cancelled by user.")
72
+ return 130
73
+ except Exception as exc:
74
+ print("\n" + "=" * 72, file=sys.stderr)
75
+ print("F1 BACKEND REPLAY FAILED", file=sys.stderr)
76
+ print(f"{type(exc).__name__}: {exc}", file=sys.stderr)
77
+ if args.traceback:
78
+ traceback.print_exc()
79
+ else:
80
+ print("Re-run with --traceback for technical details.", file=sys.stderr)
81
+ print("=" * 72, file=sys.stderr)
82
+ return 1
83
+
84
+
85
+ async def _run(args: argparse.Namespace) -> int:
86
+ # The replay is deterministic and self-contained. It always exercises the
87
+ # saved local production artifact, regardless of deployment-only remote URLs.
88
+ settings = get_settings().model_copy(update={"model_backend": "local"})
89
+ model = ModelService(settings)
90
+ gateway = InferenceGateway(
91
+ settings=settings,
92
+ local_model=model,
93
+ remote_model=RemoteModelClient(settings),
94
+ )
95
+ await gateway.startup()
96
+
97
+ predictions = PredictionService(
98
+ compressor=LiveLapCompressor(),
99
+ feature_engineer=LiveFeatureEngineer(settings),
100
+ gateway=gateway,
101
+ )
102
+ pipeline = LivePipeline(
103
+ normalizer=RawNormalizer(),
104
+ registry=DriverRegistry(),
105
+ state=LiveRaceState(),
106
+ predictions=predictions,
107
+ )
108
+ replay = FastF1Replay(
109
+ ReplayConfig(
110
+ year=args.year,
111
+ grand_prix=str(args.gp),
112
+ session=str(args.session),
113
+ replay_speed=args.speed,
114
+ max_laps=args.max_laps,
115
+ cache_dir=args.cache_dir,
116
+ )
117
+ )
118
+
119
+ print(
120
+ f"Loading FastF1 data for {args.year} {args.gp} ({args.session}). "
121
+ "The first run can take several minutes..."
122
+ )
123
+ checkpoints: dict[int, list[dict[str, Any]]] = {}
124
+
125
+ async def capture_progress(
126
+ race_lap: int,
127
+ total_laps: int,
128
+ leaderboard: list[dict[str, Any]],
129
+ ) -> None:
130
+ targets = {
131
+ max(1, round(total_laps * fraction))
132
+ for fraction in (0.25, 0.50, 0.75, 1.0)
133
+ }
134
+ if race_lap in targets and race_lap not in checkpoints:
135
+ checkpoints[race_lap] = [dict(row) for row in leaderboard[:3]]
136
+ leader = leaderboard[0]["driver"] if leaderboard else "waiting"
137
+ print(f" lap {race_lap:>2}/{total_laps}: leader={leader}")
138
+
139
+ result: ReplayResult = await replay.run(
140
+ pipeline,
141
+ predictions,
142
+ on_progress=capture_progress,
143
+ )
144
+ result.prediction_checkpoints = checkpoints
145
+ leaderboard = await predictions.leaderboard()
146
+ passed = print_report(result, pipeline, predictions, model, leaderboard)
147
+ return 0 if passed else 1