-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathf1.py
More file actions
574 lines (485 loc) · 21.7 KB
/
Copy pathf1.py
File metadata and controls
574 lines (485 loc) · 21.7 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
#!/usr/bin/env python3
import urllib.request
import urllib.error
import json
import sys
import os
import time
from datetime import datetime, timezone, timedelta
# Force UTF-8 encoding for Windows console
if sys.stdout.encoding != 'utf-8':
try:
sys.stdout.reconfigure(encoding='utf-8')
except AttributeError:
pass
# --- CONFIGURATION ---
BASE_URL = "https://api.jolpi.ca/ergast/f1"
SEASON = "2026"
TIMEOUT = 10
# --- COLOR SYSTEM ---
class C:
RESET = "\033[0m"
BOLD = "\033[1m"
DIM = "\033[2m"
UNDER = "\033[4m"
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
MAGENTA = "\033[95m"
CYAN = "\033[96m"
WHITE = "\033[97m"
def supports_color():
if os.environ.get("NO_COLOR"):
return False
if sys.platform == "win32":
try:
import ctypes
kernel32 = ctypes.windll.kernel32
# Enable VT100 mode on Windows 10+
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
return True
except Exception:
return False
return hasattr(sys.stdout, "isatty") and sys.stdout.isatty()
USE_COLOR = supports_color()
def c(color, text):
if USE_COLOR:
return color + str(text) + C.RESET
return str(text)
# --- UTILITIES ---
def pad(text, length, right=False):
s = str(text) if text is not None else ""
if right:
return s.rjust(length)[:length]
return s.ljust(length)[:length]
def team_color(name):
lower_name = str(name).lower()
if 'red bull' in lower_name: return C.BLUE
if 'ferrari' in lower_name: return C.RED
if 'mercedes' in lower_name: return C.CYAN
if 'mclaren' in lower_name: return C.YELLOW
if 'aston martin' in lower_name: return C.GREEN
if 'alpine' in lower_name: return C.MAGENTA
return C.GREEN
def get_flag(nationality):
flags = {
'Dutch': '🇳🇱', 'British': '🇬🇧', 'Monegasque': '🇲🇨', 'Spanish': '🇪🇸',
'Australian': '🇦🇺', 'Mexican': '🇲🇽', 'French': '🇫🇷', 'Japanese': '🇯🇵',
'Canadian': '🇨🇦', 'German': '🇩🇪', 'Thai': '🇹🇭', 'Danish': '🇩🇰',
'Finnish': '🇫🇮', 'Chinese': '🇨🇳', 'American': '🇺🇸', 'New Zealander': '🇳🇿',
'Italian': '🇮🇹', 'Austrian': '🇦🇹', 'Swiss': '🇨🇭', 'Swiss-French': '🇨🇭'
}
return flags.get(nationality, '🏁')
def get_race_flag(country):
flags = {
'Bahrain': '🇧🇭', 'Saudi Arabia': '🇸🇦', 'Australia': '🇦🇺', 'Japan': '🇯🇵',
'China': '🇨🇳', 'USA': '🇺🇸', 'United States': '🇺🇸', 'Italy': '🇮🇹',
'Monaco': '🇲🇨', 'Canada': '🇨🇦', 'Spain': '🇪🇸', 'Austria': '🇦🇹',
'UK': '🇬🇧', 'Hungary': '🇭🇺', 'Belgium': '🇧🇪', 'Netherlands': '🇳🇱',
'Azerbaijan': '🇦🇿', 'Singapore': '🇸🇬', 'Brazil': '🇧🇷', 'Mexico': '🇲🇽',
'Qatar': '🇶🇦', 'UAE': '🇦🇪'
}
return flags.get(country, '🏁')
# --- HTTP LAYER ---
def api_fetch(endpoint, label="Fetching data"):
url = "{}{}".format(BASE_URL, endpoint)
spinner = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
def print_spin(i):
msg = "{} {}...".format(c(C.CYAN, spinner[i % len(spinner)]), label)
sys.stdout.write("\r" + msg + " " * 10)
sys.stdout.flush()
try:
from urllib.request import Request, urlopen
import ssl
from threading import Thread
req = Request(url, headers={'User-Agent': 'F1TerminalCLI/1.0'})
res = None
err = None
done = False
# NOTE: SSL verification is disabled for Jolpi API compatibility on some
# systems. The API is a public read-only endpoint with no credentials involved.
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
def worker():
nonlocal res, err, done
try:
with urlopen(req, timeout=TIMEOUT, context=ctx) as response:
if response.status != 200:
err = Exception("HTTP {}: {}".format(response.status, response.reason))
else:
res = json.loads(response.read().decode('utf-8'))
except Exception as e:
err = e
finally:
done = True
t = Thread(target=worker)
t.daemon = True
t.start()
i = 0
while not done:
print_spin(i)
time.sleep(0.1)
i += 1
sys.stdout.write("\r" + " " * 60 + "\r") # Clear spinner
sys.stdout.flush()
if err is not None:
raise err
return res
except urllib.error.URLError as e:
if "getaddrinfo failed" in str(e.reason):
print(c(C.RED, "\n[ERROR] DNS Error: Cannot resolve '{}'. The API might be down or your internet is offline.".format(BASE_URL)))
else:
print(c(C.RED, "\n[ERROR] Network error: {}".format(e.reason)))
sys.exit(1)
except json.JSONDecodeError:
print(c(C.RED, "\n[ERROR] Invalid response from API."))
sys.exit(1)
except Exception as e:
print(c(C.RED, "\n[ERROR] Failed to fetch data: {}".format(str(e))))
sys.exit(1)
# --- COMMAND HANDLERS ---
def _print_header(title):
print("\n" + c(C.BOLD + C.YELLOW, "═" * 60))
print(c(C.BOLD + C.WHITE, " 🏎️ " + title.upper()))
print(c(C.BOLD + C.YELLOW, "═" * 60))
def cmd_standings():
_print_header("Driver Standings {}".format(SEASON))
data = api_fetch("/{}/driverStandings.json".format(SEASON), "Fetching standings")
try:
table = data["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"]
print((c(C.DIM, "POS {pos} DRIVER {driver} TEAM {team} PTS").format(
pos=pad("", 2),
driver=pad("", 15),
team=pad("", 15)
)))
for d in table:
pos = d.get("position", d.get("positionText", "-"))
pts = d.get("points", "0")
driver = d["Driver"]
team = d["Constructors"][0] if d["Constructors"] else {"name": "Unknown"}
name = "{} {}".format(driver["givenName"][0], driver["familyName"])
team_colored = c(team_color(team["name"]), team["name"])
val_medal = ""
if pos == "1": val_medal = c(C.YELLOW, "🥇")
elif pos == "2": val_medal = c(C.WHITE, "🥈")
elif pos == "3": val_medal = c(C.RED, "🥉")
else: val_medal = pad("", 2)
print("{pos_pad} {medal} {name_pad} {team_pad} {pts_pad}".format(
pos_pad=c(C.BOLD, pad(pos, 2, right=True)),
medal=val_medal,
name_pad=c(C.WHITE, pad(name, 19)),
team_pad=pad(team_colored, 28), # ANSI chars add logic, pad manually handles length vs visual
pts_pad=c(C.GREEN + C.BOLD, pad(pts, 4, right=True))
))
except IndexError:
print(c(C.RED, "No standings data found for {}.".format(SEASON)))
def cmd_constructors():
_print_header("Constructor Standings {}".format(SEASON))
data = api_fetch("/{}/constructorStandings.json".format(SEASON), "Fetching constructors")
try:
table = data["MRData"]["StandingsTable"]["StandingsLists"][0]["ConstructorStandings"]
print((c(C.DIM, "POS {pos} TEAM {team} NAT {nat} WINS {wins} PTS").format(
pos=pad("", 2),
team=pad("", 15),
nat=pad("", 5),
wins=pad("", 2)
)))
for c_val in table:
pos = c_val.get("position", c_val.get("positionText", "-"))
pts = c_val.get("points", "0")
wins = c_val.get("wins", "0")
team = c_val["Constructor"]
team_colored = c(team_color(team["name"]), team["name"])
flag = get_flag(team["nationality"])
val_medal = ""
if pos == "1": val_medal = c(C.YELLOW, "🥇")
elif pos == "2": val_medal = c(C.WHITE, "🥈")
elif pos == "3": val_medal = c(C.RED, "🥉")
else: val_medal = pad("", 2)
print("{pos_pad} {medal} {team_pad} {flag_pad} {wins_pad} {pts_pad}".format(
pos_pad=c(C.BOLD, pad(pos, 2, right=True)),
medal=val_medal,
team_pad=pad(team_colored, 28),
flag_pad=pad(flag, 4),
wins_pad=pad(wins, 4, right=True),
pts_pad=c(C.GREEN + C.BOLD, pad(pts, 4, right=True))
))
except IndexError:
print("No constructors data found.")
def cmd_schedule():
_print_header("Race Schedule {}".format(SEASON))
data = api_fetch("/{}.json".format(SEASON), "Fetching schedule")
try:
races = data["MRData"]["RaceTable"]["Races"]
for r in races:
rnd = r["round"]
name = r["raceName"]
circuit = r["Circuit"]["circuitName"]
loc = r["Circuit"]["Location"]
date = r["date"]
time_str = r.get("time", "TBD")
if time_str != "TBD":
time_str_clean = time_str.replace("Z", "")
dt_str = "{}T{}Z".format(date, time_str_clean)
r_dt = datetime.strptime(dt_str, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
local_dt = r_dt.astimezone(timezone(timedelta(hours=3)))
date = local_dt.strftime("%Y-%m-%d")
time_str = local_dt.strftime("%H:%M (UTC+3)")
else:
time_str = time_str.replace("Z", "")
flag = get_race_flag(loc["country"])
print("{rnd_pad}. {flag} {name_pad} {date_pad} {time_pad}".format(
rnd_pad=c(C.DIM, pad(rnd, 2, right=True)),
flag=flag,
name_pad=c(C.WHITE + C.BOLD, pad(name, 30)),
date_pad=c(C.CYAN, pad(date, 12)),
time_pad=c(C.DIM, time_str)
))
print(" {}\n".format(c(C.DIM, pad(circuit + ", " + loc["locality"], 40))))
except Exception as e:
print("Error parsing schedule:", e)
def cmd_last():
_print_header("Last Race Results")
data = api_fetch("/current/last/results.json", "Fetching last race")
# If the current season hasn't started, fetch the last race of the previous season
try:
if len(data["MRData"]["RaceTable"]["Races"]) == 0:
current_season = int(data["MRData"]["RaceTable"]["season"])
prev_season = current_season - 1
data = api_fetch(f"/{prev_season}/last/results.json", f"Fetching last race of {prev_season}")
except KeyError:
pass
try:
race_info = data["MRData"]["RaceTable"]["Races"][0]
race_name = race_info["raceName"]
results = race_info["Results"]
print(c(C.CYAN, "Season {} Round {}: {}\n".format(race_info["season"], race_info["round"], race_name)))
print(c(C.DIM, "POS {pos} DRIVER TEAM TIME/STATUS").format(
pos=pad("", 3)
))
for res in results:
pos = res["position"]
driver = res["Driver"]
team = res["Constructor"]
status = res["status"]
name = "{} {}".format(driver["givenName"][0], driver["familyName"])
team_colored = c(team_color(team["name"]), team["name"])
time_str = status
if "Time" in res:
time_str = res["Time"]["time"]
print("{pos_pad} {name_pad} {team_pad} {time_pad}".format(
pos_pad=c(C.BOLD, pad(pos, 3, right=True)),
name_pad=c(C.WHITE, pad(name, 20)),
team_pad=pad(team_colored, 28),
time_pad=c(C.GREEN if "Laps" not in time_str and "Finished" not in time_str else C.DIM, time_str)
))
except IndexError:
print("No recent race results found.")
def cmd_next():
_print_header("Next Race")
data = api_fetch("/current.json", "Fetching schedule")
try:
races = data["MRData"]["RaceTable"]["Races"]
now = datetime.now(timezone.utc)
next_race = None
race_dt = None
for r in races:
date_str = r["date"]
time_str = r.get("time", "00:00:00Z")
dt_str = "{}T{}".format(date_str, time_str)
r_dt = datetime.strptime(dt_str, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
if r_dt > now:
next_race = r
race_dt = r_dt
break
if next_race:
name = next_race["raceName"]
circuit = next_race["Circuit"]["circuitName"]
loc = next_race["Circuit"]["Location"]
flag = get_race_flag(loc["country"])
diff = race_dt - now
days = diff.days
hours, remainder = divmod(diff.seconds, 3600)
minutes, _ = divmod(remainder, 60)
local_dt = race_dt.astimezone(timezone(timedelta(hours=3)))
print("{} {}".format(flag, c(C.BOLD + C.WHITE, name)))
print(c(C.DIM, "Location: {}, {}".format(circuit, loc['locality'])))
print(c(C.CYAN, "Date: {} at {} UTC+3".format(local_dt.strftime("%Y-%m-%d"), local_dt.strftime("%H:%M"))))
print(c(C.YELLOW + C.BOLD, "Starts in: {}d {}h {}m\n".format(days, hours, minutes)))
else:
print("No upcoming races found for this season.")
except Exception as e:
print("Error finding next race:", e)
def cmd_drivers():
_print_header("Drivers {}".format(SEASON))
data = api_fetch("/{}/drivers.json".format(SEASON), "Fetching drivers")
s_data = api_fetch("/{}/driverStandings.json".format(SEASON), "Fetching teams")
FALLBACK_TEAMS = {
"albon": "Williams", "alonso": "Aston Martin", "antonelli": "Mercedes",
"bearman": "Haas", "bortoleto": "Sauber", "bottas": "Sauber",
"colapinto": "Williams", "gasly": "Alpine", "hadjar": "RB",
"hamilton": "Ferrari", "hulkenberg": "Sauber", "lawson": "RB",
"leclerc": "Ferrari", "lindblad": "RB", "norris": "McLaren", "ocon": "Haas",
"piastri": "McLaren", "perez": "Red Bull", "russell": "Mercedes",
"sainz": "Williams", "stroll": "Aston Martin", "max_verstappen": "Red Bull",
"tsunoda": "RB", "doohan": "Alpine"
}
team_map = {}
try:
lists = s_data["MRData"]["StandingsTable"]["StandingsLists"]
if lists:
for d in lists[0]["DriverStandings"]:
team_map[d["Driver"]["driverId"]] = d["Constructors"][0]["name"]
except (KeyError, IndexError, TypeError):
pass
try:
drivers = data["MRData"]["DriverTable"]["Drivers"]
print((c(C.DIM, "NO {no} DRIVER {driver} TEAM {team_pad} NAT {nat} CODE").format(
no=pad("", 1),
driver=pad("", 16),
team_pad=pad("", 15),
nat=pad("", 3)
)))
for d in drivers:
no = d.get("permanentNumber", "N/A")
name = "{} {}".format(d["givenName"], d["familyName"])
nat = d["nationality"]
flag = get_flag(nat)
code = d.get("code", "N/A")
d_id = d["driverId"]
team_name = team_map.get(d_id, FALLBACK_TEAMS.get(d_id, "Unknown"))
team_colored = c(team_color(team_name), team_name)
print("{no_pad} {name_pad} {team_str} {flag_pad} {code_pad}".format(
no_pad=c(C.BOLD, pad(no, 3, right=True)),
name_pad=c(C.WHITE, pad(name, 23)),
team_str=pad(team_colored, 28),
flag_pad=pad(flag, 4),
code_pad=c(C.CYAN, pad(code, 4))
))
except Exception as e:
print("Error parsing drivers:", e)
def cmd_pilot(code=None):
if not code:
print(c(C.RED, "Please provide a pilot 3-letter code. (e.g. 'python f1.py pilot VER')"))
return
code = code.upper()
_print_header(f"Pilot Profile: {code}")
# 1. Fetch current drivers to find ID
data = api_fetch("/current/drivers.json", f"Searching for {code}")
try:
drivers = data["MRData"]["DriverTable"]["Drivers"]
driver = next((d for d in drivers if d.get("code") == code), None)
if not driver:
# Fallback: maybe they entered a driverId directly
driver_id = code.lower()
try:
# Test if it exists
single_data = api_fetch(f"/drivers/{driver_id}.json", "Validating ID")
if single_data["MRData"]["total"] == "0":
print(c(C.RED, f"Driver '{code}' not found in active grid. Use full driverId for historical pilots."))
return
driver = single_data["MRData"]["DriverTable"]["Drivers"][0]
except (KeyError, IndexError, Exception):
print(c(C.RED, f"Driver '{code}' not found."))
return
else:
driver_id = driver["driverId"]
name = f"{driver['givenName']} {driver['familyName']}"
nat = get_flag(driver["nationality"])
number = driver.get("permanentNumber", "N/A")
# known world championships mapping
wdc = {
"michael_schumacher": 7, "hamilton": 7, "fangio": 5, "prost": 4,
"vettel": 4, "max_verstappen": 4, "brabham": 3, "stewart": 3,
"lauda": 3, "piquet": 3, "senna": 3, "alonso": 2, "hakkinen": 2,
"fittipaldi": 2, "clark": 2, "ascari": 2, "raikkonen": 1, "rosberg": 1,
"nico_rosberg": 1, "button": 1, "villeneuve": 1, "damon_hill": 1,
"mansell": 1, "andretti": 1, "hunt": 1, "scheckter": 1, "jones": 1,
"surtees": 1, "phil_hill": 1, "hawthorn": 1, "farina": 1
}
# 2. Fetch all-time stats
wins_data = api_fetch(f"/drivers/{driver_id}/results/1.json?limit=1", "Fetching Wins")
poles_data = api_fetch(f"/drivers/{driver_id}/qualifying/1.json?limit=1", "Fetching Poles")
starts_data = api_fetch(f"/drivers/{driver_id}/results.json?limit=1", "Fetching Starts")
total_wins = wins_data["MRData"]["total"]
total_poles = poles_data["MRData"]["total"]
total_starts = starts_data["MRData"]["total"]
total_champs = wdc.get(driver_id, 0)
print()
print(f" {nat} {c(C.BOLD + C.WHITE, name)} | #{number} | {driver['dateOfBirth']}")
print(c(C.DIM, " " + "-"*40))
print(f" {c(C.YELLOW, 'World Championships:')} {c(C.BOLD, total_champs)}")
print(f" {c(C.GREEN, 'All-Time Wins:')} {c(C.BOLD, total_wins)}")
print(f" {c(C.CYAN, 'Pole Positions:')} {c(C.BOLD, total_poles)}")
print(f" {c(C.DIM, 'Race Starts:')} {c(C.BOLD, total_starts)}\n")
except Exception as e:
print("Error fetching pilot data:", e)
def cmd_help():
_print_header("F1 Terminal CLI - Help")
print(c(C.BOLD, "Available commands:"))
print(" {} - Show driver standings".format(c(C.GREEN, "standings")))
print(" {} - Show all drivers/pilots grid".format(c(C.GREEN, "drivers")))
print(" {} - Show constructor standings".format(c(C.GREEN, "constructors")))
print(" {} - Show race schedule".format(c(C.GREEN, "schedule")))
print(" {} - Show next upcoming race and countdown".format(c(C.GREEN, "next")))
print(" {} - Show last race results".format(c(C.GREEN, "last")))
print(" {} VER - Show historical stats for a pilot".format(c(C.GREEN, "pilot")))
print(" {} - Exit interactive mode".format(c(C.RED, "exit/quit")))
print()
def dispatch(cmd_name, args):
table = {
"standings": cmd_standings,
"drivers": cmd_drivers,
"constructors": cmd_constructors,
"schedule": cmd_schedule,
"next": cmd_next,
"last": cmd_last,
"pilot": cmd_pilot,
"help": cmd_help,
"quit": sys.exit,
"exit": sys.exit
}
fn = table.get(cmd_name.lower())
if fn:
try:
fn(*args) if args else fn()
except TypeError:
fn()
else:
if cmd_name:
print(c(C.RED, "Unknown command: {}. Type 'help' for options.".format(cmd_name)))
# --- MAIN / REPL ---
def main():
args = sys.argv[1:]
# Check NO_COLOR early if passed as argument
if "--no-color" in args:
global USE_COLOR
USE_COLOR = False
args.remove("--no-color")
if len(args) > 0:
# CLI Mode
cmd = args[0]
dispatch(cmd, args[1:])
else:
# REPL Mode
print(c(C.BOLD + C.RED, r"""
___ _ _____ _ _
| __/ | |_ _|___ _ _ _ __(_)_ _ __ _| |
| _|| | | |/ -_) '_| ' \| | ' \/ _` | |
|_| |_| |_|\___|_| |_|_|_|_|_||_\__,_|_|
"""))
print(c(C.DIM, "Welcome to the F1 Terminal! Type 'help' to see commands."))
while True:
try:
raw_in = input("\n{} ".format(c(C.RED, "f1>"))).strip()
if not raw_in:
continue
user_input = raw_in.split()
dispatch(user_input[0], user_input[1:])
except (KeyboardInterrupt, EOFError):
print("\nGoodbye!")
break
if __name__ == "__main__":
main()