File size: 12,643 Bytes
6b07e4a
 
 
 
fab0ae1
ec60e9a
6b07e4a
 
 
f7387e3
ec60e9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fab0ae1
6b07e4a
 
6da808e
6b07e4a
6da808e
 
 
 
ec60e9a
 
 
 
be34010
ec60e9a
f6c1bc9
 
 
 
ec60e9a
 
 
 
6da808e
ec60e9a
 
 
 
 
 
 
 
 
6da808e
ec60e9a
cc6a423
6da808e
 
 
 
 
ec60e9a
6da808e
 
 
 
 
 
 
5126148
6da808e
 
 
5126148
6da808e
 
 
5126148
6da808e
 
 
5126148
6da808e
 
 
5126148
6da808e
 
 
 
 
 
 
6b07e4a
6da808e
 
 
be34010
 
 
6da808e
 
 
5126148
6da808e
 
5126148
6da808e
 
 
 
5126148
6da808e
 
5126148
6da808e
6b07e4a
6da808e
 
5126148
6da808e
be34010
 
 
6b07e4a
be34010
6da808e
ec60e9a
be34010
 
 
 
fd5c6de
be34010
fd5c6de
be34010
fd5c6de
be34010
 
 
fd5c6de
be34010
6b07e4a
6da808e
 
6b07e4a
 
 
 
f6c1bc9
6b07e4a
f6c1bc9
6b07e4a
 
 
 
 
 
 
ef51dcd
6b07e4a
 
fab0ae1
 
 
 
 
 
 
6b07e4a
 
 
 
 
 
 
 
 
fab0ae1
 
 
 
 
 
6b07e4a
 
 
 
 
 
 
fab0ae1
 
 
 
 
 
6b07e4a
 
 
 
 
 
 
fab0ae1
 
 
 
 
 
 
 
6b07e4a
 
 
 
 
 
fab0ae1
6b07e4a
 
 
 
 
 
 
 
 
 
 
 
 
 
8d31802
 
 
 
 
6b07e4a
8d31802
 
 
6b07e4a
 
8d31802
 
 
 
 
 
 
 
 
 
 
6b07e4a
 
8d31802
 
 
6b07e4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fab0ae1
 
 
 
6b07e4a
fab0ae1
fd5c6de
 
 
 
 
 
 
 
 
 
 
 
 
6b07e4a
 
8d31802
6b07e4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import requests
import gradio as gr
from urllib.parse import urlencode
import os
from datetime import datetime
import json

# Load environment variables

DEFAULT_IMAGE = "https://hub-recap.imglab-cdn.net/default.jpg?width=1200&text=%3Cspan+size%3D%2212pt%22+weight%3D%22bold%22%3EHugging+Face++%E2%9D%A4%EF%B8%8F+bartowski+in+2024%3C%2Fspan%3E%0A%0A%3Cspan+weight%3D%22bold%22%3E2%2C020%2C552%3C%2Fspan%3E+model+downloads%0A%3Cspan+weight%3D%22bold%22%3E5%2C407%3C%2Fspan%3E+model+likes%0A%3Cspan+weight%3D%22bold%22%3E0%3C%2Fspan%3E+dataset+downloads%0A%3Cspan+weight%3D%22bold%22%3E0%3C%2Fspan%3E+dataset+likes%0A%0A%3Cspan+size%3D%2210pt%22%3EMost+Popular+Contributions%3A%3C%2Fspan%3E%0AModel%3A+%3Cspan+weight%3D%22bold%22%3Ebartowski%2Fgemma-2-9b-it-GGUF%3C%2Fspan%3E%0A++%2843%2C949+downloads%2C+196+likes%29%0ADataset%3A+%3Cspan+weight%3D%22bold%22%3ENone%3C%2Fspan%3E%0A++%280+downloads%2C+0+likes%29%0ASpace%3A+%3Cspan+weight%3D%22bold%22%3Ebartowski%2Fgguf-metadata-updater%3C%2Fspan%3E%0A++%287+likes%29&text-width=800&text-height=600&text-padding=60&text-color=39%2C71%2C111&text-x=460&text-y=40&format=png&dpr=2"

# Load percentiles data
with open("percentiles.json") as f:
    PERCENTILES = json.load(f)


def get_percentile_rank(likes, category):
    if likes == 0:
        return 0
    percentiles = PERCENTILES[f"{category}_percentiles"]
    if likes >= percentiles["p_99999"]:
        return 99.999
    elif likes >= percentiles["p_9999"]:
        return 99.99
    elif likes >= percentiles["p_999"]:
        return 99.9
    return 0


def create_image(stats, username):
    # Determine which image to use based on highest value
    total_stats = stats["Total Statistics"]
    model_activity = total_stats["Model Downloads"] + total_stats["Model Likes"]
    dataset_activity = total_stats["Dataset Downloads"] + total_stats["Dataset Likes"]
    space_activity = total_stats["Space Likes"]

    # Calculate percentiles based on likes
    model_percentile = get_percentile_rank(total_stats["Model Likes"], "model")
    dataset_percentile = get_percentile_rank(total_stats["Dataset Likes"], "dataset")
    space_percentile = get_percentile_rank(space_activity, "space")

    # Choose base image URL based on highest activity (keep using activity for image selection)
    if model_activity == 0 and dataset_activity == 0 and space_activity == 0:
        url = "https://hub-recap.imglab-cdn.net/images/empty.png"
        avatar = "new! We couldn't find your stats on the Hub, maybe in 2025?"
    elif model_activity >= max(dataset_activity, space_activity):
        url = "https://hub-recap.imglab-cdn.net/images/model.png"
        avatar = f"Model Pro" + (
            f" (top {model_percentile}%)" if model_percentile > 0 else ""
        )
    elif dataset_activity >= max(model_activity, space_activity):
        url = "https://hub-recap.imglab-cdn.net/images/dataset.png"
        avatar = f"Dataset Guru" + (
            f" (top {dataset_percentile}%)" if dataset_percentile > 0 else ""
        )
    elif space_activity >= max(model_activity, dataset_activity):
        url = "https://hub-recap.imglab-cdn.net/images/space.png"
        avatar = f"Space Artiste" + (
            f" (top {space_percentile}%)" if space_percentile > 0 else ""
        )
    else:
        url = "https://hub-recap.imglab-cdn.net/images/empty.png"
        avatar = "newbie! We couldn't find your stats on the Hub, maybe in 2025?"

    # Build text content with proper formatting
    text_parts = []

    text_parts.append(
        f'<span size="11pt" weight="bold">Hugging Face ❤️ {username} in 2024</span>'
    )
    text_parts.append("")  # Empty line for spacing

    # Stats section
    stats_lines = []
    if total_stats["Model Downloads"] > 0:
        stats_lines.append(
            f'<span size="9pt"><span weight="bold">{total_stats["Model Downloads"]:,}</span> model downloads</span>'
        )
    if total_stats["Model Likes"] > 0:
        stats_lines.append(
            f'<span size="9pt"><span weight="bold">{total_stats["Model Likes"]:,}</span> model likes</span>'
        )
    if total_stats["Dataset Downloads"] > 0:
        stats_lines.append(
            f'<span size="9pt"><span weight="bold">{total_stats["Dataset Downloads"]:,}</span> dataset downloads</span>'
        )
    if total_stats["Dataset Likes"] > 0:
        stats_lines.append(
            f'<span size="9pt"><span weight="bold">{total_stats["Dataset Likes"]:,}</span> dataset likes</span>'
        )
    if total_stats["Space Likes"] > 0:
        stats_lines.append(
            f'<span size="9pt"><span weight="bold">{total_stats["Space Likes"]:,}</span> space likes</span>'
        )

    if stats_lines:
        text_parts.extend(stats_lines)
        text_parts.append("")  # Empty line for spacing

    # Popular items section
    top_items = stats["Most Popular Items"]
    if any(
        item["likes"] > 0 or item.get("downloads", 0) > 0 for item in top_items.values()
    ):
        text_parts.append(
            '<span size="9pt" weight="bold">Most Popular Contributions:</span>'
        )

        if top_items["Top Model"]["downloads"] > 0:
            text_parts.append(
                f'<span size="9pt">Model: <span weight="bold">{top_items["Top Model"]["name"]}</span></span>'
            )
            text_parts.append(
                f'<span size="9pt">  ({top_items["Top Model"]["downloads"]:,} downloads, {top_items["Top Model"]["likes"]} likes)</span>'
            )

        if top_items["Top Dataset"]["downloads"] > 0:
            text_parts.append(
                f'<span size="9pt">Dataset: <span weight="bold">{top_items["Top Dataset"]["name"]}</span></span>'
            )
            text_parts.append(
                f'<span size="9pt">  ({top_items["Top Dataset"]["downloads"]:,} downloads, {top_items["Top Dataset"]["likes"]} likes)</span>'
            )

        if top_items["Top Space"]["likes"] > 0:
            text_parts.append(
                f'<span size="9pt">Space: <span weight="bold">{top_items["Top Space"]["name"]}</span></span>'
            )
            text_parts.append(
                f'<span size="9pt">  ({top_items["Top Space"]["likes"]} likes)</span>'
            )

    # Update the avatar message with percentile
    text_parts.append("")  # Empty line for spacing
    text_parts.append(f'<span size="9pt">You are a {avatar}!</span>')

    # Add additional percentile info if other categories are significant
    other_percentiles = []
    if model_percentile > 0 and "model" not in avatar.lower():
        other_percentiles.append(f"Top {model_percentile}% in models")
    if dataset_percentile > 0 and "dataset" not in avatar.lower():
        other_percentiles.append(f"Top {dataset_percentile}% in datasets")
    if space_percentile > 0 and "space" not in avatar.lower():
        other_percentiles.append(f"Top {space_percentile}% in spaces")

    if other_percentiles:
        text_parts.append(
            f'<span size="9pt">{". ".join(other_percentiles)}!</span>'
        )

    # Join all parts with newlines
    text = "\n".join(text_parts)

    params = {
        "width": "1200",
        "text": text,
        "text-width": "700",
        "text-height": "600",
        "text-padding": "30",
        "text-color": "39,71,111",
        "text-x": "460",
        "text-y": "40",
        "format": "png",
        "dpr": "2",
    }

    return f"{url}?{urlencode(params)}"


def is_from_2024(created_at_str):
    if not created_at_str:
        return False
    created_at = datetime.strptime(created_at_str, "%Y-%m-%dT%H:%M:%S.%fZ")
    return created_at.year == 2024


def get_user_stats(username):
    headers = {"Authorization": f"Bearer {os.getenv('HF_TOKEN')}"}

    # Get models stats
    models_response = requests.get(
        "https://huggingface.co/api/models",
        params={"author": username, "full": "True"},
        headers=headers,
    )
    # Filter for 2024 models only
    models = [
        model
        for model in models_response.json()
        if is_from_2024(model.get("createdAt"))
    ]

    # Get datasets stats
    datasets_response = requests.get(
        "https://huggingface.co/api/datasets",
        params={"author": username, "full": "True"},
        headers=headers,
    )
    # Filter for 2024 datasets only
    datasets = [
        dataset
        for dataset in datasets_response.json()
        if is_from_2024(dataset.get("createdAt"))
    ]

    # Get spaces stats
    spaces_response = requests.get(
        "https://huggingface.co/api/spaces",
        params={"author": username, "full": "True"},
        headers=headers,
    )
    # Filter for 2024 spaces only
    spaces = [
        space
        for space in spaces_response.json()
        if is_from_2024(space.get("createdAt"))
    ]

    # Calculate totals for 2024 items only
    total_model_downloads = sum(model.get("downloads", 0) for model in models)
    total_model_likes = sum(model.get("likes", 0) for model in models)
    total_dataset_downloads = sum(dataset.get("downloads", 0) for dataset in datasets)
    total_dataset_likes = sum(dataset.get("likes", 0) for dataset in datasets)
    total_space_likes = sum(space.get("likes", 0) for space in spaces)

    # Find most liked items from 2024
    most_liked_model = max(models, key=lambda x: x.get("likes", 0), default=None)
    most_liked_dataset = max(datasets, key=lambda x: x.get("likes", 0), default=None)
    most_liked_space = max(spaces, key=lambda x: x.get("likes", 0), default=None)

    stats = {
        "Total Statistics": {
            "Model Downloads": total_model_downloads,
            "Model Likes": total_model_likes,
            "Dataset Downloads": total_dataset_downloads,
            "Dataset Likes": total_dataset_likes,
            "Space Likes": total_space_likes,
        },
        "Most Popular Items": {
            "Top Model": {
                "name": (
                    most_liked_model.get("modelId", "None")
                    if most_liked_model
                    else "None"
                ),
                "likes": most_liked_model.get("likes", 0) if most_liked_model else 0,
                "downloads": (
                    most_liked_model.get("downloads", 0) if most_liked_model else 0
                ),
            },
            "Top Dataset": {
                "name": (
                    most_liked_dataset.get("id", "None")
                    if most_liked_dataset
                    else "None"
                ),
                "likes": (
                    most_liked_dataset.get("likes", 0) if most_liked_dataset else 0
                ),
                "downloads": (
                    most_liked_dataset.get("downloads", 0) if most_liked_dataset else 0
                ),
            },
            "Top Space": {
                "name": (
                    most_liked_space.get("id", "None") if most_liked_space else "None"
                ),
                "likes": most_liked_space.get("likes", 0) if most_liked_space else 0,
            },
        },
    }

    # Generate image URL
    image_url = create_image(stats, username)

    return image_url


with gr.Blocks(title="Hugging Face Community Stats") as demo:
    gr.Markdown("# Hugging Face Community Recap")
    gr.Markdown(
        "Enter a username to see their impact and top contributions across the Hugging Face Hub"
    )

    with gr.Row():
        username_input = gr.Textbox(
            label="Hub username",
            placeholder="Enter Hugging Face username...",
            scale=6,
            value="bartowski",
        )
        submit_btn = gr.Button("Get Stats", scale=6)
    with gr.Row():
        # Add example usernames
        gr.Examples(
            examples=[
                ["merve"],
                ["mlabonne"],
                ["bartowski"],
                ["huggingface"],
                ["cfahlgren1"],
            ],
            inputs=username_input,
            label="Try these examples",
        )
    with gr.Row():
        with gr.Column():
            stats_image = gr.Markdown(f"![Hugging Face Stats]({DEFAULT_IMAGE})")

    def format_markdown(image_url):
        return f"![Hugging Face Stats]({image_url})"

    # Handle submission
    submit_btn.click(
        fn=lambda x: format_markdown(get_user_stats(x)),
        inputs=username_input,
        outputs=stats_image,
        api_name="get_stats",
    )
    # Also trigger on enter key
    username_input.submit(
        fn=lambda x: format_markdown(get_user_stats(x)),
        inputs=username_input,
        outputs=stats_image,
    )

if __name__ == "__main__":
    demo.launch()