afght12 commited on
Commit
714cdab
·
verified ·
1 Parent(s): 354e747

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -0
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import time
4
+ from typing import Any
5
+ from communex.client import CommuneClient
6
+ from communex.balance import from_nano
7
+ import json
8
+
9
+ netuid = 0
10
+ node_url = "wss://commune.api.onfinality.io/public-ws"
11
+
12
+ def get_com_price() -> Any:
13
+ retries = 5
14
+ for i in range(0, retries):
15
+ try:
16
+ return float(requests.get("https://api.mexc.com/api/v3/avgPrice?symbol=COMAIUSDT").json()["price"])
17
+ except Exception as e:
18
+ print(e)
19
+ if i == retries - 1:
20
+ raise
21
+ time.sleep(retries)
22
+ raise RuntimeError()
23
+
24
+ def get_score():
25
+ com_price = get_com_price()
26
+ blocks_in_day = 10_800
27
+ client = CommuneClient(node_url)
28
+ emission = client.query("Emission", params=[netuid])
29
+ distribution_dict: dict[int, float] = {}
30
+ for uid, emi in enumerate(emission):
31
+ distribution_dict[uid] = ((emi / 10**11) * blocks_in_day) * com_price
32
+ return distribution_dict
33
+
34
+ def load_leaderboard():
35
+ with open("leaderboard.json", "r") as f:
36
+ leaderboard_data = json.load(f)
37
+ return leaderboard_data
38
+
39
+ def save_leaderboard():
40
+ scores = get_score()
41
+ sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
42
+ leaderboard_data = []
43
+ for rank, (uid, score) in enumerate(sorted_scores, start=1):
44
+ leaderboard_data.append({"rank": rank, "uid": uid, "score": score})
45
+ with open("leaderboard.json", "w") as f:
46
+ json.dump(leaderboard_data, f)
47
+
48
+ with gr.Blocks() as demo:
49
+ gr.Markdown("# Commune Leaderboard")
50
+
51
+ leaderboard_data = load_leaderboard()
52
+
53
+ leaderboard_table = gr.components.DataFrame(
54
+ value=leaderboard_data,
55
+ headers=["rank", "uid", "score"],
56
+ datatype=["number", "number", "number"],
57
+ interactive=False,
58
+ visible=True
59
+ )
60
+
61
+ refresh_button = gr.Button("Refresh Leaderboard")
62
+
63
+ def refresh_leaderboard():
64
+ save_leaderboard()
65
+ updated_data = load_leaderboard()
66
+ return gr.components.DataFrame.update(value=updated_data)
67
+
68
+ refresh_button.click(fn=refresh_leaderboard, outputs=leaderboard_table)
69
+
70
+ if __name__ == "__main__":
71
+ demo.launch()