Maharshi Gor commited on
Commit
b9c0bac
·
1 Parent(s): 5f3e7d5

Updated leaderboard

Browse files
.gitignore CHANGED
@@ -20,4 +20,5 @@ eval-*/
20
  logs/
21
  data/
22
  outputs/
23
- hf_cache/
 
 
20
  logs/
21
  data/
22
  outputs/
23
+ hf_cache/
24
+ demos/
app.py CHANGED
@@ -9,6 +9,7 @@ from loguru import logger
9
  import populate
10
  from about import LEADERBOARD_INTRODUCTION_TEXT, LEADERBOARD_TITLE
11
  from app_configs import DEFAULT_SELECTIONS, THEME
 
12
  from components.quizbowl.bonus import BonusInterface
13
  from components.quizbowl.tossup import TossupInterface
14
  from components.typed_dicts import PipelineInterfaceDefaults, TossupInterfaceDefaults
@@ -55,18 +56,6 @@ def download_dataset_snapshot(repo_id, local_dir):
55
  download_dataset_snapshot(QUEUE_REPO, EVAL_REQUESTS_PATH)
56
 
57
 
58
- def fetch_tossup_leaderboard():
59
- logger.info("Tossup leaderboard fetched...")
60
- download_dataset_snapshot(RESULTS_REPO, EVAL_RESULTS_PATH)
61
- return populate.get_tossups_leaderboard_df(EVAL_RESULTS_PATH, "tiny_eval")
62
-
63
-
64
- def fetch_bonus_leaderboard():
65
- logger.info("Bonus leaderboard fetched...")
66
- download_dataset_snapshot(RESULTS_REPO, EVAL_RESULTS_PATH)
67
- return populate.get_bonuses_leaderboard_df(EVAL_RESULTS_PATH, "tiny_eval")
68
-
69
-
70
  def load_dataset(mode: str):
71
  if mode == "tossup":
72
  ds = datasets.load_dataset(PLAYGROUND_DATASET_NAMES["tossup"], split="eval")
@@ -155,30 +144,7 @@ if __name__ == "__main__":
155
  leaderboard_timer = gr.Timer(LEADERBOARD_REFRESH_INTERVAL)
156
  gr.Markdown("<a id='leaderboard' href='#leaderboard'>QANTA Leaderboard</a>")
157
  gr.Markdown(LEADERBOARD_INTRODUCTION_TEXT)
158
- refresh_btn = gr.Button("🔄 Refresh")
159
-
160
- gr.Markdown("## 📚 Tossup Round Leaderboard")
161
- tossup_leaderboard = gr.Dataframe(
162
- value=fetch_tossup_leaderboard,
163
- every=leaderboard_timer,
164
- headers=[c.name for c in fields(AutoEvalColumn)],
165
- datatype=[c.type for c in fields(AutoEvalColumn)],
166
- elem_id="tossup-table",
167
- interactive=False,
168
- visible=True,
169
- )
170
-
171
- gr.Markdown("## 📚 Bonus Round Leaderboard")
172
- bonus_leaderboard = gr.Dataframe(
173
- value=fetch_bonus_leaderboard,
174
- every=leaderboard_timer,
175
- headers=[c.name for c in fields(AutoEvalColumn)],
176
- datatype=[c.type for c in fields(AutoEvalColumn)],
177
- elem_id="bonus-table",
178
- )
179
-
180
- refresh_btn.click(fn=fetch_tossup_leaderboard, inputs=[], outputs=tossup_leaderboard)
181
- refresh_btn.click(fn=fetch_bonus_leaderboard, inputs=[], outputs=bonus_leaderboard)
182
  with gr.Tab("❓ Help", id="help"):
183
  with gr.Row():
184
  with gr.Column():
 
9
  import populate
10
  from about import LEADERBOARD_INTRODUCTION_TEXT, LEADERBOARD_TITLE
11
  from app_configs import DEFAULT_SELECTIONS, THEME
12
+ from components.leaderboard import create_leaderboard_interface
13
  from components.quizbowl.bonus import BonusInterface
14
  from components.quizbowl.tossup import TossupInterface
15
  from components.typed_dicts import PipelineInterfaceDefaults, TossupInterfaceDefaults
 
56
  download_dataset_snapshot(QUEUE_REPO, EVAL_REQUESTS_PATH)
57
 
58
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  def load_dataset(mode: str):
60
  if mode == "tossup":
61
  ds = datasets.load_dataset(PLAYGROUND_DATASET_NAMES["tossup"], split="eval")
 
144
  leaderboard_timer = gr.Timer(LEADERBOARD_REFRESH_INTERVAL)
145
  gr.Markdown("<a id='leaderboard' href='#leaderboard'>QANTA Leaderboard</a>")
146
  gr.Markdown(LEADERBOARD_INTRODUCTION_TEXT)
147
+ create_leaderboard_interface(demo)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  with gr.Tab("❓ Help", id="help"):
149
  with gr.Row():
150
  with gr.Column():
shared/workflows CHANGED
@@ -1 +1 @@
1
- Subproject commit 9d8bfae31f4db8b25165c950742d13e6c4e80de8
 
1
+ Subproject commit a3347cef2dbbf020dcd01029efa4969e851b393a
src/components/leaderboard.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is kept for reference only and is not used in the enhanced implementation
2
+ # The actual implementation is in enhanced_leaderboard.py
3
+
4
+ import gradio as gr
5
+ import pandas as pd
6
+ from gradio_leaderboard import Leaderboard
7
+
8
+ import populate
9
+ from envs import EVAL_RESULTS_PATH, LEADERBOARD_REFRESH_INTERVAL
10
+
11
+
12
+ def fetch_tossup_leaderboard(style: bool = True):
13
+ # download_dataset_snapshot(RESULTS_REPO, EVAL_RESULTS_PATH)
14
+ df = populate.get_tossups_leaderboard_df(EVAL_RESULTS_PATH, "tiny_eval")
15
+
16
+ def colour_pos_neg(v):
17
+ """Return a CSS rule for the cell that called the function."""
18
+ if pd.isna(v): # keep NaNs unstyled
19
+ return ""
20
+ return "color: green;" if v > 0 else "color: red;"
21
+
22
+ # Apply formatting and styling
23
+ styled_df = df.style.format(
24
+ {
25
+ "Avg Score ⬆️": "{:5.2f}",
26
+ "Buzz Accuracy": "{:>6.1%}",
27
+ "Buzz Position": "{:>6.2f}",
28
+ "Win Rate w/ Humans": "{:>6.1%}",
29
+ "Win Rate w/ Humans (Aggressive)": "{:>6.1%}",
30
+ }
31
+ ).map(colour_pos_neg, subset=["Avg Score ⬆️"])
32
+
33
+ return styled_df if style else df
34
+
35
+
36
+ def fetch_bonus_leaderboard(style: bool = True):
37
+ # download_dataset_snapshot(RESULTS_REPO, EVAL_RESULTS_PATH)
38
+ df = populate.get_bonuses_leaderboard_df(EVAL_RESULTS_PATH, "tiny_eval")
39
+
40
+ # Apply formatting and styling
41
+ styled_df = df.style.format(
42
+ {
43
+ "Question Accuracy": "{:>6.1%}",
44
+ "Part Accuracy": "{:>6.1%}",
45
+ }
46
+ )
47
+
48
+ return styled_df if style else df
49
+
50
+
51
+ def create_leaderboard_interface(app):
52
+ leaderboard_timer = gr.Timer(LEADERBOARD_REFRESH_INTERVAL)
53
+ refresh_btn = gr.Button("🔄 Refresh")
54
+
55
+ gr.Markdown("## 📚 Tossup Round Leaderboard")
56
+ tossup_df = fetch_tossup_leaderboard(style=False)
57
+ tossup_leaderboard = Leaderboard(
58
+ value=tossup_df,
59
+ search_columns=["Submission"],
60
+ datatype=["str", "number", "number", "number", "number", "number"],
61
+ elem_id="tossup-table",
62
+ interactive=False, # Ensure it's not interactive
63
+ )
64
+
65
+ gr.Markdown("## 📚 Bonus Round Leaderboard")
66
+ bonus_df = fetch_bonus_leaderboard(style=False)
67
+ bonus_leaderboard = Leaderboard(
68
+ value=bonus_df,
69
+ search_columns=["Submission"],
70
+ datatype=["str", "number", "number"],
71
+ elem_id="bonus-table",
72
+ interactive=False, # Ensure it's not interactive
73
+ )
74
+
75
+ gr.on(
76
+ triggers=[leaderboard_timer.tick, refresh_btn.click, app.load],
77
+ fn=fetch_tossup_leaderboard,
78
+ inputs=[],
79
+ outputs=tossup_leaderboard,
80
+ )
81
+ gr.on(
82
+ triggers=[leaderboard_timer.tick, refresh_btn.click, app.load],
83
+ fn=fetch_bonus_leaderboard,
84
+ inputs=[],
85
+ outputs=bonus_leaderboard,
86
+ )
src/display/custom_css.py CHANGED
@@ -109,6 +109,9 @@ input[type=range][disabled] {
109
  font-size: 20px;
110
  }
111
 
 
 
 
112
 
113
  .step-container {
114
  background-color: var(--card-bg-color);
 
109
  font-size: 20px;
110
  }
111
 
112
+ .table td .cell-wrap span {
113
+ white-space: pre;
114
+ }
115
 
116
  .step-container {
117
  background-color: var(--card-bg-color);
src/leaderboard/gradio_leaderboard.py ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """gr.Leaderboard() component"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import warnings
6
+ from dataclasses import dataclass, field
7
+ from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Tuple, Union
8
+
9
+ import pandas as pd
10
+ import semantic_version
11
+ from gradio.components import Component
12
+ from gradio.data_classes import GradioModel
13
+ from gradio.events import Events
14
+ from pandas.api.types import (
15
+ is_bool_dtype,
16
+ is_numeric_dtype,
17
+ is_object_dtype,
18
+ is_string_dtype,
19
+ )
20
+ from pandas.io.formats.style import Styler
21
+
22
+
23
+ @dataclass
24
+ class SearchColumns:
25
+ primary_column: str
26
+ secondary_columns: Optional[List[str]]
27
+ label: Optional[str] = None
28
+ placeholder: Optional[str] = None
29
+
30
+
31
+ @dataclass
32
+ class SelectColumns:
33
+ default_selection: Optional[list[str]] = field(default_factory=list)
34
+ cant_deselect: Optional[list[str]] = field(default_factory=list)
35
+ allow: bool = True
36
+ label: Optional[str] = None
37
+ show_label: bool = True
38
+ info: Optional[str] = None
39
+
40
+
41
+ @dataclass
42
+ class ColumnFilter:
43
+ column: str
44
+ type: Literal["slider", "dropdown", "checkboxgroup", "boolean"] = None
45
+ default: Optional[Union[int, float, List[Tuple[str, str]]]] = None
46
+ choices: Optional[Union[int, float, List[Tuple[str, str]]]] = None
47
+ label: Optional[str] = None
48
+ info: Optional[str] = None
49
+ show_label: bool = True
50
+ min: Optional[Union[int, float]] = None
51
+ max: Optional[Union[int, float]] = None
52
+
53
+
54
+ class DataframeData(GradioModel):
55
+ headers: List[str]
56
+ data: Union[List[List[Any]], List[Tuple[Any, ...]]]
57
+ metadata: Optional[Dict[str, Optional[List[Any]]]] = None
58
+
59
+
60
+ class Leaderboard(Component):
61
+ """
62
+ This component displays a table of value spreadsheet-like component. Can be used to display data as an output component, or as an input to collect data from the user.
63
+ Demos: filter_records, matrix_transpose, tax_calculator, sort_records
64
+ """
65
+
66
+ EVENTS = [Events.change, Events.input, Events.select]
67
+
68
+ data_model = DataframeData
69
+
70
+ def __init__(
71
+ self,
72
+ value: pd.DataFrame | None = None,
73
+ *,
74
+ datatype: str | list[str] = "str",
75
+ search_columns: list[str] | SearchColumns | None = None,
76
+ select_columns: list[str] | SelectColumns | None = None,
77
+ filter_columns: list[str | ColumnFilter] | None = None,
78
+ bool_checkboxgroup_label: str | None = None,
79
+ hide_columns: list[str] | None = None,
80
+ latex_delimiters: list[dict[str, str | bool]] | None = None,
81
+ label: str | None = None,
82
+ show_label: bool | None = None,
83
+ every: float | None = None,
84
+ height: int = 500,
85
+ scale: int | None = None,
86
+ min_width: int = 160,
87
+ interactive: bool | None = None,
88
+ visible: bool = True,
89
+ elem_id: str | None = None,
90
+ elem_classes: list[str] | str | None = None,
91
+ render: bool = True,
92
+ wrap: bool = False,
93
+ line_breaks: bool = True,
94
+ column_widths: list[str | int] | None = None,
95
+ ):
96
+ """
97
+ Parameters:
98
+ value: Default value to display in the DataFrame. Must be a pandas DataFrame.
99
+ datatype: Datatype of values in sheet. Can be provided per column as a list of strings, or for the entire sheet as a single string. Valid datatypes are "str", "number", "bool", "date", and "markdown".
100
+ search_columns: See Configuration section of docs for details.
101
+ select_columns: See Configuration section of docs for details.
102
+ filter_columns: See Configuration section of docs for details.
103
+ bool_checkboxgroup_label: Label for the checkboxgroup filter for boolean columns.
104
+ hide_columns: List of columns to hide by default. They will not be displayed in the table but they can still be used for searching, filtering.
105
+ label: The label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.
106
+ latex_delimiters: A list of dicts of the form {"left": open delimiter (str), "right": close delimiter (str), "display": whether to display in newline (bool)} that will be used to render LaTeX expressions. If not provided, `latex_delimiters` is set to `[{ "left": "$$", "right": "$$", "display": True }]`, so only expressions enclosed in $$ delimiters will be rendered as LaTeX, and in a new line. Pass in an empty list to disable LaTeX rendering. For more information, see the [KaTeX documentation](https://katex.org/docs/autorender.html). Only applies to columns whose datatype is "markdown".
107
+ label: The label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.
108
+ show_label: if True, will display label.
109
+ every: If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
110
+ height: The maximum height of the dataframe, specified in pixels if a number is passed, or in CSS units if a string is passed. If more rows are created than can fit in the height, a scrollbar will appear.
111
+ scale: relative size compared to adjacent Components. For example if Components A and B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide as B. Should be an integer. scale applies in Rows, and to top-level Components in Blocks where fill_height=True.
112
+ min_width: minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.
113
+ interactive: if True, will allow users to edit the dataframe; if False, can only be used to display data. If not provided, this is inferred based on whether the component is used as an input or output.
114
+ visible: If False, component will be hidden.
115
+ elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
116
+ elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.
117
+ render: If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.
118
+ wrap: If True, the text in table cells will wrap when appropriate. If False and the `column_width` parameter is not set, the column widths will expand based on the cell contents and the table may need to be horizontally scrolled. If `column_width` is set, then any overflow text will be hidden.
119
+ line_breaks: If True (default), will enable Github-flavored Markdown line breaks in chatbot messages. If False, single new lines will be ignored. Only applies for columns of type "markdown."
120
+ column_widths: An optional list representing the width of each column. The elements of the list should be in the format "100px" (ints are also accepted and converted to pixel values) or "10%". If not provided, the column widths will be automatically determined based on the content of the cells. Setting this parameter will cause the browser to try to fit the table within the page width.
121
+ """
122
+ if value is None:
123
+ raise ValueError("Leaderboard component must have a value set.")
124
+ self.wrap = wrap
125
+ self.headers = [str(s) for s in value.columns]
126
+ self.datatype = datatype
127
+ self.search_columns = self._get_search_columns(search_columns)
128
+ self.bool_checkboxgroup_label = bool_checkboxgroup_label
129
+ self.select_columns_config = self._get_select_columns(select_columns, value)
130
+ self.filter_columns = self._get_column_filter_configs(filter_columns, value)
131
+ self.raise_error_if_incorrect_config()
132
+
133
+ self.hide_columns = hide_columns or []
134
+ self.col_count = (len(self.headers), "fixed")
135
+ if isinstance(value, Styler):
136
+ self.row_count = (value.data.shape[0], "fixed")
137
+ else:
138
+ self.row_count = (value.shape[0], "fixed")
139
+
140
+ if latex_delimiters is None:
141
+ latex_delimiters = [{"left": "$$", "right": "$$", "display": True}]
142
+ self.latex_delimiters = latex_delimiters
143
+ self.height = height
144
+ self.line_breaks = line_breaks
145
+ self.column_widths = [w if isinstance(w, str) else f"{w}px" for w in (column_widths or [])]
146
+ super().__init__(
147
+ label=label,
148
+ every=every,
149
+ show_label=show_label,
150
+ scale=scale,
151
+ min_width=min_width,
152
+ interactive=interactive,
153
+ visible=visible,
154
+ elem_id=elem_id,
155
+ elem_classes=elem_classes,
156
+ render=render,
157
+ value=value,
158
+ )
159
+
160
+ def raise_error_if_incorrect_config(self):
161
+ for col in [self.search_columns.primary_column, *self.search_columns.secondary_columns]:
162
+ if col not in self.headers:
163
+ raise ValueError(f"Column '{col}' not found in the DataFrame headers.")
164
+ for col in self.select_columns_config.default_selection + self.select_columns_config.cant_deselect:
165
+ if col not in self.headers:
166
+ raise ValueError(f"Column '{col}' not found in the DataFrame headers.")
167
+ for col in [col.column for col in self.filter_columns]:
168
+ if col not in self.headers:
169
+ raise ValueError(f"Column '{col}' not found in the DataFrame headers.")
170
+
171
+ @staticmethod
172
+ def _get_best_filter_type(
173
+ column: str, value: pd.DataFrame
174
+ ) -> Literal["slider", "checkboxgroup", "dropdown", "checkbox"]:
175
+ if is_bool_dtype(value[column]):
176
+ return "checkbox"
177
+ if is_numeric_dtype(value[column]):
178
+ return "slider"
179
+ if is_string_dtype(value[column]) or is_object_dtype(value[column]):
180
+ return "checkboxgroup"
181
+ warnings.warn(
182
+ f"{column}'s type is not numeric or string, defaulting to checkboxgroup filter type.",
183
+ UserWarning,
184
+ )
185
+ return "checkboxgroup"
186
+
187
+ @staticmethod
188
+ def _get_column_filter_configs(columns: list[str | ColumnFilter] | None, value: pd.DataFrame) -> list[ColumnFilter]:
189
+ if columns is None:
190
+ return []
191
+ if not isinstance(columns, list):
192
+ raise ValueError("Columns must be a list of strings or ColumnFilter objects")
193
+ return [Leaderboard._get_column_filter_config(column, value) for column in columns]
194
+
195
+ @staticmethod
196
+ def _get_column_filter_config(column: str | ColumnFilter, value: pd.DataFrame):
197
+ column_name = column if isinstance(column, str) else column.column
198
+ best_filter_type = Leaderboard._get_best_filter_type(column_name, value)
199
+ min_val = None
200
+ max_val = None
201
+ if best_filter_type == "slider":
202
+ default = [
203
+ value[column_name].quantile(0.25),
204
+ value[column_name].quantile(0.70),
205
+ ]
206
+ min_val = value[column_name].min()
207
+ max_val = value[column_name].max()
208
+ choices = None
209
+ elif best_filter_type == "checkbox":
210
+ default = False
211
+ choices = None
212
+ else:
213
+ default = value[column_name].unique().tolist()
214
+ default = [(s, s) for s in default]
215
+ choices = default
216
+ if isinstance(column, ColumnFilter):
217
+ if column.type == "boolean":
218
+ column.type = "checkbox"
219
+ if not column.type:
220
+ column.type = best_filter_type
221
+ if column.default is None:
222
+ column.default = default
223
+ if not column.choices:
224
+ column.choices = choices
225
+ if min_val is not None and max_val is not None:
226
+ column.min = min_val
227
+ column.max = max_val
228
+ return column
229
+ if isinstance(column, str):
230
+ return ColumnFilter(
231
+ column=column,
232
+ type=best_filter_type,
233
+ default=default,
234
+ choices=choices,
235
+ min=min_val,
236
+ max=max_val,
237
+ )
238
+ raise ValueError(f"Columns {column} must be a string or a ColumnFilter object")
239
+
240
+ @staticmethod
241
+ def _get_search_columns(
242
+ search_columns: list[str] | SearchColumns | None,
243
+ ) -> SearchColumns:
244
+ if search_columns is None:
245
+ return SearchColumns(primary_column=None, secondary_columns=[])
246
+ if isinstance(search_columns, SearchColumns):
247
+ return search_columns
248
+ if isinstance(search_columns, list):
249
+ return SearchColumns(primary_column=search_columns[0], secondary_columns=search_columns[1:])
250
+ raise ValueError("search_columns must be a list of strings or a SearchColumns object")
251
+
252
+ @staticmethod
253
+ def _get_select_columns(
254
+ select_columns: list[str] | SelectColumns | None,
255
+ value: pd.DataFrame,
256
+ ) -> SelectColumns:
257
+ if select_columns is None:
258
+ return SelectColumns(allow=False)
259
+ if isinstance(select_columns, SelectColumns):
260
+ if not select_columns.default_selection:
261
+ select_columns.default_selection = value.columns.tolist()
262
+ return select_columns
263
+ if isinstance(select_columns, list):
264
+ return SelectColumns(default_selection=select_columns, allow=True)
265
+ raise ValueError("select_columns must be a list of strings or a SelectColumns object")
266
+
267
+ def get_config(self):
268
+ return {
269
+ "row_count": self.row_count,
270
+ "col_count": self.col_count,
271
+ "headers": self.headers,
272
+ "select_columns_config": self.select_columns_config,
273
+ **super().get_config(),
274
+ }
275
+
276
+ def preprocess(self, payload: DataframeData) -> pd.DataFrame:
277
+ """
278
+ Parameters:
279
+ payload: the uploaded spreadsheet data as an object with `headers` and `data` attributes
280
+ Returns:
281
+ Passes the uploaded spreadsheet data as a `pandas.DataFrame`, `numpy.array`, `polars.DataFrame`, or native 2D Python `list[list]` depending on `type`
282
+ """
283
+ import pandas as pd
284
+
285
+ if payload.headers is not None:
286
+ return pd.DataFrame(
287
+ [] if payload.data == [[]] else payload.data,
288
+ columns=payload.headers,
289
+ )
290
+ else:
291
+ return pd.DataFrame(payload.data)
292
+
293
+ def postprocess(self, value: pd.DataFrame) -> DataframeData:
294
+ """
295
+ Parameters:
296
+ value: Expects data any of these formats: `pandas.DataFrame`, `pandas.Styler`, `numpy.array`, `polars.DataFrame`, `list[list]`, `list`, or a `dict` with keys 'data' (and optionally 'headers'), or `str` path to a csv, which is rendered as the spreadsheet.
297
+ Returns:
298
+ the uploaded spreadsheet data as an object with `headers` and `data` attributes
299
+ """
300
+ import pandas as pd
301
+ from pandas.io.formats.style import Styler
302
+
303
+ if value is None:
304
+ return self.postprocess(pd.DataFrame({"column 1": []}))
305
+ if isinstance(value, (str, pd.DataFrame)):
306
+ if isinstance(value, str):
307
+ value = pd.read_csv(value) # type: ignore
308
+ if len(value) == 0:
309
+ return DataframeData(
310
+ headers=list(value.columns), # type: ignore
311
+ data=[[]], # type: ignore
312
+ )
313
+ return DataframeData(
314
+ headers=list(value.columns), # type: ignore
315
+ data=value.to_dict(orient="split")["data"], # type: ignore
316
+ )
317
+ elif isinstance(value, Styler):
318
+ if semantic_version.Version(pd.__version__) < semantic_version.Version("1.5.0"):
319
+ raise ValueError(
320
+ "Styler objects are only supported in pandas version 1.5.0 or higher. Please try: `pip install --upgrade pandas` to use this feature."
321
+ )
322
+ if self.interactive:
323
+ warnings.warn(
324
+ "Cannot display Styler object in interactive mode. Will display as a regular pandas dataframe instead."
325
+ )
326
+ df: pd.DataFrame = value.data # type: ignore
327
+ if len(df) == 0:
328
+ return DataframeData(
329
+ headers=list(df.columns),
330
+ data=[[]],
331
+ metadata=self.__extract_metadata(value), # type: ignore
332
+ )
333
+ return DataframeData(
334
+ headers=list(df.columns),
335
+ data=df.to_dict(orient="split")["data"], # type: ignore
336
+ metadata=self.__extract_metadata(value), # type: ignore
337
+ )
338
+
339
+ @staticmethod
340
+ def __get_cell_style(cell_id: str, cell_styles: list[dict]) -> str:
341
+ styles_for_cell = []
342
+ for style in cell_styles:
343
+ if cell_id in style.get("selectors", []):
344
+ styles_for_cell.extend(style.get("props", []))
345
+ styles_str = "; ".join([f"{prop}: {value}" for prop, value in styles_for_cell])
346
+ return styles_str
347
+
348
+ @staticmethod
349
+ def __extract_metadata(df: Styler) -> dict[str, list[list]]:
350
+ metadata = {"display_value": [], "styling": []}
351
+ style_data = df._compute()._translate(None, None) # type: ignore
352
+ cell_styles = style_data.get("cellstyle", [])
353
+ for i in range(len(style_data["body"])):
354
+ metadata["display_value"].append([])
355
+ metadata["styling"].append([])
356
+ for j in range(len(style_data["body"][i])):
357
+ cell_type = style_data["body"][i][j]["type"]
358
+ if cell_type != "td":
359
+ continue
360
+ display_value = style_data["body"][i][j]["display_value"]
361
+ cell_id = style_data["body"][i][j]["id"]
362
+ styles_str = Leaderboard.__get_cell_style(cell_id, cell_styles)
363
+ metadata["display_value"][i].append(display_value)
364
+ metadata["styling"][i].append(styles_str)
365
+ return metadata
366
+
367
+ def process_example(
368
+ self,
369
+ value: pd.DataFrame | Styler | str | None,
370
+ ):
371
+ import pandas as pd
372
+
373
+ if value is None:
374
+ return ""
375
+ value_df_data = self.postprocess(value)
376
+ value_df = pd.DataFrame(value_df_data.data, columns=value_df_data.headers)
377
+ return value_df.head(n=5).to_dict(orient="split")["data"]
378
+
379
+ def example_payload(self) -> Any:
380
+ return {"headers": ["a", "b"], "data": [["foo", "bar"]]}
381
+
382
+ def example_inputs(self) -> Any:
383
+ return self.example_value()
384
+
385
+ def example_value(self) -> Any:
386
+ return {"headers": ["a", "b"], "data": [["foo", "bar"]]}
src/leaderboard/visualization.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import matplotlib
2
+ import matplotlib.pyplot as plt
3
+ import numpy as np
4
+ import plotly.graph_objects as go
5
+
6
+ from utils import get_chart_colors
7
+
8
+
9
+ def setup_matplotlib():
10
+ matplotlib.use("Agg")
11
+ plt.close("all")
12
+
13
+
14
+ def get_performance_chart(df, category_name="Overall"):
15
+ plt.close("all")
16
+ colors = get_chart_colors()
17
+ score_column = "Category Score"
18
+ df_sorted = df.sort_values(score_column, ascending=True)
19
+
20
+ height = max(8, len(df_sorted) * 0.8)
21
+ fig, ax = plt.subplots(figsize=(16, height))
22
+ plt.rcParams.update({"font.size": 12})
23
+
24
+ fig.patch.set_facecolor(colors["background"])
25
+ ax.set_facecolor(colors["background"])
26
+
27
+ try:
28
+ bars = ax.barh(
29
+ np.arange(len(df_sorted)),
30
+ df_sorted[score_column],
31
+ height=0.4,
32
+ capstyle="round",
33
+ color=[colors[t] for t in df_sorted["Model Type"]],
34
+ )
35
+
36
+ ax.set_title(
37
+ f"Model Performance - {category_name}",
38
+ pad=20,
39
+ fontsize=20,
40
+ fontweight="bold",
41
+ color=colors["text"],
42
+ )
43
+ ax.set_xlabel(
44
+ "Average Score (Tool Selection Quality)",
45
+ fontsize=14,
46
+ fontweight="bold",
47
+ labelpad=10,
48
+ color=colors["text"],
49
+ )
50
+ ax.set_xlim(0.0, 1.0)
51
+
52
+ ax.set_yticks(np.arange(len(df_sorted)))
53
+ ax.set_yticklabels(df_sorted["Model"], fontsize=12, fontweight="bold", color=colors["text"])
54
+
55
+ plt.subplots_adjust(left=0.35)
56
+
57
+ for i, v in enumerate(df_sorted[score_column]):
58
+ ax.text(
59
+ v + 0.01,
60
+ i,
61
+ f"{v:.3f}",
62
+ va="center",
63
+ fontsize=12,
64
+ fontweight="bold",
65
+ color=colors["text"],
66
+ )
67
+
68
+ ax.grid(True, axis="x", linestyle="--", alpha=0.2, color=colors["grid"])
69
+ ax.spines[["top", "right"]].set_visible(False)
70
+ ax.spines[["bottom", "left"]].set_color(colors["grid"])
71
+ ax.tick_params(colors=colors["text"])
72
+
73
+ legend_elements = [
74
+ plt.Rectangle((0, 0), 1, 1, facecolor=color, label=label)
75
+ for label, color in {k: colors[k] for k in ["Private", "Open source"]}.items()
76
+ ]
77
+ ax.legend(
78
+ handles=legend_elements,
79
+ title="Model Type",
80
+ loc="lower right",
81
+ fontsize=12,
82
+ title_fontsize=14,
83
+ facecolor=colors["background"],
84
+ labelcolor=colors["text"],
85
+ )
86
+
87
+ plt.tight_layout()
88
+ return fig
89
+ finally:
90
+ plt.close(fig)
91
+
92
+
93
+ def create_radar_plot(df, model_names):
94
+ datasets = [col for col in df.columns[7:] if col != "IO Cost"]
95
+ fig = go.Figure()
96
+
97
+ colors = ["rgba(99, 102, 241, 0.3)", "rgba(34, 197, 94, 0.3)"]
98
+ line_colors = ["#4F46E5", "#16A34A"]
99
+
100
+ for idx, model_name in enumerate(model_names):
101
+ model_data = df[df["Model"] == model_name].iloc[0]
102
+ values = [model_data[m] for m in datasets]
103
+ values.append(values[0])
104
+ datasets_plot = datasets + [datasets[0]]
105
+
106
+ fig.add_trace(
107
+ go.Scatterpolar(
108
+ r=values,
109
+ theta=datasets_plot,
110
+ fill="toself",
111
+ fillcolor=colors[idx % len(colors)],
112
+ line=dict(color=line_colors[idx % len(line_colors)], width=2),
113
+ name=model_name,
114
+ text=[f"{val:.3f}" for val in values],
115
+ textposition="middle right",
116
+ mode="lines+markers+text",
117
+ )
118
+ )
119
+
120
+ fig.update_layout(
121
+ polar=dict(
122
+ radialaxis=dict(visible=True, range=[0, 1], showline=False, tickfont=dict(size=12)),
123
+ angularaxis=dict(
124
+ tickfont=dict(size=13, family="Arial"),
125
+ rotation=90,
126
+ direction="clockwise",
127
+ ),
128
+ ),
129
+ showlegend=True,
130
+ legend=dict(
131
+ orientation="h",
132
+ yanchor="bottom",
133
+ y=-0.2,
134
+ xanchor="center",
135
+ x=0.5,
136
+ font=dict(size=14),
137
+ ),
138
+ title=dict(
139
+ text="Model Comparison",
140
+ x=0.5,
141
+ y=0.95,
142
+ font=dict(size=24, family="Arial", color="#1F2937"),
143
+ ),
144
+ paper_bgcolor="white",
145
+ plot_bgcolor="white",
146
+ height=700,
147
+ width=900,
148
+ margin=dict(t=100, b=100, l=80, r=80),
149
+ )
150
+
151
+ return fig
152
+
153
+
154
+ def get_performance_cost_chart(df, category_name="Overall"):
155
+ colors = get_chart_colors()
156
+ fig, ax = plt.subplots(figsize=(12, 8), dpi=300)
157
+
158
+ fig.patch.set_facecolor(colors["background"])
159
+ ax.set_facecolor(colors["background"])
160
+ ax.grid(True, linestyle="--", alpha=0.15, which="both", color=colors["grid"])
161
+
162
+ score_column = "Category Score"
163
+
164
+ for _, row in df.iterrows():
165
+ color = colors[row["Model Type"]]
166
+ size = 100 if row[score_column] > 0.85 else 80
167
+ edge_color = colors["Private"] if row["Model Type"] == "Private" else colors["Open source"]
168
+
169
+ ax.scatter(
170
+ row["IO Cost"],
171
+ row[score_column] * 100,
172
+ c=color,
173
+ s=size,
174
+ alpha=0.9,
175
+ edgecolor=edge_color,
176
+ linewidth=1,
177
+ zorder=5,
178
+ )
179
+
180
+ bbox_props = dict(boxstyle="round,pad=0.3", fc=colors["background"], ec="none", alpha=0.8)
181
+
182
+ ax.annotate(
183
+ f"{row['Model']}\n(${row['IO Cost']:.2f})",
184
+ (row["IO Cost"], row[score_column] * 100),
185
+ xytext=(5, 5),
186
+ textcoords="offset points",
187
+ fontsize=8,
188
+ fontweight="bold",
189
+ color=colors["text"],
190
+ bbox=bbox_props,
191
+ zorder=6,
192
+ )
193
+
194
+ ax.set_xscale("log")
195
+ ax.set_xlim(0.08, 1000)
196
+ ax.set_ylim(60, 100)
197
+
198
+ ax.set_xlabel(
199
+ "I/O Cost per Million Tokens ($)",
200
+ fontsize=10,
201
+ fontweight="bold",
202
+ labelpad=10,
203
+ color=colors["text"],
204
+ )
205
+ ax.set_ylabel(
206
+ "Model Performance Score",
207
+ fontsize=10,
208
+ fontweight="bold",
209
+ labelpad=10,
210
+ color=colors["text"],
211
+ )
212
+
213
+ legend_elements = [plt.scatter([], [], c=colors[label], label=label, s=80) for label in ["Private", "Open source"]]
214
+ ax.legend(
215
+ handles=legend_elements,
216
+ loc="upper right",
217
+ frameon=True,
218
+ facecolor=colors["background"],
219
+ edgecolor="none",
220
+ fontsize=9,
221
+ labelcolor=colors["text"],
222
+ )
223
+
224
+ ax.set_title(
225
+ f"Performance vs. Cost - {category_name}",
226
+ fontsize=14,
227
+ pad=15,
228
+ fontweight="bold",
229
+ color=colors["text"],
230
+ )
231
+
232
+ for y1, y2, color in zip([85, 75, 60], [100, 85, 75], colors["performance_bands"]):
233
+ ax.axhspan(y1, y2, alpha=0.2, color=color, zorder=1)
234
+
235
+ ax.tick_params(axis="both", which="major", labelsize=9, colors=colors["text"])
236
+ ax.tick_params(axis="both", which="minor", labelsize=8, colors=colors["text"])
237
+ ax.xaxis.set_minor_locator(plt.LogLocator(base=10.0, subs=np.arange(2, 10) * 0.1))
238
+
239
+ for spine in ax.spines.values():
240
+ spine.set_color(colors["grid"])
241
+
242
+ plt.tight_layout()
243
+ return fig
src/populate.py CHANGED
@@ -40,13 +40,13 @@ def get_tossups_leaderboard_df(repo_dir: str, eval_split: str) -> pd.DataFrame:
40
 
41
  row = {
42
  "Submission": f"{username}/{model_name}",
43
- "Avg Score (Max 10)": metrics["tossup_score"],
44
- "Buzzer Accuracy": buzz_accuracy,
45
- "Buzzer Position": metrics["buzz_position"],
46
  }
47
  if "human_win_rate" in metrics:
48
- row["Win Rate w/ Human"] = metrics["human_win_rate"]
49
- row["Win Rate w/ Human (Aggressive)"] = metrics["human_win_rate_strict"]
50
  eval_results.append(row)
51
  except Exception as e:
52
  logger.error(f"Error processing model result '{username}/{model_name}': {e}")
 
40
 
41
  row = {
42
  "Submission": f"{username}/{model_name}",
43
+ "Avg Score ⬆️": metrics["tossup_score"],
44
+ "Buzz Accuracy": buzz_accuracy,
45
+ "Buzz Position": metrics["buzz_position"],
46
  }
47
  if "human_win_rate" in metrics:
48
+ row["Win Rate w/ Humans"] = metrics["human_win_rate"]
49
+ row["Win Rate w/ Humans (Aggressive)"] = metrics["human_win_rate_strict"]
50
  eval_results.append(row)
51
  except Exception as e:
52
  logger.error(f"Error processing model result '{username}/{model_name}': {e}")