Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
| 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 | |
| from apscheduler.schedulers.background import BackgroundScheduler | |
| from gspread_dataframe import get_as_dataframe, set_with_dataframe | |
| from huggingface_hub import HfApi, list_liked_repos, list_metrics, list_models | |
| 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) | |
| 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() |