-
Notifications
You must be signed in to change notification settings - Fork 4
/
utils.py
337 lines (266 loc) Β· 10.3 KB
/
utils.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
import json
import logging
from datetime import date, datetime
from io import BytesIO
from operator import itemgetter
import pandas as pd
from discord import ApplicationContext, Colour, File
from discord.ext import commands
from matplotlib.figure import Figure
from tabulate import tabulate
from fastf1.core import Session
from fastf1 import plotting
from f1.api.fetch import fetch
from f1.config import CACHE_DIR
from f1.errors import DriverNotFoundError, MessageTooLongError
from f1.target import MessageTarget
logger = logging.getLogger("f1-bot")
F1_RED = Colour.from_rgb(226, 36, 32)
async def check_season(ctx: commands.Context | ApplicationContext, season):
"""Raise error if the given season is in the future. Otherwise returns the year as an int."""
if is_future(season):
tgt = MessageTarget(ctx)
await tgt.send("Can't predict future :thinking:")
raise commands.BadArgument('Given season is in the future.')
def convert_season(season):
"""Return the season as an int, works for 'current' season."""
if season == "current":
return current_year()
return int(season)
def sprint_qual_type(season):
"""Get the name used for the Saturday sprint qualifying session.
Naming between 2021-2022 is synonymous. 2023+ uses new format.
"""
s_int = convert_season(season)
if s_int < 2023:
return 'Sprint'
return 'Sprint Shootout'
def contains(first, second):
"""Returns True if any item in `first` matches an item in `second`."""
return any(i in first for i in second)
def is_future(year):
"""Return True if `year` is greater than current year."""
if year == 'current':
return False
return datetime.now().year < int(year)
def too_long(message: str):
"""Returns True if the message exceeds discord's 2000 character limit."""
return len(message) >= 2000
def make_table(data, headers='keys', fmt='fancy_grid', **kwargs):
"""Tabulate data into an ASCII table. Return value is a str.
The `fmt` param defaults to 'fancy_grid' which includes borders for cells. If the table exceeds
Discord message limit the table is rebuilt with borders removed.
If still too large raise `MessageTooLongError`.
"""
table = tabulate(data, headers=headers, tablefmt=fmt, **kwargs)
# remove cell borders if too long
if too_long(table):
table = tabulate(data, headers=headers, tablefmt='plain', **kwargs)
# cannot send table if too large even without borders
if too_long(table):
raise MessageTooLongError('Table too large to send.', table)
return table
def current_year():
return date.today().year
def age(yob):
if current_year() < int(yob):
return 0
return current_year() - int(yob)
def date_parser(date_str):
return datetime.strptime(date_str, '%Y-%m-%d').strftime('%d %b')
def time_parser(time_str):
return datetime.strptime(time_str, '%H:%M:%SZ').strftime('%H:%M UTC')
def pluralize(number: int, singular: str, plural: str = None):
if not plural:
plural = singular + 's'
return f"{number} {singular if number == 1 else plural}"
def countdown(target: datetime):
"""
Calculate time to `target` datetime object from current time when invoked.
Returns a list containing the string output and tuple of (days, hrs, mins, sec).
"""
delta = target - datetime.now()
if delta.days < 0:
d, h, m, s = (0, 0, 0, 0)
else:
d = delta.days if delta.days > 0 else 0
# timedelta only stores seconds so calculate mins and hours by dividing remainder
h, rem = divmod(delta.seconds, 3600)
m, s = divmod(rem, 60)
# text representation
stringify = (
f"{pluralize(int(d), 'day')}, "
f"{pluralize(int(h), 'hour')}, "
f"{pluralize(int(m), 'minute')}, "
f"{pluralize(int(s), 'second')} "
)
return [stringify, (d, h, m, s)]
def format_timedelta(delta: pd.Timedelta, hours=False):
"""Get a time string in `[%H]:%M:%S.%f` with a precision of 3 places. If not a valid time the string is empty."""
if pd.isna(delta):
return ''
return (datetime.min + delta).strftime(f"{'%H:' if hours else ''}%M:%S.%f").lstrip('0')[:-3]
def lap_time_to_seconds(time_str: str):
"""Returns the lap time string as a float representing total seconds.
E.g. '1:30.202' -> 90.202
"""
min, secs = time_str.split(':')
total = int(min) * 60 + float(secs)
return total
def load_drivers():
"""Load drivers JSON from file and return as dict."""
with open(CACHE_DIR.joinpath('drivers.json'), 'r', encoding='utf-8') as f:
data = json.load(f)
DRIVERS = data['MRData']['DriverTable']['Drivers']
logger.info('Drivers loaded.')
return DRIVERS
def find_driver(id: str, drivers: list[dict]):
"""Find the driver entry and return as a dict.
Parameters
----------
`id` : str
Can be either a valid Ergast API ID e.g. 'alonso', 'max_verstappen' or the
driver code e.g. 'HAM' or the driver number e.g. '44'.
`drivers` : list[dict]
The drivers dataset to search.
Returns
-------
`driver` : dict
Raises
------
`DriverNotFoundError`
"""
for d in drivers:
if str(id).casefold() in (str(v).casefold() for v in d.values()):
return d
continue
raise DriverNotFoundError()
def rank_best_lap_times(timings):
"""Sorts the list of lap times returned by `api.get_best_laps()` dataset."""
sorted_times = sorted(timings['data'], key=itemgetter('Rank'))
return sorted_times
def rank_pitstops(times):
"""Sort pitstop times based on the duration. `times` is the response from `api.get_pitstops()`."""
sorted_times = sorted(times['data'], key=itemgetter('Duration'))
return sorted_times
def filter_laps_by_driver(laps, drivers):
"""Filter lap time data to get only laps driven by the driver in `drivers`.
Parameters
----------
`laps` : dict
Timings for each driver per lap as returned by `api.get_all_laps` data key
`*drivers` : list
A valid driver_id used by Ergast API
Returns
-------
dict
`laps` filtered to contain only a list of timings per lap for the specified drivers
"""
if len(drivers) == 0:
return laps
else:
result = {
'data': {},
'race': laps.get('race', ''),
'season': laps.get('season', ''),
'round': laps.get('round', '')
}
for lap, times in laps['data'].items():
result['data'][lap] = [t for t in times if t['id'] in drivers]
return result
def filter_times(sorted_times, filter: str | None):
"""Filters the list of times by the filter keyword. If no filter is given the
times are returned unfiltered.
Parameters
-----------
`sorted_times` : list
Collection of already sorted items, e.g. pitstops or laptimes data.
`filter` : str
The type of filter to apply;
'slowest' - single slowest time
'fastest' - single fastest time
'top' - top 5 fastest times
'bottom' - bottom 5 slowest times
Returns
-------
list
A subset of the `sorted_times` according to the filter.
"""
# Force list return type instead of pulling out single string element for slowest and fastest
# Top/Bottom already outputs a list type with slicing
# slowest
if filter == 'slowest':
return [sorted_times[len(sorted_times) - 1]]
# fastest
elif filter == 'fastest':
return [sorted_times[0]]
# fastest 5
elif 'top' in filter:
return sorted_times[:5]
# slowest 5
elif 'bottom' in filter:
return sorted_times[len(sorted_times) - 5:]
# no filter given, return full sorted results
else:
return sorted_times
def keep_fastest(lst: list[dict], key: str):
"""Checks list of sorted timing data e.g. pitstops and removes duplicates to
keep only the fastest entry.
Parameters
----------
`lst` : list[dict]
Collection of *sorted* timing entries per driver, e.g. from `utils.rank_pitstops`.
`key` : str
Dict key to sort by.
Returns
----------
list[dict]
A new list of entries with duplicates removed where only the lower `key` values are kept.
"""
seen = {}
for d in lst:
if d['Driver'] not in seen or d[key] < seen[d['Driver']][key]:
seen[d['Driver']] = d
return list(seen.values())
async def get_wiki_thumbnail(url: str):
"""Get image thumbnail from Wikipedia link. Returns the thumbnail URL."""
if url is None or url == '':
return 'https://i.imgur.com/kvZYOue.png'
# Get URL name after the first '/'
wiki_title = url.rsplit('/', 1)[1]
# Get page thumbnail from wikipedia API if it exists
api_query = ('https://en.wikipedia.org/w/api.php?action=query&format=json&formatversion=2' +
'&prop=pageimages&piprop=thumbnail&pithumbsize=600' + f'&titles={wiki_title}')
res = await fetch(api_query)
first = res['query']['pages'][0]
# Get page thumb or return placeholder
if 'thumbnail' in first:
return first['thumbnail']['source']
else:
return 'https://i.imgur.com/kvZYOue.png'
def plot_to_file(fig: Figure, name: str):
"""Generates a `discord.File` as `name`. Takes a plot Figure and
saves it to a `BytesIO` memory buffer without saving to disk.
"""
with BytesIO() as buffer:
fig.savefig(buffer, format="png", bbox_inches="tight")
buffer.seek(0)
file = File(buffer, filename=f"{name}.png")
return file
def get_driver_or_team_color(id: str, session: Session, team_only=False, api_only=False):
"""Tries to get the color from `fastf1.plotting` or fallback to the team color from F1 API.
Use `team_only=True` when searching team name instead of driver. Use `api_only=True` to
get driver team color from F1 API instead of fastf1.
"""
if team_only:
return "#" + str(session.results.loc[
session.results["TeamName"] == id,
"TeamColor"
].values[0])
if not api_only and (int(session.date.year) == current_year()):
try:
c = plotting.driver_color(id)
return c
except KeyError:
pass
return f"#{session.get_driver(id)['TeamColor']}"