-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
347 lines (310 loc) · 10.8 KB
/
utils.py
File metadata and controls
347 lines (310 loc) · 10.8 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
import numpy as np
import datetime as dt
from time import time
from time import ctime
import fastf1 as ff1
import pathlib
import platform
from pymongo import MongoClient
import os
from dotenv import load_dotenv
platform.system()
load_dotenv()
connection_string = os.getenv("connection_string")
db_name = os.getenv("db_name")
client = MongoClient(connection_string)
db = client[db_name]
### UTIL FUNCTIONS ###
# get_datetime helper
def get_time():
return ctime(time())
# get current time
def get_datetime():
datetime = get_time()
datetime = datetime.replace(" ", "-")
datetime = datetime.replace(":", ".")
return datetime
# get parth of file
dir_path = r"" + str(pathlib.Path(__file__).parent.resolve())
# get path separator for os
def get_path():
return os.sep
# load the session
def get_sess(yr, rc, sn):
try:
rc = int(rc)
except:
pass
session_type = "normal"
if yr == 2020:
if rc == "Pre-Season Test 1":
session_type = "1"
elif rc == "Pre-Season Test 2":
session_type = "2"
elif yr == 2021:
if rc == "Pre-Season Test":
session_type = "1"
elif yr == 2022:
if rc == "Pre-Season Track Session":
session_type = "1"
elif rc == "Pre-Season Test":
session_type = "2"
elif yr >= 2023:
if "Pre-Season" in str(rc):
session_type = "1"
if session_type == "1" or session_type == "2":
if sn == "Day 1":
sn = 1
elif sn == "Day 2":
sn = 2
elif sn == "Day 3":
sn = 3
if session_type == "normal":
session = ff1.get_session(yr, rc, sn)
elif session_type == "1":
session = ff1.get_testing_session(yr, 1, sn)
elif session_type == "2":
session = ff1.get_testing_session(yr, 2, sn)
session.load()
try:
fix = session.laps.pick_fastest()
except:
pass
return session
# enable cache
if os.path.exists(dir_path + get_path() + "doc_cache"):
ff1.Cache.enable_cache(dir_path + get_path() + "doc_cache")
###
### gets the years for which data is available for each function ###
def get_years(func):
years = []
func = func.lower()
if func == "results" or func == "schedule" or func == "drivers" or func == "points":
for i in range(1950, dt.datetime.now().year+1):
years.append(i)
elif func == "constructors":
for i in range(1958, dt.datetime.now().year+1):
years.append(i)
else:
for i in range(2018, dt.datetime.now().year+1):
years.append(i)
return years[::-1]
### get races of a given year ###
def get_races(yr):
collection_name = "races"
collection = db[collection_name]
doc = collection.find_one({"year": int(yr)})
return doc["races"]
### gets sessions of a grand prix weekend ###
def get_sessions(yr, rc):
if "Pre-Season" in rc:
return ['Day 1', 'Day 2', 'Day 3']
else:
yr = int(yr)
sessions = []
i=1
while True:
sess = 'Session' + str(i)
fastf1_obj = ff1.get_event(yr, rc)
try:
sessions.append((getattr(fastf1_obj, sess)))
except:
break
i+=1
return sessions
### gets drivers of a session ###
def get_drivers(yr, rc, sn):
session = get_sess(yr, rc, sn)
session.load()
laps = session.laps
ls = set(tuple(x) for x in laps[['Driver']].values.tolist())
lis = [x[0] for x in ls]
return lis
### gets laps of a session ###
def get_laps(yr, rc, sn):
session = get_sess(yr, rc, sn)
session.load()
laps = session.laps
ls = set(tuple(x) for x in laps[['LapNumber']].values.tolist())
lis = sorted([int(x[0]) for x in ls])
max = int(np.max(lis))
res = []
for i in range(1, max+1):
res.append(i)
return res
### gets distance of a session ###
def get_distance(yr, rc, sn):
session = get_sess(yr, rc, sn)
session.load()
laps = session.laps
car_data = laps.pick_fastest().get_car_data().add_distance()
maxdist = int(np.max(car_data['Distance']))
res = []
for i in range(0, maxdist+1, 100):
res.append(i)
res.append(maxdist)
return res
### db ###
def get_races_from_db(func, yr):
collection = db["races"]
doc = collection.find_one({"year": int(yr)})
if doc is None:
return []
races = doc["races"]
res = []
for race in races:
if race not in res:
res.append(race)
return res
def get_sessions_from_db(yr, rc):
# Always return full session list from FastF1
return get_sessions(yr, rc)
def get_drivers_from_db(yr, rc, sn):
if rc is None and sn is None:
# All drivers for the year — try DB first
collection = db["data"]
docs = collection.find({"year": int(yr)})
drivers = []
for doc in docs:
for driver in doc.get("drivers", []):
if driver not in drivers:
drivers.append(driver)
if drivers:
return drivers
# Fallback: fetch from Ergast API
try:
import requests
url = f'https://api.jolpi.ca/ergast/f1/{yr}/drivers.json?limit=100'
resp = requests.get(url, timeout=15).json()
driver_list = resp['MRData']['DriverTable']['Drivers']
return [d.get('code', d['driverId'][:3].upper()) for d in driver_list]
except Exception:
return []
# Try DB first
collection = db["data"]
sn_cap = sn.capitalize() if sn else sn
doc = collection.find_one({"year": int(yr), "race": rc, "session": sn_cap})
if doc and "drivers" in doc:
return doc["drivers"]
# Fallback to live FastF1, then cache
drivers = get_drivers(yr, rc, sn)
if drivers:
_cache_session_data(yr, rc, sn_cap, drivers=drivers)
return drivers
def get_laps_from_db(yr, rc, sn):
if rc is None and sn is None:
return []
collection = db["data"]
sn_cap = sn.capitalize() if sn else sn
doc = collection.find_one({"year": int(yr), "race": rc, "session": sn_cap})
if doc and "laps" in doc:
return doc["laps"]
laps = get_laps(yr, rc, sn)
if laps:
_cache_session_data(yr, rc, sn_cap, laps=laps)
return laps
def get_distance_from_db(yr, rc, sn):
if rc is None and sn is None:
return []
collection = db["data"]
sn_cap = sn.capitalize() if sn else sn
doc = collection.find_one({"year": int(yr), "race": rc, "session": sn_cap})
if doc and "distance" in doc:
return doc["distance"]
dist = get_distance(yr, rc, sn)
if dist:
_cache_session_data(yr, rc, sn_cap, distance=dist)
return dist
def _cache_session_data(yr, rc, sn, drivers=None, laps=None, distance=None):
"""Upsert session data into the DB so subsequent lookups are instant."""
try:
collection = db["data"]
doc = collection.find_one({"year": int(yr), "race": rc, "session": sn})
update = {}
if drivers is not None: update["drivers"] = drivers
if laps is not None: update["laps"] = laps
if distance is not None: update["distance"] = distance
if doc:
collection.update_one({"year": int(yr), "race": rc, "session": sn}, {"$set": update})
else:
collection.insert_one({"year": int(yr), "race": rc, "session": sn, **update})
except Exception:
pass
def upload_drivers_standings(year, file):
with open(file, 'rb') as f:
file_data = f.read()
collection_name = "drivers_standings"
collection = db[collection_name]
doc = collection.find_one({"year": year})
if doc:
collection.update_one({"year": year}, {"$set": {"file": file_data}})
print(f"Updated {year} Drivers Standings")
else:
collection.insert_one({"year": year, "file": file_data})
print(f"Inserted {year} Drivers Standings")
f.close()
os.remove(file)
return
def upload_constructors_standings(year, file):
with open(file, 'rb') as f:
file_data = f.read()
collection_name = "constructors_standings"
collection = db[collection_name]
doc = collection.find_one({"year": year})
if doc:
collection.update_one({"year": year}, {"$set": {"file": file_data}})
print(f"Updated {year} Constructors Standings")
else:
collection.insert_one({"year": year, "file": file_data})
print(f"Inserted {year} Constructors Standings")
f.close()
os.remove(file)
return
def upload_points(year, file):
with open(file, 'rb') as f:
file_data = f.read()
collection_name = "points"
collection = db[collection_name]
doc = collection.find_one({"year": year})
if doc:
collection.update_one({"year": year}, {"$set": {"file": file_data}})
print(f"Updated {year} Points")
else:
collection.insert_one({"year": year, "file": file_data})
print(f"Inserted {year} Points")
f.close()
os.remove(file)
return
def get_d_standings(yr):
collection_name = "drivers_standings"
collection = db[collection_name]
doc = collection.find_one({"year": int(yr)})
if doc is None:
raise Exception(f"No drivers standings data available for {yr}")
file = doc["file"]
with open(dir_path + get_path() + "res" + get_path() + "output" + get_path() + f"{yr}_DRIVERS_STANDINGS" + ".png", 'wb') as f:
f.write(file)
f.close()
return f"{yr}_DRIVERS_STANDINGS.png"
def get_c_standings(yr):
collection_name = "constructors_standings"
collection = db[collection_name]
doc = collection.find_one({"year": int(yr)})
if doc is None:
raise Exception(f"No constructors standings data available for {yr}")
file = doc["file"]
with open(dir_path + get_path() + "res" + get_path() + "output" + get_path() + f"{yr}_CONSTRUCTORS_STANDINGS" + ".png", 'wb') as f:
f.write(file)
f.close()
return f"{yr}_CONSTRUCTORS_STANDINGS.png"
def get_p(yr):
collection_name = "points"
collection = db[collection_name]
doc = collection.find_one({"year": int(yr)})
if doc is None:
raise Exception(f"No points data available for {yr}")
file = doc["file"]
with open(dir_path + get_path() + "res" + get_path() + "output" + get_path() + f"{yr}_POINTS" + ".png", 'wb') as f:
f.write(file)
f.close()
return f"{yr}_POINTS.png"