File size: 10,038 Bytes
42f73ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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"
        }