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 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" # Create gallery HTML gallery_html = "
" 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 '🤍' # Format timestamp if created_at != 'N/A': try: dt = datetime.fromisoformat(created_at.replace('Z', '+00:00')) created_date = dt.strftime('%Y-%m-%d') created_time = dt.strftime('%H:%M') except: created_date = created_at created_time = '' else: created_date = 'Unknown' created_time = '' # Text display 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" # Get image URL image_url = output.get('image_url') if not image_url: # Try to get from image_urls array image_urls = output.get('image_urls', []) if image_urls and isinstance(image_urls, list) and len(image_urls) > 0: image_url = image_urls[0] if image_url: # Add to gallery gallery_html += f"""
📅 {created_date}
🤖 {model_name[:15]}{'...' if len(model_name) > 15 else ''}
{gallery_emoji} {gallery_status}
{favorite_emoji}
""" display_text += f" 🖼️ Image URL: {image_url[: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') if len(prompt) > 50: prompt = prompt[:50] + '...' display_text += f" 📝 Prompt: {prompt}\n" display_text += "─" * 40 + "\n" gallery_html += "
" if not outputs: display_text = "📭 No outputs found. Generate some images first!" gallery_html = "
No images found
" return display_text, gallery_html, str(data) else: error_msg = f"❌ Error {response.status_code}" return error_msg, f"
{error_msg}
", f"Error: {response.text}" except Exception as e: error_msg = f"❌ Error: {str(e)}" return error_msg, f"
{error_msg}
", "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=1): outputs_display = gr.Textbox(label="Output Details", lines=25) with gr.Column(scale=2): 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()