lunarflu HF staff commited on
Commit
bfb4d01
β€’
1 Parent(s): c1086e4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +113 -131
app.py CHANGED
@@ -14,6 +14,7 @@ import csv
14
  from tabulate import tabulate
15
  import logging
16
  import time
 
17
 
18
  import gradio_client
19
  import gradio as gr
@@ -51,7 +52,6 @@ async def on_ready():
51
  print(f"XP_PER_MESSAGE: {XP_PER_MESSAGE}")
52
 
53
 
54
-
55
  def calculate_level(xp):
56
  return int(xp ** (1.0 / 3.0))
57
 
@@ -60,7 +60,6 @@ def calculate_xp(level):
60
  return (int(level ** 3))
61
 
62
 
63
-
64
  processed_users = set()
65
 
66
  async def periodic_api_test():
@@ -98,44 +97,6 @@ async def periodic_api_test():
98
  print(f"periodic_api_test Error: {e}")
99
 
100
 
101
-
102
-
103
- """
104
- async def search_csv(file_path, column_index, search_value):
105
- with open(file_path, 'r', newline='') as csvfile:
106
- reader = csv.reader(csvfile)
107
- first_row = next(reader)
108
- print(first_row)
109
- for row in reader:
110
- if row and len(row) > column_index and row[column_index] == search_value:
111
- print(row)
112
-
113
-
114
-
115
- def is_csv_empty(file_path):
116
- if not os.path.isfile(file_path):
117
- print(f"The file '{file_path}' does not exist.")
118
- return False
119
-
120
- with open(file_path, 'r', newline='') as csvfile:
121
- reader = csv.reader(csvfile)
122
- try:
123
- first_row = next(reader)
124
- print(first_row)
125
- except StopIteration:
126
- print(f"The file '{file_path}' is empty.")
127
- return False
128
-
129
- if not any(first_row):
130
- print(f"The file '{file_path}' has no data.")
131
- return False
132
-
133
- return True
134
-
135
- """
136
-
137
-
138
-
139
  def blocking_io(member_id):
140
  try:
141
  time.sleep(1)
@@ -274,8 +235,6 @@ async def on_reaction_add(reaction, user):
274
  print(f"on_reaction_add Error: {e}")
275
 
276
 
277
-
278
-
279
  @bot.command(name='update_leaderboard')
280
  async def update_leaderboard(ctx, num_results: int = 10):
281
  if ctx.author.id == 811235357663297546:
@@ -306,7 +265,6 @@ async def update_leaderboard(ctx, num_results: int = 10):
306
  top_data_pairs = sorted_data_pairs[:num_results]
307
  """
308
 
309
-
310
  # remove huggingfolks
311
  guild = ctx.guild
312
  role = discord.utils.get(guild.roles, id=897376942817419265)
@@ -333,106 +291,80 @@ async def update_leaderboard(ctx, num_results: int = 10):
333
  await message.edit(content=f"Updated Leaderboard:\n```\n{new_table}\n```")
334
 
335
 
336
-
337
-
338
  @bot.command(name='xp_help')
339
  async def xp_help(ctx):
340
  help_message = "How to earn Discord / Hub exp: Post messages, react, Like, discuss, create repos and papers"
341
  await ctx.author.send(help_message)
342
 
343
 
344
-
345
  @bot.command()
346
  async def write_csv(ctx):
347
- worksheet = gspread_bot.open("levelbot").sheet1
348
- values = worksheet.get_all_values()
349
- target_id = '811235357663297546'
350
- variable_xp = 0
351
-
352
- csv_file_path = 'test.csv'
353
- with open(csv_file_path, 'w', newline='') as csv_file:
354
- csv_writer = csv.writer(csv_file)
355
- csv_writer.writerows(values)
356
-
357
-
358
- # modifying csv data
359
- with open(csv_file_path, 'r') as csv_file:
360
- csv_reader = csv.reader(csv_file)
361
- rows = list(csv_reader)
362
-
363
- for row in rows:
364
- print(row)
365
- if target_id in row:
366
- index_of_target = row.index(target_id)
367
 
368
- # 2 to right
369
- cell_to_increment_index = index_of_target + 2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
370
 
371
- # +10
372
- try:
373
- row[cell_to_increment_index] = str(int(row[cell_to_increment_index]) + variable_xp)
374
- print(row[cell_to_increment_index])
375
- except (IndexError, ValueError):
376
- print(f"Error: Unable to increment cell at index {cell_to_increment_index}")
377
 
378
- break
379
-
380
-
381
- # write modified data and send in discord
382
- with open(csv_file_path, 'w', newline='') as csv_file:
383
- csv_writer = csv.writer(csv_file)
384
- csv_writer.writerows(rows)
385
-
386
- csv_data_str = '\n'.join(','.join(row) for row in rows)
387
- csv_file = discord.File(csv_file_path)
388
-
389
- await ctx.channel.send(content="csv", file=csv_file)
390
 
391
- #target_user = await bot.fetch_user(int(target_id))
392
- #await target_user.send(content="csv", file=csv_file)
393
-
394
-
395
-
396
-
397
-
398
- # do simple operation on file (change one value)
399
-
400
- # post current version to discord
401
-
402
- # recover csv from discord channel, read into memory
403
 
404
 
405
  @bot.command()
406
  async def read_csv(ctx):
407
- async for message in ctx.channel.history(limit=10):
408
- if message.attachments:
409
- attachment = message.attachments[0]
410
- if attachment.filename.endswith('.csv'):
411
- csv_content = await attachment.read()
412
- csv_data = []
413
- csv_lines = csv_content.decode('utf-8').splitlines()
414
- csv_reader = csv.reader(csv_lines)
415
- for row in csv_reader:
416
- csv_data.append(row)
417
- print(csv_data)
418
-
419
- await ctx.send("discord -> read -> updated HF Hub")
420
- # react to the given message, helps with explainability
421
- await message.add_reaction('βœ…')
422
- break
423
-
424
-
425
-
426
- """
427
- @bot.command(name='send_message')
428
- async def send_message(ctx):
429
- channel = ctx.channel
430
- leaderboard_data = [("User 1", 100), ("User 2", 80), ("User 3", 60)]
431
- table = tabulate(leaderboard_data, headers=["User", "Score"], tablefmt="plain")
432
- message = await channel.send(f"Leaderboard:\n```\n{table}\n```")
433
-
434
- """
435
-
436
 
437
 
438
  # embeds with user pfps?
@@ -458,7 +390,57 @@ DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
458
  def run_bot():
459
  bot.run(DISCORD_TOKEN)
460
  threading.Thread(target=run_bot).start()
461
- def greet(name):
462
- return "Hello " + name + "!"
463
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
464
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  from tabulate import tabulate
15
  import logging
16
  import time
17
+ import pandas as pd
18
 
19
  import gradio_client
20
  import gradio as gr
 
52
  print(f"XP_PER_MESSAGE: {XP_PER_MESSAGE}")
53
 
54
 
 
55
  def calculate_level(xp):
56
  return int(xp ** (1.0 / 3.0))
57
 
 
60
  return (int(level ** 3))
61
 
62
 
 
63
  processed_users = set()
64
 
65
  async def periodic_api_test():
 
97
  print(f"periodic_api_test Error: {e}")
98
 
99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  def blocking_io(member_id):
101
  try:
102
  time.sleep(1)
 
235
  print(f"on_reaction_add Error: {e}")
236
 
237
 
 
 
238
  @bot.command(name='update_leaderboard')
239
  async def update_leaderboard(ctx, num_results: int = 10):
240
  if ctx.author.id == 811235357663297546:
 
265
  top_data_pairs = sorted_data_pairs[:num_results]
266
  """
267
 
 
268
  # remove huggingfolks
269
  guild = ctx.guild
270
  role = discord.utils.get(guild.roles, id=897376942817419265)
 
291
  await message.edit(content=f"Updated Leaderboard:\n```\n{new_table}\n```")
292
 
293
 
 
 
294
  @bot.command(name='xp_help')
295
  async def xp_help(ctx):
296
  help_message = "How to earn Discord / Hub exp: Post messages, react, Like, discuss, create repos and papers"
297
  await ctx.author.send(help_message)
298
 
299
 
 
300
  @bot.command()
301
  async def write_csv(ctx):
302
+ if ctx.author.id == 811235357663297546:
303
+ worksheet = gspread_bot.open("levelbot").sheet1
304
+ values = worksheet.get_all_values()
305
+ target_id = '811235357663297546'
306
+ variable_xp = 0
307
+
308
+ csv_file_path = 'test.csv'
309
+ with open(csv_file_path, 'w', newline='') as csv_file:
310
+ csv_writer = csv.writer(csv_file)
311
+ csv_writer.writerows(values)
 
 
 
 
 
 
 
 
 
 
312
 
313
+ # modifying csv data
314
+ with open(csv_file_path, 'r') as csv_file:
315
+ csv_reader = csv.reader(csv_file)
316
+ rows = list(csv_reader)
317
+
318
+ for row in rows:
319
+ print(row)
320
+ if target_id in row:
321
+ index_of_target = row.index(target_id)
322
+
323
+ # 2 to right
324
+ cell_to_increment_index = index_of_target + 2
325
+
326
+ # +10
327
+ try:
328
+ row[cell_to_increment_index] = str(int(row[cell_to_increment_index]) + variable_xp)
329
+ print(row[cell_to_increment_index])
330
+ except (IndexError, ValueError):
331
+ print(f"Error: Unable to increment cell at index {cell_to_increment_index}")
332
+
333
+ break
334
 
335
+ # write modified data and send in discord
336
+ with open(csv_file_path, 'w', newline='') as csv_file:
337
+ csv_writer = csv.writer(csv_file)
338
+ csv_writer.writerows(rows)
 
 
339
 
340
+ csv_data_str = '\n'.join(','.join(row) for row in rows)
341
+ csv_file = discord.File(csv_file_path)
 
 
 
 
 
 
 
 
 
 
342
 
343
+ await ctx.channel.send(content="csv", file=csv_file)
344
+
345
+ #target_user = await bot.fetch_user(int(target_id))
346
+ #await target_user.send(content="csv", file=csv_file)
 
 
 
 
 
 
 
 
347
 
348
 
349
  @bot.command()
350
  async def read_csv(ctx):
351
+ if ctx.author.id == 811235357663297546:
352
+ async for message in ctx.channel.history(limit=10):
353
+ if message.attachments:
354
+ attachment = message.attachments[0]
355
+ if attachment.filename.endswith('.csv'):
356
+ csv_content = await attachment.read()
357
+ csv_data = []
358
+ csv_lines = csv_content.decode('utf-8').splitlines()
359
+ csv_reader = csv.reader(csv_lines)
360
+ for row in csv_reader:
361
+ csv_data.append(row)
362
+ print(csv_data)
363
+
364
+ await ctx.send("discord -> read -> updated HF Hub")
365
+ # react to the given message, helps with explainability
366
+ await message.add_reaction('βœ…')
367
+ break
 
 
 
 
 
 
 
 
 
 
 
 
368
 
369
 
370
  # embeds with user pfps?
 
390
  def run_bot():
391
  bot.run(DISCORD_TOKEN)
392
  threading.Thread(target=run_bot).start()
393
+
394
+ URL = "https://docs.google.com/spreadsheets/d/1hQSsIg1Y9WdBF_CdNM1L1rUUREoxKqRTe3_ILo-WK8w/edit#gid=0"
395
+ csv_url = URL.replace('/edit#gid=', '/export?format=csv&gid=')
396
+
397
+ def get_data():
398
+ data = pd.read_csv(csv_url)
399
+ first_3_columns = data.iloc[:, 1:4]
400
+ first_3_columns.to_csv('first_3_columns.csv', index=False)
401
+ return first_3_columns
402
+
403
+ # csv
404
+ # read into pandas dataframe1
405
+ # read levels column and create pandas dataframe2 with first column containing levels from 2-max found in dataframe1
406
+ # create second column in dataframe2 for number of each level found in dataframe1 levels column
407
+
408
+ demo = gr.Blocks()
409
+ with demo:
410
+ dataframe1 = pd.read_csv(csv_url)
411
+ column_values_unique = sorted(dataframe1.iloc[:, 3].unique())
412
+ dataframe2 = pd.DataFrame({'Levels': column_values_unique})
413
+ counts = {}
414
+ for value in dataframe1.iloc[:, 3]:
415
+ counts[value] = counts.get(value, 0) + 1
416
+ dataframe2['Members'] = dataframe2['Levels'].map(counts)
417
+
418
+ print("Dataframe 1:")
419
+ print(dataframe1)
420
+ print("\nDataframe 2:")
421
+ print(dataframe2)
422
+
423
+ TITLE = """<h1 align="center" id="space-title">πŸ€— Hugging Face Level Leaderboard</h1>"""
424
+ gr.HTML(TITLE)
425
+ with gr.Tabs(elem_classes="tab-buttons") as tabs:
426
+ with gr.TabItem("πŸ… Level leaderboard", elem_id="level-table", id=0):
427
+ #gr.Markdown("# πŸ“ˆ Experience Leaderboard")
428
+ with gr.Row():
429
+ with gr.Column():
430
+ gr.DataFrame(get_data, every=5, height=500, interactive=False, col_count=(3, "fixed"), column_widths=["100px","100px","100px"])
431
+
432
+ with gr.Column():
433
+ gr.BarPlot(
434
+ value=dataframe2,
435
+ x="Levels",
436
+ y="Members",
437
+ title="Level Distribution",
438
+ height=450,
439
+ width=450,
440
+ interactive=False
441
+ )
442
+ #with gr.TabItem("πŸ“ˆ Members of the Week", elem_id="week-table", id=1):
443
+
444
+ #with gr.TabItem("πŸ“ˆ Hub-only leaderboard", elem_id="hub-table", id=2):
445
+
446
+ demo.queue(default_concurrency_limit=40).launch()