lunarflu HF staff commited on
Commit
960e451
·
verified ·
1 Parent(s): 37baec4

test speed upgrade

Browse files
Files changed (1) hide show
  1. app.py +72 -64
app.py CHANGED
@@ -1,45 +1,23 @@
1
  import os
2
  import io
3
- import re
4
- import csv
5
  import sys
6
- import json
7
- import time
8
- import random
9
  import asyncio
10
  import discord
11
- import logging
12
  import aiohttp
13
- import gspread
14
- import datetime
15
- import requests
16
- import threading
17
- import schedule
18
- import gradio_client
19
-
20
- import numpy as np
21
  import pandas as pd
22
  import gradio as gr
23
- import plotly.graph_objects as go
24
-
25
- from tabulate import tabulate
26
- from requests import HTTPError
27
- from gradio_client import Client
28
- from discord import Color, Embed
29
- from discord.ui import Button, View
30
- from discord.ext import commands, tasks
31
  from datetime import datetime, timedelta
32
- from urllib.parse import urlparse, parse_qs
33
  from apscheduler.schedulers.asyncio import AsyncIOScheduler
34
- from gspread_formatting.dataframe import format_with_dataframe
35
- from gspread_dataframe import get_as_dataframe, set_with_dataframe
36
- from huggingface_hub import HfApi, list_liked_repos, list_models
37
 
 
38
  DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
39
 
 
40
  intents = discord.Intents.all()
41
  bot = commands.Bot(command_prefix='!', intents=intents)
42
 
 
43
  scheduler = AsyncIOScheduler()
44
 
45
  def restart_bot():
@@ -51,18 +29,41 @@ def periodic_restart():
51
  print("Scheduled restart triggered...")
52
  restart_bot()
53
 
54
- @bot.event
55
- async def on_ready():
56
- """Import data from Google Sheets -> HF Space df"""
57
- print(f"We have logged in as {bot.user}")
58
- scheduler.start()
59
- await give_verified_roles()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  async def give_verified_roles():
 
 
 
62
  while True:
63
  try:
64
- global_df = pd.DataFrame()
65
-
66
  async with aiohttp.ClientSession() as session:
67
  try:
68
  async with session.get(
@@ -84,43 +85,50 @@ async def give_verified_roles():
84
  await asyncio.sleep(30)
85
  continue
86
 
 
87
  guild = bot.get_guild(879548962464493619)
 
 
 
 
88
  role = guild.get_role(900063512829755413)
 
 
 
 
89
 
90
- org_link = "https://huggingface.co/organizations/discord-community/share/wPKRAHYbAlaEaCxUxcqVyaaaeZcYagDvqc"
91
- invite_message = "Click to join our community org on the HF Hub!"
92
-
93
- await guild.chunk()
94
-
95
- for index, row in global_df.iterrows():
96
- hf_user_name = row['hf_user_name']
97
- if pd.notna(hf_user_name) and hf_user_name.lower() != 'n/a':
98
- discord_id = row['discord_user_id'].strip('L')
99
- member = guild.get_member(int(discord_id))
100
- if not member:
101
- continue
102
- if role not in member.roles:
103
- await member.add_roles(role)
104
- #await asyncio.sleep(1)
105
- print(f"Role added to member: {member}")
106
- lunar = bot.get_user(811235357663297546)
107
- if lunar:
108
- await lunar.send(f"Verified role given to {member}!")
109
- await member.send(
110
- f"Verification successful! [{member} <---> {row['discord_user_name']}] \n🤗 {org_link} {invite_message}"
111
- )
112
- #await asyncio.sleep(1)
113
 
 
 
 
114
  except Exception as e:
115
- print(f"Error encountered: {e}")
116
- await asyncio.sleep(10) # 30
 
117
 
118
- def run_bot():
119
- bot.run(DISCORD_TOKEN)
120
-
121
- threading.Thread(target=run_bot).start()
 
 
122
 
 
123
  def greet(name):
124
  return "Hello " + name + "!"
 
 
125
  demo = gr.Interface(fn=greet, inputs="text", outputs="text")
126
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import io
 
 
3
  import sys
 
 
 
4
  import asyncio
5
  import discord
 
6
  import aiohttp
 
 
 
 
 
 
 
 
7
  import pandas as pd
8
  import gradio as gr
 
 
 
 
 
 
 
 
9
  from datetime import datetime, timedelta
10
+ from discord.ext import commands
11
  from apscheduler.schedulers.asyncio import AsyncIOScheduler
 
 
 
12
 
13
+ # Environment variable for Discord token
14
  DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
15
 
16
+ # Create Discord bot with all intents
17
  intents = discord.Intents.all()
18
  bot = commands.Bot(command_prefix='!', intents=intents)
19
 
20
+ # Setup an async scheduler for periodic tasks like a bot restart
21
  scheduler = AsyncIOScheduler()
22
 
23
  def restart_bot():
 
29
  print("Scheduled restart triggered...")
30
  restart_bot()
31
 
32
+ async def process_row(row, guild, role):
33
+ """
34
+ Process a single CSV row to verify a member and add the role if needed.
35
+ """
36
+ hf_user_name = row['hf_user_name']
37
+ if pd.notna(hf_user_name) and hf_user_name.lower() != 'n/a':
38
+ discord_id = row['discord_user_id'].strip('L')
39
+ try:
40
+ member = guild.get_member(int(discord_id))
41
+ except Exception as e:
42
+ print(f"Error converting Discord ID {discord_id}: {e}")
43
+ return
44
+
45
+ if not member:
46
+ return
47
+ if role not in member.roles:
48
+ try:
49
+ await member.add_roles(role)
50
+ print(f"Role added to member: {member}")
51
+ lunar = bot.get_user(811235357663297546)
52
+ if lunar:
53
+ await lunar.send(f"Verified role given to {member}!")
54
+ await member.send(
55
+ f"Verification successful! [{member} <---> {row['discord_user_name']}]"
56
+ )
57
+ except Exception as e:
58
+ print(f"Error processing member {member}: {e}")
59
 
60
  async def give_verified_roles():
61
+ """
62
+ Periodically fetch CSV data from Google Sheets and verify roles for members.
63
+ """
64
  while True:
65
  try:
66
+ # Fetch the CSV from Google Sheets
 
67
  async with aiohttp.ClientSession() as session:
68
  try:
69
  async with session.get(
 
85
  await asyncio.sleep(30)
86
  continue
87
 
88
+ # Get the guild and role objects
89
  guild = bot.get_guild(879548962464493619)
90
+ if not guild:
91
+ print("Guild not found.")
92
+ await asyncio.sleep(30)
93
+ continue
94
  role = guild.get_role(900063512829755413)
95
+ if not role:
96
+ print("Role not found.")
97
+ await asyncio.sleep(30)
98
+ continue
99
 
100
+ await guild.chunk() # Ensure all guild members are cached
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
+ # Process all rows concurrently
103
+ tasks = [process_row(row, guild, role) for _, row in global_df.iterrows()]
104
+ await asyncio.gather(*tasks)
105
  except Exception as e:
106
+ print(f"Error in give_verified_roles loop: {e}")
107
+ # Adjust the sleep interval based on how often you expect updates
108
+ await asyncio.sleep(30)
109
 
110
+ @bot.event
111
+ async def on_ready():
112
+ print(f"We have logged in as {bot.user}")
113
+ scheduler.start()
114
+ # Start the background role verification loop
115
+ bot.loop.create_task(give_verified_roles())
116
 
117
+ # A simple Gradio interface function
118
  def greet(name):
119
  return "Hello " + name + "!"
120
+
121
+ # Create the Gradio interface
122
  demo = gr.Interface(fn=greet, inputs="text", outputs="text")
123
+
124
+ async def main():
125
+ # Launch Gradio in non-blocking mode so it doesn't interfere with the bot's event loop
126
+ demo.launch(share=False, block=False)
127
+ # Start the Discord bot (this will run until the bot is stopped)
128
+ await bot.start(DISCORD_TOKEN)
129
+
130
+ if __name__ == "__main__":
131
+ try:
132
+ asyncio.run(main())
133
+ except KeyboardInterrupt:
134
+ print("Shutting down...")