-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2085 lines (1785 loc) · 99.4 KB
/
app.py
File metadata and controls
2085 lines (1785 loc) · 99.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
🏎️ F1 Strategy AI Pro - Premium Race Prediction Dashboard
A professional-grade Formula 1 prediction application powered by FastF1, XGBoost ML, and SHAP explainability.
Author: F1 Strategy AI Team
Version: 3.0.0
"""
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import json
from pathlib import Path
from datetime import datetime
# Import project modules
from src.data_loader import (
get_available_seasons,
get_available_gps,
load_gp_data,
aggregate_practice_pace,
get_qualifying_results,
get_race_results,
get_session_laps,
get_drivers_from_session,
load_static_data
)
from src.data_fetcher import fetch_gp, fetch_session, save_session_json
from src.model import AdvancedRacePredictor, F1MLPredictor
# STYLING & CONFIGURATION
# F1 Team Colors (2024 Season)
TEAM_COLORS = {
"Red Bull Racing": "#3671C6",
"Red Bull": "#3671C6",
"Ferrari": "#E8002D",
"Scuderia Ferrari": "#E8002D",
"Mercedes": "#27F4D2",
"Mercedes-AMG Petronas F1 Team": "#27F4D2",
"McLaren": "#FF8000",
"McLaren F1 Team": "#FF8000",
"Aston Martin": "#229971",
"Aston Martin Aramco F1 Team": "#229971",
"Alpine": "#FF87BC",
"Alpine F1 Team": "#FF87BC",
"Williams": "#64C4FF",
"Williams Racing": "#64C4FF",
"AlphaTauri": "#5E8FAA",
"Visa Cash App RB F1 Team": "#6692FF",
"RB": "#6692FF",
"Alfa Romeo": "#C92D4B",
"Kick Sauber": "#52E252",
"Sauber": "#52E252",
"Haas F1 Team": "#B6BABD",
"Haas": "#B6BABD",
}
# Page configuration
st.set_page_config(
page_title="F1 Strategy AI Pro",
page_icon="🏎️",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS for F1-grade premium styling
st.markdown("""
<style>
/* Import Racing Font */
@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@400;500;600;700;800;900&family=Inter:wght@300;400;500;600;700&display=swap');
/* Root Variables */
:root {
--f1-red: #E10600;
--f1-dark: #15151E;
--f1-darker: #0D0D12;
--f1-card: rgba(30, 30, 45, 0.85);
--f1-border: rgba(255, 255, 255, 0.08);
--f1-glow: rgba(225, 6, 0, 0.3);
--f1-accent: #FF1E00;
--f1-success: #00D26A;
--f1-warning: #FFB800;
--glass-bg: rgba(20, 20, 30, 0.75);
--glass-border: rgba(255, 255, 255, 0.1);
}
/* Main App Background */
.stApp {
background: linear-gradient(165deg, #0D0D12 0%, #15151E 50%, #1A1A28 100%);
}
/* Hide Streamlit Branding */
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
header {visibility: hidden;}
/* Main Header Styling */
.f1-header {
background: linear-gradient(135deg, rgba(225, 6, 0, 0.15) 0%, rgba(30, 30, 45, 0.9) 100%);
border: 1px solid var(--glass-border);
border-radius: 16px;
padding: 2rem 2.5rem;
margin-bottom: 2rem;
backdrop-filter: blur(20px);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.1);
}
.f1-header h1 {
font-family: 'Orbitron', monospace;
font-size: 2.5rem;
font-weight: 800;
background: linear-gradient(135deg, #FFFFFF 0%, #E10600 50%, #FF4444 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
margin: 0;
letter-spacing: 3px;
text-transform: uppercase;
}
.f1-header .subtitle {
font-family: 'Inter', sans-serif;
color: rgba(255, 255, 255, 0.6);
font-size: 0.95rem;
margin-top: 0.5rem;
letter-spacing: 1px;
}
/* Sidebar Styling */
[data-testid="stSidebar"] {
background: linear-gradient(180deg, #0D0D12 0%, #15151E 100%);
border-right: 1px solid var(--glass-border);
}
[data-testid="stSidebar"] .stSelectbox label,
[data-testid="stSidebar"] .stButton button {
font-family: 'Inter', sans-serif;
}
/* Mission Control Buttons */
.mission-btn {
background: linear-gradient(135deg, var(--f1-red) 0%, #B30500 100%);
border: none;
border-radius: 8px;
color: white;
font-family: 'Orbitron', monospace;
font-weight: 600;
padding: 0.75rem 1.5rem;
text-transform: uppercase;
letter-spacing: 2px;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(225, 6, 0, 0.3);
}
.mission-btn:hover {
transform: translateY(-2px);
box-shadow: 0 6px 25px rgba(225, 6, 0, 0.5);
}
/* Metric Cards */
.metric-card {
background: var(--glass-bg);
border: 1px solid var(--glass-border);
border-radius: 12px;
padding: 1.25rem;
backdrop-filter: blur(10px);
transition: all 0.3s ease;
}
.metric-card:hover {
border-color: rgba(225, 6, 0, 0.3);
box-shadow: 0 4px 20px rgba(225, 6, 0, 0.15);
}
.metric-label {
font-family: 'Inter', sans-serif;
font-size: 0.75rem;
color: rgba(255, 255, 255, 0.5);
text-transform: uppercase;
letter-spacing: 1px;
margin-bottom: 0.5rem;
}
.metric-value {
font-family: 'Orbitron', monospace;
font-size: 1.75rem;
font-weight: 700;
color: #FFFFFF;
}
.metric-delta {
font-family: 'Inter', sans-serif;
font-size: 0.8rem;
margin-top: 0.25rem;
}
.metric-delta.positive { color: var(--f1-success); }
.metric-delta.negative { color: var(--f1-red); }
/* Data Tables */
.dataframe {
font-family: 'Inter', sans-serif !important;
background: var(--glass-bg) !important;
border-radius: 12px !important;
overflow: hidden;
}
.dataframe th {
background: rgba(225, 6, 0, 0.15) !important;
color: white !important;
font-weight: 600 !important;
text-transform: uppercase !important;
letter-spacing: 1px !important;
font-size: 0.75rem !important;
}
.dataframe td {
color: rgba(255, 255, 255, 0.9) !important;
border-bottom: 1px solid var(--glass-border) !important;
}
/* Tab Styling */
.stTabs [data-baseweb="tab-list"] {
background: var(--glass-bg);
border-radius: 12px;
padding: 0.5rem;
gap: 0.5rem;
border: 1px solid var(--glass-border);
}
.stTabs [data-baseweb="tab"] {
font-family: 'Orbitron', monospace;
font-weight: 500;
font-size: 0.85rem;
letter-spacing: 1px;
text-transform: uppercase;
color: rgba(255, 255, 255, 0.6);
background: transparent;
border-radius: 8px;
padding: 0.75rem 1.25rem;
}
.stTabs [aria-selected="true"] {
background: linear-gradient(135deg, var(--f1-red) 0%, #B30500 100%) !important;
color: white !important;
}
/* Charts Container */
.chart-container {
background: var(--glass-bg);
border: 1px solid var(--glass-border);
border-radius: 16px;
padding: 1.5rem;
margin: 1rem 0;
backdrop-filter: blur(10px);
}
/* Session Status Badges */
.status-badge {
display: inline-block;
padding: 0.35rem 0.75rem;
border-radius: 20px;
font-family: 'Inter', sans-serif;
font-size: 0.7rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 1px;
}
.status-available {
background: rgba(0, 210, 106, 0.2);
color: var(--f1-success);
border: 1px solid rgba(0, 210, 106, 0.3);
}
.status-missing {
background: rgba(255, 184, 0, 0.2);
color: var(--f1-warning);
border: 1px solid rgba(255, 184, 0, 0.3);
}
/* Prediction Results */
.prediction-card {
background: linear-gradient(135deg, rgba(225, 6, 0, 0.1) 0%, var(--glass-bg) 100%);
border: 1px solid var(--glass-border);
border-radius: 16px;
padding: 1.5rem;
margin: 0.75rem 0;
transition: all 0.3s ease;
}
.prediction-card:hover {
border-color: rgba(225, 6, 0, 0.4);
transform: translateX(4px);
}
.driver-name {
font-family: 'Orbitron', monospace;
font-size: 1.1rem;
font-weight: 700;
color: white;
}
.team-name {
font-family: 'Inter', sans-serif;
font-size: 0.8rem;
color: rgba(255, 255, 255, 0.5);
}
/* Progress Bars */
.prob-bar {
height: 8px;
border-radius: 4px;
background: rgba(255, 255, 255, 0.1);
overflow: hidden;
margin-top: 0.5rem;
}
.prob-fill {
height: 100%;
border-radius: 4px;
background: linear-gradient(90deg, var(--f1-red) 0%, #FF4444 100%);
transition: width 0.5s ease;
}
/* Animations */
@keyframes pulse-glow {
0%, 100% { box-shadow: 0 0 20px rgba(225, 6, 0, 0.3); }
50% { box-shadow: 0 0 40px rgba(225, 6, 0, 0.6); }
}
.live-indicator {
animation: pulse-glow 2s infinite;
}
/* Scrollbar */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: var(--f1-darker);
}
::-webkit-scrollbar-thumb {
background: var(--f1-red);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #FF4444;
}
</style>
""", unsafe_allow_html=True)
# ═══════════════════════════════════════════════════════════════════════════════
# 🛠️ HELPER FUNCTIONS
# ═══════════════════════════════════════════════════════════════════════════════
def get_team_color(team_name: str) -> str:
"""Get F1 team color by name."""
for key, color in TEAM_COLORS.items():
if key.lower() in team_name.lower() or team_name.lower() in key.lower():
return color
return "#FFFFFF"
def format_lap_time(seconds: float) -> str:
"""Format lap time in seconds to M:SS.mmm format."""
if pd.isna(seconds) or seconds is None:
return "—"
mins = int(seconds // 60)
secs = seconds % 60
return f"{mins}:{secs:06.3f}"
def format_gap(gap_seconds: float) -> str:
"""Format gap to leader."""
if pd.isna(gap_seconds) or gap_seconds == 0:
return "LEADER"
return f"+{gap_seconds:.3f}s"
def create_pace_chart(pace_df: pd.DataFrame) -> go.Figure:
"""Create interactive practice pace comparison chart."""
if pace_df.empty:
return None
# Sort by best time
pace_df = pace_df.sort_values("best").head(15)
# Calculate gap to fastest
fastest = pace_df["best"].min()
pace_df["gap"] = pace_df["best"] - fastest
# Color scale: green (fast) to red (slow)
max_gap = pace_df["gap"].max()
colors = [f"rgb({min(255, int(150 + (g/max_gap)*105))}, {max(50, int(200 - (g/max_gap)*150))}, 50)"
for g in pace_df["gap"]]
fig = go.Figure()
fig.add_trace(go.Bar(
y=pace_df["driver"],
x=pace_df["gap"],
orientation='h',
marker=dict(
color=colors,
line=dict(color='rgba(255,255,255,0.3)', width=1)
),
text=[format_gap(g) for g in pace_df["gap"]],
textposition='outside',
textfont=dict(family="Orbitron", size=11, color="white"),
hovertemplate="<b>%{y}</b><br>Gap: +%{x:.3f}s<br>Best: %{customdata}<extra></extra>",
customdata=[format_lap_time(t) for t in pace_df["best"]]
))
fig.update_layout(
template="plotly_dark",
paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)",
font=dict(family="Inter", color="white"),
title=dict(
text="📊 PRACTICE PACE ANALYSIS",
font=dict(family="Orbitron", size=16, color="white"),
x=0.5
),
xaxis=dict(
title="Gap to Fastest (seconds)",
gridcolor="rgba(255,255,255,0.1)",
zerolinecolor="rgba(255,255,255,0.3)"
),
yaxis=dict(
title="",
autorange="reversed",
tickfont=dict(family="Orbitron", size=11)
),
height=500,
margin=dict(l=80, r=100, t=60, b=40),
showlegend=False
)
return fig
def create_qualifying_chart(quali_df: pd.DataFrame) -> go.Figure:
"""Create qualifying gap visualization with team colors."""
if quali_df.empty:
return None
# Get best Q time for each driver
quali_df = quali_df.copy()
# Find the best time column available
for q_col in ["q3", "q2", "q1"]:
if q_col in quali_df.columns:
quali_df[q_col] = pd.to_numeric(quali_df[q_col], errors='coerce')
# Get best qualifying time
q_cols = [c for c in ["q3", "q2", "q1"] if c in quali_df.columns]
if not q_cols:
return None
quali_df["best_q"] = quali_df[q_cols].min(axis=1)
quali_df = quali_df.dropna(subset=["best_q"]).sort_values("position").head(20)
if quali_df.empty:
return None
fastest = quali_df["best_q"].min()
quali_df["gap"] = quali_df["best_q"] - fastest
# Get team colors for each driver
colors = []
for _, row in quali_df.iterrows():
team = row.get("team", "")
team_color = get_team_color(team) if team else "#FFFFFF"
colors.append(team_color)
fig = go.Figure()
# Add Q3 cutoff line
if len(quali_df) >= 10:
fig.add_vline(x=10.5, line_dash="dash", line_color="rgba(225,6,0,0.5)",
annotation_text="Q3", annotation_position="top")
if len(quali_df) >= 15:
fig.add_vline(x=15.5, line_dash="dash", line_color="rgba(255,184,0,0.5)",
annotation_text="Q2", annotation_position="top")
fig.add_trace(go.Bar(
x=quali_df["position"],
y=quali_df["gap"],
marker=dict(
color=colors,
line=dict(color='rgba(255,255,255,0.4)', width=1)
),
text=quali_df["driver"],
textposition='outside',
textfont=dict(family="Orbitron", size=10, color="white"),
hovertemplate="<b>P%{x} - %{text}</b><br>Gap: +%{y:.3f}s<br>Team: %{customdata}<extra></extra>",
customdata=quali_df["team"] if "team" in quali_df.columns else None
))
fig.update_layout(
template="plotly_dark",
paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)",
font=dict(family="Inter", color="white"),
title=dict(
text="🏁 QUALIFYING GAPS TO POLE",
font=dict(family="Orbitron", size=16, color="white"),
x=0.5
),
xaxis=dict(
title="Grid Position",
gridcolor="rgba(255,255,255,0.1)",
dtick=1
),
yaxis=dict(
title="Gap to Pole (seconds)",
gridcolor="rgba(255,255,255,0.1)"
),
height=400,
margin=dict(l=60, r=40, t=60, b=40),
showlegend=False
)
return fig
def create_prediction_chart(predictions_df: pd.DataFrame) -> go.Figure:
"""Create Monte Carlo prediction visualization."""
if predictions_df.empty:
return None
fig = make_subplots(
rows=1, cols=2,
subplot_titles=("🏆 Win Probability", "📊 Expected Points"),
specs=[[{"type": "bar"}, {"type": "bar"}]]
)
top_10 = predictions_df.head(10)
# Win probability bars
fig.add_trace(
go.Bar(
y=top_10["Driver"],
x=top_10["Win %"] * 100,
orientation='h',
marker=dict(
color=top_10["Win %"],
colorscale=[[0, "#3671C6"], [0.5, "#FFB800"], [1, "#E10600"]],
line=dict(color='rgba(255,255,255,0.3)', width=1)
),
text=[f"{p*100:.1f}%" for p in top_10["Win %"]],
textposition='outside',
textfont=dict(family="Orbitron", size=10, color="white"),
hovertemplate="<b>%{y}</b><br>Win: %{x:.1f}%<extra></extra>"
),
row=1, col=1
)
# Expected points bars
fig.add_trace(
go.Bar(
y=top_10["Driver"],
x=top_10["Exp. Points"],
orientation='h',
marker=dict(
color=top_10["Exp. Points"],
colorscale=[[0, "#64C4FF"], [0.5, "#00D26A"], [1, "#E10600"]],
line=dict(color='rgba(255,255,255,0.3)', width=1)
),
text=[f"{p:.1f}" for p in top_10["Exp. Points"]],
textposition='outside',
textfont=dict(family="Orbitron", size=10, color="white"),
hovertemplate="<b>%{y}</b><br>Exp. Points: %{x:.1f}<extra></extra>"
),
row=1, col=2
)
fig.update_layout(
template="plotly_dark",
paper_bgcolor="rgba(0,0,0,0)",
plot_bgcolor="rgba(0,0,0,0)",
font=dict(family="Inter", color="white"),
height=450,
showlegend=False,
margin=dict(l=80, r=80, t=60, b=40)
)
fig.update_yaxes(autorange="reversed", tickfont=dict(family="Orbitron", size=10))
fig.update_xaxes(gridcolor="rgba(255,255,255,0.1)")
return fig
# ═══════════════════════════════════════════════════════════════════════════════
# 🎯 MAIN APPLICATION
# ═══════════════════════════════════════════════════════════════════════════════
def main():
"""Main application entry point."""
# ─────────────────────────────────────────────────────────────────────────
# HEADER
# ─────────────────────────────────────────────────────────────────────────
st.markdown("""
<div class="f1-header">
<h1>🏎️ F1 STRATEGY AI PRO</h1>
<p class="subtitle">Advanced Race Prediction • Monte Carlo Simulation • Real-Time Analysis</p>
</div>
""", unsafe_allow_html=True)
# ─────────────────────────────────────────────────────────────────────────
# SIDEBAR - MISSION CONTROL
# ─────────────────────────────────────────────────────────────────────────
with st.sidebar:
st.markdown("""
<div style="text-align: center; padding: 1rem 0;">
<span style="font-family: 'Orbitron', monospace; font-size: 1.2rem; color: #E10600; letter-spacing: 3px;">
MISSION CONTROL
</span>
</div>
""", unsafe_allow_html=True)
st.markdown("---")
# ═══════════════════════════════════════════════════════════════════
# DATA DOWNLOADER SECTION
# ═══════════════════════════════════════════════════════════════════
with st.expander("📡 **DATA DOWNLOADER**", expanded=False):
st.markdown("""
<div style="font-family: 'Inter', sans-serif; font-size: 0.8rem; color: rgba(255,255,255,0.6); margin-bottom: 1rem;">
Fetch F1 data directly from FastF1. Choose to download entire seasons, specific GPs, or individual sessions.
</div>
""", unsafe_allow_html=True)
# Download Mode Selection
download_mode = st.radio(
"Download Mode",
options=["🗓️ Full Season", "🏁 Single GP", "📊 Single Session"],
horizontal=True,
label_visibility="collapsed"
)
st.markdown("")
# ─────────────────────────────────────────────────────────────────
# MODE 1: FULL SEASON DOWNLOAD
# ─────────────────────────────────────────────────────────────────
if download_mode == "🗓️ Full Season":
st.markdown("##### 🗓️ Download Full Season")
current_year = datetime.now().year
fetch_year = st.number_input(
"Season Year",
min_value=2018,
max_value=current_year,
value=current_year,
step=1,
help="Select the F1 season year to download (2018-present)"
)
# Session selection for season
st.markdown("**Sessions to fetch:**")
season_sessions = []
col1, col2 = st.columns(2)
with col1:
if st.checkbox("FP1", value=True, key="season_fp1"): season_sessions.append("FP1")
if st.checkbox("FP2", value=True, key="season_fp2"): season_sessions.append("FP2")
if st.checkbox("FP3", value=True, key="season_fp3"): season_sessions.append("FP3")
if st.checkbox("Qualifying", value=True, key="season_q"): season_sessions.append("Q")
with col2:
if st.checkbox("Sprint Quali", value=False, key="season_sq"): season_sessions.append("SQ")
if st.checkbox("Sprint", value=False, key="season_s"): season_sessions.append("S")
if st.checkbox("Race", value=True, key="season_r"): season_sessions.append("R")
if st.button("🚀 DOWNLOAD SEASON", use_container_width=True, type="primary", key="btn_season"):
if not season_sessions:
st.warning("Select at least one session type")
else:
try:
import fastf1
schedule = fastf1.get_event_schedule(fetch_year)
# Filter out testing events
races = schedule[schedule["EventFormat"] != "testing"]
total_gps = len(races)
progress_bar = st.progress(0, text="Initializing...")
status_text = st.empty()
success_count = 0
fail_count = 0
for idx, (_, event) in enumerate(races.iterrows()):
round_num = int(event["RoundNumber"])
gp_name = event["EventName"]
progress = (idx + 1) / total_gps
progress_bar.progress(progress, text=f"Fetching {gp_name}...")
status_text.markdown(f"**Round {round_num}**: {gp_name}")
try:
results = fetch_gp(fetch_year, round_num, season_sessions)
session_success = sum(1 for v in results.values() if v)
success_count += session_success
except Exception as e:
fail_count += 1
st.warning(f"⚠️ {gp_name}: {str(e)[:50]}")
progress_bar.progress(1.0, text="Complete!")
st.success(f"✅ Downloaded {success_count} sessions from {total_gps} GPs")
if fail_count > 0:
st.warning(f"⚠️ {fail_count} GPs had errors")
st.rerun()
except Exception as e:
st.error(f"❌ Failed to fetch schedule: {str(e)}")
# ─────────────────────────────────────────────────────────────────
# MODE 2: SINGLE GP DOWNLOAD
# ─────────────────────────────────────────────────────────────────
elif download_mode == "🏁 Single GP":
st.markdown("##### 🏁 Download Single Grand Prix")
current_year = datetime.now().year
gp_year = st.number_input(
"Season Year",
min_value=2018,
max_value=current_year,
value=current_year,
step=1,
key="gp_year"
)
# Try to load schedule for GP selection
gp_identifier = None
try:
import fastf1
schedule = fastf1.get_event_schedule(gp_year)
races = schedule[schedule["EventFormat"] != "testing"]
gp_names = [f"R{int(row['RoundNumber']):02d} - {row['EventName']}"
for _, row in races.iterrows()]
selected_gp_name = st.selectbox(
"Select Grand Prix",
options=gp_names,
key="gp_select"
)
# Extract round number
gp_identifier = int(selected_gp_name.split(" - ")[0].replace("R", ""))
except Exception:
# Fallback to manual input
gp_input_method = st.radio(
"Identify GP by:",
options=["Round Number", "GP Name"],
horizontal=True,
key="gp_input_method"
)
if gp_input_method == "Round Number":
gp_identifier = st.number_input(
"Round Number",
min_value=1,
max_value=24,
value=1,
key="gp_round"
)
else:
gp_identifier = st.text_input(
"GP Name (e.g., Monaco, Silverstone)",
value="",
key="gp_name_input"
)
# Session selection for GP
st.markdown("**Sessions to fetch:**")
gp_sessions = []
col1, col2 = st.columns(2)
with col1:
if st.checkbox("FP1", value=True, key="gp_fp1"): gp_sessions.append("FP1")
if st.checkbox("FP2", value=True, key="gp_fp2"): gp_sessions.append("FP2")
if st.checkbox("FP3", value=True, key="gp_fp3"): gp_sessions.append("FP3")
if st.checkbox("Qualifying", value=True, key="gp_q"): gp_sessions.append("Q")
with col2:
if st.checkbox("Sprint Quali", value=False, key="gp_sq"): gp_sessions.append("SQ")
if st.checkbox("Sprint", value=False, key="gp_s"): gp_sessions.append("S")
if st.checkbox("Race", value=True, key="gp_r"): gp_sessions.append("R")
if st.button("🚀 DOWNLOAD GP", use_container_width=True, type="primary", key="btn_gp"):
if not gp_identifier:
st.warning("Please select or enter a GP")
elif not gp_sessions:
st.warning("Select at least one session type")
else:
with st.spinner(f"Fetching GP data from FastF1..."):
try:
results = fetch_gp(gp_year, gp_identifier, gp_sessions)
success_count = sum(1 for v in results.values() if v)
st.success(f"✅ Downloaded {success_count}/{len(gp_sessions)} sessions")
st.rerun()
except Exception as e:
st.error(f"❌ Error: {str(e)}")
# ─────────────────────────────────────────────────────────────────
# MODE 3: SINGLE SESSION DOWNLOAD
# ─────────────────────────────────────────────────────────────────
else: # Single Session
st.markdown("##### 📊 Download Single Session")
current_year = datetime.now().year
session_year = st.number_input(
"Season Year",
min_value=2018,
max_value=current_year,
value=current_year,
step=1,
key="session_year"
)
# GP identification
session_gp = st.text_input(
"GP Name or Round Number",
value="",
placeholder="e.g., Monaco, 7, Silverstone",
key="session_gp"
)
# Try to convert to int if it's a number
try:
session_gp_id = int(session_gp)
except ValueError:
session_gp_id = session_gp if session_gp else None
# Session type selection
session_type = st.selectbox(
"Session Type",
options=["FP1", "FP2", "FP3", "Q", "SQ", "S", "R"],
format_func=lambda x: {
"FP1": "🔧 Practice 1",
"FP2": "🔧 Practice 2",
"FP3": "🔧 Practice 3",
"Q": "⏱️ Qualifying",
"SQ": "⏱️ Sprint Qualifying",
"S": "🏃 Sprint Race",
"R": "🏁 Race"
}.get(x, x),
key="session_type"
)
if st.button("🚀 DOWNLOAD SESSION", use_container_width=True, type="primary", key="btn_session"):
if not session_gp_id:
st.warning("Please enter a GP name or round number")
else:
with st.spinner(f"Fetching {session_type} from FastF1..."):
try:
result = fetch_session(session_year, session_gp_id, session_type)
if result:
session_data, round_num, gp_name = result
save_session_json(session_data, session_year, round_num, gp_name, session_type)
st.success(f"✅ Downloaded {session_type} for {gp_name}")
st.rerun()
else:
st.error("❌ Session not available")
except Exception as e:
st.error(f"❌ Error: {str(e)}")
st.markdown("---")
# ═══════════════════════════════════════════════════════════════════
# DATA SELECTION SECTION
# ═══════════════════════════════════════════════════════════════════
st.markdown("""
<div style="font-family: 'Orbitron', monospace; font-size: 0.75rem; color: rgba(255,255,255,0.5);
text-transform: uppercase; letter-spacing: 2px; margin-bottom: 0.5rem;">
Data Selection
</div>
""", unsafe_allow_html=True)
# Season Selection
seasons = get_available_seasons()
if not seasons:
st.info("📡 No local data. Use Data Downloader above to fetch F1 data.")
selected_season = None
selected_gp = None
else:
selected_season = st.selectbox(
"📅 SELECT SEASON",
options=seasons,
format_func=lambda x: f"🏁 {x} Season"
)
# GP Selection
gps = get_available_gps(selected_season) if selected_season else []
if not gps:
st.warning(f"No GP data for {selected_season}")
selected_gp = None
else:
gp_options = {gp["folder"]: gp for gp in gps}
selected_gp_folder = st.selectbox(
"🏎️ SELECT GRAND PRIX",
options=list(gp_options.keys()),
format_func=lambda x: f"R{gp_options[x]['round']:02d} • {gp_options[x]['name']}"
)
selected_gp = gp_options.get(selected_gp_folder)
st.markdown("---")
# ═══════════════════════════════════════════════════════════════════
# QUICK ACTIONS
# ═══════════════════════════════════════════════════════════════════
st.markdown("""
<div style="font-family: 'Orbitron', monospace; font-size: 0.75rem; color: rgba(255,255,255,0.5);
text-transform: uppercase; letter-spacing: 2px; margin-bottom: 0.5rem;">
Quick Actions
</div>
""", unsafe_allow_html=True)
col1, col2 = st.columns(2)
with col1:
if st.button("REFRESH GP", use_container_width=True, type="primary"):
if selected_season and selected_gp:
with st.spinner("Refreshing GP data..."):
try:
results = fetch_gp(selected_season, selected_gp["round"])
success_count = sum(1 for v in results.values() if v)
st.success(f"✅ {success_count} sessions updated")
st.rerun()
except Exception as e:
st.error(f"❌ Error: {str(e)}")
else:
st.warning("Select a GP first")
with col2:
if st.button("CLEAR CACHE", use_container_width=True):
cache_dir = Path("f1_cache")
if cache_dir.exists():
import shutil
shutil.rmtree(cache_dir)
cache_dir.mkdir(exist_ok=True)
st.success("✅ Cache cleared")
else:
st.info("Cache is empty")
st.markdown("---")
# ═══════════════════════════════════════════════════════════════════
# SESSION STATUS
# ═══════════════════════════════════════════════════════════════════
if selected_gp:
st.markdown("""
<div style="font-family: 'Orbitron', monospace; font-size: 0.75rem; color: rgba(255,255,255,0.5);
text-transform: uppercase; letter-spacing: 2px; margin-bottom: 0.5rem;">
Session Status
</div>
""", unsafe_allow_html=True)
sessions = selected_gp.get("sessions", {})
# Create a grid layout for session badges
session_display = [
("FP1", "fp1", sessions.get("fp1", False)),
("FP2", "fp2", sessions.get("fp2", False)),
("FP3", "fp3", sessions.get("fp3", False)),
("QUALI", "Q", sessions.get("qualifying", False)),
("SQ", "SQ", sessions.get("sprint_qualifying", False)),
("SPRINT", "S", sessions.get("sprint", False)),
("RACE", "R", sessions.get("race", False)),
]
col1, col2 = st.columns(2)
for i, (name, session_code, available) in enumerate(session_display):
with col1 if i % 2 == 0 else col2:
if available:
st.markdown(f'<span class="status-badge status-available">✓ {name}</span>',
unsafe_allow_html=True)
else:
# Add fetch button for missing sessions
if st.button(f"📥 {name}", key=f"fetch_{session_code}", use_container_width=True):
with st.spinner(f"Fetching {name}..."):
try:
result = fetch_session(selected_season, selected_gp["round"], session_code)
if result:
session_data, round_num, gp_name = result