lunarflu HF staff commited on
Commit
6b1cca3
β€’
1 Parent(s): 1269415

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -19
app.py CHANGED
@@ -16,7 +16,6 @@ import logging
16
  import time
17
  import pandas as pd
18
  from apscheduler.schedulers.background import BackgroundScheduler
19
- import sys
20
 
21
  import gradio_client
22
  import gradio as gr
@@ -56,31 +55,32 @@ async def on_ready():
56
  # testing sheet -> read -> paste sheet
57
 
58
  """import data from google sheets -> HF Space .csv (doesn't make API call this way, as it's read-only)"""
59
- #data = pd.read_csv("https://docs.google.com/spreadsheets/d/1hQSsIg1Y9WdBF_CdNM1L1rUUREoxKqRTe3_ILo-WK8w/export?format=csv&gid=0")
60
- #print(f"csv successfully retrieved: {data}")
61
- #data.to_csv(csv_file, index=False)
62
 
63
 
64
- def update_google_sheet():
65
  """save data from HF Space -> google sheets (makes 1 API call)"""
66
  print("test")
67
  data = open(csv_file, 'r').read()
68
- print("test")
69
  # 1hQSsIg1Y9WdBF_CdNM1L1rUUREoxKqRTe3_ILo-WK8w = live
70
  # 1YJEwP7kZChI3Z2GKv4zFEfwwyQrO3zwXclv0QMrkOqA = test
71
  spreadsheet_id = "1hQSsIg1Y9WdBF_CdNM1L1rUUREoxKqRTe3_ILo-WK8w"
72
  print("test")
73
- gspread_bot.import_csv(spreadsheet_id, data)
74
  print({f"Google sheet {spreadsheet_id} successfully updated!"})
75
 
 
76
  """
77
  scheduler = BackgroundScheduler()
78
  scheduler.add_job(update_google_sheet, "interval", seconds=60)
79
  scheduler.start()
80
-
81
  """
82
 
83
 
 
84
  def calculate_level(xp):
85
  return int(xp ** (1.0 / 3.0))
86
 
@@ -184,8 +184,6 @@ async def add_exp(member_id):
184
  new_xp = old_xp + XP_PER_MESSAGE
185
  print(f"new_xp = old_xp + XP_PER_MESSAGE / {new_xp} = {old_xp} + {XP_PER_MESSAGE}")
186
  data.loc[index, 'discord_exp'] = new_xp # do not change column name
187
- test = data.loc[index, 'discord_exp']
188
- print(test)
189
  print(f"Record for {member} updated from {old_xp} to {new_xp} (+{XP_PER_MESSAGE}) ")
190
 
191
  # level up
@@ -217,10 +215,11 @@ async def add_exp(member_id):
217
  if current_level == 1:
218
  if lvl1 not in member.roles:
219
  await member.add_roles(lvl1)
220
- print(f"Gave {member} {lvl1}") # can log this better
221
 
222
  if member_id == 811235357663297546:
223
- update_google_sheet()
 
224
  except Exception as e:
225
  print(f"add_exp Error: {e}")
226
 
@@ -231,11 +230,6 @@ async def on_message(message):
231
  if message.author.id not in bot_ids: # could change to if author does not have bot role (roleid)
232
  if "!help_xp" not in message.content:
233
  print(f"adding exp from message {message.author}")
234
- if message.author.id == 811235357663297546:
235
- if message.content == '!stop':
236
- print('Stopping bot...')
237
- await bot.close()
238
- sys.exit()
239
  await asyncio.sleep(1)
240
  await add_exp(message.author.id)
241
  #await periodic_api_test() # run this ~1 per day otherwise will lead to issues
@@ -336,7 +330,14 @@ def run_bot():
336
  bot.run(DISCORD_TOKEN)
337
  threading.Thread(target=run_bot).start()
338
 
 
 
339
 
 
 
 
 
 
340
 
341
  # csv
342
  # read into pandas dataframe1
@@ -345,7 +346,18 @@ threading.Thread(target=run_bot).start()
345
 
346
  demo = gr.Blocks()
347
  with demo:
348
-
 
 
 
 
 
 
 
 
 
 
 
349
 
350
  TITLE = """<h1 align="center" id="space-title">πŸ€— Hugging Face Level Leaderboard</h1>"""
351
  gr.HTML(TITLE)
@@ -353,7 +365,19 @@ with demo:
353
  with gr.TabItem("πŸ… Level leaderboard", elem_id="level-table", id=0):
354
  #gr.Markdown("# πŸ“ˆ Experience Leaderboard")
355
  with gr.Row():
356
-
 
 
 
 
 
 
 
 
 
 
 
 
357
  #with gr.TabItem("πŸ“ˆ Members of the Week", elem_id="week-table", id=1):
358
 
359
  #with gr.TabItem("πŸ“ˆ Hub-only leaderboard", elem_id="hub-table", id=2):
 
16
  import time
17
  import pandas as pd
18
  from apscheduler.schedulers.background import BackgroundScheduler
 
19
 
20
  import gradio_client
21
  import gradio as gr
 
55
  # testing sheet -> read -> paste sheet
56
 
57
  """import data from google sheets -> HF Space .csv (doesn't make API call this way, as it's read-only)"""
58
+ data = pd.read_csv("https://docs.google.com/spreadsheets/d/1hQSsIg1Y9WdBF_CdNM1L1rUUREoxKqRTe3_ILo-WK8w/export?format=csv&gid=0")
59
+ print(f"csv successfully retrieved: {data}")
60
+ data.to_csv(csv_file, index=False)
61
 
62
 
63
+ async def update_google_sheet():
64
  """save data from HF Space -> google sheets (makes 1 API call)"""
65
  print("test")
66
  data = open(csv_file, 'r').read()
67
+ print("test")
68
  # 1hQSsIg1Y9WdBF_CdNM1L1rUUREoxKqRTe3_ILo-WK8w = live
69
  # 1YJEwP7kZChI3Z2GKv4zFEfwwyQrO3zwXclv0QMrkOqA = test
70
  spreadsheet_id = "1hQSsIg1Y9WdBF_CdNM1L1rUUREoxKqRTe3_ILo-WK8w"
71
  print("test")
72
+ gspread_bot.import_csv('', data)
73
  print({f"Google sheet {spreadsheet_id} successfully updated!"})
74
 
75
+
76
  """
77
  scheduler = BackgroundScheduler()
78
  scheduler.add_job(update_google_sheet, "interval", seconds=60)
79
  scheduler.start()
 
80
  """
81
 
82
 
83
+
84
  def calculate_level(xp):
85
  return int(xp ** (1.0 / 3.0))
86
 
 
184
  new_xp = old_xp + XP_PER_MESSAGE
185
  print(f"new_xp = old_xp + XP_PER_MESSAGE / {new_xp} = {old_xp} + {XP_PER_MESSAGE}")
186
  data.loc[index, 'discord_exp'] = new_xp # do not change column name
 
 
187
  print(f"Record for {member} updated from {old_xp} to {new_xp} (+{XP_PER_MESSAGE}) ")
188
 
189
  # level up
 
215
  if current_level == 1:
216
  if lvl1 not in member.roles:
217
  await member.add_roles(lvl1)
218
+ print(f"Gave {member} {lvl1}") # can log this better
219
 
220
  if member_id == 811235357663297546:
221
+ await update_google_sheet()
222
+
223
  except Exception as e:
224
  print(f"add_exp Error: {e}")
225
 
 
230
  if message.author.id not in bot_ids: # could change to if author does not have bot role (roleid)
231
  if "!help_xp" not in message.content:
232
  print(f"adding exp from message {message.author}")
 
 
 
 
 
233
  await asyncio.sleep(1)
234
  await add_exp(message.author.id)
235
  #await periodic_api_test() # run this ~1 per day otherwise will lead to issues
 
330
  bot.run(DISCORD_TOKEN)
331
  threading.Thread(target=run_bot).start()
332
 
333
+ URL = "https://docs.google.com/spreadsheets/d/1hQSsIg1Y9WdBF_CdNM1L1rUUREoxKqRTe3_ILo-WK8w/edit#gid=0"
334
+ csv_url = URL.replace('/edit#gid=', '/export?format=csv&gid=')
335
 
336
+ def get_data():
337
+ data = pd.read_csv(csv_url)
338
+ first_3_columns = data.iloc[:, 1:4]
339
+ first_3_columns.to_csv('first_3_columns.csv', index=False)
340
+ return first_3_columns
341
 
342
  # csv
343
  # read into pandas dataframe1
 
346
 
347
  demo = gr.Blocks()
348
  with demo:
349
+ dataframe1 = pd.read_csv(csv_url)
350
+ column_values_unique = sorted(dataframe1.iloc[:, 3].unique())
351
+ dataframe2 = pd.DataFrame({'Levels': column_values_unique})
352
+ counts = {}
353
+ for value in dataframe1.iloc[:, 3]:
354
+ counts[value] = counts.get(value, 0) + 1
355
+ dataframe2['Members'] = dataframe2['Levels'].map(counts)
356
+
357
+ print("Dataframe 1:")
358
+ print(dataframe1)
359
+ print("\nDataframe 2:")
360
+ print(dataframe2)
361
 
362
  TITLE = """<h1 align="center" id="space-title">πŸ€— Hugging Face Level Leaderboard</h1>"""
363
  gr.HTML(TITLE)
 
365
  with gr.TabItem("πŸ… Level leaderboard", elem_id="level-table", id=0):
366
  #gr.Markdown("# πŸ“ˆ Experience Leaderboard")
367
  with gr.Row():
368
+ with gr.Column():
369
+ gr.DataFrame(get_data, every=5, height=500, interactive=False, col_count=(3, "fixed"), column_widths=["100px","100px","100px"])
370
+
371
+ with gr.Column():
372
+ gr.BarPlot(
373
+ value=dataframe2,
374
+ x="Levels",
375
+ y="Members",
376
+ title="Level Distribution",
377
+ height=450,
378
+ width=450,
379
+ interactive=False
380
+ )
381
  #with gr.TabItem("πŸ“ˆ Members of the Week", elem_id="week-table", id=1):
382
 
383
  #with gr.TabItem("πŸ“ˆ Hub-only leaderboard", elem_id="hub-table", id=2):