""" Leonardo AI Design Generator - Test Space HuggingFace Space for testing Leonardo AI integration """ import os import gradio as gr import asyncio from leonardo.client import LeonardoClient from dotenv import load_dotenv # Load environment variables load_dotenv() # Initialize Leonardo client try: leo_client = LeonardoClient() client_ready = True except Exception as e: leo_client = None client_ready = False error_message = str(e) # Prompt templates DESIGN_TEMPLATES = { "Mobile App Mockup (3 Screens)": """ Professional mobile app presentation mockup, three iPhone 14 Pro devices arranged horizontally in a row, showcasing {app_type} application, left phone shows {screen_type}, Dribbble portfolio style, floating devices on gradient {colors} background, soft drop shadows beneath each phone, subtle 3D perspective, realistic iPhone bezels and notch, clean modern UI design on screens, {style}, professional product photography lighting, ultra high quality, photorealistic, 8k, studio lighting, premium mockup presentation, realistic device frames, clear readable UI elements on each screen, {elements} """.strip(), "Mobile App UI (Clean)": """ Professional mobile app UI design mockup, {app_type} application, {screen_type} screen, Visual style: {style}, Design system: Material Design 3, Color palette: {colors}, Layout elements: {elements}, Quality: high fidelity, clean UI mockup, smartphone screen portrait orientation, ultra detailed, pixel perfect, modern design guidelines """.strip(), "Web Dashboard": """ Professional web dashboard UI design, {app_type} application, {screen_type} view, Visual style: {style}, Design system: modern web design, Color palette: {colors}, Layout elements: {elements}, Quality: high fidelity, professional mockup, desktop view, wide screen, ultra detailed, Behance quality """.strip(), "Landing Page": """ Modern landing page design, {app_type} website, {section} section, Visual style: {style}, Color palette: {colors}, Layout elements: {elements}, Quality: high fidelity, professional mockup, responsive web design, ultra detailed, Awwwards quality """.strip() } NEGATIVE_PROMPT = """ blurry, low quality, distorted, lorem ipsum, placeholder text, dummy content, watermark, logo, branding, pixelated, artifacts, noise, duplicate screens, same screen repeated, messy layout, cluttered composition """.strip() async def check_credits(): """Check Leonardo AI credits""" if not client_ready: return f"❌ Client not initialized: {error_message}" try: user_info = await leo_client.get_user_info() total_credits = user_info['api_credits'] + user_info['subscription_tokens'] return f"✅ Available credits: {total_credits} (API: {user_info['api_credits']}, Subscription: {user_info['subscription_tokens']})" except Exception as e: return f"❌ Error: {str(e)}" async def generate_design( template_type: str, app_type: str, screen_type: str, style: str, colors: str, elements: str, custom_prompt: str, width: int, height: int, num_images: int, progress=gr.Progress() ): """Generate design mockup with Leonardo AI""" if not client_ready: return None, f"❌ Leonardo client not initialized: {error_message}" try: progress(0.1, desc="Preparing prompt...") # Build prompt if custom_prompt.strip(): final_prompt = custom_prompt else: template = DESIGN_TEMPLATES[template_type] final_prompt = template.format( app_type=app_type, screen_type=screen_type, style=style, colors=colors, elements=elements, section=screen_type ) progress(0.2, desc="Sending to Leonardo AI...") # Generate gen_result = await leo_client.generate_image( prompt=final_prompt, negative_prompt=NEGATIVE_PROMPT, width=width, height=height, num_images=num_images, guidance_scale=7, prompt_magic=True, alchemy=True ) generation_id = gen_result["generation_id"] cost = gen_result["api_credit_cost"] progress(0.4, desc=f"Generating... (Cost: {cost} credits)") # Wait for completion result = await leo_client.wait_for_generation(generation_id, max_wait_seconds=120) progress(0.9, desc="Processing results...") if result["status"] == "COMPLETE" and result["images"]: image_urls = [img["url"] for img in result["images"]] # Return first image and info info = f"""✅ Generation Complete! Generation ID: {generation_id} Cost: {cost} credits Images generated: {len(image_urls)} Image URLs: {chr(10).join(f'- {url}' for url in image_urls)} Prompt used: {final_prompt} """ progress(1.0, desc="Done!") return image_urls[0] if image_urls else None, info else: return None, f"❌ Generation failed or no images produced" except Exception as e: return None, f"❌ Error: {str(e)}" # Gradio Interface with gr.Blocks(title="Leonardo AI Design Generator", theme=gr.themes.Soft()) as demo: gr.Markdown(""" # 🎨 Leonardo AI Design Generator Test space for generating UI/UX design mockups using Leonardo AI. **Features:** - Mobile app UI mockups - Web dashboard designs - Landing page layouts - Customizable prompts """) with gr.Row(): with gr.Column(): gr.Markdown("### Credits Info") credits_btn = gr.Button("🔍 Check Credits", variant="secondary") credits_output = gr.Textbox(label="Credits Status", lines=2) gr.Markdown("---") with gr.Row(): with gr.Column(scale=1): gr.Markdown("### Design Settings") template_type = gr.Dropdown( choices=list(DESIGN_TEMPLATES.keys()), value="Mobile App Mockup (3 Screens)", label="Template Type" ) app_type = gr.Textbox( value="delivery rider gamification", label="App Type", placeholder="e.g., delivery rider gamification, e-commerce, social media" ) screen_type = gr.Textbox( value="home dashboard, active delivery, earnings stats", label="Screen Types (3 screens separated by commas)", placeholder="e.g., home dashboard, active delivery, earnings stats" ) style = gr.Textbox( value="energetic gaming aesthetic, modern, vibrant", label="Visual Style", placeholder="e.g., minimalist, energetic gaming, corporate" ) colors = gr.Textbox( value="primary #FF3B30, secondary #FFD60A, background #0A0A0A", label="Color Palette", placeholder="e.g., primary #FF0000, secondary #00FF00" ) elements = gr.Textbox( value="stats cards, performance chart, recent orders list", label="Layout Elements", placeholder="e.g., header, cards, buttons, charts", lines=3 ) gr.Markdown("### Advanced Options") custom_prompt = gr.Textbox( label="Custom Prompt (optional - overrides template)", placeholder="Enter your own Leonardo AI prompt...", lines=5 ) with gr.Row(): width = gr.Slider( minimum=320, maximum=1536, value=1280, step=8, label="Width (3 screens: 1280, single: 512)" ) height = gr.Slider( minimum=320, maximum=1536, value=768, step=8, label="Height (3 screens: 768, portrait: 896)" ) num_images = gr.Slider( minimum=1, maximum=4, value=1, step=1, label="Number of Images" ) generate_btn = gr.Button("🚀 Generate Design", variant="primary", size="lg") with gr.Column(scale=1): gr.Markdown("### Generated Design") output_image = gr.Image(label="Design Mockup", type="filepath") output_info = gr.Textbox(label="Generation Info", lines=15) # Event handlers credits_btn.click( fn=check_credits, outputs=credits_output ) generate_btn.click( fn=generate_design, inputs=[ template_type, app_type, screen_type, style, colors, elements, custom_prompt, width, height, num_images ], outputs=[output_image, output_info] ) gr.Markdown(""" --- ### Tips: - Check your credits before generating - Mobile screens are typically 375x812 (iPhone) or 360x800 (Android) - Desktop mockups work well at 1024x768 - Be specific in your prompts for better results - Use negative prompts to avoid unwanted elements ### Cost: - Each generation costs approximately 10-20 credits - Higher resolution and more images = higher cost """) # Launch if __name__ == "__main__": demo.launch()