-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrackets.py
More file actions
executable file
·822 lines (701 loc) · 25.8 KB
/
brackets.py
File metadata and controls
executable file
·822 lines (701 loc) · 25.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
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
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.13"
# dependencies = [
# "click",
# "requests",
# "beautifulsoup4",
# ]
# ///
import os
import json
import re
import requests
import click
import tempfile
from typing import TypedDict, List
from common import fzf_choose
from datetime import datetime
import subprocess
import sys
from bs4 import BeautifulSoup
KEVBOT_SGG_ID = "658c6a49"
API_KEY = os.getenv("START_GG_API_KEY")
if not API_KEY:
raise ValueError("START_GG_API_KEY environment variable is required")
class Bracket(TypedDict):
title: str
VODs: List[str]
BracketUrl: str
Date: str
"""
example response from
https://tril.kevbot.xyz/custom/brackets
[
{
"title": "Get On My Level: Forever - Canadian Fighting Game Championships",
"VODs": [],
"BracketUrl": "https://www.start.gg/tournament/get-on-my-level-forever-canadian-fighting-game-championships/event/super-smash-bros-melee-singles",
"Date": "2025-07-05"
"relativeDate": "X days ago"
}, ...
]
"""
def url2slug(url: str) -> str:
path_segments = [segment for segment in url.split("/") if segment]
i = path_segments.index("tournament")
return "/".join(path_segments[i : i + 4])
def get_brackets() -> List[Bracket]:
"""Fetch brackets from the API"""
return requests.get("https://tril.kevbot.xyz/custom/brackets").json()
# Known Melee characters for parsing
MELEE_CHARACTERS = [
"Captain Falcon",
"Donkey Kong",
"Dr Mario",
"Dr. Mario",
"Ice Climbers",
"Ice Climber",
"Jigglypuff",
"Young Link",
"Falco",
"Fox",
"Marth",
"Peach",
"Sheik",
"Luigi",
"Samus",
"Yoshi",
"Ganon",
"Ganondorf",
"Pikachu",
"Mario",
"Mewtwo",
"Ness",
"Pichu",
"Zelda",
"Link",
"Roy",
"Kirby",
"Bowser",
"Game & Watch",
"Mr. Game & Watch",
"Falcon",
]
CHAR_CACHE_FILE = os.path.join(tempfile.gettempdir(), "brackets_char_cache.html")
def fetch_character_html(force: bool = False) -> str:
"""Fetch and cache the character HTML data"""
if not force and os.path.exists(CHAR_CACHE_FILE):
with open(CHAR_CACHE_FILE, "r") as f:
return f.read()
try:
response = requests.get("https://tril.kevbot.xyz/custom/brackets-html/")
response.raise_for_status()
html = response.text
with open(CHAR_CACHE_FILE, "w") as f:
f.write(html)
return html
except requests.RequestException as e:
click.echo(f"Warning: Could not fetch character data: {e}", err=True)
return ""
def get_character_lookup(html: str) -> dict[str, str]:
"""Parse HTML and build a tag -> character lookup"""
if not html:
return {}
soup = BeautifulSoup(html, "html.parser")
lookup: dict[str, str] = {}
# Find all table cells in the first column (opponent cells)
for table in soup.find_all("table"):
for row in table.find_all("tr"):
cells = row.find_all("td")
if cells:
text = cells[0].get_text(strip=True)
if not text:
continue
# Try to extract character from the end of the string
found_char = None
tag = text
for char in sorted(MELEE_CHARACTERS, key=len, reverse=True):
if text.lower().endswith(" " + char.lower()):
found_char = char
tag = text[: -(len(char) + 1)].strip()
break
if found_char and tag:
# Store lowercase tag for case-insensitive lookup
tag_lower = tag.lower()
if tag_lower not in lookup:
lookup[tag_lower] = found_char
return lookup
def get_entrants(slug: str, num: int = 100):
"""Fetch entrants from start.gg API"""
query = """
query GetEventSeeds($slug: String!, $num: Int!) {
event(slug: $slug) {
id
name
phases {
seeds(query: {
page: 1
perPage: $num
}) {
nodes {
seedNum
entrant {
name
}
}
}
}
}
}
"""
headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}
response = requests.post(
"https://api.start.gg/gql/alpha",
json={"query": query, "variables": {"slug": slug, "num": num}},
headers=headers,
)
if response.status_code != 200:
click.echo(f"Error: {response.status_code}", err=True)
click.echo(response.text, err=True)
raise click.Abort()
data = response.json()
if "errors" in data:
click.echo("GraphQL Errors:", err=True)
for error in data["errors"]:
click.echo(error["message"], err=True)
raise click.Abort()
return data["data"]["event"]
@click.group()
def cli():
"""Bracket information tool"""
pass
def get_latest_bracket() -> Bracket:
"""Get the most recent bracket based on date"""
brackets = get_brackets()
if not brackets:
raise click.ClickException("No brackets found")
# Filter out future brackets and sort by date (most recent first)
today = datetime.now().date()
past_brackets = []
for bracket in brackets:
try:
bracket_date = datetime.strptime(bracket.get("Date", ""), "%Y-%m-%d").date()
if bracket_date <= today:
past_brackets.append(bracket)
except (ValueError, TypeError):
# Skip brackets with invalid dates
continue
if not past_brackets:
raise click.ClickException("No past brackets found")
# Sort by date (most recent first)
sorted_brackets = sorted(
past_brackets, key=lambda x: x.get("Date", ""), reverse=True
)
return sorted_brackets[0]
def choose_bracket(latest: bool = False) -> Bracket:
"""Choose a bracket from the available ones"""
if latest:
return get_latest_bracket()
brackets = get_brackets()
chosen = fzf_choose(
brackets,
display_func=lambda x: f"{x.get('relativeDate'):12} - {x.get('title', '')}",
)
return chosen
def is_kevbot_set(s):
"""Check if a set contains kevbot"""
if not s["slots"][0]["entrant"] or not s["slots"][1]["entrant"]:
return False
for slot in s["slots"]:
if slot["entrant"] and slot["entrant"]["participants"]:
for participant in slot["entrant"]["participants"]:
if participant and (
"kevbot" in participant.get("gamerTag", "").lower()
or (
participant.get("user")
and participant.get("user", {}).get("id") == KEVBOT_SGG_ID
)
):
return True
return False
@cli.command()
@click.option("--latest", is_flag=True, help="Choose the most recent bracket")
@click.option("--upload", is_flag=True, help="Upload a new bracket")
@click.option("--execute", is_flag=True, help="execute Uploading a new bracket")
@click.option("--nocleanup", is_flag=True, default=False, help="keep vid file around")
def bracket(
latest: bool = False,
upload: bool = False,
execute: bool = False,
nocleanup: bool = False,
) -> Bracket:
"""List available brackets, choose one"""
bracket = choose_bracket(latest=latest)
if upload or execute:
title = bracket.get("title", "")
title = title.replace("'", "")
bracket_url = bracket.get("BracketUrl")
vod = bracket["VODs"][0]["url"]
cleanup_arg = "" if nocleanup else "--cleanup"
cmd = f"vodbackup.py {cleanup_arg} --title '{title}' --bracket-url '{bracket_url}' '{vod}'"
if upload:
click.echo(cmd)
if execute:
click.echo(f"executing: {cmd}")
subprocess.run(cmd, shell=True, check=True)
else:
click.echo(json.dumps(bracket, indent=2))
return Bracket
@cli.command()
@click.option("--tournament-url", required=True, help="URL of the tournament")
@click.option("--event-name", required=True, help="Name of the event")
def tourney2slug(tournament_url, event_name):
"""Find event by name in tournament and return the full slug"""
# Extract tournament slug from URL
tournament_slug = url2slug(tournament_url)
# Query start.gg API to get tournament and find event by name
query = """
query GetTournamentEvents($slug: String!) {
tournament(slug: $slug) {
id
name
slug
events {
id
name
slug
}
}
}
"""
headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}
response = requests.post(
"https://api.start.gg/gql/alpha",
json={"query": query, "variables": {"slug": tournament_slug}},
headers=headers,
)
if response.status_code != 200:
click.echo(f"Error: {response.status_code}", err=True)
click.echo(response.text, err=True)
raise click.Abort()
data = response.json()
if "errors" in data:
click.echo("GraphQL Errors:", err=True)
for error in data["errors"]:
click.echo(error["message"], err=True)
raise click.Abort()
tournament = data["data"]["tournament"]
if not tournament:
click.echo(f"Tournament not found: {tournament_slug}", err=True)
raise click.Abort()
# Find event by name (case-insensitive)
matching_events = []
for event in tournament["events"]:
if event["name"].lower() == event_name.lower():
matching_events.append(event)
if not matching_events:
click.echo(
f"Event '{event_name}' not found in tournament '{tournament['name']}'",
err=True,
)
click.echo("Available events:", err=True)
for event in tournament["events"]:
click.echo(f" - {event['name']}", err=True)
raise click.Abort()
if len(matching_events) > 1:
click.echo(f"Multiple events found with name '{event_name}':", err=True)
for event in matching_events:
click.echo(f" - {event['name']} (slug: {event['slug']})", err=True)
raise click.Abort()
# Return the full slug
event_slug = matching_events[0]["slug"]
# Check if event_slug already contains the tournament part
if event_slug.startswith(tournament_slug):
full_slug = event_slug
else:
full_slug = f"{tournament_slug}/event/{event_slug}"
click.echo(full_slug)
return full_slug
@cli.command()
@click.option("--bracket", help="URL or slug of the bracket")
@click.option("--latest", is_flag=True, help="Choose the most recent bracket")
def sets(bracket, latest):
"""Show kevbot's sets with win/loss format"""
if bracket:
# If it's a URL, convert to slug
if bracket.startswith("http"):
slug = url2slug(bracket)
else:
slug = bracket
else:
chosen = choose_bracket(latest=latest)
slug = url2slug(chosen["BracketUrl"])
# First get phase and phase group IDs
structure_query = """
query EventStructure($slug: String!) {
event(slug: $slug) {
name
phases {
id
name
phaseGroups {
nodes {
id
displayIdentifier
}
}
}
}
}
"""
# Query for sets from a specific phase
phase_sets_query = """
query GetPhaseSets($phaseId: ID!, $perPage: Int!, $page: Int!) {
phase(id: $phaseId) {
sets(perPage: $perPage, page: $page) {
pageInfo {
totalPages
}
nodes {
id
round
fullRoundText
winnerId
displayScore
completedAt
slots {
entrant {
id
name
participants {
gamerTag
user {
id
}
}
}
}
}
}
}
}
"""
# Query for sets from a specific phase group
phase_group_sets_query = """
query GetPhaseGroupSets($phaseGroupId: ID!, $perPage: Int!, $page: Int!) {
phaseGroup(id: $phaseGroupId) {
sets(perPage: $perPage, page: $page) {
pageInfo {
totalPages
}
nodes {
id
round
fullRoundText
winnerId
displayScore
completedAt
slots {
entrant {
id
name
participants {
gamerTag
user {
id
}
}
}
}
}
}
}
}
"""
headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}
# Get event structure
response = requests.post(
"https://api.start.gg/gql/alpha",
json={"query": structure_query, "variables": {"slug": slug}},
headers=headers,
)
if response.status_code != 200:
click.echo(f"Error: {response.status_code}", err=True)
click.echo(response.text, err=True)
raise click.Abort()
data = response.json()
if "errors" in data:
click.echo("GraphQL Errors:", err=True)
for error in data["errors"]:
click.echo(error["message"], err=True)
raise click.Abort()
event = data["data"]["event"]
if not event["phases"]:
click.echo("No phases found for this event.")
return
# Collect all sets (deduplicate by set ID)
all_sets_dict = {}
per_page = 50 # Lower to avoid complexity issues
# Fetch sets from each phase and phase group with pagination
for phase in event["phases"]:
# Fetch phase sets if no phase groups (e.g., single elimination brackets)
if not phase["phaseGroups"]["nodes"]:
click.echo(f"Fetching sets from phase {phase['name']}...", err=True)
page = 1
while True:
response = requests.post(
"https://api.start.gg/gql/alpha",
json={
"query": phase_sets_query,
"variables": {
"phaseId": phase["id"],
"perPage": per_page,
"page": page,
},
},
headers=headers,
)
if response.status_code != 200:
break
data = response.json()
if "errors" in data:
break
if not data["data"]["phase"]:
break
phase_sets = data["data"]["phase"]["sets"]["nodes"]
if not phase_sets:
break
click.echo(f" Page {page}: {len(phase_sets)} sets", err=True)
# Add sets and check for kevbot
for s in phase_sets:
all_sets_dict[s["id"]] = s
# Stop if we got less than a full page
if len(phase_sets) < per_page:
break
page += 1
# Fetch from each phase group
for phase_group in phase["phaseGroups"]["nodes"]:
click.echo(
f"Fetching sets from {phase['name']} - Pool {phase_group['displayIdentifier']}...",
err=True,
)
page = 1
while True:
response = requests.post(
"https://api.start.gg/gql/alpha",
json={
"query": phase_group_sets_query,
"variables": {
"phaseGroupId": phase_group["id"],
"perPage": per_page,
"page": page,
},
},
headers=headers,
)
if response.status_code != 200:
break
data = response.json()
if "errors" in data:
break
if not data["data"]["phaseGroup"]:
break
pg_sets = data["data"]["phaseGroup"]["sets"]["nodes"]
if not pg_sets:
break
click.echo(f" Page {page}: {len(pg_sets)} sets", err=True)
# Add sets
for s in pg_sets:
all_sets_dict[s["id"]] = s
# Stop if we got less than a full page
if len(pg_sets) < per_page:
break
page += 1
all_sets = list(all_sets_dict.values())
click.echo(f"Total sets processed: {len(all_sets)}", err=True)
# Get character lookup from historical data (force refresh cache each run)
click.echo("Fetching character data...", err=True)
html = fetch_character_html(force=True)
char_lookup = get_character_lookup(html)
click.echo(f"Loaded {len(char_lookup)} opponent-character mappings", err=True)
# Filter for kevbot sets
kevbot_sets = []
for s in all_sets:
if s["slots"][0]["entrant"] and s["slots"][1]["entrant"]:
# Check if kevbot is in the set
kevbot_slot = None
opponent_slot = None
for i, slot in enumerate(s["slots"]):
if slot["entrant"] and slot["entrant"]["participants"]:
for participant in slot["entrant"]["participants"]:
if participant and (
"kevbot" in participant.get("gamerTag", "").lower()
or (
participant.get("user")
and participant.get("user", {}).get("id")
== KEVBOT_SGG_ID
)
):
kevbot_slot = i
opponent_slot = 1 - i
break
if kevbot_slot is not None:
break
if kevbot_slot is not None:
opponent_name = s["slots"][opponent_slot]["entrant"]["name"].split(
" | "
)[-1]
# Look up character from historical data
char = char_lookup.get(opponent_name.lower())
if char:
opponent_name = f"{opponent_name} {char}"
round_text = s["fullRoundText"] or f"Round {s['round']}"
# Abbreviate round names
round_lower = round_text.lower().replace("-", "")
# Start with bracket type
if "winners" in round_lower:
abbrev = "W"
elif "losers" in round_lower:
abbrev = "L"
elif "grand" in round_lower:
abbrev = "GF"
else:
abbrev = ""
# Add round type
if "quarter" in round_lower:
abbrev += "Q"
elif "semi" in round_lower:
abbrev += "S"
elif "final" in round_lower:
if abbrev != "GF": # Don't add F to GF
abbrev += "F"
round_text = abbrev if abbrev else round_text
# Determine win/loss and format score
if s["winnerId"] and s["displayScore"]:
kevbot_won = (
s["winnerId"] == s["slots"][kevbot_slot]["entrant"]["id"]
)
# Parse the actual score from displayScore
score_text = s["displayScore"]
# displayScore format is "PlayerName score - PlayerName score"
# Split on " - " and take the trailing number from each half
# so numbers in player names/sponsors don't get picked up as scores
parts = re.split(r"\s+-\s+", score_text, maxsplit=1)
if len(parts) == 2:
m1 = re.search(r"(\d+)\s*$", parts[0])
m2 = re.search(r"(\d+)\s*$", parts[1])
score1 = m1.group(1) if m1 else None
score2 = m2.group(1) if m2 else None
else:
score1, score2 = None, None
if score1 and score2:
# Determine which score is kevbot's based on slot position
if kevbot_slot == 0:
kevbot_score = score1
opponent_score = score2
else:
kevbot_score = score2
opponent_score = score1
formatted_score = f"{kevbot_score}-{opponent_score}"
else:
# Show the raw score if we can't parse it
formatted_score = f"[{score_text}]"
status = ""
else:
status = ""
formatted_score = "?-?"
kevbot_sets.append(
{
"opponent": opponent_name,
"status": status,
"score": formatted_score,
"round": round_text,
"round_num": s["round"],
"completedAt": s.get("completedAt", 0) or 0,
}
)
click.echo(f"Kevbot sets found: {len(kevbot_sets)}", err=True)
if not kevbot_sets:
click.echo("No sets found for kevbot in this tournament.")
return
# Sort by completion time (most recent first)
kevbot_sets.sort(key=lambda x: x["completedAt"], reverse=True)
# Print console summary
if kevbot_sets:
click.echo("Tournament Results:")
for set_info in kevbot_sets:
click.echo(
f"{set_info['opponent']} {set_info['score']} {set_info['round']}"
)
click.echo()
# Generate HTML table
html_rows = []
for set_info in kevbot_sets:
html_rows.append(
f"<tr><td>{set_info['opponent']}</td><td>{set_info['status']}</td><td>{set_info['score']} {set_info['round']}</td></tr>"
)
html_table = f"<table><tbody>{''.join(html_rows)}</tbody></table>"
# Copy HTML to clipboard
try:
if sys.platform == "darwin":
# macOS: use clippy
result = subprocess.run(
["clippy", "--mime", "text/html"],
input=html_table,
text=True,
check=True,
)
else:
# Linux: use xclip
result = subprocess.run(
["xclip", "-selection", "clipboard", "-i", "-t", "text/html"],
input=html_table,
text=True,
check=True,
)
click.echo("HTML table copied to clipboard!")
except subprocess.CalledProcessError as e:
click.echo(f"Error copying to clipboard: {e}", err=True)
except FileNotFoundError:
tool = "clippy" if sys.platform == "darwin" else "xclip"
click.echo(f"{tool} not found.")
@cli.command()
@click.option("--bracket", help="URL or slug of the bracket")
@click.option("--latest", is_flag=True, help="Choose the most recent bracket")
@click.option(
"--num", default=100, help="Number of seeds to fetch (default: 100, max: 512)"
)
def entrants(bracket, latest, num):
if num > 512:
click.echo("Error: --num cannot exceed 512", err=True)
raise click.Abort()
"""Get entrants for a bracket"""
if bracket:
# If it's a URL, convert to slug
if bracket.startswith("http"):
slug = url2slug(bracket)
else:
slug = bracket
else:
chosen = choose_bracket(latest=latest)
slug = url2slug(chosen["BracketUrl"])
event = get_entrants(slug, num)
click.echo(f"\nEvent: {event['name']}")
# Get seeds from the first phase
if event["phases"] and event["phases"][0]["seeds"]["nodes"]:
seeds = event["phases"][0]["seeds"]["nodes"]
click.echo(f"Tournament: https://start.gg/{slug}")
click.echo(f"Total Seeds: {len(seeds)}")
click.echo("\nSeeds (ordered by seed number):")
# Sort by seed number
sorted_seeds = sorted(seeds, key=lambda x: x["seedNum"])
for seed in sorted_seeds:
name = seed["entrant"]["name"]
# Split name on | and take the right part if it exists, otherwise keep full name
name = name.split(" | ")[-1]
click.echo(f"{seed['seedNum']:03d} - {name}")
else:
click.echo("No seeds found for this event.")
if __name__ == "__main__":
cli()