lunarflu HF staff commited on
Commit
e91740b
·
verified ·
1 Parent(s): 71989fb

misc cleanup

Browse files
Files changed (1) hide show
  1. app.py +43 -61
app.py CHANGED
@@ -1,20 +1,13 @@
1
  import asyncio
2
- import csv
3
  import datetime
4
  import json
5
- import logging
6
  import os
7
  import os.path
8
- import random
9
- import re
10
  import threading
11
- import time
12
 
13
  import discord
14
  import gradio as gr
15
- import gradio_client
16
  import gspread
17
- import numpy as np
18
  import pandas as pd
19
  import requests
20
 
@@ -23,20 +16,15 @@ from apscheduler.executors.pool import ThreadPoolExecutor
23
  from apscheduler.schedulers.background import BackgroundScheduler
24
  from discord import Color, Embed
25
  from discord.ext import commands, tasks
26
- from gradio_client import Client
27
- from gspread_dataframe import get_as_dataframe, set_with_dataframe
28
- from gspread_formatting.dataframe import format_with_dataframe
29
- from huggingface_hub import HfApi, list_liked_repos, list_metrics, list_models
30
  from tabulate import tabulate
31
- from datetime import datetime
32
 
33
  DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
34
  intents = discord.Intents.all()
35
  bot = commands.Bot(command_prefix='!', intents=intents)
36
 
37
- #logger = logging.getLogger(__name__)
38
- #logging.basicConfig(level=logging.DEBUG)
39
-
40
 
41
  """"""
42
  XP_PER_MESSAGE = 10 # 100k messages = 1M exp = lvl 100
@@ -53,14 +41,13 @@ bot_ids = [1136614989411655780, 1166392942387265536, 1158038249835610123, 113077
53
  """"""
54
  api = HfApi()
55
  """"""
56
- #csv_file = 'data.csv'
57
  global_df = pd.DataFrame()
58
  print(type(global_df))
59
  community_global_df = pd.DataFrame()
60
  community_global_df_with_id = pd.DataFrame()
61
  community_global_df_gradio = pd.DataFrame()
62
  test_merge = pd.read_csv("https://docs.google.com/spreadsheets/d/1C8aLqgCqLYcMiIFf-P_Aosaa03C_WLIB_UyqvjSdWg8/export?format=csv&gid=0")
63
- data = pd.read_csv("https://docs.google.com/spreadsheets/d/1hQSsIg1Y9WdBF_CdNM1L1rUUREoxKqRTe3_ILo-WK8w/export?format=csv&gid=0")
64
 
65
  @bot.event
66
  async def on_ready():
@@ -76,7 +63,7 @@ async def on_ready():
76
 
77
  # updates both leaderboards
78
  remove_huggingfolks.start()
79
- print(f"------------------------------------------------------------------------")
80
  except Exception as e:
81
  print(f"on_ready Error: {e}")
82
 
@@ -85,13 +72,13 @@ def update_google_sheet():
85
  """save data from HF Space -> google sheets (makes 1 API call)"""
86
  try:
87
  print("Updating google sheets...")
88
- print(f"------------------------------------------------------------------------")
89
  name = "test_merge_worksheet"
90
  set_with_dataframe(test_merge_worksheet, global_df)
91
  timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
92
- print(f"------------------------------------------------------------------------")
93
  print(f"Google sheet {name} {test_merge_worksheet} successfully updated at {timestamp}! \n{global_df}")
94
- print(f"------------------------------------------------------------------------")
95
  except Exception as e:
96
  print(f"update_google_sheet Error: {e}")
97
 
@@ -100,7 +87,7 @@ def update_hub_stats():
100
  try:
101
  global global_df
102
  print("Updating hub stats...")
103
- print(f"------------------------------------------------------------------------")
104
 
105
  for index, row in global_df.iterrows():
106
  user = row['hf_user_name']
@@ -133,7 +120,7 @@ def update_hub_stats():
133
 
134
  total_hub_activity = likes + models + datasets + spaces + discussions + papers + upvotes
135
  total_hub_exp = total_hub_activity * 20 #2x better than discord
136
- total_hub_exp_string = f"L" + str(total_hub_exp) + f"L"
137
 
138
  # hub exp
139
  global_df.loc[index, 'hub_exp'] = total_hub_exp_string
@@ -142,7 +129,7 @@ def update_hub_stats():
142
  discord_exp = row['discord_exp']
143
  discord_exp_int = discord_exp.strip('L')
144
  total_exp = int(discord_exp_int) + int(total_hub_exp)
145
- total_exp_string = f"L" + str(total_exp) + f"L"
146
  global_df.loc[index, 'total_exp'] = total_exp_string
147
 
148
  # level
@@ -159,9 +146,9 @@ def update_hub_stats():
159
  except Exception as e:
160
  print(f"Failed to parse data for user {user}. {e}")
161
  timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
162
- print(f"------------------------------------------------------------------------")
163
  print(f"Hub stats successfully updated at {timestamp}! \n{global_df}")
164
- print(f"------------------------------------------------------------------------")
165
 
166
  executor = ThreadPoolExecutor(max_workers=2)
167
  scheduler = BackgroundScheduler(executors={'default': executor})
@@ -292,7 +279,7 @@ async def add_exp(member_id):
292
 
293
  # set old level; use this for more accurate logging and jumping multiple levels at once (for example, verifying)
294
  old_total_xp = int(total_exp)
295
- old_level = calculate_level(old_total_xp)
296
 
297
  # check if hub exp not empty
298
  if hub_xp.strip():
@@ -306,13 +293,13 @@ async def add_exp(member_id):
306
  # convert back to string + google sheet proofing
307
  new_xp = str(new_xp)
308
  if not new_xp.startswith("L") and not new_xp.endswith("L"):
309
- new_xp = f"L" + str(new_xp) + f"L"
310
  global_df.loc[index, 'discord_exp'] = new_xp # do not change column name
311
 
312
  # after
313
  total_exp = str(total_exp)
314
  if not total_exp.startswith("L") and not total_exp.endswith("L"):
315
- total_exp = f"L" + str(total_exp) + f"L"
316
 
317
  # add back to dataframe in memory after checking redundantly;
318
  if total_exp.startswith("L") and total_exp.endswith("L"):
@@ -340,7 +327,7 @@ async def add_exp(member_id):
340
  rank = (copy_df['total_exp'] > target_exp).sum() + 1
341
  print(f"The rank for {member} based on total_exp is: {rank}")
342
  except Exception as e:
343
- print(f"Discord ID {member} {member_id} not found in the DataFrame.")
344
  rank = "🤗"
345
 
346
  # if level 3 -> then send embed, remove some exp
@@ -365,18 +352,18 @@ async def add_exp(member_id):
365
  embed.description = f"{msg}"
366
  verification_link = "https://discord.com/channels/879548962464493619/900125909984624713"
367
  embed.add_field(name="Verify Here:", value=verification_link, inline=True)
368
- u_1 = f"👑 Earn exp for activity on Discord and HF and climb the ⁠leaderboard !"
369
- u_2 = f"🌎 Feature your content in weekly news and increase its visibility!"
370
- u_3 = f"🚀 Early access to Beta features!"
371
- u_4 = f"🛡️ Secure your progress, and restore if needed!"
372
  embed.add_field(name="You can Unlock:", value=f"{u_1}\n{u_2}\n{u_3}\n{u_4}", inline=True)
373
  embed.set_image(url='https://cdn.discordapp.com/attachments/1150399343912833024/1205537451242688573/download_1.png?ex=65d8bb3e&is=65c6463e&hm=042fe7dd3521887db0bd48eeb846de1cc7c75194f9e95215c23512ff61ea3475&')
374
 
375
  lunar = bot.get_user(811235357663297546)
376
  await member.send(embed=embed)
377
  await lunar.send(embed=embed)
378
- print(f"Sent verification cap embed to {member}")
379
- print(f"------------------------------------------------------------------------")
380
  return
381
 
382
  # increment the old level value (better to replace outright)
@@ -430,7 +417,7 @@ async def add_exp(member_id):
430
  await member.send(embed=embed)
431
  await lunar.send(embed=embed)
432
  print(f"Sent levelup embed to {member}")
433
- print(f"------------------------------------------------------------------------")
434
  if not member_found: # this only checks if discord_user_id (with L) is present in discord_user_id column,
435
  # if not, create new record
436
  print(f"Creating new record for {member}")
@@ -439,10 +426,10 @@ async def add_exp(member_id):
439
  current_level = calculate_level(xp)
440
  xp = str(xp)
441
  if not xp.startswith("L") and not xp.endswith("L"):
442
- xp = f"L" + str(xp) + f"L"
443
  member_id = str(member_id)
444
  if not member_id.startswith("L") and not member_id.endswith("L"):
445
- member_id = f"L" + str(member_id) + f"L"
446
  member_name = str(member.name)
447
  hf_user_name = "n/a"
448
  hub_exp = "L0L"
@@ -461,7 +448,7 @@ async def add_exp(member_id):
461
  row_data = [member_id, member_name, xp, current_level, hf_user_name, hub_exp, total_exp, verified_date, likes, models, datasets, spaces, discussions, papers, upvotes]
462
  global_df.loc[len(global_df.index)] = row_data
463
 
464
- print(f"------------------------------------------------------------------------")
465
  except Exception as e:
466
  print(f"add_exp Error: {e}")
467
 
@@ -487,7 +474,7 @@ async def on_message(message):
487
  try:
488
  user = HfApi().whoami(token)
489
  except HTTPError as e:
490
- await message.channel.send("Error occured when trying to authenticate. Likely invalid API Token.")
491
  token = "abc" # reset right after we use to be safe
492
 
493
  if user['type'] == 'org':
@@ -552,21 +539,21 @@ async def on_message(message):
552
  print(f"verification Error: {e}")
553
 
554
  # -----------------------------------------------------------------------------------------
 
555
  xp = 10
556
- current_level = calculate_level(xp)
557
- xp = str(xp)
558
- if not xp.startswith("L") and not xp.endswith("L"):
559
- xp = f"L" + str(xp) + f"L"
560
  hub_exp = "L0L"
561
- total_exp = xp
 
562
 
563
  row_data = [altered_member_id,
564
  member.name,
565
- xp,
566
  current_level,
567
  user['name'],
568
  "L0L",
569
- xp,
 
570
  verified_date,
571
  likes,
572
  models,
@@ -580,7 +567,7 @@ async def on_message(message):
580
  await member.add_roles(role)
581
  if role in member.roles:
582
  print(f"New record created for {member}")
583
- print(f"------------------------------------------------------------------------")
584
  await bot.process_commands(message)
585
  except Exception as e:
586
  print(f"on_message Error: {e}")
@@ -592,7 +579,7 @@ async def on_reaction_add(reaction, user):
592
  if user.id not in bot_ids:
593
  print(f"adding exp from react {user}")
594
  await asyncio.sleep(0.1)
595
- if not isinstance(message.channel, discord.DMChannel): # can't earn exp from DMing the bot, which is harder to track
596
  await add_exp(user.id)
597
  await asyncio.sleep(0.1)
598
  if reaction.message.author.id != user.id: # can't earn while self-reacting, which is abuseable
@@ -660,8 +647,8 @@ async def remove_huggingfolks():
660
  # put into message / leaderboard
661
  new_table = tabulate(top_num_rows, headers=["Name", "Level", "Experience", "Rank"], tablefmt="plain")
662
  await message.edit(content=f"Updated Leaderboard:\n```\n{new_table}\n```")
663
- print(f"Updated discord leaderboard!")
664
- print(f"------------------------------------------------------------------------")
665
  except Exception as e:
666
  print(f"remove_huggingfolks Error: {e}")
667
 
@@ -710,23 +697,18 @@ def get_data2():
710
  demo = gr.Blocks()
711
  with demo:
712
  try:
713
- dataframe1 = pd.read_csv("https://docs.google.com/spreadsheets/d/1C8aLqgCqLYcMiIFf-P_Aosaa03C_WLIB_UyqvjSdWg8/export?format=csv&gid=0")
714
- #data = dataframe1.copy()
715
- print(dataframe1)
716
  column_values_unique = sorted(dataframe1.iloc[:, 3].unique())
717
- print(column_values_unique)
718
  dataframe2 = pd.DataFrame({'Levels': column_values_unique})
719
- print(dataframe2)
720
  counts = {}
721
  try:
722
  for value in dataframe1.iloc[:, 3]:
723
- print(value)
724
- print(type(value))
725
  counts[value] = counts.get(value, 0) + 1
726
  dataframe2['Members'] = dataframe2['Levels'].map(counts)
727
  except Exception as e:
728
- print(f"dataframe2 Error: {e}")
729
- print(dataframe2)
730
 
731
  TITLE = """<h1 align="center" id="space-title">🤗 Hugging Face Level Leaderboard</h1>"""
732
  gr.HTML(TITLE)
 
1
  import asyncio
 
2
  import datetime
3
  import json
 
4
  import os
5
  import os.path
 
 
6
  import threading
 
7
 
8
  import discord
9
  import gradio as gr
 
10
  import gspread
 
11
  import pandas as pd
12
  import requests
13
 
 
16
  from apscheduler.schedulers.background import BackgroundScheduler
17
  from discord import Color, Embed
18
  from discord.ext import commands, tasks
19
+ from gspread_dataframe import set_with_dataframe
20
+ from huggingface_hub import HfApi
 
 
21
  from tabulate import tabulate
22
+
23
 
24
  DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
25
  intents = discord.Intents.all()
26
  bot = commands.Bot(command_prefix='!', intents=intents)
27
 
 
 
 
28
 
29
  """"""
30
  XP_PER_MESSAGE = 10 # 100k messages = 1M exp = lvl 100
 
41
  """"""
42
  api = HfApi()
43
  """"""
 
44
  global_df = pd.DataFrame()
45
  print(type(global_df))
46
  community_global_df = pd.DataFrame()
47
  community_global_df_with_id = pd.DataFrame()
48
  community_global_df_gradio = pd.DataFrame()
49
  test_merge = pd.read_csv("https://docs.google.com/spreadsheets/d/1C8aLqgCqLYcMiIFf-P_Aosaa03C_WLIB_UyqvjSdWg8/export?format=csv&gid=0")
50
+
51
 
52
  @bot.event
53
  async def on_ready():
 
63
 
64
  # updates both leaderboards
65
  remove_huggingfolks.start()
66
+ print("------------------------------------------------------------------------")
67
  except Exception as e:
68
  print(f"on_ready Error: {e}")
69
 
 
72
  """save data from HF Space -> google sheets (makes 1 API call)"""
73
  try:
74
  print("Updating google sheets...")
75
+ print("------------------------------------------------------------------------")
76
  name = "test_merge_worksheet"
77
  set_with_dataframe(test_merge_worksheet, global_df)
78
  timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
79
+ print("------------------------------------------------------------------------")
80
  print(f"Google sheet {name} {test_merge_worksheet} successfully updated at {timestamp}! \n{global_df}")
81
+ print("------------------------------------------------------------------------")
82
  except Exception as e:
83
  print(f"update_google_sheet Error: {e}")
84
 
 
87
  try:
88
  global global_df
89
  print("Updating hub stats...")
90
+ print("------------------------------------------------------------------------")
91
 
92
  for index, row in global_df.iterrows():
93
  user = row['hf_user_name']
 
120
 
121
  total_hub_activity = likes + models + datasets + spaces + discussions + papers + upvotes
122
  total_hub_exp = total_hub_activity * 20 #2x better than discord
123
+ total_hub_exp_string = "L" + str(total_hub_exp) + "L"
124
 
125
  # hub exp
126
  global_df.loc[index, 'hub_exp'] = total_hub_exp_string
 
129
  discord_exp = row['discord_exp']
130
  discord_exp_int = discord_exp.strip('L')
131
  total_exp = int(discord_exp_int) + int(total_hub_exp)
132
+ total_exp_string = "L" + str(total_exp) + "L"
133
  global_df.loc[index, 'total_exp'] = total_exp_string
134
 
135
  # level
 
146
  except Exception as e:
147
  print(f"Failed to parse data for user {user}. {e}")
148
  timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
149
+ print("------------------------------------------------------------------------")
150
  print(f"Hub stats successfully updated at {timestamp}! \n{global_df}")
151
+ print("------------------------------------------------------------------------")
152
 
153
  executor = ThreadPoolExecutor(max_workers=2)
154
  scheduler = BackgroundScheduler(executors={'default': executor})
 
279
 
280
  # set old level; use this for more accurate logging and jumping multiple levels at once (for example, verifying)
281
  old_total_xp = int(total_exp)
282
+ #old_level = calculate_level(old_total_xp)
283
 
284
  # check if hub exp not empty
285
  if hub_xp.strip():
 
293
  # convert back to string + google sheet proofing
294
  new_xp = str(new_xp)
295
  if not new_xp.startswith("L") and not new_xp.endswith("L"):
296
+ new_xp = "L" + str(new_xp) + "L"
297
  global_df.loc[index, 'discord_exp'] = new_xp # do not change column name
298
 
299
  # after
300
  total_exp = str(total_exp)
301
  if not total_exp.startswith("L") and not total_exp.endswith("L"):
302
+ total_exp = "L" + str(total_exp) + "L"
303
 
304
  # add back to dataframe in memory after checking redundantly;
305
  if total_exp.startswith("L") and total_exp.endswith("L"):
 
327
  rank = (copy_df['total_exp'] > target_exp).sum() + 1
328
  print(f"The rank for {member} based on total_exp is: {rank}")
329
  except Exception as e:
330
+ print(f"Discord ID {member} {member_id} not found in the DataFrame. {e}")
331
  rank = "🤗"
332
 
333
  # if level 3 -> then send embed, remove some exp
 
352
  embed.description = f"{msg}"
353
  verification_link = "https://discord.com/channels/879548962464493619/900125909984624713"
354
  embed.add_field(name="Verify Here:", value=verification_link, inline=True)
355
+ u_1 = "👑 Earn exp for activity on Discord and HF and climb the ⁠leaderboard !"
356
+ u_2 = "🌎 Feature your content in weekly news and increase its visibility!"
357
+ u_3 = "🚀 Early access to Beta features!"
358
+ u_4 = "🛡️ Secure your progress, and restore if needed!"
359
  embed.add_field(name="You can Unlock:", value=f"{u_1}\n{u_2}\n{u_3}\n{u_4}", inline=True)
360
  embed.set_image(url='https://cdn.discordapp.com/attachments/1150399343912833024/1205537451242688573/download_1.png?ex=65d8bb3e&is=65c6463e&hm=042fe7dd3521887db0bd48eeb846de1cc7c75194f9e95215c23512ff61ea3475&')
361
 
362
  lunar = bot.get_user(811235357663297546)
363
  await member.send(embed=embed)
364
  await lunar.send(embed=embed)
365
+ print("Sent verification cap embed to {member}")
366
+ print("------------------------------------------------------------------------")
367
  return
368
 
369
  # increment the old level value (better to replace outright)
 
417
  await member.send(embed=embed)
418
  await lunar.send(embed=embed)
419
  print(f"Sent levelup embed to {member}")
420
+ print("------------------------------------------------------------------------")
421
  if not member_found: # this only checks if discord_user_id (with L) is present in discord_user_id column,
422
  # if not, create new record
423
  print(f"Creating new record for {member}")
 
426
  current_level = calculate_level(xp)
427
  xp = str(xp)
428
  if not xp.startswith("L") and not xp.endswith("L"):
429
+ xp = "L" + str(xp) + "L"
430
  member_id = str(member_id)
431
  if not member_id.startswith("L") and not member_id.endswith("L"):
432
+ member_id = "L" + str(member_id) + "L"
433
  member_name = str(member.name)
434
  hf_user_name = "n/a"
435
  hub_exp = "L0L"
 
448
  row_data = [member_id, member_name, xp, current_level, hf_user_name, hub_exp, total_exp, verified_date, likes, models, datasets, spaces, discussions, papers, upvotes]
449
  global_df.loc[len(global_df.index)] = row_data
450
 
451
+ print("------------------------------------------------------------------------")
452
  except Exception as e:
453
  print(f"add_exp Error: {e}")
454
 
 
474
  try:
475
  user = HfApi().whoami(token)
476
  except HTTPError as e:
477
+ await message.channel.send(f"Error occured when trying to authenticate. Likely invalid API Token. {e}")
478
  token = "abc" # reset right after we use to be safe
479
 
480
  if user['type'] == 'org':
 
539
  print(f"verification Error: {e}")
540
 
541
  # -----------------------------------------------------------------------------------------
542
+ # If creating new record (edge case)
543
  xp = 10
544
+ discord_exp = "L10L"
 
 
 
545
  hub_exp = "L0L"
546
+ total_exp = "L10L"
547
+ current_level = calculate_level(xp)
548
 
549
  row_data = [altered_member_id,
550
  member.name,
551
+ discord_exp,
552
  current_level,
553
  user['name'],
554
  "L0L",
555
+ hub_exp,
556
+ total_exp,
557
  verified_date,
558
  likes,
559
  models,
 
567
  await member.add_roles(role)
568
  if role in member.roles:
569
  print(f"New record created for {member}")
570
+ print("------------------------------------------------------------------------")
571
  await bot.process_commands(message)
572
  except Exception as e:
573
  print(f"on_message Error: {e}")
 
579
  if user.id not in bot_ids:
580
  print(f"adding exp from react {user}")
581
  await asyncio.sleep(0.1)
582
+ if not isinstance(reaction.message.channel, discord.DMChannel): # can't earn exp from reacting in bot DMs, which is harder to track
583
  await add_exp(user.id)
584
  await asyncio.sleep(0.1)
585
  if reaction.message.author.id != user.id: # can't earn while self-reacting, which is abuseable
 
647
  # put into message / leaderboard
648
  new_table = tabulate(top_num_rows, headers=["Name", "Level", "Experience", "Rank"], tablefmt="plain")
649
  await message.edit(content=f"Updated Leaderboard:\n```\n{new_table}\n```")
650
+ print("Updated discord leaderboard!")
651
+ print("------------------------------------------------------------------------")
652
  except Exception as e:
653
  print(f"remove_huggingfolks Error: {e}")
654
 
 
697
  demo = gr.Blocks()
698
  with demo:
699
  try:
700
+ dataframe1 = pd.read_csv("https://docs.google.com/spreadsheets/d/1C8aLqgCqLYcMiIFf-P_Aosaa03C_WLIB_UyqvjSdWg8/export?format=csv&gid=0") # required for timing
 
 
701
  column_values_unique = sorted(dataframe1.iloc[:, 3].unique())
 
702
  dataframe2 = pd.DataFrame({'Levels': column_values_unique})
703
+
704
  counts = {}
705
  try:
706
  for value in dataframe1.iloc[:, 3]:
 
 
707
  counts[value] = counts.get(value, 0) + 1
708
  dataframe2['Members'] = dataframe2['Levels'].map(counts)
709
  except Exception as e:
710
+ print(f"gradio display error Error: {e}")
711
+ print(f"dataframe2: {dataframe2}")
712
 
713
  TITLE = """<h1 align="center" id="space-title">🤗 Hugging Face Level Leaderboard</h1>"""
714
  gr.HTML(TITLE)