import os
import requests
import gradio as gr
from datetime import datetime
# API Configuration
API_KEY = os.getenv('StableCogKey')
API_HOST = 'https://api.stablecog.com'
headers = {
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'
}
def get_models():
"""Fetch and display available models"""
try:
url = f'{API_HOST}/v1/image/generation/models'
response = requests.get(url, headers=headers, timeout=10)
if response.status_code == 200:
data = response.json()
models = data.get('models', [])
# Format display
display_text = f"📊 Found {len(models)} models\n"
display_text += f"⏰ {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
for i, model in enumerate(models, 1):
name = model.get('name', 'Unknown')
model_type = model.get('type', 'unknown')
description = model.get('description', 'No description')
display_text += f"{i}. 🔹 **{name}**\n"
display_text += f" 📝 {description}\n"
display_text += f" 🏷️ Type: {model_type}\n"
display_text += f" 🌍 Public: {'✅' if model.get('is_public') else '❌'}\n"
display_text += f" ⭐ Default: {'✅' if model.get('is_default') else '❌'}\n"
display_text += f" 👥 Community: {'✅' if model.get('is_community') else '❌'}\n"
display_text += "─" * 40 + "\n"
return display_text, str(data)
else:
return f"❌ Error {response.status_code}", f"Error: {response.text}"
except Exception as e:
return f"❌ Error: {str(e)}", "No data"
def get_outputs():
"""Fetch and display recent outputs with images"""
try:
url = f'{API_HOST}/v1/image/generation/outputs'
response = requests.get(url, headers=headers, timeout=10)
if response.status_code == 200:
data = response.json()
outputs = data.get('outputs', [])
total = data.get('total_count', 0)
next_cursor = data.get('next', 'None')
# Prepare display components
image_gallery = []
display_text = ""
gallery_html = "
"
if outputs:
display_text += f"📊 Total outputs: {total}\n"
display_text += f"📋 Showing: {len(outputs)} outputs\n"
display_text += f"⏭️ Next cursor: {next_cursor}\n"
display_text += f"⏰ {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
for i, output in enumerate(outputs, 1):
output_id = output.get('id', 'N/A')
short_id = output_id[:8] + '...' if len(output_id) > 8 else output_id
created_at = output.get('created_at', 'N/A')
status = output.get('status', 'unknown')
model_name = output.get('model_name', 'Unknown')
# Gallery status with emojis
gallery_status = output.get('gallery_status', 'not_submitted')
gallery_emoji = {
'not_submitted': '🔒',
'submitted': '📤',
'approved': '✅',
'rejected': '❌'
}.get(gallery_status, '❓')
# Favorites
is_favorited = output.get('is_favorited', False)
favorite_emoji = '❤️' if is_favorited else '🤍'
# Auto-submitted
was_auto_submitted = output.get('was_auto_submitted', False)
auto_submit_emoji = '🤖' if was_auto_submitted else '👤'
# Format timestamp
if created_at != 'N/A':
try:
dt = datetime.fromisoformat(created_at.replace('Z', '+00:00'))
created_at = dt.strftime('%Y-%m-%d %H:%M')
except:
pass
display_text += f"{i}. 🔹 **Output {short_id}**\n"
display_text += f" 🕒 Created: {created_at}\n"
display_text += f" 📊 Status: {status}\n"
display_text += f" 🤖 Model: {model_name}\n"
display_text += f" 🖼️ Gallery: {gallery_emoji} {gallery_status}\n"
display_text += f" {favorite_emoji} Favorite\n"
display_text += f" {auto_submit_emoji} {'Auto-submitted' if was_auto_submitted else 'Manual'}\n"
# Get image URLs
image_url = output.get('image_url')
image_urls = output.get('image_urls', [])
# Use image_url if available, otherwise check image_urls array
image_to_show = image_url or (image_urls[0] if image_urls else None)
if image_to_show:
# Add to gallery
gallery_html += f"""
📅 {created_at.split()[0] if ' ' in created_at else created_at}
🤖 {model_name[:15]}{'...' if len(model_name) > 15 else ''}
{gallery_emoji} {gallery_status}
{favorite_emoji}
"""
display_text += f" 🖼️ Image: {image_to_show[:50]}...\n"
else:
display_text += f" 🖼️ No image available\n"
# Show generation details if available
generation = output.get('generation', {})
if generation:
prompt = generation.get('prompt', 'No prompt')
width = generation.get('width', '?')
height = generation.get('height', '?')
display_text += f" 📝 Prompt: {prompt[:50]}...\n"
display_text += f" 📐 Size: {width}x{height}\n"
display_text += "─" * 40 + "\n"
else:
display_text = "📭 No outputs found. Generate some images first!"
gallery_html += "
No images found
"
gallery_html += "
"
return display_text, gallery_html, str(data)
else:
error_text = f"❌ Error {response.status_code}"
return error_text, "" + error_text + "
", f"Error: {response.text}"
except Exception as e:
error_text = f"❌ Error: {str(e)}"
return error_text, "" + error_text + "
", "No data"
# Create Gradio interface
with gr.Blocks(title="StableCog Dashboard") as demo:
gr.Markdown("# 🎯 StableCog Dashboard")
with gr.Tabs():
with gr.Tab("🤖 Models"):
with gr.Row():
models_display = gr.Textbox(label="Available Models", lines=25)
models_raw = gr.Code(label="Raw JSON", language="json", lines=25)
check_models_btn = gr.Button("🔄 Refresh Models", variant="primary")
check_models_btn.click(get_models, outputs=[models_display, models_raw])
with gr.Tab("🖼️ Outputs"):
with gr.Row():
with gr.Column(scale=2):
outputs_display = gr.Textbox(label="Output Details", lines=25)
with gr.Column(scale=3):
outputs_gallery = gr.HTML(label="Image Gallery")
with gr.Row():
outputs_raw = gr.Code(label="Raw JSON", language="json", lines=15)
check_outputs_btn = gr.Button("🔄 Refresh Outputs", variant="primary")
check_outputs_btn.click(get_outputs, outputs=[outputs_display, outputs_gallery, outputs_raw])
if __name__ == "__main__":
demo.launch()