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17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
import os
import json
import gradio as gr
import pandas as pd
import numpy as np

from collections import defaultdict


LENGTHS = ["dataset_total_score", "4k", "8k", "16k", "32k", "64k", "128k"]
datasets_params = json.load(open("datasets_config.json", "r"))
TASKS = datasets_params.keys()


def task_keys_star_first():
    """LIBRA Mini datasets (display name ends with ' *') first, then others; order within each group follows datasets_config."""
    keys = list(datasets_params.keys())
    star = [k for k in keys if datasets_params[k]["name"].endswith(" *")]
    rest = [k for k in keys if k not in star]
    return star + rest


TASK_TAB_ORDER = task_keys_star_first()

LIBRA_MINI_TASK_KEYS = frozenset(
    k for k in datasets_params if datasets_params[k]["name"].endswith(" *")
)


def make_default_md():
    leaderboard_md = f"""
    🏅 LIBRA LeaderBoard
    | [GitHub](https://github.com/ai-forever/LIBRA) | [Datasets](https://huggingface.co/datasets/ai-forever/LIBRA) |
    """
    return leaderboard_md


def make_model_desc_md():
    with open("docs/description.md", "r") as f:
        description = f.read()
    return description


def make_overall_table_by_tasks(files):
    results = defaultdict(list)

    result_dct = {}
    for file in files:
        if not file.endswith("json"): continue
        path = "results/" + file
        data = json.load(open(path))
        model_name = file.split('/')[-1].split(".json")[0]
        result_dct[model_name] = {}
        for dataset in data.keys():
            if dataset == "total_score":
                result_dct[model_name][dataset] = round(data[dataset] * 100, 1)
                continue
            result_dct[model_name][dataset] = round(data[dataset]["dataset_total_score"] * 100, 1)

    for file in files:
        if not file.endswith("json"): continue
        model_name = file.split('/')[-1].split(".json")[0]
        results['Model'].append(model_name)
        for key in result_dct[model_name].keys():
            if key == "total_score":
                results["Total Score"].append(result_dct[model_name][key])
            else:
                results[datasets_params[key]["name"]].append(result_dct[model_name][key])

    table = pd.DataFrame(results).sort_values(['Total Score'], ascending=False)
    front = ["Model", "Total Score"]
    rest = [datasets_params[t]["name"] for t in TASK_TAB_ORDER if datasets_params[t]["name"] in table.columns]
    rest += [c for c in table.columns if c not in front and c not in rest]
    return table[front + rest]


def make_overall_table_by_tasks_mini(files):
    """Per-task scores for LIBRA Mini datasets only; Total Score = mean over mini tasks."""
    results = defaultdict(list)

    result_dct = {}
    for file in files:
        if not file.endswith("json"):
            continue
        path = "results/" + file
        data = json.load(open(path))
        model_name = file.split("/")[-1].split(".json")[0]
        result_dct[model_name] = {}
        mini_raw = []
        for dataset in data.keys():
            if dataset == "total_score":
                continue
            if dataset not in LIBRA_MINI_TASK_KEYS:
                continue
            result_dct[model_name][dataset] = round(data[dataset]["dataset_total_score"] * 100, 1)
            mini_raw.append(data[dataset]["dataset_total_score"])
        if mini_raw:
            result_dct[model_name]["total_score"] = round(float(np.mean(mini_raw)) * 100, 1)
        else:
            result_dct[model_name]["total_score"] = float("nan")

    for file in files:
        if not file.endswith("json"):
            continue
        model_name = file.split("/")[-1].split(".json")[0]
        results["Model"].append(model_name)
        for key in result_dct[model_name].keys():
            if key == "total_score":
                results["Total Score"].append(result_dct[model_name][key])
            else:
                results[datasets_params[key]["name"]].append(result_dct[model_name][key])

    table = pd.DataFrame(results).sort_values(["Total Score"], ascending=False)
    front = ["Model", "Total Score"]
    mini_tab_order = [t for t in TASK_TAB_ORDER if t in LIBRA_MINI_TASK_KEYS]
    rest = [datasets_params[t]["name"] for t in mini_tab_order if datasets_params[t]["name"] in table.columns]
    rest += [c for c in table.columns if c not in front and c not in rest]
    return table[front + rest]


def make_overall_table_by_lengths(files):
    results = defaultdict(list)

    result_dct = {}
    for file in files:
        if not file.endswith("json"): continue
        path = "results/" + file
        data = json.load(open(path))
        model_name = file.split('/')[-1].split(".json")[0]
        result_dct[model_name] = {}
        for dataset in data.keys():
            if dataset == "total_score":
                result_dct[model_name][dataset] = data[dataset]
                continue
            for length in data[dataset].keys():
                if length == "dataset_total_score": continue
                if length not in result_dct[model_name]:
                    result_dct[model_name][length] = []
                result_dct[model_name][length].append(data[dataset][length])

    for model_name in result_dct.keys():
        for length in result_dct[model_name].keys():
            result_dct[model_name][length] = round(np.mean(result_dct[model_name][length]) * 100, 1)

    for file in files:
        if not file.endswith("json"): continue
        model_name = file.split('/')[-1].split(".json")[0]
        results['Model'].append(model_name)
        for key in result_dct[model_name].keys():
            if key == "total_score":
                results["Total Score"].append(result_dct[model_name][key])
            else:
                results[key].append(result_dct[model_name][key])

    table = pd.DataFrame(results).sort_values(['Total Score'], ascending=False)
    front = ["Model", "Total Score"]
    length_cols = [c for c in LENGTHS if c in table.columns]
    return table[front + length_cols]


def make_overall_table_by_lengths_mini(files):
    """Aggregate by context length using only LIBRA Mini datasets (names ending with ' *')."""
    results = defaultdict(list)

    result_dct = {}
    for file in files:
        if not file.endswith("json"):
            continue
        path = "results/" + file
        data = json.load(open(path))
        model_name = file.split("/")[-1].split(".json")[0]
        result_dct[model_name] = {}
        mini_scores = []
        for dataset in data.keys():
            if dataset == "total_score":
                continue
            if dataset not in LIBRA_MINI_TASK_KEYS:
                continue
            block = data[dataset]
            if "dataset_total_score" in block:
                mini_scores.append(block["dataset_total_score"])
            for length in block.keys():
                if length == "dataset_total_score":
                    continue
                if length not in result_dct[model_name]:
                    result_dct[model_name][length] = []
                result_dct[model_name][length].append(block[length])

        if mini_scores:
            result_dct[model_name]["total_score"] = float(np.mean(mini_scores))
        else:
            result_dct[model_name]["total_score"] = float("nan")

    for model_name in result_dct.keys():
        for length in list(result_dct[model_name].keys()):
            if length == "total_score":
                continue
            result_dct[model_name][length] = round(np.mean(result_dct[model_name][length]) * 100, 1)

    for file in files:
        if not file.endswith("json"):
            continue
        model_name = file.split("/")[-1].split(".json")[0]
        results["Model"].append(model_name)
        for key in result_dct[model_name].keys():
            if key == "total_score":
                results["Total Score"].append(round(result_dct[model_name][key] * 100, 1))
            else:
                results[key].append(result_dct[model_name][key])

    table = pd.DataFrame(results).sort_values(["Total Score"], ascending=False)
    front = ["Model", "Total Score"]
    length_cols = [c for c in LENGTHS if c in table.columns]
    return table[front + length_cols]


def load_model(files, tab_name):
    results = defaultdict(list)

    for file in files:
        if not file.endswith("json"): continue
        model_name = file.split('/')[-1].split(".json")[0]
        results['Model'].append(model_name)
        result = json.load(open("results/" + file, "r"))
        task_block = result.get(tab_name)
        if not task_block:
            results["Dataset Total Score"].append("-")
            for length in LENGTHS:
                if length == "dataset_total_score":
                    continue
                results[length].append("-")
            continue
        for length in LENGTHS:
            if length in task_block.keys():
                if length == "dataset_total_score":
                    results["Dataset Total Score"].append(round(task_block[length] * 100, 1))
                    continue
                results[length].append(round(task_block[length] * 100, 1))
            else:
                results[length].append("-")

    df = pd.DataFrame(results)
    df["_sort_key"] = pd.to_numeric(df["Dataset Total Score"], errors="coerce").fillna(-1)
    return df.sort_values("_sort_key", ascending=False).drop(columns=["_sort_key"])


def build_leaderboard_tab(files):
    default_md = make_default_md()
    md_1 = gr.Markdown(default_md, elem_id="leaderboard_markdown")

    with gr.Tabs() as tabs:

        with gr.Tab("Results by length (LIBRA-mini)", id=0):
            df = make_overall_table_by_lengths_mini(files)
            gr.Dataframe(
                headers=[
                            "Model",
                        ] + LENGTHS,
                datatype=[
                    "markdown",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                ],
                value=df,
                elem_id="arena_leaderboard_dataframe",
                max_height=700,
                wrap=True,
            )

        with gr.Tab("Results by length (LIBRA)", id=1):
            df = make_overall_table_by_lengths(files)
            gr.Dataframe(
                headers=[
                            "Model",
                        ] + LENGTHS,
                datatype=[
                    "markdown",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                ],
                value=df,
                elem_id="arena_leaderboard_dataframe",
                max_height=700,
                wrap=True,
            )

        with gr.Tab("Results by task (LIBRA-mini)", id=2):
            df = make_overall_table_by_tasks_mini(files)
            gr.Dataframe(
                headers=[
                            "Model",
                        ] + LENGTHS,
                datatype=[
                    "markdown",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str"
                ],
                value=df,
                elem_id="arena_leaderboard_dataframe",
                max_height=700,
                wrap=False,
            )

        with gr.Tab("Results by task (LIBRA)", id=3):
            df = make_overall_table_by_tasks(files)
            gr.Dataframe(
                headers=[
                            "Model",
                        ] + LENGTHS,
                datatype=[
                    "markdown",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str",
                    "str"
                ],
                value=df,
                elem_id="arena_leaderboard_dataframe",
                max_height=700,
                wrap=False,
            )

        for tab_id, tab_name in enumerate(TASK_TAB_ORDER):
                df = load_model(files, tab_name)
                with gr.Tab(datasets_params[tab_name]["name"], id=tab_id + 4):
                    gr.Dataframe(
                        headers=[
                            "Model",
                        ] + LENGTHS,
                        datatype=[
                            "markdown",
                            "str",
                            "str",
                            "str",
                            "str",
                            "str",
                            "str",
                            "str",
                        ],
                        value=df,
                        elem_id="arena_leaderboard_dataframe",
                        max_height=700,
                        wrap=True,
                    )

        with gr.Tab("Description", id=len(TASK_TAB_ORDER) + 4):
            desc_md = make_model_desc_md()
            gr.Markdown(desc_md, elem_id="leaderboard_markdown")

    return [md_1]


def build_demo(files):

    with gr.Blocks(title="LIBRA leaderboard") as demo:
        build_leaderboard_tab(files)
    return demo


if __name__ == "__main__":
    files = os.listdir("results")
    demo = build_demo(files)
    text_size = gr.themes.sizes.text_lg
    demo.launch(theme=gr.themes.Base(text_size=text_size), share=False)