-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
executable file
·2728 lines (1854 loc) · 134 KB
/
app.py
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
from datetime import datetime
from email.policy import default
from unicodedata import category
import pandas as pd
import numpy as np
import streamlit as st
import requests
import fastf1
import fastf1.plotting
import matplotlib.pyplot as plt
from src.about import about_cs
#from src.carimages import fetch_carimgs
from pathlib import Path
import base64
from dateutil import parser
import plotly.graph_objects as go
import copy
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib import cm
import seaborn as sns
from src.attributions import attribute
import pycountry
from itertools import cycle
import pickle
# fastf1.Cache.enable_cache('./cache')
missing_endpoints = {'Abu Dhabi':"United Arab Emirates", 'UAE':"United Arab Emirates"}
def load_model():
reconstructed_model = load_model("data_mining_LSTM.h5")
return reconstructed_model
# default subroutines
def img_to_bytes(img_path):
img_bytes = Path(img_path).read_bytes()
encoded = base64.b64encode(img_bytes).decode()
return encoded
@st.cache_data
def load_carspecs():
with open('./data/CAR_SPECIFICATIONS_v3.pickle', 'rb') as f:
return pickle.load(f)
def fabricate_dict(dictionary):
if dictionary == []:
return "No Data"
else:
manifactured = {}
for string in dictionary:
if len(string.split(':')) == 1:
try:
key, value = string.split(';')
except:
key = string.split(':')[0]
value = 'No Data'
elif len(string.split(':'))>2:
ex = string.split(':')
l = [ex[0]]
l.append(','.join(ex[1:]))
key, value = l
else:
key, value = string.split(':')
manifactured[key] = value.strip()
return manifactured
def load_carimage_data():
df = pd.read_csv('./data/FINAL-CAR-IMAGES_2012-2022.csv')
return df
def load_miscellaneous_data():
rounds = pd.read_csv('./data/year_wise_rounds.csv').set_index('Unnamed: 0')
return rounds
@st.cache_data
def load_rounds():
rounds = pd.read_csv('./data/year_wise_rounds.csv')
rounds.columns = ['year','rounds']
years = rounds['year'].to_list()
round_v = rounds['rounds'].to_list()
rounds = {}
for year, r in zip(years, round_v):
rounds[year] = r
return rounds
def instantiate_API_keys():
API_elements = {
'drivers_wr': 'http://ergast.com/api/f1/{}/{}/drivers.json',
'drivers_wor': 'http://ergast.com/api/f1/{}/drivers.json'
}
return API_elements
def fetch_position_rank(const=None, driver=None,team=None,year=2022, individual=False):
if not individual:
pos = const.loc[year].loc[rounds[year]].reset_index()
position = pos[pos['Constructor']==team]['position'].values[0]
points = pos[pos['Constructor']==team]['points'].values[0]
return position, points
else:
pos = driver.loc[year].loc[rounds[year]].reset_index()
dr_standings = {}
for dr in pos[pos['Constructors'] == team].values:
pos, name, _, code, team, points, wins = dr
dr_standings[name] = [(pos, code, points, wins)]
return dr_standings
def drivers_summary(api_elements, yearwise_rounds):
# API access links
drivers_wr = api_elements['drivers_wr']
drivers_wor = api_elements['drivers_wor']
# test
data = requests.get(drivers_wor.format('2019'))
st.write(data.json())
def date_modifier(date_obj, type=1):
if date_obj != 'None':
if type == 1:
morphed_date = date_obj.strftime('%d %b, %Y')
elif type == 2:
morphed_date = date_obj.strftime('%d %b')
return morphed_date
else:
return None
@st.cache_data
def fetch_constructorStandings(range_list=[2014,2023], roundwise=False,rounds=None,verbose=False):
if roundwise == False:
dfs = []
years = list(range(*range_list))
for year in range(*range_list):
url = f'http://ergast.com/api/f1/{year}/constructorStandings.json'
response = requests.get(url)
constructor_standings = response.json()
itemlist = constructor_standings['MRData']['StandingsTable']['StandingsLists'][0]['ConstructorStandings']
teams = []
for item in itemlist:
teams.append(item['Constructor']['name'])
constructor_data = pd.DataFrame(itemlist)
constructor_data['Constructor'] = teams
constructor_data = constructor_data.set_index('position',drop=True)
constructor_data = constructor_data.drop('positionText',axis=1)
dfs.append(constructor_data)
return pd.concat(dfs, keys=years)
elif rounds != None and roundwise==True:
# roundwise constructors
dfs_y = {}
for year in range(*range_list):
dfs_r = []
for r in range(1,rounds[year]+1):
if verbose:
print(f'Constructors: fetching {year}, round:{r}')
url = f'http://ergast.com/api/f1/{year}/{r}/constructorStandings.json'
res = requests.get(url)
res = res.json()
item_list = res['MRData']['StandingsTable']['StandingsLists'][0]['ConstructorStandings']
teams = []
for item in item_list:
teams.append(item['Constructor']['name'])
constructor_data = pd.DataFrame(item_list)
constructor_data['Constructor'] = teams
constructor_data = constructor_data.set_index('position',drop=True)
constructor_data = constructor_data.drop('positionText',axis=1)
dfs_r.append(constructor_data)
dfs_y[year] = dfs_r
year_wise_data = []
for key in zip(dfs_y.keys()):
# print(key[0])
year_wise_data.append(pd.concat(dfs_y[key[0]], keys=range(1,rounds[year]+1)))
const = pd.concat(year_wise_data, keys=range(*range_list))
return const
@st.cache_data
def fetch_driverstandings(range_list=[2014,2023], rounds=None, roundwise=False,verbose=False):
if roundwise == False:
dfs = []
years = list(range(*range_list))
for year in range(*range_list):
url = f'http://ergast.com/api/f1/{year}/driverStandings.json'
response = requests.get(url)
drivers_standings = response.json()
item_list = drivers_standings['MRData']['StandingsTable']['StandingsLists'][0]['DriverStandings']
teams = []
for item in item_list:
teams.append(item['Constructors'][0]['name'])
driver_dict_list = []
for item in item_list:
driver_dict_list.append(item['Driver'])
ds = pd.DataFrame(item_list)
ds['Constructors'] = teams
ds = pd.concat([ds,pd.DataFrame(driver_dict_list)],axis=1)
ds['fullname'] = ds['givenName'] + ' ' + ds['familyName']
ds = ds.drop(['positionText','Driver','driverId','url','dateOfBirth','givenName','familyName','nationality'],axis=1)
ds = ds.set_index('position',drop=True)
col_order = ['fullname','permanentNumber','code','Constructors','points','wins']
dfs.append(ds[col_order])
pd.concat(dfs,keys=years).to_csv('driver_standings_2014_2023.csv',index=False)
return pd.concat(dfs,keys=years)
elif roundwise==True and rounds != None:
# Drivers Round Wise
dfs_y = {}
for year in range(*[2014,2023]):
dfs_r = []
for r in range(1,rounds[year]+1):
print(f'fetching {year}, round:{r}')
url = f'http://ergast.com/api/f1/{year}/{r}/driverStandings.json'
res = requests.get(url)
res = res.json()
item_list = res['MRData']['StandingsTable']['StandingsLists'][0]['DriverStandings']
teams = []
for item in item_list:
teams.append(item['Constructors'][0]['name'])
driver_dict_list = []
for item in item_list:
driver_dict_list.append(item['Driver'])
ds = pd.DataFrame(item_list)
ds['Constructors'] = teams
ds = pd.concat([ds,pd.DataFrame(driver_dict_list)],axis=1)
ds['fullname'] = ds['givenName'] + ' ' + ds['familyName']
ds = ds.drop(['positionText','Driver','driverId','url','dateOfBirth','givenName','familyName','nationality'],axis=1)
ds = ds.set_index('position',drop=True)
col_order = ['fullname','permanentNumber','code','Constructors','points','wins']
ds = ds[col_order]
dfs_r.append(ds)
dfs_y[year] = dfs_r
year_wise_data = []
for key in zip(dfs_y.keys()):
# print(key[0])
year_wise_data.append(pd.concat(dfs_y[key[0]], keys=range(1,rounds[year]+1)))
drivers = pd.concat(year_wise_data, keys=range(*range_list))
drivers.to_csv('driver_standings_2014_2023_roundwise.csv',index=False)
return drivers
@st.cache_data
def summarised_session(session,data,mode=None,round_number=None):
if session == "Qualifying":
items_required = ['DriverNumber', 'BroadcastName', 'Abbreviation', 'TeamName', 'TeamColor', 'FullName', 'Position']
if mode == 'Knocked':
round_dict = {'Q1':'Q1', 'Q2':'Q1','Q3':'Q2'}
items_required.append(round_dict[round_number])
package = {}
temp_package = {}
if data[data[round_number]=='0'].empty:
return None
else:
for item in items_required:
temp_package[item] = data[data[round_number]=='0'].T.loc[item]
package['driver_data'] = temp_package
package['round_number'] = round_number
return package
elif mode == 'Final Grid-Positions':
x = data.copy(deep=True)
package = {}
temp_package = {}
for item in items_required:
temp_package[item] = x[item].to_list()
package['driver_data'] = temp_package
order = x['DriverNumber'].to_list()
x = x.set_index('DriverNumber',drop=True)
Q3t = x[x['Q3'] !='0']['Q3']
Q3_idx = Q3t.index
Q2t = x[x['Q2'] !='0']['Q2'].drop(Q3_idx,axis=0)
Q2_idx = Q2t.index
idx_compiled = list(Q3_idx) + list(Q2_idx)
if x[x['Q1'] == '0'].empty:
Q1t = x[x['Q1'] != '0']['Q1']
Q1t = Q1t.drop(idx_compiled, axis=0)
times= Q3t.append((Q2t,Q1t))
else:
no_time = x[x['Q1'] == '0']['Q1']
Q1t = x[x['Q1'] != '0']['Q1']
Q1t = Q1t.drop(idx_compiled, axis=0)
times= Q3t.append((Q2t,Q1t,no_time))
package['Times'] = times
return package
elif mode in ["Q1 Grid-Positions", "Q2 Grid-Positions", "Q3 Grid-Positions"]:
data = data[data[round_number] != '0']
temp_package = {}
package = {}
for item in items_required:
temp_package[item] = data[item].to_list()
package['driver_data'] = temp_package
package['Times'] = data[round_number]
return package
elif mode in ["Practice 1", "Practice 2", "Practice 3"]:
pass
@st.cache_resource
def load_session_data(year, event, session_select):
session_obj = fastf1.get_session(year, event, session_select)
with st.spinner(session_obj.load()):
session_results = session_obj.results.reset_index(drop=True)
return session_results, session_obj
@st.cache_resource
def return_session_object(year,event, session_select):
session = fastf1.get_session(year, event, session_select)
with st.spinner(session.load()):
pass
return session
@st.cache_resource (show_spinner=True)
def fetch_event_schedule(year):
event_schedule = fastf1.get_event_schedule(year)
event_names = event_schedule['EventName'].to_list()
event_names.insert(0, "List of Grand Prix's")
return event_names, event_schedule
def display_schedule(year, circuit_cdf, circuits_rdf):
event_schedule = fastf1.get_event_schedule(year)
event_names = event_schedule['EventName'].to_list()
# st.code(event_schedule['OfficialEventName'])
circuit_flag = 0
for event_name in event_names:
# slicing data
event_data = event_schedule[event_schedule['EventName'] == event_name].T
event_data = event_data.fillna('None')
# circuit = circuits_df.loc[event_name, 'Circuits']
# locality = circuits_df.loc[event_name, 'Localities']
country = event_data.loc['Country'].values[0]
# circuit name
try:
circuit = circuits_rdf.loc[event_name, 'Circuits']
locality = circuits_rdf.loc[event_name, 'Localities']
except:
circuit = circuits_cdf.loc[country, 'Circuits']
locality = circuits_cdf.loc[country, 'Localities']
# packaging event summarised-information
package = {}
items = event_schedule.columns[:-1]
for item in items:
package[item] = event_data.loc[item].values[0]
sessions_list = [package[x] for x in ['Session'+str(i) for i in range(1,6)]]
# checkered flag
current_date = datetime.now()
try:
flag = pycountry.countries.search_fuzzy(package["Country"].lower())[0].flag
except:
flag = pycountry.countries.search_fuzzy(missing_endpoints[package["Country"]])[0].flag
if current_date > package['EventDate']:
st.markdown(f'''<p style="font-size:30px; font-weight:bold; font-family:formula1, syne;"> {flag} <u>{package["EventName"]}</u> | <span style="font-size:23px;">{date_modifier(package["EventDate"])} <br>{circuit}, {locality} <img src='data:image/png;base64,{img_to_bytes('./assets/checkered-flag.png')}' class='img-fluid' width=50 ></span> </p>''',unsafe_allow_html=True)
else:
st.markdown(f'''<p style="font-size:30px; font-weight:bold; font-family:formula1, syne;"> {flag} <u>{package["EventName"]}</u> | <span style="font-size:23px;">{date_modifier(package["EventDate"])} <br>{circuit}, {locality} </span></p>''',unsafe_allow_html=True)
cols = st.columns(len(sessions_list))
for i, session_name in enumerate(sessions_list, start=0) :
cols[i].markdown('> <p style="font-size:17px; font-weight:bold; font-family:formula1, syne;"><u>{}</u><p>'.format(session_name),unsafe_allow_html=True)
cols[i].markdown('> <p style="font-size:13px; font-weight:bold; font-family:formula1, syne;">{}<p>'.format(date_modifier(package['Session'+str(i+1)+"Date"])),unsafe_allow_html=True)
st.markdown('***')
def timedelta_conversion(timevar):
if timevar.seconds == 0 and timevar.microseconds == 0:
return 'No Time'
else:
return parser.parse(str(timevar).split(' ')[-1:][0]).strftime('%-M:%S:%f')
def delta_variation(driver_time, fastest_time):
if driver_time > fastest_time:
positive_delta = driver_time - fastest_time
return '+{}'.format(str(positive_delta).split('.')[-1:][0][:4])
elif driver_time < fastest_time:
negative_delta = driver_time - fastest_time
return '-{}'.format(str(negative_delta).split('.')[-1:][0][:4])
else:
return '000'
@st.cache_resource
def fetch_circuits_data(year):
url = f'http://ergast.com/api/f1/{year}.json'
result= requests.get(url)
races = result.json()['MRData']['RaceTable']['Races']
localities = []
countries = []
circuits = []
racenames = []
for race in races:
circuits.append(race['Circuit']['circuitName'])
racenames.append(race['raceName'])
countries.append(race['Circuit']['Location']['country'])
localities.append(race['Circuit']['Location']['locality'])
circuits_df = {'Countries': countries, 'Localities': localities, 'Circuits': circuits, 'Race Name':racenames, }
circuits_rdf = pd.DataFrame(circuits_df).set_index('Race Name',drop=True)
circuits_cdf = pd.DataFrame(circuits_df).set_index('Countries',drop=True)
return circuits_cdf, circuits_rdf
def fetch_circuit_name():
pass
def speed_visualisation(package, mode):
if len(package) == 2:
iterations = 2
else:
iterations = 1
fig = go.Figure()
for i in range(iterations):
x, y, color, AB = package[i]
if mode == 'different':
fig.add_trace(go.Scatter(x=x, y=y,
line = dict(color=color),
mode='lines',
name=f'{AB} Speed'))
else:
fig.add_trace(go.Scatter(x=x, y=y,
mode='lines',
name=f'{AB} Speed'))
fig.update_layout(paper_bgcolor="#e5e9f0", template='seaborn', showlegend=True)
return fig
def gear_heatmap(x,y,tel,driver,event,year):
'''
This code snippet is lifted from the official fastf1 documentation
'''
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
gear = tel['nGear'].to_numpy().astype(float)
cmap = cm.get_cmap('Paired')
lc_comp = LineCollection(segments, norm=plt.Normalize(1, cmap.N+1), cmap=cmap)
lc_comp.set_array(gear)
lc_comp.set_linewidth(4)
plt.gca().add_collection(lc_comp)
plt.axis('equal')
plt.tick_params(labelleft=False, left=False, labelbottom=False, bottom=False)
# title = plt.suptitle(
# f"Lap Gear Shift Visualization\n"
# f"{driver} - {event} {year}"
# )
cbar = plt.colorbar(mappable=lc_comp, label="Gear", boundaries=np.arange(1, 10))
cbar.set_ticks(np.arange(1.5, 9.5))
cbar.set_ticklabels(np.arange(1, 9))
st.pyplot(plt.show())
def bump_plot(driver, team=None, mode='overall', year=2022, team_color=None ):
if mode == 'team':
if team_color == None:
team_color = 'orange'
plt.style.use('seaborn-darkgrid')
test = driver.loc[year].reset_index()
plt.style.use('seaborn-whitegrid')
plt.figure(figsize=(11,8))
sns.lineplot(data=test[test['Constructors']==team], x='level_0',y='position',
style='code',
markers=True,linewidth=3, color=team_color )
plt.xticks(ticks=list(range(1,rounds[year])))
plt.legend(bbox_to_anchor =(1.25,1), loc='lower right')
plt.xlabel('Rounds',size=15)
plt.ylabel('Position',size=15)
plt.title(f'{team}, Drivers-Standing: Position Vs Rounds for the Year {year}')
elif mode == 'overall':
plt.style.use('seaborn-darkgrid')
test = driver.loc[year].reset_index()
plt.style.use('seaborn-whitegrid')
plt.figure(figsize=(11,8))
sns.lineplot(data=test, x='level_0',y='position',
style='code', hue='Constructors',
markers=True,linewidth=3, palette='Set2' )
plt.xticks(ticks=list(range(1,rounds[year])))
plt.legend(bbox_to_anchor =(1.25,-0.1), loc='lower right')
plt.xlabel('Rounds',size=15)
plt.ylabel('Position',size=15)
plt.title(f'Drivers Standing Position Vs Rounds for the Year {year}')
def qualifying_comparison(driver1, driver2, joined, driver_dict, delta_required, session_obj, event, year, mode):
AB2, BN2, TN2, TC2 = driver_dict[driver2]
driver2_data = joined.pick_driver(AB2).pick_fastest()
driver2_compound = driver2_data['Compound']
Comparison = [driver1, driver2]
cols = st.columns([6,6])
for i, driver in enumerate(Comparison, 0):
cols[i].markdown('***')
AB, BN, TN, TC = driver_dict[driver]
if TN == 'Haas F1 Team':
TC = 'bcbcbc'
# cols[1].markdown('')
if mode == 'different':
cols[i].markdown(f'''<h5 style="font-family:formula1, syne; font-weight:800;">{BN} <br><sub style='color:#{TC};'> {TN}</sub></h4>''',unsafe_allow_html=True)
# cols[0].markdown('')
# cols[0].markdown('')
else:
cols[i].markdown(f'''<h5 style="font-family:formula1, syne; font-weight:800;">{BN} <sub>({AB})</sub></h5>''',unsafe_allow_html=True)
# cols[1].markdown('')
cols[i].markdown('***')
# driver_data
driver_data = joined.pick_driver(AB)
# fastest-lap and compound
if driver_data.empty or pd.isnull(driver_data.pick_fastest()).all():
st.error(f'''{BN}, has no Lap Records!.''')
else:
# Fastest Lap
driver_data = joined.pick_driver(AB).pick_fastest()
# compounds
compound = driver_data['Compound'].lower()
# flags
if pd.isnull(driver2_data).all():
control = 'halt'
elif pd.isnull(driver_data).all():
# cols[0].warning("The Driver has No Lap Records!")
control = 'halt'
else:
control = 'continue'
if control == 'continue':
# delta driver1 in-contrast to driver2
delta_dict = {}
for item in delta_required:
delta_dict[item] = delta_variation(driver_data[item], driver2_data[item])
if driver_data['IsPersonalBest']:
cols[i].markdown(f'''> <h5 style="font-family:formula1, syne; color:purple;">Lap Time - {timedelta_conversion(driver_data['LapTime'])} <sub style='color:black;'>Personal Best</sub></h5>''',unsafe_allow_html=True)
else:
cols[i].markdown(f'''> <h5 style="font-family:formula1, syne; color:purple;">Lap Time - {timedelta_conversion(driver_data['LapTime'])}</h5>''',unsafe_allow_html=True)
cols[i].markdown(f'''<h6 style="font-family:formula1, syne;"><u>Sector Times</u></h6>''',unsafe_allow_html=True)
# for j, item in enumerate(delta_required[1:],1):
# st.write(delta_dict)
cols[i].markdown(f'''<h6 style="font-family:formula1, syne; ">S1 - {timedelta_conversion(driver_data["Sector1Time"])} <sub>{delta_dict['Sector1Time']} ({driver2_data['Driver']})</sub></h6>''',unsafe_allow_html=True)
cols[i].markdown(f'''<h6 style="font-family:formula1, syne; ">S2 - {timedelta_conversion(driver_data["Sector2Time"])} <sub>{delta_dict['Sector2Time']} ({driver2_data['Driver']})</sub></h6>''',unsafe_allow_html=True)
cols[i].markdown(f'''<h6 style="font-family:formula1, syne; ">S3 - {timedelta_conversion(driver_data["Sector3Time"])} <sub>{delta_dict['Sector3Time']} ({driver2_data['Driver']})</sub></h6>''',unsafe_allow_html=True)
cols[i].markdown('***')
# compound
cols[i].markdown(f'''<h6 style="font-family:formula1, syne"><u>Compounds Used</u></h6>''',unsafe_allow_html=True)
cols[i].markdown(f'''<h6 style="font-family:formula1, syne; "><img src='data:image/png;base64,{img_to_bytes(f'./assets/{compound}.png')}' class='img-fluid' width=70 > {compound.upper()} Compound, <br> Tyre Life <span style='font-size:28px'>{driver_data['TyreLife']}</span> Laps</h6>''',unsafe_allow_html=True)
cols[i].markdown('***')
# Speed Traps
cols[i].markdown(f'''<h6 style="font-family:formula1, syne;"><u>Speed Traps</u></h6>''',unsafe_allow_html=True)
cols[i].markdown(f'''<h6 style="font-family:formula1, syne; ">Sector1 Speed - <span style='font-size:28px'>{driver_data['SpeedI1']}<sup>km/h</sup></span> </h6>''',unsafe_allow_html=True)
cols[i].markdown(f'''<h6 style="font-family:formula1, syne; ">Sector2 Speed - <span style='font-size:28px'>{driver_data['SpeedI2']} <sup>km/h</sup></span> </h6>''',unsafe_allow_html=True)
cols[i].markdown(f'''<h6 style="font-family:formula1, syne; ">Finish Line Speed - <span style='font-size:28px'>{driver_data['SpeedFL']} <sup>km/h</sup></span> </h6>''',unsafe_allow_html=True)
cols[i].markdown(f'''<h6 style="font-family:formula1, syne; ">Longest Straight Speed - <span style='font-size:28px'>{driver_data['SpeedST']} <sup>km/h</sup></span> </h6>''',unsafe_allow_html=True)
cols[i].markdown('***')
cols[i].markdown(f'''<h6 style="font-family:formula1, syne;"><u>Weather Data</u></h6>''',unsafe_allow_html=True)
cols[i].markdown(f'''<h6 style="font-family:formula1, syne;">Air Temperature - {driver_data['AirTemp']} °C</h6>''',unsafe_allow_html=True)
cols[i].markdown(f'''<h6 style="font-family:formula1, syne;">Track Temperature - {driver_data['TrackTemp']} °C</h6>''',unsafe_allow_html=True)
cols[i].markdown(f'''<h6 style="font-family:formula1, syne;">Humidity - {driver_data['Humidity']}%</h6>''',unsafe_allow_html=True)
cols[i].markdown(f'''<h6 style="font-family:formula1, syne;">Pressure - {driver_data['Pressure']} Pa</h6>''',unsafe_allow_html=True)
cols[i].markdown(f'''<h6 style="font-family:formula1, syne;">Wind Direction - {driver_data['WindDirection']}°</h6>''',unsafe_allow_html=True)
cols[i].markdown(f'''<h6 style="font-family:formula1, syne;">Wind Speed - {driver_data['WindSpeed']} Kmph</h6>''',unsafe_allow_html=True)
if driver_data['Rainfall']:
cols[i].markdown(f'''<h6 style="font-family:formula1, syne;"> Climate - <img src='data:image/png;base64, {img_to_bytes('./assets/rain.gif')}' class='img-fluid', width=35> </h6>''',unsafe_allow_html=True)
else:
cols[i].markdown(f'''<h6 style="font-family:formula1, syne;"> Climate - <img src='data:image/png;base64, {img_to_bytes('./assets/no-rain.gif')}' class='img-fluid', width=35> </h6>''',unsafe_allow_html=True)
cols[i].markdown('***')
try:
lap = session_obj.laps.pick_driver(AB).pick_fastest()
tel = lap.get_telemetry()
x = np.array(tel['X'].values)
y = np.array(tel['Y'].values)
cols[i].markdown(f'''<h6 style="font-family:formula1, syne;"><u>Lap Gear Shift Visualization</u></h6>''',unsafe_allow_html=True)
expander = cols[i].expander(f'{BN}',expanded=True)
with expander:
gear_heatmap(x,y,tel,driver,event,year)
except:
st.warning('Data Descrepancy!, No Telemetry Records Found. ')
if i ==0:
st.markdown('***')
# st.markdown(f'''<h6 style="font-family:formula1, syne;"><u>Speed Chart Comparison</u></h6>''',unsafe_allow_html=True)
st.markdown(f'''<h6 style="font-family:formula1, syne;"><u>Speed Vs Distance Visualisation</u>, <br> {AB} Vs {AB2} - {event} {year}</h6>''',unsafe_allow_html=True)
driver_lap = session_obj.laps.pick_driver(AB).pick_fastest()
driver_tel = driver_lap.get_car_data().add_distance()
driver2_lap = session_obj.laps.pick_driver(AB2).pick_fastest()
driver2_tel = driver2_lap.get_car_data().add_distance()
try:
driver_color = '#'+TC
driver2_color = '#'+TC2
except:
driver_color = 'gold'
driver2_color = 'purple'
x1 = driver_tel['Distance']
y1 = driver_tel['Speed']
x2 = driver2_tel['Distance']
y2 = driver2_tel['Speed']
package = [(x1, y1, driver_color, AB),(x2, y2, driver2_color, AB2)]
fig = speed_visualisation(package, mode=mode)
# context = f'{AB} Speed'
st.plotly_chart(fig)
st.markdown('***')
def qualifying(summarised_results, year, session_obj):
# Driver dict
drivers = summarised_results['FullName'].to_list()
driver_dict = {}
for driver in drivers:
temp_list = temp_list = [summarised_results[summarised_results['FullName']==driver].loc[:,'Abbreviation'].values[0],
summarised_results[summarised_results['FullName']==driver].loc[:,'BroadcastName'].values[0],
summarised_results[summarised_results['FullName']==driver].loc[:,'TeamName'].values[0],
summarised_results[summarised_results['FullName']==driver].loc[:,'TeamColor'].values[0],
]
driver_dict[driver] = temp_list
preference = st.select_slider('Preference', [ 'Summarise', 'Get Nerdy!' ],key='mode of information')
if preference == 'Summarise':
st.markdown(f'''<h6 style="font-family:formula1, syne;">{session_select} Summary</h6>''',unsafe_allow_html=True)
select_choice = st.selectbox('Data Summary', ['Choose','Q1 Grid-Positions', 'Q2 Grid-Positions', 'Q3 Grid-Positions', 'Knocked Out', 'Final Grid-Positions'])
if not select_choice == 'Choose':
if select_choice == 'Knocked Out':
# latice of if-else structure
knocked_q1 = summarised_session('Qualifying',summarised_results, 'Knocked', round_number='Q1')
knocked_q2 = summarised_session('Qualifying',summarised_results, 'Knocked', round_number='Q2')
knocked_q3 = summarised_session('Qualifying',summarised_results, 'Knocked', round_number='Q3')
tq2 = copy.deepcopy(knocked_q2)
tq3 = copy.deepcopy(knocked_q3)
# Repeating knockout drivers
if not knocked_q1 == None:
tq2['driver_data'] = dict(pd.DataFrame(tq2['driver_data']).set_index('DriverNumber').drop(knocked_q1['driver_data']['DriverNumber'].to_list(),axis=0).reset_index())
tq3['driver_data'] = dict(pd.DataFrame(tq3['driver_data']).set_index('DriverNumber').drop(knocked_q1['driver_data']['DriverNumber'].to_list(),axis=0).reset_index())
tq3['driver_data'] = dict(pd.DataFrame(tq3['driver_data']).set_index('DriverNumber').drop(tq2['driver_data']['DriverNumber'].to_list(),axis=0).reset_index())
if knocked_q1 == None:
st.markdown(f'''> <h5 style="font-family:formula1, syne;">Everyone Qualified Q1</h5>''',unsafe_allow_html=True)
else:
st.markdown(f'''> <h5 style="font-family:formula1, syne;"><u>Q1 Knockouts</u></h5>''',unsafe_allow_html=True)
display_qualifying_summary(knocked_q1, mode='Knocked')
if knocked_q2 == None:
st.markdown(f'''<h5 style="font-family:formula1, syne;">Everyone Qualified Q2</h5>''',unsafe_allow_html=True)
else:
st.markdown(f'''> <h5 style="font-family:formula1, syne;"><u>Q2 Knockouts</u></h5>''',unsafe_allow_html=True)
display_qualifying_summary(tq2, mode='Knocked')
if knocked_q3 == None:
st.markdown(f'''<h5 style="font-family:formula1, syne;">Everyone Qualified Q3</h5>''',unsafe_allow_html=True)
else:
st.markdown(f'''> <h5 style="font-family:formula1, syne;"><u>Q3 Knockouts</u></h5>''',unsafe_allow_html=True)
display_qualifying_summary(tq3,mode='Knocked')
elif select_choice == 'Final Grid-Positions':
full_grid = summarised_session('Qualifying',summarised_results, 'Final Grid-Positions')
display_qualifying_summary(full_grid, mode='Final Grid-Positions')
elif select_choice == 'Q1 Grid-Positions':
q1_grid = summarised_session('Qualifying',summarised_results, 'Q1 Grid-Positions', round_number='Q1')
display_qualifying_summary(q1_grid, mode='Q1 Grid-Positions')
elif select_choice == 'Q2 Grid-Positions':
q1_grid = summarised_session('Qualifying',summarised_results, 'Q2 Grid-Positions', round_number='Q2')
display_qualifying_summary(q1_grid, mode='Q2 Grid-Positions')
elif select_choice == 'Q3 Grid-Positions':
q1_grid = summarised_session('Qualifying',summarised_results, 'Q3 Grid-Positions', round_number='Q3')
display_qualifying_summary(q1_grid, mode='Q3 Grid-Positions')
else:
if year >= 2018:
st.markdown(f'''<h6 style="font-family:formula1, syne;">{session_select} Comprehensive Analysis</h6>''',unsafe_allow_html=True)
cols = st.columns([6,3])
placeholder = cols[1].empty()
analysis_type = cols[0].selectbox('Select to Investigate', ['Analysis Type?','Driver Performance Analysis', 'Team Performance Analysis'],key='key-analysis')
placeholder.selectbox('?',[])
# laps
laps = session_obj.laps.reset_index(drop=True)
# weather data
weather_data = session_obj.laps.get_weather_data()
weather_data = weather_data.reset_index(drop=True)
# club data
joined = pd.concat([laps, weather_data.loc[:, ~(weather_data.columns == 'Time')]], axis=1) #from the fastf1 documentation
delta_required = [ 'LapTime',
'Sector1Time',
'Sector2Time',
'Sector3Time', ]
if analysis_type == 'Driver Performance Analysis':
# overwrite placeholder selectbox
analysis_mode = placeholder.selectbox('Type of Analysis', ['Individual','Comparative'])
if analysis_mode == 'Individual':
driver = st.selectbox('Choose Driver', driver_dict.keys())
fastest_driver = list(driver_dict.keys())[0]
st.markdown('***')
st.markdown(f'''<h6 style="font-family:formula1, syne;"><u> Driver Performance Investigation</u></h6>''',unsafe_allow_html=True)
AB, BN, TN, TC = driver_dict[driver]
st.markdown(f'''<h6 style="font-family:formula1, syne;">Fastest Lap Analysis</h6>''',unsafe_allow_html=True)
st.markdown(f'''<h4 style="font-family:formula1, syne; font-weight:800;">{BN} ({AB})<sub style='color:#{TC}'>{TN}</sub></h4>''',unsafe_allow_html=True)
# session data
# session = return_session_object(year, event, session_select)
# compounds
driver_data = joined.pick_driver(AB)
if driver_data.empty or pd.isnull(driver_data.pick_fastest()).all():
st.error(f'''No Time recorded, is either Knocked out or Data is Invalidated.''')
else:
compounds_used = list(driver_data['Compound'].dropna().unique())
# Fastest Lap
driver_data = joined.pick_driver(AB).pick_fastest()
compound = driver_data['Compound'].lower()
# fastest time in that session
fastest = joined.pick_fastest()
fcompound = fastest['Compound'].lower()
fdriver = fastest['Driver']
# st.write(fdriver)
# st.write()
# Lap and Sector Times
# positive and negative delta
delta_dict = {}
for item in delta_required:
delta_dict[item] = delta_variation(driver_data[item], fastest[item])
# st.write(delta_dict)
if driver_data['IsPersonalBest']:
st.markdown(f'''> <h5 style="font-family:formula1, syne; color:purple;">Lap Time - {timedelta_conversion(driver_data['LapTime'])} <sub style='color:black;'>Personal Best</sub></h5>''',unsafe_allow_html=True)
else:
st.markdown(f'''> <h5 style="font-family:formula1, syne; color:purple;">Lap Time - {timedelta_conversion(driver_data['LapTime'])}</h5>''',unsafe_allow_html=True)
st.markdown(f'''<h6 style="font-family:formula1, syne;"><u>Sector Times</u></h6>''',unsafe_allow_html=True)
for i,item in enumerate(delta_required[1:],1):
st.markdown(f'''<h6 style="font-family:formula1, syne; ">S{i} - {timedelta_conversion(driver_data[item])} <sub>{delta_dict[item]} ({fastest['Driver']})</sub></h6>''',unsafe_allow_html=True)
st.markdown('***')
# compound
st.markdown(f'''<h6 style="font-family:formula1, syne"><u>Compounds Used</u></h6>''',unsafe_allow_html=True)
st.markdown(f'''<h6 style="font-family:formula1, syne; "><img src='data:image/png;base64,{img_to_bytes(f'./assets/{compound}.png')}' class='img-fluid' width=70 > {compound.upper()} Compound, Tyre Life <span style='font-size:28px'>{driver_data['TyreLife']}</span> Laps</h6>''',unsafe_allow_html=True)
st.markdown('***')
if not driver_data['Driver'] == fdriver:
# Speed Traps
st.markdown(f'''<h6 style="font-family:formula1, syne;"><u>Speed Traps</u></h6>''',unsafe_allow_html=True)
st.markdown(f'''<h6 style="font-family:formula1, syne; ">Sector1 Speed - <span style='font-size:28px'>{driver_data['SpeedI1']}<sup>km/h</sup></span> <sub>{fastest['SpeedI1']} km/h ({fastest['Driver']}) <img src='data:image/png;base64,{img_to_bytes(f'./assets/{fcompound}.png')}' class='img-fluid' width=40></sub></h6>''',unsafe_allow_html=True)
st.markdown(f'''<h6 style="font-family:formula1, syne; ">Sector2 Speed - <span style='font-size:28px'>{driver_data['SpeedI2']} <sup>km/h</sup></span> <sub>{fastest['SpeedI2']} km/h ({fastest['Driver']}) <img src='data:image/png;base64,{img_to_bytes(f'./assets/{fcompound}.png')}' class='img-fluid' width=40></sub></h6>''',unsafe_allow_html=True)
st.markdown(f'''<h6 style="font-family:formula1, syne; ">Finish Line Speed - <span style='font-size:28px'>{driver_data['SpeedFL']} <sup>km/h</sup></span> <sub>{fastest['SpeedFL']} km/h ({fastest['Driver']}) <img src='data:image/png;base64,{img_to_bytes(f'./assets/{fcompound}.png')}' class='img-fluid' width=40></sub></h6>''',unsafe_allow_html=True)
st.markdown(f'''<h6 style="font-family:formula1, syne; ">Longest Straight Speed - <span style='font-size:28px'>{driver_data['SpeedST']} <sup>km/h</sup></span> <sub>{fastest['SpeedST']} km/h ({fastest['Driver']}) <img src='data:image/png;base64,{img_to_bytes(f'./assets/{fcompound}.png')}' class='img-fluid' width=40></sub></h6>''',unsafe_allow_html=True)
else:
st.markdown(f'''<h6 style="font-family:formula1, syne;"><u>Speed Traps</u></h6>''',unsafe_allow_html=True)
st.markdown(f'''<h6 style="font-family:formula1, syne; ">Sector1 Speed - <span style='font-size:28px'>{driver_data['SpeedI1']}<sup>km/h</sup></span> </h6>''',unsafe_allow_html=True)
st.markdown(f'''<h6 style="font-family:formula1, syne; ">Sector2 Speed - <span style='font-size:28px'>{driver_data['SpeedI2']} <sup>km/h</sup></span> </h6>''',unsafe_allow_html=True)
st.markdown(f'''<h6 style="font-family:formula1, syne; ">Finish Line Speed - <span style='font-size:28px'>{driver_data['SpeedFL']} <sup>km/h</sup></span> </h6>''',unsafe_allow_html=True)
st.markdown(f'''<h6 style="font-family:formula1, syne; ">Longest Straight Speed - <span style='font-size:28px'>{driver_data['SpeedST']} <sup>km/h</sup></span> </h6>''',unsafe_allow_html=True)
st.markdown('***')