File size: 12,743 Bytes
2c2ec39
 
58d8c29
 
 
 
 
 
 
 
 
 
 
09bfa0e
3111eb6
 
 
09bfa0e
3111eb6
09bfa0e
a632ee2
09bfa0e
3111eb6
09bfa0e
 
58d8c29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18801fb
2bb119f
18801fb
 
2bb119f
58d8c29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18801fb
bcdfbc2
 
 
 
 
 
 
 
18801fb
bead680
18801fb
1a9d613
f45ec7c
bead680
18801fb
 
 
09bfa0e
18801fb
 
 
2d89a48
58d8c29
c9fdcf2
 
 
 
09bfa0e
58d8c29
 
c9fdcf2
2d89a48
e563844
58d8c29
c9fdcf2
58d8c29
aa75803
58d8c29
18801fb
bcdfbc2
 
9a94aea
 
bcdfbc2
 
 
 
 
 
9a94aea
 
bcdfbc2
 
 
 
 
09bfa0e
bcdfbc2
 
 
 
 
 
 
 
 
 
 
 
 
 
c9f7b16
bcdfbc2
 
 
 
 
 
ed6456c
 
bcdfbc2
ed6456c
 
 
 
18801fb
ed6456c
09bfa0e
ed6456c
 
 
 
a2dd461
ed6456c
09bfa0e
ed6456c
 
 
58d8c29
18801fb
393821f
 
bcdfbc2
393821f
 
 
 
 
 
 
09bfa0e
393821f
 
 
 
a2dd461
393821f
09bfa0e
393821f
 
 
2d89a48
bead680
58d8c29
 
 
 
 
 
 
 
 
 
 
 
18801fb
09bfa0e
18801fb
58d8c29
 
 
 
 
 
09bfa0e
58d8c29
 
 
 
2c2ec39
2446c8a
 
 
 
58d8c29
f3379af
58d8c29
f3379af
58d8c29
 
 
 
 
f3379af
58d8c29
 
 
09bfa0e
58d8c29
09bfa0e
 
f3379af
58d8c29
 
2c2ec39
 
 
 
 
 
 
f3379af
2c2ec39
 
 
 
 
 
 
 
 
 
 
 
 
f3379af
 
2c2ec39
 
58d8c29
 
2c2ec39
 
 
 
58d8c29
 
 
 
 
 
2c2ec39
58d8c29
2c2ec39
 
 
18801fb
2c2ec39
3d2851f
2c2ec39
 
 
 
 
 
 
 
58d8c29
 
9e2634b
58d8c29
31deabc
2e8bf47
9e2634b
31deabc
9e2634b
31deabc
9e2634b
2e8bf47
9e2634b
31deabc
 
9e2634b
58d8c29
 
bcdfbc2
58d8c29
3d2851f
9e2634b
 
58d8c29
 
393821f
 
2c2ec39
393821f
 
 
2c2ec39
 
393821f
 
2c2ec39
ed6456c
 
 
2c2ec39
 
ed6456c
 
2c2ec39
393821f
bcdfbc2
393821f
2c2ec39
 
393821f
 
58d8c29
 
9e2634b
 
58d8c29
 
 
 
 
2c2ec39
58d8c29
2c2ec39
58d8c29
 
f3379af
09bfa0e
58d8c29
2446c8a
58d8c29
 
b43278c
58d8c29
 
2c2ec39
 
f3379af
58d8c29
 
 
 
 
 
 
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
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
from apscheduler.schedulers.background import BackgroundScheduler
import datetime
import os
from typing import Dict, Tuple
from uuid import UUID

import altair as alt
import argilla as rg
from argilla.feedback import FeedbackDataset
from argilla.client.feedback.dataset.remote.dataset import RemoteFeedbackDataset
import gradio as gr
import pandas as pd

# Translation of legends and titels
ANNOTATED = 'Đã dịch'
NUMBER_ANNOTATED = 'Tổng số mẫu đã dịch'
PENDING = 'Số mẫu còn lại'

NUMBER_ANNOTATORS = "Số thành viên tham gia"
NAME = 'Username'
NUMBER_ANNOTATIONS = 'Tổng số mẫu'

CATEGORY = 'Danh mục'



def obtain_source_target_datasets() -> (
    Tuple[
        FeedbackDataset | RemoteFeedbackDataset, FeedbackDataset | RemoteFeedbackDataset
    ]
):
    """
    This function returns the source and target datasets to be used in the application.

    Returns:
        A tuple with the source and target datasets. The source dataset is filtered by the response status 'pending'.

    """

    # Obtain the public dataset and see how many pending records are there
    source_dataset = rg.FeedbackDataset.from_argilla(
        os.getenv("SOURCE_DATASET"), workspace=os.getenv("SOURCE_WORKSPACE")
    )
    filtered_source_dataset = source_dataset.filter_by(response_status=["pending"])

    # Obtain a list of users from the private workspace
    # target_dataset = rg.FeedbackDataset.from_argilla(
    #    os.getenv("RESULTS_DATASET"), workspace=os.getenv("RESULTS_WORKSPACE")
    # )

    target_dataset = source_dataset.filter_by(response_status=["submitted"])

    return filtered_source_dataset, target_dataset


def get_user_annotations_dictionary(
    dataset: FeedbackDataset | RemoteFeedbackDataset,
) -> Dict[str, int]:
    """
    This function returns a dictionary with the username as the key and the number of annotations as the value.

    Args:
        dataset: The dataset to be analyzed.
    Returns:
        A dictionary with the username as the key and the number of annotations as the value.
    """
    output = {}
    for record in dataset:
        for response in record.responses:
            if str(response.user_id) not in output.keys():
                output[str(response.user_id)] = 1
            else:
                output[str(response.user_id)] += 1

    # Changing the name of the keys, from the id to the username
    for key in list(output.keys()):
        output[rg.User.from_id(UUID(key)).username] = output.pop(key)

    return output


def donut_chart_total() -> alt.Chart:
    """
    This function returns a donut chart with the progress of the total annotations.
    Counts each record that has been annotated at least once.

    Returns:
        An altair chart with the donut chart.
    """

    # Load your data
    annotated_records = len(target_dataset)
    pending_records = int(os.getenv("TARGET_RECORDS")) - annotated_records

    # Prepare data for the donut chart
    source = pd.DataFrame(
        {
            "values": [annotated_records, pending_records],
            "category": [ANNOTATED, PENDING],
            "colors": ["#4CAF50", "#757575"],  # Green for Completed, Grey for Remaining
        }
    )

    base = alt.Chart(source).encode(
        theta=alt.Theta("values:Q", stack=True),
        radius=alt.Radius(
            "values", scale=alt.Scale(type="sqrt", zero=True, rangeMin=20)
        ),
        color=alt.Color("category:N", legend=alt.Legend(title=CATEGORY)),
    )

    c1 = base.mark_arc(innerRadius=20, stroke="#fff")

    c2 = base.mark_text(radiusOffset=20).encode(text="values:Q")

    chart = c1 + c2

    return chart


def donut_chart_target() -> alt.Chart:
    """
    This function returns a donut chart with the progress of the total annotations, in terms of the v1 objective.
    Counts each record that has been annotated at least once.

    Returns:
        An altair chart with the donut chart.
    """

    # Load your data
    annotated_records = len(target_dataset)
    pending_records = int(os.getenv("TARGET_ANNOTATIONS_V1")) - annotated_records

    # Prepare data for the donut chart
    source = pd.DataFrame(
        {
            "values": [annotated_records, pending_records],
            "category": [ANNOTATED, PENDING],
            "colors": ["#4CAF50", "#757575"],  # Green for Completed, Grey for Remaining
        }
    )

    base = alt.Chart(source).encode(
        theta=alt.Theta("values:Q", stack=True),
        radius=alt.Radius(
            "values", scale=alt.Scale(type="sqrt", zero=True, rangeMin=20)
        ),
        color=alt.Color("category:N", legend=alt.Legend(title="Category")),
    )

    c1 = base.mark_arc(innerRadius=20, stroke="#fff")

    c2 = base.mark_text(radiusOffset=20).encode(text="values:Q")

    chart = c1 + c2

    return chart


def kpi_chart_remaining() -> alt.Chart:
    """
    This function returns a KPI chart with the remaining amount of records to be annotated.
    Returns:
        An altair chart with the KPI chart.
    """

    pending_records = int(os.getenv("TARGET_RECORDS")) - len(target_dataset)
    # Assuming you have a DataFrame with user data, create a sample DataFrame
    data = pd.DataFrame({"Category": [PENDING], "Value": [pending_records]})

    # Create Altair chart
    chart = (
        alt.Chart(data)
        .mark_text(fontSize=100, align="center", baseline="middle", color="steelblue")
        .encode(text="Value:N")
        .properties(title=PENDING, width=250, height=200)
    )

    return chart


def kpi_chart_submitted() -> alt.Chart:
    """
    This function returns a KPI chart with the total amount of records that have been annotated.
    Returns:
        An altair chart with the KPI chart.
    """

    total = len(target_dataset)

    # Assuming you have a DataFrame with user data, create a sample DataFrame
    data = pd.DataFrame({"Category": [NUMBER_ANNOTATED], "Value": [total]})

    # Create Altair chart
    chart = (
        alt.Chart(data)
        .mark_text(fontSize=100, align="center", baseline="middle", color="#e68b39")
        .encode(text="Value:N")
        .properties(title=NUMBER_ANNOTATED, width=250, height=200)
    )

    return chart


def kpi_chart() -> alt.Chart:
    """
    This function returns a KPI chart with the total amount of annotators.

    Returns:
        An altair chart with the KPI chart.
    """

    # Obtain the total amount of annotators
    total_annotators = len(user_ids_annotations)

    # Assuming you have a DataFrame with user data, create a sample DataFrame
    data = pd.DataFrame(
        {"Category": [NUMBER_ANNOTATORS], "Value": [total_annotators]}
    )

    # Create Altair chart
    chart = (
        alt.Chart(data)
        .mark_text(fontSize=100, align="center", baseline="middle", color="steelblue")
        .encode(text="Value:N")
        .properties(title=NUMBER_ANNOTATORS, width=250, height=200)
    )

    return chart


def render_hub_user_link(hub_id):
    link = f"https://huggingface.co/{hub_id}"
    return f'<a target="_blank" href="{link}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{hub_id}</a>'


def obtain_top_users(user_ids_annotations: Dict[str, int], N: int = 50) -> pd.DataFrame:
    """
    This function returns the top N users with the most annotations.

    Args:
        user_ids_annotations: A dictionary with the user ids as the key and the number of annotations as the value.

    Returns:
        A pandas dataframe with the top N users with the most annotations.
    """

    dataframe = pd.DataFrame(
        user_ids_annotations.items(), columns=[NAME, NUMBER_ANNOTATIONS]
    )
    dataframe[NAME] = dataframe[NAME].apply(render_hub_user_link)
    dataframe = dataframe.sort_values(by=NUMBER_ANNOTATIONS, ascending=False)
    return dataframe.head(N)


def fetch_data() -> None:
    """
    This function fetches the data from the source and target datasets and updates the global variables.
    """

    print(f"Starting to fetch data: {datetime.datetime.now()}")

    global source_dataset, target_dataset, user_ids_annotations, annotated, remaining, percentage_completed, top_dataframe
    source_dataset, target_dataset = obtain_source_target_datasets()
    user_ids_annotations = get_user_annotations_dictionary(target_dataset)

    annotated = len(target_dataset)
    remaining = int(os.getenv("TARGET_RECORDS")) - annotated
    percentage_completed = round(
        (annotated / int(os.getenv("TARGET_RECORDS"))) * 100, 1
    )

    # Print the current date and time
    print(f"Data fetched: {datetime.datetime.now()}")


def get_top(N = 50) -> pd.DataFrame:
    return obtain_top_users(user_ids_annotations, N=N)


def main() -> None:

    # Set the update interval
    update_interval = 300  # seconds
    update_interval_charts = 30  # seconds

    # Connect to the space with rg.init()
    rg.init(
        api_url=os.getenv("ARGILLA_API_URL"),
        api_key=os.getenv("ARGILLA_API_KEY"),
    )

    fetch_data()

    scheduler = BackgroundScheduler()
    scheduler.add_job(
        func=fetch_data, trigger="interval", seconds=update_interval, max_instances=1
    )
    scheduler.start()

    # To avoid the orange border for the Gradio elements that are in constant loading
    css = """
    .generating {
        border: none;
    }
    """

    with gr.Blocks(css=css) as demo:
        gr.Markdown(
            """
            # 🌍 Tiếng Việt - Dự án Đánh giá Prompt Đa ngôn ngữ

            Hugging Face và @argilla đang phát triển dự án [Dự án Đánh giá prompt Đa ngôn ngữ](https://github.com/huggingface/data-is-better-together/tree/main/prompt_translation). Đây là một chuẩn mực mở đa ngôn ngữ để đánh giá các mô hình ngôn ngữ, và tất nhiên, cũng dành cho tiếng Việt.

            ## Mục tiêu là dịch 500 Prompts
            
            Và như mọi khi: cần có dữ liệu cho việc đó! Cộng đồng đã chọn ra 500 prompt tốt nhất sẽ tạo nên chuẩn mực đánh giá. Bằng tiếng Anh, tất nhiên.
            
            **Đó là lý do chúng mình cần sự giúp đỡ của bạn**: nếu chúng ta cùng nhau dịch 500 prompts, chúng mình có thể thêm Tiếng Việt vào bảng xếp hạng.

            ## Cách tham gia
            Truy cập vào [AI-Vietnam/prompt-translation-for-vie](https://huggingface.co/spaces/AI-Vietnam/prompt-translation-for-vie), đăng nhập hoặc tạo một tài khoản Hugging Face, và bạn có thể bắt đầu.
            
            Cảm ơn các bạn rất nhiều! Bên cạnh đó, chúng mình đã dùng AI để chuẩn bị sẵn một đề xuất dịch giúp tăng tốc quá trình dịch thuật.
            """
        )

        gr.Markdown(
            f"""
            ## 🚀 Tiến độ hiện tại
            Cùng nhau xây dựng bộ dữ liệu này nhé!
            """
        )
        with gr.Row():

            kpi_submitted_plot = gr.Plot(label="Plot")
            demo.load(
                kpi_chart_submitted,
                inputs=[],
                outputs=[kpi_submitted_plot],
                every=update_interval_charts,
            )

            kpi_remaining_plot = gr.Plot(label="Plot")
            demo.load(
                kpi_chart_remaining,
                inputs=[],
                outputs=[kpi_remaining_plot],
                every=update_interval_charts,
            )

            donut_total_plot = gr.Plot(label="Plot")
            demo.load(
                donut_chart_total,
                inputs=[],
                outputs=[donut_total_plot],
                every=update_interval_charts,
            )

        gr.Markdown(
            """
            ## 👾 Bảng xếp hạng
            Tại đây bạn có thể thấy những người đóng góp hàng đầu và số lượng bản dịch họ đã thực hiện:
            """
        )

        with gr.Row():

            kpi_hall_plot = gr.Plot(label="Plot")
            demo.load(
                kpi_chart, inputs=[], outputs=[kpi_hall_plot], every=update_interval_charts
            )

            top_df_plot = gr.Dataframe(
                headers=[NAME, NUMBER_ANNOTATIONS],
                datatype=[
                    "markdown",
                    "number",
                ],
                row_count=50,
                col_count=(2, "fixed"),
                interactive=False,
                every=update_interval,
            )
            demo.load(get_top, None, [top_df_plot], every=update_interval_charts)

    # Launch the Gradio interface
    demo.launch()


if __name__ == "__main__":
    main()