space-ac-design / agents /design_preview_generator.py
Claude
Deploy AC3 Complete Refactor - Deterministic Styling + AI Composition
42f73ba
Raw History Blame Contribute Delete
10 kB
"""
AC3: Design Preview Generator Agent
Generates realistic screen previews using Leonardo.ai based on design themes.
Takes a design theme from AC2 and generates visual mockups of app screens.
"""
import os
import json
import time
from typing import Dict, Any, List
import httpx
class DesignPreviewGenerator:
"""
Agent that generates screen previews using Leonardo.ai
"""
def __init__(self):
self.name = "design_preview_generator"
self.description = "Generates realistic app screen previews using Leonardo.ai"
self.leonardo_api_key = os.getenv("LEONARDO_API_KEY", "")
self.leonardo_api_base = "https://cloud.leonardo.ai/api/rest/v1"
# Leonardo.ai Phoenix model ID for photorealistic images
self.model_id = "6b645e3a-d64f-4341-a6d8-7a3690fbf042" # Phoenix
def process(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
"""
Generate screen previews from a design theme
Args:
input_data: {
"theme": {...}, # Complete theme from AC2
"screens": ["home", "profile", "settings"], # Screens to generate
"app_context": {
"type": "mobile_app",
"description": "E-commerce app"
}
}
Returns:
{
"previews": [
{
"screen": "home",
"image_url": "...",
"prompt": "...",
"status": "generated"
}
]
}
"""
theme = input_data.get("theme", {})
screens = input_data.get("screens", ["home", "profile", "settings"])
app_context = input_data.get("app_context", {})
# Generate previews for each screen
previews = []
for screen in screens:
# Generate prompt for this screen
prompt = self._generate_screen_prompt(theme, screen, app_context)
# Generate image using Leonardo.ai
if self.leonardo_api_key:
image_result = self._generate_with_leonardo(prompt)
else:
# Fallback: return placeholder
image_result = {
"image_url": f"https://via.placeholder.com/768x1344/333333/FFFFFF?text={screen.upper()}+Screen",
"status": "placeholder",
"message": "Leonardo.ai API key not configured"
}
previews.append({
"screen": screen,
"image_url": image_result.get("image_url", ""),
"prompt": prompt,
"status": image_result.get("status", "generated"),
"generation_id": image_result.get("generation_id", ""),
"message": image_result.get("message", "")
})
return {
"previews": previews,
"theme_name": theme.get("name", "Unknown"),
"total_screens": len(previews)
}
def _generate_screen_prompt(
self,
theme: Dict[str, Any],
screen: str,
app_context: Dict[str, Any]
) -> str:
"""Generate detailed prompt for Leonardo.ai"""
# Extract theme details
theme_name = theme.get("name", "Modern")
theme_style = theme.get("style", "clean")
palette = theme.get("palette", {})
typography = theme.get("typography", {})
# Extract colors
primary_color = palette.get("primary", "#007AFF")
background_color = palette.get("background", "#FFFFFF")
text_color = palette.get("text", "#000000")
# Extract typography
display_font = typography.get("display", {}).get("font_family", "SF Pro Display")
body_font = typography.get("body", {}).get("font_family", "SF Pro Text")
# App description
app_description = app_context.get("description", "mobile application")
# Screen-specific content
screen_descriptions = {
"home": f"home screen with navigation bar, featured content cards, and bottom tab bar",
"profile": f"user profile screen with avatar, stats, settings button, and personal information",
"settings": f"settings screen with toggle switches, list items, and section headers",
"feed": f"feed screen with vertical scrolling cards, like buttons, and comments",
"search": f"search screen with search bar, filters, and grid results",
"detail": f"detail screen with large header image, title, description, and action buttons",
"cart": f"shopping cart screen with product list, quantity controls, and checkout button",
"chat": f"chat screen with message bubbles, text input, and timestamp",
"onboarding": f"onboarding screen with illustration, headline, description, and next button",
"login": f"login screen with email field, password field, and login button"
}
screen_content = screen_descriptions.get(
screen,
f"{screen} screen with relevant UI elements"
)
# Build comprehensive prompt
prompt = f"""Professional mobile app UI design mockup, {theme_style} style.
{app_description} - {screen_content}.
Design specifications:
- Color scheme: primary {primary_color}, background {background_color}, text {text_color}
- Typography: {display_font} for headers, {body_font} for body text
- Style: {theme_name} theme - {theme.get('mood', 'modern and clean')}
- Modern iOS/Android UI patterns
- Clean spacing and alignment
- Professional shadows and depth
High quality UI/UX design, Figma-style mockup, mobile app interface, clean and polished, modern design system, flat design with subtle depth, photorealistic rendering.
No text, no placeholder text, focus on visual design and layout."""
return prompt
def _generate_with_leonardo(self, prompt: str) -> Dict[str, Any]:
"""
Generate image using Leonardo.ai API
Returns:
{
"image_url": "https://...",
"generation_id": "...",
"status": "generated"
}
"""
if not self.leonardo_api_key:
return {
"image_url": "https://via.placeholder.com/768x1344",
"status": "error",
"message": "Leonardo.ai API key not configured"
}
headers = {
"Authorization": f"Bearer {self.leonardo_api_key}",
"Content-Type": "application/json"
}
# Request payload
payload = {
"prompt": prompt,
"modelId": self.model_id,
"width": 768,
"height": 1344,
"num_images": 1,
"guidance_scale": 7,
"num_inference_steps": 30,
"presetStyle": "PHOTOGRAPHY"
}
try:
# Create generation
with httpx.Client(timeout=60.0) as client:
response = client.post(
f"{self.leonardo_api_base}/generations",
headers=headers,
json=payload
)
if response.status_code != 200:
return {
"image_url": "https://via.placeholder.com/768x1344",
"status": "error",
"message": f"Leonardo.ai API error: {response.status_code}"
}
result = response.json()
generation_id = result.get("sdGenerationJob", {}).get("generationId", "")
if not generation_id:
return {
"image_url": "https://via.placeholder.com/768x1344",
"status": "error",
"message": "No generation ID returned"
}
# Poll for completion (max 60 seconds)
max_attempts = 30
for attempt in range(max_attempts):
time.sleep(2)
# Get generation status
status_response = client.get(
f"{self.leonardo_api_base}/generations/{generation_id}",
headers=headers
)
if status_response.status_code == 200:
status_data = status_response.json()
generation = status_data.get("generations_by_pk", {})
if generation.get("status") == "COMPLETE":
images = generation.get("generated_images", [])
if images:
image_url = images[0].get("url", "")
return {
"image_url": image_url,
"generation_id": generation_id,
"status": "generated"
}
# Timeout
return {
"image_url": "https://via.placeholder.com/768x1344",
"status": "timeout",
"message": "Generation timed out",
"generation_id": generation_id
}
except Exception as e:
return {
"image_url": "https://via.placeholder.com/768x1344",
"status": "error",
"message": f"Error: {str(e)}"
}
def _generate_with_dalle(self, prompt: str) -> Dict[str, Any]:
"""
Fallback: Generate with DALL-E if Leonardo.ai is not available
"""
# This would require OpenAI API key
# For now, return placeholder
return {
"image_url": "https://via.placeholder.com/768x1344",
"status": "not_implemented",
"message": "DALL-E fallback not yet implemented"
}