File size: 7,049 Bytes
714cdab
 
b925697
714cdab
526fa85
 
 
 
714cdab
 
526fa85
 
 
 
 
 
1562935
 
526fa85
 
 
04fe107
e7617a7
714cdab
 
526fa85
714cdab
 
 
 
526fa85
 
 
 
 
fd8c150
 
714cdab
fd8c150
714cdab
 
04fe107
fd8c150
714cdab
526fa85
04fe107
 
 
 
 
b2b4327
 
04fe107
 
 
 
 
b2b4327
04fe107
 
b2b4327
 
 
 
 
04fe107
 
 
b2b4327
 
 
 
 
 
 
 
 
 
04fe107
 
 
 
b925697
fd8c150
 
 
 
04fe107
eed803b
fd8c150
04fe107
 
 
 
fd8c150
 
 
04fe107
 
 
 
fd8c150
 
 
 
526fa85
 
b925697
 
7748e2a
 
c3c43f6
 
 
07cd623
2da42f8
526fa85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b925697
04fe107
c3c43f6
714cdab
2da42f8
526fa85
714cdab
526fa85
714cdab
2da42f8
e07ccbf
0587701
ba801bf
714cdab
 
526fa85
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
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

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 Commune Leaderboard!</h2>
<p align="center">This leaderboard showcases the top-performing models in the Synthia Commune Subnet. The models are ranked based on their daily rewards.</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 in $COMAI. <b>UID</b> is the unique identifier of the model submitter. <b>$USD Value</b> is the estimated dollar value of the daily rewards.</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")


def make_query(client: CommuneClient) -> tuple[dict[int, int], dict[int, str]]:
    request_dict: dict[Any, Any] = {
        "SubspaceModule": [
            ("Name", [netuid]),
            ("Emission", []),
            ("Incentive", []),
            ("Dividends", []),
        ],
    }
    emission_dict: dict[int, int] = {}
    name_dict: dict[int, str] = {}
    result = client.query_batch_map(request_dict)

    emission = result["Emission"]
    netuid_emission = emission[netuid]
    incentive = result["Incentive"]
    netuid_incentive = incentive[netuid]
    dividends = result["Dividends"]
    netuid_dividends = dividends[netuid]

    names = result["Name"]
    highest_uid = max(names.keys())
    for uid in range(highest_uid + 1):

        emission = netuid_emission[uid]

        if emission != 0:
            incentive = netuid_incentive[uid]
            dividends = netuid_dividends[uid]
            
            if incentive > dividends:
                emission_dict[uid] = netuid_emission[uid]
                name_dict[uid] = names[uid]

    return emission_dict, name_dict


async def get_leaderboard_data():
    try:
        com_price = get_com_price()
        blocks_in_day = 10_800
        client = CommuneClient(node_url)
        emission_dict, name_dict = make_query(client)
        print("got tha emission")
        scores = {}
        for uid, emi in emission_dict.items():
            # we are doing ** 11 because emission are for modules have 2 extra units,
            # (otherwise it would be more intuive to do ** 9, hence from_nano)
            scores[uid] = (emi / 10**11) * blocks_in_day
        sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
        leaderboard_data = []
        for rank, (uid, score) in enumerate(sorted_scores, start=1):
            name = name_dict[uid]
            units = score
            usd_value = score * com_price
            leaderboard_data.append((rank, uid, name, units, f"${usd_value:.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 πŸ†", "UID", "Name", "Rewards / Day", "$USD Value"],
        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()