lunarflu HF staff commited on
Commit
64de934
1 Parent(s): ea2e1d2

small revert

Browse files
Files changed (1) hide show
  1. app.py +69 -19
app.py CHANGED
@@ -53,40 +53,37 @@ api = HfApi()
53
  """"""
54
  #csv_file = 'data.csv'
55
  global_df = pd.DataFrame()
56
- worksheet2_df = pd.DataFrame()
57
  print(type(global_df))
58
  community_global_df = pd.DataFrame()
59
  data = pd.read_csv("https://docs.google.com/spreadsheets/d/1hQSsIg1Y9WdBF_CdNM1L1rUUREoxKqRTe3_ILo-WK8w/export?format=csv&gid=0")
60
- data2 = pd.read_csv("https://docs.google.com/spreadsheets/d/1T_twNONDSZ8zw7aDcYhw92DlawqPktti1xFw9ssJ13Y/edit#gid=0")
61
-
62
 
63
  @bot.event
64
  async def on_ready():
65
  try:
66
  global global_df
67
- global worksheet2_df
68
  await asyncio.sleep(1.1)
69
  print(f'Logged in as {bot.user.name}')
70
  print(f"XP_PER_MESSAGE: {XP_PER_MESSAGE}")
 
 
 
71
 
72
- """import data from google sheets -> HF Space df (doesn't make API call this way, as it's read-only)"""
73
  data['discord_user_id'] = data['discord_user_id'].astype(str)
74
  global_df = data
75
  print(f"csv successfully retrieved: \n {global_df}")
76
- worksheet2_df = data2
77
 
78
- # updates both leaderboards
79
  remove_huggingfolks.start()
80
- await(periodic_api_test)
81
  print(f"------------------------------------------------------------------------")
82
  except Exception as e:
83
  print(f"on_message Error: {e}")
84
 
85
 
86
  def update_google_sheet():
87
- """save data from HF Space -> google sheets (makes 2 API calls)"""
 
88
  try:
89
- print("Updating google sheets...")
90
  name = "levelbot"
91
  #worksheet = gspread_bot.open(name).sheet1
92
  global_df['discord_user_id'] = global_df['discord_user_id'].astype(str)
@@ -107,8 +104,14 @@ def update_google_sheet():
107
 
108
  executor = ThreadPoolExecutor(max_workers=1)
109
  scheduler = BackgroundScheduler(executors={'default': executor})
110
- scheduler.add_job(update_google_sheet, trigger='interval', minutes=1, max_instances=1)
111
  scheduler.start()
 
 
 
 
 
 
112
 
113
 
114
  def calculate_level(xp):
@@ -119,7 +122,41 @@ def calculate_xp(level):
119
  return (int(level ** 3))
120
 
121
 
122
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
 
124
 
125
  async def add_exp(member_id):
@@ -231,7 +268,7 @@ async def add_exp(member_id):
231
 
232
  #lunar = bot.get_user(811235357663297546)
233
  await member.send(embed=embed)
234
- print(f"Sent levelup embed to {member}")
235
  #You can verify your account to earn 100 points! To verify, do A.
236
 
237
 
@@ -274,7 +311,7 @@ async def on_message(message):
274
  async def on_reaction_add(reaction, user):
275
  try:
276
  if user.id not in bot_ids:
277
- print(f"adding exp from react {user}")
278
  await asyncio.sleep(0.1)
279
  await add_exp(user.id)
280
  await asyncio.sleep(0.1)
@@ -298,25 +335,25 @@ async def remove_huggingfolks():
298
  for member_id in members_with_role:
299
  community_global_df = community_global_df[community_global_df.iloc[:, 0] != str(member_id)]
300
 
301
- #print(community_global_df)
302
 
303
  community_global_df.drop(community_global_df.columns[0], axis=1, inplace=True)
304
  community_global_df['discord_exp'] = pd.to_numeric(community_global_df['discord_exp'])
305
  community_global_df = community_global_df.nlargest(len(community_global_df), 'discord_exp')
306
 
307
  top_30_exp = community_global_df.nlargest(30, 'discord_exp')
 
308
 
309
  top_30_exp['D'] = ['🥇','🥈','🥉','','','','','','','','','','','','','','','','','','','','','','','','','','','']
310
  top_30_rows = top_30_exp.values.tolist()
311
 
312
- #print(top_30_rows)
313
  channel = bot.get_channel(1197143964994773023)
314
  message = await channel.fetch_message(1197148293164187678)
315
 
316
  # put into message / leaderboard
317
  new_table = tabulate(top_30_rows, headers=["Name", "Experience", "Level", "Rank"], tablefmt="plain")
318
  await message.edit(content=f"Updated Leaderboard:\n```\n{new_table}\n```")
319
- print(f"Updated discord leaderboard!")
320
 
321
  except Exception as e:
322
  print(f"remove_huggingfolks Error: {e}")
@@ -342,13 +379,24 @@ async def count_users_with_role(ctx, role_id):
342
  # embeds with user pfps?
343
  # name, pfp, time in server....
344
 
 
 
 
 
345
  # weekly do different count
346
  # count number of messages per user for every channel (total messages)
347
  # fix sheet if necessary
 
 
348
  # add emojis for some color
349
  # check if members are still in the server
350
 
351
 
 
 
 
 
 
352
  """"""
353
  DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
354
  def run_bot():
@@ -365,7 +413,10 @@ def get_data():
365
  return community_global_df
366
  except Exception as e:
367
  print(f"on_message Error: {e}")
368
-
 
 
 
369
 
370
  demo = gr.Blocks()
371
  with demo:
@@ -407,4 +458,3 @@ with demo:
407
  print(f"on_message Error: {e}")
408
  demo.queue().launch()
409
 
410
-
 
53
  """"""
54
  #csv_file = 'data.csv'
55
  global_df = pd.DataFrame()
 
56
  print(type(global_df))
57
  community_global_df = pd.DataFrame()
58
  data = pd.read_csv("https://docs.google.com/spreadsheets/d/1hQSsIg1Y9WdBF_CdNM1L1rUUREoxKqRTe3_ILo-WK8w/export?format=csv&gid=0")
 
 
59
 
60
  @bot.event
61
  async def on_ready():
62
  try:
63
  global global_df
 
64
  await asyncio.sleep(1.1)
65
  print(f'Logged in as {bot.user.name}')
66
  print(f"XP_PER_MESSAGE: {XP_PER_MESSAGE}")
67
+ # testing sheet -> read -> paste sheet
68
+
69
+ """import data from google sheets -> HF Space .csv (doesn't make API call this way, as it's read-only)"""
70
 
 
71
  data['discord_user_id'] = data['discord_user_id'].astype(str)
72
  global_df = data
73
  print(f"csv successfully retrieved: \n {global_df}")
74
+ #data.to_csv(csv_file, index=False)
75
 
 
76
  remove_huggingfolks.start()
 
77
  print(f"------------------------------------------------------------------------")
78
  except Exception as e:
79
  print(f"on_message Error: {e}")
80
 
81
 
82
  def update_google_sheet():
83
+ """save data from HF Space -> google sheets (makes 1 API call)"""
84
+ # run this in separate thread?
85
  try:
86
+ print("Updating...")
87
  name = "levelbot"
88
  #worksheet = gspread_bot.open(name).sheet1
89
  global_df['discord_user_id'] = global_df['discord_user_id'].astype(str)
 
104
 
105
  executor = ThreadPoolExecutor(max_workers=1)
106
  scheduler = BackgroundScheduler(executors={'default': executor})
107
+ scheduler.add_job(update_google_sheet, trigger='interval', minutes=2, max_instances=1)
108
  scheduler.start()
109
+ """
110
+ scheduler = BackgroundScheduler()
111
+ scheduler.add_job(update_google_sheet, "interval", seconds=60)
112
+ scheduler.start()
113
+
114
+ """
115
 
116
 
117
  def calculate_level(xp):
 
122
  return (int(level ** 3))
123
 
124
 
125
+ processed_users = set()
126
+
127
+ async def periodic_api_test(): # needs rewrite, can do same thing and interact with csv -> push to google sheets
128
+ try:
129
+ await asyncio.sleep(0.1)
130
+ column_values_3 = worksheet2.col_values(3)
131
+ column_values_8 = worksheet2.col_values(8)
132
+
133
+ for i, user in enumerate(column_values_3):
134
+ if user in processed_users:
135
+ continue
136
+
137
+ url = f"https://huggingface.co/api/users/{user}/overview"
138
+ response = requests.get(url)
139
+
140
+ if response.status_code == 200:
141
+ data = response.json()
142
+
143
+ likes = data["numLikes"]
144
+ models = data["numModels"]
145
+ datasets = data["numDatasets"]
146
+ spaces = data["numSpaces"]
147
+ discussions = data["numDiscussions"]
148
+ papers = data["numPapers"]
149
+ upvotes = data["numUpvotes"]
150
+
151
+ worksheet2.update(values=[[likes, models, datasets, spaces, discussions, papers, upvotes]],
152
+ range_name=f'G{i+1}:M{i+1}')
153
+
154
+ processed_users.add(user)
155
+ else:
156
+ print(f"Failed to retrieve data for user {user}. Status code: {response.status_code}")
157
+
158
+ except Exception as e:
159
+ print(f"periodic_api_test Error: {e}")
160
 
161
 
162
  async def add_exp(member_id):
 
268
 
269
  #lunar = bot.get_user(811235357663297546)
270
  await member.send(embed=embed)
271
+
272
  #You can verify your account to earn 100 points! To verify, do A.
273
 
274
 
 
311
  async def on_reaction_add(reaction, user):
312
  try:
313
  if user.id not in bot_ids:
314
+ print(f"adding exp from react {user.id}")
315
  await asyncio.sleep(0.1)
316
  await add_exp(user.id)
317
  await asyncio.sleep(0.1)
 
335
  for member_id in members_with_role:
336
  community_global_df = community_global_df[community_global_df.iloc[:, 0] != str(member_id)]
337
 
338
+ print(community_global_df)
339
 
340
  community_global_df.drop(community_global_df.columns[0], axis=1, inplace=True)
341
  community_global_df['discord_exp'] = pd.to_numeric(community_global_df['discord_exp'])
342
  community_global_df = community_global_df.nlargest(len(community_global_df), 'discord_exp')
343
 
344
  top_30_exp = community_global_df.nlargest(30, 'discord_exp')
345
+ #community_global_df = top_30_exp.copy() # for gradio
346
 
347
  top_30_exp['D'] = ['🥇','🥈','🥉','','','','','','','','','','','','','','','','','','','','','','','','','','','']
348
  top_30_rows = top_30_exp.values.tolist()
349
 
350
+ print(top_30_rows)
351
  channel = bot.get_channel(1197143964994773023)
352
  message = await channel.fetch_message(1197148293164187678)
353
 
354
  # put into message / leaderboard
355
  new_table = tabulate(top_30_rows, headers=["Name", "Experience", "Level", "Rank"], tablefmt="plain")
356
  await message.edit(content=f"Updated Leaderboard:\n```\n{new_table}\n```")
 
357
 
358
  except Exception as e:
359
  print(f"remove_huggingfolks Error: {e}")
 
379
  # embeds with user pfps?
380
  # name, pfp, time in server....
381
 
382
+ # discord_level column
383
+ # pick 10 highest
384
+ # update
385
+
386
  # weekly do different count
387
  # count number of messages per user for every channel (total messages)
388
  # fix sheet if necessary
389
+
390
+ # might need cell location data to pull both level and username at same time
391
  # add emojis for some color
392
  # check if members are still in the server
393
 
394
 
395
+
396
+
397
+
398
+
399
+
400
  """"""
401
  DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
402
  def run_bot():
 
413
  return community_global_df
414
  except Exception as e:
415
  print(f"on_message Error: {e}")
416
+ # csv
417
+ # read into pandas dataframe1
418
+ # read levels column and create pandas dataframe2 with first column containing levels from 2-max found in dataframe1
419
+ # create second column in dataframe2 for number of each level found in dataframe1 levels column
420
 
421
  demo = gr.Blocks()
422
  with demo:
 
458
  print(f"on_message Error: {e}")
459
  demo.queue().launch()
460