-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.py
More file actions
3036 lines (2638 loc) · 122 KB
/
Copy pathbuild.py
File metadata and controls
3036 lines (2638 loc) · 122 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
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Static site generator for the SEC-bench leaderboard site
Converts YAML data to static HTML using Jinja2 templates
"""
import json
import html
import copy
import re
import shutil
from datetime import date, datetime
from pathlib import Path
from urllib.parse import quote, unquote
try:
from jinja2 import Environment, FileSystemLoader
except ModuleNotFoundError:
Environment = None
FileSystemLoader = None
try:
import yaml
except ModuleNotFoundError:
yaml = None
try:
import markdown
except ModuleNotFoundError:
markdown = None
try:
from pygments import highlight as pygments_highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import TextLexer, get_lexer_by_name
from pygments.util import ClassNotFound
except ModuleNotFoundError:
pygments_highlight = None
HtmlFormatter = None
TextLexer = None
get_lexer_by_name = None
ClassNotFound = Exception
# ==============================================================================
# Citation Formats
# ==============================================================================
CITATION_FORMATS = (
("bibtex", "BibTeX"),
("apa", "APA"),
("mla", "MLA"),
)
RESOURCE_LINK_KEYS = ("paper_url", "code_url", "data_url", "submit_url")
RESOURCE_LINK_MODES = ("pro", "classic")
def normalize_resource_links(site_config: dict) -> dict:
"""Return per-mode navigation resource links from leaderboards.yaml."""
configured = site_config.get("resource_links") or {}
links = {}
for mode in RESOURCE_LINK_MODES:
values = configured.get(mode) or {}
links[mode] = {key: values.get(key) for key in RESOURCE_LINK_KEYS}
return links
def default_markdown_content(resource_links: dict) -> dict:
"""Resource links and small content fallbacks when Markdown is unavailable."""
return {
"about": (
"<p>SEC-bench Pro expands the SEC-bench benchmark family toward harder, "
"project-specific security evaluations across Chromium V8, Firefox SpiderMonkey, and Linux.</p>"
),
"resource_links": resource_links,
"paper_url": resource_links["classic"]["paper_url"],
"code_url": resource_links["classic"]["code_url"],
"data_url": resource_links["classic"]["data_url"],
}
def load_citations_data(citations_file: Path) -> list:
"""Load citation tabs and normalize citation formats for template rendering."""
if yaml is None:
raise SystemExit("PyYAML is required to read data/citations.yaml. Run `make install`.")
if not citations_file.exists():
print(f"⚠ Warning: citations file not found: {citations_file}")
return []
with open(citations_file, "r", encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
citations = []
for entry in data.get("citation_tabs", []):
citation_id = entry.get("id")
raw_formats = entry.get("citations") or {}
formats = [
{"id": format_id, "label": label, "text": raw_formats[format_id].strip()}
for format_id, label in CITATION_FORMATS
if raw_formats.get(format_id)
]
if not citation_id or not formats:
print(f"⚠ Warning: Skipping malformed citation entry: {entry}")
continue
citations.append(
{
"id": citation_id,
"label": entry.get("label") or citation_id,
"heading": entry.get("heading") or entry.get("label") or citation_id,
"description": entry.get("description", ""),
"formats": formats,
}
)
return citations
# ==============================================================================
# Organization Logo Mapping
# ==============================================================================
# Maps organization names to their logo image URLs.
# Add new organizations here as they submit to the leaderboard.
# ==============================================================================
ORG_LOGOS = {
# Agent/Tool Organizations
"All Hands": "https://avatars.githubusercontent.com/u/169105795?s=200&v=4", # OpenHands
"OpenHands": "https://avatars.githubusercontent.com/u/169105795?s=200&v=4",
"SWE-agent": "https://avatars.githubusercontent.com/u/166046056?s=200&v=4",
"Princeton": "https://avatars.githubusercontent.com/u/166046056?s=200&v=4", # SWE-agent is from Princeton
"University of Melbourne": "/img/unimelb-logo.svg",
"Aider": "https://avatars.githubusercontent.com/u/172139148?s=48&v=4",
"Agentless": "https://avatars.githubusercontent.com/u/104632009?s=200&v=4", # UIUC
"UIUC": "https://avatars.githubusercontent.com/u/104632009?s=200&v=4",
# AI Model Providers
"Anthropic": "https://avatars.githubusercontent.com/u/76263028?s=200&v=4",
"OpenAI": "https://avatars.githubusercontent.com/u/14957082?s=200&v=4",
"Google": "https://avatars.githubusercontent.com/u/1342004?s=200&v=4",
"Gemini": "https://avatars.githubusercontent.com/u/1342004?s=200&v=4",
"Moonshot": "https://avatars.githubusercontent.com/u/129152888?s=200&v=4",
"Kimi": "https://avatars.githubusercontent.com/u/129152888?s=200&v=4",
"Moonshot AI": "https://statics.moonshot.cn/moonshot-ai/assets/static/kimi-icon.ByIGCGon.webp",
"MiniMax": "/img/minimax-color.svg",
"Z.ai": "https://upload.wikimedia.org/wikipedia/commons/f/f4/Z.ai_%28company_logo%29.svg",
"Zhipu": "https://upload.wikimedia.org/wikipedia/commons/f/f4/Z.ai_%28company_logo%29.svg",
"NVIDIA": "https://avatars.githubusercontent.com/u/1728152?s=200&v=4",
# Cloud/Enterprise
"Amazon": "https://avatars.githubusercontent.com/u/2232217?s=200&v=4",
"AWS": "https://avatars.githubusercontent.com/u/2232217?s=200&v=4",
"Microsoft": "https://avatars.githubusercontent.com/u/6154722?s=200&v=4",
"Meta": "https://avatars.githubusercontent.com/u/69631?s=200&v=4",
"Alibaba": "https://avatars.githubusercontent.com/u/1961952?s=200&v=4",
"Bytedance": "https://avatars.githubusercontent.com/u/20225159?s=200&v=4",
# Research Labs
"NUS": "https://avatars.githubusercontent.com/u/28691550?s=200&v=4", # AutoCodeRover
"Stanford": "https://avatars.githubusercontent.com/u/6937093?s=200&v=4",
# Other Organizations
"Factory": "https://avatars.githubusercontent.com/u/121155557?s=200&v=4",
"AppMap": "https://avatars.githubusercontent.com/u/48058882?s=200&v=4",
"Moatless": "https://avatars.githubusercontent.com/u/172453067?s=200&v=4",
"CodeStory": "https://avatars.githubusercontent.com/u/132aboratory?s=200&v=4",
"AbanteAI": "https://avatars.githubusercontent.com/u/128949612?s=200&v=4",
}
# Default logo for unknown organizations
DEFAULT_ORG_LOGO = "https://avatars.githubusercontent.com/u/0?s=200&v=4"
RESULTS_DATA_FILE = "results.json"
BLOG_DEFAULT_METADATA = {}
BLOG_MARKDOWN_EXTENSIONS = ["fenced_code", "tables", "toc"]
def org_logo_filter(org_name: str) -> str:
"""Convert organization name to logo URL"""
return ORG_LOGOS.get(org_name, DEFAULT_ORG_LOGO)
def auto_name_from_display(display_name: str) -> str:
"""Convert a display name to the generated leaderboard identifier."""
auto_name = display_name.lower().replace(" ", "_").replace("-", "_")
return "".join(c if c.isalnum() or c == "_" else "" for c in auto_name)
def format_number_filter(value) -> str:
"""Format numeric values for display."""
if value is None or value == "":
return "N/A"
try:
number = float(value)
except (TypeError, ValueError):
return str(value)
if number.is_integer():
return f"{int(number):,}"
return f"{number:,.1f}"
def format_currency_filter(value) -> str:
"""Format a number as USD."""
if value is None or value == "":
return "N/A"
try:
number = float(value)
except (TypeError, ValueError):
return str(value)
if number >= 1000:
return f"${number:,.0f}"
return f"${number:,.2f}"
def token_count_value(value):
"""Parse compact token labels such as 2.6B, 10.4M, or 276K into counts."""
if value in (None, ""):
return None
raw = str(value).strip().replace(",", "")
match = re.fullmatch(r"([0-9]+(?:\.[0-9]+)?)([bBkKmM]?)", raw)
if not match:
return None
number = float(match.group(1))
suffix = match.group(2).upper()
if suffix == "B":
number *= 1_000_000_000
elif suffix == "M":
number *= 1_000_000
elif suffix == "K":
number *= 1_000
return number
def format_token_count(value) -> str:
"""Format token counts with K/M/B suffixes, up to one decimal place."""
if value in (None, ""):
return ""
try:
number = float(value)
except (TypeError, ValueError):
return ""
suffix = ""
if not suffix:
if number >= 1_000_000_000:
number /= 1_000_000_000
suffix = "B"
elif number >= 1_000_000:
number /= 1_000_000
suffix = "M"
elif number >= 1_000:
number /= 1_000
suffix = "K"
compact = f"{number:,.1f}".rstrip("0").rstrip(".")
return f"{compact}{suffix}"
def format_token_label(value) -> str:
"""Normalize compact token labels to one decimal with K/M/B suffixes."""
count = token_count_value(value)
if count is None:
return "" if value in (None, "") else str(value).replace("k", "K")
return format_token_count(count)
def token_pair_label(instance: dict) -> str:
"""Render input/output token usage for a detail-table row."""
token_input = format_token_label(instance.get("tokens_input"))
token_output = format_token_label(instance.get("tokens_output"))
if token_input and token_output:
return f"{token_input}/{token_output}"
if token_input:
return token_input
if token_output:
return token_output
return ""
def display_result_label(instance: dict) -> str:
"""Normalize visible result labels without changing scoring fields."""
if instance.get("result") in ("Timed out", "TIMEOUT"):
return "TIMEOUT"
return instance.get("result", "")
def display_result_class(instance: dict) -> str:
label = display_result_label(instance)
return str(label).lower().replace(" ", "-")
def token_pair_from_counts(input_count, output_count) -> str:
token_input = format_token_count(input_count)
token_output = format_token_count(output_count)
if token_input and token_output:
return f"{token_input}/{token_output}"
return token_input or token_output
def format_runtime_minutes(value) -> str:
if value in (None, ""):
return "N/A"
try:
minutes = float(value)
except (TypeError, ValueError):
return str(value)
if minutes < 60:
return f"{minutes:.1f}".rstrip("0").rstrip(".") + "m"
hours = minutes / 60
return f"{hours:.1f}".rstrip("0").rstrip(".") + "h"
def format_percent_filter(value) -> str:
"""Format a percent with one decimal place unless it is whole."""
if value is None or value == "":
return "N/A"
try:
number = float(value)
except (TypeError, ValueError):
return str(value)
return f"{number:.0f}%" if number.is_integer() else f"{number:.1f}%"
def load_yaml_data(yaml_file: Path) -> dict:
"""Load leaderboard data from YAML file and auto-generate names"""
if yaml is None:
raise SystemExit("PyYAML is required to read data/leaderboards.yaml. Run `make install`.")
with open(yaml_file, "r") as f:
data = yaml.safe_load(f)
# Auto-generate 'name' from 'display_name' if not provided
leaderboard_groups = [data.get("leaderboards", [])]
if isinstance(data.get("legacy"), dict):
leaderboard_groups.append(data["legacy"].get("leaderboards", []))
for leaderboard in [item for group in leaderboard_groups for item in group]:
if "name" not in leaderboard and "display_name" in leaderboard:
leaderboard["name"] = auto_name_from_display(leaderboard["display_name"])
return data
def normalize_run_detail_summary_metrics(run_details: dict):
"""Ensure detail summaries have token and average labels for rendering."""
for detail in run_details.values():
instances = detail.get("instances", [])
summary = detail.setdefault("summary", {})
total = int_value(summary.get("instances"), len(instances)) or len(instances)
total_tokens_input = sum(
instance.get("tokens_input_count")
if instance.get("tokens_input_count") is not None
else (token_count_value(instance.get("tokens_input")) or 0)
for instance in instances
)
total_tokens_output = sum(
instance.get("tokens_output_count")
if instance.get("tokens_output_count") is not None
else (token_count_value(instance.get("tokens_output")) or 0)
for instance in instances
)
total_tokens = sum(
instance.get("tokens_total_count")
if instance.get("tokens_total_count") is not None
else (token_count_value(instance.get("tokens_total")) or 0)
for instance in instances
)
if not total_tokens and (total_tokens_input or total_tokens_output):
total_tokens = total_tokens_input + total_tokens_output
total_runtime = summary.get("total_runtime_min")
if total_runtime in (None, ""):
total_runtime = sum(instance.get("runtime_min") or 0 for instance in instances)
total_runtime = float_value(total_runtime, 0) or 0
total_tools = summary.get("total_tool_calls")
if total_tools in (None, ""):
total_tools = sum(instance.get("tool_calls") or 0 for instance in instances)
total_tools = float_value(total_tools, 0) or 0
summary["total_tokens"] = total_tokens
summary["total_tokens_input"] = total_tokens_input
summary["total_tokens_output"] = total_tokens_output
summary["total_tokens_label"] = token_pair_from_counts(
total_tokens_input, total_tokens_output
)
summary["average_tokens"] = round(total_tokens / total, 1) if total else 0
summary["average_tokens_input"] = (
round(total_tokens_input / total, 1) if total else 0
)
summary["average_tokens_output"] = (
round(total_tokens_output / total, 1) if total else 0
)
summary["average_tokens_label"] = token_pair_from_counts(
total_tokens_input / total if total else 0,
total_tokens_output / total if total else 0,
)
summary["average_tool_calls"] = round(total_tools / total, 1) if total else 0
summary["average_runtime_min"] = round(total_runtime / total, 1) if total else 0
summary["total_runtime_min"] = round(total_runtime, 1)
summary["total_runtime_label"] = format_runtime_minutes(total_runtime)
summary["average_runtime_label"] = format_runtime_minutes(
total_runtime / total if total else 0
)
def percent(solved: int, total: int) -> float:
"""Return a one-decimal percentage for scoreboard display."""
if not total:
return 0.0
return round(solved / total * 100, 1)
def int_value(value, default: int = 0) -> int:
"""Best-effort integer parsing for CSV fields."""
if value in (None, ""):
return default
try:
return int(float(value))
except (TypeError, ValueError):
return default
def float_value(value, default=None):
"""Best-effort float parsing for CSV fields."""
if value in (None, ""):
return default
try:
return float(value)
except (TypeError, ValueError):
return default
def normalize_results_snapshot(data: dict) -> dict:
"""Normalize one generated Pro results snapshot for rendering."""
details = {}
for key, detail in data.get("run_details", {}).items():
if "/" not in key:
continue
target, slug = key.split("/", 1)
details[(target, slug)] = detail
return {
"leaderboards": data.get("leaderboards", []),
"target_tabs": data.get("target_tabs", []),
"run_details": details,
}
def infer_backend(result: dict) -> str:
"""Infer the execution backend for existing Pro result snapshots."""
if result.get("backend"):
return str(result["backend"])
model_text = " ".join(
str(result.get(key, "")) for key in ("model", "model_version", "agent")
).lower()
org = str(result.get("org", "")).lower()
if org == "openai" or "gpt" in model_text:
return "OpenAI"
open_weight_orgs = {"z.ai", "zhipu", "moonshot ai", "minimax"}
open_weight_models = ("glm", "kimi", "minimax")
if (
result.get("open_source")
or org == "anthropic"
or org in open_weight_orgs
or "opus" in model_text
or any(name in model_text for name in open_weight_models)
):
return "AWS Bedrock"
return ""
def load_results_data(data_dir: Path) -> dict | None:
"""Load trajectory-derived generated Pro snapshots for CI builds without siblings."""
path = data_dir / RESULTS_DATA_FILE
if not path.exists():
return None
try:
data = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
print(f"⚠ Warning: Could not parse {path}: {exc}")
return None
if isinstance(data.get("snapshots"), dict):
versions = data.get("versions") or [
{"name": name, "date": "", "title": name}
for name in data["snapshots"].keys()
]
default_version = (
data.get("default_version")
or next(
(
version.get("name")
for version in versions
if version.get("default")
),
None,
)
or (versions[-1].get("name") if versions else None)
)
snapshots = {}
for version in versions:
name = version.get("name")
if not name or name not in data["snapshots"]:
continue
snapshots[name] = normalize_results_snapshot(data["snapshots"][name])
return {
"versions": versions,
"default_version": default_version,
"snapshots": snapshots,
}
return {
"versions": [
{
"name": "current",
"date": "",
"title": "Current snapshot",
"default": True,
}
],
"default_version": "current",
"snapshots": {"current": normalize_results_snapshot(data)},
}
def normalize_footnotes(value) -> list[str]:
"""Normalize YAML footnote lists while tolerating strings and {text: ...} items."""
if not value:
return []
if isinstance(value, str):
value = [value]
if not isinstance(value, list):
return []
footnotes = []
for item in value:
text = item.get("text") if isinstance(item, dict) else item
if text in (None, ""):
continue
footnotes.append(str(text))
return footnotes
def merge_footnotes(*groups) -> list[str]:
"""Merge footnote groups, preserving order and removing duplicates."""
merged = []
seen = set()
for group in groups:
for footnote in normalize_footnotes(group):
if footnote in seen:
continue
seen.add(footnote)
merged.append(footnote)
return merged
def merge_generated_target_tabs(configured_tabs: list, generated_tabs: list) -> list:
"""Overlay YAML-owned tab metadata onto generated target tabs."""
configured_by_name = {
tab.get("name"): tab for tab in configured_tabs if tab.get("name")
}
metadata_keys = ("display_name", "logo", "leaderboard", "status")
merged = []
for tab in generated_tabs:
name = tab.get("name")
configured = configured_by_name.get(name, {})
item = dict(tab)
for key in metadata_keys:
if key in configured:
item[key] = configured[key]
if "instances" not in item and "instances" in configured:
item["instances"] = configured["instances"]
merged.append(item)
return merged
def apply_results_data(
leaderboards_data: dict,
run_details: dict,
generated: dict,
):
"""Merge results.json data into the rendered Pro site data."""
configured_leaderboards = {
leaderboard.get("name"): leaderboard
for leaderboard in leaderboards_data.get("leaderboards", [])
if leaderboard.get("name")
}
common_footnotes = leaderboards_data.get("pro_common_footnotes", [])
metadata_keys = ("display_name", "is_overall")
for leaderboard in generated["leaderboards"]:
configured = configured_leaderboards.get(leaderboard.get("name"), {})
for key in metadata_keys:
if key in configured:
leaderboard[key] = configured[key]
if configured.get("info_sections"):
leaderboard["info_sections"] = configured["info_sections"]
elif not leaderboard.get("info_sections"):
leaderboard["info_sections"] = leaderboards_data.get(
"pro_common_info_sections", []
)
footnotes = merge_footnotes(
common_footnotes,
configured.get("footnotes", []),
leaderboard.get("footnotes", []),
)
if footnotes:
leaderboard["footnotes"] = footnotes
for result in leaderboard.get("results", []):
result["backend"] = infer_backend(result)
leaderboards_data["leaderboards"] = generated["leaderboards"]
leaderboards_data["target_tabs"] = merge_generated_target_tabs(
leaderboards_data.get("target_tabs", []),
generated["target_tabs"],
)
normalize_run_detail_summary_metrics(generated["run_details"])
for detail in generated["run_details"].values():
detail["backend"] = infer_backend(detail)
run_details.update(generated["run_details"])
def url_prefix_for_version(version_name: str, default_version: str | None) -> str:
"""Keep the default/current snapshot on the historical root URLs."""
if not version_name or version_name == default_version:
return ""
return f"/{version_name}"
def prepare_pro_version(
base_site_config: dict,
snapshot: dict,
version: dict,
versions: list[dict],
default_version: str | None,
) -> dict:
"""Build a complete render context for one Pro benchmark snapshot."""
site_config = copy.deepcopy(base_site_config)
generated = copy.deepcopy(snapshot)
run_details = {}
apply_results_data(site_config, run_details, generated)
normalize_run_detail_summary_metrics(run_details)
active_version = dict(version)
version_name = active_version.get("name", "")
url_prefix = url_prefix_for_version(version_name, default_version)
site_config["active_version"] = active_version
site_config["versions"] = versions
site_config["default_version"] = default_version
apply_target_urls(site_config, url_prefix)
attach_run_detail_urls(site_config, run_details, url_prefix)
return {
"name": version_name,
"meta": active_version,
"url_prefix": url_prefix,
"leaderboards_data": site_config,
"run_details": run_details,
"pro_stats": leaderboard_mode_stats(site_config, "pro"),
}
def build_version_links(
pro_versions: list[dict],
active_version: str,
active_leaderboard: str | None,
) -> list[dict]:
links = []
for version in pro_versions:
site_config = version["leaderboards_data"]
target_by_leaderboard = target_for_leaderboard(site_config)
target_urls = {
leaderboard_name: target.get("url", "/")
for leaderboard_name, target in target_by_leaderboard.items()
}
target = target_by_leaderboard.get(active_leaderboard or "overall")
unavailable = False
if target is None:
target = target_by_leaderboard.get("overall")
unavailable = True
version_meta = version["meta"]
base_title = version_meta.get("title") or version_meta.get("name", "")
title = base_title
if unavailable and active_leaderboard:
title = f"{title} - opens Overall; selected target is not in this snapshot"
links.append(
{
"name": version_meta.get("name", ""),
"base_title": base_title,
"title": title,
"url": target.get("url", "/") if target else "/",
"target_urls": target_urls,
"active": version["name"] == active_version,
"unavailable": unavailable,
}
)
return links
def normalize_legacy_leaderboards(site_config: dict) -> dict:
"""Normalize classic SEC-bench rows for the shared leaderboard template."""
if not isinstance(site_config, dict):
return {}
for leaderboard in site_config.get("leaderboards", []):
results = [
result
for result in leaderboard.get("results", [])
if result.get("resolved") is not None
]
ranked = sorted(
results,
key=lambda result: float(result.get("resolved") or 0),
reverse=True,
)
rank_by_id = {id(result): index + 1 for index, result in enumerate(ranked)}
for result in leaderboard.get("results", []):
result["rank"] = rank_by_id.get(id(result))
result["score_label"] = "SEC-bench score"
result.setdefault("open_source", False)
result.setdefault("verified", False)
result.setdefault("date", "")
return site_config
def leaderboard_mode_stats(site_config: dict, mode: str) -> list[dict]:
"""Build compact hero stats for one leaderboard mode."""
leaderboards = site_config.get("leaderboards", [])
total_entries = sum(len(board.get("results", [])) for board in leaderboards)
if mode == "pro":
tabs = [
target
for target in available_target_tabs(site_config)
if target.get("name") != "overall"
]
return [
{
"value": leaderboards[0].get("instances", 0) if leaderboards else 0,
"label": "instances",
},
{
"value": len(leaderboards[0].get("results", [])) if leaderboards else 0,
"label": "runs",
},
{"value": len(tabs), "label": "projects"},
{"value": 2, "label": "score views"},
]
return [
{"value": len(leaderboards), "label": "tasks"},
{"value": total_entries, "label": "entries"},
{"value": "PoC", "label": "generation"},
{"value": "Patch", "label": "repair"},
]
def available_target_tabs(site_config: dict) -> list:
"""Return Pro target tabs that have published leaderboard pages."""
return [
target
for target in site_config.get("target_tabs", [])
if target.get("status") == "available" and target.get("leaderboard")
]
def target_for_leaderboard(site_config: dict) -> dict:
"""Map leaderboard names to their Pro target tab config."""
mapping = {}
for target in available_target_tabs(site_config):
mapping[target.get("leaderboard") or target.get("name")] = target
return mapping
def normalize_url_prefix(url_prefix: str = "") -> str:
prefix = (url_prefix or "").strip()
if not prefix:
return ""
return "/" + prefix.strip("/")
def target_url(target_name: str, url_prefix: str = "") -> str:
prefix = normalize_url_prefix(url_prefix)
if target_name == "overall":
return f"{prefix}/" if prefix else "/"
return f"{prefix}/{target_name}" if prefix else f"/{target_name}"
def detail_url(target_name: str, slug: str, url_prefix: str = "") -> str:
prefix = normalize_url_prefix(url_prefix)
path = f"/{target_name}/runs/{slug}"
return f"{prefix}{path}" if prefix else path
def apply_target_urls(site_config: dict, url_prefix: str = ""):
for target in site_config.get("target_tabs", []):
if not target.get("name"):
continue
target["url"] = target_url(target["name"], url_prefix)
def attach_run_detail_urls(site_config: dict, run_details: dict, url_prefix: str = ""):
"""Annotate leaderboard rows with clean detail URLs when detail data exists."""
target_by_leaderboard = target_for_leaderboard(site_config)
for leaderboard in site_config.get("leaderboards", []):
target = target_by_leaderboard.get(leaderboard.get("name"))
if not target:
continue
scored_results = [
result
for result in leaderboard.get("results", [])
if result.get("resolved") is not None
]
ranked_results = sorted(
scored_results,
key=lambda result: float(result.get("resolved") or 0),
reverse=True,
)
rank_by_id = {
id(result): index + 1 for index, result in enumerate(ranked_results)
}
for result in leaderboard.get("results", []):
result["rank"] = rank_by_id.get(id(result))
details = (
result.get("details")
if isinstance(result.get("details"), dict)
else None
)
if not details:
continue
slug = details.get("slug")
detail = run_details.get((target["name"], slug))
if not slug or not detail:
print(f"⚠ Warning: Missing run detail data for {target['name']}/{slug}")
continue
result["details_available"] = True
result["details_url"] = detail_url(target["name"], slug, url_prefix)
result["details_summary"] = detail.get("summary", {})
def slugify(value: str, fallback: str = "post") -> str:
"""Convert a title into a stable URL slug."""
slug = re.sub(r"[^a-z0-9]+", "-", str(value or "").lower()).strip("-")
return slug or fallback
def parse_front_matter(md_text: str) -> tuple[dict, str]:
"""Return optional YAML front matter and the Markdown body."""
if not md_text.startswith("---\n"):
return {}, md_text
parts = md_text.split("\n---\n", 1)
if len(parts) != 2:
return {}, md_text
raw_meta = parts[0][4:]
if yaml is None:
return {}, parts[1]
try:
metadata = yaml.safe_load(raw_meta) or {}
except yaml.YAMLError as exc:
print(f"⚠ Warning: Could not parse blog front matter: {exc}")
metadata = {}
return metadata if isinstance(metadata, dict) else {}, parts[1]
def plain_text_from_markdown(md_text: str) -> str:
"""Best-effort plain text extraction for titles and summaries."""
text = re.sub(r"```.*?```", " ", str(md_text or ""), flags=re.DOTALL)
text = re.sub(r"`([^`]*)`", r"\1", text)
text = re.sub(r"!\[[^\]]*\]\([^)]+\)", " ", text)
text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text)
text = re.sub(r"<[^>]+>", " ", text)
text = re.sub(r"[*_~>#|`]", "", text)
text = re.sub(r"\s+", " ", text)
return text.strip()
def extract_blog_title(md_text: str, metadata: dict, fallback: str) -> tuple[str, str]:
"""Extract the H1 title and remove it from the post body."""
if metadata.get("title"):
return str(metadata["title"]).strip(), md_text
lines = md_text.splitlines()
for index, line in enumerate(lines):
match = re.match(r"^#\s+(.+?)\s*$", line)
if not match:
continue
title = plain_text_from_markdown(match.group(1)) or fallback
del lines[index]
return title, "\n".join(lines).lstrip()
return fallback, md_text
def extract_blog_summary(md_text: str, metadata: dict) -> tuple[str, str]:
"""Extract a summary and remove deck text from the rendered body."""
explicit = metadata.get("summary") or metadata.get("description") or metadata.get("subtitle")
if explicit:
return plain_text_from_markdown(str(explicit)), md_text
lines = md_text.splitlines()
start = next((index for index, line in enumerate(lines) if line.strip()), None)
if start is None:
return "", md_text
end = start
while end < len(lines) and lines[end].strip():
end += 1
leading_block = "\n".join(lines[start:end]).strip()
if leading_block.startswith(">"):
summary = plain_text_from_markdown(
"\n".join(re.sub(r"^>\s?", "", line) for line in lines[start:end])
)
del lines[start:end]
return summary, "\n".join(lines).lstrip()
if (
len(leading_block) >= 2
and leading_block.startswith(("*", "_"))
and leading_block.endswith(("*", "_"))
):
summary = plain_text_from_markdown(leading_block)
del lines[start:end]
return summary, "\n".join(lines).lstrip()
for block in re.split(r"\n\s*\n", md_text):
candidate = block.strip()
if not candidate or candidate.startswith(("#", "|", "```", "---")):
continue
summary = plain_text_from_markdown(candidate)
if summary:
lines = md_text.splitlines()
block_start = next(
(
index
for index, line in enumerate(lines)
if line.strip() == candidate.splitlines()[0].strip()
),
None,
)
if block_start is None:
return summary, md_text
block_end = block_start
while block_end < len(lines) and lines[block_end].strip():
block_end += 1
del lines[block_start:block_end]
return summary, "\n".join(lines).lstrip()
return "", md_text
def parse_blog_date(value, source_path: Path) -> datetime:
"""Parse a post date, falling back to the source mtime."""
if isinstance(value, datetime):
return value
if isinstance(value, date):
return datetime.combine(value, datetime.min.time())
if value:
text = str(value).strip()
for fmt in ("%Y-%m-%d", "%Y/%m/%d", "%B %d, %Y", "%b %d, %Y"):
try:
return datetime.strptime(text, fmt)
except ValueError:
continue
try:
return datetime.fromisoformat(text)
except ValueError:
print(f"⚠ Warning: Could not parse blog date {text!r} in {source_path}")