ignacioct commited on
Commit
8f9f16f
β€’
1 Parent(s): e0ad21e

pushing the dashboard

Browse files
Files changed (4) hide show
  1. README.md +5 -7
  2. app.py +367 -0
  3. dumpy.py +52 -0
  4. requirements.txt +72 -0
README.md CHANGED
@@ -1,13 +1,11 @@
1
  ---
2
- title: TemplateDashboardPromptTranslation
3
- emoji: πŸ¦€
4
  colorFrom: indigo
5
- colorTo: pink
6
  sdk: gradio
7
- sdk_version: 4.22.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
 
1
  ---
2
+ title: Template for Dashboards - Multilingual Prompt Evaluation Project
3
+ emoji: πŸ“Š
4
  colorFrom: indigo
5
+ colorTo: indigo
6
  sdk: gradio
7
+ sdk_version: 4.21.0
8
  app_file: app.py
9
  pinned: false
10
  license: apache-2.0
11
+ ---
 
 
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 = 'Total Annotations'
30
+ PENDING = 'Pending'
31
+
32
+ NUMBER_ANNOTATORS = "Number of annotators"
33
+ NAME = 'Username'
34
+ NUMBER_ANNOTATIONS = 'Number of annotations'
35
+
36
+ CATEGORY = 'Category'
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()
dumpy.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import os
4
+
5
+ import argilla as rg
6
+ from huggingface_hub import HfApi
7
+
8
+ logger = logging.getLogger(__name__)
9
+ logger.setLevel(logging.INFO)
10
+
11
+ if __name__ == "__main__":
12
+ logger.info("*** Initializing Argilla session ***")
13
+ rg.init(
14
+ api_url=os.getenv("ARGILLA_API_URL"),
15
+ api_key=os.getenv("ARGILLA_API_KEY"),
16
+ extra_headers={"Authorization": f"Bearer {os.getenv('HF_TOKEN')}"},
17
+ )
18
+
19
+ logger.info("*** Fetching dataset from Argilla ***")
20
+ dataset = rg.FeedbackDataset.from_argilla(
21
+ os.getenv("SOURCE_DATASET"),
22
+ workspace=os.getenv("SOURCE_WORKSPACE"),
23
+ )
24
+ logger.info("*** Filtering records by `response_status` ***")
25
+ dataset = dataset.filter_by(response_status=["submitted"]) # type: ignore
26
+
27
+ logger.info("*** Calculating users and annotation count ***")
28
+ output = {}
29
+ for record in dataset.records:
30
+ for response in record.responses:
31
+ if response.user_id not in output:
32
+ output[response.user_id] = 0
33
+ output[response.user_id] += 1
34
+
35
+ for key in list(output.keys()):
36
+ output[rg.User.from_id(key).username] = output.pop(key)
37
+
38
+ logger.info("*** Users and annotation count successfully calculated! ***")
39
+
40
+ logger.info("*** Dumping Python dict into `stats.json` ***")
41
+ with open("stats.json", "w") as file:
42
+ json.dump(output, file, indent=4)
43
+
44
+ logger.info("*** Uploading `stats.json` to Hugging Face Hub ***")
45
+ api = HfApi(token=os.getenv("HF_TOKEN"))
46
+ api.upload_file(
47
+ path_or_fileobj="stats.json",
48
+ path_in_repo="stats.json",
49
+ repo_id="DIBT/prompt-collective-dashboard",
50
+ repo_type="space",
51
+ )
52
+ logger.info("*** `stats.json` successfully uploaded to Hugging Face Hub! ***")
requirements.txt ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiofiles==23.2.1
2
+ altair==5.2.0
3
+ annotated-types==0.6.0
4
+ anyio==4.2.0
5
+ apscheduler==3.10.4
6
+ argilla==1.23.0
7
+ attrs==23.2.0
8
+ backoff==2.2.1
9
+ certifi==2024.2.2
10
+ charset-normalizer==3.3.2
11
+ click==8.1.7
12
+ colorama==0.4.6
13
+ contourpy==1.2.0
14
+ cycler==0.12.1
15
+ Deprecated==1.2.14
16
+ exceptiongroup==1.2.0
17
+ fastapi==0.109.2
18
+ ffmpy==0.3.1
19
+ filelock==3.13.1
20
+ fonttools==4.48.1
21
+ fsspec==2024.2.0
22
+ gradio==4.17.0
23
+ gradio_client==0.9.0
24
+ h11==0.14.0
25
+ httpcore==1.0.2
26
+ httpx==0.26.0
27
+ huggingface-hub==0.20.3
28
+ idna==3.6
29
+ importlib-resources==6.1.1
30
+ Jinja2==3.1.3
31
+ jsonschema==4.21.1
32
+ jsonschema-specifications==2023.12.1
33
+ kiwisolver==1.4.5
34
+ markdown-it-py==3.0.0
35
+ MarkupSafe==2.1.5
36
+ matplotlib==3.8.2
37
+ mdurl==0.1.2
38
+ monotonic==1.6
39
+ numpy==1.23.5
40
+ orjson==3.9.13
41
+ packaging==23.2
42
+ pandas==1.5.3
43
+ pillow==10.2.0
44
+ pydantic==2.6.1
45
+ pydantic_core==2.16.2
46
+ pydub==0.25.1
47
+ Pygments==2.17.2
48
+ pyparsing==3.1.1
49
+ python-dateutil==2.8.2
50
+ python-multipart==0.0.7
51
+ pytz==2024.1
52
+ PyYAML==6.0.1
53
+ referencing==0.33.0
54
+ requests==2.31.0
55
+ rich==13.7.0
56
+ rpds-py==0.17.1
57
+ ruff==0.2.1
58
+ semantic-version==2.10.0
59
+ shellingham==1.5.4
60
+ six==1.16.0
61
+ sniffio==1.3.0
62
+ starlette==0.36.3
63
+ tomlkit==0.12.0
64
+ toolz==0.12.1
65
+ tqdm==4.66.1
66
+ typer==0.9.0
67
+ typing_extensions==4.9.0
68
+ urllib3==2.2.0
69
+ uvicorn==0.27.0.post1
70
+ vega-datasets==0.9.0
71
+ websockets==11.0.3
72
+ wrapt==1.14.1