alielfilali01 commited on
Commit
24a5f16
β€’
1 Parent(s): 22c6549

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +658 -0
app.py ADDED
@@ -0,0 +1,658 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import numpy as np
4
+ import pandas as pd
5
+ import gradio as gr
6
+ from huggingface_hub import HfApi, hf_hub_download
7
+
8
+
9
+ OWNER = "inceptionai"
10
+ DATASET_REPO_ID = f"{OWNER}/requests-dataset"
11
+
12
+ HEADER = """
13
+ <center>
14
+ <h1>AraGen Leaderboard: Generative Tasks Evaluation of Arabic LLMs</h1>
15
+ </center>
16
+
17
+ <br></br>
18
+
19
+ <p>This leaderboard is designed to redefine the evaluation of Arabic Large Language Models (LLMs). Powered by the new <strong>3C3H</strong> evaluation measure, this framework delivers a transparent, robust, and holistic evaluation system that balances factual accuracy and usability assessment for a production ready setting.</p>
20
+
21
+ <p>For more details, please consider going through the technical blogpost <a href="https://huggingface.co/blog/">here</a>.</p>
22
+ """
23
+
24
+ ABOUT_SECTION = """
25
+ ## About:
26
+
27
+ The AraGen Leaderboard is designed to evaluate and compare the performance of Chat Arabic Large Language Models (LLMs) on a set of generative tasks. By leveraging the new **3C3H** evaluation measure which evaluate the model's output across six dimensions β€”Correctness, Completeness, Conciseness, Helpfulness, Honesty, and Harmlessnessβ€” the leaderboard provides a comprehensive and holistic evaluation of a model's performance in generating human-like and ethically responsible content.
28
+
29
+ ### Why Focus on Chat Models?
30
+
31
+ AraGen β€”And 3C3H in generalβ€” is specifically tailored to assess **chat models**, which interact in conversational settings, intended for end user interaction and require a blend of factual accuracy and user-centric dialogue capabilities. While it is technically possible to submit foundational models, we kindly ask users to refrain from doing so. For evaluations of foundational models using likelihood accuracy based benchmarks, please refer to the [Open Arabic LLM Leaderboard (OALL)](https://huggingface.co/spaces/OALL/Open-Arabic-LLM-Leaderboard).
32
+
33
+ ### How to Submit Your Model?
34
+
35
+ avigate to the submission section below to submit your open chat model from the HuggingFace Hub for evaluation. Ensure that your model is public and the submmited metadata (precision, revision, #params) is accurate.
36
+
37
+ ### Contact
38
+
39
+ For any inquiries or assistance, please reach out through the community tab at [Inception AraGen Community](https://huggingface.co/spaces/inceptionai/AraGen-Leaderboard/discussions) or via [email](mailto:ali.filali@inceptionai.ai).
40
+ """
41
+
42
+ CITATION_BUTTON_TEXT = """
43
+ CITATION
44
+ """
45
+
46
+ CITATION_BUTTON_LABEL = """
47
+ CITATION_BUTTON_LABEL
48
+ """
49
+
50
+ def load_results():
51
+ # Get the current directory of the script and construct the path to results.json
52
+ current_dir = os.path.dirname(os.path.abspath(__file__))
53
+ results_file = os.path.join(current_dir, "assets", "results", "results.json")
54
+
55
+ # Load the JSON data from the specified file
56
+ with open(results_file, 'r') as f:
57
+ data = json.load(f)
58
+
59
+ # Lists to collect data
60
+ data_3c3h = []
61
+ data_tasks = []
62
+
63
+ for model_data in data:
64
+ # Extract model meta data
65
+ meta = model_data.get('Meta', {})
66
+ model_name = meta.get('Model Name', 'UNK')
67
+ revision = meta.get('Revision', 'UNK')
68
+ precision = meta.get('Precision', 'UNK')
69
+ params = meta.get('Params', 'UNK')
70
+ license = meta.get('License', 'UNK')
71
+
72
+ # Convert "Model Size" to numeric, treating "UNK" as infinity
73
+ try:
74
+ model_size_numeric = float(params)
75
+ except (ValueError, TypeError):
76
+ model_size_numeric = np.inf
77
+
78
+ # 3C3H Scores
79
+ scores_data = model_data.get('claude-3.5-sonnet Scores', {})
80
+ scores_3c3h = scores_data.get('3C3H Scores', {})
81
+ scores_tasks = scores_data.get('Tasks Scores', {})
82
+
83
+ # Multiply scores by 100 to get percentages (keep them as numeric values)
84
+ formatted_scores_3c3h = {k: v*100 for k, v in scores_3c3h.items()}
85
+ formatted_scores_tasks = {k: v*100 for k, v in scores_tasks.items()}
86
+
87
+ # For 3C3H Scores DataFrame
88
+ data_entry_3c3h = {
89
+ 'Model Name': model_name,
90
+ 'Revision': revision,
91
+ 'License': license,
92
+ 'Precision': precision,
93
+ 'Model Size': model_size_numeric, # Numeric value for sorting
94
+ '3C3H Score': formatted_scores_3c3h.get("3C3H Score", np.nan),
95
+ 'Correctness': formatted_scores_3c3h.get("Correctness", np.nan),
96
+ 'Completeness': formatted_scores_3c3h.get("Completeness", np.nan),
97
+ 'Conciseness': formatted_scores_3c3h.get("Conciseness", np.nan),
98
+ 'Helpfulness': formatted_scores_3c3h.get("Helpfulness", np.nan),
99
+ 'Honesty': formatted_scores_3c3h.get("Honesty", np.nan),
100
+ 'Harmlessness': formatted_scores_3c3h.get("Harmlessness", np.nan),
101
+ }
102
+ data_3c3h.append(data_entry_3c3h)
103
+
104
+ # For Tasks Scores DataFrame
105
+ data_entry_tasks = {
106
+ 'Model Name': model_name,
107
+ 'Revision': revision,
108
+ 'License': license,
109
+ 'Precision': precision,
110
+ 'Model Size': model_size_numeric, # Numeric value for sorting
111
+ **formatted_scores_tasks
112
+ }
113
+ data_tasks.append(data_entry_tasks)
114
+
115
+ df_3c3h = pd.DataFrame(data_3c3h)
116
+ df_tasks = pd.DataFrame(data_tasks)
117
+
118
+ # Round the numeric score columns to 4 decimal places
119
+ score_columns_3c3h = ['3C3H Score', 'Correctness', 'Completeness', 'Conciseness', 'Helpfulness', 'Honesty', 'Harmlessness']
120
+ df_3c3h[score_columns_3c3h] = df_3c3h[score_columns_3c3h].round(4)
121
+
122
+ # Replace np.inf with a large number in 'Model Size Filter' for filtering
123
+ max_model_size_value = 1000 # Define a maximum value
124
+ df_3c3h['Model Size Filter'] = df_3c3h['Model Size'].replace(np.inf, max_model_size_value)
125
+
126
+ # Sort df_3c3h by '3C3H Score' descending if column exists
127
+ if '3C3H Score' in df_3c3h.columns:
128
+ df_3c3h = df_3c3h.sort_values(by='3C3H Score', ascending=False)
129
+ df_3c3h.insert(0, 'Rank', range(1, len(df_3c3h) + 1)) # Add Rank column starting from 1
130
+ else:
131
+ df_3c3h.insert(0, 'Rank', range(1, len(df_3c3h) + 1))
132
+
133
+ # Extract task columns
134
+ task_columns = [col for col in df_tasks.columns if col not in ['Model Name', 'Revision', 'License', 'Precision', 'Model Size', 'Model Size Filter']]
135
+
136
+ # Round the task score columns to 4 decimal places
137
+ if task_columns:
138
+ df_tasks[task_columns] = df_tasks[task_columns].round(4)
139
+
140
+ # Replace np.inf with a large number in 'Model Size Filter' for filtering
141
+ df_tasks['Model Size Filter'] = df_tasks['Model Size'].replace(np.inf, max_model_size_value)
142
+
143
+ # Sort df_tasks by the first task column if it exists
144
+ if task_columns:
145
+ first_task = task_columns[0]
146
+ df_tasks = df_tasks.sort_values(by=first_task, ascending=False)
147
+ df_tasks.insert(0, 'Rank', range(1, len(df_tasks) + 1)) # Add Rank column starting from 1
148
+ else:
149
+ df_tasks = df_tasks.sort_values(by='Model Name', ascending=True)
150
+ df_tasks.insert(0, 'Rank', range(1, len(df_tasks) + 1))
151
+
152
+ return df_3c3h, df_tasks, task_columns
153
+
154
+ def load_requests(status_folder):
155
+ api = HfApi()
156
+ requests_data = []
157
+ folder_path_in_repo = status_folder # 'pending', 'finished', or 'failed'
158
+
159
+ hf_api_token = os.environ.get('HF_API_TOKEN', None)
160
+
161
+ try:
162
+ # List files in the dataset repository
163
+ files_info = api.list_repo_files(
164
+ repo_id=DATASET_REPO_ID,
165
+ repo_type="dataset",
166
+ token=hf_api_token
167
+ )
168
+ except Exception as e:
169
+ print(f"Error accessing dataset repository: {e}")
170
+ return pd.DataFrame() # Return empty DataFrame if repository not found or inaccessible
171
+
172
+ # Filter files in the desired folder
173
+ files_in_folder = [f for f in files_info if f.startswith(f"{folder_path_in_repo}/") and f.endswith('.json')]
174
+
175
+ for file_path in files_in_folder:
176
+ try:
177
+ # Download the JSON file
178
+ local_file_path = hf_hub_download(
179
+ repo_id=DATASET_REPO_ID,
180
+ filename=file_path,
181
+ repo_type="dataset",
182
+ token=hf_api_token
183
+ )
184
+ # Load JSON data
185
+ with open(local_file_path, 'r') as f:
186
+ request = json.load(f)
187
+ requests_data.append(request)
188
+ except Exception as e:
189
+ print(f"Error loading file {file_path}: {e}")
190
+ continue # Skip files that can't be loaded
191
+
192
+ df = pd.DataFrame(requests_data)
193
+ return df
194
+
195
+ def submit_model(model_name, revision, precision, params, license):
196
+ # Load existing evaluations
197
+ df_3c3h, df_tasks, _ = load_results()
198
+ existing_models_results = df_3c3h[['Model Name', 'Revision', 'Precision']]
199
+
200
+ # Handle 'Missing' precision
201
+ if precision == 'Missing':
202
+ precision = None
203
+ else:
204
+ precision = precision.strip().lower()
205
+
206
+ # Load pending and finished requests from the dataset repository
207
+ df_pending = load_requests('pending')
208
+ df_finished = load_requests('finished')
209
+
210
+ # Check if model is already evaluated
211
+ model_exists_in_results = ((existing_models_results['Model Name'] == model_name) &
212
+ (existing_models_results['Revision'] == revision) &
213
+ (existing_models_results['Precision'] == precision)).any()
214
+ if model_exists_in_results:
215
+ return f"**Model '{model_name}' with revision '{revision}' and precision '{precision}' has already been evaluated.**"
216
+
217
+ # Check if model is in pending requests
218
+ if not df_pending.empty:
219
+ existing_models_pending = df_pending[['model_name', 'revision', 'precision']]
220
+ model_exists_in_pending = ((existing_models_pending['model_name'] == model_name) &
221
+ (existing_models_pending['revision'] == revision) &
222
+ (existing_models_pending['precision'] == precision)).any()
223
+ if model_exists_in_pending:
224
+ return f"**Model '{model_name}' with revision '{revision}' and precision '{precision}' is already in the pending evaluations.**"
225
+
226
+ # Check if model is in finished requests
227
+ if not df_finished.empty:
228
+ existing_models_finished = df_finished[['model_name', 'revision', 'precision']]
229
+ model_exists_in_finished = ((existing_models_finished['model_name'] == model_name) &
230
+ (existing_models_finished['revision'] == revision) &
231
+ (existing_models_finished['precision'] == precision)).any()
232
+ if model_exists_in_finished:
233
+ return f"**Model '{model_name}' with revision '{revision}' and precision '{precision}' has already been evaluated.**"
234
+
235
+ # Check if model exists on HuggingFace Hub
236
+ api = HfApi()
237
+ try:
238
+ model_info = api.model_info(model_name)
239
+ except Exception as e:
240
+ return f"**Error: Could not find model '{model_name}' on HuggingFace Hub. Please ensure the model name is correct and the model is public.**"
241
+
242
+ # Proceed with submission
243
+ status = "PENDING"
244
+
245
+ # Prepare the submission data
246
+ submission = {
247
+ "model_name": model_name,
248
+ "license": license,
249
+ "revision": revision,
250
+ "precision": precision,
251
+ "status": status,
252
+ "params": params
253
+ }
254
+
255
+ # Serialize the submission to JSON
256
+ submission_json = json.dumps(submission, indent=2)
257
+
258
+ # Define the file path in the repository
259
+ org_model = model_name.split('/')
260
+ if len(org_model) != 2:
261
+ return "**Please enter the full model name including the organization or username, e.g., 'inceptionai/jais-family-30b-8k'**"
262
+ org, model_id = org_model
263
+ precision_str = precision if precision else 'Missing'
264
+ file_path_in_repo = f"pending/{org}/{model_id}_eval_request_{revision}_{precision_str}.json"
265
+
266
+ # Upload the submission to the dataset repository
267
+ try:
268
+ hf_api_token = os.environ.get('HF_API_TOKEN', None)
269
+ api.upload_file(
270
+ path_or_fileobj=submission_json.encode('utf-8'),
271
+ path_in_repo=file_path_in_repo,
272
+ repo_id=DATASET_REPO_ID,
273
+ repo_type="dataset",
274
+ token=hf_api_token
275
+ )
276
+ except Exception as e:
277
+ return f"**Error: Could not submit the model. {str(e)}**"
278
+
279
+ return f"**Model '{model_name}' has been submitted for evaluation.**"
280
+
281
+ def main():
282
+ df_3c3h, df_tasks, task_columns = load_results()
283
+
284
+ # Extract unique Precision and License values for filters
285
+ precision_options_3c3h = sorted(df_3c3h['Precision'].dropna().unique().tolist())
286
+ precision_options_3c3h = [p for p in precision_options_3c3h if p != 'UNK']
287
+ precision_options_3c3h.append('Missing')
288
+
289
+ license_options_3c3h = sorted(df_3c3h['License'].dropna().unique().tolist())
290
+ license_options_3c3h = [l for l in license_options_3c3h if l != 'UNK']
291
+ license_options_3c3h.append('Missing')
292
+
293
+ precision_options_tasks = sorted(df_tasks['Precision'].dropna().unique().tolist())
294
+ precision_options_tasks = [p for p in precision_options_tasks if p != 'UNK']
295
+ precision_options_tasks.append('Missing')
296
+
297
+ license_options_tasks = sorted(df_tasks['License'].dropna().unique().tolist())
298
+ license_options_tasks = [l for l in license_options_tasks if l != 'UNK']
299
+ license_options_tasks.append('Missing')
300
+
301
+ # Get min and max model sizes for sliders, handling 'inf' values
302
+ min_model_size_3c3h = int(df_3c3h['Model Size Filter'].min())
303
+ max_model_size_3c3h = int(df_3c3h['Model Size Filter'].max())
304
+
305
+ min_model_size_tasks = int(df_tasks['Model Size Filter'].min())
306
+ max_model_size_tasks = int(df_tasks['Model Size Filter'].max())
307
+
308
+ # Exclude 'Model Size Filter' from column selectors
309
+ column_choices_3c3h = [col for col in df_3c3h.columns if col != 'Model Size Filter']
310
+ column_choices_tasks = [col for col in df_tasks.columns if col != 'Model Size Filter']
311
+
312
+ with gr.Blocks() as demo:
313
+ gr.HTML(HEADER)
314
+
315
+ with gr.Tabs():
316
+ with gr.Tab("Leaderboard"):
317
+ with gr.Tabs():
318
+ with gr.Tab("3C3H Scores"):
319
+ with gr.Row():
320
+ search_box_3c3h = gr.Textbox(
321
+ placeholder="Search for models...",
322
+ label="Search",
323
+ interactive=True
324
+ )
325
+ with gr.Row():
326
+ column_selector_3c3h = gr.CheckboxGroup(
327
+ choices=column_choices_3c3h,
328
+ value=[
329
+ 'Rank', 'Model Name', '3C3H Score', 'Correctness', 'Completeness',
330
+ 'Conciseness', 'Helpfulness', 'Honesty', 'Harmlessness'
331
+ ],
332
+ label="Select columns to display",
333
+ )
334
+ with gr.Row():
335
+ license_filter_3c3h = gr.CheckboxGroup(
336
+ choices=license_options_3c3h,
337
+ value=license_options_3c3h.copy(), # Default all selected
338
+ label="Filter by License",
339
+ )
340
+ precision_filter_3c3h = gr.CheckboxGroup(
341
+ choices=precision_options_3c3h,
342
+ value=precision_options_3c3h.copy(), # Default all selected
343
+ label="Filter by Precision",
344
+ )
345
+ with gr.Row():
346
+ model_size_min_filter_3c3h = gr.Slider(
347
+ minimum=min_model_size_3c3h,
348
+ maximum=max_model_size_3c3h,
349
+ value=min_model_size_3c3h,
350
+ step=1,
351
+ label="Minimum Model Size",
352
+ interactive=True
353
+ )
354
+ model_size_max_filter_3c3h = gr.Slider(
355
+ minimum=min_model_size_3c3h,
356
+ maximum=max_model_size_3c3h,
357
+ value=max_model_size_3c3h,
358
+ step=1,
359
+ label="Maximum Model Size",
360
+ interactive=True
361
+ )
362
+
363
+ leaderboard_3c3h = gr.Dataframe(
364
+ df_3c3h[['Rank', 'Model Name', '3C3H Score', 'Correctness', 'Completeness',
365
+ 'Conciseness', 'Helpfulness', 'Honesty', 'Harmlessness']],
366
+ interactive=False
367
+ )
368
+
369
+ def filter_df_3c3h(search_query, selected_cols, precision_filters, license_filters, min_size, max_size):
370
+ filtered_df = df_3c3h.copy()
371
+
372
+ # Ensure min_size <= max_size
373
+ if min_size > max_size:
374
+ min_size, max_size = max_size, min_size
375
+
376
+ # Apply search filter
377
+ if search_query:
378
+ filtered_df = filtered_df[filtered_df['Model Name'].str.contains(search_query, case=False, na=False)]
379
+
380
+ # Apply Precision filter
381
+ if precision_filters:
382
+ include_missing = 'Missing' in precision_filters
383
+ selected_precisions = [p for p in precision_filters if p != 'Missing']
384
+ if include_missing:
385
+ filtered_df = filtered_df[
386
+ (filtered_df['Precision'].isin(selected_precisions)) |
387
+ (filtered_df['Precision'] == 'UNK') |
388
+ (filtered_df['Precision'].isna())
389
+ ]
390
+ else:
391
+ filtered_df = filtered_df[filtered_df['Precision'].isin(selected_precisions)]
392
+
393
+ # Apply License filter
394
+ if license_filters:
395
+ include_missing = 'Missing' in license_filters
396
+ selected_licenses = [l for l in license_filters if l != 'Missing']
397
+ if include_missing:
398
+ filtered_df = filtered_df[
399
+ (filtered_df['License'].isin(selected_licenses)) |
400
+ (filtered_df['License'] == 'UNK') |
401
+ (filtered_df['License'].isna())
402
+ ]
403
+ else:
404
+ filtered_df = filtered_df[filtered_df['License'].isin(selected_licenses)]
405
+
406
+ # Apply Model Size filter
407
+ filtered_df = filtered_df[
408
+ (filtered_df['Model Size Filter'] >= min_size) &
409
+ (filtered_df['Model Size Filter'] <= max_size)
410
+ ]
411
+
412
+ # Remove existing 'Rank' column if present
413
+ if 'Rank' in filtered_df.columns:
414
+ filtered_df = filtered_df.drop(columns=['Rank'])
415
+
416
+ # Recalculate Rank after filtering
417
+ filtered_df = filtered_df.reset_index(drop=True)
418
+ filtered_df.insert(0, 'Rank', range(1, len(filtered_df) + 1))
419
+
420
+ # Ensure selected columns are present
421
+ selected_cols = [col for col in selected_cols if col in filtered_df.columns]
422
+
423
+ return filtered_df[selected_cols]
424
+
425
+ # Bind the filter function to the appropriate events
426
+ filter_inputs_3c3h = [
427
+ search_box_3c3h,
428
+ column_selector_3c3h,
429
+ precision_filter_3c3h,
430
+ license_filter_3c3h,
431
+ model_size_min_filter_3c3h,
432
+ model_size_max_filter_3c3h
433
+ ]
434
+ search_box_3c3h.submit(
435
+ filter_df_3c3h,
436
+ inputs=filter_inputs_3c3h,
437
+ outputs=leaderboard_3c3h
438
+ )
439
+
440
+ # Bind change events for CheckboxGroups and sliders
441
+ for component in filter_inputs_3c3h:
442
+ component.change(
443
+ filter_df_3c3h,
444
+ inputs=filter_inputs_3c3h,
445
+ outputs=leaderboard_3c3h
446
+ )
447
+
448
+ with gr.Tab("Tasks Scores"):
449
+ gr.Markdown("""
450
+ Note: This Table is sorted based on the First Task (Question Answering)
451
+ """)
452
+
453
+ with gr.Row():
454
+ search_box_tasks = gr.Textbox(
455
+ placeholder="Search for models...",
456
+ label="Search",
457
+ interactive=True
458
+ )
459
+ with gr.Row():
460
+ column_selector_tasks = gr.CheckboxGroup(
461
+ choices=column_choices_tasks,
462
+ value=['Rank', 'Model Name'] + task_columns,
463
+ label="Select columns to display",
464
+ )
465
+ with gr.Row():
466
+ license_filter_tasks = gr.CheckboxGroup(
467
+ choices=license_options_tasks,
468
+ value=license_options_tasks.copy(), # Default all selected
469
+ label="Filter by License",
470
+ )
471
+ precision_filter_tasks = gr.CheckboxGroup(
472
+ choices=precision_options_tasks,
473
+ value=precision_options_tasks.copy(), # Default all selected
474
+ label="Filter by Precision",
475
+ )
476
+ with gr.Row():
477
+ model_size_min_filter_tasks = gr.Slider(
478
+ minimum=min_model_size_tasks,
479
+ maximum=max_model_size_tasks,
480
+ value=min_model_size_tasks,
481
+ step=1,
482
+ label="Minimum Model Size",
483
+ interactive=True
484
+ )
485
+ model_size_max_filter_tasks = gr.Slider(
486
+ minimum=min_model_size_tasks,
487
+ maximum=max_model_size_tasks,
488
+ value=max_model_size_tasks,
489
+ step=1,
490
+ label="Maximum Model Size",
491
+ interactive=True
492
+ )
493
+
494
+ leaderboard_tasks = gr.Dataframe(
495
+ df_tasks[['Rank', 'Model Name'] + task_columns],
496
+ interactive=False
497
+ )
498
+
499
+ def filter_df_tasks(search_query, selected_cols, precision_filters, license_filters, min_size, max_size):
500
+ filtered_df = df_tasks.copy()
501
+
502
+ # Ensure min_size <= max_size
503
+ if min_size > max_size:
504
+ min_size, max_size = max_size, min_size
505
+
506
+ # Apply search filter
507
+ if search_query:
508
+ filtered_df = filtered_df[filtered_df['Model Name'].str.contains(search_query, case=False, na=False)]
509
+
510
+ # Apply Precision filter
511
+ if precision_filters:
512
+ include_missing = 'Missing' in precision_filters
513
+ selected_precisions = [p for p in precision_filters if p != 'Missing']
514
+ if include_missing:
515
+ filtered_df = filtered_df[
516
+ (filtered_df['Precision'].isin(selected_precisions)) |
517
+ (filtered_df['Precision'] == 'UNK') |
518
+ (filtered_df['Precision'].isna())
519
+ ]
520
+ else:
521
+ filtered_df = filtered_df[filtered_df['Precision'].isin(selected_precisions)]
522
+
523
+ # Apply License filter
524
+ if license_filters:
525
+ include_missing = 'Missing' in license_filters
526
+ selected_licenses = [l for l in license_filters if l != 'Missing']
527
+ if include_missing:
528
+ filtered_df = filtered_df[
529
+ (filtered_df['License'].isin(selected_licenses)) |
530
+ (filtered_df['License'] == 'UNK') |
531
+ (filtered_df['License'].isna())
532
+ ]
533
+ else:
534
+ filtered_df = filtered_df[filtered_df['License'].isin(selected_licenses)]
535
+
536
+ # Apply Model Size filter
537
+ filtered_df = filtered_df[
538
+ (filtered_df['Model Size Filter'] >= min_size) &
539
+ (filtered_df['Model Size Filter'] <= max_size)
540
+ ]
541
+
542
+ # Remove existing 'Rank' column if present
543
+ if 'Rank' in filtered_df.columns:
544
+ filtered_df = filtered_df.drop(columns=['Rank'])
545
+
546
+ # Sort by the first task column if it exists
547
+ if task_columns:
548
+ first_task = task_columns[0]
549
+ filtered_df = filtered_df.sort_values(by=first_task, ascending=False)
550
+ else:
551
+ filtered_df = filtered_df.sort_values(by='Model Name', ascending=True)
552
+
553
+ # Recalculate Rank after filtering
554
+ filtered_df = filtered_df.reset_index(drop=True)
555
+ filtered_df.insert(0, 'Rank', range(1, len(filtered_df) + 1))
556
+
557
+ # Ensure selected columns are present
558
+ selected_cols = [col for col in selected_cols if col in filtered_df.columns]
559
+
560
+ return filtered_df[selected_cols]
561
+
562
+ # Bind the filter function to the appropriate events
563
+ filter_inputs_tasks = [
564
+ search_box_tasks,
565
+ column_selector_tasks,
566
+ precision_filter_tasks,
567
+ license_filter_tasks,
568
+ model_size_min_filter_tasks,
569
+ model_size_max_filter_tasks
570
+ ]
571
+ search_box_tasks.submit(
572
+ filter_df_tasks,
573
+ inputs=filter_inputs_tasks,
574
+ outputs=leaderboard_tasks
575
+ )
576
+
577
+ # Bind change events for CheckboxGroups and sliders
578
+ for component in filter_inputs_tasks:
579
+ component.change(
580
+ filter_df_tasks,
581
+ inputs=filter_inputs_tasks,
582
+ outputs=leaderboard_tasks
583
+ )
584
+
585
+ with gr.Tab("Submit Here"):
586
+ gr.Markdown(ABOUT_SECTION)
587
+ gr.Markdown("---")
588
+ gr.Markdown("# Submit Your Model for Evaluation")
589
+ with gr.Column():
590
+ model_name_input = gr.Textbox(
591
+ label="Model Name",
592
+ placeholder="Enter the full model name from HuggingFace Hub (e.g., inceptionai/jais-family-30b-8k)"
593
+ )
594
+ revision_input = gr.Textbox(
595
+ label="Revision",
596
+ placeholder="main",
597
+ value="main"
598
+ )
599
+ precision_input = gr.Dropdown(
600
+ choices=["float16", "float32", "bfloat16", "8bit", "4bit"],
601
+ label="Precision",
602
+ value="float16"
603
+ )
604
+ params_input = gr.Textbox(
605
+ label="Params",
606
+ placeholder="Enter the approximate number of parameters as Integer (e.g., 7, 13, 30, 70 ...)"
607
+ )
608
+ # Changed from Dropdown to Textbox with default value "Open"
609
+ license_input = gr.Textbox(
610
+ label="License",
611
+ placeholder="Enter the license type (Generic one is 'Open' in case no License is provided)",
612
+ value="Open"
613
+ )
614
+ submit_button = gr.Button("Submit Model")
615
+ submission_result = gr.Markdown()
616
+
617
+ submit_button.click(
618
+ submit_model,
619
+ inputs=[model_name_input, revision_input, precision_input, params_input, license_input],
620
+ outputs=submission_result
621
+ )
622
+
623
+ # Load pending, finished, and failed requests
624
+ df_pending = load_requests('pending')
625
+ df_finished = load_requests('finished')
626
+ df_failed = load_requests('failed')
627
+
628
+ # Display the tables
629
+ gr.Markdown("## Evaluation Status")
630
+ with gr.Accordion(f"Pending Evaluations ({len(df_pending)})", open=False):
631
+ if not df_pending.empty:
632
+ gr.Dataframe(df_pending)
633
+ else:
634
+ gr.Markdown("No pending evaluations.")
635
+ with gr.Accordion(f"Finished Evaluations ({len(df_finished)})", open=False):
636
+ if not df_finished.empty:
637
+ gr.Dataframe(df_finished)
638
+ else:
639
+ gr.Markdown("No finished evaluations.")
640
+ with gr.Accordion(f"Failed Evaluations ({len(df_failed)})", open=False):
641
+ if not df_failed.empty:
642
+ gr.Dataframe(df_failed)
643
+ else:
644
+ gr.Markdown("No failed evaluations.")
645
+ with gr.Row():
646
+ with gr.Accordion("πŸ“™ Citation", open=False):
647
+ citation_button = gr.Textbox(
648
+ value=CITATION_BUTTON_TEXT,
649
+ label=CITATION_BUTTON_LABEL,
650
+ lines=20,
651
+ elem_id="citation-button",
652
+ show_copy_button=True,
653
+ )
654
+
655
+ demo.launch()
656
+
657
+ if __name__ == "__main__":
658
+ main()