File size: 10,072 Bytes
58d8c29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f73bb6
f272cc4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145deff
731d628
ead70d9
 
 
 
372b939
ead70d9
372b939
ead70d9
 
 
372b939
ead70d9
372b939
ead70d9
 
1f73bb6
 
ead70d9
 
 
 
5f2c2db
 
ead70d9
 
 
372b939
 
ead70d9
 
 
abb2057
372b939
ead70d9
 
 
 
 
 
58d8c29
ead70d9
 
 
 
 
 
 
 
 
 
5f2c2db
ead70d9
1f73bb6
58d8c29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b62d049
58d8c29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7a2ed4
58d8c29
 
 
 
 
 
b7a2ed4
58d8c29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7a2ed4
58d8c29
b7a2ed4
b62d049
58d8c29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
372b939
58d8c29
 
 
 
 
 
 
2f28cd4
58d8c29
 
 
 
 
 
 
 
 
 
 
 
 
 
2f28cd4
58d8c29
 
 
 
2f28cd4
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
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


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")
    )

    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 gauge_chart() -> alt.Chart:
    # Assuming obtain_source_target_datasets() returns a tuple where the first item is the dataset
    source_dataset, _ = obtain_source_target_datasets()
    total_records = int(os.getenv("TARGET_RECORDS"))  # This should be the total number of records you want to annotate.
    annotated_records = len(source_dataset)  # This is the number of records already annotated.
    pending_records = total_records - annotated_records  # Calculate the pending records.

    # Prepare data for the gauge chart
    gauge_data = pd.DataFrame({
        'category': ['Annotated', 'Remaining'],
        'value': [annotated_records, pending_records]
    })

    # The background of the gauge
    base = alt.Chart(pd.DataFrame({'value': [total_records], 'category': ['Total']})).mark_bar(
        color='#e0e0e0', size=40
    ).encode(
        alt.X('value:Q', scale=alt.Scale(domain=[0, total_records]), title='Record Count'),
        alt.Y('category:N', axis=alt.Axis(title=''))
    )

    # The value part of the gauge
    value_bar = alt.Chart(gauge_data).mark_bar(size=40).encode(
        alt.X('value:Q'),
        alt.Y('category:N', axis=alt.Axis(title='')),
        alt.Color('category:N', scale=alt.Scale(domain=['Annotated', 'Remaining'], range=['#28a745', '#dcdcdc']))
    )

    # Combine the bars to create a gauge effect
    chart = alt.layer(base, value_bar).properties(
        title='Progress Towards Goal',
        width=700,
        height=100
    )

    # Add a text label for the current value
    text = alt.Chart(pd.DataFrame({'value': [annotated_records + pending_records/2], 'text': [f'{annotated_records} / {total_records}']})).mark_text(
        align='center', baseline='middle', fontSize=16, fontWeight='bold', dy=-30
    ).encode(
        x='value:Q',
        text='text:N'
    )

    return (chart + text)


import altair as alt
import pandas as pd
import os

def progress_bar_chart() -> alt.Chart:
    # Load your data
    source_dataset, _ = obtain_source_target_datasets()
    total_records = int(os.getenv("TARGET_RECORDS"))
    annotated_records = len(source_dataset)
    percentage_complete = annotated_records / total_records * 100

    # Define the data for the bars
    progress_data = pd.DataFrame({
        'category': ['Completed', 'Pending'],
        'value': [annotated_records, total_records - annotated_records]
    })

    # Base chart for the progress
    base = alt.Chart(progress_data).encode(
        alt.X('value:Q', scale=alt.Scale(domain=[0, total_records]), title='Number of Records'),
        alt.Y('category:N', title='')
    )

    # Colored bar for completion
    bar = base.mark_bar(size=50, color='#28a745').transform_filter(
        alt.datum.category == 'Completed'
    )

    # Gray bar for pending
    background = base.mark_bar(size=50, color='#dcdcdc').transform_filter(
        alt.datum.category == 'Pending'
    )

    # Text for the completed records
    text = base.mark_text(align='left', dx=3, dy=0, fontSize=16, fontWeight='bold', color='black').encode(
        text='value:Q'
    ).transform_filter(
        alt.datum.category == 'Completed'
    )

    # Combine the charts
    chart = alt.layer(background, bar, text).resolve_scale(y='independent').properties(
        width=700,
        height=400,
        title='Progress Towards Goal'
    ).configure_view(
        strokeWidth=0
    ).configure_axis(
        grid=False
    )

    return chart

def donut_chart() -> alt.Chart:
    """
    This function returns a donut chart with the number of annotated and pending records.

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

    source_dataset, _ = obtain_source_target_datasets()
    annotated_records = len(source_dataset)
    pending_records = int(os.getenv("TARGET_RECORDS")) - annotated_records

    source = pd.DataFrame(
        {
            "values": [annotated_records, pending_records],
            "category": ["Submitted", "Pending"],  # Add a new column for categories
        }
    )

    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=10).encode(text="values:Q")

    chart = c1 + c2

    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
    _, target_dataset = obtain_source_target_datasets()
    user_ids_annotations = get_user_annotations_dictionary(target_dataset)
    total_annotators = len(user_ids_annotations)

    # Assuming you have a DataFrame with user data, create a sample DataFrame
    data = pd.DataFrame({"Category": ["Total Contributors"], "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 of Contributors", width=250, height=200)
    )

    return chart


def obtain_top_5_users(user_ids_annotations: Dict[str, int]) -> pd.DataFrame:
    """
    This function returns the top 5 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 5 users with the most annotations.
    """

    dataframe = pd.DataFrame(
        user_ids_annotations.items(), columns=["Name", "Submitted Responses"]
    )
    dataframe = dataframe.sort_values(by="Submitted Responses", ascending=False)
    return dataframe.head(10)


def main() -> None:

    # Connect to the space with rg.init()
    rg.init(
        api_url=os.getenv("ARGILLA_API_URL"),
        api_key=os.getenv("ARGILLA_API_KEY"),
        extra_headers={"Authorization": f"Bearer {os.getenv('HF_TOKEN')}"},
    )

    source_dataset, target_dataset = obtain_source_target_datasets()
    user_ids_annotations = get_user_annotations_dictionary(target_dataset)

    top5_dataframe = obtain_top_5_users(user_ids_annotations)

    with gr.Blocks() as demo:
        gr.Markdown(
            """
            # πŸ—£οΈ The Prompt Collective Dashboad

            This Gradio dashboard shows the progress of the first "Data is Better Together" initiative to understand and collect good quality and diverse prompt for the OSS AI community.
            If you want to contribute to OSS AI, join [the Prompt Collective HF Space](https://huggingface.co/spaces/DIBT/prompt-collective).
            """
        )
        gr.Markdown(
            """
            ## πŸš€ Contributors Progress

            How many records have been submitted, how many are still pending?
            """
        )
        plot = gr.Plot(label="Plot")
        demo.load(
            progress_bar_chart,
            inputs=[],
            outputs=[plot],
        )

        gr.Markdown(
            """
            ## πŸ‘Ύ Contributors Hall of Fame
            The number of all contributors and the top 10 contributors:
            """
        )

        with gr.Row():

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

            gr.Dataframe(
                value=top5_dataframe,
                headers=["Name", "Submitted Responses"],
                datatype=[
                    "str",
                    "number",
                ],
                row_count=10,
                col_count=(2, "fixed"),
                interactive=False,
            ),

    # Launch the Gradio interface
    demo.launch()


if __name__ == "__main__":
    main()