MySafeCode commited on
Commit
c838643
·
verified ·
1 Parent(s): be61cc3

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -600
app.py DELETED
@@ -1,600 +0,0 @@
1
- import os
2
- import json
3
- import requests
4
- import gradio as gr
5
- from datetime import datetime
6
- from dotenv import load_dotenv
7
-
8
- # Load environment variables from .env file
9
- load_dotenv()
10
-
11
- # API Configuration
12
- API_KEY = os.getenv('StableCogKey', '')
13
- if not API_KEY:
14
- API_KEY = "StableCogKey"
15
-
16
- API_HOST = 'https://api.stablecog.com'
17
-
18
- # API Endpoints
19
- CREDITS_ENDPOINT = '/v1/credits'
20
- MODELS_ENDPOINT = '/v1/image/generation/models'
21
-
22
- CREDITS_URL = f'{API_HOST}{CREDITS_ENDPOINT}'
23
- MODELS_URL = f'{API_HOST}{MODELS_ENDPOINT}'
24
-
25
- headers = {
26
- 'Authorization': f'Bearer {API_KEY}',
27
- 'Content-Type': 'application/json'
28
- }
29
-
30
- def check_credits():
31
- """Check StableCog credits and return formatted results"""
32
- try:
33
- response = requests.get(CREDITS_URL, headers=headers, timeout=10)
34
-
35
- if response.status_code == 200:
36
- res_json = response.json()
37
-
38
- # Parse the actual response structure
39
- total_remaining_credits = res_json.get('total_remaining_credits', 0)
40
- credits_list = res_json.get('credits', [])
41
-
42
- # Calculate total initial credits from all credit entries
43
- total_initial_credits = 0
44
- total_used_credits = 0
45
- credit_details = []
46
-
47
- for credit in credits_list:
48
- credit_type = credit.get('type', {})
49
- initial_amount = credit_type.get('amount', 0)
50
- remaining_amount = credit.get('remaining_amount', 0)
51
- credit_name = credit_type.get('name', 'Unknown')
52
-
53
- total_initial_credits += initial_amount
54
- used_credits = initial_amount - remaining_amount
55
- total_used_credits += used_credits
56
-
57
- # Store credit details for display
58
- credit_details.append({
59
- 'name': credit_name,
60
- 'initial': initial_amount,
61
- 'remaining': remaining_amount,
62
- 'used': used_credits,
63
- 'expires': credit.get('expires_at', 'Never'),
64
- 'description': credit_type.get('description', '')
65
- })
66
-
67
- # Use total_remaining_credits from API or calculate it
68
- if total_remaining_credits == 0 and credits_list:
69
- total_remaining_credits = sum(credit.get('remaining_amount', 0) for credit in credits_list)
70
-
71
- # Calculate total credits
72
- total_credits = max(total_initial_credits, total_remaining_credits + total_used_credits)
73
-
74
- # Calculate percentage used
75
- if total_credits > 0:
76
- percentage_used = (total_used_credits / total_credits * 100)
77
- else:
78
- percentage_used = 0
79
-
80
- # Create formatted output
81
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S UTC")
82
-
83
- result = {
84
- "success": True,
85
- "total_credits": total_credits,
86
- "total_remaining_credits": total_remaining_credits,
87
- "total_used_credits": total_used_credits,
88
- "percentage_used": round(percentage_used, 2),
89
- "credit_details": credit_details,
90
- "total_credit_types": len(credits_list),
91
- "timestamp": timestamp,
92
- "raw_data": json.dumps(res_json, indent=2)
93
- }
94
-
95
- return result
96
-
97
- else:
98
- return {
99
- "success": False,
100
- "error": f"API Error: {response.status_code}",
101
- "message": response.text if response.text else "No response text",
102
- "status_code": response.status_code
103
- }
104
-
105
- except requests.exceptions.Timeout:
106
- return {
107
- "success": False,
108
- "error": "Timeout Error",
109
- "message": "The request timed out. Please try again."
110
- }
111
- except requests.exceptions.ConnectionError:
112
- return {
113
- "success": False,
114
- "error": "Connection Error",
115
- "message": "Could not connect to the API. Check your internet connection."
116
- }
117
- except Exception as e:
118
- return {
119
- "success": False,
120
- "error": f"Unexpected Error: {type(e).__name__}",
121
- "message": str(e)
122
- }
123
-
124
- def get_available_models():
125
- """Get available StableCog models"""
126
- try:
127
- response = requests.get(MODELS_URL, headers=headers, timeout=10)
128
-
129
- if response.status_code == 200:
130
- res_json = response.json()
131
- models_list = res_json.get('models', [])
132
-
133
- # Organize models by type
134
- organized_models = []
135
- for model in models_list:
136
- # Extract model information
137
- model_info = {
138
- 'id': model.get('id', ''),
139
- 'name': model.get('name', 'Unknown'),
140
- 'description': model.get('description', ''),
141
- 'type': model.get('type', 'unknown'),
142
- 'is_public': model.get('is_public', False),
143
- 'is_default': model.get('is_default', False),
144
- 'is_community': model.get('is_community', False),
145
- 'created_at': model.get('created_at', ''),
146
- 'updated_at': model.get('updated_at', '')
147
- }
148
- organized_models.append(model_info)
149
-
150
- # Sort models: default/public first, then by name
151
- organized_models.sort(key=lambda x: (
152
- not x['is_default'],
153
- not x['is_public'],
154
- x['name'].lower()
155
- ))
156
-
157
- # Count by type
158
- model_count = len(organized_models)
159
- public_count = sum(1 for m in organized_models if m['is_public'])
160
- default_count = sum(1 for m in organized_models if m['is_default'])
161
- community_count = sum(1 for m in organized_models if m['is_community'])
162
-
163
- result = {
164
- "success": True,
165
- "models": organized_models,
166
- "total_models": model_count,
167
- "public_models": public_count,
168
- "default_models": default_count,
169
- "community_models": community_count,
170
- "raw_data": json.dumps(res_json, indent=2),
171
- "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S UTC")
172
- }
173
-
174
- return result
175
-
176
- else:
177
- return {
178
- "success": False,
179
- "error": f"API Error: {response.status_code}",
180
- "message": response.text if response.text else "No response text",
181
- "status_code": response.status_code
182
- }
183
-
184
- except requests.exceptions.Timeout:
185
- return {
186
- "success": False,
187
- "error": "Timeout Error",
188
- "message": "The request timed out. Please try again."
189
- }
190
- except requests.exceptions.ConnectionError:
191
- return {
192
- "success": False,
193
- "error": "Connection Error",
194
- "message": "Could not connect to the API. Check your internet connection."
195
- }
196
- except Exception as e:
197
- return {
198
- "success": False,
199
- "error": f"Unexpected Error: {type(e).__name__}",
200
- "message": str(e)
201
- }
202
-
203
- def update_display():
204
- """Update the UI with credit information"""
205
- result = check_credits()
206
-
207
- if result["success"]:
208
- # Create a visual progress bar with color coding
209
- percentage = result["percentage_used"]
210
- if percentage < 50:
211
- bar_color = "#4CAF50" # Green
212
- status = "🟢 Good"
213
- status_color = "#4CAF50"
214
- elif percentage < 80:
215
- bar_color = "#FF9800" # Orange
216
- status = "🟡 Moderate"
217
- status_color = "#FF9800"
218
- else:
219
- bar_color = "#F44336" # Red
220
- status = "🔴 Low"
221
- status_color = "#F44336"
222
-
223
- # Build credit details HTML
224
- credit_details_html = ""
225
- for i, credit in enumerate(result["credit_details"]):
226
- if credit['remaining'] > 0 or credit['initial'] > 0:
227
- credit_percentage = (credit['used'] / credit['initial'] * 100) if credit['initial'] > 0 else 0
228
- credit_details_html += f"""
229
- <div style='margin-bottom: 15px; padding: 12px; background: rgba(255,255,255,0.05); border-radius: 8px;'>
230
- <div style='display: flex; justify-content: space-between; margin-bottom: 5px;'>
231
- <span style='font-weight: bold;'>{credit['name']}</span>
232
- <span>{credit['remaining']} / {credit['initial']} ⭐</span>
233
- </div>
234
- <div style='font-size: 12px; opacity: 0.8; margin-bottom: 8px;'>{credit['description']}</div>
235
- <div style='height: 6px; background: rgba(255,255,255,0.1); border-radius: 3px; overflow: hidden;'>
236
- <div style='height: 100%; width: {min(credit_percentage, 100)}%; background: {bar_color}; border-radius: 3px;'></div>
237
- </div>
238
- </div>
239
- """
240
-
241
- if credit_details_html:
242
- credit_details_section = f"""
243
- <div style='margin-top: 20px;'>
244
- <h3 style='margin-bottom: 15px; font-size: 18px;'>📊 Credit Breakdown</h3>
245
- {credit_details_html}
246
- </div>
247
- """
248
- else:
249
- credit_details_section = ""
250
-
251
- html_content = f"""
252
- <div style='font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; padding: 25px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px; color: white; box-shadow: 0 10px 30px rgba(0,0,0,0.2);'>
253
- <h2 style='text-align: center; margin-bottom: 30px; font-size: 28px; font-weight: 600;'>🎨 StableCog Credit Status</h2>
254
-
255
- <div style='background: rgba(255,255,255,0.1); backdrop-filter: blur(10px); padding: 25px; border-radius: 12px; margin-bottom: 25px; border: 1px solid rgba(255,255,255,0.2);'>
256
- <div style='display: flex; justify-content: space-between; margin-bottom: 15px; padding-bottom: 10px; border-bottom: 1px solid rgba(255,255,255,0.1);'>
257
- <span style='font-size: 16px; opacity: 0.9;'>Total Credits:</span>
258
- <span style='font-weight: bold; font-size: 24px;'>{result['total_credits']} ⭐</span>
259
- </div>
260
-
261
- <div style='display: flex; justify-content: space-between; margin-bottom: 15px; padding-bottom: 10px; border-bottom: 1px solid rgba(255,255,255,0.1);'>
262
- <span style='font-size: 16px; opacity: 0.9;'>Remaining Credits:</span>
263
- <span style='font-weight: bold; font-size: 24px; color: #90EE90;'>{result['total_remaining_credits']} ⭐</span>
264
- </div>
265
-
266
- <div style='display: flex; justify-content: space-between; margin-bottom: 20px;'>
267
- <span style='font-size: 16px; opacity: 0.9;'>Used Credits:</span>
268
- <span style='font-weight: bold; font-size: 20px;'>{result['total_used_credits']} ⭐</span>
269
- </div>
270
-
271
- <div style='margin-bottom: 20px;'>
272
- <div style='display: flex; justify-content: space-between; margin-bottom: 8px;'>
273
- <span style='font-size: 16px; opacity: 0.9;'>Overall Usage:</span>
274
- <span style='font-weight: bold;'>{result['percentage_used']}%</span>
275
- </div>
276
- <div style='height: 22px; background: rgba(255,255,255,0.15); border-radius: 11px; overflow: hidden; position: relative;'>
277
- <div style='height: 100%; width: {min(result['percentage_used'], 100)}%; background: {bar_color};
278
- border-radius: 11px; transition: width 0.5s ease-in-out; box-shadow: 0 0 10px {bar_color}80;'></div>
279
- <div style='position: absolute; right: 10px; top: 50%; transform: translateY(-50%); color: white; font-size: 12px; font-weight: bold; text-shadow: 0 1px 2px rgba(0,0,0,0.5);'>
280
- {result['percentage_used']}%
281
- </div>
282
- </div>
283
- </div>
284
-
285
- <div style='display: flex; justify-content: space-between; align-items: center; margin-top: 20px; padding-top: 20px; border-top: 1px solid rgba(255,255,255,0.2);'>
286
- <span style='font-size: 16px; opacity: 0.9;'>Status:</span>
287
- <span style='font-weight: bold; font-size: 18px; color: {status_color}; padding: 5px 15px; background: rgba(255,255,255,0.1); border-radius: 20px;'>
288
- {status}
289
- </span>
290
- </div>
291
-
292
- {credit_details_section}
293
- </div>
294
-
295
- <div style='text-align: center; font-size: 14px; opacity: 0.7; margin-top: 10px;'>
296
- ⏰ Last checked: {result['timestamp']} | 📋 Credit types: {result['total_credit_types']}
297
- </div>
298
- </div>
299
- """
300
-
301
- return html_content, result['raw_data'], result['total_remaining_credits'], result['percentage_used']
302
-
303
- else:
304
- # Error display
305
- html_content = f"""
306
- <div style='font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; padding: 25px; background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); border-radius: 15px; color: white; text-align: center; box-shadow: 0 10px 30px rgba(0,0,0,0.2);'>
307
- <h2 style='margin-bottom: 20px; font-size: 26px;'>⚠️ API Connection Error</h2>
308
-
309
- <div style='background: rgba(255,255,255,0.15); backdrop-filter: blur(10px); padding: 20px; border-radius: 10px; margin-bottom: 20px; border: 1px solid rgba(255,255,255,0.2);'>
310
- <p style='margin: 0 0 10px 0; font-size: 18px; font-weight: bold;'>{result.get('error', 'Unknown error')}</p>
311
- <p style='margin: 0; font-size: 14px; opacity: 0.9;'>{result.get('message', '')}</p>
312
- {'<p style="margin: 10px 0 0 0; font-size: 14px;">Status Code: ' + str(result.get('status_code', '')) + '</p>' if result.get('status_code') else ''}
313
- </div>
314
-
315
- <div style='margin-top: 25px; padding: 15px; background: rgba(255,255,255,0.1); border-radius: 10px;'>
316
- <h3 style='margin-top: 0;'>🔧 Troubleshooting Tips:</h3>
317
- <ul style='text-align: left; margin: 10px 0; padding-left: 20px;'>
318
- <li>Check if your API key is set in Hugging Face Secrets</li>
319
- <li>Verify the API key has proper permissions</li>
320
- <li>Ensure StableCog API is currently available</li>
321
- <li>Check your internet connection</li>
322
- </ul>
323
- </div>
324
- </div>
325
- """
326
-
327
- return html_content, f"Error: {result.get('error', 'Unknown error')}\n\nDetails: {result.get('message', '')}", 0, 0
328
-
329
- def display_models():
330
- """Display available models in a formatted way"""
331
- result = get_available_models()
332
-
333
- if result["success"]:
334
- models_html = ""
335
- model_counter = 0
336
-
337
- for model in result["models"]:
338
- model_counter += 1
339
-
340
- # Determine model type badge
341
- model_type = model['type'].upper() if model['type'] else 'UNKNOWN'
342
- if model['is_community']:
343
- model_type_badge = f"<span style='background: #FF6B6B; padding: 2px 8px; border-radius: 12px; font-size: 11px; margin-left: 5px;'>COMMUNITY</span>"
344
- elif model['is_default']:
345
- model_type_badge = f"<span style='background: #4CAF50; padding: 2px 8px; border-radius: 12px; font-size: 11px; margin-left: 5px;'>DEFAULT</span>"
346
- elif model['is_public']:
347
- model_type_badge = f"<span style='background: #2196F3; padding: 2px 8px; border-radius: 12px; font-size: 11px; margin-left: 5px;'>PUBLIC</span>"
348
- else:
349
- model_type_badge = f"<span style='background: #9E9E9E; padding: 2px 8px; border-radius: 12px; font-size: 11px; margin-left: 5px;'>{model_type}</span>"
350
-
351
- # Model ID (shortened)
352
- model_id_short = model['id'][:8] + "..." if len(model['id']) > 8 else model['id']
353
-
354
- models_html += f"""
355
- <div style='background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0.05) 100%); border-radius: 10px; padding: 15px; margin-bottom: 12px; border-left: 4px solid #667eea;'>
356
- <div style='display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;'>
357
- <h3 style='margin: 0; font-size: 16px;'>
358
- #{model_counter}. {model['name']}
359
- {model_type_badge}
360
- </h3>
361
- <span style='font-size: 12px; opacity: 0.7;'>ID: {model_id_short}</span>
362
- </div>
363
-
364
- <p style='margin: 0 0 10px 0; font-size: 14px; opacity: 0.9;'>{model['description'] or 'No description available'}</p>
365
-
366
- <div style='display: flex; gap: 10px; font-size: 12px; opacity: 0.7;'>
367
- <span>📅 Created: {model['created_at'][:10] if model['created_at'] else 'Unknown'}</span>
368
- <span>🔄 Updated: {model['updated_at'][:10] if model['updated_at'] else 'Unknown'}</span>
369
- </div>
370
- </div>
371
- """
372
-
373
- # Create stats section
374
- stats_html = f"""
375
- <div style='display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin-bottom: 20px;'>
376
- <div style='background: rgba(102, 126, 234, 0.2); padding: 15px; border-radius: 8px; text-align: center;'>
377
- <div style='font-size: 28px; font-weight: bold;'>{result['total_models']}</div>
378
- <div style='font-size: 12px; opacity: 0.8;'>Total Models</div>
379
- </div>
380
- <div style='background: rgba(76, 175, 80, 0.2); padding: 15px; border-radius: 8px; text-align: center;'>
381
- <div style='font-size: 28px; font-weight: bold;'>{result['public_models']}</div>
382
- <div style='font-size: 12px; opacity: 0.8;'>Public Models</div>
383
- </div>
384
- <div style='background: rgba(33, 150, 243, 0.2); padding: 15px; border-radius: 8px; text-align: center;'>
385
- <div style='font-size: 28px; font-weight: bold;'>{result['default_models']}</div>
386
- <div style='font-size: 12px; opacity: 0.8;'>Default Models</div>
387
- </div>
388
- <div style='background: rgba(255, 107, 107, 0.2); padding: 15px; border-radius: 8px; text-align: center;'>
389
- <div style='font-size: 28px; font-weight: bold;'>{result['community_models']}</div>
390
- <div style='font-size: 12px; opacity: 0.8;'>Community Models</div>
391
- </div>
392
- </div>
393
- """
394
-
395
- html_content = f"""
396
- <div style='font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; padding: 25px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px; color: white; box-shadow: 0 10px 30px rgba(0,0,0,0.2);'>
397
- <h2 style='text-align: center; margin-bottom: 25px; font-size: 28px; font-weight: 600;'>🤖 Available StableCog Models</h2>
398
-
399
- <div style='background: rgba(255,255,255,0.1); backdrop-filter: blur(10px); padding: 25px; border-radius: 12px; margin-bottom: 20px; border: 1px solid rgba(255,255,255,0.2);'>
400
- {stats_html}
401
- <div style='max-height: 500px; overflow-y: auto; padding-right: 10px;'>
402
- {models_html}
403
- </div>
404
- </div>
405
-
406
- <div style='text-align: center; font-size: 14px; opacity: 0.7; margin-top: 10px;'>
407
- ⏰ Last updated: {result['timestamp']} | 🔄 Refresh to see latest models
408
- </div>
409
- </div>
410
- """
411
-
412
- return html_content, result['raw_data']
413
-
414
- else:
415
- # Error display
416
- html_content = f"""
417
- <div style='font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; padding: 25px; background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); border-radius: 15px; color: white; text-align: center; box-shadow: 0 10px 30px rgba(0,0,0,0.2);'>
418
- <h2 style='margin-bottom: 20px; font-size: 26px;'>⚠️ Failed to Load Models</h2>
419
-
420
- <div style='background: rgba(255,255,255,0.15); backdrop-filter: blur(10px); padding: 20px; border-radius: 10px; margin-bottom: 20px; border: 1px solid rgba(255,255,255,0.2);'>
421
- <p style='margin: 0 0 10px 0; font-size: 18px; font-weight: bold;'>{result.get('error', 'Unknown error')}</p>
422
- <p style='margin: 0; font-size: 14px; opacity: 0.9;'>{result.get('message', '')}</p>
423
- </div>
424
- </div>
425
- """
426
-
427
- return html_content, f"Error: {result.get('error', 'Unknown error')}\n\nDetails: {result.get('message', '')}"
428
-
429
- def get_recommendation(remaining_credits, percentage_used):
430
- """Provide recommendations based on credit status"""
431
- if remaining_credits == 0:
432
- return "💸 **No credits remaining.** Please add credits to continue using StableCog services."
433
- elif percentage_used >= 90:
434
- return "🛑 **Critically low credits!** Consider purchasing more credits before starting new projects."
435
- elif percentage_used >= 75:
436
- return "⚠️ **Credits are running low.** You can still do some work, but plan ahead for larger projects."
437
- elif remaining_credits < 10:
438
- return "📝 **Limited credits available.** Good for small tasks, testing, or single images."
439
- elif remaining_credits < 50:
440
- return "✨ **Credits available!** Suitable for several medium-sized projects or batch processing."
441
- else:
442
- return "🚀 **Plenty of credits!** Ready for extensive image generation work and experimentation."
443
-
444
- # Create Gradio interface with simplified theme configuration for Gradio 6
445
- # In Gradio 6, theme is set differently or uses default
446
- with gr.Blocks(
447
- title="StableCog Dashboard",
448
- css="""
449
- footer {display: none !important;}
450
- .gradio-container {max-width: 1400px !important;}
451
- .tab-nav {background: rgba(255,255,255,0.1) !important; border-radius: 10px !important; padding: 5px !important;}
452
- .stat-box input {font-weight: bold !important; font-size: 18px !important;}
453
- .recommendation-box textarea {font-size: 16px !important; line-height: 1.5 !important;}
454
- body {
455
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
456
- min-height: 100vh;
457
- padding: 20px;
458
- }
459
- .gradio-container {
460
- background: rgba(255, 255, 255, 0.95);
461
- border-radius: 20px;
462
- padding: 20px;
463
- box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
464
- }
465
- """
466
- ) as demo:
467
- gr.Markdown("""
468
- # 🎯 StableCog Dashboard
469
-
470
- *Monitor your credits and explore available AI models for image generation.*
471
- """)
472
-
473
- with gr.Tabs() as tabs:
474
- with gr.Tab("💰 Credits Dashboard", id="credits"):
475
- # Status row
476
- with gr.Row():
477
- with gr.Column(scale=2):
478
- credits_html_output = gr.HTML(label="Credit Status")
479
- with gr.Column(scale=1):
480
- credits_raw_output = gr.Code(
481
- label="📋 Raw API Response",
482
- language="json",
483
- interactive=False,
484
- lines=15
485
- )
486
-
487
- # Stats row
488
- with gr.Row():
489
- with gr.Column():
490
- credits_display = gr.Number(
491
- label="Remaining Credits",
492
- interactive=False
493
- )
494
- with gr.Column():
495
- usage_display = gr.Number(
496
- label="Usage Percentage",
497
- interactive=False
498
- )
499
-
500
- # Recommendation row
501
- with gr.Row():
502
- recommendation_box = gr.Textbox(
503
- label="🎯 AI Recommendation",
504
- interactive=False,
505
- lines=3
506
- )
507
-
508
- # Control row
509
- with gr.Row():
510
- check_credits_btn = gr.Button(
511
- "🔄 Check Credits",
512
- variant="primary"
513
- )
514
-
515
- with gr.Tab("🤖 Available Models", id="models"):
516
- with gr.Row():
517
- with gr.Column(scale=2):
518
- models_html_output = gr.HTML(label="Available Models")
519
- with gr.Column(scale=1):
520
- models_raw_output = gr.Code(
521
- label="📋 Raw API Response",
522
- language="json",
523
- interactive=False,
524
- lines=15
525
- )
526
-
527
- with gr.Row():
528
- check_models_btn = gr.Button(
529
- "🔄 Refresh Models",
530
- variant="primary"
531
- )
532
-
533
- # Instructions and info
534
- with gr.Accordion("📚 How to Use & Setup", open=False):
535
- gr.Markdown("""
536
- ### Setting Up on Hugging Face Spaces:
537
-
538
- 1. **Add your API key as a Secret:**
539
- - Go to your Space's Settings → Secrets
540
- - Add a new secret with:
541
- - Key: `STABLECOG_API_KEY`
542
- - Value: `your_actual_api_key_here`
543
-
544
- ### Features:
545
- - **💰 Credits Dashboard**: Monitor your credit usage and remaining balance
546
- - **🤖 Available Models**: Browse all StableCog image generation models
547
- - **Smart Recommendations**: Get AI-powered suggestions based on your credits
548
- - **Credit Breakdown**: See detailed breakdown by credit type
549
-
550
- ### Understanding Credits:
551
- - **Free Credits**: Base credits provided to users
552
- - **Refund Credits**: Credits returned for failed generations
553
- - Each credit type may have different amounts and expiration
554
- """)
555
-
556
- gr.Markdown("""
557
- ---
558
- *Built with ❤️ for StableCog users | [Report Issues](https://github.com/stability-ai/stablecog/issues)*
559
- """)
560
-
561
- # Initialize displays on load
562
- demo.load(
563
- fn=update_display,
564
- inputs=None,
565
- outputs=[credits_html_output, credits_raw_output, credits_display, usage_display]
566
- )
567
-
568
- demo.load(
569
- fn=display_models,
570
- inputs=None,
571
- outputs=[models_html_output, models_raw_output]
572
- )
573
-
574
- # Connect buttons
575
- def update_all_credits():
576
- html, raw, credits, usage = update_display()
577
- recommendation = get_recommendation(credits, usage)
578
- return html, raw, credits, usage, recommendation
579
-
580
- check_credits_btn.click(
581
- fn=update_all_credits,
582
- inputs=None,
583
- outputs=[credits_html_output, credits_raw_output, credits_display, usage_display, recommendation_box]
584
- )
585
-
586
- check_models_btn.click(
587
- fn=display_models,
588
- inputs=None,
589
- outputs=[models_html_output, models_raw_output]
590
- )
591
-
592
- if __name__ == "__main__":
593
- # For Hugging Face Spaces - Gradio 6 syntax
594
- demo.launch(
595
- server_name="0.0.0.0",
596
- server_port=7860,
597
- share=False,
598
- show_error=True,
599
- debug=False
600
- )