Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
File size: 9,403 Bytes
5a26019 65c7e49 8b23687 5a26019 65c7e49 5086fc0 5a26019 39a3bfb 5a26019 8b23687 65c7e49 5a26019 65c7e49 bfb4d01 5a26019 4d6295e 6386d92 5a26019 6386d92 5a26019 8b23687 fc1881a 5a26019 7586254 5a26019 42d451d 39a3bfb 5a26019 500d61b c284eb8 65c7e49 421347b a5603d3 7187a61 cf1e692 a5603d3 5a26019 d520393 e91740b 39a3bfb 0aa83ad 5a26019 4e807ea 5a26019 0e4a071 d7d3013 6b5ae25 f5d5dc6 4e807ea f5d5dc6 4e807ea 5a26019 eb0e82f e698139 963edf4 5a26019 963edf4 5a26019 963edf4 5a26019 e698139 bf12b5f f5d5dc6 d520393 4f19e81 5fc7c16 0b7628c 4f19e81 4e807ea 0b7628c 816bd48 06985d8 635c9a7 146c3c3 66cef69 459c6ce 4d6295e 5a26019 4e807ea bc29339 5a26019 bc29339 5a26019 bc29339 5a26019 bc29339 5a26019 8e267f5 5a26019 bc29339 907d206 5a26019 bc29339 5a26019 bc29339 e63a0f9 5a26019 0c0ca86 c78fdb7 5a26019 215dffc 5a26019 bc29339 5a26019 4e807ea 4f0ae67 bfb3bca 22d3c95 f5d5dc6 5a26019 359b637 42641d6 f5d5dc6 63e32ce ca772d6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 |
import os
import re
import csv
import json
import time
import random
import asyncio
import discord
import logging
import os.path
import secrets
import gspread
import datetime
import tempfile
import requests
import threading
import gradio_client
import numpy as np
import pandas as pd
import gradio as gr
import plotly.graph_objects as go
from tabulate import tabulate
from requests import HTTPError
from gradio_client import Client
from discord import Color, Embed
from huggingface_hub import HfApi
from discord.ui import Button, View
from discord.ext import commands, tasks
from datetime import datetime, timedelta
from urllib.parse import urlparse, parse_qs
# starting to migrate to HF datasets and away from google sheets
from huggingface_hub import HfApi, HfFolder, Repository
from apscheduler.executors.pool import ThreadPoolExecutor
from apscheduler.executors.asyncio import AsyncIOExecutor
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from gspread_formatting.dataframe import format_with_dataframe
DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='!', intents=intents)
GRADIO_APP_URL = "https://huggingface.co/spaces/discord-community/LevelBot"
""""""
bot_ids = [1136614989411655780, 1166392942387265536, 1158038249835610123, 1130774761031610388, 1155489509518098565, 1155169841276260546, 1152238037355474964, 1154395078735953930]
""""""
hf_token = os.environ.get("HF_TOKEN")
class DMButton(Button):
def __init__(self, label, style):
super().__init__(label=label, style=style)
async def callback(self, interaction: discord.Interaction):
# await interaction.user.send(self.message) # this is for DMs, but users may have DMs disabled
user_id = interaction.user.id
guild = interaction.guild
member = guild.get_member(user_id)
pending_role = guild.get_role(1380908157475360899) # pending verification role, this is to verify that the discord account actually clicked the button at least once
if member and pending_role:
await member.add_roles(pending_role)
print(f"Assigned 'Pending Verification' role to {member.name}") # should log this in #admin-logs properly
unique_link = f"<{GRADIO_APP_URL}?user_id={user_id}>" # don't need token
message = f"Login link generated! To complete the verification process:\n- 1 Visit this link,\n- 2 click the 'π€Sign in with Hugging Face' button\n\n{unique_link}"
await interaction.response.send_message(message, ephemeral=True)
@bot.event
async def on_ready():
try:
print(f'Logged in as {bot.user.name}')
guild = bot.get_guild(879548962464493619)
await guild.chunk() # get all users into bot cache
channel = bot.get_channel(900125909984624713)
if channel:
try:
message = await channel.fetch_message(1271145797433557023)
if message:
button = DMButton(label="Verify Discord Account", style=discord.ButtonStyle.primary)
view = View(timeout=None)
view.add_item(button)
await message.edit(view=view)
print("message edited")
except discord.NotFound:
print(f"Message with ID 1271145797433557023 not found.")
except discord.HTTPException as e:
print(f"Failed to fetch message with ID 1271145797433557023: {e}")
print("------------------------------------------------------------------------")
except Exception as e:
print(f"on_ready Error: {e}")
DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)
def run_bot():
bot.run(DISCORD_TOKEN)
threading.Thread(target=run_bot).start()
#-------------------------------------------------------------------------------------------------------------------------------
"""
def verify_button(profile: gr.OAuthProfile | None, request: gr.Request) -> str:
url_str = str(request.url)
query_params = parse_qs(urlparse(url_str).query)
user_id = query_params.get('user_id', [None])[0]
print(f"user_id={user_id}")
token = query_params.get('token', [None])[0]
print(f"token={token}")
print(f"||| token:{token}||| user_id:{user_id}||| profile:{profile}||| user_tokens:{user_tokens}")
if user_id is None or token is None:
return "# β Invalid link. Generate a new link [here](https://discord.com/channels/879548962464493619/900125909984624713) !"
if int(user_id) not in user_tokens or user_tokens[int(user_id)] != token:
return "# β Invalid or expired link. Generate a new link [here](https://discord.com/channels/879548962464493619/900125909984624713) !"
if profile is None:
return f"# β Not logged in with Hugging Face yet."
# check if hf_user_name in dataframe:
if profile.username in global_df['hf_user_name'].values:
return (f"# β The HF account {profile.username} is already verified!")
# check if discord_user_id in dataframe:
altered_member_id = "L" + str(user_id) + "L"
if altered_member_id in global_df['discord_user_id'].values:
hf_user_name = global_df.loc[global_df['discord_user_id'] == altered_member_id, 'hf_user_name'].iloc[0]
if pd.isnull(hf_user_name) or hf_user_name == 'n/a':
# empty (no link created yet between discord_user_id and hf_user_name) so we can update
verified_date = datetime.now().strftime("%m/%d/%Y, %H:%M:%S")
global_df.loc[global_df['discord_user_id'] == altered_member_id, 'hf_user_name'] = profile.username
global_df.loc[global_df['discord_user_id'] == altered_member_id, 'verified_date'] = verified_date
org_link = "https://huggingface.co/organizations/discord-community/share/wPKRAHYbAlaEaCxUxcqVyaaaeZcYagDvqc"
invite_message = "Click to join our community org on the HF Hub!"
return (f"# β
Verification successful! [Discord ID {user_id} <---> {profile.username}] π€\n{invite_message}\n{org_link} ")
print(f"# β
Verification successful! [Discord ID {user_id} <---> {profile.username}] π€")
else:
return (f"# β The Discord account {user_id} is already verified! To change discord accounts or HF accounts, contact @lunarflu on discord")
print(f"# β The Discord account {user_id} is already verified! To change discord accounts or HF accounts, contact @lunarflu on discord")
# Remove the token after successful verification
del user_tokens[int(user_id)]
"""
def verify_button(profile: gr.OAuthProfile | None, request: gr.Request) -> str:
query_params = parse_qs(urlparse(str(request.url)).query)
user_id = query_params.get('user_id', [None])[0]
if not user_id:
return "# β Missing Discord user ID."
if profile is None:
return "# β You're not logged in with Hugging Face."
async def upgrade_role():
guild = bot.get_guild(879548962464493619)
member = guild.get_member(int(user_id))
pending_role = guild.get_role(1380908157475360899) # pending
verified_role = guild.get_role(900063512829755413) # verified
if not member:
print(f"β Could not find Discord user {user_id}")
return
if pending_role in member.roles:
await member.remove_roles(pending_role)
await member.add_roles(verified_role)
print(f"β
{member.name} verified and upgraded to verified role.")
else:
print(f"β οΈ {member.name} did not have the pending role. Ignoring.")
asyncio.create_task(upgrade_role())
return f"# β
Verification successful! Welcome, {profile.username} π"
demo = gr.Blocks()
with demo:
try:
TITLE = """<h1 align="center" id="space-title">π€ Hugging Face Level Leaderboard</h1>"""
gr.HTML(TITLE)
with gr.Tabs(elem_classes="tab-buttons") as tabs:
#------------------------------------------------------------------------------
with gr.TabItem("β
Discord Verification", elem_id="verify-tab", id=2):
login_button = gr.LoginButton()
m1 = gr.Markdown()
demo.load(verify_button, inputs=None, outputs=m1)
def check_login_status():
try:
return login_button.get_session().get("oauth_info", None)
except AttributeError:
return None
def check_login_wrapper():
session = check_login_status()
if session is None:
return "Not logged in."
else:
return f"Logged in as {session.get('username', 'Unknown')}"
login_button.click(check_login_wrapper, inputs=None, outputs=m1)
#------------------------------------------------------------------------------
#with gr.TabItem("π Hub-only leaderboard", elem_id="hub-table", id=2):
except Exception as e:
print(f"gradio demo Error: {e}")
demo.queue().launch() |