File size: 11,781 Bytes
24d828a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
import gradio as gr
import numpy as np
import pandas as pd
import argparse

def make_default_md():
    leaderboard_md = f"""
    # πŸ† LLms Benchmark
    
    The main goal of this project is to utilize Large Language Models (LLMs) to extract specific information from PDF documents and organize it into a structured JSON format.
    
    To achieve this objective, we are assessing various LLMs on two benchmarks:
    
    1. [Benchmark1](https://huggingface.co/spaces/Nechba/LLms-Benchmark/blob/main/dataset.jsonl): 
    This benchmark consists of a dataset of 59 pages as context and corresponding JSON extracts from "Interchange and Service Fees Manual: Europe Region".
    
    2. [Benchmark2](https://huggingface.co/datasets/Effyis/Table-Extraction): 
    This benchmark comprises a dataset of 16573 tables as context and corresponding JSON extracts.
    """
    return leaderboard_md


def make_arena_leaderboard_md(total_models):
    leaderboard_md = f"""
Total #models: **{total_models}**. Last updated: Avril 04, 2024.

"""
    return leaderboard_md

def model_hyperlink(model_name, link):
    return f'<a target="_blank" href="{link}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{model_name}</a>'

def load_leaderboard_table_csv(filename, add_hyperlink=True):
    rows = []
    with open(filename, 'r') as file:
        lines = file.readlines()
        heads = [v.strip() for v in lines[0].split(",")]
        for line in lines[1:]:
            row = [v.strip() for v in line.split(",")]
            item = {}
            for h, v in zip(heads, row):
                item[h] = v
            if add_hyperlink:
                item["Model"] = model_hyperlink(item["Model"], item["Link"])
                item["Notebook link"] = model_hyperlink("Notebook", item["Notebook link"])
            rows.append(item)
    return rows

def get_arena_table(model_table_df):
    # change type Percentage of values column of df
    model_table_df["Percentage of values"] = model_table_df["Percentage of values"].astype(float)
    model_table_df["Percentage of keys"] = model_table_df["Percentage of keys"].astype(float)
    model_table_df["Average time (s)"] = model_table_df["Average time (s)"].astype(float)
    arena_df = model_table_df.sort_values(by=["Percentage of values"], ascending=False)
    values = []
    if not arena_df.empty:  # Check if arena_df is not empty
        for i in range(len(arena_df)):
            row = []
            model_name = arena_df["Model"].values[i]  # Access model name directly without index 0
            row.append(model_name)
            row.append(arena_df.iloc[i]["Percentage of values"])
            row.append(arena_df.iloc[i]["Percentage of keys"])
            row.append(arena_df.iloc[i]["Average time (s)"])
            row.append(arena_df.iloc[i]["Notebook link"])
            row.append(arena_df.iloc[i]["License"])
            # row.append(arena_df.iloc[i]["Link"])
            values.append(row)
    return values

def build_leaderboard_tab(leaderboard_table_file1,leaderboard_table_file2, show_plot=False):
    default_md = make_default_md()
    md_1 = gr.Markdown(default_md, elem_id="leaderboard_markdown")
    if leaderboard_table_file1:
        data1 = load_leaderboard_table_csv(leaderboard_table_file1)
        model_table_df1 = pd.DataFrame(data1)
        data2 = load_leaderboard_table_csv(leaderboard_table_file2)
        model_table_df2 = pd.DataFrame(data2)
        with gr.Tabs() as tabs:
            with gr.Tab(" πŸ… Benchmark 1", id=0):
                arena_table_vals = get_arena_table(model_table_df1)
                md = make_arena_leaderboard_md(len(arena_table_vals))
                gr.Markdown(md, elem_id="leaderboard_markdown")
                gr.Dataframe(
                    headers=[
                        "Model",
                        "Percentage of values (%)",
                        "Percentage of keys (%)",
                        "Average time (s)",
                        "Code",
                        "License",
                    ],
                    datatype=[
                        "markdown",
                        "number",
                        "number",
                        "number",
                        "markdown",
                        "str"
                    ],
                    value=arena_table_vals,
                    elem_id="arena_leaderboard_dataframe",
                    height=700,
                    column_widths=[200, 150, 150, 130, 100, 140],
                    wrap=True,
                )
                # Displaying a note about the leaderboard analysis
                gr.Markdown(
                    f"""Note: Upon reviewing the leaderboard, it's evident that two models, Gemini and OpenHermes, outperform the others. Our next step involves a detailed analysis and comparison of the results obtained by these two models.""",
                    elem_id="leaderboard_markdown"
                )
                
                # Displaying additional statistics for Gemini and OpenHermes
                gr.Markdown(
                    f"""## More Statistics for Gemini and OpenHermes\n
                Now we will focus on Gemini and OpenHermes, diving deeper into their performance for a comprehensive comparison.""",
                    elem_id=0
                )
                
                # Displaying the confusion matrices for Gemini and OpenHermes
                with gr.Row():
                    with gr.Column():
                        gr.Markdown(
                            "#### Figure 1: Gemini Confusion Matrix"
                        )
                        plot_1 = gr.Image("./Benchmark1/gemini_cm.png", show_label=False)
                        # Detailed analysis of Gemini's performance
                        gr.Markdown(
                            """### True Positives:
                Our model correctly identified all 18 pages lacking the desired information (Payment product, FeeTier, and Rate).
                
                ### True Negatives:
                The model successfully predicted desired information on 39 out of 41 pages with an accuracy ranging from 12% to 100%. (For more details about accuracy, check the Notebook [here](https://huggingface.co/spaces/Effyis/LLms-Benchmark/blob/main/Benchmark1/gemini.ipynb))
                
                ### False Negatives:
                In 2 instances, the model incorrectly predicted that pages lacked the desired information when they actually contained it.
                
                ### False Positives:
                The model incorrectly predicted that 0 pages contained the desired information when they were actually missing it."""
                        )
                
                    with gr.Column():
                        gr.Markdown(
                            "#### Figure 2: OpenHermes Confusion Matrix"
                        )
                        plot_2 = gr.Image("./Benchmark1/openhermes_cm.png", show_label=False)
                        # Detailed analysis of OpenHermes's performance
                        gr.Markdown(
                            """### True Positives:
                Our model correctly identified 12 out of 18 pages lacking the desired information (Payment product, FeeTier, and Rate).
                
                ### True Negatives:
                The model successfully predicted desired information on 21 out of 41 pages with an accuracy ranging from 5% to 66%. (For more details about accuracy, check the Notebook [here](https://huggingface.co/spaces/Effyis/LLms-Benchmark/blob/main/Benchmark1/openhermes.ipynb))
                
                ### False Negatives:
                In 20 instances, the model incorrectly predicted that pages lacked the desired information when they actually contained it.
                
                ### False Positives:
                The model incorrectly predicted that 6 pages contained the desired information when they were actually missing it."""
                        )
                
                # Conclusion based on the analysis
                gr.Markdown(
                    """## Conclusion\n
                Upon analyzing the performance of Gemini and OpenHermes, it becomes evident that both models exhibit strengths and weaknesses. Gemini demonstrates higher accuracy in identifying pages lacking desired information and also performs better in predicting pages containing the desired information. On the other hand, while OpenHermes shows good results in identifying pages lacking desired information, it achieves only 50% accuracy in predicting pages containing the desired information. Further fine-tuning of both models could lead to enhanced overall performance."""
                )

            
            with gr.Tab("πŸ… Benchmark 2", id=1):
                arena_table_vals = get_arena_table(model_table_df2)
                md = make_arena_leaderboard_md(len(arena_table_vals))
                gr.Markdown(md, elem_id="leaderboard_markdown")
                gr.Dataframe(
                    headers=[
                        "Model",
                        "Percentage of values (%)",
                        "Percentage of keys (%)",
                        "Average time (s)",
                        "Code",
                        "License",
                    ],
                    datatype=[
                        "markdown",
                        "number",
                        "number",
                        "number",
                        "markdown",
                        "str"
                    ],
                    value=arena_table_vals,
                    elem_id="arena_leaderboard_dataframe",
                    height=700,
                    column_widths=[200, 150, 150, 130, 100, 140],
                    wrap=True,
                )      
            gr.Markdown(
                    f"""
Note: For this benchmark, only a sample of 100 points from the dataset is utilized. It's evident that the data context is straightforward, yet it includes Arabic names. This could explain the lower performance scores of the models, as they may lack robust capabilities in handling Arabic names.""",
                    elem_id="leaderboard_markdown"
                )
                
    else:
            pass
    return [md_1,plot_1, plot_2]

block_css = """
#notice_markdown {
    font-size: 104%
}
#notice_markdown th {
    display: none;
}
#notice_markdown td {
    padding-top: 6px;
    padding-bottom: 6px;
}
#leaderboard_markdown {
    font-size: 104%
}
#leaderboard_markdown td {
    padding-top: 6px;
    padding-bottom: 6px;
}
#leaderboard_dataframe td {
    line-height: 0.1em;
}
footer {
    display:none !important
}
.sponsor-image-about img {
    margin: 0 20px;
    margin-top: 20px;
    height: 40px;
    max-height: 100%;
    width: auto;
    float: left;
}
"""

def build_demo(leaderboard_table_file1, leaderboard_table_file2):
    text_size = gr.themes.sizes.text_lg
    with gr.Blocks(
        title="LLMS Benchmark",
        theme=gr.themes.Base(text_size=text_size),
        css=block_css,
    ) as demo:
        leader_components = build_leaderboard_tab(
            leaderboard_table_file1,leaderboard_table_file2, show_plot=True
        )
    return demo

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--share", action="store_true")
    args = parser.parse_args()

    leaderboard_table_file1 = "./Benchmark1/leaderboard.csv"
    leaderboard_table_file2 = "./Benchmark2/leaderboard.csv"
    demo = build_demo(leaderboard_table_file1,leaderboard_table_file2)
    demo.launch(share=args.share)