-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshow_scoreboard.py
More file actions
322 lines (281 loc) · 10.4 KB
/
Copy pathshow_scoreboard.py
File metadata and controls
322 lines (281 loc) · 10.4 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
#!/usr/bin/env python3
"""Show one team's score on every graded ICFP Contest 2026 problem."""
from __future__ import annotations
import argparse
import json
import math
import re
import sys
from typing import Any
from urllib.error import HTTPError, URLError
from urllib.parse import quote
from urllib.request import Request, urlopen
DEFAULT_BASE_URL = "https://icfpcontest2026.com"
DEFAULT_TEAM = "TSG"
USER_AGENT = (
"Mozilla/5.0 (compatible; show_scoreboard.py/1.0; "
"+https://icfpcontest2026.com/problem-sets)"
)
class ScoreboardError(RuntimeError):
"""An expected error fetching or interpreting scoreboard data."""
def fetch_json(base_url: str, path: str, timeout: float) -> Any:
request = Request(
f"{base_url.rstrip('/')}{path}",
headers={"Accept": "application/json", "User-Agent": USER_AGENT},
)
try:
with urlopen(request, timeout=timeout) as response:
return json.load(response)
except HTTPError as error:
detail = ""
try:
payload = json.loads(error.read())
detail = payload.get("error", {}).get("message", "")
except (json.JSONDecodeError, AttributeError, UnicodeDecodeError):
pass
suffix = f": {detail}" if detail else ""
raise ScoreboardError(f"HTTP {error.code} for {path}{suffix}") from error
except URLError as error:
raise ScoreboardError(f"request failed for {path}: {error.reason}") from error
except (json.JSONDecodeError, UnicodeDecodeError) as error:
raise ScoreboardError(f"invalid JSON returned for {path}") from error
def find_team(standings: dict[str, Any], wanted: str) -> dict[str, Any]:
teams = standings.get("teams")
if not isinstance(teams, list):
raise ScoreboardError("unexpected response from /api/v1/standings")
by_id = [team for team in teams if team.get("teamId") == wanted]
if by_id:
return by_id[0]
exact = [team for team in teams if team.get("teamName") == wanted]
if len(exact) == 1:
return exact[0]
if len(exact) > 1:
raise ScoreboardError(
f"multiple teams are named {wanted!r}; pass a teamId with --team"
)
folded = [
team
for team in teams
if str(team.get("teamName", "")).casefold() == wanted.casefold()
]
if len(folded) == 1:
return folded[0]
if len(folded) > 1:
raise ScoreboardError(
f"multiple teams match {wanted!r}; pass a teamId with --team"
)
raise ScoreboardError(f"team {wanted!r} was not found in the standings")
def natural_key(value: str) -> tuple[tuple[int, Any], ...]:
parts = re.split(r"(\d+)", value.casefold())
return tuple(
(0, int(part)) if part.isdigit() else (1, part)
for part in parts
if part
)
def format_score(value: Any) -> str:
if not isinstance(value, (int, float)) or not math.isfinite(value):
return "—"
if float(value).is_integer():
return f"{int(value):,}"
return f"{value:,.3f}".rstrip("0").rstrip(".")
def format_points(value: Any) -> str:
if not isinstance(value, (int, float)) or not math.isfinite(value):
return "—"
return f"{value:.3f}"
def format_table(headers: list[str], rows: list[list[str]]) -> str:
widths = [
max(len(headers[index]), *(len(row[index]) for row in rows))
for index in range(len(headers))
]
numeric_columns = {2, 3, 4, 5}
def render(row: list[str]) -> str:
cells = []
for index, cell in enumerate(row):
cells.append(
cell.rjust(widths[index])
if index in numeric_columns
else cell.ljust(widths[index])
)
return " | ".join(cells)
separator = "-+-".join("-" * width for width in widths)
return "\n".join([render(headers), separator, *(render(row) for row in rows)])
def collect_scores(
base_url: str, team_name_or_id: str, timeout: float
) -> dict[str, Any]:
standings = fetch_json(base_url, "/api/v1/standings", timeout)
if not isinstance(standings, dict):
raise ScoreboardError("unexpected response from /api/v1/standings")
team = find_team(standings, team_name_or_id)
team_id = team.get("teamId")
if not isinstance(team_id, str):
raise ScoreboardError("the selected team has no teamId")
problems = fetch_json(base_url, "/api/v1/public/problems", timeout)
team_data = fetch_json(
base_url,
f"/api/v1/standings/teams/{quote(team_id, safe='')}",
timeout,
)
if not isinstance(problems, list) or not isinstance(team_data, dict):
raise ScoreboardError("unexpected response from the public API")
standing_by_problem = {
row["problemId"]: row
for row in team_data.get("rows", [])
if isinstance(row, dict) and isinstance(row.get("problemId"), str)
}
graded = [
problem
for problem in problems
if isinstance(problem, dict)
and problem.get("status") == "graded"
and problem.get("problemSetVisible")
]
graded.sort(
key=lambda problem: (
natural_key(str(problem.get("problemSetName") or "Unassigned")),
problem.get("orderInSet")
if isinstance(problem.get("orderInSet"), (int, float))
else math.inf,
natural_key(str(problem.get("name") or problem.get("slug") or "")),
)
)
rows = []
for problem in graded:
standing = standing_by_problem.get(problem.get("id"))
rows.append(
{
"problemSet": problem.get("problemSetName") or "Unassigned",
"problem": problem.get("name") or problem.get("slug") or problem["id"],
"slug": problem.get("slug"),
"problemId": problem.get("id"),
"rank": standing.get("rank") if standing else None,
"fieldSize": standing.get("fieldSize") if standing else None,
"casesPassed": standing.get("casesPassed") if standing else None,
"casesTotal": standing.get("casesTotal") if standing else None,
"score": standing.get("score") if standing else None,
"points": standing.get("points") if standing else None,
}
)
return {
"updatedAt": team_data.get("updatedAt") or standings.get("updatedAt"),
"frozen": bool(team_data.get("frozen", standings.get("frozen", False))),
"teamId": team_id,
"teamName": team_data.get("teamName") or team.get("teamName") or team_id,
"overallRank": team_data.get("rank", team.get("rank")),
"overallPoints": team_data.get("points", team.get("points")),
"fullPasses": team.get("fullPasses"),
"problemCount": team_data.get(
"problemCount", standings.get("problemCount", len(graded))
),
"problems": rows,
}
def sorted_problems(
problems: list[dict[str, Any]], sort_order: str
) -> list[dict[str, Any]]:
if sort_order == "points":
return sorted(
problems,
key=lambda item: (
item["points"] is None,
-(item["points"] or 0),
natural_key(str(item["problem"])),
),
)
return problems
def print_text(data: dict[str, Any], sort_order: str) -> None:
headers = ["Set", "Problem", "Rank", "Passed", "Score", "Points"]
rows = []
for item in sorted_problems(data["problems"], sort_order):
rank = (
f"{item['rank']}/{item['fieldSize']}"
if item["rank"] is not None and item["fieldSize"] is not None
else "—"
)
passed = (
f"{item['casesPassed']}/{item['casesTotal']}"
if item["casesPassed"] is not None and item["casesTotal"] is not None
else "—"
)
rows.append(
[
str(item["problemSet"]),
str(item["problem"]),
rank,
passed,
format_score(item["score"]),
format_points(item["points"]),
]
)
solved = data.get("fullPasses")
count = data.get("problemCount")
solved_text = f", solved {solved}/{count}" if solved is not None else ""
frozen_text = " [FROZEN]" if data["frozen"] else ""
print(
f"{data['teamName']}: overall rank {data['overallRank']}, "
f"{format_points(data['overallPoints'])} points{solved_text}{frozen_text}"
)
print(f"Updated: {data['updatedAt'] or 'unknown'}")
print()
print(format_table(headers, rows))
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description=(
"Display a team's score on every visible graded ICFP Contest 2026 "
"problem."
)
)
parser.add_argument(
"--team",
default=DEFAULT_TEAM,
metavar="NAME_OR_ID",
help=f"team name or teamId (default: {DEFAULT_TEAM})",
)
parser.add_argument(
"--base-url",
default=DEFAULT_BASE_URL,
help=f"contest site base URL (default: {DEFAULT_BASE_URL})",
)
parser.add_argument(
"--timeout",
type=float,
default=20.0,
metavar="SECONDS",
help="timeout for each HTTP request (default: 20)",
)
parser.add_argument(
"--json",
action="store_true",
help="emit machine-readable JSON with unrounded scores",
)
parser.add_argument(
"--sort",
choices=("set", "points"),
default="points",
help="row order: Points descending or problem-set order (default: points)",
)
parser.add_argument(
"--no-sort",
dest="sort",
action="store_const",
const="set",
help="disable Points sorting and use problem-set order",
)
args = parser.parse_args()
if args.timeout <= 0:
parser.error("--timeout must be greater than zero")
return args
def main() -> int:
args = parse_args()
try:
data = collect_scores(args.base_url, args.team, args.timeout)
except ScoreboardError as error:
print(f"error: {error}", file=sys.stderr)
return 1
if args.json:
data["problems"] = sorted_problems(data["problems"], args.sort)
json.dump(data, sys.stdout, ensure_ascii=False, indent=2)
print()
else:
print_text(data, args.sort)
return 0
if __name__ == "__main__":
raise SystemExit(main())