rvienne commited on
Commit
b61bd2b
Β·
1 Parent(s): 39a8f18

Add application file

Browse files
Files changed (1) hide show
  1. app.py +367 -0
app.py ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from apscheduler.schedulers.background import BackgroundScheduler
2
+ import datetime
3
+ import os
4
+ from typing import Dict, Tuple
5
+ from uuid import UUID
6
+
7
+ import altair as alt
8
+ import argilla as rg
9
+ from argilla.feedback import FeedbackDataset
10
+ from argilla.client.feedback.dataset.remote.dataset import RemoteFeedbackDataset
11
+ import gradio as gr
12
+ import pandas as pd
13
+
14
+ """
15
+ This is the main file for the dashboard application. It contains the main function and the functions to obtain the data and create the charts.
16
+ It's designed as a template to recreate the dashboard for the prompt translation project of any language.
17
+
18
+ To create a new dashboard, you need several environment variables, that you can easily set in the HuggingFace Space that you are using to host the dashboard:
19
+
20
+ - SOURCE_DATASET: The dataset id of the source dataset
21
+ - SOURCE_WORKSPACE: The workspace id of the source dataset
22
+ - TARGET_RECORDS: The number of records that you have as a target to annotate. We usually set this to 500.
23
+ - ARGILLA_API_URL: Link to the Huggingface Space where the annotation effort is being hosted. For example, the Spanish one is https://somosnlp-dibt-prompt-translation-for-es.hf.space/
24
+ - ARGILLA_API_KEY: The API key to access the Huggingface Space. Please, write this as a secret in the Huggingface Space configuration.
25
+ """
26
+
27
+ # Translation of legends and titles
28
+ ANNOTATED = 'Annotations'
29
+ NUMBER_ANNOTATED = "Nombre d'annotations (total)"
30
+ PENDING = 'A annoter'
31
+
32
+ NUMBER_ANNOTATORS = "Nombre d'annotateurs"
33
+ NAME = "Nom d'utilisateur"
34
+ NUMBER_ANNOTATIONS = "Nombre d'annotations"
35
+
36
+ CATEGORY = 'CatΓ©gorie'
37
+
38
+ def obtain_source_target_datasets() -> (
39
+ Tuple[
40
+ FeedbackDataset | RemoteFeedbackDataset, FeedbackDataset | RemoteFeedbackDataset
41
+ ]
42
+ ):
43
+ """
44
+ This function returns the source and target datasets to be used in the application.
45
+
46
+ Returns:
47
+ A tuple with the source and target datasets. The source dataset is filtered by the response status 'pending'.
48
+
49
+ """
50
+
51
+ # Obtain the public dataset and see how many pending records are there
52
+ source_dataset = rg.FeedbackDataset.from_argilla(
53
+ os.getenv("SOURCE_DATASET"), workspace=os.getenv("SOURCE_WORKSPACE")
54
+ )
55
+ filtered_source_dataset = source_dataset.filter_by(response_status=["pending"])
56
+
57
+ # Obtain a list of users from the private workspace
58
+ # target_dataset = rg.FeedbackDataset.from_argilla(
59
+ # os.getenv("RESULTS_DATASET"), workspace=os.getenv("RESULTS_WORKSPACE")
60
+ # )
61
+
62
+ target_dataset = source_dataset.filter_by(response_status=["submitted"])
63
+
64
+ return filtered_source_dataset, target_dataset
65
+
66
+
67
+ def get_user_annotations_dictionary(
68
+ dataset: FeedbackDataset | RemoteFeedbackDataset,
69
+ ) -> Dict[str, int]:
70
+ """
71
+ This function returns a dictionary with the username as the key and the number of annotations as the value.
72
+
73
+ Args:
74
+ dataset: The dataset to be analyzed.
75
+ Returns:
76
+ A dictionary with the username as the key and the number of annotations as the value.
77
+ """
78
+ output = {}
79
+ for record in dataset:
80
+ for response in record.responses:
81
+ if str(response.user_id) not in output.keys():
82
+ output[str(response.user_id)] = 1
83
+ else:
84
+ output[str(response.user_id)] += 1
85
+
86
+ # Changing the name of the keys, from the id to the username
87
+ for key in list(output.keys()):
88
+ output[rg.User.from_id(UUID(key)).username] = output.pop(key)
89
+
90
+ return output
91
+
92
+
93
+ def donut_chart_total() -> alt.Chart:
94
+ """
95
+ This function returns a donut chart with the progress of the total annotations.
96
+ Counts each record that has been annotated at least once.
97
+
98
+ Returns:
99
+ An altair chart with the donut chart.
100
+ """
101
+
102
+ # Load your data
103
+ annotated_records = len(target_dataset)
104
+ pending_records = int(os.getenv("TARGET_RECORDS")) - annotated_records
105
+
106
+ # Prepare data for the donut chart
107
+ source = pd.DataFrame(
108
+ {
109
+ "values": [annotated_records, pending_records],
110
+ "category": [ANNOTATED, PENDING],
111
+ "colors": ["#4CAF50", "#757575"], # Green for Completed, Grey for Remaining
112
+ }
113
+ )
114
+
115
+ base = alt.Chart(source).encode(
116
+ theta=alt.Theta("values:Q", stack=True),
117
+ radius=alt.Radius(
118
+ "values", scale=alt.Scale(type="sqrt", zero=True, rangeMin=20)
119
+ ),
120
+ color=alt.Color("category:N", legend=alt.Legend(title=CATEGORY)),
121
+ )
122
+
123
+ c1 = base.mark_arc(innerRadius=20, stroke="#fff")
124
+
125
+ c2 = base.mark_text(radiusOffset=20).encode(text="values:Q")
126
+
127
+ chart = c1 + c2
128
+
129
+ return chart
130
+
131
+
132
+ def kpi_chart_remaining() -> alt.Chart:
133
+ """
134
+ This function returns a KPI chart with the remaining amount of records to be annotated.
135
+ Returns:
136
+ An altair chart with the KPI chart.
137
+ """
138
+
139
+ pending_records = int(os.getenv("TARGET_RECORDS")) - len(target_dataset)
140
+ # Assuming you have a DataFrame with user data, create a sample DataFrame
141
+ data = pd.DataFrame({"Category": [PENDING], "Value": [pending_records]})
142
+
143
+ # Create Altair chart
144
+ chart = (
145
+ alt.Chart(data)
146
+ .mark_text(fontSize=100, align="center", baseline="middle", color="#e68b39")
147
+ .encode(text="Value:N")
148
+ .properties(title=PENDING, width=250, height=200)
149
+ )
150
+
151
+ return chart
152
+
153
+
154
+ def kpi_chart_submitted() -> alt.Chart:
155
+ """
156
+ This function returns a KPI chart with the total amount of records that have been annotated.
157
+ Returns:
158
+ An altair chart with the KPI chart.
159
+ """
160
+
161
+ total = len(target_dataset)
162
+
163
+ # Assuming you have a DataFrame with user data, create a sample DataFrame
164
+ data = pd.DataFrame({"Category": [NUMBER_ANNOTATED], "Value": [total]})
165
+
166
+ # Create Altair chart
167
+ chart = (
168
+ alt.Chart(data)
169
+ .mark_text(fontSize=100, align="center", baseline="middle", color="steelblue")
170
+ .encode(text="Value:N")
171
+ .properties(title=NUMBER_ANNOTATED, width=250, height=200)
172
+ )
173
+
174
+ return chart
175
+
176
+
177
+ def kpi_chart_total_annotators() -> alt.Chart:
178
+ """
179
+ This function returns a KPI chart with the total amount of annotators.
180
+
181
+ Returns:
182
+ An altair chart with the KPI chart.
183
+ """
184
+
185
+ # Obtain the total amount of annotators
186
+ total_annotators = len(user_ids_annotations)
187
+
188
+ # Assuming you have a DataFrame with user data, create a sample DataFrame
189
+ data = pd.DataFrame(
190
+ {"Category": [NUMBER_ANNOTATORS], "Value": [total_annotators]}
191
+ )
192
+
193
+ # Create Altair chart
194
+ chart = (
195
+ alt.Chart(data)
196
+ .mark_text(fontSize=100, align="center", baseline="middle", color="steelblue")
197
+ .encode(text="Value:N")
198
+ .properties(title=NUMBER_ANNOTATORS, width=250, height=200)
199
+ )
200
+
201
+ return chart
202
+
203
+
204
+ def render_hub_user_link(hub_id:str) -> str:
205
+ """
206
+ This function returns a link to the user's profile on Hugging Face.
207
+
208
+ Args:
209
+ hub_id: The user's id on Hugging Face.
210
+
211
+ Returns:
212
+ A string with the link to the user's profile on Hugging Face.
213
+ """
214
+ link = f"https://huggingface.co/{hub_id}"
215
+ return f'<a target="_blank" href="{link}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{hub_id}</a>'
216
+
217
+
218
+ def obtain_top_users(user_ids_annotations: Dict[str, int], N: int = 50) -> pd.DataFrame:
219
+ """
220
+ This function returns the top N users with the most annotations.
221
+
222
+ Args:
223
+ user_ids_annotations: A dictionary with the user ids as the key and the number of annotations as the value.
224
+
225
+ Returns:
226
+ A pandas dataframe with the top N users with the most annotations.
227
+ """
228
+
229
+ dataframe = pd.DataFrame(
230
+ user_ids_annotations.items(), columns=[NAME, NUMBER_ANNOTATIONS]
231
+ )
232
+ dataframe[NAME] = dataframe[NAME].apply(render_hub_user_link)
233
+ dataframe = dataframe.sort_values(by=NUMBER_ANNOTATIONS, ascending=False)
234
+ return dataframe.head(N)
235
+
236
+
237
+ def fetch_data() -> None:
238
+ """
239
+ This function fetches the data from the source and target datasets and updates the global variables.
240
+ """
241
+
242
+ print(f"Starting to fetch data: {datetime.datetime.now()}")
243
+
244
+ global source_dataset, target_dataset, user_ids_annotations, annotated, remaining, percentage_completed, top_dataframe
245
+ source_dataset, target_dataset = obtain_source_target_datasets()
246
+ user_ids_annotations = get_user_annotations_dictionary(target_dataset)
247
+
248
+ annotated = len(target_dataset)
249
+ remaining = int(os.getenv("TARGET_RECORDS")) - annotated
250
+ percentage_completed = round(
251
+ (annotated / int(os.getenv("TARGET_RECORDS"))) * 100, 1
252
+ )
253
+
254
+ # Print the current date and time
255
+ print(f"Data fetched: {datetime.datetime.now()}")
256
+
257
+
258
+ def get_top(N = 50) -> pd.DataFrame:
259
+ """
260
+ This function returns the top N users with the most annotations.
261
+
262
+ Args:
263
+ N: The number of users to be returned. 50 by default
264
+
265
+ Returns:
266
+ A pandas dataframe with the top N users with the most annotations.
267
+ """
268
+
269
+ return obtain_top_users(user_ids_annotations, N=N)
270
+
271
+
272
+ def main() -> None:
273
+
274
+ # Connect to the space with rg.init()
275
+ rg.init(
276
+ api_url=os.getenv("ARGILLA_API_URL"),
277
+ api_key=os.getenv("ARGILLA_API_KEY"),
278
+ )
279
+
280
+ # Fetch the data initially
281
+ fetch_data()
282
+
283
+ # To avoid the orange border for the Gradio elements that are in constant loading
284
+ css = """
285
+ .generating {
286
+ border: none;
287
+ }
288
+ """
289
+
290
+ with gr.Blocks(css=css) as demo:
291
+ gr.Markdown(
292
+ """
293
+ # 🌍 [YOUR LANGUAGE] - Multilingual Prompt Evaluation Project
294
+
295
+ Hugging Face and @argilla are developing [Multilingual Prompt Evaluation Project](https://github.com/huggingface/data-is-better-together/tree/main/prompt_translation) project. It is an open multilingual benchmark for evaluating language models, and of course, also for [YOUR LANGUAGE].
296
+
297
+ ## The goal is to translate 500 Prompts
298
+ And as always: data is needed for that! The community selected the best 500 prompts that will form the benchmark. In English, of course.
299
+ **That's why we need your help**: if we all translate the 500 prompts, we can add [YOUR LANGUAGE] to the leaderboard.
300
+
301
+ ## How to participate
302
+ Participating is easy. Go to the [annotation space][add a link to your annotation dataset], log in or create a Hugging Face account, and you can start working.
303
+ Thanks in advance! Oh, and we'll give you a little push: GPT4 has already prepared a translation suggestion for you.
304
+ """
305
+ )
306
+
307
+ gr.Markdown(
308
+ f"""
309
+ ## πŸš€ Current Progress
310
+ This is what we've achieved so far!
311
+ """
312
+ )
313
+ with gr.Row():
314
+
315
+ kpi_submitted_plot = gr.Plot(label="Plot")
316
+ demo.load(
317
+ kpi_chart_submitted,
318
+ inputs=[],
319
+ outputs=[kpi_submitted_plot],
320
+ )
321
+
322
+ kpi_remaining_plot = gr.Plot(label="Plot")
323
+ demo.load(
324
+ kpi_chart_remaining,
325
+ inputs=[],
326
+ outputs=[kpi_remaining_plot],
327
+ )
328
+
329
+ donut_total_plot = gr.Plot(label="Plot")
330
+ demo.load(
331
+ donut_chart_total,
332
+ inputs=[],
333
+ outputs=[donut_total_plot],
334
+ )
335
+
336
+ gr.Markdown(
337
+ """
338
+ ## πŸ‘Ύ Hall of Fame
339
+ Here you can see the top contributors and the number of annotations they have made.
340
+ """
341
+ )
342
+
343
+ with gr.Row():
344
+
345
+ kpi_hall_plot = gr.Plot(label="Plot")
346
+ demo.load(
347
+ kpi_chart_total_annotators, inputs=[], outputs=[kpi_hall_plot]
348
+ )
349
+
350
+ top_df_plot = gr.Dataframe(
351
+ headers=[NAME, NUMBER_ANNOTATIONS],
352
+ datatype=[
353
+ "markdown",
354
+ "number",
355
+ ],
356
+ row_count=50,
357
+ col_count=(2, "fixed"),
358
+ interactive=False,
359
+ )
360
+ demo.load(get_top, None, [top_df_plot])
361
+
362
+ # Launch the Gradio interface
363
+ demo.launch()
364
+
365
+
366
+ if __name__ == "__main__":
367
+ main()