lunarflu HF staff commited on
Commit
ba302bd
·
verified ·
1 Parent(s): 64de934

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -43
app.py CHANGED
@@ -53,37 +53,40 @@ api = HfApi()
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,15 +107,9 @@ def update_google_sheet():
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):
118
  return int(xp ** (1.0 / 3.0))
@@ -126,14 +123,14 @@ 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
 
@@ -147,9 +144,10 @@ async def periodic_api_test(): # needs rewrite, can do same thing and interact w
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:
@@ -268,7 +266,7 @@ 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,7 +309,7 @@ async def on_message(message):
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,25 +333,25 @@ async def remove_huggingfolks():
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,24 +377,13 @@ async def count_users_with_role(ctx, role_id):
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,10 +400,7 @@ def get_data():
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:
 
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
 
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):
115
  return int(xp ** (1.0 / 3.0))
 
123
 
124
  async def periodic_api_test(): # needs rewrite, can do same thing and interact with csv -> push to google sheets
125
  try:
126
+ # this should be gspread type function (do not mix with discord at all)
127
+ global worksheet2_df
128
+ await asyncio.sleep(5)
129
+ # get
130
+ for index, user in enumerate(worksheet2_df['hf_user_name']):
131
  if user in processed_users:
132
  continue
133
+
134
  url = f"https://huggingface.co/api/users/{user}/overview"
135
  response = requests.get(url)
136
 
 
144
  discussions = data["numDiscussions"]
145
  papers = data["numPapers"]
146
  upvotes = data["numUpvotes"]
147
+
148
+ worksheet2_df.loc[index:index, 'likes':'upvotes'] = [[likes, models, datasets, spaces, discussions, papers, upvotes]]
149
+ print(worksheet2_df)
150
+
151
 
152
  processed_users.add(user)
153
  else:
 
266
 
267
  #lunar = bot.get_user(811235357663297546)
268
  await member.send(embed=embed)
269
+ print(f"Sent levelup embed to {member}")
270
  #You can verify your account to earn 100 points! To verify, do A.
271
 
272
 
 
309
  async def on_reaction_add(reaction, user):
310
  try:
311
  if user.id not in bot_ids:
312
+ print(f"adding exp from react {user}")
313
  await asyncio.sleep(0.1)
314
  await add_exp(user.id)
315
  await asyncio.sleep(0.1)
 
333
  for member_id in members_with_role:
334
  community_global_df = community_global_df[community_global_df.iloc[:, 0] != str(member_id)]
335
 
336
+ #print(community_global_df)
337
 
338
  community_global_df.drop(community_global_df.columns[0], axis=1, inplace=True)
339
  community_global_df['discord_exp'] = pd.to_numeric(community_global_df['discord_exp'])
340
  community_global_df = community_global_df.nlargest(len(community_global_df), 'discord_exp')
341
 
342
  top_30_exp = community_global_df.nlargest(30, 'discord_exp')
 
343
 
344
  top_30_exp['D'] = ['🥇','🥈','🥉','','','','','','','','','','','','','','','','','','','','','','','','','','','']
345
  top_30_rows = top_30_exp.values.tolist()
346
 
347
+ #print(top_30_rows)
348
  channel = bot.get_channel(1197143964994773023)
349
  message = await channel.fetch_message(1197148293164187678)
350
 
351
  # put into message / leaderboard
352
  new_table = tabulate(top_30_rows, headers=["Name", "Experience", "Level", "Rank"], tablefmt="plain")
353
  await message.edit(content=f"Updated Leaderboard:\n```\n{new_table}\n```")
354
+ print(f"Updated discord leaderboard!")
355
 
356
  except Exception as e:
357
  print(f"remove_huggingfolks Error: {e}")
 
377
  # embeds with user pfps?
378
  # name, pfp, time in server....
379
 
 
 
 
 
380
  # weekly do different count
381
  # count number of messages per user for every channel (total messages)
382
  # fix sheet if necessary
 
 
383
  # add emojis for some color
384
  # check if members are still in the server
385
 
386
 
 
 
 
 
 
387
  """"""
388
  DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
389
  def run_bot():
 
400
  return community_global_df
401
  except Exception as e:
402
  print(f"on_message Error: {e}")
403
+
 
 
 
404
 
405
  demo = gr.Blocks()
406
  with demo: