darkc0de commited on
Commit
0cfe4b3
Β·
verified Β·
1 Parent(s): d66e028

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -61
app.py CHANGED
@@ -14,98 +14,131 @@ def make_clickable_model(model_name, link):
14
 
15
  def get_data():
16
  """
17
- Downloads, processes, and returns the leaderboard data.
18
  """
19
- print("πŸ”„ Downloading data...")
20
  try:
21
- # Download file from the source space
22
  file_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME, repo_type="space")
23
 
24
- # Load CSV
25
- df = pd.read_csv(file_path)
26
-
27
- # Clean column names (remove whitespace)
28
  df.columns = df.columns.str.strip()
29
 
30
- # Debug: Print columns to logs to verify they exist
31
- print(f"Columns found: {df.columns.tolist()}")
32
-
33
- # Rename columns to standard names
34
- rename_map = {
35
- 'author/model_name': 'Model',
36
- 'Model Link': 'Link',
37
- 'UGI πŸ†': 'UGI',
38
- 'NatInt πŸ’‘': 'NatInt',
39
- 'W/10 πŸ‘': 'W/10'
40
- }
41
- df = df.rename(columns=rename_map)
42
 
43
- # Ensure required columns exist, create them if missing to prevent crash
44
- for col in ['UGI', 'NatInt', 'W/10']:
45
- if col not in df.columns:
46
- df[col] = 0
47
- else:
48
- # Force numeric
49
- df[col] = pd.to_numeric(df[col], errors='coerce').fillna(0)
 
50
 
51
- # --- Calculate UGI Index ---
 
 
 
 
52
  # Formula: (UGI + NatInt) * (W/10)
53
- df['UGI Index'] = (df['UGI'] + df['NatInt']) * df['W/10']
54
  df['UGI Index'] = df['UGI Index'].round(2)
55
 
56
- # Create Links
57
- if 'Link' in df.columns:
58
- df['Model'] = df.apply(lambda x: make_clickable_model(x['Model'], x['Link']), axis=1)
59
- # Drop the raw link column to clean up UI
60
- df = df.drop(columns=['Link'])
61
 
62
- # Sort by UGI Index High -> Low
63
  df = df.sort_values(by='UGI Index', ascending=False)
64
-
65
- # Add Rank Column
66
  df.insert(0, 'Rank', range(1, len(df) + 1))
67
 
68
- # Reorder Columns: Put Rank, Model, Index first
69
- cols = ['Rank', 'Model', 'UGI Index', 'UGI', 'NatInt', 'W/10']
70
- # Add whatever other columns are left
71
- cols += [c for c in df.columns if c not in cols]
 
 
 
 
 
 
 
 
 
72
 
73
- print(f"βœ… Loaded {len(df)} rows.")
74
- return df[cols]
 
75
 
76
  except Exception as e:
77
- print(f"❌ Error: {e}")
78
- # Return a dataframe with the error so it shows in the UI
79
- return pd.DataFrame({"Status": ["Error loading data"], "Details": [str(e)]})
 
 
 
 
 
 
 
 
 
80
 
81
  def search(query):
82
- """Search filter function"""
83
- df = get_data()
84
- if query:
85
- return df[df['Model'].astype(str).str.contains(query, case=False, na=False)]
86
- return df
 
 
 
 
87
 
88
  # --- UI ---
89
- with gr.Blocks(title="UGI Index Leaderboard") as demo:
 
 
 
 
 
90
  gr.Markdown("# πŸ† UGI Index Leaderboard")
91
- gr.Markdown("Reordered by **UGI Index**: `(UGI + NatInt) * (W/10)`")
92
 
93
  with gr.Row():
94
- search_box = gr.Textbox(label="Search Models", placeholder="Type model name...", scale=4)
95
- refresh_btn = gr.Button("Refresh", scale=1)
96
 
97
- # Passing `value=get_data` tells Gradio to run this function immediately on load
 
 
 
98
  data_table = gr.Dataframe(
99
- value=get_data,
100
  datatype="markdown",
101
  interactive=False,
102
  wrap=True
103
  )
104
 
105
- # Interactions
106
- search_box.submit(fn=search, inputs=search_box, outputs=data_table)
 
 
 
 
 
 
107
  search_box.change(fn=search, inputs=search_box, outputs=data_table)
108
- refresh_btn.click(fn=get_data, outputs=data_table)
109
 
110
- if __name__ == "__main__":
111
- demo.launch()
 
14
 
15
  def get_data():
16
  """
17
+ Downloads, processes, and returns the leaderboard data + status message.
18
  """
19
+ print("πŸ”„ Starting download...")
20
  try:
21
+ # 1. Download file
22
  file_path = hf_hub_download(repo_id=REPO_ID, filename=FILENAME, repo_type="space")
23
 
24
+ # 2. Load CSV
25
+ # utf-8-sig handles the BOM character if present
26
+ df = pd.read_csv(file_path, encoding='utf-8-sig')
 
27
  df.columns = df.columns.str.strip()
28
 
29
+ # 3. Fuzzy Column Matching (Robust against emojis)
30
+ # We look for columns that *contain* the keywords rather than exact match
31
+ def get_col(keyword):
32
+ matches = [c for c in df.columns if keyword.lower() in c.lower()]
33
+ return matches[0] if matches else None
34
+
35
+ model_col = get_col("author") or get_col("model")
36
+ link_col = get_col("link")
37
+ ugi_col = get_col("ugi")
38
+ natint_col = get_col("natint")
39
+ w10_col = get_col("w/10")
 
40
 
41
+ # 4. Check if we found everything
42
+ if not all([model_col, ugi_col, natint_col, w10_col]):
43
+ missing = []
44
+ if not model_col: missing.append("Model")
45
+ if not ugi_col: missing.append("UGI")
46
+ if not natint_col: missing.append("NatInt")
47
+ if not w10_col: missing.append("W/10")
48
+ return pd.DataFrame(), f"❌ Error: Could not find columns: {', '.join(missing)}. Found: {list(df.columns)}"
49
 
50
+ # 5. Clean Numeric Data
51
+ for col in [ugi_col, natint_col, w10_col]:
52
+ df[col] = pd.to_numeric(df[col], errors='coerce').fillna(0)
53
+
54
+ # 6. Calculate UGI Index
55
  # Formula: (UGI + NatInt) * (W/10)
56
+ df['UGI Index'] = (df[ugi_col] + df[natint_col]) * df[w10_col]
57
  df['UGI Index'] = df['UGI Index'].round(2)
58
 
59
+ # 7. Format Links
60
+ if link_col:
61
+ df[model_col] = df.apply(lambda x: make_clickable_model(x[model_col], x[link_col]), axis=1)
 
 
62
 
63
+ # 8. Sort and Rank
64
  df = df.sort_values(by='UGI Index', ascending=False)
 
 
65
  df.insert(0, 'Rank', range(1, len(df) + 1))
66
 
67
+ # 9. Renaming for display
68
+ final_cols = {
69
+ model_col: 'Model',
70
+ ugi_col: 'UGI',
71
+ natint_col: 'NatInt',
72
+ w10_col: 'W/10'
73
+ }
74
+ df = df.rename(columns=final_cols)
75
+
76
+ # 10. Select Columns to Display
77
+ display_cols = ['Rank', 'Model', 'UGI Index', 'UGI', 'NatInt', 'W/10']
78
+ # Add remaining columns if you want them
79
+ # extra_cols = [c for c in df.columns if c not in display_cols and c != link_col]
80
 
81
+ final_df = df[display_cols]
82
+
83
+ return final_df, f"βœ… Successfully loaded {len(final_df)} models."
84
 
85
  except Exception as e:
86
+ print(f"Error: {e}")
87
+ return pd.DataFrame(), f"❌ Error: {str(e)}"
88
+
89
+ # Global cache for search to use
90
+ CACHED_DF = pd.DataFrame()
91
+
92
+ def app_load():
93
+ """Called when app starts."""
94
+ global CACHED_DF
95
+ df, status = get_data()
96
+ CACHED_DF = df
97
+ return df, status
98
 
99
  def search(query):
100
+ """Filters the cached dataframe."""
101
+ if CACHED_DF.empty:
102
+ return CACHED_DF
103
+
104
+ if not query:
105
+ return CACHED_DF
106
+
107
+ # Filter
108
+ return CACHED_DF[CACHED_DF['Model'].astype(str).str.contains(query, case=False, na=False)]
109
 
110
  # --- UI ---
111
+ custom_css = """
112
+ .gradio-container {max-width: 95% !important}
113
+ footer {visibility: hidden}
114
+ """
115
+
116
+ with gr.Blocks(css=custom_css, title="UGI Index Leaderboard") as demo:
117
  gr.Markdown("# πŸ† UGI Index Leaderboard")
 
118
 
119
  with gr.Row():
120
+ status_box = gr.Textbox(label="Status", value="Initializing...", interactive=False, scale=4)
121
+ refresh_btn = gr.Button("Refresh Data", scale=1)
122
 
123
+ with gr.Row():
124
+ search_box = gr.Textbox(label="Search Models", placeholder="Type model name...", interactive=True)
125
+
126
+ # Initialize with empty dataframe
127
  data_table = gr.Dataframe(
128
+ headers=['Rank', 'Model', 'UGI Index', 'UGI', 'NatInt', 'W/10'],
129
  datatype="markdown",
130
  interactive=False,
131
  wrap=True
132
  )
133
 
134
+ # Wire up events
135
+ # 1. On Load: Fetch data, update table and status
136
+ demo.load(fn=app_load, outputs=[data_table, status_box])
137
+
138
+ # 2. On Refresh: Fetch data again
139
+ refresh_btn.click(fn=app_load, outputs=[data_table, status_box])
140
+
141
+ # 3. On Search: Filter existing data
142
  search_box.change(fn=search, inputs=search_box, outputs=data_table)
 
143
 
144
+ if __name__ == "__ma