abhinav-joshi commited on
Commit
056e156
1 Parent(s): 967b0ef

Initial Commit

Browse files
.DS_Store ADDED
Binary file (6.15 kB). View file
 
.gitattributes CHANGED
@@ -25,6 +25,7 @@
25
  *.safetensors filter=lfs diff=lfs merge=lfs -text
26
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
  *.tar.* filter=lfs diff=lfs merge=lfs -text
 
28
  *.tflite filter=lfs diff=lfs merge=lfs -text
29
  *.tgz filter=lfs diff=lfs merge=lfs -text
30
  *.wasm filter=lfs diff=lfs merge=lfs -text
@@ -32,4 +33,3 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
32
  *.zip filter=lfs diff=lfs merge=lfs -text
33
  *.zst filter=lfs diff=lfs merge=lfs -text
34
  *tfevents* filter=lfs diff=lfs merge=lfs -text
35
- scale-hf-logo.png filter=lfs diff=lfs merge=lfs -text
 
25
  *.safetensors filter=lfs diff=lfs merge=lfs -text
26
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
  *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
  *.tflite filter=lfs diff=lfs merge=lfs -text
30
  *.tgz filter=lfs diff=lfs merge=lfs -text
31
  *.wasm filter=lfs diff=lfs merge=lfs -text
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
.pre-commit-config.yaml DELETED
@@ -1,53 +0,0 @@
1
- # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
-
15
- default_language_version:
16
- python: python3
17
-
18
- ci:
19
- autofix_prs: true
20
- autoupdate_commit_msg: '[pre-commit.ci] pre-commit suggestions'
21
- autoupdate_schedule: quarterly
22
-
23
- repos:
24
- - repo: https://github.com/pre-commit/pre-commit-hooks
25
- rev: v4.3.0
26
- hooks:
27
- - id: check-yaml
28
- - id: check-case-conflict
29
- - id: detect-private-key
30
- - id: check-added-large-files
31
- args: ['--maxkb=1000']
32
- - id: requirements-txt-fixer
33
- - id: end-of-file-fixer
34
- - id: trailing-whitespace
35
-
36
- - repo: https://github.com/PyCQA/isort
37
- rev: 5.12.0
38
- hooks:
39
- - id: isort
40
- name: Format imports
41
-
42
- - repo: https://github.com/psf/black
43
- rev: 22.12.0
44
- hooks:
45
- - id: black
46
- name: Format code
47
- additional_dependencies: ['click==8.0.2']
48
-
49
- - repo: https://github.com/charliermarsh/ruff-pre-commit
50
- # Ruff version.
51
- rev: 'v0.0.267'
52
- hooks:
53
- - id: ruff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Makefile DELETED
@@ -1,13 +0,0 @@
1
- .PHONY: style format
2
-
3
-
4
- style:
5
- python -m black --line-length 119 .
6
- python -m isort .
7
- ruff check --fix .
8
-
9
-
10
- quality:
11
- python -m black --check --line-length 119 .
12
- python -m isort --check-only .
13
- ruff check .
 
 
 
 
 
 
 
 
 
 
 
 
 
 
README.md CHANGED
@@ -1,45 +1,13 @@
1
  ---
2
  title: IL-TUR Leaderboard
3
- emoji: 🥇
4
- colorFrom: green
5
- colorTo: indigo
6
  sdk: gradio
7
- sdk_version: 4.4.0
8
  app_file: app.py
9
- pinned: true
10
  license: apache-2.0
11
  ---
12
 
13
- # Start the configuration
14
-
15
- Most of the variables to change for a default leaderboard are in `src/env.py` (replace the path for your leaderboard) and `src/about.py` (for tasks).
16
-
17
- Results files should have the following format and be stored as json files:
18
- ```json
19
- {
20
- "config": {
21
- "model_dtype": "torch.float16", # or torch.bfloat16 or 8bit or 4bit
22
- "model_name": "path of the model on the hub: org/model",
23
- "model_sha": "revision on the hub",
24
- },
25
- "results": {
26
- "task_name": {
27
- "metric_name": score,
28
- },
29
- "task_name2": {
30
- "metric_name": score,
31
- }
32
- }
33
- }
34
- ```
35
-
36
- Request files are created automatically by this tool.
37
-
38
- If you encounter problem on the space, don't hesitate to restart it to remove the create eval-queue, eval-queue-bk, eval-results and eval-results-bk created folder.
39
-
40
- # Code logic for more complex edits
41
-
42
- You'll find
43
- - the main table' columns names and properties in `src/display/utils.py`
44
- - the logic to read all results and request files, then convert them in dataframe lines, in `src/leaderboard/read_evals.py`, and `src/populate.py`
45
- - teh logic to allow or filter submissions in `src/submission/submit.py` and `src/submission/check_validity.py`
 
1
  ---
2
  title: IL-TUR Leaderboard
3
+ emoji: 📊
4
+ colorFrom: yellow
5
+ colorTo: green
6
  sdk: gradio
7
+ sdk_version: 4.8.0
8
  app_file: app.py
9
+ pinned: false
10
  license: apache-2.0
11
  ---
12
 
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py CHANGED
@@ -1,394 +1,224 @@
1
- import subprocess
2
  import gradio as gr
3
  import pandas as pd
 
4
  from apscheduler.schedulers.background import BackgroundScheduler
5
- from huggingface_hub import snapshot_download
6
-
7
- from src.about import (
8
- CITATION_BUTTON_LABEL,
9
- CITATION_BUTTON_TEXT,
10
- EVALUATION_QUEUE_TEXT,
11
- INTRODUCTION_TEXT,
12
- LLM_BENCHMARKS_TEXT,
13
- TITLE,
14
- )
15
- from src.display.css_html_js import custom_css
16
- from src.display.utils import (
17
- BENCHMARK_COLS,
18
- COLS,
19
- EVAL_COLS,
20
- EVAL_TYPES,
21
- NUMERIC_INTERVALS,
22
- TYPES,
23
- AutoEvalColumn,
24
- ModelType,
25
- fields,
26
- WeightType,
27
- Precision,
28
- )
29
- from src.envs import API, EVAL_REQUESTS_PATH, EVAL_RESULTS_PATH, QUEUE_REPO, REPO_ID, RESULTS_REPO, TOKEN
30
- from src.populate import get_evaluation_queue_df, get_leaderboard_df
31
- from src.submission.submit import add_new_eval
32
 
33
 
34
  def restart_space():
35
- # breakpoint()
36
- # API.restart_space(repo_id=REPO_ID)
37
- return
38
-
39
-
40
- try:
41
- print(EVAL_REQUESTS_PATH)
42
- snapshot_download(
43
- repo_id=QUEUE_REPO,
44
- local_dir=EVAL_REQUESTS_PATH,
45
- repo_type="dataset",
46
- tqdm_class=None,
47
- etag_timeout=30,
48
- token=TOKEN,
49
- )
50
- except Exception:
51
- restart_space()
52
- try:
53
- print(EVAL_RESULTS_PATH)
54
- snapshot_download(
55
- repo_id=RESULTS_REPO,
56
- local_dir=EVAL_RESULTS_PATH,
57
- repo_type="dataset",
58
- tqdm_class=None,
59
- etag_timeout=30,
60
- token=TOKEN,
61
- )
62
- except Exception:
63
- restart_space()
64
-
65
-
66
- raw_data, original_df = get_leaderboard_df(EVAL_RESULTS_PATH, EVAL_REQUESTS_PATH, COLS, BENCHMARK_COLS)
67
-
68
- leaderboard_df = original_df.copy()
69
- # breakpoint()
70
-
71
- (
72
- finished_eval_queue_df,
73
- running_eval_queue_df,
74
- pending_eval_queue_df,
75
- ) = get_evaluation_queue_df(EVAL_REQUESTS_PATH, EVAL_COLS)
76
-
77
-
78
- # Searching and filtering
79
- def update_table(
80
- hidden_df: pd.DataFrame,
81
- columns: list,
82
- type_query: list,
83
- precision_query: str,
84
- size_query: list,
85
- show_deleted: bool,
86
- query: str,
87
- ):
88
- filtered_df = filter_models(hidden_df, type_query, size_query, precision_query, show_deleted)
89
- filtered_df = filter_queries(query, filtered_df)
90
- df = select_columns(filtered_df, columns)
91
  return df
92
 
93
 
94
- def search_table(df: pd.DataFrame, query: str) -> pd.DataFrame:
95
- return df[(df[AutoEvalColumn.model.name].str.contains(query, case=False))]
96
 
 
97
 
98
- def select_columns(df: pd.DataFrame, columns: list) -> pd.DataFrame:
99
- # breakpoint()
100
- always_here_cols = [
101
- # AutoEvalColumn.model_type_symbol.name,
102
- # AutoEvalColumn.model_name.name,
103
- "eval_name"
104
- ]
105
- print(
106
- "---------------",
107
- AutoEvalColumn.model_name.name,
108
- )
109
- # We use COLS to maintain sorting
110
- filtered_df = df[always_here_cols + [c for c in COLS if c in df.columns and c in columns]]
111
- # filtered_df = df[[c for c in COLS if c in df.columns and c in columns]]
112
- # breakpoint()
113
- return filtered_df
114
-
115
-
116
- def filter_queries(query: str, filtered_df: pd.DataFrame) -> pd.DataFrame:
117
- final_df = []
118
- if query != "":
119
- queries = [q.strip() for q in query.split(";")]
120
- for _q in queries:
121
- _q = _q.strip()
122
- if _q != "":
123
- temp_filtered_df = search_table(filtered_df, _q)
124
- if len(temp_filtered_df) > 0:
125
- final_df.append(temp_filtered_df)
126
- if len(final_df) > 0:
127
- filtered_df = pd.concat(final_df)
128
- filtered_df = filtered_df.drop_duplicates(
129
- subset=[AutoEvalColumn.model.name, AutoEvalColumn.precision.name, AutoEvalColumn.revision.name]
130
- )
131
 
132
- return filtered_df
 
 
 
 
 
133
 
134
 
135
- def filter_models(
136
- df: pd.DataFrame, type_query: list, size_query: list, precision_query: list, show_deleted: bool
137
- ) -> pd.DataFrame:
138
- # Show all models
139
- if show_deleted:
140
- filtered_df = df
141
- else: # Show only still on the hub models
142
- filtered_df = df[df[AutoEvalColumn.still_on_hub.name] == True]
143
 
144
- type_emoji = [t[0] for t in type_query]
145
- filtered_df = filtered_df.loc[df[AutoEvalColumn.model_type_symbol.name].isin(type_emoji)]
146
- filtered_df = filtered_df.loc[df[AutoEvalColumn.precision.name].isin(precision_query + ["None"])]
147
 
148
- numeric_interval = pd.IntervalIndex(sorted([NUMERIC_INTERVALS[s] for s in size_query]))
149
- params_column = pd.to_numeric(df[AutoEvalColumn.params.name], errors="coerce")
150
- mask = params_column.apply(lambda x: any(numeric_interval.contains(x)))
151
- filtered_df = filtered_df.loc[mask]
152
 
153
- return filtered_df
 
 
 
 
 
 
 
154
 
 
 
 
 
 
 
 
 
155
 
156
- demo = gr.Blocks(css=custom_css)
157
- with demo:
158
- gr.HTML(TITLE)
159
- gr.Markdown(INTRODUCTION_TEXT, elem_classes="markdown-text")
160
 
161
- with gr.Tabs(elem_classes="tab-buttons") as tabs:
162
- with gr.TabItem("🏅 IL-TUR Benchmark", elem_id="llm-benchmark-tab-table", id=0):
163
  with gr.Row():
164
- with gr.Column():
165
- with gr.Row():
166
- search_bar = gr.Textbox(
167
- placeholder=" 🔍 Search for your model (separate multiple queries with `;`) and press ENTER...",
168
- show_label=False,
169
- elem_id="search-bar",
170
- )
171
- with gr.Row():
172
- shown_columns = gr.CheckboxGroup(
173
- choices=[c.name for c in fields(AutoEvalColumn) if not c.hidden and not c.never_hidden],
174
- value=[
175
- c.name
176
- for c in fields(AutoEvalColumn)
177
- if c.displayed_by_default and not c.hidden and not c.never_hidden
178
- ],
179
- label="Select tasks to show",
180
- elem_id="column-select",
181
- interactive=True,
182
- )
183
- # with gr.Row():
184
- # deleted_models_visibility = gr.Checkbox(
185
- # value=False, label="Show gated/private/deleted models", interactive=True
186
- # )
187
- # with gr.Column(min_width=320):
188
- # # with gr.Box(elem_id="box-filter"):
189
- # filter_columns_type = gr.CheckboxGroup(
190
- # label="Model types",
191
- # choices=[t.to_str() for t in ModelType],
192
- # value=[t.to_str() for t in ModelType],
193
- # interactive=True,
194
- # elem_id="filter-columns-type",
195
- # )
196
- # filter_columns_precision = gr.CheckboxGroup(
197
- # label="Precision",
198
- # choices=[i.value.name for i in Precision],
199
- # value=[i.value.name for i in Precision],
200
- # interactive=True,
201
- # elem_id="filter-columns-precision",
202
- # )
203
- # filter_columns_size = gr.CheckboxGroup(
204
- # label="Model sizes (in billions of parameters)",
205
- # choices=list(NUMERIC_INTERVALS.keys()),
206
- # value=list(NUMERIC_INTERVALS.keys()),
207
- # interactive=True,
208
- # elem_id="filter-columns-size",
209
- # )
210
 
211
  leaderboard_table = gr.components.Dataframe(
212
- value=leaderboard_df[[c.name for c in fields(AutoEvalColumn) if c.never_hidden] + shown_columns.value],
213
- headers=[c.name for c in fields(AutoEvalColumn) if c.never_hidden] + shown_columns.value,
214
- datatype=TYPES,
215
- elem_id="leaderboard-table",
216
- interactive=False,
217
  visible=True,
218
  )
219
 
220
- # Dummy leaderboard for handling the case when the user uses backspace key
221
- hidden_leaderboard_table_for_search = gr.components.Dataframe(
222
- value=original_df[COLS],
223
- headers=COLS,
224
- datatype=TYPES,
225
- visible=False,
226
- )
227
- search_bar.submit(
228
- update_table,
229
- [
230
- hidden_leaderboard_table_for_search,
231
- shown_columns,
232
- # filter_columns_type,
233
- # filter_columns_precision,
234
- # filter_columns_size,
235
- # deleted_models_visibility,
236
  search_bar,
 
237
  ],
238
- leaderboard_table,
239
  )
240
- for selector in [
241
- shown_columns,
242
- # filter_columns_type,
243
- # filter_columns_precision,
244
- # filter_columns_size,
245
- # deleted_models_visibility,
246
- ]:
247
- selector.change(
248
- update_table,
249
- [
250
- hidden_leaderboard_table_for_search,
251
- shown_columns,
252
- # filter_columns_type,
253
- # filter_columns_precision,
254
- # filter_columns_size,
255
- # deleted_models_visibility,
256
- search_bar,
257
- ],
258
- leaderboard_table,
259
- queue=True,
260
- )
261
 
262
- # with gr.TabItem("📝 About", elem_id="llm-benchmark-tab-table", id=2):
263
- # gr.Markdown(LLM_BENCHMARKS_TEXT, elem_classes="markdown-text")
264
-
265
- # with gr.TabItem("🚀 Submit here! ", elem_id="llm-benchmark-tab-table", id=3):
266
- # with gr.Column():
267
- # with gr.Row():
268
- # gr.Markdown(EVALUATION_QUEUE_TEXT, elem_classes="markdown-text")
269
-
270
- # with gr.Column():
271
- # with gr.Accordion(
272
- # f"✅ Finished Evaluations ({len(finished_eval_queue_df)})",
273
- # open=False,
274
- # ):
275
- # with gr.Row():
276
- # finished_eval_table = gr.components.Dataframe(
277
- # value=finished_eval_queue_df,
278
- # headers=EVAL_COLS,
279
- # datatype=EVAL_TYPES,
280
- # row_count=5,
281
- # )
282
- # with gr.Accordion(
283
- # f"🔄 Running Evaluation Queue ({len(running_eval_queue_df)})",
284
- # open=False,
285
- # ):
286
- # with gr.Row():
287
- # running_eval_table = gr.components.Dataframe(
288
- # value=running_eval_queue_df,
289
- # headers=EVAL_COLS,
290
- # datatype=EVAL_TYPES,
291
- # row_count=5,
292
- # )
293
-
294
- # with gr.Accordion(
295
- # f"⏳ Pending Evaluation Queue ({len(pending_eval_queue_df)})",
296
- # open=False,
297
- # ):
298
- # with gr.Row():
299
- # pending_eval_table = gr.components.Dataframe(
300
- # value=pending_eval_queue_df,
301
- # headers=EVAL_COLS,
302
- # datatype=EVAL_TYPES,
303
- # row_count=5,
304
- # )
305
- # with gr.Row():
306
- # gr.Markdown("# ✉️✨ Submit your Results here!", elem_classes="markdown-text")
307
-
308
- # with gr.Row():
309
- # with gr.Column():
310
- # model_name_textbox = gr.Textbox(label="Model name")
311
- # revision_name_textbox = gr.Textbox(label="Revision commit", placeholder="main")
312
- # model_type = gr.Dropdown(
313
- # choices=[t.to_str(" : ") for t in ModelType if t != ModelType.Unknown],
314
- # label="Model type",
315
- # multiselect=False,
316
- # value=None,
317
- # interactive=True,
318
- # )
319
-
320
- # with gr.Column():
321
- # precision = gr.Dropdown(
322
- # choices=[i.value.name for i in Precision if i != Precision.Unknown],
323
- # label="Precision",
324
- # multiselect=False,
325
- # value="float16",
326
- # interactive=True,
327
- # )
328
- # weight_type = gr.Dropdown(
329
- # choices=[i.value.name for i in WeightType],
330
- # label="Weights type",
331
- # multiselect=False,
332
- # value="Original",
333
- # interactive=True,
334
- # )
335
- # base_model_name_textbox = gr.Textbox(label="Base model (for delta or adapter weights)")
336
-
337
- with gr.Accordion("Submit a prediction files for evaluation"):
338
- with gr.Row():
339
- with gr.Column():
340
- method_name_textbox = gr.Textbox(label="Method name")
341
- # llama, phi
342
- # model_family_radio = gr.Radio(["llama", "phi"], value="llama", label="Model family")
343
- # forget_rate_radio = gr.Radio(["1%", "5%", "10%"], value="10%", label="Forget rate")
344
- url_textbox = gr.Textbox(label="Url to model information")
345
- with gr.Column():
346
- organisation = gr.Textbox(label="Organisation")
347
- mail = gr.Textbox(label="Contact email")
348
- file_output = gr.File()
349
-
350
- submit_button = gr.Button("Submit Eval")
351
- submission_result = gr.Markdown()
352
- submit_button.click(
353
- add_new_eval,
354
- [
355
- method_name_textbox,
356
- # model_family_radio,
357
- # forget_rate_radio,
358
- url_textbox,
359
- file_output,
360
- organisation,
361
- mail,
362
- ],
363
- submission_result,
364
  )
365
 
366
- # submit_button = gr.Button("Submit Eval")
367
- # submission_result = gr.Markdown()
368
- # submit_button.click(
369
- # add_new_eval,
370
- # [
371
- # model_name_textbox,
372
- # base_model_name_textbox,
373
- # revision_name_textbox,
374
- # precision,
375
- # weight_type,
376
- # model_type,
377
- # ],
378
- # submission_result,
379
- # )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
380
 
381
- with gr.Row():
382
- with gr.Accordion("📙 Citation", open=False):
383
- citation_button = gr.Textbox(
384
- value=CITATION_BUTTON_TEXT,
385
- label=CITATION_BUTTON_LABEL,
386
- lines=20,
387
- elem_id="citation-button",
388
- show_copy_button=True,
389
- )
390
 
 
391
  scheduler = BackgroundScheduler()
392
- scheduler.add_job(restart_space, "interval", seconds=1800)
393
  scheduler.start()
394
- demo.queue(default_concurrency_limit=40).launch()
 
 
1
  import gradio as gr
2
  import pandas as pd
3
+ import os
4
  from apscheduler.schedulers.background import BackgroundScheduler
5
+ from huggingface_hub import HfApi
6
+ from uploads import add_new_eval
7
+
8
+ CITATION_BUTTON_LABEL = "Copy the following snippet to cite these results"
9
+ CITATION_BUTTON_TEXT = r"""@inproceedings{iltur-2024,
10
+ title = "IL-TUR: Benchmark for Indian Legal Text Understanding and Reasoning",
11
+ author = "Joshi, Abhinav and Paul, Shaunak Sharma, Akshat and Goyal, Pawan and Ghosh, Saptarshi and Modi, Ashutosh",
12
+ booktitle = "Proceedings of the 62st Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)",
13
+ month = aug,
14
+ year = "2024",
15
+ address = "Bangkok, Thailand",
16
+ publisher = "Association for Computational Linguistics",
17
+ }
18
+ }"""
19
+
20
+ api = HfApi()
21
+ TOKEN = os.environ.get("TOKEN", None)
22
+ LEADERBOARD_PATH = f"Exploration-lab/IL-TUR-Leaderboard"
 
 
 
 
 
 
 
 
 
23
 
24
 
25
  def restart_space():
26
+ api.restart_space(repo_id=LEADERBOARD_PATH, token=TOKEN)
27
+
28
+
29
+ # Function to load data from a given CSV file
30
+ def baseline_load_data(tasks):
31
+ # version = version.replace("%", "p")
32
+ file_path = f"submissions/baseline/baseline.csv" # Replace with your file paths
33
+ df = pd.read_csv(file_path)
34
+
35
+ # we only want specific columns and in a specific order
36
+
37
+ column_names = [
38
+ "Method",
39
+ "Submitted By",
40
+ "L-NER",
41
+ "RR",
42
+ "CJPE",
43
+ "BAIL",
44
+ "LSI",
45
+ "PCR",
46
+ "SUMM",
47
+ "Average",
48
+ ]
49
+ if tasks is None:
50
+ breakpoint()
51
+ # based on the tasks, remove the columns that are not needed
52
+ if "L-NER" not in tasks:
53
+ column_names.remove("L-NER")
54
+ if "RR" not in tasks:
55
+ column_names.remove("RR")
56
+ if "CJPE" not in tasks:
57
+ column_names.remove("CJPE")
58
+ if "BAIL" not in tasks:
59
+ column_names.remove("BAIL")
60
+ if "LSI" not in tasks:
61
+ column_names.remove("LSI")
62
+ if "PCR" not in tasks:
63
+ column_names.remove("PCR")
64
+ if "SUMM" not in tasks:
65
+ column_names.remove("SUMM")
66
+
67
+ df = df[column_names]
68
+ df = df.sort_values(by="Average", ascending=False)
69
+ df = df.drop_duplicates(subset=["Method"], keep="first")
70
+
 
 
 
 
 
 
 
 
 
 
 
71
  return df
72
 
73
 
74
+ def load_data(tasks):
75
+ baseline_df = baseline_load_data(tasks)
76
 
77
+ return baseline_df
78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
 
80
+ # Function for searching in the leaderboard
81
+ def search_leaderboard(df, query):
82
+ if query == "":
83
+ return df
84
+ else:
85
+ return df[df["Method"].str.contains(query)]
86
 
87
 
88
+ # Function to change the version of the leaderboard
89
+ def change_version(tasks):
90
+ new_df = load_data(tasks)
91
+ return new_df
 
 
 
 
92
 
 
 
 
93
 
94
+ # Initialize Gradio app
95
+ demo = gr.Blocks()
 
 
96
 
97
+ with demo:
98
+ gr.Markdown(
99
+ """
100
+ ## 🥇 IL-TUR Leaderboard
101
+ Legal systems worldwide are inundated with exponential growth in cases and documents. There is an imminent need to develop NLP and ML techniques for automatically processing and understanding legal documents to streamline the legal system. However, evaluating and comparing various NLP models designed specifically for the legal domain is challenging. This paper addresses this challenge by proposing IL-TUR: Benchmark for Indian Legal Text Understanding and Reasoning. IL-TUR contains monolingual (English, Hindi) and multi-lingual (9 Indian languages) domain-specific tasks that address different aspects of the legal system from the point of view of understanding and reasoning over Indian legal documents. We present baseline models (including LLM-based) for each task, outlining the gap between models and the ground truth. We will release a public leaderboard where the research community can upload and compare legal text understanding systems on various metrics, thus fostering research in the legal domain.
102
+ Read more at [https://exploration-lab.github.io/IL-TUR/](https://exploration-lab.github.io/IL-TUR/).
103
+ """
104
+ )
105
 
106
+ with gr.Row():
107
+ with gr.Accordion("📙 Citation", open=False):
108
+ citation_button = gr.Textbox(
109
+ value=CITATION_BUTTON_TEXT,
110
+ label=CITATION_BUTTON_LABEL,
111
+ elem_id="citation-button",
112
+ show_copy_button=True,
113
+ ) # .style(show_copy_button=True)
114
 
115
+ with gr.Tabs():
116
+ with gr.TabItem("Leaderboard"):
 
 
117
 
 
 
118
  with gr.Row():
119
+ tasks_checkbox = gr.CheckboxGroup(
120
+ label="Select Tasks",
121
+ choices=["L-NER", "RR", "CJPE", "BAIL", "LSI", "PCR", "SUMM"],
122
+ value=["L-NER", "RR", "CJPE", "BAIL", "LSI", "PCR", "SUMM"],
123
+ )
124
+
125
+ with gr.Row():
126
+ search_bar = gr.Textbox(
127
+ placeholder="Search for methods...",
128
+ show_label=False,
129
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
 
131
  leaderboard_table = gr.components.Dataframe(
132
+ value=load_data(
133
+ # "baseline",
134
+ ["L-NER", "RR", "CJPE", "BAIL", "LSI", "PCR", "SUMM"],
135
+ ),
136
+ interactive=True,
137
  visible=True,
138
  )
139
 
140
+ # version_dropdown.change(
141
+ # change_version,
142
+ # inputs=[model_dropdown, version_dropdown, tasks_checkbox],
143
+ # outputs=leaderboard_table,
144
+ # )
145
+
146
+ # model_dropdown.change(
147
+ # change_version,
148
+ # inputs=[model_dropdown, version_dropdown, tasks_checkbox],
149
+ # outputs=leaderboard_table,
150
+ # )
151
+
152
+ search_bar.change(
153
+ search_leaderboard,
154
+ inputs=[
155
+ leaderboard_table,
156
  search_bar,
157
+ # tasks_checkbox
158
  ],
159
+ outputs=leaderboard_table,
160
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
 
162
+ tasks_checkbox.change(
163
+ change_version,
164
+ inputs=[tasks_checkbox],
165
+ outputs=leaderboard_table,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
  )
167
 
168
+ with gr.Accordion("Submit a new model for evaluation"):
169
+ with gr.Row():
170
+ with gr.Column():
171
+ method_name_textbox = gr.Textbox(label="Method name")
172
+ url_textbox = gr.Textbox(label="Url to model information")
173
+ with gr.Column():
174
+ organisation = gr.Textbox(label="Organisation")
175
+ mail = gr.Textbox(label="Contact email")
176
+ file_output = gr.File()
177
+
178
+ submit_button = gr.Button("Submit Eval")
179
+ submission_result = gr.Markdown()
180
+ submit_button.click(
181
+ add_new_eval,
182
+ [
183
+ method_name_textbox,
184
+ url_textbox,
185
+ file_output,
186
+ organisation,
187
+ mail,
188
+ ],
189
+ submission_result,
190
+ )
191
+
192
+ gr.Markdown(
193
+ """
194
+ ## Quick Links
195
+
196
+ - [**Website**](https://exploration-lab.github.io/IL-TUR): The landing page for IL-TUR
197
+ - [**arXiv Paper**](https://arxiv.org/abs/2307.05260): Detailed information about the IL-TUR dataset and its significance in unlearning tasks.
198
+ - [**GitHub Repository**](https://github.com/exploration-lab/IL-TUR): Access the source code, fine-tuning scripts, and additional resources for the IL-TUR dataset.
199
+ - [**Dataset on Hugging Face**](https://huggingface.co/datasets/Exploration-Lab/IL-TUR): Direct link to download the IL-TUR dataset.
200
+ - [**Leaderboard on Hugging Face Spaces**](https://huggingface.co/spaces/Exploration-Lab/IL-TUR_leaderboard): Current rankings and submissions for the IL-TUR dataset challenges.
201
+
202
+ ## Loading the Dataset
203
+
204
+ To load the dataset, use the following code:
205
+
206
+ ```python
207
+ from datasets import load_dataset
208
+ dataset = load_dataset("Exploration-Lab/IL-TUR","<task_name>")
209
+ ```
210
+
211
+
212
+ """
213
+ )
214
 
215
+ # scheduler = BackgroundScheduler()
216
+ # scheduler.add_job(restart_space, "interval", seconds=1800)
217
+ # scheduler.start()
218
+ # demo.queue(default_concurrency_limit=40).launch()
 
 
 
 
 
219
 
220
+ # demo.launch()
221
  scheduler = BackgroundScheduler()
222
+ scheduler.add_job(restart_space, "interval", seconds=3600)
223
  scheduler.start()
224
+ demo.launch(debug=True)
pyproject.toml DELETED
@@ -1,13 +0,0 @@
1
- [tool.ruff]
2
- # Enable pycodestyle (`E`) and Pyflakes (`F`) codes by default.
3
- select = ["E", "F"]
4
- ignore = ["E501"] # line too long (black is taking care of this)
5
- line-length = 119
6
- fixable = ["A", "B", "C", "D", "E", "F", "G", "I", "N", "Q", "S", "T", "W", "ANN", "ARG", "BLE", "COM", "DJ", "DTZ", "EM", "ERA", "EXE", "FBT", "ICN", "INP", "ISC", "NPY", "PD", "PGH", "PIE", "PL", "PT", "PTH", "PYI", "RET", "RSE", "RUF", "SIM", "SLF", "TCH", "TID", "TRY", "UP", "YTT"]
7
-
8
- [tool.isort]
9
- profile = "black"
10
- line_length = 119
11
-
12
- [tool.black]
13
- line-length = 119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,18 +1,7 @@
1
- APScheduler==3.10.1
2
- black==23.11.0
3
- click==8.1.3
4
  datasets==2.14.5
5
- gradio==4.4.0
6
- gradio_client==0.7.0
7
- huggingface-hub>=0.18.0
8
- matplotlib==3.7.1
9
  numpy==1.24.2
10
- pandas==2.0.0
11
- python-dateutil==2.8.2
12
- requests==2.28.2
13
- tqdm==4.65.0
14
- transformers==4.35.2
15
- tokenizers>=0.15.0
16
- git+https://github.com/EleutherAI/lm-evaluation-harness.git@b281b0921b636bc36ad05c0b0b0763bd6dd43463#egg=lm-eval
17
- accelerate==0.24.1
18
- sentencepiece
 
1
+ seaborn
2
+ scipy
 
3
  datasets==2.14.5
4
+ gradio==4.3.0
5
+ huggingface-hub==0.18.0
 
 
6
  numpy==1.24.2
7
+ APScheduler==3.10.1
 
 
 
 
 
 
 
 
src/about.py DELETED
@@ -1,56 +0,0 @@
1
- from dataclasses import dataclass
2
- from enum import Enum
3
-
4
-
5
- @dataclass
6
- class Task:
7
- benchmark: str
8
- metric: str
9
- col_name: str
10
-
11
-
12
- # Select your tasks here
13
- # ---------------------------------------------------
14
- class Tasks(Enum):
15
- # task_key in the json file, metric_key in the json file, name to display in the leaderboard
16
- task0 = Task("anli_r1", "acc", "Legal Named Entity Recognition (L-NER)")
17
- task1 = Task("logiqa", "acc_norm", "Rhetorical Role Prediction (RR)")
18
- task2 = Task("logiqa", "acc_norm", "Court Judgment Prediction and Explanation (CJPE)")
19
- task3 = Task("logiqa", "acc_norm", "Bail Prediction (BAIL)")
20
- task4 = Task("logiqa", "acc_norm", "Legal Statute Identification (LSI)")
21
- task5 = Task("logiqa", "acc_norm", "Prior Case Retrieval (PCR)")
22
- task6 = Task("logiqa", "acc_norm", "Summarization (SUMM)")
23
-
24
-
25
- # ---------------------------------------------------
26
-
27
-
28
- NUM_FEWSHOT = 0 # Change with your few shot
29
- # ---------------------------------------------------
30
-
31
-
32
- # Your leaderboard name
33
- TITLE = """<h1 align="center" id="space-title">IL-TUR Leaderboard</h1>"""
34
-
35
- # What does your leaderboard evaluate?
36
- INTRODUCTION_TEXT = """
37
- """
38
-
39
- # Which evaluations are you running? how can people reproduce what you have?
40
- LLM_BENCHMARKS_TEXT = f"""
41
- ## How it works
42
-
43
- ## Reproducibility
44
- To reproduce our results, here is the commands you can run:
45
-
46
- """
47
-
48
- EVALUATION_QUEUE_TEXT = """
49
- We encourage submissions for the IL-TUR leaderboard. The leaderboard is open to all researchers and practitioners.
50
-
51
- Every task has its own leaderboard, and researchers can submit their results for any task. We also encourage submissions for multiple tasks.
52
- """
53
-
54
- CITATION_BUTTON_LABEL = "Copy the following snippet to cite these results"
55
- CITATION_BUTTON_TEXT = r"""
56
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/display/css_html_js.py DELETED
@@ -1,105 +0,0 @@
1
- custom_css = """
2
-
3
- .markdown-text {
4
- font-size: 16px !important;
5
- }
6
-
7
- #models-to-add-text {
8
- font-size: 18px !important;
9
- }
10
-
11
- #citation-button span {
12
- font-size: 16px !important;
13
- }
14
-
15
- #citation-button textarea {
16
- font-size: 16px !important;
17
- }
18
-
19
- #citation-button > label > button {
20
- margin: 6px;
21
- transform: scale(1.3);
22
- }
23
-
24
- #leaderboard-table {
25
- margin-top: 15px
26
- }
27
-
28
- #leaderboard-table-lite {
29
- margin-top: 15px
30
- }
31
-
32
- #search-bar-table-box > div:first-child {
33
- background: none;
34
- border: none;
35
- }
36
-
37
- #search-bar {
38
- padding: 0px;
39
- }
40
-
41
- /* Limit the width of the first AutoEvalColumn so that names don't expand too much */
42
- table td:first-child,
43
- table th:first-child {
44
- max-width: 400px;
45
- overflow: auto;
46
- white-space: nowrap;
47
- }
48
-
49
- .tab-buttons button {
50
- font-size: 20px;
51
- }
52
-
53
- #scale-logo {
54
- border-style: none !important;
55
- box-shadow: none;
56
- display: block;
57
- margin-left: auto;
58
- margin-right: auto;
59
- max-width: 600px;
60
- }
61
-
62
- #scale-logo .download {
63
- display: none;
64
- }
65
- #filter_type{
66
- border: 0;
67
- padding-left: 0;
68
- padding-top: 0;
69
- }
70
- #filter_type label {
71
- display: flex;
72
- }
73
- #filter_type label > span{
74
- margin-top: var(--spacing-lg);
75
- margin-right: 0.5em;
76
- }
77
- #filter_type label > .wrap{
78
- width: 103px;
79
- }
80
- #filter_type label > .wrap .wrap-inner{
81
- padding: 2px;
82
- }
83
- #filter_type label > .wrap .wrap-inner input{
84
- width: 1px
85
- }
86
- #filter-columns-type{
87
- border:0;
88
- padding:0.5;
89
- }
90
- #filter-columns-size{
91
- border:0;
92
- padding:0.5;
93
- }
94
- #box-filter > .form{
95
- border: 0
96
- }
97
- """
98
-
99
- get_window_url_params = """
100
- function(url_params) {
101
- const params = new URLSearchParams(window.location.search);
102
- url_params = Object.fromEntries(params);
103
- return url_params;
104
- }
105
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/display/formatting.py DELETED
@@ -1,27 +0,0 @@
1
- def model_hyperlink(link, model_name):
2
- return f'<a target="_blank" href="{link}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{model_name}</a>'
3
-
4
-
5
- def make_clickable_model(model_name):
6
- link = f"https://huggingface.co/{model_name}"
7
- return model_hyperlink(link, model_name)
8
-
9
-
10
- def styled_error(error):
11
- return f"<p style='color: red; font-size: 20px; text-align: center;'>{error}</p>"
12
-
13
-
14
- def styled_warning(warn):
15
- return f"<p style='color: orange; font-size: 20px; text-align: center;'>{warn}</p>"
16
-
17
-
18
- def styled_message(message):
19
- return f"<p style='color: green; font-size: 20px; text-align: center;'>{message}</p>"
20
-
21
-
22
- def has_no_nan_values(df, columns):
23
- return df[columns].notna().all(axis=1)
24
-
25
-
26
- def has_nan_values(df, columns):
27
- return df[columns].isna().any(axis=1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/display/utils.py DELETED
@@ -1,144 +0,0 @@
1
- from dataclasses import dataclass, make_dataclass
2
- from enum import Enum
3
-
4
- import pandas as pd
5
-
6
- from src.about import Tasks
7
-
8
-
9
- def fields(raw_class):
10
- return [v for k, v in raw_class.__dict__.items() if k[:2] != "__" and k[-2:] != "__"]
11
-
12
-
13
- # These classes are for user facing column names,
14
- # to avoid having to change them all around the code
15
- # when a modif is needed
16
- @dataclass
17
- class ColumnContent:
18
- name: str
19
- type: str
20
- displayed_by_default: bool
21
- hidden: bool = False
22
- never_hidden: bool = False
23
-
24
-
25
- ## Leaderboard columns
26
- auto_eval_column_dict = []
27
- # Init
28
- # auto_eval_column_dict.append(["model_type_symbol", ColumnContent, ColumnContent("T", "str", True, never_hidden=True)])
29
- # auto_eval_column_dict.append(["team", ColumnContent, ColumnContent("Team", "markdown", True, never_hidden=True)])
30
- # auto_eval_column_dict.append(["team_name", ColumnContent, ColumnContent("team_name", "str", True)])
31
- # Scores
32
- auto_eval_column_dict.append(["eval_name", ColumnContent, ColumnContent("eval_name", "str", True)])
33
- auto_eval_column_dict.append(["average", ColumnContent, ColumnContent("Average ⬆️", "number", True)])
34
- for task in Tasks:
35
- auto_eval_column_dict.append([task.name, ColumnContent, ColumnContent(task.value.col_name, "number", True)])
36
- # # Model information
37
- # auto_eval_column_dict.append(["model_type", ColumnContent, ColumnContent("Type", "str", False)])
38
- # auto_eval_column_dict.append(["architecture", ColumnContent, ColumnContent("Architecture", "str", False)])
39
- # auto_eval_column_dict.append(["weight_type", ColumnContent, ColumnContent("Weight type", "str", False, True)])
40
- # auto_eval_column_dict.append(["precision", ColumnContent, ColumnContent("Precision", "str", False)])
41
- # auto_eval_column_dict.append(["license", ColumnContent, ColumnContent("Hub License", "str", False)])
42
- # auto_eval_column_dict.append(["params", ColumnContent, ColumnContent("#Params (B)", "number", False)])
43
- # auto_eval_column_dict.append(["likes", ColumnContent, ColumnContent("Hub ❤️", "number", False)])
44
- # auto_eval_column_dict.append(["still_on_hub", ColumnContent, ColumnContent("Available on the hub", "bool", False)])
45
- # auto_eval_column_dict.append(["revision", ColumnContent, ColumnContent("Model sha", "str", False, False)])
46
-
47
- # We use make dataclass to dynamically fill the scores from Tasks
48
- AutoEvalColumn = make_dataclass("AutoEvalColumn", auto_eval_column_dict, frozen=True)
49
-
50
-
51
- ## For the queue columns in the submission tab
52
- @dataclass(frozen=True)
53
- class EvalQueueColumn: # Queue column
54
- model = ColumnContent("model", "markdown", True)
55
- revision = ColumnContent("revision", "str", True)
56
- private = ColumnContent("private", "bool", True)
57
- precision = ColumnContent("precision", "str", True)
58
- weight_type = ColumnContent("weight_type", "str", "Original")
59
- status = ColumnContent("status", "str", True)
60
-
61
-
62
- ## All the model information that we might need
63
- @dataclass
64
- class ModelDetails:
65
- name: str
66
- display_name: str = ""
67
- symbol: str = "" # emoji
68
-
69
-
70
- class ModelType(Enum):
71
- PT = ModelDetails(name="pretrained", symbol="🟢")
72
- FT = ModelDetails(name="fine-tuned", symbol="🔶")
73
- IFT = ModelDetails(name="instruction-tuned", symbol="⭕")
74
- RL = ModelDetails(name="RL-tuned", symbol="🟦")
75
- Unknown = ModelDetails(name="", symbol="?")
76
-
77
- def to_str(self, separator=" "):
78
- return f"{self.value.symbol}{separator}{self.value.name}"
79
-
80
- @staticmethod
81
- def from_str(type):
82
- if "fine-tuned" in type or "🔶" in type:
83
- return ModelType.FT
84
- if "pretrained" in type or "🟢" in type:
85
- return ModelType.PT
86
- if "RL-tuned" in type or "🟦" in type:
87
- return ModelType.RL
88
- if "instruction-tuned" in type or "⭕" in type:
89
- return ModelType.IFT
90
- return ModelType.Unknown
91
-
92
-
93
- class WeightType(Enum):
94
- Adapter = ModelDetails("Adapter")
95
- Original = ModelDetails("Original")
96
- Delta = ModelDetails("Delta")
97
-
98
-
99
- class Precision(Enum):
100
- float16 = ModelDetails("float16")
101
- bfloat16 = ModelDetails("bfloat16")
102
- float32 = ModelDetails("float32")
103
- # qt_8bit = ModelDetails("8bit")
104
- # qt_4bit = ModelDetails("4bit")
105
- # qt_GPTQ = ModelDetails("GPTQ")
106
- Unknown = ModelDetails("?")
107
-
108
- def from_str(precision):
109
- if precision in ["torch.float16", "float16"]:
110
- return Precision.float16
111
- if precision in ["torch.bfloat16", "bfloat16"]:
112
- return Precision.bfloat16
113
- if precision in ["float32"]:
114
- return Precision.float32
115
- # if precision in ["8bit"]:
116
- # return Precision.qt_8bit
117
- # if precision in ["4bit"]:
118
- # return Precision.qt_4bit
119
- # if precision in ["GPTQ", "None"]:
120
- # return Precision.qt_GPTQ
121
- return Precision.Unknown
122
-
123
-
124
- # Column selection
125
- COLS = [c.name for c in fields(AutoEvalColumn) if not c.hidden]
126
- TYPES = [c.type for c in fields(AutoEvalColumn) if not c.hidden]
127
- COLS_LITE = [c.name for c in fields(AutoEvalColumn) if c.displayed_by_default and not c.hidden]
128
- TYPES_LITE = [c.type for c in fields(AutoEvalColumn) if c.displayed_by_default and not c.hidden]
129
-
130
- EVAL_COLS = [c.name for c in fields(EvalQueueColumn)]
131
- EVAL_TYPES = [c.type for c in fields(EvalQueueColumn)]
132
-
133
- BENCHMARK_COLS = [t.value.col_name for t in Tasks]
134
-
135
- NUMERIC_INTERVALS = {
136
- "?": pd.Interval(-1, 0, closed="right"),
137
- "~1.5": pd.Interval(0, 2, closed="right"),
138
- "~3": pd.Interval(2, 4, closed="right"),
139
- "~7": pd.Interval(4, 9, closed="right"),
140
- "~13": pd.Interval(9, 20, closed="right"),
141
- "~35": pd.Interval(20, 45, closed="right"),
142
- "~60": pd.Interval(45, 70, closed="right"),
143
- "70+": pd.Interval(70, 10000, closed="right"),
144
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/envs.py DELETED
@@ -1,25 +0,0 @@
1
- import os
2
-
3
- from huggingface_hub import HfApi
4
-
5
- # Info to change for your repository
6
- # ----------------------------------
7
- TOKEN = os.environ.get("TOKEN") # A read/write token for your org
8
-
9
- OWNER = "Exploration-Lab" # Change to your org - don't forget to create a results and request dataset, with the correct format!
10
- # ----------------------------------
11
-
12
- REPO_ID = f"{OWNER}/IL-TUR-Leaderboard"
13
- QUEUE_REPO = f"{OWNER}/IL-TUR-Leaderboard-requests"
14
- RESULTS_REPO = f"{OWNER}/IL-TUR-Leaderboard-results"
15
-
16
- # If you setup a cache later, just change HF_HOME
17
- CACHE_PATH=os.getenv("HF_HOME", ".")
18
-
19
- # Local caches
20
- EVAL_REQUESTS_PATH = os.path.join(CACHE_PATH, "eval-queue")
21
- EVAL_RESULTS_PATH = os.path.join(CACHE_PATH, "eval-results")
22
- EVAL_REQUESTS_PATH_BACKEND = os.path.join(CACHE_PATH, "eval-queue-bk")
23
- EVAL_RESULTS_PATH_BACKEND = os.path.join(CACHE_PATH, "eval-results-bk")
24
-
25
- API = HfApi(token=TOKEN)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/leaderboard/read_evals.py DELETED
@@ -1,216 +0,0 @@
1
- import glob
2
- import json
3
- import math
4
- import os
5
- from dataclasses import dataclass
6
-
7
- import dateutil
8
- import numpy as np
9
-
10
- from src.display.formatting import make_clickable_model
11
- from src.display.utils import AutoEvalColumn, ModelType, Tasks, Precision, WeightType
12
- from src.submission.check_validity import is_model_on_hub
13
-
14
-
15
- @dataclass
16
- class EvalResult:
17
- """Represents one full evaluation. Built from a combination of the result and request file for a given run."""
18
-
19
- eval_name: str # org_model_precision (uid)
20
- full_model: str # org/model (path on hub)
21
- org: str
22
- model: str
23
- revision: str # commit hash, "" if main
24
- results: dict
25
- precision: Precision = Precision.Unknown
26
- model_type: ModelType = ModelType.Unknown # Pretrained, fine tuned, ...
27
- weight_type: WeightType = WeightType.Original # Original or Adapter
28
- architecture: str = "Unknown"
29
- license: str = "?"
30
- likes: int = 0
31
- num_params: int = 0
32
- date: str = "" # submission date of request file
33
- still_on_hub: bool = False
34
-
35
- @classmethod
36
- def init_from_json_file(self, json_filepath):
37
- """Inits the result from the specific model result file"""
38
- with open(json_filepath) as fp:
39
- data = json.load(fp)
40
-
41
- config = data.get("config")
42
-
43
- # Precision
44
- precision = Precision.from_str(config.get("model_dtype"))
45
-
46
- # Get model and org
47
- org_and_model = config.get("model_name", config.get("model_args", None))
48
- org_and_model = org_and_model.split("/", 1)
49
-
50
- if len(org_and_model) == 1:
51
- org = None
52
- model = org_and_model[0]
53
- result_key = f"{model}_{precision.value.name}"
54
- else:
55
- org = org_and_model[0]
56
- model = org_and_model[1]
57
- result_key = f"{org}_{model}_{precision.value.name}"
58
- full_model = "/".join(org_and_model)
59
-
60
- still_on_hub, _, model_config = is_model_on_hub(
61
- full_model, config.get("model_sha", "main"), trust_remote_code=True, test_tokenizer=False
62
- )
63
- architecture = "?"
64
- if model_config is not None:
65
- architectures = getattr(model_config, "architectures", None)
66
- if architectures:
67
- architecture = ";".join(architectures)
68
-
69
- # Extract results available in this file (some results are split in several files)
70
- results = {}
71
- for task in Tasks:
72
- task = task.value
73
-
74
- # We average all scores of a given metric (not all metrics are present in all files)
75
- accs = np.array([v.get(task.metric, None) for k, v in data["results"].items() if task.benchmark == k])
76
- if accs.size == 0 or any([acc is None for acc in accs]):
77
- continue
78
-
79
- mean_acc = np.mean(accs) * 100.0
80
- results[task.benchmark] = mean_acc
81
-
82
- return self(
83
- eval_name=result_key,
84
- full_model=full_model,
85
- org=org,
86
- model=model,
87
- results=results,
88
- precision=precision,
89
- revision=config.get("model_sha", ""),
90
- still_on_hub=still_on_hub,
91
- architecture=architecture,
92
- )
93
-
94
- def update_with_request_file(self, requests_path):
95
- """Finds the relevant request file for the current model and updates info with it"""
96
- request_file = get_request_file_for_model(requests_path, self.full_model, self.precision.value.name)
97
-
98
- try:
99
- with open(request_file, "r") as f:
100
- request = json.load(f)
101
- self.model_type = ModelType.from_str(request.get("model_type", ""))
102
- self.weight_type = WeightType[request.get("weight_type", "Original")]
103
- self.license = request.get("license", "?")
104
- self.likes = request.get("likes", 0)
105
- self.num_params = request.get("params", 0)
106
- self.date = request.get("submitted_time", "")
107
- except Exception:
108
- print(
109
- f"Could not find request file for {self.org}/{self.model} with precision {self.precision.value.name}"
110
- )
111
-
112
- def to_dict(self):
113
- """Converts the Eval Result to a dict compatible with our dataframe display"""
114
-
115
- average = sum([v for v in self.results.values() if v is not None]) / len(Tasks)
116
-
117
- data_dict = {
118
- "eval_name": self.eval_name, # not a column, just a save name,
119
- # AutoEvalColumn.precision.name: self.precision.value.name,
120
- # AutoEvalColumn.team_name.name: self.team_name.value.name,
121
- # AutoEvalColumn.weight_type.name: self.weight_type.value.name,
122
- # AutoEvalColumn.architecture.name: self.architecture,
123
- # AutoEvalColumn.model.name: make_clickable_model(self.full_model),
124
- # AutoEvalColumn.revision.name: self.revision,
125
- AutoEvalColumn.average.name: average,
126
- # AutoEvalColumn.license.name: self.license,
127
- # AutoEvalColumn.likes.name: self.likes,
128
- # AutoEvalColumn.params.name: self.num_params,
129
- # AutoEvalColumn.still_on_hub.name: self.still_on_hub,
130
- }
131
-
132
- for task in Tasks:
133
- data_dict[task.value.col_name] = self.results[task.value.benchmark]
134
-
135
- # data_dict = {
136
- # "eval_name": self.eval_name, # not a column, just a save name,
137
- # # AutoEvalColumn.precision.name: self.precision.value.name,
138
- # AutoEvalColumn.model_type.name: self.model_type.value.name,
139
- # AutoEvalColumn.model_type_symbol.name: self.model_type.value.symbol,
140
- # # AutoEvalColumn.weight_type.name: self.weight_type.value.name,
141
- # # AutoEvalColumn.architecture.name: self.architecture,
142
- # # AutoEvalColumn.model.name: make_clickable_model(self.full_model),
143
- # # AutoEvalColumn.revision.name: self.revision,
144
- # AutoEvalColumn.average.name: average,
145
- # # AutoEvalColumn.license.name: self.license,
146
- # # AutoEvalColumn.likes.name: self.likes,
147
- # # AutoEvalColumn.params.name: self.num_params,
148
- # # AutoEvalColumn.still_on_hub.name: self.still_on_hub,
149
- # }
150
-
151
- return data_dict
152
-
153
-
154
- def get_request_file_for_model(requests_path, model_name, precision):
155
- """Selects the correct request file for a given model. Only keeps runs tagged as FINISHED"""
156
- request_files = os.path.join(
157
- requests_path,
158
- f"{model_name}_eval_request_*.json",
159
- )
160
- request_files = glob.glob(request_files)
161
-
162
- # Select correct request file (precision)
163
- request_file = ""
164
- request_files = sorted(request_files, reverse=True)
165
- for tmp_request_file in request_files:
166
- with open(tmp_request_file, "r") as f:
167
- req_content = json.load(f)
168
- if (
169
- req_content["status"]
170
- in ["FINISHED"]
171
- # and req_content["precision"] == precision.split(".")[-1]
172
- ):
173
- request_file = tmp_request_file
174
- return request_file
175
-
176
-
177
- def get_raw_eval_results(results_path: str, requests_path: str) -> list[EvalResult]:
178
- """From the path of the results folder root, extract all needed info for results"""
179
- model_result_filepaths = []
180
-
181
- for root, _, files in os.walk(results_path):
182
- # We should only have json files in model results
183
- if len(files) == 0 or any([not f.endswith(".json") for f in files]):
184
- continue
185
-
186
- # Sort the files by date
187
- try:
188
- files.sort(key=lambda x: x.removesuffix(".json").removeprefix("results_")[:-7])
189
- except dateutil.parser._parser.ParserError:
190
- files = [files[-1]]
191
-
192
- for file in files:
193
- model_result_filepaths.append(os.path.join(root, file))
194
-
195
- eval_results = {}
196
- for model_result_filepath in model_result_filepaths:
197
- # Creation of result
198
- eval_result = EvalResult.init_from_json_file(model_result_filepath)
199
- eval_result.update_with_request_file(requests_path)
200
-
201
- # Store results of same eval together
202
- eval_name = eval_result.eval_name
203
- if eval_name in eval_results.keys():
204
- eval_results[eval_name].results.update({k: v for k, v in eval_result.results.items() if v is not None})
205
- else:
206
- eval_results[eval_name] = eval_result
207
-
208
- results = []
209
- for v in eval_results.values():
210
- try:
211
- v.to_dict() # we test if the dict version is complete
212
- results.append(v)
213
- except KeyError: # not all eval values present
214
- continue
215
-
216
- return results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/populate.py DELETED
@@ -1,60 +0,0 @@
1
- import json
2
- import os
3
-
4
- import pandas as pd
5
-
6
- from src.display.formatting import has_no_nan_values, make_clickable_model
7
- from src.display.utils import AutoEvalColumn, EvalQueueColumn
8
- from src.leaderboard.read_evals import get_raw_eval_results
9
-
10
-
11
- def get_leaderboard_df(results_path: str, requests_path: str, cols: list, benchmark_cols: list) -> pd.DataFrame:
12
- """Creates a dataframe from all the individual experiment results"""
13
- raw_data = get_raw_eval_results(results_path, requests_path)
14
- all_data_json = [v.to_dict() for v in raw_data]
15
-
16
- df = pd.DataFrame.from_records(all_data_json)
17
- # breakpoint()
18
- df = df.sort_values(by=[AutoEvalColumn.average.name], ascending=False)
19
- # df = df[cols].round(decimals=2)
20
-
21
- # filter out if any of the benchmarks have not been produced
22
- df = df[has_no_nan_values(df, benchmark_cols)]
23
- # breakpoint()
24
- return raw_data, df
25
-
26
-
27
- def get_evaluation_queue_df(save_path: str, cols: list) -> list[pd.DataFrame]:
28
- """Creates the different dataframes for the evaluation queues requestes"""
29
- entries = [entry for entry in os.listdir(save_path) if not entry.startswith(".")]
30
- all_evals = []
31
-
32
- for entry in entries:
33
- if ".json" in entry:
34
- file_path = os.path.join(save_path, entry)
35
- with open(file_path) as fp:
36
- data = json.load(fp)
37
-
38
- data[EvalQueueColumn.model.name] = make_clickable_model(data["model"])
39
- data[EvalQueueColumn.revision.name] = data.get("revision", "main")
40
-
41
- all_evals.append(data)
42
- elif ".md" not in entry:
43
- # this is a folder
44
- sub_entries = [e for e in os.listdir(f"{save_path}/{entry}") if not e.startswith(".")]
45
- for sub_entry in sub_entries:
46
- file_path = os.path.join(save_path, entry, sub_entry)
47
- with open(file_path) as fp:
48
- data = json.load(fp)
49
-
50
- data[EvalQueueColumn.model.name] = make_clickable_model(data["model"])
51
- data[EvalQueueColumn.revision.name] = data.get("revision", "main")
52
- all_evals.append(data)
53
-
54
- pending_list = [e for e in all_evals if e["status"] in ["PENDING", "RERUN"]]
55
- running_list = [e for e in all_evals if e["status"] == "RUNNING"]
56
- finished_list = [e for e in all_evals if e["status"].startswith("FINISHED") or e["status"] == "PENDING_NEW_EVAL"]
57
- df_pending = pd.DataFrame.from_records(pending_list, columns=cols)
58
- df_running = pd.DataFrame.from_records(running_list, columns=cols)
59
- df_finished = pd.DataFrame.from_records(finished_list, columns=cols)
60
- return df_finished[cols], df_running[cols], df_pending[cols]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/submission/check_validity.py DELETED
@@ -1,99 +0,0 @@
1
- import json
2
- import os
3
- import re
4
- from collections import defaultdict
5
- from datetime import datetime, timedelta, timezone
6
-
7
- import huggingface_hub
8
- from huggingface_hub import ModelCard
9
- from huggingface_hub.hf_api import ModelInfo
10
- from transformers import AutoConfig
11
- from transformers.models.auto.tokenization_auto import AutoTokenizer
12
-
13
- def check_model_card(repo_id: str) -> tuple[bool, str]:
14
- """Checks if the model card and license exist and have been filled"""
15
- try:
16
- card = ModelCard.load(repo_id)
17
- except huggingface_hub.utils.EntryNotFoundError:
18
- return False, "Please add a model card to your model to explain how you trained/fine-tuned it."
19
-
20
- # Enforce license metadata
21
- if card.data.license is None:
22
- if not ("license_name" in card.data and "license_link" in card.data):
23
- return False, (
24
- "License not found. Please add a license to your model card using the `license` metadata or a"
25
- " `license_name`/`license_link` pair."
26
- )
27
-
28
- # Enforce card content
29
- if len(card.text) < 200:
30
- return False, "Please add a description to your model card, it is too short."
31
-
32
- return True, ""
33
-
34
- def is_model_on_hub(model_name: str, revision: str, token: str = None, trust_remote_code=False, test_tokenizer=False) -> tuple[bool, str]:
35
- """Checks if the model model_name is on the hub, and whether it (and its tokenizer) can be loaded with AutoClasses."""
36
- try:
37
- config = AutoConfig.from_pretrained(model_name, revision=revision, trust_remote_code=trust_remote_code, token=token)
38
- if test_tokenizer:
39
- try:
40
- tk = AutoTokenizer.from_pretrained(model_name, revision=revision, trust_remote_code=trust_remote_code, token=token)
41
- except ValueError as e:
42
- return (
43
- False,
44
- f"uses a tokenizer which is not in a transformers release: {e}",
45
- None
46
- )
47
- except Exception as e:
48
- return (False, "'s tokenizer cannot be loaded. Is your tokenizer class in a stable transformers release, and correctly configured?", None)
49
- return True, None, config
50
-
51
- except ValueError:
52
- return (
53
- False,
54
- "needs to be launched with `trust_remote_code=True`. For safety reason, we do not allow these models to be automatically submitted to the leaderboard.",
55
- None
56
- )
57
-
58
- except Exception as e:
59
- return False, "was not found on hub!", None
60
-
61
-
62
- def get_model_size(model_info: ModelInfo, precision: str):
63
- """Gets the model size from the configuration, or the model name if the configuration does not contain the information."""
64
- try:
65
- model_size = round(model_info.safetensors["total"] / 1e9, 3)
66
- except (AttributeError, TypeError):
67
- return 0 # Unknown model sizes are indicated as 0, see NUMERIC_INTERVALS in app.py
68
-
69
- size_factor = 8 if (precision == "GPTQ" or "gptq" in model_info.modelId.lower()) else 1
70
- model_size = size_factor * model_size
71
- return model_size
72
-
73
- def get_model_arch(model_info: ModelInfo):
74
- """Gets the model architecture from the configuration"""
75
- return model_info.config.get("architectures", "Unknown")
76
-
77
- def already_submitted_models(requested_models_dir: str) -> set[str]:
78
- """Gather a list of already submitted models to avoid duplicates"""
79
- depth = 1
80
- file_names = []
81
- users_to_submission_dates = defaultdict(list)
82
-
83
- for root, _, files in os.walk(requested_models_dir):
84
- current_depth = root.count(os.sep) - requested_models_dir.count(os.sep)
85
- if current_depth == depth:
86
- for file in files:
87
- if not file.endswith(".json"):
88
- continue
89
- with open(os.path.join(root, file), "r") as f:
90
- info = json.load(f)
91
- file_names.append(f"{info['model']}_{info['revision']}_{info['precision']}")
92
-
93
- # Select organisation
94
- if info["model"].count("/") == 0 or "submitted_time" not in info:
95
- continue
96
- organisation, _ = info["model"].split("/")
97
- users_to_submission_dates[organisation].append(info["submitted_time"])
98
-
99
- return set(file_names), users_to_submission_dates
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/submission/submit.py DELETED
@@ -1,205 +0,0 @@
1
- import json
2
- import os
3
- from datetime import datetime, timezone
4
-
5
- from src.display.formatting import styled_error, styled_message, styled_warning
6
- from src.envs import API, EVAL_REQUESTS_PATH, TOKEN, QUEUE_REPO
7
- from src.submission.check_validity import (
8
- already_submitted_models,
9
- check_model_card,
10
- get_model_size,
11
- is_model_on_hub,
12
- )
13
-
14
- REQUESTED_MODELS = None
15
- USERS_TO_SUBMISSION_DATES = None
16
-
17
- OUT_DIR = f"{EVAL_REQUESTS_PATH}"
18
- RESULTS_PATH = f"{OUT_DIR}/evaluation.json"
19
-
20
- # def add_new_eval(
21
- # model: str,
22
- # base_model: str,
23
- # revision: str,
24
- # precision: str,
25
- # weight_type: str,
26
- # model_type: str,
27
- # ):
28
- # global REQUESTED_MODELS
29
- # global USERS_TO_SUBMISSION_DATES
30
- # if not REQUESTED_MODELS:
31
- # REQUESTED_MODELS, USERS_TO_SUBMISSION_DATES = already_submitted_models(EVAL_REQUESTS_PATH)
32
-
33
- # user_name = ""
34
- # model_path = model
35
- # if "/" in model:
36
- # user_name = model.split("/")[0]
37
- # model_path = model.split("/")[1]
38
-
39
- # precision = precision.split(" ")[0]
40
- # current_time = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
41
-
42
- # if model_type is None or model_type == "":
43
- # return styled_error("Please select a model type.")
44
-
45
- # # Does the model actually exist?
46
- # if revision == "":
47
- # revision = "main"
48
-
49
- # # Is the model on the hub?
50
- # if weight_type in ["Delta", "Adapter"]:
51
- # base_model_on_hub, error, _ = is_model_on_hub(
52
- # model_name=base_model, revision=revision, token=TOKEN, test_tokenizer=True
53
- # )
54
- # if not base_model_on_hub:
55
- # return styled_error(f'Base model "{base_model}" {error}')
56
-
57
- # if not weight_type == "Adapter":
58
- # model_on_hub, error, _ = is_model_on_hub(model_name=model, revision=revision, token=TOKEN, test_tokenizer=True)
59
- # if not model_on_hub:
60
- # return styled_error(f'Model "{model}" {error}')
61
-
62
- # # Is the model info correctly filled?
63
- # try:
64
- # model_info = API.model_info(repo_id=model, revision=revision)
65
- # except Exception:
66
- # return styled_error("Could not get your model information. Please fill it up properly.")
67
-
68
- # model_size = get_model_size(model_info=model_info, precision=precision)
69
-
70
- # # Were the model card and license filled?
71
- # try:
72
- # license = model_info.cardData["license"]
73
- # except Exception:
74
- # return styled_error("Please select a license for your model")
75
-
76
- # modelcard_OK, error_msg = check_model_card(model)
77
- # if not modelcard_OK:
78
- # return styled_error(error_msg)
79
-
80
- # # Seems good, creating the eval
81
- # print("Adding new eval")
82
-
83
- # eval_entry = {
84
- # "model": model,
85
- # "base_model": base_model,
86
- # "revision": revision,
87
- # "precision": precision,
88
- # "weight_type": weight_type,
89
- # "status": "PENDING",
90
- # "submitted_time": current_time,
91
- # "model_type": model_type,
92
- # "likes": model_info.likes,
93
- # "params": model_size,
94
- # "license": license,
95
- # "private": False,
96
- # }
97
-
98
- # # Check for duplicate submission
99
- # if f"{model}_{revision}_{precision}" in REQUESTED_MODELS:
100
- # return styled_warning("This model has been already submitted.")
101
-
102
- # print("Creating eval file")
103
- # OUT_DIR = f"{EVAL_REQUESTS_PATH}/{user_name}"
104
- # os.makedirs(OUT_DIR, exist_ok=True)
105
- # out_path = f"{OUT_DIR}/{model_path}_eval_request_False_{precision}_{weight_type}.json"
106
-
107
- # with open(out_path, "w") as f:
108
- # f.write(json.dumps(eval_entry))
109
-
110
- # print("Uploading eval file")
111
- # API.upload_file(
112
- # path_or_fileobj=out_path,
113
- # path_in_repo=out_path.split("eval-queue/")[1],
114
- # repo_id=QUEUE_REPO,
115
- # repo_type="dataset",
116
- # commit_message=f"Add {model} to eval queue",
117
- # )
118
-
119
- # # Remove the local file
120
- # os.remove(out_path)
121
-
122
- # return styled_message(
123
- # "Your request has been submitted to the evaluation queue!\nPlease wait for up to an hour for the model to show in the PENDING list."
124
- # )
125
-
126
-
127
- def format_error(msg):
128
- return f"<p style='color: red; font-size: 20px; text-align: center;'>{msg}</p>"
129
-
130
-
131
- def format_warning(msg):
132
- return f"<p style='color: orange; font-size: 20px; text-align: center;'>{msg}</p>"
133
-
134
-
135
- def format_log(msg):
136
- return f"<p style='color: green; font-size: 20px; text-align: center;'>{msg}</p>"
137
-
138
-
139
- def model_hyperlink(link, model_name):
140
- return f'<a target="_blank" href="{link}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{model_name}</a>'
141
-
142
-
143
- def input_verification(model, model_family, forget_rate, url, path_to_file, organisation, mail):
144
- for input in [model, model_family, forget_rate, url, organisation]:
145
- if input == "":
146
- return format_warning("Please fill all the fields.")
147
-
148
- # Very basic email parsing
149
- _, parsed_mail = parseaddr(mail)
150
- if not "@" in parsed_mail:
151
- return format_warning("Please provide a valid email adress.")
152
-
153
- if path_to_file is None:
154
- return format_warning("Please attach a file.")
155
-
156
- return parsed_mail
157
-
158
-
159
- def add_new_eval(
160
- model: str,
161
- model_family: str,
162
- forget_rate: str,
163
- url: str,
164
- path_to_file: str,
165
- organisation: str,
166
- mail: str,
167
- ):
168
-
169
- parsed_mail = input_verification(model, model_family, forget_rate, url, path_to_file, organisation, mail)
170
-
171
- # load the file
172
- df = pd.read_csv(path_to_file)
173
-
174
- # modify the df to include metadata
175
- df["model"] = model
176
- df["model_family"] = model_family
177
- df["forget_rate"] = forget_rate
178
- df["url"] = url
179
- df["organisation"] = organisation
180
- df["mail"] = parsed_mail
181
- df["timestamp"] = datetime.datetime.now()
182
-
183
- # upload to spaces using the hf api at
184
-
185
- path_in_repo = f"versions/{model_family}-{forget_rate.replace('%', 'p')}"
186
- file_name = f"{model}-{organisation}-{datetime.datetime.now().strftime('%Y-%m-%d')}.csv"
187
-
188
- # upload the df to spaces
189
- import io
190
-
191
- buffer = io.BytesIO()
192
- df.to_csv(buffer, index=False) # Write the DataFrame to a buffer in CSV format
193
- buffer.seek(0) # Rewind the buffer to the beginning
194
-
195
- API.upload_file(
196
- repo_id=RESULTS_PATH,
197
- path_in_repo=f"{path_in_repo}/{file_name}",
198
- path_or_fileobj=buffer,
199
- token=TOKEN,
200
- repo_type="space",
201
- )
202
-
203
- return format_log(
204
- f"Model {model} submitted by {organisation} successfully. \nPlease refresh the leaderboard, and wait a bit to see the score displayed"
205
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
submissions/.DS_Store ADDED
Binary file (6.15 kB). View file
 
submissions/baseline/baseline.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ ,index,Method,Submitted By,L-NER,RR,CJPE,BAIL,LSI,PCR,SUMM,Average
2
+ ,0,baseline,baseline,0,0,0,0,0,0,0,0
3
+ ,0,baseline2,baseline2,0,0,0,0,0,0,0,0
submissions/modify.sh ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Loop through each CSV file in the current directory
4
+ for csv_file in *.csv; do
5
+ # Check if the file is a regular file
6
+ if [ -f "$csv_file" ]; then
7
+ echo "Processing $csv_file..."
8
+
9
+ # Temporary file
10
+ temp_file=$(mktemp)
11
+
12
+ # Check if the file has a header
13
+ if head -1 "$csv_file" | grep -q "Submitted By"; then
14
+ echo "The 'Submitted By' column already exists in $csv_file."
15
+ continue
16
+ fi
17
+
18
+ # Add 'Submitted By' column header and 'Baseline' entry for each row
19
+ awk -v OFS="," 'NR==1 {print $0, "Submitted By"} NR>1 {print $0, "Baseline"}' "$csv_file" > "$temp_file"
20
+
21
+ # Move the temporary file to original file
22
+ mv "$temp_file" "$csv_file"
23
+
24
+ echo "Column 'Submitted By' added successfully with 'Baseline' entry in each row for $csv_file."
25
+ fi
26
+ done
27
+
28
+ echo "All CSV files processed."
uploads.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from email.utils import parseaddr
2
+ from huggingface_hub import HfApi
3
+ import os
4
+ import datetime
5
+ import pandas as pd
6
+
7
+
8
+ RESULTS_PATH = "Exploration-Lab/IL-TUR-Leaderboard-results"
9
+ api = HfApi()
10
+ TOKEN = os.environ.get("TOKEN", None)
11
+ YEAR_VERSION = "2024"
12
+
13
+
14
+ def format_error(msg):
15
+ return f"<p style='color: red; font-size: 20px; text-align: center;'>{msg}</p>"
16
+
17
+
18
+ def format_warning(msg):
19
+ return f"<p style='color: orange; font-size: 20px; text-align: center;'>{msg}</p>"
20
+
21
+
22
+ def format_log(msg):
23
+ return f"<p style='color: green; font-size: 20px; text-align: center;'>{msg}</p>"
24
+
25
+
26
+ def model_hyperlink(link, model_name):
27
+ return f'<a target="_blank" href="{link}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{model_name}</a>'
28
+
29
+
30
+ def input_verification(method_name, url, path_to_file, organisation, mail):
31
+ for input in [method_name, url, path_to_file, organisation, mail]:
32
+ if input == "":
33
+ return format_warning("Please fill all the fields.")
34
+
35
+ # Very basic email parsing
36
+ _, parsed_mail = parseaddr(mail)
37
+ if not "@" in parsed_mail:
38
+ return format_warning("Please provide a valid email adress.")
39
+
40
+ if path_to_file is None:
41
+ return format_warning("Please attach a file.")
42
+
43
+ return parsed_mail
44
+
45
+
46
+ def add_new_eval(
47
+ method_name: str,
48
+ url: str,
49
+ path_to_file: str,
50
+ organisation: str,
51
+ mail: str,
52
+ ):
53
+
54
+ parsed_mail = input_verification(
55
+ method_name,
56
+ url,
57
+ path_to_file,
58
+ organisation,
59
+ mail,
60
+ )
61
+
62
+ # load the file
63
+ df = pd.read_csv(path_to_file)
64
+
65
+ # modify the df to include metadata
66
+ df["method_name"] = method_name
67
+ df["url"] = url
68
+ df["organisation"] = organisation
69
+ df["mail"] = parsed_mail
70
+ df["timestamp"] = datetime.datetime.now()
71
+
72
+ # upload to spaces using the hf api at
73
+
74
+ path_in_repo = f"submissions/{method_name}"
75
+ file_name = f"{method_name}-{organisation}-{datetime.datetime.now().strftime('%Y-%m-%d')}.csv"
76
+
77
+ # upload the df to spaces
78
+ import io
79
+
80
+ buffer = io.BytesIO()
81
+ df.to_csv(buffer, index=False) # Write the DataFrame to a buffer in CSV format
82
+ buffer.seek(0) # Rewind the buffer to the beginning
83
+
84
+ api.upload_file(
85
+ repo_id=RESULTS_PATH,
86
+ path_in_repo=f"{path_in_repo}/{file_name}",
87
+ path_or_fileobj=buffer,
88
+ token=TOKEN,
89
+ repo_type="dataset",
90
+ )
91
+
92
+ return format_log(
93
+ f"Method {method_name} submitted by {organisation} successfully. \nPlease refresh the leaderboard, and wait a bit to see the score displayed"
94
+ )