Sfarzi commited on
Commit
02fbbb9
Β·
1 Parent(s): 5dd5fd1

Initial clone with modifications

Browse files
.ipynb_checkpoints/app-checkpoint.py CHANGED
@@ -18,6 +18,364 @@ import plotly.graph_objects as go
18
  import numpy as np
19
 
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  def mean_of_max_per_field(df):
22
  """
23
  Calcola il massimo per ciascun campo e poi la media dei massimi.
@@ -158,33 +516,33 @@ def boxplot_per_task(dataframe=None, baselines=None, references=None):
158
  ))
159
 
160
  # baseline
161
- if task in baselines and baselines[task] is not None:
162
- fig.add_shape(
163
- type="line",
164
- x0=i - 0.3, x1=i + 0.3,
165
- y0=baselines[task], y1=baselines[task],
166
- line=dict(color="black", width=2, dash="dot"), # piΓΉ visibile
167
- xref="x", yref="y"
168
- )
169
- '''
170
- fig.add_annotation(
171
- x=i, y=baselines[task],
172
- text=f"{baselines[task]}%",
173
- showarrow=False,
174
- yshift=10,
175
- font=dict(size=10, color="black")
176
- )
177
- '''
178
 
179
  # reference GPT-4o
180
- if task in references and references[task] is not None:
181
- fig.add_shape(
182
- type="line",
183
- x0=i - 0.3, x1=i + 0.3,
184
- y0=references[task], y1=references[task],
185
- line=dict(color="red", width=2, dash="dashdot"),
186
- xref="x", yref="y"
187
- )
188
 
189
  fig.update_layout(
190
  title="Distribution of Model Accuracy by Task",
@@ -268,8 +626,6 @@ def boxplot_prompts_per_task(dataframe, tasks=None):
268
  y=avg_y,
269
  name="Avg. Accuracy",
270
  marker_color="#1f77b4",
271
- #hovertemplate="%{y:.2f}%<extra></extra>"
272
- #hovertemplate="<b>" + task + "</b><br>Accuracy: %{y:.2f}%<extra></extra>",
273
  ))
274
 
275
  # Barre Best Prompt (rosso)
@@ -278,8 +634,6 @@ def boxplot_prompts_per_task(dataframe, tasks=None):
278
  y=best_y,
279
  name="Best Prompt",
280
  marker_color="#d62728",
281
- #hovertemplate="%{y:.2f}%<extra></extra>"
282
- #hovertemplate = "<b>" + task + "</b><br>Accuracy: %{y:.2f}%<extra></extra>",
283
  ))
284
 
285
  # Testo sopra barre Best Prompt con ID
@@ -347,7 +701,7 @@ def line_chart(dataframe):
347
  x=x_true,
348
  y=y_true,
349
  mode='markers',
350
- name='5-Shot',
351
  marker=dict(
352
  color='blue',
353
  size=scale_sizes(x_true)
@@ -418,7 +772,7 @@ def line_chart(dataframe):
418
  # Caption
419
  fig.add_annotation(
420
  text="Accuracy generally rises with #Params, but smaller models <br>"
421
- "with 5-shot can outperform larger zero-shot models.",
422
  xref="paper", yref="paper",
423
  x=0.5, y=-0.3, # πŸ‘ˆ centrata
424
  showarrow=False,
@@ -523,25 +877,13 @@ def init_leaderboard(dataframe, default_selection=None, hidden_columns=None):
523
  return Leaderboard(
524
  value=sorted_dataframe,
525
  datatype=[c.type for c in field_list],
526
- #select_columns=SelectColumns(
527
- # default_selection=default_selection or [c.name for c in field_list if c.displayed_by_default],
528
- # cant_deselect=[c.name for c in field_list if c.never_hidden],
529
- # label="Select Columns to Display:",
530
- #),
531
  search_columns=[AutoEvalColumn.model.name, AutoEvalColumn.license.name],
532
  hide_columns=hidden_columns or [c.name for c in field_list if c.hidden],
533
  filter_columns=[
534
- ColumnFilter(AutoEvalColumn.fewshot_symbol.name, type="checkboxgroup", label="N-Shot Learning (FS)"),
535
- #ColumnFilter(AutoEvalColumn.fewshot_symbol.name, type="checkboxgroup", label="N-Few-Shot Learning (FS)",
536
- # default=[["0️⃣", "0️⃣"]]),
537
- ColumnFilter(AutoEvalColumn.LANG.name, type="checkboxgroup", label="Languges "),
538
-
539
  ColumnFilter(AutoEvalColumn.params.name, type="slider", min=0, max = 100, default = [0,100], label="Select the number of parameters (B)"),
540
  ],
541
- #filter_columns=[
542
- # ColumnFilter("IS_FS", type="checkbox", default=False, label="5-Few-Shot")
543
- # #ColumnFilter("FS", type="dropdown", label="5-Few-Shot")
544
- #],
545
  bool_checkboxgroup_label="Evaluation Mode",
546
  interactive=False,
547
  )
@@ -620,8 +962,8 @@ def update_task_leaderboard(dataframe, default_selection=None, hidden_columns=No
620
  search_columns=[AutoEvalColumn.model.name, AutoEvalColumn.license.name],
621
  hide_columns=hidden_columns or [c.name for c in field_list if c.hidden],
622
  filter_columns=[
623
- ColumnFilter(AutoEvalColumn.fewshot_symbol.name, type="checkboxgroup", label="N-Shot Learning (FS)"),
624
- ColumnFilter(AutoEvalColumn.LANG.name, type="checkboxgroup", label="Languges "),
625
 
626
  ColumnFilter(AutoEvalColumn.params.name, type="slider", min=0, max=100, default=[0, 100],
627
  label="Select the number of parameters (B)"),
@@ -687,25 +1029,17 @@ with demo:
687
  <h1 style="
688
  margin: 0 auto;
689
  font-weight: 900;
690
- font-size: 2.5em;
691
  letter-spacing: 2px;
692
  text-transform: uppercase;
 
693
  background: linear-gradient(90deg, #1f77b4, #00c6ff);
694
  -webkit-background-clip: text;
695
  -webkit-text-fill-color: transparent;
696
- text-shadow: 2px 2px 8px rgba(0,0,0,0.2);
697
  ">
698
- EVALITA-LLM Leaderboard
699
  </h1>
700
- <a href="https://huggingface.co/spaces/mii-llm/open_ita_llm_leaderboard" target="_blank"
701
- style="position: absolute; right: 0; display: inline-flex; align-items: center; gap: 6px; text-decoration: none; color: #1f77b4; font-weight: 600;">
702
- <!-- Icona stilizzata -->
703
- <svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" fill="#1f77b4" viewBox="0 0 24 24">
704
- <path d="M3.9 12a5 5 0 0 1 7.07-7.07l1.41 1.41-1.41 1.41-1.42-1.42a3 3 0 1 0 4.24 4.24l3.54-3.54a5 5 0 0 1-7.07 7.07l-1.41-1.41 1.41-1.41 1.42 1.42z"/>
705
- <path d="M20.1 12a5 5 0 0 1-7.07 7.07l-1.41-1.41 1.41-1.41 1.42 1.42a3 3 0 1 0-4.24-4.24l-3.54 3.54a5 5 0 0 1 7.07-7.07l1.41 1.41-1.41 1.41-1.42-1.42z"/>
706
- </svg>
707
- Open Italian LLM Leaderboard
708
- </a>
709
  </div>
710
  """
711
  )
@@ -715,8 +1049,37 @@ with demo:
715
  with gr.Row():
716
  gr.Plot(value=line_chart(LEADERBOARD_DF), elem_id="line-chart")
717
  gr.Plot(value=boxplot_per_task(LEADERBOARD_DF, BASELINES, REFERENCES), elem_id="boxplot-task")
718
- #gr.Plot(value=boxplot_prompts_per_task(LEADERBOARD_DF), elem_id="boxplot-prompt-task")
719
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
720
  with gr.Tabs(elem_classes="tab-buttons") as tabs:
721
 
722
  # Main leaderboard tab
@@ -728,41 +1091,11 @@ with demo:
728
  hidden_columns=[col for col in LEADERBOARD_DF.columns if col not in ['Rank', 'Size', 'LANG', 'FS', 'Model', "Avg. Comb. Perf. ⬆️", "TE", "SA", "HS", "AT", "WIC", "FAQ", "LS", "SU", "NER", "REL"]]
729
  )
730
 
731
- # gr.HTML(
732
- # f"""
733
- # <div style="
734
- # border: 2px solid #1f77b4;
735
- # border-radius: 10px;
736
- # padding: 10px;
737
- # background-color: #f0f8ff;
738
- # font-weight: bold;
739
- # font-size: 14px;
740
- # display: inline-block;
741
- # ">
742
- # Theoretical performance of a model that scores the highest on every individual task: <span style="color:#d62728; font-size:18px;">{theoretical_max_combined_perf:.2f}</span>
743
- # </div>
744
- # $ """
745
- # )
746
-
747
- '''
748
- with gr.TabItem("πŸ“ˆ Charts"):
749
- #gr.Plot(value=line_chart(LEADERBOARD_DF), label="Andamento di esempio")
750
- #gr.Plot(value=line_chart_interactive_test(), label="Andamento interattivo")
751
- gr.Plot(value=line_chart(LEADERBOARD_DF))
752
- gr.Plot(value=boxplot_per_task(LEADERBOARD_DF, BASELINES))
753
- gr.Plot(value=boxplot_prompts_per_task(LEADERBOARD_DF))
754
- gr.Plot(value=barplot_mean_few_minus_zero_shot(LEADERBOARD_DF))
755
- '''
756
 
757
  # About tab
758
  with gr.TabItem("πŸ“ About"):
759
  gr.Markdown(LLM_BENCHMARKS_TEXT, elem_classes="markdown-text")
760
 
761
- # About tab
762
- with gr.TabItem("β•‘", interactive=False):
763
- gr.Markdown("", elem_classes="markdown-text")
764
-
765
-
766
  # Task-specific leaderboards
767
  for task, metadata in TASK_METADATA_MULTIPLECHOICE.items():
768
 
@@ -785,8 +1118,8 @@ with demo:
785
  for task, metadata in TASK_METADATA_GENERATIVE.items():
786
  with gr.TabItem(f"{metadata['icon']}{task}"):
787
  task_description = TASK_DESCRIPTIONS.get(task, "Description not available.")
788
- gr.Markdown(task_description, elem_classes="markdown-text")
789
-
790
  leaderboard = update_task_leaderboard(
791
  LEADERBOARD_DF.rename(columns={f"{task} Prompt Average": "Prompt Average",
792
  f"{task} Prompt Std": "Prompt Std",
@@ -807,13 +1140,9 @@ with demo:
807
  with gr.Accordion("πŸ“™ Credits", open=False):
808
  gr.Markdown(
809
  """
810
- **This project has benefited from the following support:**
811
-
812
- - 🧠 **Codebase**: Based on and extended from the Open Italian LLM Leaderboard, developed by **Alessandro Ercolani** and **Samuele Colombo**. We warmly thank them for their invaluable support and guidance in implementing this leaderboard.
813
-
814
- - πŸ’Ά **Funding**: Partially supported by the PNRR project **FAIR - Future AI Research (PE00000013)**, under the NRRP MUR program funded by **NextGenerationEU**.
815
 
816
- - πŸ–₯️ **Computation**: We gratefully acknowledge **CINECA** for granting access to the **LEONARDO** supercomputer.
817
  """
818
  )
819
 
 
18
  import numpy as np
19
 
20
 
21
+
22
+
23
+ # === NEW: helper for prompt sensitivity (simple: only NER/REL and 3 prompts) ===
24
+ def calculate_prompt_sensitivity(dataframe, tasks, prompt_ids):
25
+ """
26
+ Computes a simple Prompt Sensitivity Index (PSI) over the tasks (NER, REL)
27
+ using the distribution of 'Best Prompt Id' across the provided prompt_ids.
28
+ """
29
+ cv_per_task = []
30
+ for task in tasks:
31
+ prompt_col = f"{task} Best Prompt Id"
32
+ task_accuracies = []
33
+ for pid in prompt_ids:
34
+ total = len(dataframe[prompt_col].dropna()) if prompt_col in dataframe.columns else 0
35
+ count = (dataframe[prompt_col] == pid).sum() if prompt_col in dataframe.columns else 0
36
+ acc = (count / total * 100) if total > 0 else 0
37
+ task_accuracies.append(acc)
38
+ if task_accuracies:
39
+ mean_acc = np.mean(task_accuracies)
40
+ std_acc = np.std(task_accuracies)
41
+ cv_per_task.append((std_acc / mean_acc) if mean_acc > 0 else 0)
42
+ else:
43
+ cv_per_task.append(0)
44
+ mean_cv = np.mean(cv_per_task) if cv_per_task else 0
45
+ psi = 1.0 if mean_cv >= 0.5 else (mean_cv / 0.5)
46
+ return psi, mean_cv, cv_per_task
47
+
48
+ def create_best_model_comparison_table(dataframe, lang: str | None = None, shot: str | None = None):
49
+ """
50
+ Table with best overall model per task (NER, REL) and the model with the best prompt score.
51
+ Applies optional filters:
52
+ - lang in {EN, IT, SL, SK, GR, PL} or None/"All"
53
+ - shot in {"0","10"} or None/"All" (mapped to IS_FS False/True)
54
+ """
55
+ tasks = ["NER", "REL"]
56
+ df = dataframe.copy()
57
+
58
+ if lang and lang != "All" and "LANG" in df.columns:
59
+ df = df[df["LANG"] == lang]
60
+ if shot and shot != "All" and "IS_FS" in df.columns:
61
+ df = df[df["IS_FS"] == (shot == "10")]
62
+
63
+ table_data = {'Task': [], 'Best Overall Model': [], 'CPS': [], 'Best Prompt Model': [], 'Acc.': []}
64
+
65
+ for task in tasks:
66
+ if task not in df.columns or df.empty:
67
+ continue
68
+ # Best overall on task
69
+ max_idx = df[task].idxmax()
70
+ model_raw = df.loc[max_idx, 'Model']
71
+ if isinstance(model_raw, str) and '<' in model_raw:
72
+ match = re.search(r'>([^<]+)<', model_raw)
73
+ model_name = match.group(1) if match else model_raw
74
+ else:
75
+ model_name = str(model_raw)
76
+ comb_perf_value = df.loc[max_idx, task]
77
+
78
+ # Best prompt row for task
79
+ best_prompt_column = f"{task} Best Prompt"
80
+ if best_prompt_column in df.columns and df[best_prompt_column].notna().any():
81
+ best_prompt_idx = df[best_prompt_column].idxmax()
82
+ best_prompt_model_raw = df.loc[best_prompt_idx, 'Model']
83
+ if isinstance(best_prompt_model_raw, str) and '<' in best_prompt_model_raw:
84
+ match = re.search(r'>([^<]+)<', best_prompt_model_raw)
85
+ best_prompt_model = match.group(1) if match else best_prompt_model_raw
86
+ else:
87
+ best_prompt_model = str(best_prompt_model_raw)
88
+ best_prompt_accuracy = df.loc[best_prompt_idx, best_prompt_column]
89
+ else:
90
+ best_prompt_model = "n/a"
91
+ best_prompt_accuracy = float('nan')
92
+
93
+ table_data['Task'].append(task)
94
+ table_data['Best Overall Model'].append(model_name)
95
+ table_data['CPS'].append(f"{comb_perf_value:.2f}")
96
+ table_data['Best Prompt Model'].append(best_prompt_model)
97
+ table_data['Acc.'].append(f"{best_prompt_accuracy:.2f}" if isinstance(best_prompt_accuracy, (int, float)) else "n/a")
98
+
99
+ fig = go.Figure(data=[go.Table(
100
+ columnwidth=[60, 220, 60, 220, 60],
101
+ header=dict(
102
+ values=[f'<b>{col}</b>' for col in table_data.keys()],
103
+ fill_color=['#2171b5', '#2171b5', '#2171b5', '#4292c6', '#4292c6'],
104
+ font=dict(color='white', size=12, family='Arial'),
105
+ align='center', height=30
106
+ ),
107
+ cells=dict(
108
+ values=list(table_data.values()),
109
+ fill_color=[['#f0f0f0' if i % 2 == 0 else 'white' for i in range(len(table_data['Task']))]],
110
+ font=dict(color='#2c3e50', size=11, family='Arial'),
111
+ align=['center', 'left', 'center', 'left', 'center'],
112
+ height=30
113
+ )
114
+ )])
115
+
116
+ subtitle = []
117
+ subtitle.append(lang if (lang and lang != "All") else "All languages")
118
+ subtitle.append(f"{shot}-shot" if (shot and shot != "All") else "All shots")
119
+
120
+ fig.update_layout(
121
+ title={'text': f"Top Model per Task: CPS & Best Prompt (NER/REL) β€” {', '.join(subtitle)}",
122
+ 'font': {'family': 'Arial', 'size': 14, 'color': '#2c3e50'}},
123
+ font=dict(family="Arial", size=11),
124
+ height=420, margin=dict(l=20, r=20, t=50, b=80)
125
+ )
126
+ return fig
127
+
128
+
129
+
130
+ # === NEW: Best-model comparison table (only NER, REL) ===
131
+ def create_best_model_comparison_table_without_lang(dataframe):
132
+ """
133
+ Table with the best overall model per task (NER, REL) and the model that
134
+ achieves the best score with its own best prompt.
135
+ """
136
+ tasks = ["NER", "REL"]
137
+ table_data = {'Task': [], 'Best Overall Model': [], 'CPS': [], 'Best Prompt Model': [], 'Acc.': []}
138
+
139
+ for task in tasks:
140
+ if task not in dataframe.columns:
141
+ continue
142
+
143
+ # Best overall on the task's combined performance
144
+ max_idx = dataframe[task].idxmax()
145
+ model_raw = dataframe.loc[max_idx, 'Model']
146
+ if isinstance(model_raw, str) and '<' in model_raw:
147
+ match = re.search(r'>([^<]+)<', model_raw)
148
+ model_name = match.group(1) if match else model_raw
149
+ else:
150
+ model_name = str(model_raw)
151
+ comb_perf_value = dataframe.loc[max_idx, task]
152
+
153
+ # Model with the best prompt for this task
154
+ best_prompt_column = f"{task} Best Prompt"
155
+ if best_prompt_column in dataframe.columns:
156
+ best_prompt_idx = dataframe[best_prompt_column].idxmax()
157
+ best_prompt_model_raw = dataframe.loc[best_prompt_idx, 'Model']
158
+ if isinstance(best_prompt_model_raw, str) and '<' in best_prompt_model_raw:
159
+ match = re.search(r'>([^<]+)<', best_prompt_model_raw)
160
+ best_prompt_model = match.group(1) if match else best_prompt_model_raw
161
+ else:
162
+ best_prompt_model = str(best_prompt_model_raw)
163
+ best_prompt_accuracy = dataframe.loc[best_prompt_idx, best_prompt_column]
164
+ else:
165
+ best_prompt_model = "n/a"
166
+ best_prompt_accuracy = float('nan')
167
+
168
+ table_data['Task'].append(task)
169
+ table_data['Best Overall Model'].append(model_name)
170
+ table_data['CPS'].append(f"{comb_perf_value:.2f}")
171
+ table_data['Best Prompt Model'].append(best_prompt_model)
172
+ table_data['Acc.'].append(f"{best_prompt_accuracy:.2f}" if isinstance(best_prompt_accuracy, (int, float)) else "n/a")
173
+
174
+ fig = go.Figure(data=[go.Table(
175
+ columnwidth=[60, 220, 60, 220, 60],
176
+ header=dict(
177
+ values=[f'<b>{col}</b>' for col in table_data.keys()],
178
+ fill_color=['#2171b5', '#2171b5', '#2171b5', '#4292c6', '#4292c6'],
179
+ font=dict(color='white', size=12, family='Arial'),
180
+ align='center', height=30
181
+ ),
182
+ cells=dict(
183
+ values=list(table_data.values()),
184
+ fill_color=[['#f0f0f0' if i % 2 == 0 else 'white' for i in range(len(table_data['Task']))]],
185
+ font=dict(color='#2c3e50', size=11, family='Arial'),
186
+ align=['center', 'left', 'center', 'left', 'center'],
187
+ height=30
188
+ )
189
+ )])
190
+ fig.update_layout(
191
+ title={'text': "Top Model per Task: CPS & Best Prompt (NER/REL)",
192
+ 'font': {'family': 'Arial', 'size': 14, 'color': '#2c3e50'}},
193
+ font=dict(family="Arial", size=11),
194
+ height=420, margin=dict(l=20, r=20, t=50, b=80)
195
+ )
196
+ fig.add_annotation(
197
+ text=("Best Overall Model uses the task's primary metric (CPS). "
198
+ "Best Prompt Model is the one whose own best prompt yields the highest score."),
199
+ xref="paper", yref="paper", x=0.5, y=-0.20, showarrow=False,
200
+ font=dict(size=11, color="gray", family="Arial"), align="center", xanchor="center"
201
+ )
202
+ return fig
203
+
204
+ def create_prompt_heatmap(dataframe, lang: str | None = None, shot: str | None = None):
205
+ """
206
+ Heatmap of share (%) of models whose BEST prompt is each pid, for NER/REL with prompts p1..p3.
207
+ Optional filters:
208
+ - lang: None or one of EN/IT/SL/SK/GR/PL (None means All)
209
+ - shot: None or "0"/"10" (None means All) mapped to IS_FS False/True
210
+ """
211
+ tasks = ["NER", "REL"]
212
+
213
+ df = dataframe.copy()
214
+ # Language filter
215
+ if lang and lang != "All" and "LANG" in df.columns:
216
+ df = df[df["LANG"] == lang]
217
+ # Shot filter -> IS_FS (10-shot=True, 0-shot=False)
218
+ if shot and shot != "All" and "IS_FS" in df.columns:
219
+ df = df[df["IS_FS"] == (shot == "10")]
220
+
221
+ # Collect prompt ids present, normalize labels to p1..p3
222
+ def label_for(pid):
223
+ if isinstance(pid, str): return pid
224
+ try: return f"p{int(pid)}"
225
+ except Exception: return str(pid)
226
+
227
+ all_ids = set()
228
+ for task in tasks:
229
+ col = f"{task} Best Prompt Id"
230
+ if col in df.columns:
231
+ all_ids.update(df[col].dropna().unique())
232
+ prompt_ids_raw = sorted(list(all_ids), key=lambda x: int(re.sub(r'[^0-9]', '', str(x)) or 0))
233
+ prompt_ids_raw = [pid for pid in prompt_ids_raw if label_for(pid) in {"p1", "p2", "p3"}] or [1, 2, 3]
234
+ y_tick_labels = [label_for(pid) for pid in prompt_ids_raw]
235
+
236
+ matrix, hovers = [], []
237
+ for pid in prompt_ids_raw:
238
+ row, hover_row = [], []
239
+ for task in tasks:
240
+ col = f"{task} Best Prompt Id"
241
+ if col in df.columns and len(df[col].dropna()) > 0:
242
+ series = df[col].dropna()
243
+
244
+ def same_pid(v):
245
+ a = re.sub(r'[^0-9]', '', str(v))
246
+ b = re.sub(r'[^0-9]', '', str(pid))
247
+ return a == b and a != ""
248
+
249
+ total = len(series)
250
+ count = sum(same_pid(v) for v in series)
251
+ pct = (count / total * 100) if total > 0 else 0
252
+ row.append(pct)
253
+ hover_row.append(f"<b>{task} β€” {label_for(pid)}</b><br>Models: {count}/{total}<br>Percentage: {pct:.1f}%")
254
+ else:
255
+ row.append(0); hover_row.append(f"<b>{task} β€” {label_for(pid)}</b><br>No data")
256
+ matrix.append(row); hovers.append(hover_row)
257
+
258
+ fig = go.Figure(data=go.Heatmap(
259
+ z=matrix, x=tasks, y=y_tick_labels,
260
+ colorscale=[[0,'#f7fbff'],[0.2,'#deebf7'],[0.4,'#9ecae1'],[0.6,'#4292c6'],[0.8,'#2171b5'],[1,'#08519c']],
261
+ text=[[f"{val:.0f}%" if val is not None else "" for val in row] for row in matrix],
262
+ texttemplate="%{text}", textfont={"size": 11, "family": "Arial"},
263
+ hovertemplate='%{customdata}<extra></extra>', customdata=hovers,
264
+ colorbar=dict(title="% Models", ticksuffix="%"),
265
+ zmin=0, zmax=100
266
+ ))
267
+
268
+ title_parts = []
269
+ title_parts.append(lang if (lang and lang != "All") else "All languages")
270
+ title_parts.append(f"{shot}-shot" if (shot and shot != "All") else "All shots")
271
+ fig.update_layout(
272
+ title={'text': f"Most Effective Prompts (NER/REL) β€” {', '.join(title_parts)}",
273
+ 'font': {'family': 'Arial', 'size': 14, 'color': '#2c3e50'}},
274
+ xaxis_title="Task", yaxis_title="Prompt",
275
+ font=dict(family="Arial", size=11), margin=dict(b=100),
276
+ template="plotly_white", dragmode=False, height=420
277
+ )
278
+ fig.update_xaxes(fixedrange=True); fig.update_yaxes(fixedrange=True)
279
+ return fig
280
+
281
+
282
+ # === NEW: Prompt heatmap (only NER, REL; 3 prompts p1, p2, p3) ===
283
+ def create_prompt_heatmap_without_lang(dataframe):
284
+ """
285
+ Heatmap of the share of models (in %) whose BEST prompt for the task is each prompt id,
286
+ for tasks NER and REL, with exactly 3 prompts (p1, p2, p3). It supports columns storing
287
+ ids as integers (1/2/3) or strings ('p1'/'p2'/'p3').
288
+ """
289
+ tasks = ["NER", "REL"]
290
+
291
+ # Collect unique prompt ids as they appear (int or 'pX'); restrict to 3 prompts
292
+ all_ids = set()
293
+ for task in tasks:
294
+ col = f"{task} Best Prompt Id"
295
+ if col in dataframe.columns:
296
+ all_ids.update(dataframe[col].dropna().unique())
297
+
298
+ # Normalize to display labels and preserve the original values as keys
299
+ def label_for(pid):
300
+ if isinstance(pid, str):
301
+ return pid # e.g., 'p1'
302
+ try:
303
+ return f"p{int(pid)}"
304
+ except Exception:
305
+ return str(pid)
306
+
307
+ prompt_ids_raw = sorted(list(all_ids), key=lambda x: int(re.sub(r'[^0-9]', '', str(x)) or 0))
308
+ # Optional: hard-limit to p1/p2/p3 if extra noise exists
309
+ prompt_ids_raw = [pid for pid in prompt_ids_raw if label_for(pid) in {"p1", "p2", "p3"}]
310
+
311
+ if not prompt_ids_raw:
312
+ # Fallback to p1..p3
313
+ prompt_ids_raw = [1, 2, 3]
314
+
315
+ y_tick_labels = [label_for(pid) for pid in prompt_ids_raw]
316
+
317
+ matrix, hovers = [], []
318
+ for pid in prompt_ids_raw:
319
+ row, hover_row = [], []
320
+ for task in tasks:
321
+ col = f"{task} Best Prompt Id"
322
+ if col in dataframe.columns:
323
+ series = dataframe[col].dropna()
324
+ # match values regardless of 'p1' vs 1 vs '1'
325
+ def same_pid(v):
326
+ a = re.sub(r'[^0-9]', '', str(v))
327
+ b = re.sub(r'[^0-9]', '', str(pid))
328
+ return a == b and a != ""
329
+ total = len(series)
330
+ count = sum(same_pid(v) for v in series)
331
+ pct = (count / total * 100) if total > 0 else 0
332
+ row.append(pct)
333
+ hover_row.append(
334
+ f"<b>{task} β€” {label_for(pid)}</b><br>Models: {count}/{total}<br>Percentage: {pct:.1f}%"
335
+ )
336
+ else:
337
+ row.append(0); hover_row.append(f"<b>{task} β€” {label_for(pid)}</b><br>No data")
338
+ matrix.append(row)
339
+ hovers.append(hover_row)
340
+
341
+ fig = go.Figure(data=go.Heatmap(
342
+ z=matrix, x=tasks, y=y_tick_labels,
343
+ colorscale=[[0,'#f7fbff'],[0.2,'#deebf7'],[0.4,'#9ecae1'],[0.6,'#4292c6'],[0.8,'#2171b5'],[1,'#08519c']],
344
+ text=[[f"{val:.0f}%" if val is not None else "" for val in row] for row in matrix],
345
+ texttemplate="%{text}",
346
+ textfont={"size": 11, "family": "Arial"},
347
+ hovertemplate='%{customdata}<extra></extra>',
348
+ customdata=hovers,
349
+ colorbar=dict(title="% Models", ticksuffix="%"),
350
+ zmin=0, zmax=100
351
+ ))
352
+ fig.update_layout(
353
+ title={'text': "Most Effective Prompts Across Models (NER/REL)",
354
+ 'font': {'family': 'Arial', 'size': 14, 'color': '#2c3e50'}},
355
+ xaxis_title="Task", yaxis_title="Prompt",
356
+ font=dict(family="Arial", size=11),
357
+ margin=dict(b=120), template="plotly_white", dragmode=False, height=420
358
+ )
359
+
360
+ # PSI (optional info line)
361
+ psi, mean_cv, _ = calculate_prompt_sensitivity(
362
+ dataframe, tasks, prompt_ids_raw
363
+ )
364
+ fig.add_annotation(
365
+ text=f"Prompt Sensitivity (mean CV): {mean_cv:.2f}",
366
+ xref="paper", yref="paper", x=0.3, y=1.12, showarrow=False,
367
+ font=dict(size=11, color="#2c3e50", family="Arial")
368
+ )
369
+
370
+ fig.update_xaxes(fixedrange=True); fig.update_yaxes(fixedrange=True)
371
+ return fig
372
+
373
+
374
+
375
+
376
+
377
+
378
+
379
  def mean_of_max_per_field(df):
380
  """
381
  Calcola il massimo per ciascun campo e poi la media dei massimi.
 
516
  ))
517
 
518
  # baseline
519
+ #if task in baselines and baselines[task] is not None:
520
+ #fig.add_shape(
521
+ # type="line",
522
+ # x0=i - 0.3, x1=i + 0.3,
523
+ # y0=baselines[task], y1=baselines[task],
524
+ # line=dict(color="black", width=2, dash="dot"), # piΓΉ visibile
525
+ # xref="x", yref="y"
526
+ #)
527
+ #'''
528
+ #fig.add_annotation(
529
+ #x=i, y=baselines[task],
530
+ #text=f"{baselines[task]}%",
531
+ #showarrow=False,
532
+ #yshift=10,
533
+ #font=dict(size=10, color="black")
534
+ #)
535
+ #'''
536
 
537
  # reference GPT-4o
538
+ # if task in references and references[task] is not None:
539
+ # fig.add_shape(
540
+ # type="line",
541
+ # x0=i - 0.3, x1=i + 0.3,
542
+ # y0=references[task], y1=references[task],
543
+ # line=dict(color="red", width=2, dash="dashdot"),
544
+ # xref="x", yref="y"
545
+ # )
546
 
547
  fig.update_layout(
548
  title="Distribution of Model Accuracy by Task",
 
626
  y=avg_y,
627
  name="Avg. Accuracy",
628
  marker_color="#1f77b4",
 
 
629
  ))
630
 
631
  # Barre Best Prompt (rosso)
 
634
  y=best_y,
635
  name="Best Prompt",
636
  marker_color="#d62728",
 
 
637
  ))
638
 
639
  # Testo sopra barre Best Prompt con ID
 
701
  x=x_true,
702
  y=y_true,
703
  mode='markers',
704
+ name='10-Shot',
705
  marker=dict(
706
  color='blue',
707
  size=scale_sizes(x_true)
 
772
  # Caption
773
  fig.add_annotation(
774
  text="Accuracy generally rises with #Params, but smaller models <br>"
775
+ "with 10-shot can outperform larger zero-shot models.",
776
  xref="paper", yref="paper",
777
  x=0.5, y=-0.3, # πŸ‘ˆ centrata
778
  showarrow=False,
 
877
  return Leaderboard(
878
  value=sorted_dataframe,
879
  datatype=[c.type for c in field_list],
 
 
 
 
 
880
  search_columns=[AutoEvalColumn.model.name, AutoEvalColumn.license.name],
881
  hide_columns=hidden_columns or [c.name for c in field_list if c.hidden],
882
  filter_columns=[
883
+ ColumnFilter(AutoEvalColumn.fewshot_symbol.name, type="checkboxgroup", label="N-Shot Learning (FS): "),
884
+ ColumnFilter(AutoEvalColumn.LANG.name, type="checkboxgroup", label="Languges: "),
 
 
 
885
  ColumnFilter(AutoEvalColumn.params.name, type="slider", min=0, max = 100, default = [0,100], label="Select the number of parameters (B)"),
886
  ],
 
 
 
 
887
  bool_checkboxgroup_label="Evaluation Mode",
888
  interactive=False,
889
  )
 
962
  search_columns=[AutoEvalColumn.model.name, AutoEvalColumn.license.name],
963
  hide_columns=hidden_columns or [c.name for c in field_list if c.hidden],
964
  filter_columns=[
965
+ ColumnFilter(AutoEvalColumn.fewshot_symbol.name, type="checkboxgroup", label="N-Shot Learning (FS): "),
966
+ ColumnFilter(AutoEvalColumn.LANG.name, type="checkboxgroup", label="Languges: "),
967
 
968
  ColumnFilter(AutoEvalColumn.params.name, type="slider", min=0, max=100, default=[0, 100],
969
  label="Select the number of parameters (B)"),
 
1029
  <h1 style="
1030
  margin: 0 auto;
1031
  font-weight: 900;
1032
+ font-size: 5.5em;
1033
  letter-spacing: 2px;
1034
  text-transform: uppercase;
1035
+ color: red;
1036
  background: linear-gradient(90deg, #1f77b4, #00c6ff);
1037
  -webkit-background-clip: text;
1038
  -webkit-text-fill-color: transparent;
1039
+ text-shadow: 2px 2px 8px rgba(0.2,0,0,0);
1040
  ">
1041
+ ECREAM-LLM Leaderboard
1042
  </h1>
 
 
 
 
 
 
 
 
 
1043
  </div>
1044
  """
1045
  )
 
1049
  with gr.Row():
1050
  gr.Plot(value=line_chart(LEADERBOARD_DF), elem_id="line-chart")
1051
  gr.Plot(value=boxplot_per_task(LEADERBOARD_DF, BASELINES, REFERENCES), elem_id="boxplot-task")
 
1052
 
1053
+ # === NEW: second row with the 2 extra plots (NER/REL + p1..p3) ===
1054
+ #with gr.Row():
1055
+ #gr.Plot(value=create_prompt_heatmap(LEADERBOARD_DF), elem_id="prompt-heatmap")
1056
+ #gr.Plot(value=create_best_model_comparison_table(LEADERBOARD_DF), elem_id="best-model-table")
1057
+ # === NEW: gray background wrapper for combos ===
1058
+ with gr.Row(elem_id="filters-wrap"):
1059
+ lang_dd = gr.Dropdown(
1060
+ choices=["All", "EN", "IT", "SL", "SK", "GR", "PL"],
1061
+ value="All", label="Language: ", scale=1
1062
+ )
1063
+ shot_dd = gr.Dropdown(
1064
+ choices=["All", "0", "10"],
1065
+ value="All", label="N-Shot: ", scale=1
1066
+ )
1067
+
1068
+ with gr.Row():
1069
+ heatmap_plot = gr.Plot(value=create_prompt_heatmap(LEADERBOARD_DF, None, None), elem_id="prompt-heatmap")
1070
+ table_plot = gr.Plot(value=create_best_model_comparison_table(LEADERBOARD_DF, None, None), elem_id="best-model-table")
1071
+
1072
+ def _update_both(lang, shot):
1073
+ return (
1074
+ create_prompt_heatmap(LEADERBOARD_DF, None if lang == "All" else lang, None if shot == "All" else shot),
1075
+ create_best_model_comparison_table(LEADERBOARD_DF, None if lang == "All" else lang, None if shot == "All" else shot)
1076
+ )
1077
+
1078
+ lang_dd.change(_update_both, inputs=[lang_dd, shot_dd], outputs=[heatmap_plot, table_plot])
1079
+ shot_dd.change(_update_both, inputs=[lang_dd, shot_dd], outputs=[heatmap_plot, table_plot])
1080
+
1081
+
1082
+
1083
  with gr.Tabs(elem_classes="tab-buttons") as tabs:
1084
 
1085
  # Main leaderboard tab
 
1091
  hidden_columns=[col for col in LEADERBOARD_DF.columns if col not in ['Rank', 'Size', 'LANG', 'FS', 'Model', "Avg. Comb. Perf. ⬆️", "TE", "SA", "HS", "AT", "WIC", "FAQ", "LS", "SU", "NER", "REL"]]
1092
  )
1093
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1094
 
1095
  # About tab
1096
  with gr.TabItem("πŸ“ About"):
1097
  gr.Markdown(LLM_BENCHMARKS_TEXT, elem_classes="markdown-text")
1098
 
 
 
 
 
 
1099
  # Task-specific leaderboards
1100
  for task, metadata in TASK_METADATA_MULTIPLECHOICE.items():
1101
 
 
1118
  for task, metadata in TASK_METADATA_GENERATIVE.items():
1119
  with gr.TabItem(f"{metadata['icon']}{task}"):
1120
  task_description = TASK_DESCRIPTIONS.get(task, "Description not available.")
1121
+ gr.Markdown(task_description, elem_classes="markdown-text1")
1122
+ #print (LEADERBOARD_DF)
1123
  leaderboard = update_task_leaderboard(
1124
  LEADERBOARD_DF.rename(columns={f"{task} Prompt Average": "Prompt Average",
1125
  f"{task} Prompt Std": "Prompt Std",
 
1140
  with gr.Accordion("πŸ“™ Credits", open=False):
1141
  gr.Markdown(
1142
  """
1143
+ ***This project has been funded by the European Union under:
 
 
 
 
1144
 
1145
+ Horizon Europe eCREAM Project (Grant Agreement No.101057726)
1146
  """
1147
  )
1148
 
app.py CHANGED
@@ -18,6 +18,364 @@ import plotly.graph_objects as go
18
  import numpy as np
19
 
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  def mean_of_max_per_field(df):
22
  """
23
  Calcola il massimo per ciascun campo e poi la media dei massimi.
@@ -158,33 +516,33 @@ def boxplot_per_task(dataframe=None, baselines=None, references=None):
158
  ))
159
 
160
  # baseline
161
- if task in baselines and baselines[task] is not None:
162
- fig.add_shape(
163
- type="line",
164
- x0=i - 0.3, x1=i + 0.3,
165
- y0=baselines[task], y1=baselines[task],
166
- line=dict(color="black", width=2, dash="dot"), # piΓΉ visibile
167
- xref="x", yref="y"
168
- )
169
- '''
170
- fig.add_annotation(
171
- x=i, y=baselines[task],
172
- text=f"{baselines[task]}%",
173
- showarrow=False,
174
- yshift=10,
175
- font=dict(size=10, color="black")
176
- )
177
- '''
178
 
179
  # reference GPT-4o
180
- if task in references and references[task] is not None:
181
- fig.add_shape(
182
- type="line",
183
- x0=i - 0.3, x1=i + 0.3,
184
- y0=references[task], y1=references[task],
185
- line=dict(color="red", width=2, dash="dashdot"),
186
- xref="x", yref="y"
187
- )
188
 
189
  fig.update_layout(
190
  title="Distribution of Model Accuracy by Task",
@@ -268,8 +626,6 @@ def boxplot_prompts_per_task(dataframe, tasks=None):
268
  y=avg_y,
269
  name="Avg. Accuracy",
270
  marker_color="#1f77b4",
271
- #hovertemplate="%{y:.2f}%<extra></extra>"
272
- #hovertemplate="<b>" + task + "</b><br>Accuracy: %{y:.2f}%<extra></extra>",
273
  ))
274
 
275
  # Barre Best Prompt (rosso)
@@ -278,8 +634,6 @@ def boxplot_prompts_per_task(dataframe, tasks=None):
278
  y=best_y,
279
  name="Best Prompt",
280
  marker_color="#d62728",
281
- #hovertemplate="%{y:.2f}%<extra></extra>"
282
- #hovertemplate = "<b>" + task + "</b><br>Accuracy: %{y:.2f}%<extra></extra>",
283
  ))
284
 
285
  # Testo sopra barre Best Prompt con ID
@@ -523,25 +877,13 @@ def init_leaderboard(dataframe, default_selection=None, hidden_columns=None):
523
  return Leaderboard(
524
  value=sorted_dataframe,
525
  datatype=[c.type for c in field_list],
526
- #select_columns=SelectColumns(
527
- # default_selection=default_selection or [c.name for c in field_list if c.displayed_by_default],
528
- # cant_deselect=[c.name for c in field_list if c.never_hidden],
529
- # label="Select Columns to Display:",
530
- #),
531
  search_columns=[AutoEvalColumn.model.name, AutoEvalColumn.license.name],
532
  hide_columns=hidden_columns or [c.name for c in field_list if c.hidden],
533
  filter_columns=[
534
- ColumnFilter(AutoEvalColumn.fewshot_symbol.name, type="checkboxgroup", label="N-Shot Learning (FS)"),
535
- #ColumnFilter(AutoEvalColumn.fewshot_symbol.name, type="checkboxgroup", label="N-Few-Shot Learning (FS)",
536
- # default=[["0️⃣", "0️⃣"]]),
537
- ColumnFilter(AutoEvalColumn.LANG.name, type="checkboxgroup", label="Languges "),
538
-
539
  ColumnFilter(AutoEvalColumn.params.name, type="slider", min=0, max = 100, default = [0,100], label="Select the number of parameters (B)"),
540
  ],
541
- #filter_columns=[
542
- # ColumnFilter("IS_FS", type="checkbox", default=False, label="5-Few-Shot")
543
- # #ColumnFilter("FS", type="dropdown", label="5-Few-Shot")
544
- #],
545
  bool_checkboxgroup_label="Evaluation Mode",
546
  interactive=False,
547
  )
@@ -620,8 +962,8 @@ def update_task_leaderboard(dataframe, default_selection=None, hidden_columns=No
620
  search_columns=[AutoEvalColumn.model.name, AutoEvalColumn.license.name],
621
  hide_columns=hidden_columns or [c.name for c in field_list if c.hidden],
622
  filter_columns=[
623
- ColumnFilter(AutoEvalColumn.fewshot_symbol.name, type="checkboxgroup", label="N-Shot Learning (FS)"),
624
- ColumnFilter(AutoEvalColumn.LANG.name, type="checkboxgroup", label="Languges "),
625
 
626
  ColumnFilter(AutoEvalColumn.params.name, type="slider", min=0, max=100, default=[0, 100],
627
  label="Select the number of parameters (B)"),
@@ -707,8 +1049,37 @@ with demo:
707
  with gr.Row():
708
  gr.Plot(value=line_chart(LEADERBOARD_DF), elem_id="line-chart")
709
  gr.Plot(value=boxplot_per_task(LEADERBOARD_DF, BASELINES, REFERENCES), elem_id="boxplot-task")
710
- #gr.Plot(value=boxplot_prompts_per_task(LEADERBOARD_DF), elem_id="boxplot-prompt-task")
711
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
712
  with gr.Tabs(elem_classes="tab-buttons") as tabs:
713
 
714
  # Main leaderboard tab
@@ -720,41 +1091,11 @@ with demo:
720
  hidden_columns=[col for col in LEADERBOARD_DF.columns if col not in ['Rank', 'Size', 'LANG', 'FS', 'Model', "Avg. Comb. Perf. ⬆️", "TE", "SA", "HS", "AT", "WIC", "FAQ", "LS", "SU", "NER", "REL"]]
721
  )
722
 
723
- # gr.HTML(
724
- # f"""
725
- # <div style="
726
- # border: 2px solid #1f77b4;
727
- # border-radius: 10px;
728
- # padding: 10px;
729
- # background-color: #f0f8ff;
730
- # font-weight: bold;
731
- # font-size: 14px;
732
- # display: inline-block;
733
- # ">
734
- # Theoretical performance of a model that scores the highest on every individual task: <span style="color:#d62728; font-size:18px;">{theoretical_max_combined_perf:.2f}</span>
735
- # </div>
736
- # $ """
737
- # )
738
-
739
- '''
740
- with gr.TabItem("πŸ“ˆ Charts"):
741
- #gr.Plot(value=line_chart(LEADERBOARD_DF), label="Andamento di esempio")
742
- #gr.Plot(value=line_chart_interactive_test(), label="Andamento interattivo")
743
- gr.Plot(value=line_chart(LEADERBOARD_DF))
744
- gr.Plot(value=boxplot_per_task(LEADERBOARD_DF, BASELINES))
745
- gr.Plot(value=boxplot_prompts_per_task(LEADERBOARD_DF))
746
- gr.Plot(value=barplot_mean_few_minus_zero_shot(LEADERBOARD_DF))
747
- '''
748
 
749
  # About tab
750
  with gr.TabItem("πŸ“ About"):
751
  gr.Markdown(LLM_BENCHMARKS_TEXT, elem_classes="markdown-text")
752
 
753
- # About tab
754
- #with gr.TabItem("β•‘", interactive=False):
755
- # gr.Markdown("", elem_classes="markdown-text")
756
-
757
-
758
  # Task-specific leaderboards
759
  for task, metadata in TASK_METADATA_MULTIPLECHOICE.items():
760
 
 
18
  import numpy as np
19
 
20
 
21
+
22
+
23
+ # === NEW: helper for prompt sensitivity (simple: only NER/REL and 3 prompts) ===
24
+ def calculate_prompt_sensitivity(dataframe, tasks, prompt_ids):
25
+ """
26
+ Computes a simple Prompt Sensitivity Index (PSI) over the tasks (NER, REL)
27
+ using the distribution of 'Best Prompt Id' across the provided prompt_ids.
28
+ """
29
+ cv_per_task = []
30
+ for task in tasks:
31
+ prompt_col = f"{task} Best Prompt Id"
32
+ task_accuracies = []
33
+ for pid in prompt_ids:
34
+ total = len(dataframe[prompt_col].dropna()) if prompt_col in dataframe.columns else 0
35
+ count = (dataframe[prompt_col] == pid).sum() if prompt_col in dataframe.columns else 0
36
+ acc = (count / total * 100) if total > 0 else 0
37
+ task_accuracies.append(acc)
38
+ if task_accuracies:
39
+ mean_acc = np.mean(task_accuracies)
40
+ std_acc = np.std(task_accuracies)
41
+ cv_per_task.append((std_acc / mean_acc) if mean_acc > 0 else 0)
42
+ else:
43
+ cv_per_task.append(0)
44
+ mean_cv = np.mean(cv_per_task) if cv_per_task else 0
45
+ psi = 1.0 if mean_cv >= 0.5 else (mean_cv / 0.5)
46
+ return psi, mean_cv, cv_per_task
47
+
48
+ def create_best_model_comparison_table(dataframe, lang: str | None = None, shot: str | None = None):
49
+ """
50
+ Table with best overall model per task (NER, REL) and the model with the best prompt score.
51
+ Applies optional filters:
52
+ - lang in {EN, IT, SL, SK, GR, PL} or None/"All"
53
+ - shot in {"0","10"} or None/"All" (mapped to IS_FS False/True)
54
+ """
55
+ tasks = ["NER", "REL"]
56
+ df = dataframe.copy()
57
+
58
+ if lang and lang != "All" and "LANG" in df.columns:
59
+ df = df[df["LANG"] == lang]
60
+ if shot and shot != "All" and "IS_FS" in df.columns:
61
+ df = df[df["IS_FS"] == (shot == "10")]
62
+
63
+ table_data = {'Task': [], 'Best Overall Model': [], 'CPS': [], 'Best Prompt Model': [], 'Acc.': []}
64
+
65
+ for task in tasks:
66
+ if task not in df.columns or df.empty:
67
+ continue
68
+ # Best overall on task
69
+ max_idx = df[task].idxmax()
70
+ model_raw = df.loc[max_idx, 'Model']
71
+ if isinstance(model_raw, str) and '<' in model_raw:
72
+ match = re.search(r'>([^<]+)<', model_raw)
73
+ model_name = match.group(1) if match else model_raw
74
+ else:
75
+ model_name = str(model_raw)
76
+ comb_perf_value = df.loc[max_idx, task]
77
+
78
+ # Best prompt row for task
79
+ best_prompt_column = f"{task} Best Prompt"
80
+ if best_prompt_column in df.columns and df[best_prompt_column].notna().any():
81
+ best_prompt_idx = df[best_prompt_column].idxmax()
82
+ best_prompt_model_raw = df.loc[best_prompt_idx, 'Model']
83
+ if isinstance(best_prompt_model_raw, str) and '<' in best_prompt_model_raw:
84
+ match = re.search(r'>([^<]+)<', best_prompt_model_raw)
85
+ best_prompt_model = match.group(1) if match else best_prompt_model_raw
86
+ else:
87
+ best_prompt_model = str(best_prompt_model_raw)
88
+ best_prompt_accuracy = df.loc[best_prompt_idx, best_prompt_column]
89
+ else:
90
+ best_prompt_model = "n/a"
91
+ best_prompt_accuracy = float('nan')
92
+
93
+ table_data['Task'].append(task)
94
+ table_data['Best Overall Model'].append(model_name)
95
+ table_data['CPS'].append(f"{comb_perf_value:.2f}")
96
+ table_data['Best Prompt Model'].append(best_prompt_model)
97
+ table_data['Acc.'].append(f"{best_prompt_accuracy:.2f}" if isinstance(best_prompt_accuracy, (int, float)) else "n/a")
98
+
99
+ fig = go.Figure(data=[go.Table(
100
+ columnwidth=[60, 220, 60, 220, 60],
101
+ header=dict(
102
+ values=[f'<b>{col}</b>' for col in table_data.keys()],
103
+ fill_color=['#2171b5', '#2171b5', '#2171b5', '#4292c6', '#4292c6'],
104
+ font=dict(color='white', size=12, family='Arial'),
105
+ align='center', height=30
106
+ ),
107
+ cells=dict(
108
+ values=list(table_data.values()),
109
+ fill_color=[['#f0f0f0' if i % 2 == 0 else 'white' for i in range(len(table_data['Task']))]],
110
+ font=dict(color='#2c3e50', size=11, family='Arial'),
111
+ align=['center', 'left', 'center', 'left', 'center'],
112
+ height=30
113
+ )
114
+ )])
115
+
116
+ subtitle = []
117
+ subtitle.append(lang if (lang and lang != "All") else "All languages")
118
+ subtitle.append(f"{shot}-shot" if (shot and shot != "All") else "All shots")
119
+
120
+ fig.update_layout(
121
+ title={'text': f"Top Model per Task: CPS & Best Prompt (NER/REL) β€” {', '.join(subtitle)}",
122
+ 'font': {'family': 'Arial', 'size': 14, 'color': '#2c3e50'}},
123
+ font=dict(family="Arial", size=11),
124
+ height=420, margin=dict(l=20, r=20, t=50, b=80)
125
+ )
126
+ return fig
127
+
128
+
129
+
130
+ # === NEW: Best-model comparison table (only NER, REL) ===
131
+ def create_best_model_comparison_table_without_lang(dataframe):
132
+ """
133
+ Table with the best overall model per task (NER, REL) and the model that
134
+ achieves the best score with its own best prompt.
135
+ """
136
+ tasks = ["NER", "REL"]
137
+ table_data = {'Task': [], 'Best Overall Model': [], 'CPS': [], 'Best Prompt Model': [], 'Acc.': []}
138
+
139
+ for task in tasks:
140
+ if task not in dataframe.columns:
141
+ continue
142
+
143
+ # Best overall on the task's combined performance
144
+ max_idx = dataframe[task].idxmax()
145
+ model_raw = dataframe.loc[max_idx, 'Model']
146
+ if isinstance(model_raw, str) and '<' in model_raw:
147
+ match = re.search(r'>([^<]+)<', model_raw)
148
+ model_name = match.group(1) if match else model_raw
149
+ else:
150
+ model_name = str(model_raw)
151
+ comb_perf_value = dataframe.loc[max_idx, task]
152
+
153
+ # Model with the best prompt for this task
154
+ best_prompt_column = f"{task} Best Prompt"
155
+ if best_prompt_column in dataframe.columns:
156
+ best_prompt_idx = dataframe[best_prompt_column].idxmax()
157
+ best_prompt_model_raw = dataframe.loc[best_prompt_idx, 'Model']
158
+ if isinstance(best_prompt_model_raw, str) and '<' in best_prompt_model_raw:
159
+ match = re.search(r'>([^<]+)<', best_prompt_model_raw)
160
+ best_prompt_model = match.group(1) if match else best_prompt_model_raw
161
+ else:
162
+ best_prompt_model = str(best_prompt_model_raw)
163
+ best_prompt_accuracy = dataframe.loc[best_prompt_idx, best_prompt_column]
164
+ else:
165
+ best_prompt_model = "n/a"
166
+ best_prompt_accuracy = float('nan')
167
+
168
+ table_data['Task'].append(task)
169
+ table_data['Best Overall Model'].append(model_name)
170
+ table_data['CPS'].append(f"{comb_perf_value:.2f}")
171
+ table_data['Best Prompt Model'].append(best_prompt_model)
172
+ table_data['Acc.'].append(f"{best_prompt_accuracy:.2f}" if isinstance(best_prompt_accuracy, (int, float)) else "n/a")
173
+
174
+ fig = go.Figure(data=[go.Table(
175
+ columnwidth=[60, 220, 60, 220, 60],
176
+ header=dict(
177
+ values=[f'<b>{col}</b>' for col in table_data.keys()],
178
+ fill_color=['#2171b5', '#2171b5', '#2171b5', '#4292c6', '#4292c6'],
179
+ font=dict(color='white', size=12, family='Arial'),
180
+ align='center', height=30
181
+ ),
182
+ cells=dict(
183
+ values=list(table_data.values()),
184
+ fill_color=[['#f0f0f0' if i % 2 == 0 else 'white' for i in range(len(table_data['Task']))]],
185
+ font=dict(color='#2c3e50', size=11, family='Arial'),
186
+ align=['center', 'left', 'center', 'left', 'center'],
187
+ height=30
188
+ )
189
+ )])
190
+ fig.update_layout(
191
+ title={'text': "Top Model per Task: CPS & Best Prompt (NER/REL)",
192
+ 'font': {'family': 'Arial', 'size': 14, 'color': '#2c3e50'}},
193
+ font=dict(family="Arial", size=11),
194
+ height=420, margin=dict(l=20, r=20, t=50, b=80)
195
+ )
196
+ fig.add_annotation(
197
+ text=("Best Overall Model uses the task's primary metric (CPS). "
198
+ "Best Prompt Model is the one whose own best prompt yields the highest score."),
199
+ xref="paper", yref="paper", x=0.5, y=-0.20, showarrow=False,
200
+ font=dict(size=11, color="gray", family="Arial"), align="center", xanchor="center"
201
+ )
202
+ return fig
203
+
204
+ def create_prompt_heatmap(dataframe, lang: str | None = None, shot: str | None = None):
205
+ """
206
+ Heatmap of share (%) of models whose BEST prompt is each pid, for NER/REL with prompts p1..p3.
207
+ Optional filters:
208
+ - lang: None or one of EN/IT/SL/SK/GR/PL (None means All)
209
+ - shot: None or "0"/"10" (None means All) mapped to IS_FS False/True
210
+ """
211
+ tasks = ["NER", "REL"]
212
+
213
+ df = dataframe.copy()
214
+ # Language filter
215
+ if lang and lang != "All" and "LANG" in df.columns:
216
+ df = df[df["LANG"] == lang]
217
+ # Shot filter -> IS_FS (10-shot=True, 0-shot=False)
218
+ if shot and shot != "All" and "IS_FS" in df.columns:
219
+ df = df[df["IS_FS"] == (shot == "10")]
220
+
221
+ # Collect prompt ids present, normalize labels to p1..p3
222
+ def label_for(pid):
223
+ if isinstance(pid, str): return pid
224
+ try: return f"p{int(pid)}"
225
+ except Exception: return str(pid)
226
+
227
+ all_ids = set()
228
+ for task in tasks:
229
+ col = f"{task} Best Prompt Id"
230
+ if col in df.columns:
231
+ all_ids.update(df[col].dropna().unique())
232
+ prompt_ids_raw = sorted(list(all_ids), key=lambda x: int(re.sub(r'[^0-9]', '', str(x)) or 0))
233
+ prompt_ids_raw = [pid for pid in prompt_ids_raw if label_for(pid) in {"p1", "p2", "p3"}] or [1, 2, 3]
234
+ y_tick_labels = [label_for(pid) for pid in prompt_ids_raw]
235
+
236
+ matrix, hovers = [], []
237
+ for pid in prompt_ids_raw:
238
+ row, hover_row = [], []
239
+ for task in tasks:
240
+ col = f"{task} Best Prompt Id"
241
+ if col in df.columns and len(df[col].dropna()) > 0:
242
+ series = df[col].dropna()
243
+
244
+ def same_pid(v):
245
+ a = re.sub(r'[^0-9]', '', str(v))
246
+ b = re.sub(r'[^0-9]', '', str(pid))
247
+ return a == b and a != ""
248
+
249
+ total = len(series)
250
+ count = sum(same_pid(v) for v in series)
251
+ pct = (count / total * 100) if total > 0 else 0
252
+ row.append(pct)
253
+ hover_row.append(f"<b>{task} β€” {label_for(pid)}</b><br>Models: {count}/{total}<br>Percentage: {pct:.1f}%")
254
+ else:
255
+ row.append(0); hover_row.append(f"<b>{task} β€” {label_for(pid)}</b><br>No data")
256
+ matrix.append(row); hovers.append(hover_row)
257
+
258
+ fig = go.Figure(data=go.Heatmap(
259
+ z=matrix, x=tasks, y=y_tick_labels,
260
+ colorscale=[[0,'#f7fbff'],[0.2,'#deebf7'],[0.4,'#9ecae1'],[0.6,'#4292c6'],[0.8,'#2171b5'],[1,'#08519c']],
261
+ text=[[f"{val:.0f}%" if val is not None else "" for val in row] for row in matrix],
262
+ texttemplate="%{text}", textfont={"size": 11, "family": "Arial"},
263
+ hovertemplate='%{customdata}<extra></extra>', customdata=hovers,
264
+ colorbar=dict(title="% Models", ticksuffix="%"),
265
+ zmin=0, zmax=100
266
+ ))
267
+
268
+ title_parts = []
269
+ title_parts.append(lang if (lang and lang != "All") else "All languages")
270
+ title_parts.append(f"{shot}-shot" if (shot and shot != "All") else "All shots")
271
+ fig.update_layout(
272
+ title={'text': f"Most Effective Prompts (NER/REL) β€” {', '.join(title_parts)}",
273
+ 'font': {'family': 'Arial', 'size': 14, 'color': '#2c3e50'}},
274
+ xaxis_title="Task", yaxis_title="Prompt",
275
+ font=dict(family="Arial", size=11), margin=dict(b=100),
276
+ template="plotly_white", dragmode=False, height=420
277
+ )
278
+ fig.update_xaxes(fixedrange=True); fig.update_yaxes(fixedrange=True)
279
+ return fig
280
+
281
+
282
+ # === NEW: Prompt heatmap (only NER, REL; 3 prompts p1, p2, p3) ===
283
+ def create_prompt_heatmap_without_lang(dataframe):
284
+ """
285
+ Heatmap of the share of models (in %) whose BEST prompt for the task is each prompt id,
286
+ for tasks NER and REL, with exactly 3 prompts (p1, p2, p3). It supports columns storing
287
+ ids as integers (1/2/3) or strings ('p1'/'p2'/'p3').
288
+ """
289
+ tasks = ["NER", "REL"]
290
+
291
+ # Collect unique prompt ids as they appear (int or 'pX'); restrict to 3 prompts
292
+ all_ids = set()
293
+ for task in tasks:
294
+ col = f"{task} Best Prompt Id"
295
+ if col in dataframe.columns:
296
+ all_ids.update(dataframe[col].dropna().unique())
297
+
298
+ # Normalize to display labels and preserve the original values as keys
299
+ def label_for(pid):
300
+ if isinstance(pid, str):
301
+ return pid # e.g., 'p1'
302
+ try:
303
+ return f"p{int(pid)}"
304
+ except Exception:
305
+ return str(pid)
306
+
307
+ prompt_ids_raw = sorted(list(all_ids), key=lambda x: int(re.sub(r'[^0-9]', '', str(x)) or 0))
308
+ # Optional: hard-limit to p1/p2/p3 if extra noise exists
309
+ prompt_ids_raw = [pid for pid in prompt_ids_raw if label_for(pid) in {"p1", "p2", "p3"}]
310
+
311
+ if not prompt_ids_raw:
312
+ # Fallback to p1..p3
313
+ prompt_ids_raw = [1, 2, 3]
314
+
315
+ y_tick_labels = [label_for(pid) for pid in prompt_ids_raw]
316
+
317
+ matrix, hovers = [], []
318
+ for pid in prompt_ids_raw:
319
+ row, hover_row = [], []
320
+ for task in tasks:
321
+ col = f"{task} Best Prompt Id"
322
+ if col in dataframe.columns:
323
+ series = dataframe[col].dropna()
324
+ # match values regardless of 'p1' vs 1 vs '1'
325
+ def same_pid(v):
326
+ a = re.sub(r'[^0-9]', '', str(v))
327
+ b = re.sub(r'[^0-9]', '', str(pid))
328
+ return a == b and a != ""
329
+ total = len(series)
330
+ count = sum(same_pid(v) for v in series)
331
+ pct = (count / total * 100) if total > 0 else 0
332
+ row.append(pct)
333
+ hover_row.append(
334
+ f"<b>{task} β€” {label_for(pid)}</b><br>Models: {count}/{total}<br>Percentage: {pct:.1f}%"
335
+ )
336
+ else:
337
+ row.append(0); hover_row.append(f"<b>{task} β€” {label_for(pid)}</b><br>No data")
338
+ matrix.append(row)
339
+ hovers.append(hover_row)
340
+
341
+ fig = go.Figure(data=go.Heatmap(
342
+ z=matrix, x=tasks, y=y_tick_labels,
343
+ colorscale=[[0,'#f7fbff'],[0.2,'#deebf7'],[0.4,'#9ecae1'],[0.6,'#4292c6'],[0.8,'#2171b5'],[1,'#08519c']],
344
+ text=[[f"{val:.0f}%" if val is not None else "" for val in row] for row in matrix],
345
+ texttemplate="%{text}",
346
+ textfont={"size": 11, "family": "Arial"},
347
+ hovertemplate='%{customdata}<extra></extra>',
348
+ customdata=hovers,
349
+ colorbar=dict(title="% Models", ticksuffix="%"),
350
+ zmin=0, zmax=100
351
+ ))
352
+ fig.update_layout(
353
+ title={'text': "Most Effective Prompts Across Models (NER/REL)",
354
+ 'font': {'family': 'Arial', 'size': 14, 'color': '#2c3e50'}},
355
+ xaxis_title="Task", yaxis_title="Prompt",
356
+ font=dict(family="Arial", size=11),
357
+ margin=dict(b=120), template="plotly_white", dragmode=False, height=420
358
+ )
359
+
360
+ # PSI (optional info line)
361
+ psi, mean_cv, _ = calculate_prompt_sensitivity(
362
+ dataframe, tasks, prompt_ids_raw
363
+ )
364
+ fig.add_annotation(
365
+ text=f"Prompt Sensitivity (mean CV): {mean_cv:.2f}",
366
+ xref="paper", yref="paper", x=0.3, y=1.12, showarrow=False,
367
+ font=dict(size=11, color="#2c3e50", family="Arial")
368
+ )
369
+
370
+ fig.update_xaxes(fixedrange=True); fig.update_yaxes(fixedrange=True)
371
+ return fig
372
+
373
+
374
+
375
+
376
+
377
+
378
+
379
  def mean_of_max_per_field(df):
380
  """
381
  Calcola il massimo per ciascun campo e poi la media dei massimi.
 
516
  ))
517
 
518
  # baseline
519
+ #if task in baselines and baselines[task] is not None:
520
+ #fig.add_shape(
521
+ # type="line",
522
+ # x0=i - 0.3, x1=i + 0.3,
523
+ # y0=baselines[task], y1=baselines[task],
524
+ # line=dict(color="black", width=2, dash="dot"), # piΓΉ visibile
525
+ # xref="x", yref="y"
526
+ #)
527
+ #'''
528
+ #fig.add_annotation(
529
+ #x=i, y=baselines[task],
530
+ #text=f"{baselines[task]}%",
531
+ #showarrow=False,
532
+ #yshift=10,
533
+ #font=dict(size=10, color="black")
534
+ #)
535
+ #'''
536
 
537
  # reference GPT-4o
538
+ # if task in references and references[task] is not None:
539
+ # fig.add_shape(
540
+ # type="line",
541
+ # x0=i - 0.3, x1=i + 0.3,
542
+ # y0=references[task], y1=references[task],
543
+ # line=dict(color="red", width=2, dash="dashdot"),
544
+ # xref="x", yref="y"
545
+ # )
546
 
547
  fig.update_layout(
548
  title="Distribution of Model Accuracy by Task",
 
626
  y=avg_y,
627
  name="Avg. Accuracy",
628
  marker_color="#1f77b4",
 
 
629
  ))
630
 
631
  # Barre Best Prompt (rosso)
 
634
  y=best_y,
635
  name="Best Prompt",
636
  marker_color="#d62728",
 
 
637
  ))
638
 
639
  # Testo sopra barre Best Prompt con ID
 
877
  return Leaderboard(
878
  value=sorted_dataframe,
879
  datatype=[c.type for c in field_list],
 
 
 
 
 
880
  search_columns=[AutoEvalColumn.model.name, AutoEvalColumn.license.name],
881
  hide_columns=hidden_columns or [c.name for c in field_list if c.hidden],
882
  filter_columns=[
883
+ ColumnFilter(AutoEvalColumn.fewshot_symbol.name, type="checkboxgroup", label="N-Shot Learning (FS): "),
884
+ ColumnFilter(AutoEvalColumn.LANG.name, type="checkboxgroup", label="Languges: "),
 
 
 
885
  ColumnFilter(AutoEvalColumn.params.name, type="slider", min=0, max = 100, default = [0,100], label="Select the number of parameters (B)"),
886
  ],
 
 
 
 
887
  bool_checkboxgroup_label="Evaluation Mode",
888
  interactive=False,
889
  )
 
962
  search_columns=[AutoEvalColumn.model.name, AutoEvalColumn.license.name],
963
  hide_columns=hidden_columns or [c.name for c in field_list if c.hidden],
964
  filter_columns=[
965
+ ColumnFilter(AutoEvalColumn.fewshot_symbol.name, type="checkboxgroup", label="N-Shot Learning (FS): "),
966
+ ColumnFilter(AutoEvalColumn.LANG.name, type="checkboxgroup", label="Languges: "),
967
 
968
  ColumnFilter(AutoEvalColumn.params.name, type="slider", min=0, max=100, default=[0, 100],
969
  label="Select the number of parameters (B)"),
 
1049
  with gr.Row():
1050
  gr.Plot(value=line_chart(LEADERBOARD_DF), elem_id="line-chart")
1051
  gr.Plot(value=boxplot_per_task(LEADERBOARD_DF, BASELINES, REFERENCES), elem_id="boxplot-task")
 
1052
 
1053
+ # === NEW: second row with the 2 extra plots (NER/REL + p1..p3) ===
1054
+ #with gr.Row():
1055
+ #gr.Plot(value=create_prompt_heatmap(LEADERBOARD_DF), elem_id="prompt-heatmap")
1056
+ #gr.Plot(value=create_best_model_comparison_table(LEADERBOARD_DF), elem_id="best-model-table")
1057
+ # === NEW: gray background wrapper for combos ===
1058
+ with gr.Row(elem_id="filters-wrap"):
1059
+ lang_dd = gr.Dropdown(
1060
+ choices=["All", "EN", "IT", "SL", "SK", "GR", "PL"],
1061
+ value="All", label="Language: ", scale=1
1062
+ )
1063
+ shot_dd = gr.Dropdown(
1064
+ choices=["All", "0", "10"],
1065
+ value="All", label="N-Shot: ", scale=1
1066
+ )
1067
+
1068
+ with gr.Row():
1069
+ heatmap_plot = gr.Plot(value=create_prompt_heatmap(LEADERBOARD_DF, None, None), elem_id="prompt-heatmap")
1070
+ table_plot = gr.Plot(value=create_best_model_comparison_table(LEADERBOARD_DF, None, None), elem_id="best-model-table")
1071
+
1072
+ def _update_both(lang, shot):
1073
+ return (
1074
+ create_prompt_heatmap(LEADERBOARD_DF, None if lang == "All" else lang, None if shot == "All" else shot),
1075
+ create_best_model_comparison_table(LEADERBOARD_DF, None if lang == "All" else lang, None if shot == "All" else shot)
1076
+ )
1077
+
1078
+ lang_dd.change(_update_both, inputs=[lang_dd, shot_dd], outputs=[heatmap_plot, table_plot])
1079
+ shot_dd.change(_update_both, inputs=[lang_dd, shot_dd], outputs=[heatmap_plot, table_plot])
1080
+
1081
+
1082
+
1083
  with gr.Tabs(elem_classes="tab-buttons") as tabs:
1084
 
1085
  # Main leaderboard tab
 
1091
  hidden_columns=[col for col in LEADERBOARD_DF.columns if col not in ['Rank', 'Size', 'LANG', 'FS', 'Model', "Avg. Comb. Perf. ⬆️", "TE", "SA", "HS", "AT", "WIC", "FAQ", "LS", "SU", "NER", "REL"]]
1092
  )
1093
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1094
 
1095
  # About tab
1096
  with gr.TabItem("πŸ“ About"):
1097
  gr.Markdown(LLM_BENCHMARKS_TEXT, elem_classes="markdown-text")
1098
 
 
 
 
 
 
1099
  # Task-specific leaderboards
1100
  for task, metadata in TASK_METADATA_MULTIPLECHOICE.items():
1101
 
app_17_10_2025.py ADDED
@@ -0,0 +1,815 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from gradio_leaderboard import Leaderboard, ColumnFilter, SelectColumns
3
+ import pandas as pd
4
+ from apscheduler.schedulers.background import BackgroundScheduler
5
+ from huggingface_hub import snapshot_download
6
+ from src.about import CITATION_BUTTON_LABEL, CITATION_BUTTON_TEXT, EVALUATION_QUEUE_TEXT, INTRODUCTION_TEXT, LLM_BENCHMARKS_TEXT, TITLE
7
+ from src.tasks import TASK_DESCRIPTIONS, MEASURE_DESCRIPTION
8
+ from src.display.css_html_js import custom_css
9
+ from src.display.utils import BENCHMARK_COLS, COLS, EVAL_COLS, EVAL_TYPES, AutoEvalColumn, ModelType, fields, WeightType, Precision
10
+ from src.envs import API, EVAL_REQUESTS_PATH, EVAL_RESULTS_PATH, QUEUE_REPO, REPO_ID, RESULTS_REPO, TOKEN
11
+ from src.populate import get_evaluation_queue_df, get_leaderboard_df
12
+ from src.submission.submit import add_new_eval
13
+ import random
14
+ import matplotlib.pyplot as plt
15
+ import re
16
+ import plotly.express as px
17
+ import plotly.graph_objects as go
18
+ import numpy as np
19
+
20
+
21
+ def mean_of_max_per_field(df):
22
+ """
23
+ Calcola il massimo per ciascun campo e poi la media dei massimi.
24
+
25
+ Args:
26
+ df (pd.DataFrame): DataFrame con colonne TE, SA, HS, AT, WIC, FAQ, LS, SU, NER, REL
27
+
28
+ Returns:
29
+ float: media dei valori massimi dei campi
30
+ """
31
+ #fields = ["TE", "SA", "HS", "AT", "WIC", "FAQ", "LS", "SU", "NER", "REL"]
32
+ fields = ["NER", "REL"]
33
+ #print(df.columns)
34
+
35
+ # Controlla che tutte le colonne esistano nel DataFrame
36
+ missing = [f for f in fields if f not in df.columns]
37
+ if missing:
38
+ raise ValueError(f"Le seguenti colonne mancano nel DataFrame: {missing}")
39
+
40
+ # Calcola il massimo per ciascun campo
41
+ max_values = df[fields].max()
42
+
43
+ # Calcola la media dei massimi
44
+ mean_max = max_values.mean()
45
+
46
+ return mean_max
47
+
48
+
49
+ def barplot_mean_few_minus_zero_shot(dataframe, tasks=None):
50
+ if tasks is None:
51
+ tasks = ["TE", "SA", "HS", "AT", "WIC", "FAQ", "LS", "SU", "NER", "REL"]
52
+
53
+ task_means = {}
54
+
55
+ for task in tasks:
56
+ if task not in dataframe.columns:
57
+ continue
58
+
59
+ # Separa few-shot e zero-shot
60
+ few_shot = dataframe[dataframe['IS_FS'] == True][["Model", task]]
61
+ zero_shot = dataframe[dataframe['IS_FS'] == False][["Model", task]]
62
+
63
+ # Allinea i modelli
64
+ merged = pd.merge(few_shot, zero_shot, on="Model", suffixes=("_few", "_zero"))
65
+
66
+ # Rimuovi righe con valori mancanti
67
+ merged = merged.dropna(subset=[f"{task}_few", f"{task}_zero"])
68
+
69
+ if merged.empty:
70
+ continue
71
+
72
+ # Calcola differenza few - zero
73
+ diff = merged[f"{task}_few"] - merged[f"{task}_zero"]
74
+
75
+ # Calcola la media
76
+ task_means[task] = diff.mean()
77
+
78
+ # Crea barplot
79
+ fig = go.Figure([go.Bar(
80
+ x=list(task_means.keys()),
81
+ y=list(task_means.values()),
82
+ marker_color="#ff7f0e",
83
+ text=[f"{v:.2f}" for v in task_means.values()],
84
+ textposition="outside",
85
+ hovertemplate="<b>%{x}</b><br>Mean Delta Accuracy: %{y:.2f}%<extra></extra>"
86
+ )])
87
+
88
+ # Linea di riferimento a 0
89
+ '''
90
+ fig.add_shape(
91
+ type="line",
92
+ x0=-0.5, x1=len(task_means) - 0.5,
93
+ y0=0, y1=0,
94
+ line=dict(color="black", width=2, dash="dash"),
95
+ xref="x", yref="y"
96
+ )
97
+ '''
98
+
99
+ fig.update_layout(
100
+ title="Mean Accuracy Difference (Few-shot βˆ’ Zero-shot) per Task",
101
+ xaxis_title="",
102
+ yaxis_title="Mean Delta Combined Performance",
103
+ template="plotly_white",
104
+ font=dict(family="Arial", size=13),
105
+ #margin=dict(b=100)
106
+ )
107
+
108
+ fig.add_annotation(
109
+ text="10-shot learning generally outperforms zero-shot. <br>"
110
+ "",
111
+ xref="paper", yref="paper",
112
+ x=0, y=-0.2,
113
+ showarrow=False,
114
+ font=dict(size=11, color="gray"),
115
+ align="left"
116
+ )
117
+
118
+ return fig
119
+
120
+
121
+ def boxplot_per_task(dataframe=None, baselines=None, references=None):
122
+
123
+ #print(dataframe.columns)
124
+
125
+ #tasks = ["TE", "SA", "HS", "AT", "WIC", "FAQ", "LS", "SU", "NER", "REL"]
126
+ tasks =["NER", "REL"]
127
+ if dataframe is None:
128
+ np.random.seed(42)
129
+ dataframe = pd.DataFrame({
130
+ task: np.random.uniform(0.4, 0.9, 20) * 100
131
+ for task in tasks
132
+ })
133
+
134
+ if baselines is None:
135
+ baselines = {task: np.random.randint(50, 70) for task in tasks}
136
+
137
+ colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd",
138
+ "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"]
139
+
140
+ fig = go.Figure()
141
+
142
+ for i, task in enumerate(tasks):
143
+ if task in dataframe.columns:
144
+ y_data = dataframe[task].dropna().tolist()
145
+
146
+ # boxplot
147
+ fig.add_trace(go.Box(
148
+ y=y_data,
149
+ name=task,
150
+ marker=dict(color=colors[i]),
151
+ line=dict(color="black", width=2),
152
+ fillcolor=colors[i],
153
+ opacity=0.7,
154
+ hovertemplate="<b>"+task+"</b><br>Accuracy: %{y:.2f}%<extra></extra>",
155
+ width=0.6,
156
+ whiskerwidth=0.2,
157
+ quartilemethod="linear"
158
+ ))
159
+
160
+ # baseline
161
+ if task in baselines and baselines[task] is not None:
162
+ fig.add_shape(
163
+ type="line",
164
+ x0=i - 0.3, x1=i + 0.3,
165
+ y0=baselines[task], y1=baselines[task],
166
+ line=dict(color="black", width=2, dash="dot"), # piΓΉ visibile
167
+ xref="x", yref="y"
168
+ )
169
+ '''
170
+ fig.add_annotation(
171
+ x=i, y=baselines[task],
172
+ text=f"{baselines[task]}%",
173
+ showarrow=False,
174
+ yshift=10,
175
+ font=dict(size=10, color="black")
176
+ )
177
+ '''
178
+
179
+ # reference GPT-4o
180
+ if task in references and references[task] is not None:
181
+ fig.add_shape(
182
+ type="line",
183
+ x0=i - 0.3, x1=i + 0.3,
184
+ y0=references[task], y1=references[task],
185
+ line=dict(color="red", width=2, dash="dashdot"),
186
+ xref="x", yref="y"
187
+ )
188
+
189
+ fig.update_layout(
190
+ title="Distribution of Model Accuracy by Task",
191
+ xaxis_title="Task",
192
+ yaxis_title="Combined Performance",
193
+ template="plotly_white",
194
+ boxmode="group",
195
+ dragmode=False,
196
+ font=dict(family="Arial", size=10),
197
+ margin=dict(b=80),
198
+ )
199
+
200
+ fig.add_annotation(
201
+ text=(""
202
+ #"In tasks like TE and SA, models approach the accuracy of supervised <br>"
203
+ #"models at EVALITA (dashed black line); in NER and REL they remain lower. <br>"
204
+ # "Dashed red lines show GPT-4o reference results for generative tasks."
205
+ ),
206
+ xref="paper", yref="paper",
207
+ x=0.5, y=-0.30,
208
+ showarrow=False,
209
+ font=dict(size=11, color="gray"),
210
+ align="left"
211
+ )
212
+
213
+ fig.update_yaxes(range=[0, 100], fixedrange=True)
214
+
215
+ return fig
216
+
217
+ # EVALITA results
218
+ BASELINES = {
219
+ "TE":71.00, "SA": 66.38, "HS": 80.88, "AT": 82.40, "WIC": 85.00,
220
+ "LS": 38.82, "SU": 38.91, "NER":88.00, "REL": 62.99
221
+ }
222
+
223
+ # GPT-4o
224
+ REFERENCES = {
225
+ "NER": 79.11,
226
+ "REL": 63.32,
227
+ "LS": 59.25,
228
+ "SU": 33.04
229
+
230
+ }
231
+
232
+
233
+ def boxplot_prompts_per_task(dataframe, tasks=None):
234
+ if tasks is None:
235
+ tasks = ["TE", "SA", "HS", "AT", "WIC", "FAQ", "LS", "SU", "NER", "REL"]
236
+
237
+ # Lista delle colonne da aggiornare
238
+ cols_to_update = ["REL Best Prompt Id", "NER Best Prompt Id", "SU Best Prompt Id", "LS Best Prompt Id"]
239
+ # Applichiamo la trasformazione
240
+ for col in cols_to_update:
241
+ dataframe[col] = dataframe[col].replace({1: 7, 2: 8})
242
+
243
+ fig = go.Figure()
244
+
245
+ # Liste per creare una sola voce in legenda per Average e Best
246
+ avg_x, avg_y = [], []
247
+ best_x, best_y, best_text = [], [], []
248
+
249
+ for task in tasks:
250
+ avg_col = f"{task} Prompt Average"
251
+ best_col = f"{task} Best Prompt"
252
+ best_id_col = f"{task} Best Prompt Id"
253
+
254
+ if all(col in dataframe.columns for col in [avg_col, best_col, best_id_col]):
255
+ avg_value = dataframe[avg_col].mean()
256
+ avg_x.append(task)
257
+ avg_y.append(avg_value)
258
+
259
+ best_value = dataframe[best_col].mean()
260
+ best_x.append(task)
261
+ best_y.append(best_value)
262
+ best_id = dataframe[best_id_col].mode()[0] # Most frequent best prompt id
263
+ best_text.append(f"P:{best_id}")
264
+
265
+ # Barre Average Accuracy (azzurro)
266
+ fig.add_trace(go.Bar(
267
+ x=avg_x,
268
+ y=avg_y,
269
+ name="Avg. Accuracy",
270
+ marker_color="#1f77b4",
271
+ #hovertemplate="%{y:.2f}%<extra></extra>"
272
+ #hovertemplate="<b>" + task + "</b><br>Accuracy: %{y:.2f}%<extra></extra>",
273
+ ))
274
+
275
+ # Barre Best Prompt (rosso)
276
+ fig.add_trace(go.Bar(
277
+ x=best_x,
278
+ y=best_y,
279
+ name="Best Prompt",
280
+ marker_color="#d62728",
281
+ #hovertemplate="%{y:.2f}%<extra></extra>"
282
+ #hovertemplate = "<b>" + task + "</b><br>Accuracy: %{y:.2f}%<extra></extra>",
283
+ ))
284
+
285
+ # Testo sopra barre Best Prompt con ID
286
+ for x, y, text in zip(best_x, best_y, best_text):
287
+ fig.add_annotation(
288
+ x=x,
289
+ y=y + 3, # leggermente sopra la barra
290
+ text=text,
291
+ showarrow=False,
292
+ font=dict(size=12, color="black")
293
+ )
294
+
295
+ fig.update_layout(
296
+ title= "Prompt Accuracy: Avg vs Best",
297
+ xaxis_title="Task",
298
+ yaxis_title="Combined Performance",
299
+ barmode='group',
300
+ template="plotly_white",
301
+ font=dict(family="Arial", size=10),
302
+ yaxis=dict(range=[0, 100], fixedrange=True)
303
+ )
304
+
305
+ # caption come annotazione separata
306
+ fig.add_annotation(
307
+ text="There is no single prompt that performs best across all tasks.<br>"
308
+ "Different prompts achieve the highest accuracy on different tasks.",
309
+ xref="paper", yref="paper",
310
+ x=0.5, y=-0.3,
311
+ showarrow=False,
312
+ font=dict(size=11, color="gray"),
313
+ align="center",
314
+ xanchor="center"
315
+ )
316
+
317
+ return fig
318
+
319
+
320
+ def line_chart(dataframe):
321
+
322
+ # Normalizza le dimensioni per avere marker non troppo piccoli nΓ© enormi
323
+ def scale_sizes(values, min_size=8, max_size=30):
324
+ vmin, vmax = min(values), max(values)
325
+ return [
326
+ min_size + (val - vmin) / (vmax - vmin) * (max_size - min_size) if vmax > vmin else (min_size + max_size) / 2
327
+ for val in values
328
+ ]
329
+
330
+ # dati in base a IS_FS
331
+ df_true = dataframe[dataframe['IS_FS'] == True]
332
+ df_false = dataframe[dataframe['IS_FS'] == False]
333
+
334
+ # Estrai valori x, y e labels
335
+ x_true = df_true['#Params (B)'].tolist()
336
+ y_true = df_true['Avg. Comb. Perf. ⬆️'].tolist()
337
+ labels_true = [re.search(r'>([^<]+)<', m).group(1) for m in df_true['Model'].tolist()]
338
+
339
+ x_false = df_false['#Params (B)'].tolist()
340
+ y_false = df_false['Avg. Comb. Perf. ⬆️'].tolist()
341
+ labels_false = [re.search(r'>([^<]+)<', m).group(1) for m in df_false['Model'].tolist()]
342
+
343
+ fig = go.Figure()
344
+
345
+ # Punti IS_FS=True
346
+ fig.add_trace(go.Scatter(
347
+ x=x_true,
348
+ y=y_true,
349
+ mode='markers',
350
+ name='10-Shot',
351
+ marker=dict(
352
+ color='blue',
353
+ size=scale_sizes(x_true)
354
+ ),
355
+ hovertemplate='<b>%{customdata}</b><br>#Params: %{x}<br>Performance: %{y}<extra></extra>',
356
+ customdata=labels_true
357
+ ))
358
+
359
+ # Punti IS_FS=False
360
+ fig.add_trace(go.Scatter(
361
+ x=x_false,
362
+ y=y_false,
363
+ mode='markers',
364
+ name='0-Shot',
365
+ marker=dict(
366
+ color='red',
367
+ size=scale_sizes(x_false)
368
+ ),
369
+ hovertemplate='<b>%{customdata}</b><br>#Params: %{x}<br>Performance: %{y}<extra></extra>',
370
+ customdata=labels_false
371
+ ))
372
+
373
+ # Trova il massimo tra tutti i modelli
374
+ all_y = y_true + y_false
375
+ all_x = x_true + x_false
376
+ all_labels = labels_true + labels_false
377
+ max_idx = all_y.index(max(all_y))
378
+ max_x = all_x[max_idx]
379
+ max_y = all_y[max_idx]
380
+ max_label = all_labels[max_idx]
381
+
382
+ # Aggiungi annotazione visibile per il modello migliore
383
+ fig.add_annotation(
384
+ x=max_x,
385
+ y=max_y,
386
+ #text=f"Top: {max_label} ({max_y:.1f}%)",
387
+ text=f"{max_label}",
388
+ showarrow=True,
389
+ arrowhead=2,
390
+ arrowsize=1,
391
+ arrowwidth=2,
392
+ arrowcolor="black",
393
+ font=dict(size=11, color="black"),
394
+ xshift=10,
395
+ yshift=10,
396
+ ax = -30, ay = -20, # sposta la label a sinistra e sopra il punto
397
+ xanchor = "right" # allinea la label a destra rispetto al punto
398
+ )
399
+
400
+ fig.update_layout(
401
+ title="Avg. Combined Performance vs #Params",
402
+ xaxis_title="#Params (B)",
403
+ yaxis_title="Avg. Combined Performance",
404
+ template="plotly_white",
405
+ hovermode="closest",
406
+ font=dict(family="Arial", size=10),
407
+ dragmode=False,
408
+ xaxis=dict(
409
+ tickvals=[0, 25, 50, 75, 100, 125],
410
+ ticktext=["0", "25", "50", "75", "100"]
411
+ ),
412
+ yaxis=dict(
413
+ tickvals=[0, 20, 40, 60, 80, 100], # πŸ‘ˆ tick fissi
414
+ range=[0, 100] # πŸ‘ˆ range bloccato
415
+ )
416
+ )
417
+
418
+ # Caption
419
+ fig.add_annotation(
420
+ text="Accuracy generally rises with #Params, but smaller models <br>"
421
+ "with 10-shot can outperform larger zero-shot models.",
422
+ xref="paper", yref="paper",
423
+ x=0.5, y=-0.3, # πŸ‘ˆ centrata
424
+ showarrow=False,
425
+ font=dict(size=11, color="gray"),
426
+ align="center",
427
+ xanchor="center" # πŸ‘ˆ ancora centrata rispetto al testo
428
+ )
429
+
430
+ fig.update_xaxes(fixedrange=True, rangeslider_visible=False)
431
+ fig.update_yaxes(fixedrange=True)
432
+
433
+ return fig
434
+
435
+
436
+ # Define task metadata (icons, names, descriptions)
437
+ TASK_METADATA_MULTIPLECHOICE = {
438
+ #"TE": {"icon": "πŸ“Š", "name": "Textual Entailment", "tooltip": ""},
439
+ #"SA": {"icon": "πŸ˜ƒ", "name": "Sentiment Analysis", "tooltip": ""},
440
+ #"HS": {"icon": "⚠️", "name": "Hate Speech", "tooltip": ""},
441
+ #"AT": {"icon": "πŸ₯", "name": "Admission Test", "tooltip": ""},
442
+ #"WIC": {"icon": "πŸ”€", "name": "Word in Context", "tooltip": ""},
443
+ #"FAQ": {"icon": "❓", "name": "Frequently Asked Questions", "tooltip": ""}
444
+ }
445
+
446
+ # Define task metadata (icons, names, descriptions)
447
+ TASK_METADATA_GENERATIVE = {
448
+ #"LS": {"icon": "πŸ”„", "name": "Lexical Substitution", "tooltip": ""},
449
+ #"SU": {"icon": "πŸ“", "name": "Summarization", "tooltip": ""},
450
+ "NER": {"icon": "🏷️", "name": "Named Entity Recognition", "tooltip": ""},
451
+ "REL": {"icon": "πŸ”—", "name": "Relation Extraction", "tooltip": ""},
452
+ }
453
+
454
+ def restart_space():
455
+ """Restart the Hugging Face space."""
456
+ API.restart_space(repo_id=REPO_ID)
457
+
458
+
459
+ def init_leaderboard(dataframe, default_selection=None, hidden_columns=None):
460
+ """
461
+ Initialize and return the leaderboard when it is first loaded or when 'benchmark' is selected.
462
+ The table is sorted based on the "Avg. Combined Performance" field.
463
+ """
464
+ if dataframe is None or dataframe.empty:
465
+ raise ValueError("Leaderboard DataFrame is empty or None.")
466
+
467
+ #print("????????????????????????????????", mean_of_max_per_field(dataframe))
468
+
469
+ sorted_dataframe = dataframe.sort_values(by="Avg. Comb. Perf. ⬆️", ascending=False)
470
+
471
+ sorted_dataframe = sorted_dataframe.reset_index(drop=True)
472
+ sorted_dataframe["Rank"] = sorted_dataframe.index + 1
473
+
474
+ # Flag per sapere se la medaglia Γ¨ giΓ  stata assegnata per categoria e tipo
475
+ large_medal_fs_assigned = False
476
+ medium_medal_fs_assigned = False
477
+ small_medal_fs_assigned = False
478
+
479
+ large_medal_0shot_assigned = False
480
+ medium_medal_0shot_assigned = False
481
+ small_medal_0shot_assigned = False
482
+
483
+ # Lista temporanea per salvare i nuovi valori della colonna Model
484
+ new_model_column = []
485
+
486
+ for _, row in sorted_dataframe.iterrows():
487
+ if row['IS_FS']: # 10-Few-Shot
488
+ if row["Size"] == "πŸ”΅πŸ”΅πŸ”΅" and not large_medal_fs_assigned:
489
+ new_model_column.append(f"{row['Model']} πŸ”΅πŸ”΅πŸ”΅πŸ†")
490
+ large_medal_fs_assigned = True
491
+ elif row["Size"] == "πŸ”΅πŸ”΅" and not medium_medal_fs_assigned:
492
+ new_model_column.append(f"{row['Model']} πŸ”΅πŸ”΅πŸ†")
493
+ medium_medal_fs_assigned = True
494
+ elif row["Size"] == "πŸ”΅" and not small_medal_fs_assigned:
495
+ new_model_column.append(f"{row['Model']} πŸ”΅πŸ†")
496
+ small_medal_fs_assigned = True
497
+ else:
498
+ new_model_column.append(row["Model"])
499
+ else: # 0-Shot
500
+ if row["Size"] == "πŸ”΅πŸ”΅πŸ”΅" and not large_medal_0shot_assigned:
501
+ new_model_column.append(f"{row['Model']} πŸ”΅πŸ”΅πŸ”΅πŸŽ–οΈ")
502
+ large_medal_0shot_assigned = True
503
+ elif row["Size"] == "πŸ”΅πŸ”΅" and not medium_medal_0shot_assigned:
504
+ new_model_column.append(f"{row['Model']} πŸ”΅πŸ”΅πŸŽ–οΈ")
505
+ medium_medal_0shot_assigned = True
506
+ elif row["Size"] == "πŸ”΅" and not small_medal_0shot_assigned:
507
+ new_model_column.append(f"{row['Model']} πŸ”΅πŸŽ–οΈ")
508
+ small_medal_0shot_assigned = True
509
+ else:
510
+ new_model_column.append(row["Model"])
511
+
512
+ # Lista delle colonne da aggiornare
513
+ #cols_to_update = ["REL Best Prompt Id", "NER Best Prompt Id", "SU Best Prompt Id", "LS Best Prompt Id"]
514
+ # Applichiamo la trasformazione
515
+ #for col in cols_to_update:
516
+ # dataframe[col] = dataframe[col].replace({1: 7, 2: 8})
517
+
518
+ # Aggiorna la colonna Model
519
+ sorted_dataframe["Model"] = new_model_column
520
+
521
+ field_list = fields(AutoEvalColumn)
522
+
523
+ return Leaderboard(
524
+ value=sorted_dataframe,
525
+ datatype=[c.type for c in field_list],
526
+ #select_columns=SelectColumns(
527
+ # default_selection=default_selection or [c.name for c in field_list if c.displayed_by_default],
528
+ # cant_deselect=[c.name for c in field_list if c.never_hidden],
529
+ # label="Select Columns to Display:",
530
+ #),
531
+ search_columns=[AutoEvalColumn.model.name, AutoEvalColumn.license.name],
532
+ hide_columns=hidden_columns or [c.name for c in field_list if c.hidden],
533
+ filter_columns=[
534
+ ColumnFilter(AutoEvalColumn.fewshot_symbol.name, type="checkboxgroup", label="N-Shot Learning (FS)"),
535
+ #ColumnFilter(AutoEvalColumn.fewshot_symbol.name, type="checkboxgroup", label="N-Few-Shot Learning (FS)",
536
+ # default=[["0️⃣", "0️⃣"]]),
537
+ ColumnFilter(AutoEvalColumn.LANG.name, type="checkboxgroup", label="Languges "),
538
+
539
+ ColumnFilter(AutoEvalColumn.params.name, type="slider", min=0, max = 100, default = [0,100], label="Select the number of parameters (B)"),
540
+ ],
541
+ #filter_columns=[
542
+ # ColumnFilter("IS_FS", type="checkbox", default=False, label="5-Few-Shot")
543
+ # #ColumnFilter("FS", type="dropdown", label="5-Few-Shot")
544
+ #],
545
+ bool_checkboxgroup_label="Evaluation Mode",
546
+ interactive=False,
547
+ )
548
+
549
+ def update_task_leaderboard(dataframe, default_selection=None, hidden_columns=None):
550
+ """
551
+ Update and return the leaderboard when a specific task is selected.
552
+ The table is sorted based on the "Combined Performance" field.
553
+ """
554
+ if dataframe is None or dataframe.empty:
555
+ raise ValueError("Leaderboard DataFrame is empty or None.")
556
+
557
+ sorted_dataframe = dataframe.sort_values(by="Combined Performance", ascending=False)
558
+
559
+ # aggiungo la colonna rank in base alla posizione
560
+ sorted_dataframe = sorted_dataframe.reset_index(drop=True)
561
+ sorted_dataframe["Rank"] = sorted_dataframe.index + 1
562
+
563
+ # Flag per sapere se la medaglia Γ¨ giΓ  stata assegnata per categoria e tipo
564
+ large_medal_fs_assigned = False
565
+ medium_medal_fs_assigned = False
566
+ small_medal_fs_assigned = False
567
+
568
+ large_medal_0shot_assigned = False
569
+ medium_medal_0shot_assigned = False
570
+ small_medal_0shot_assigned = False
571
+
572
+ # Lista temporanea per salvare i nuovi valori della colonna Model
573
+ new_model_column = []
574
+
575
+ for _, row in sorted_dataframe.iterrows():
576
+ if row['IS_FS']: # 5-Few-Shot
577
+ if row["Size"] == "πŸ”΅πŸ”΅πŸ”΅" and not large_medal_fs_assigned:
578
+ new_model_column.append(f"{row['Model']} πŸ”΅πŸ”΅πŸ”΅πŸ†")
579
+ large_medal_fs_assigned = True
580
+ elif row["Size"] == "πŸ”΅πŸ”΅" and not medium_medal_fs_assigned:
581
+ new_model_column.append(f"{row['Model']} πŸ”΅πŸ”΅πŸ†")
582
+ medium_medal_fs_assigned = True
583
+ elif row["Size"] == "πŸ”΅" and not small_medal_fs_assigned:
584
+ new_model_column.append(f"{row['Model']} πŸ”΅πŸ†")
585
+ small_medal_fs_assigned = True
586
+ else:
587
+ new_model_column.append(row["Model"])
588
+ else: # 0-Shot
589
+ if row["Size"] == "πŸ”΅πŸ”΅πŸ”΅" and not large_medal_0shot_assigned:
590
+ new_model_column.append(f"{row['Model']} πŸ”΅πŸ”΅πŸ”΅πŸŽ–οΈ")
591
+ large_medal_0shot_assigned = True
592
+ elif row["Size"] == "πŸ”΅πŸ”΅" and not medium_medal_0shot_assigned:
593
+ new_model_column.append(f"{row['Model']} πŸ”΅πŸ”΅πŸŽ–οΈ")
594
+ medium_medal_0shot_assigned = True
595
+ elif row["Size"] == "πŸ”΅" and not small_medal_0shot_assigned:
596
+ new_model_column.append(f"{row['Model']} πŸ”΅πŸŽ–οΈ")
597
+ small_medal_0shot_assigned = True
598
+ else:
599
+ new_model_column.append(row["Model"])
600
+
601
+ # Aggiorna la colonna Model
602
+ sorted_dataframe["Model"] = new_model_column
603
+
604
+ pd.set_option('display.max_colwidth', None)
605
+ #print("========================", dataframe['Model'])
606
+
607
+ #print(sorted_dataframe['Combined Performance'])
608
+
609
+ field_list = fields(AutoEvalColumn)
610
+
611
+ return Leaderboard(
612
+ value=sorted_dataframe,
613
+ #datatype=[c.type for c in field_list],
614
+ datatype=[c.type for c in field_list] + [int],
615
+ #select_columns=SelectColumns(
616
+ # default_selection=default_selection or [c.name for c in field_list if c.displayed_by_default],
617
+ # cant_deselect=[c.name for c in field_list if c.never_hidden],
618
+ # label="Select Columns to Display:",
619
+ #),
620
+ search_columns=[AutoEvalColumn.model.name, AutoEvalColumn.license.name],
621
+ hide_columns=hidden_columns or [c.name for c in field_list if c.hidden],
622
+ filter_columns=[
623
+ ColumnFilter(AutoEvalColumn.fewshot_symbol.name, type="checkboxgroup", label="N-Shot Learning (FS)"),
624
+ ColumnFilter(AutoEvalColumn.LANG.name, type="checkboxgroup", label="Languges "),
625
+
626
+ ColumnFilter(AutoEvalColumn.params.name, type="slider", min=0, max=100, default=[0, 100],
627
+ label="Select the number of parameters (B)"),
628
+ ],
629
+ bool_checkboxgroup_label="Evaluation Mode",
630
+ interactive=False
631
+ )
632
+
633
+ '''
634
+ # Helper function for leaderboard initialization
635
+ def init_leaderboard(dataframe, default_selection=None, hidden_columns=None):
636
+ """Initialize and return a leaderboard."""
637
+ if dataframe is None or dataframe.empty:
638
+ raise ValueError("Leaderboard DataFrame is empty or None.")
639
+
640
+ return Leaderboard(
641
+ value=dataframe,
642
+ datatype=[c.type for c in fields(AutoEvalColumn)],
643
+ select_columns=SelectColumns(
644
+ default_selection=default_selection or [c.name for c in fields(AutoEvalColumn) if c.displayed_by_default],
645
+ cant_deselect=[c.name for c in fields(AutoEvalColumn) if c.never_hidden],
646
+ label="Select Columns to Display:",
647
+ ),
648
+ search_columns=[AutoEvalColumn.model.name, AutoEvalColumn.license.name],
649
+ hide_columns=hidden_columns or [c.name for c in fields(AutoEvalColumn) if c.hidden],
650
+ filter_columns=[
651
+ ColumnFilter(AutoEvalColumn.fewshot_type.name, type="checkboxgroup", label="N-Few-Shot Learning (FS)"),
652
+ ColumnFilter(AutoEvalColumn.params.name, type="slider", min=0, max=150, label="Select the number of parameters (B)"),
653
+ ],
654
+ bool_checkboxgroup_label="Hide models",
655
+ interactive=False,
656
+ )
657
+ '''
658
+
659
+ def download_snapshot(repo, local_dir):
660
+ """Try to download a snapshot from Hugging Face Hub."""
661
+ try:
662
+ print(f"Downloading from {repo} to {local_dir}...")
663
+ snapshot_download(repo_id=repo, local_dir=local_dir, repo_type="dataset", tqdm_class=None, etag_timeout=30, token=TOKEN)
664
+ except Exception as e:
665
+ print(f"Error downloading {repo}: {e}")
666
+ restart_space()
667
+
668
+
669
+ # Initialize the app by downloading snapshots
670
+ download_snapshot(QUEUE_REPO, EVAL_REQUESTS_PATH)
671
+ download_snapshot(RESULTS_REPO, EVAL_RESULTS_PATH)
672
+
673
+ # Load leaderboard data
674
+ LEADERBOARD_DF = get_leaderboard_df(EVAL_RESULTS_PATH, EVAL_REQUESTS_PATH, COLS, BENCHMARK_COLS)
675
+ finished_eval_queue_df, running_eval_queue_df, pending_eval_queue_df = get_evaluation_queue_df(EVAL_REQUESTS_PATH, EVAL_COLS)
676
+ #print(LEADERBOARD_DF.columns.tolist())
677
+
678
+ theoretical_max_combined_perf = mean_of_max_per_field(LEADERBOARD_DF)
679
+
680
+ # Prepare the main interface
681
+ demo = gr.Blocks(css=custom_css)
682
+ with demo:
683
+ #gr.HTML(TITLE)
684
+ gr.HTML(
685
+ """
686
+ <div style="display: flex; align-items: center; position: relative; width: 100%; height: 60px; padding: 10px 0;">
687
+ <h1 style="
688
+ margin: 0 auto;
689
+ font-weight: 900;
690
+ font-size: 5.5em;
691
+ letter-spacing: 2px;
692
+ text-transform: uppercase;
693
+ color: red;
694
+ background: linear-gradient(90deg, #1f77b4, #00c6ff);
695
+ -webkit-background-clip: text;
696
+ -webkit-text-fill-color: transparent;
697
+ text-shadow: 2px 2px 8px rgba(0.2,0,0,0);
698
+ ">
699
+ ECREAM-LLM Leaderboard
700
+ </h1>
701
+ </div>
702
+ """
703
+ )
704
+ gr.Markdown(INTRODUCTION_TEXT, elem_classes="markdown-text")
705
+
706
+ # ⬇️ QUI aggiungiamo i grafici subito sotto la barra del titolo e sopra le tabs
707
+ with gr.Row():
708
+ gr.Plot(value=line_chart(LEADERBOARD_DF), elem_id="line-chart")
709
+ gr.Plot(value=boxplot_per_task(LEADERBOARD_DF, BASELINES, REFERENCES), elem_id="boxplot-task")
710
+ #gr.Plot(value=boxplot_prompts_per_task(LEADERBOARD_DF), elem_id="boxplot-prompt-task")
711
+
712
+ with gr.Tabs(elem_classes="tab-buttons") as tabs:
713
+
714
+ # Main leaderboard tab
715
+ with gr.TabItem("πŸ… Benchmark"):
716
+
717
+ leaderboard = init_leaderboard(
718
+ LEADERBOARD_DF,
719
+ default_selection=['Rank', 'Size', 'LANG', 'FS', 'Model', "Avg. Comb. Perf. ⬆️", "TE", "SA", "HS", "AT", "WIC", "FAQ", "LS", "SU", "NER", "REL"],
720
+ hidden_columns=[col for col in LEADERBOARD_DF.columns if col not in ['Rank', 'Size', 'LANG', 'FS', 'Model', "Avg. Comb. Perf. ⬆️", "TE", "SA", "HS", "AT", "WIC", "FAQ", "LS", "SU", "NER", "REL"]]
721
+ )
722
+
723
+ # gr.HTML(
724
+ # f"""
725
+ # <div style="
726
+ # border: 2px solid #1f77b4;
727
+ # border-radius: 10px;
728
+ # padding: 10px;
729
+ # background-color: #f0f8ff;
730
+ # font-weight: bold;
731
+ # font-size: 14px;
732
+ # display: inline-block;
733
+ # ">
734
+ # Theoretical performance of a model that scores the highest on every individual task: <span style="color:#d62728; font-size:18px;">{theoretical_max_combined_perf:.2f}</span>
735
+ # </div>
736
+ # $ """
737
+ # )
738
+
739
+ '''
740
+ with gr.TabItem("πŸ“ˆ Charts"):
741
+ #gr.Plot(value=line_chart(LEADERBOARD_DF), label="Andamento di esempio")
742
+ #gr.Plot(value=line_chart_interactive_test(), label="Andamento interattivo")
743
+ gr.Plot(value=line_chart(LEADERBOARD_DF))
744
+ gr.Plot(value=boxplot_per_task(LEADERBOARD_DF, BASELINES))
745
+ gr.Plot(value=boxplot_prompts_per_task(LEADERBOARD_DF))
746
+ gr.Plot(value=barplot_mean_few_minus_zero_shot(LEADERBOARD_DF))
747
+ '''
748
+
749
+ # About tab
750
+ with gr.TabItem("πŸ“ About"):
751
+ gr.Markdown(LLM_BENCHMARKS_TEXT, elem_classes="markdown-text")
752
+
753
+ # About tab
754
+ #with gr.TabItem("β•‘", interactive=False):
755
+ # gr.Markdown("", elem_classes="markdown-text")
756
+
757
+
758
+ # Task-specific leaderboards
759
+ for task, metadata in TASK_METADATA_MULTIPLECHOICE.items():
760
+
761
+ with gr.TabItem(f"{metadata['icon']}{task}"):
762
+
763
+ task_description = TASK_DESCRIPTIONS.get(task, "Description not available.")
764
+ gr.Markdown(task_description, elem_classes="markdown-text")
765
+
766
+ leaderboard = update_task_leaderboard(
767
+ LEADERBOARD_DF.rename(columns={f"{task} Prompt Average": "Prompt Average", f"{task} Prompt Std": "Prompt Std", f"{task} Best Prompt": "Best Prompt", f"{task} Best Prompt Id": "Best Prompt Id", task: "Combined Performance"}),
768
+ default_selection=['Rank', 'Size','LANG', 'FS', 'Model', 'Combined Performance', 'Prompt Average', 'Prompt Std', 'Best Prompt', 'Best Prompt Id'],
769
+ hidden_columns=[col for col in LEADERBOARD_DF.columns if col not in ['Rank', 'Size','LANG', 'FS', 'Model', 'Combined Performance', 'Prompt Average', 'Prompt Std', 'Best Prompt', 'Best Prompt Id']]
770
+ )
771
+
772
+ # About tab
773
+ with gr.TabItem("β”‚", interactive=False):
774
+ gr.Markdown("", elem_classes="markdown-text")
775
+
776
+ # Task-specific leaderboards
777
+ for task, metadata in TASK_METADATA_GENERATIVE.items():
778
+ with gr.TabItem(f"{metadata['icon']}{task}"):
779
+ task_description = TASK_DESCRIPTIONS.get(task, "Description not available.")
780
+ gr.Markdown(task_description, elem_classes="markdown-text1")
781
+ #print (LEADERBOARD_DF)
782
+ leaderboard = update_task_leaderboard(
783
+ LEADERBOARD_DF.rename(columns={f"{task} Prompt Average": "Prompt Average",
784
+ f"{task} Prompt Std": "Prompt Std",
785
+ f"{task} Best Prompt": "Best Prompt",
786
+ f"{task} Best Prompt Id": "Best Prompt Id",
787
+ task: "Combined Performance"}),
788
+ default_selection=['Rank', 'Size', 'LANG', 'FS', 'Model', 'Combined Performance', 'Prompt Average', 'Prompt Std', 'Best Prompt',
789
+ 'Best Prompt Id'],
790
+ hidden_columns=[col for col in LEADERBOARD_DF.columns if
791
+ col not in ['Rank', 'Size','LANG', 'FS', 'Model', 'Combined Performance', 'Prompt Average', 'Prompt Std',
792
+ 'Best Prompt', 'Best Prompt Id']]
793
+ )
794
+
795
+ # Citation section
796
+ with gr.Accordion("πŸ“™ Citation", open=False):
797
+ gr.Textbox(value=CITATION_BUTTON_TEXT, label=CITATION_BUTTON_LABEL, lines=20, elem_id="citation-button", show_copy_button=True)
798
+
799
+ with gr.Accordion("πŸ“™ Credits", open=False):
800
+ gr.Markdown(
801
+ """
802
+ ***This project has been funded by the European Union under:
803
+
804
+ Horizon Europe eCREAM Project (Grant Agreement No.101057726)
805
+ """
806
+ )
807
+
808
+ # Background job to restart space
809
+ scheduler = BackgroundScheduler()
810
+ scheduler.add_job(restart_space, "interval", seconds=1800)
811
+ scheduler.start()
812
+
813
+ # Launch the app with concurrent queueing
814
+ demo.queue(default_concurrency_limit=40).launch(debug=True, # Enable Gradio debug mode
815
+ show_error=True)
src/__pycache__/about.cpython-310.pyc CHANGED
Binary files a/src/__pycache__/about.cpython-310.pyc and b/src/__pycache__/about.cpython-310.pyc differ
 
src/display/__pycache__/css_html_js.cpython-310.pyc CHANGED
Binary files a/src/display/__pycache__/css_html_js.cpython-310.pyc and b/src/display/__pycache__/css_html_js.cpython-310.pyc differ
 
src/display/css_html_js.py CHANGED
@@ -1,5 +1,12 @@
1
  custom_css = """
2
-
 
 
 
 
 
 
 
3
  .markdown-text1 {
4
  font-size: 16px !important;
5
  max-height: 300px; /* adjust height as you like */
 
1
  custom_css = """
2
+ /* gray background behind the combo row only */
3
+ #filters-wrap {
4
+ background: #f2f3f5; /* light gray */
5
+ border-radius: 12px; /* optional */
6
+ padding: 12px 16px; /* breathing room */
7
+ margin-bottom: 8px; /* space before plots */
8
+ box-sizing: border-box;
9
+ }
10
  .markdown-text1 {
11
  font-size: 16px !important;
12
  max-height: 300px; /* adjust height as you like */