Quazim0t0 commited on
Commit
e0b825d
·
verified ·
1 Parent(s): 4a823b5

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -403
app.py DELETED
@@ -1,403 +0,0 @@
1
- """
2
- Main application for Dynamic Highscores system.
3
-
4
- This file integrates all components into a unified application.
5
- """
6
-
7
- import os
8
- import gradio as gr
9
- import threading
10
- import time
11
- from database_schema import DynamicHighscoresDB
12
- from auth import HuggingFaceAuth
13
- from benchmark_selection import BenchmarkSelector, create_benchmark_selection_ui
14
- from evaluation_queue import EvaluationQueue, create_model_submission_ui
15
- from leaderboard import Leaderboard, create_leaderboard_ui
16
- from sample_benchmarks import add_sample_benchmarks
17
-
18
- # Initialize components in main thread
19
- db = DynamicHighscoresDB()
20
- auth_manager = HuggingFaceAuth(db)
21
- benchmark_selector = BenchmarkSelector(db, auth_manager)
22
- evaluation_queue = EvaluationQueue(db, auth_manager)
23
- leaderboard = Leaderboard(db)
24
-
25
- # Initialize sample benchmarks if none exist
26
- print("Checking for existing benchmarks...")
27
- benchmarks = db.get_benchmarks()
28
- if not benchmarks or len(benchmarks) == 0:
29
- print("No benchmarks found. Adding sample benchmarks...")
30
- try:
31
- # Make sure the database path is clear
32
- print(f"Database path: {db.db_path}")
33
-
34
- # Import and call the function directly
35
- num_added = add_sample_benchmarks()
36
- print(f"Added {num_added} sample benchmarks.")
37
- except Exception as e:
38
- print(f"Error adding sample benchmarks: {str(e)}")
39
- # Try direct DB insertion as fallback
40
- try:
41
- print("Attempting direct benchmark insertion...")
42
- db.add_benchmark(
43
- name="MMLU (Massive Multitask Language Understanding)",
44
- dataset_id="cais/mmlu",
45
- description="Tests knowledge across 57 subjects"
46
- )
47
- print("Added fallback benchmark.")
48
- except Exception as inner_e:
49
- print(f"Fallback insertion failed: {str(inner_e)}")
50
- else:
51
- print(f"Found {len(benchmarks)} existing benchmarks.")
52
-
53
- # Custom CSS with theme awareness
54
- css = """
55
- /* Theme-adaptive colored info box */
56
- .info-text {
57
- background-color: rgba(53, 130, 220, 0.1);
58
- padding: 12px;
59
- border-radius: 8px;
60
- border-left: 4px solid #3498db;
61
- margin: 12px 0;
62
- }
63
-
64
- /* High-contrast text for elements - works in light and dark themes */
65
- .info-text, .header, .footer, .tab-content,
66
- button, input, textarea, select, option,
67
- .gradio-container *, .markdown-text {
68
- color: var(--text-color, inherit) !important;
69
- }
70
-
71
- /* Container styling */
72
- .container {
73
- max-width: 1200px;
74
- margin: 0 auto;
75
- }
76
-
77
- /* Header styling */
78
- .header {
79
- text-align: center;
80
- margin-bottom: 20px;
81
- font-weight: bold;
82
- font-size: 24px;
83
- }
84
-
85
- /* Footer styling */
86
- .footer {
87
- text-align: center;
88
- margin-top: 40px;
89
- padding: 20px;
90
- border-top: 1px solid var(--border-color-primary, #eee);
91
- }
92
-
93
- /* Login section styling */
94
- .login-section {
95
- padding: 10px;
96
- margin-bottom: 15px;
97
- border-radius: 8px;
98
- background-color: rgba(250, 250, 250, 0.1);
99
- text-align: center;
100
- }
101
-
102
- /* Login button styling */
103
- .login-button {
104
- background-color: #4CAF50 !important;
105
- color: white !important;
106
- font-weight: bold;
107
- }
108
-
109
- /* Force high contrast on specific input areas */
110
- input[type="text"], input[type="password"], textarea {
111
- background-color: var(--background-fill-primary) !important;
112
- color: var(--body-text-color) !important;
113
- }
114
-
115
- /* Force text visibility in multiple contexts */
116
- .gradio-markdown p, .gradio-markdown h1, .gradio-markdown h2,
117
- .gradio-markdown h3, .gradio-markdown h4, .gradio-markdown li {
118
- color: var(--body-text-color) !important;
119
- }
120
-
121
- /* Fix dark mode text visibility */
122
- @media (prefers-color-scheme: dark) {
123
- input, textarea, select {
124
- color: #ffffff !important;
125
- }
126
-
127
- ::placeholder {
128
- color: rgba(255, 255, 255, 0.5) !important;
129
- }
130
- }
131
- """
132
-
133
- # JavaScript login implementation
134
- def js_login_script():
135
- space_host = os.environ.get("SPACE_HOST", "localhost:7860")
136
- redirect_uri = f"https://{space_host}"
137
- client_id = os.environ.get("OAUTH_CLIENT_ID", "")
138
-
139
- return f"""
140
- <script src="https://unpkg.com/@huggingface/[email protected]/dist/index.umd.min.js"></script>
141
- <script>
142
- (async function() {{
143
- const HfHub = window.HfHub;
144
- try {{
145
- // Check if we're returning from OAuth redirect
146
- const oauthResult = await HfHub.oauthHandleRedirectIfPresent();
147
-
148
- if (oauthResult) {{
149
- console.log("User logged in:", oauthResult);
150
-
151
- // Store the user info in localStorage
152
- localStorage.setItem("hf_user", JSON.stringify(oauthResult.userInfo));
153
- localStorage.setItem("hf_token", oauthResult.accessToken);
154
-
155
- // Update the UI to show logged in state
156
- document.getElementById("login-status").textContent = "Logged in as: " + oauthResult.userInfo.name;
157
- document.getElementById("login-button").style.display = "none";
158
-
159
- // Add token to headers for future requests
160
- const originalFetch = window.fetch;
161
- window.fetch = function(url, options = {{}}) {{
162
- if (!options.headers) {{
163
- options.headers = {{}};
164
- }}
165
-
166
- // Add the token to the headers
167
- options.headers["HF-Token"] = oauthResult.accessToken;
168
-
169
- return originalFetch(url, options);
170
- }};
171
-
172
- // Refresh the page to update server-side state
173
- setTimeout(() => window.location.reload(), 1000);
174
- }}
175
- }} catch (error) {{
176
- console.error("OAuth error:", error);
177
- }}
178
-
179
- // Check if user is already logged in from localStorage
180
- const storedUser = localStorage.getItem("hf_user");
181
- const storedToken = localStorage.getItem("hf_token");
182
-
183
- if (storedUser && storedToken) {{
184
- try {{
185
- const userInfo = JSON.parse(storedUser);
186
- document.getElementById("login-status").textContent = "Logged in as: " + userInfo.name;
187
- document.getElementById("login-button").style.display = "none";
188
-
189
- // Add token to headers for future requests
190
- const originalFetch = window.fetch;
191
- window.fetch = function(url, options = {{}}) {{
192
- if (!options.headers) {{
193
- options.headers = {{}};
194
- }}
195
-
196
- // Add the token to the headers
197
- options.headers["HF-Token"] = storedToken;
198
-
199
- return originalFetch(url, options);
200
- }};
201
- }} catch (e) {{
202
- console.error("Error parsing stored user:", e);
203
- }}
204
- }}
205
-
206
- // Setup login button
207
- const loginButton = document.getElementById("login-button");
208
- if (loginButton) {{
209
- loginButton.addEventListener("click", async function() {{
210
- try {{
211
- const clientId = "{client_id}";
212
- if (clientId) {{
213
- // Use HuggingFace OAuth
214
- const loginUrl = await HfHub.oauthLoginUrl({{
215
- clientId: clientId,
216
- redirectUrl: "{redirect_uri}",
217
- scopes: ["openid", "profile"]
218
- }});
219
- console.log("Redirecting to:", loginUrl);
220
- window.location.href = loginUrl;
221
- }} else {{
222
- // Fallback to token-based login
223
- const token = prompt("Enter your HuggingFace token:");
224
- if (token) {{
225
- // Set the token as a cookie
226
- document.cookie = "hf_token=" + token + "; path=/; SameSite=Strict";
227
- // Reload the page to apply the token
228
- window.location.reload();
229
- }}
230
- }}
231
- }} catch (error) {{
232
- console.error("Error starting login process:", error);
233
- alert("Error starting login process. Please try again.");
234
- }}
235
- }});
236
- }}
237
- }})();
238
- </script>
239
- """
240
-
241
- # Simple manual authentication check
242
- def check_user(request: gr.Request):
243
- if request:
244
- # Check for HF-User header from Space OAuth
245
- username = request.headers.get("HF-User")
246
- if username:
247
- # User is logged in via HF Spaces
248
- print(f"User logged in via HF-User header: {username}")
249
- user = db.get_user_by_username(username)
250
- if not user:
251
- # Create user if they don't exist
252
- print(f"Creating new user: {username}")
253
- is_admin = (username == "Quazim0t0")
254
- db.add_user(username, username, is_admin)
255
- user = db.get_user_by_username(username)
256
- return username
257
-
258
- # Check for token in headers (from our custom JS)
259
- token = request.headers.get("HF-Token")
260
- if token:
261
- try:
262
- # Validate token with HuggingFace
263
- user_info = auth_manager.hf_api.whoami(token=token)
264
- if user_info:
265
- username = user_info.get("name", "")
266
- print(f"User logged in via token: {username}")
267
- return username
268
- except Exception as e:
269
- print(f"Token validation error: {e}")
270
-
271
- return None
272
-
273
- # Start evaluation queue worker
274
- def start_queue_worker():
275
- # Wait a moment to ensure app is initialized
276
- time.sleep(2)
277
- try:
278
- print("Starting evaluation queue worker...")
279
- evaluation_queue.start_worker()
280
- except Exception as e:
281
- print(f"Error starting queue worker: {e}")
282
-
283
- # Create Gradio app
284
- with gr.Blocks(css=css, title="Dynamic Highscores") as app:
285
- # State to track user
286
- user_state = gr.State(None)
287
-
288
- # Login section
289
- with gr.Row(elem_classes=["login-section"]):
290
- with gr.Column():
291
- gr.HTML("""
292
- <div style="display: flex; justify-content: space-between; align-items: center;">
293
- <div id="login-status">Not logged in</div>
294
- <button id="login-button" style="padding: 8px 16px; background-color: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer;">Login with HuggingFace</button>
295
- </div>
296
- """)
297
-
298
- # Add the JS login script
299
- gr.HTML(js_login_script())
300
-
301
- gr.Markdown("# 🏆 Dynamic Highscores", elem_classes=["header"])
302
- gr.Markdown("""
303
- Welcome to Dynamic Highscores - a community benchmark platform for evaluating and comparing language models.
304
-
305
- - **Add your own benchmarks** from HuggingFace datasets
306
- - **Submit your models** for CPU-only evaluation
307
- - **Compare performance** across different models and benchmarks
308
- - **Filter results** by model type (Merge, Agent, Reasoning, Coding, etc.)
309
- """, elem_classes=["info-text"])
310
-
311
- # Main tabs
312
- with gr.Tabs() as tabs:
313
- with gr.TabItem("📊 Leaderboard", id=0):
314
- leaderboard_ui = create_leaderboard_ui(leaderboard, db)
315
-
316
- with gr.TabItem("🚀 Submit Model", id=1):
317
- submission_ui = create_model_submission_ui(evaluation_queue, auth_manager, db)
318
-
319
- with gr.TabItem("🔍 Benchmarks", id=2):
320
- benchmark_ui = create_benchmark_selection_ui(benchmark_selector, auth_manager)
321
-
322
- with gr.TabItem("🌐 Community Framework", id=3):
323
- # Create a simple placeholder for the Community Framework tab
324
- gr.Markdown("""
325
- # 🌐 Dynamic Highscores Community Framework
326
-
327
- ## About Dynamic Highscores
328
-
329
- Dynamic Highscores is an open-source community benchmark system for evaluating language models on any dataset. This project was created to fill the gap left by the retirement of HuggingFace's "Open LLM Leaderboards" which were discontinued due to outdated benchmarks.
330
-
331
- ### Key Features
332
-
333
- - **Flexible Benchmarking**: Test models against any HuggingFace dataset, not just predefined benchmarks
334
- - **Community-Driven**: Anyone can add new benchmarks and submit models for evaluation
335
- - **Modern Evaluation**: Focus on contemporary benchmarks that better reflect current model capabilities
336
- - **CPU-Only Evaluation**: Ensures fair comparisons across different models
337
- - **Daily Submission Limits**: Prevents system abuse (one benchmark per day per user)
338
- - **Model Tagging**: Categorize models as Merge, Agent, Reasoning, Coding, etc.
339
- - **Unified Leaderboard**: View all models with filtering capabilities by tags
340
-
341
- ### Why This Project Matters
342
-
343
- When HuggingFace retired their "Open LLM Leaderboards," the community lost a valuable resource for comparing model performance. The benchmarks used had become outdated and didn't reflect the rapid advances in language model capabilities.
344
-
345
- Dynamic Highscores addresses this issue by allowing users to select from any benchmark on HuggingFace, including the most recent and relevant datasets. This ensures that models are evaluated on tasks that matter for current applications.
346
-
347
- ## Model Configuration System (Coming Soon)
348
-
349
- We're working on a modular system for model configurations that will allow users to:
350
-
351
- - Create and apply predefined configurations for different model types
352
- - Define parameters such as Temperature, Top-K, Min-P, Top-P, and Repetition Penalty
353
- - Share optimal configurations with the community
354
-
355
- ### Example Configuration (Gemma)
356
-
357
- ```
358
- Temperature: 1.0
359
- Top_K: 64
360
- Min_P: 0.01
361
- Top_P: 0.95
362
- Repetition Penalty: 1.0
363
- ```
364
-
365
- ## Contributing to the Project
366
-
367
- We welcome contributions from the community! If you'd like to improve Dynamic Highscores, here are some ways to get involved:
368
-
369
- - **Add New Features**: Enhance the platform with additional functionality
370
- - **Improve Evaluation Methods**: Help make model evaluations more accurate and efficient
371
- - **Fix Bugs**: Address issues in the codebase
372
- - **Enhance Documentation**: Make the project more accessible to new users
373
- - **Add Model Configurations**: Contribute optimal configurations for different model types
374
-
375
- To contribute, fork the repository, make your changes, and submit a pull request. We appreciate all contributions, big or small!
376
- """)
377
-
378
- gr.Markdown("""
379
- ### About Dynamic Highscores
380
-
381
- This platform allows users to select benchmarks from HuggingFace datasets and evaluate models against them.
382
- Each user can submit one benchmark per day (admin users are exempt from this limit).
383
- All evaluations run on CPU only to ensure fair comparisons.
384
-
385
- Created by Quazim0t0
386
- """, elem_classes=["footer"])
387
-
388
- # Check login on page load
389
- app.load(
390
- fn=check_user,
391
- inputs=[],
392
- outputs=[user_state]
393
- )
394
-
395
- # Launch the app
396
- if __name__ == "__main__":
397
- # Start queue worker in a separate thread
398
- queue_thread = threading.Thread(target=start_queue_worker)
399
- queue_thread.daemon = True
400
- queue_thread.start()
401
-
402
- # Launch the app
403
- app.launch()