afght12's picture
Update app.py
526fa85 verified
raw
history blame
5.8 kB
import gradio as gr
import requests
import asyncio
from typing import Any
from gradio.themes.base import Base
from gradio.themes.utils import colors, fonts, sizes
from gradio.themes.utils.colors import Color
from typing import Iterable
from communex.client import CommuneClient
from communex.balance import from_nano
FONT = """<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono&display=swap" rel="stylesheet">"""
TITLE = """<h1 align="center" id="space-title" class="typewriter">Synthia Leaderboard</h1>"""
IMAGE = """<a href="https://www.communeai.org/commune-logo.svg" target="_blank"><img src="https://www.communeai.org/commune-logo.svg" alt="Synthia Logo" style="margin: auto; width: 20%; border: 0;" /></a>"""
HEADER = """<h2 align="center" class="typewriter">Welcome to the Synthia Leaderboard!</h2>
<p align="center">This leaderboard showcases the top-performing models in the Synthia competition. The models are ranked based on their daily rewards and perplexity scores.</p>"""
EVALUATION_HEADER = """<h3 align="center">Evaluation Details</h3>"""
EVALUATION_DETAILS = """<p align="center"><b>Name</b> represents the model name. <b>Rewards / Day</b> indicates the expected daily rewards for each model. <b>Perplexity</b> represents the model's performance on the evaluation data (lower is better). <b>UID</b> is the unique identifier of the model submitter. <b>Block</b> represents the block number when the model was submitted.</p>"""
netuid = 24
node_url = "wss://commune.api.onfinality.io/public-ws"
def get_com_price() -> Any:
retries = 5
for i in range(0, retries):
try:
price = float(
requests.get(
"https://api.mexc.com/api/v3/avgPrice?symbol=COMAIUSDT"
).json()["price"]
)
print(f"Fetched COM price: {price}")
return price
except Exception as e:
print(f"Error fetching COM price: {e}")
if i == retries - 1:
raise
asyncio.sleep(retries)
raise RuntimeError("Failed to fetch COM price")
async def get_leaderboard_data():
try:
com_price = get_com_price()
blocks_in_day = 10_800
client = CommuneClient(node_url)
emission = client.query("Emission", params=[netuid])
print("got tha emission")
scores = {}
for uid, emi in enumerate(emission):
scores[uid] = ((emi / 10**11) * blocks_in_day) * com_price
sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
leaderboard_data = []
for rank, (uid, score) in enumerate(sorted_scores, start=1):
leaderboard_data.append((rank, uid, f"${score:.2f}"))
return leaderboard_data
except Exception as e:
print(f"Error fetching leaderboard data: {e}")
return []
async def update_leaderboard_table():
leaderboard_data = await get_leaderboard_data()
# Convert tuples to lists
leaderboard_data = [list(row) for row in leaderboard_data]
# Add emojis to the leaderboard data
for row in leaderboard_data:
row[0] = f"{row[0]} πŸ†"
return leaderboard_data
white = Color(
name="white",
c50="#000000",
c100="#000000",
c200="#eeeeee",
c300="#e0e0e0",
c400="#000000",
c500="#cccccc",
c600="#b3b3b3",
c700="#000000",
c800="#f0f0f0",
c900="#e8e8e8",
c950="#e2e2e2",
)
class Seafoam(Base):
def __init__(
self,
*,
primary_hue: colors.Color | str = white,
secondary_hue: colors.Color | str = white,
neutral_hue: colors.Color | str = white,
spacing_size: sizes.Size | str = sizes.spacing_md,
radius_size: sizes.Size | str = sizes.radius_md,
text_size: sizes.Size | str = sizes.text_lg,
font: fonts.Font | str | Iterable[fonts.Font | str] = (
fonts.GoogleFont("Quicksand"),
"ui-sans-serif",
"sans-serif",
),
font_mono: fonts.Font | str | Iterable[fonts.Font | str] = (
fonts.GoogleFont("IBM Plex Mono"),
"ui-monospace",
"monospace",
),
):
super().__init__(
primary_hue=primary_hue,
secondary_hue=secondary_hue,
neutral_hue=neutral_hue,
spacing_size=spacing_size,
radius_size=radius_size,
text_size=text_size,
font=font,
font_mono=font_mono,
)
super().set(
block_title_text_weight="600",
block_border_width="3px",
block_shadow="*shadow_drop_lg",
button_shadow="*shadow_drop_lg",
button_large_padding="32px",
button_primary_background_fill_hover="*button_primary_background_fill",
# Add the following lines to set the button colors
button_primary_background_fill="#333333", # Dark background color
button_primary_text_color="#ffffff", # White text color
)
seafoam = Seafoam()
with gr.Blocks(theme=seafoam, analytics_enabled=True) as demo:
gr.HTML(FONT)
gr.HTML(TITLE)
gr.HTML(IMAGE)
gr.HTML(HEADER)
gr.HTML(EVALUATION_HEADER)
gr.HTML(EVALUATION_DETAILS)
leaderboard_table = gr.components.Dataframe(
headers=["Rank πŸ†", "User πŸ˜„", "Score πŸ’°"],
datatype=["str", "str", "str"],
interactive=False,
visible=True,
elem_id="leaderboard-table",
)
refresh_button = gr.Button("Refresh Leaderboard")
refresh_button.click(fn=update_leaderboard_table, outputs=leaderboard_table)
# Initial load of leaderboard data
demo.load(update_leaderboard_table, inputs=None, outputs=leaderboard_table)
if __name__ == "__main__":
demo.launch()