Spaces:
Sleeping
Sleeping
File size: 9,680 Bytes
904d01a e44cbdb 578412b 921313b 904d01a 921313b 904d01a 921313b 904d01a e44cbdb 904d01a e44cbdb 904d01a e44cbdb 904d01a 43e1e64 e44cbdb 904d01a e44cbdb 904d01a 43e1e64 e44cbdb 904d01a e44cbdb 904d01a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 | """
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()
|