ashikshaffi08 commited on
Commit
b748005
β€’
1 Parent(s): a749388

reduced retries, fixed the async issue and loading indicator

Browse files
Files changed (1) hide show
  1. app.py +30 -34
app.py CHANGED
@@ -7,6 +7,7 @@ from gradio.themes.utils import colors, fonts, sizes
7
  from gradio.themes.utils.colors import Color
8
  from communex.client import CommuneClient
9
  import aiohttp
 
10
 
11
  FONT = """<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono&display=swap" rel="stylesheet">"""
12
  HEADER = """
@@ -24,19 +25,16 @@ LANGUAGES_SUPPORTED = """
24
  netuid = 1
25
  node_url = "wss://commune-api-node-2.communeai.net"
26
 
27
- async def get_com_price(session: aiohttp.ClientSession) -> Any:
28
- retries = 5
29
- for i in range(retries):
30
- try:
31
- async with session.get("https://api.mexc.com/api/v3/avgPrice?symbol=COMAIUSDT") as response:
32
- response.raise_for_status()
33
- price = float((await response.json())["price"])
34
- print(f"Fetched COM price: {price}")
35
- return price
36
- except Exception as e:
37
- print(f"Error fetching COM price: {e}")
38
- await asyncio.sleep(retries)
39
- raise RuntimeError("Failed to fetch COM price")
40
 
41
  async def make_query(client: CommuneClient) -> tuple[dict[int, int], dict[int, str]]:
42
  request_dict = {
@@ -76,29 +74,26 @@ async def make_query(client: CommuneClient) -> tuple[dict[int, int], dict[int, s
76
 
77
  async def get_leaderboard_data():
78
  async with aiohttp.ClientSession() as session:
79
- try:
80
- com_price = await get_com_price(session)
81
- blocks_in_day = 10_800
82
- client = CommuneClient(node_url)
83
- emission_dict, name_dict = await make_query(client)
84
- print("got the emission")
85
- scores = {}
86
- for uid, emi in emission_dict.items():
87
- scores[uid] = (emi / 10**11) * blocks_in_day
88
- sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
89
- leaderboard_data = []
90
- for rank, (uid, score) in enumerate(sorted_scores, start=1):
91
- name = name_dict[uid]
92
- units = score
93
- usd_value = score * com_price
94
- leaderboard_data.append((rank, uid, name, units, f"${usd_value:.2f}"))
95
- print("Leaderboard data:", leaderboard_data)
96
- return leaderboard_data
97
- except Exception as e:
98
- print(f"Error fetching leaderboard data: {e}")
99
- return []
100
 
101
  async def update_leaderboard_table():
 
102
  leaderboard_data = await get_leaderboard_data()
103
  leaderboard_data = [list(row) for row in leaderboard_data]
104
  for row in leaderboard_data:
@@ -106,6 +101,7 @@ async def update_leaderboard_table():
106
  total_usd_value = sum(float(row[4][1:]) for row in leaderboard_data)
107
  rewards_per_week = total_usd_value * 7
108
  rewards_per_month = total_usd_value * 30
 
109
  return leaderboard_data, f'''
110
  <div style="display: flex; justify-content: space-between; align-items: center; font-size: 16px; font-weight: bold;">
111
  <div>𝙏𝙀𝙩𝙖𝙑 $ π™ˆπ™žπ™£π™žπ™£π™œ π™π™šπ™¬π™–π™§π™™π™¨ π™‹π™šπ™§ π™’π™šπ™šπ™ : ${rewards_per_week:,.0f}</div>
 
7
  from gradio.themes.utils.colors import Color
8
  from communex.client import CommuneClient
9
  import aiohttp
10
+ import time
11
 
12
  FONT = """<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono&display=swap" rel="stylesheet">"""
13
  HEADER = """
 
25
  netuid = 1
26
  node_url = "wss://commune-api-node-2.communeai.net"
27
 
28
+ async def get_com_price(session: aiohttp.ClientSession) -> float:
29
+ try:
30
+ async with session.get("https://api.mexc.com/api/v3/avgPrice?symbol=COMAIUSDT") as response:
31
+ response.raise_for_status()
32
+ price = float((await response.json())["price"])
33
+ print(f"Fetched COM price: {price}")
34
+ return price
35
+ except Exception as e:
36
+ print(f"Error fetching COM price: {e}")
37
+ raise RuntimeError("Failed to fetch COM price")
 
 
 
38
 
39
  async def make_query(client: CommuneClient) -> tuple[dict[int, int], dict[int, str]]:
40
  request_dict = {
 
74
 
75
  async def get_leaderboard_data():
76
  async with aiohttp.ClientSession() as session:
77
+ com_price = await get_com_price(session)
78
+ blocks_in_day = 10_800
79
+ client = CommuneClient(node_url)
80
+ emission_dict, name_dict = await make_query(client)
81
+ print("Got the emission")
82
+ scores = {}
83
+ for uid, emi in emission_dict.items():
84
+ scores[uid] = (emi / 10**11) * blocks_in_day
85
+ sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
86
+ leaderboard_data = []
87
+ for rank, (uid, score) in enumerate(sorted_scores, start=1):
88
+ name = name_dict[uid]
89
+ units = score
90
+ usd_value = score * com_price
91
+ leaderboard_data.append((rank, uid, name, units, f"${usd_value:.2f}"))
92
+ print("Leaderboard data:", leaderboard_data)
93
+ return leaderboard_data
 
 
 
 
94
 
95
  async def update_leaderboard_table():
96
+ start_time = time.time()
97
  leaderboard_data = await get_leaderboard_data()
98
  leaderboard_data = [list(row) for row in leaderboard_data]
99
  for row in leaderboard_data:
 
101
  total_usd_value = sum(float(row[4][1:]) for row in leaderboard_data)
102
  rewards_per_week = total_usd_value * 7
103
  rewards_per_month = total_usd_value * 30
104
+ print(f"Updated leaderboard in {time.time() - start_time:.2f} seconds")
105
  return leaderboard_data, f'''
106
  <div style="display: flex; justify-content: space-between; align-items: center; font-size: 16px; font-weight: bold;">
107
  <div>𝙏𝙀𝙩𝙖𝙑 $ π™ˆπ™žπ™£π™žπ™£π™œ π™π™šπ™¬π™–π™§π™™π™¨ π™‹π™šπ™§ π™’π™šπ™šπ™ : ${rewards_per_week:,.0f}</div>