File size: 24,758 Bytes
beff869
fd86c50
1c1de6b
fb3b924
 
 
1c1de6b
f954a72
fb3b924
5a667ef
fb3b924
 
 
 
f232a9e
 
ffba8f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f232a9e
82f57d3
f232a9e
 
 
ffba8f1
f232a9e
 
 
 
 
 
35028de
f232a9e
 
fb3b924
1c1de6b
 
fb3b924
1c1de6b
 
 
 
 
 
fb3b924
 
 
1c1de6b
 
 
 
fb3b924
 
 
a5b7670
 
 
 
 
 
 
 
fb3b924
ea78272
fb3b924
1c1de6b
5a667ef
fb3b924
1c1de6b
 
fb3b924
 
ea78272
 
1c1de6b
 
 
 
 
 
ea78272
1c1de6b
 
 
ea78272
1c1de6b
 
 
 
 
ea78272
1c1de6b
 
ea78272
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c1de6b
fb3b924
 
 
0c42d93
1c1de6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3b924
 
fec983f
 
 
fb3b924
 
 
 
 
 
1c1de6b
 
 
 
fb3b924
0c42d93
 
 
1c1de6b
 
fec983f
fb3b924
1c1de6b
 
d2fc390
1c1de6b
fb3b924
 
0c42d93
 
1c1de6b
 
 
0c42d93
1c1de6b
 
 
0c42d93
1c1de6b
 
0c42d93
1c1de6b
 
 
 
 
0c42d93
 
 
 
 
 
1c1de6b
 
0c42d93
1c1de6b
0c42d93
5a667ef
1c1de6b
7207931
 
 
 
 
 
 
 
 
35028de
 
364e449
7207931
 
ea78272
1c1de6b
ea78272
1c1de6b
ea78272
 
 
 
 
 
 
 
 
 
 
 
 
71fd248
ea78272
71fd248
5a667ef
1c1de6b
 
 
 
 
 
 
 
 
 
5a667ef
 
1c1de6b
ea78272
fb3b924
1c1de6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffba8f1
1c1de6b
 
ffba8f1
1c1de6b
ffba8f1
1c1de6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffba8f1
1c1de6b
 
ffba8f1
1c1de6b
ffba8f1
1c1de6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffba8f1
1c1de6b
 
ffba8f1
1c1de6b
ffba8f1
1c1de6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3b924
1c1de6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffba8f1
1c1de6b
 
 
 
 
 
 
 
ffba8f1
1c1de6b
 
 
 
 
 
 
 
 
ffba8f1
1c1de6b
 
 
f232a9e
1c1de6b
 
 
 
 
 
 
 
 
fb3b924
ea78272
f232a9e
 
 
1c1de6b
9df3444
1c1de6b
fb3b924
1c1de6b
fb3b924
1c1de6b
fb3b924
1c1de6b
fb3b924
1c1de6b
fb3b924
 
ffba8f1
 
 
 
 
7e67a2b
ffba8f1
 
fb3b924
ffba8f1
5a667ef
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
import os
os.system("wget https://raw.githubusercontent.com/Weyaxi/scrape-open-llm-leaderboard/main/openllm.py")
from openllm import *
import requests
import pandas as pd
from bs4 import BeautifulSoup
from tqdm import tqdm
from huggingface_hub import HfApi, CommitOperationAdd, create_commit
import gradio as gr
import datetime

api = HfApi()


HF_TOKEN = os.getenv('HF_TOKEN')


headers_models = ["🔢 Serial Number", "👤 Author Name", "📥 Total Downloads", "👍 Total Likes", "🤖 Number of Models",
            "🏆 Best Model On Open LLM Leaderboard", "🥇 Best Rank On Open LLM Leaderboard",
            "📊 Average Downloads per Model", "📈 Average Likes per Model", "🚀 Most Downloaded Model",
            "📈 Most Download Count", "❤️ Most Liked Model", "👍 Most Like Count", "🔥 Trending Model",
            "👑 Best Rank at Trending Models", "🏷️ Type"]

headers_datasets = ["🔢 Serial Number", "👤 Author Name", "📥 Total Downloads", "👍 Total Likes", "📊 Number of Datasets",
            "📊 Average Downloads per Dataset", "📈 Average Likes per Dataset", "🚀 Most Downloaded Dataset",
            "📈 Most Download Count", "❤️ Most Liked Dataset", "👍 Most Like Count", "🔥 Trending Dataset",
            "👑 Best Rank at Trending Datasets", "🏷️ Type"]

headers_spaces = ["🔢 Serial Number", "👤 Author Name", "👍 Total Likes", "🚀 Number of Spaces", "📈 Average Likes per Space",
            "❤️ Most Liked Space", "👍 Most Like Count", "🔥 Trending Space", "👑 Best Rank at Trending Spaces",
            "🏷️ Type"]


def apply_headers(df, headers):
    tmp = df.copy()
    tmp.columns = headers

    return tmp


def get_time():
    return datetime.datetime.now().strftime("%d-%m-%Y %H-%M")


def upload_datasets(dfs):

  time = get_time()

  operations = [CommitOperationAdd(path_in_repo=f"{time}/models_df.csv", path_or_fileobj=(dfs[0].to_csv()).encode()),
                CommitOperationAdd(path_in_repo=f"{time}/datasets_df.csv", path_or_fileobj=(dfs[1].to_csv()).encode()),
                CommitOperationAdd(path_in_repo=f"{time}/spaces_df.csv", path_or_fileobj=(dfs[2].to_csv()).encode())]

  return (create_commit(repo_id="Weyaxi/huggingface-leaderboard-history", operations=operations, commit_message=f"Uploading history of {time}", repo_type="dataset", token=HF_TOKEN))


def get_most(df_for_most_function):
    download_sorted_df = df_for_most_function.sort_values(by=['downloads'], ascending=False)
    most_downloaded = download_sorted_df.iloc[0]

    like_sorted_df = df_for_most_function.sort_values(by=['likes'], ascending=False)
    most_liked = like_sorted_df.iloc[0]

    return {"Most Download": {"id": most_downloaded['id'], "downloads": most_downloaded['downloads'],
                              "likes": most_downloaded['likes']},
            "Most Likes": {"id": most_liked['id'], "downloads": most_liked['downloads'], "likes": most_liked['likes']}}


def get_sum(df_for_sum_function):
    sum_downloads = sum(df_for_sum_function['downloads'].tolist())
    sum_likes = sum(df_for_sum_function['likes'].tolist())

    return {"Downloads": sum_downloads, "Likes": sum_likes}


def get_openllm_leaderboard():
    try:
        data = get_json_format_data()
        finished_models = get_datas(data)
        df = pd.DataFrame(finished_models)
        return df['Model'].tolist()
    except Exception as e:  # something is wrong about the leaderboard so return empty list
        print(e)
        return []


def get_ranking(model_list, target_org):
    if not model_list:
        return "Error on Leaderboard"
    for index, model in enumerate(model_list):
        if model.split("/")[0].lower() == target_org.lower():
            return [index + 1, model]
    return "Not Found"


def get_models(which_one):
    if which_one == "models":
        data = api.list_models()
    elif which_one == "datasets":
        data = api.list_datasets()
    elif which_one == "spaces":
        data = api.list_spaces()

    all_list = []
    for i in tqdm(data, desc=f"Scraping {which_one}", position=0, leave=True):
        i = i.__dict__

        id = i["id"].split("/")
        if len(id) != 1:
            json_format_data = {"author": id[0], "id": "/".join(id), "downloads": i['downloads'],
                                "likes": i['likes']} if which_one != "spaces" else {"author": id[0], "id": "/".join(id),
                                                                                    "downloads": 0, "likes": i['likes']}

            all_list.append(json_format_data)
    return all_list



def search(models_dict, author_name):
    return pd.DataFrame(models_dict.get(author_name, []))


def group_models_by_author(all_things):
    models_by_author = {}
    for model in all_things:
        author_name = model['author']
        if author_name not in models_by_author:
            models_by_author[author_name] = []
        models_by_author[author_name].append(model)
    return models_by_author


def make_leaderboard(orgs, users, which_one, data):
    data_rows = []
    open_llm_leaderboard = get_openllm_leaderboard() if which_one == "models" else None

    trend = get_trending_list(1, which_one)
    hepsi = [orgs, users]

    for index, orgs in enumerate(hepsi):
        org_or_user = "Organization" if index == 0 else "User"
        for org in tqdm(orgs, desc=f"Proccesing: ({which_one}) ({org_or_user})", position=0, leave=True):
            rank = get_ranking_trend(trend, org)

            df = search(data, org)

            if len(df) == 0:
                continue
            num_things = len(df)
            sum_info = get_sum(df)
            most_info = get_most(df)

            if which_one == "models":
                open_llm_leaderboard_get_org = get_ranking(open_llm_leaderboard, org)

                data_rows.append({
                    "Author Name": org,
                    "Total Downloads": sum_info["Downloads"],
                    "Total Likes": sum_info["Likes"],
                    "Number of Models": num_things,
                    "Best Model On Open LLM Leaderboard": open_llm_leaderboard_get_org[1] if open_llm_leaderboard_get_org != "Not Found" else open_llm_leaderboard_get_org,
                    "Best Rank On Open LLM Leaderboard": open_llm_leaderboard_get_org[0] if open_llm_leaderboard_get_org != "Not Found" else open_llm_leaderboard_get_org,
                    "Average Downloads per Model": int(sum_info["Downloads"] / num_things) if num_things != 0 else 0,
                    "Average Likes per Model": int(sum_info["Likes"] / num_things) if num_things != 0 else 0,
                    "Most Downloaded Model": most_info["Most Download"]["id"],
                    "Most Download Count": most_info["Most Download"]["downloads"],
                    "Most Liked Model": most_info["Most Likes"]["id"],
                    "Most Like Count": most_info["Most Likes"]["likes"],
                    "Trending Model": rank['id'],
                    "Best Rank at Trending Models": rank['rank'],
                    "Type": org_or_user
                })
            elif which_one == "datasets":

                data_rows.append({
                    "Author Name": org,
                    "Total Downloads": sum_info["Downloads"],
                    "Total Likes": sum_info["Likes"],
                    "Number of Datasets": num_things,
                    "Average Downloads per Dataset": int(sum_info["Downloads"] / num_things) if num_things != 0 else 0,
                    "Average Likes per Dataset": int(sum_info["Likes"] / num_things) if num_things != 0 else 0,
                    "Most Downloaded Dataset": most_info["Most Download"]["id"],
                    "Most Download Count": most_info["Most Download"]["downloads"],
                    "Most Liked Dataset": most_info["Most Likes"]["id"],
                    "Most Like Count": most_info["Most Likes"]["likes"],
                    "Trending Dataset": rank['id'],
                    "Best Rank at Trending Datasets": rank['rank'],
                    "Type": org_or_user
                })

            elif which_one == "spaces":

                data_rows.append({
                    "Author Name": org,
                    "Total Likes": sum_info["Likes"],
                    "Number of Spaces": num_things,
                    "Average Likes per Space": int(sum_info["Likes"] / num_things) if num_things != 0 else 0,
                    "Most Liked Space": most_info["Most Likes"]["id"],
                    "Most Like Count": most_info["Most Likes"]["likes"],
                    "Trending Space": rank['id'],
                    "Best Rank at Trending Spaces": rank['rank'],
                    "Type": org_or_user
                })

    leaderboard = pd.DataFrame(data_rows)
    temp = ["Total Downloads"] if which_one != "spaces" else ["Total Likes"]

    leaderboard = leaderboard.sort_values(by=temp, ascending=False)
    leaderboard.insert(0, "Serial Number", range(1, len(leaderboard) + 1))
    return leaderboard


def clickable(x, which_one):
    if which_one == "models":
        if x != "Not Found":
            return f'<a target="_blank" href="https://huggingface.co/{x}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{x}</a>'
        else:
            return "Not Found"
    else:
        if x != "Not Found":
            return f'<a target="_blank" href="https://huggingface.co/{which_one}/{x}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{x}</a>'
        return "Not Found"


def models_df_to_clickable(df, columns, which_one):
    for column in columns:
        if column == "Author Name":
            df[column] = df[column].apply(lambda x: clickable(x, "models"))
        else:
            df[column] = df[column].apply(lambda x: clickable(x, which_one))
    return df


def get_trending_list(pages, which_one):
    trending_list = []
    for i in range(pages):
        json_data = requests.get(f"https://huggingface.co/{which_one}-json?p={i}").json()

        for thing in json_data[which_one]:
            id = thing["id"]
            likes = thing["likes"]

            if which_one != "spaces":
                downloads = thing["downloads"]

                trending_list.append({"id": id, "downloads": downloads, "likes": likes})
            else:
                trending_list.append({"id": id, "likes": likes})

    return trending_list


def get_ranking_trend(json_data, org_name):
    names = [item['id'].split("/")[0] for item in json_data]
    models = [item['id'] for item in json_data]
    if org_name in names:
        temp = names.index(org_name)
        return {"id": models[temp], "rank": temp + 1}
    else:
        return {"id": "Not Found", "rank": "Not Found"}



def fetch_data_from_url(url):
    response = requests.get(url)
    if response.status_code == 200:
        data = response.text.splitlines()
        return [line.rstrip("\n") for line in data]
    else:
        print(f"Failed to fetch data from URL: {url}")
        return []

user_names_url = "https://huggingface.co/datasets/Weyaxi/user-orgs-huggingface-leaderboard/raw/main/user_names.txt"
org_names_url = "https://huggingface.co/datasets/Weyaxi/user-orgs-huggingface-leaderboard/raw/main/org_names.txt"

user_names_in_list = fetch_data_from_url(user_names_url)
org_names_in_list = fetch_data_from_url(org_names_url)

datetime_now = str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))
INTRODUCTION_TEXT = f"""
🎯 The Leaderboard aims to track users and organizations rankings and stats. This space is inspired by the [Open LLM Leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard).

## Available Dataframes:

- 🏛️ Models

- 📊 Datasets

- 🚀 Spaces

## Backend

🛠️ The leaderboard's backend mainly runs on the [Hugging Face Hub API](https://huggingface.co/docs/huggingface_hub/v0.5.1/en/package_reference/hf_api).

📒 **Note:** In the model's dataframe, there are some columns related to the [Open LLM Leaderboard](https://huggingface.co/spaces/HuggingFaceH4/open_llm_leaderboard). This data is also retrieved through web scraping.

📒 **Note:** In trending models/datasets/spaces, first 300 models/datasets/spaces is being retrieved from huggingface.

## 🔍 Searching Organizations and Users

You can search for organizations and users in the Search tab. In this tab, you can view an author's stats even if they are not at the top of the leaderboard.

## Filtering Organizations and Users

🧮 You can filter the dataset to show only Organizations or Users!

✅ Use checkboxs for this!

## Last Update

⌛ This space is last updated in **{datetime_now}**.
"""



def get_avatar(user_name, user):
  try:
    url = f"https://huggingface.co/{user_name}"
    response = requests.get(url)
    soup = BeautifulSoup(response.text, "html.parser")
    if user:

      avatar = soup.find("img", {"class": "h-32 w-32 overflow-hidden rounded-full shadow-inner lg:h-48 lg:w-48"})['src']
      full = soup.find("span", {"class": "mr-3 leading-6"}).text
      return [avatar, full]

    else:

      avatar = soup.find("img", {"class": "mb-2 mr-4 h-12 w-12 flex-none overflow-hidden rounded-lg sm:mb-0 sm:h-20 sm:w-20"})['src']
      full = soup.find("h1", {"class": "mb-2 mr-3 text-2xl font-bold md:mb-0"}).text
      return [avatar, full]
  except Exception as e:
    print(e)
    return "Error"


def update_table(orgs, users, how_much=400, return_all=False):
    dataFrame = models_df

    if not orgs and users:
        filtered_df = dataFrame[(dataFrame['Type'] != 'Organization') | (dataFrame['Type'] == 'User')]

    elif orgs and not users:
        filtered_df = dataFrame[(dataFrame['Type'] == 'Organization') | (dataFrame['Type'] != 'User')]

    elif orgs and users:
        filtered_df = dataFrame[(dataFrame['Type'] == 'Organization') | (dataFrame['Type'] == 'User')]

    else:
        return apply_headers(dataFrame.head(0), headers_models)

    if return_all:
        return apply_headers(filtered_df, headers_models)
    else:
        return apply_headers(filtered_df, headers_models).head(how_much)


def update_table_datasets(orgs, users, how_much=250, return_all=False):
    dataFrame = dataset_df

    if not orgs and users:
        filtered_df = dataFrame[(dataFrame['Type'] != 'Organization') | (dataFrame['Type'] == 'User')]

    elif orgs and not users:
        filtered_df = dataFrame[(dataFrame['Type'] == 'Organization') | (dataFrame['Type'] != 'User')]

    elif orgs and users:
        filtered_df = dataFrame[(dataFrame['Type'] == 'Organization') | (dataFrame['Type'] == 'User')]

    else:
        return apply_headers(dataFrame, headers_datasets).head(0)

    if return_all:
        return apply_headers(filtered_df, headers_datasets)
    else:
        return apply_headers(filtered_df, headers_datasets).head(how_much)


def update_table_spaces(orgs, users, how_much=200, return_all=False):
    dataFrame = spaces_df

    if not orgs and users:
        filtered_df = dataFrame[(dataFrame['Type'] != 'Organization') | (dataFrame['Type'] == 'User')]

    elif orgs and not users:
        filtered_df = dataFrame[(dataFrame['Type'] == 'Organization') | (dataFrame['Type'] != 'User')]

    elif orgs and users:
        filtered_df = dataFrame[(dataFrame['Type'] == 'Organization') | (dataFrame['Type'] == 'User')]

    else:
        return apply_headers(dataFrame, headers_spaces).head(0)

    if return_all:
        return apply_headers(filtered_df, headers_spaces)
    else:
        return apply_headers(filtered_df, headers_spaces).head(how_much)



def search_df(author):
  sonuc_models, sonuc_datasets, sonuc_spaces =[], [], []
  org_or_user = "User" if author in user_names_in_list else "Org"

  a = get_avatar(author, True if org_or_user=="User" else False)

  if a == "Error":
    return "Error happened, maybe author name is not valid."

  # Search in models_df
  df = models_df
  for index, item in enumerate(df['Author Name'].tolist()):
      if f'"https://huggingface.co/{author}"' in item:
          sonuc_models = df.iloc[index]
          break  # Break out of the loop once a match is found

  # Search in dataset_df
  df = dataset_df
  for index, item in enumerate(df['Author Name'].tolist()):
      if f'"https://huggingface.co/{author}"' in item:
          sonuc_datasets = df.iloc[index]
          break  # Break out of the loop once a match is found

  # Search in spaces_df
  df = spaces_df
  for index, item in enumerate(df['Author Name'].tolist()):
      if f'"https://huggingface.co/{author}"' in item:
          sonuc_spaces = df.iloc[index]
          break  # Break out of the loop once a match is found



  author_name = sonuc_models['Author Name'] if len(sonuc_models) > 0 else "Not Found"
  global_rank = sonuc_models['Serial Number'] if len(sonuc_models) > 0 else "Not Found"

  if len(sonuc_models) > 0:
      if org_or_user == "User":
          user_rank = filtered_model_users.index(f'<a target="_blank" href="https://huggingface.co/{author}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{author}</a>')
      else:
          user_rank = filtered_model_orgs.index(f'<a target="_blank" href="https://huggingface.co/{author}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{author}</a>')
  else:
    user_rank = "Not Found"

  global_datasets = sonuc_datasets['Serial Number'] if len(sonuc_datasets) > 0 else "Not Found"

  if len(sonuc_datasets) > 0:
      if org_or_user == "User":
          user_datasets = filtered_datasets_users.index(f'<a target="_blank" href="https://huggingface.co/{author}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{author}</a>')
      else:
          user_datasets = filtered_datasets_orgs.index(f'<a target="_blank" href="https://huggingface.co/{author}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{author}</a>')
  else:
      user_datasets = "Not Found"


  global_spaces = sonuc_spaces['Serial Number'] if len(sonuc_spaces) > 0 else "Not Found"

  if len(sonuc_spaces) > 0:
    if org_or_user == "User":
        user_spaces = filtered_spaces_users.index(f'<a target="_blank" href="https://huggingface.co/{author}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{author}</a>')
    else:
        user_spaces = filtered_spaces_orgs.index(f'<a target="_blank" href="https://huggingface.co/{author}" style="color: var(--link-text-color); text-decoration: underline;text-decoration-style: dotted;">{author}</a>')
  else:
      user_spaces = "Not Found"

  total_model_downloads = sonuc_models['Total Downloads'] if len(sonuc_models) > 0 else "Not Found"
  total_model_likes = sonuc_models['Total Likes'] if len(sonuc_models) > 0 else "Not Found"
  model_count = sonuc_models['Number of Models'] if len(sonuc_models) > 0 else "Not Found"
  total_dataset_downloads = sonuc_datasets['Total Downloads'] if len(sonuc_datasets) > 0 else "Not Found"
  total_dataset_likes = sonuc_datasets['Total Likes'] if len(sonuc_datasets) > 0 else "Not Found"
  dataset_count = sonuc_datasets['Number of Datasets'] if len(sonuc_datasets) > 0 else "Not Found"
  total_space_likes = sonuc_spaces['Total Likes'] if len(sonuc_spaces) > 0 else "Not Found"
  space_count = sonuc_spaces['Number of Spaces'] if len(sonuc_spaces) > 0 else "Not Found"




  markdown_text = f'''
  <img style="float: right;" src="{a[0]}">
  <h1>{author_name} ({a[1]})<h1>

  ## 🏆 Ranks
  - Global: {global_rank}
  - Models in authors category: {user_rank}
  - Datasets (global): {global_datasets}
  - Datasets in authors category: {user_datasets}
  - Spaces (global): {global_spaces}
  - Spaces in authors category: {user_spaces}

  ## 🤖 Models
  - Total downloads: {total_model_downloads}
  - Total Likes: {total_model_likes}
  - Model count: {model_count}

  ## 📊 Datasets
  - Total downloads: {total_dataset_downloads}
  - Total Likes: {total_dataset_likes}
  - Dataset count: {dataset_count}

  ## 🚀 Spaces
  - Total Likes: {total_space_likes}
  - Spaces count: {space_count}
  '''

  return markdown_text


with gr.Blocks() as demo:
    gr.Markdown("""<h1 align="center" id="space-title">🤗 Huggingface Leaderboard</h1>""")
    gr.Markdown(INTRODUCTION_TEXT, elem_classes="markdown-text")

    all_models = get_models("models")
    all_datasets = get_models("datasets")
    all_spaces = get_models("spaces")

    with gr.Column(min_width=320):
        with gr.Box():
            orgs = gr.Checkbox(value=True, label="Show Organizations", interactive=True)
            users = gr.Checkbox(value=True, label="Show users", interactive=True)

    with gr.TabItem("🏛️ Models", id=1):
        columns_to_convert = ["Author Name", "Best Model On Open LLM Leaderboard", "Most Downloaded Model",
                              "Most Liked Model", "Trending Model"]
        models_df = make_leaderboard(org_names_in_list, user_names_in_list, "models", group_models_by_author(all_models))
        models_df = models_df_to_clickable(models_df, columns_to_convert, "models")

        gr_models = gr.Dataframe(apply_headers(models_df, headers_models).head(400), headers=headers_models, interactive=True,
                                 datatype=["str", "markdown", "str", "str", "str", "markdown", "str", "str", "str",
                                           "markdown", "str", "markdown", "str", "markdown", "str", "str"])

    with gr.TabItem("📊 Datasets", id=2):
        columns_to_convert = ["Author Name", "Most Downloaded Dataset", "Most Liked Dataset", "Trending Dataset"]
        dataset_df = make_leaderboard(org_names_in_list, user_names_in_list, "datasets", group_models_by_author(all_datasets))
        dataset_df = models_df_to_clickable(dataset_df, columns_to_convert, "datasets")

        gr_datasets = gr.Dataframe(apply_headers(dataset_df, headers_datasets).head(250), headers=headers_datasets, interactive=False,
                                   datatype=["str", "markdown", "str", "str", "str", "str", "str", "markdown", "str",
                                             "markdown", "str", "markdown", "str", "str"])

    with gr.TabItem("🚀 Spaces", id=3):
        columns_to_convert = ["Author Name", "Most Liked Space", "Trending Space"]

        spaces_df = make_leaderboard(org_names_in_list, user_names_in_list, "spaces", group_models_by_author(all_spaces))
        spaces_df = models_df_to_clickable(spaces_df, columns_to_convert, "spaces")

        gr_spaces = gr.Dataframe(apply_headers(spaces_df, headers_spaces).head(200), headers=headers_spaces, interactive=False,
                                 datatype=["str", "markdown", "str", "str", "str", "markdown", "str", "markdown", "str",
                                           "str"])

    
    with gr.TabItem("🔍 Search", id=4):
      with gr.Column(min_width=320):
            search_bar = gr.Textbox(
                          placeholder=" 🔍 Search for your author and press ENTER",
                          show_label=False)
            run_btn = gr.Button("Show stats for author")
      yazi = gr.Markdown()
      run_btn.click(fn=search_df, inputs=search_bar, outputs=yazi)
      search_bar.submit(fn=search_df, inputs=search_bar, outputs=yazi)


    commit = upload_datasets([models_df, dataset_df, spaces_df])
    print(commit)

    orgs.change(fn=update_table, inputs=[orgs, users], outputs=gr_models)

    orgs.change(fn=update_table_datasets, inputs=[orgs, users], outputs=gr_datasets)

    orgs.change(fn=update_table_spaces, inputs=[orgs, users], outputs=gr_spaces)

    users.change(fn=update_table, inputs=[orgs, users], outputs=gr_models)

    users.change(fn=update_table_datasets, inputs=[orgs, users], outputs=gr_datasets)

    users.change(fn=update_table_spaces, inputs=[orgs, users], outputs=gr_spaces)


filtered_model_users = update_table(orgs=False, users=True, return_all=True)['👤 Author Name'].tolist()
filtered_model_orgs = update_table(orgs=True, users=False, return_all=True)['👤 Author Name'].tolist()

filtered_datasets_users = update_table_datasets(orgs=False, users=True, return_all=True)['👤 Author Name'].tolist()
filtered_datasets_orgs = update_table_datasets(orgs=True, users=False, return_all=True)['👤 Author Name'].tolist()

filtered_spaces_users = update_table_spaces(orgs=False, users=True, return_all=True)['👤 Author Name'].tolist()
filtered_spaces_orgs = update_table_spaces(orgs=True, users=False, return_all=True)['👤 Author Name'].tolist()

demo.launch(debug=True)