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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b5b26a
 
 
 
9795ecf
9b5b26a
 
 
 
 
 
 
 
 
 
 
8c01ffb
9795ecf
 
 
 
 
 
 
 
 
 
 
 
 
 
8c01ffb
6aae614
ae7a494
9795ecf
e121372
9795ecf
 
 
 
13d500a
8c01ffb
9795ecf
 
 
 
 
 
8c01ffb
9795ecf
861422e
 
9795ecf
 
 
 
 
 
 
 
 
 
 
 
 
8c01ffb
8fe992b
9795ecf
8c01ffb
 
 
 
9795ecf
 
861422e
8fe992b
 
9795ecf
8c01ffb
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
import datetime
import requests
import pytz
import yaml
import base64
import io
from PIL import Image
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI

# Enhanced design-to-code tool
@tool
def design_to_code_generator(design_prompt: str, image_path: str = None) -> str:
    """A tool that generates HTML, CSS, and JavaScript code based on a design description or image.
    
    Args:
        design_prompt: A detailed description of the desired web design/interface
        image_path: Optional path to an image file for visual reference
    """
    
    # Base HTML template with modern styling capabilities
    html_template = """<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{title}</title>
    <style>
        {css_content}
    </style>
</head>
<body>
    {html_content}
    <script>
        {js_content}
    </script>
</body>
</html>"""
    
    # Analyze the design prompt to determine components and styling
    components = analyze_design_prompt(design_prompt)
    
    # Generate CSS based on design requirements
    css_content = generate_css_from_prompt(design_prompt, components)
    
    # Generate HTML structure
    html_content = generate_html_structure(design_prompt, components)
    
    # Generate JavaScript for interactivity
    js_content = generate_javascript_features(design_prompt, components)
    
    # Determine page title from prompt
    title = extract_title_from_prompt(design_prompt)
    
    # Combine everything
    final_code = html_template.format(
        title=title,
        css_content=css_content,
        html_content=html_content,
        js_content=js_content
    )
    
    return f"Generated HTML/CSS/JS code:\n\n```html\n{final_code}\n```"

def analyze_design_prompt(prompt: str) -> dict:
    """Analyze the design prompt to identify components and features needed."""
    prompt_lower = prompt.lower()
    
    components = {
        'has_header': any(word in prompt_lower for word in ['header', 'navigation', 'nav', 'menu']),
        'has_hero': any(word in prompt_lower for word in ['hero', 'banner', 'main section', 'landing']),
        'has_cards': any(word in prompt_lower for word in ['card', 'cards', 'grid', 'boxes']),
        'has_form': any(word in prompt_lower for word in ['form', 'input', 'contact', 'signup', 'login']),
        'has_footer': any(word in prompt_lower for word in ['footer', 'bottom']),
        'has_sidebar': any(word in prompt_lower for word in ['sidebar', 'aside', 'side panel']),
        'has_gallery': any(word in prompt_lower for word in ['gallery', 'images', 'photos', 'portfolio']),
        'has_animation': any(word in prompt_lower for word in ['animate', 'animation', 'hover', 'interactive']),
        'color_scheme': extract_colors_from_prompt(prompt),
        'layout_type': determine_layout_type(prompt),
        'style_theme': determine_style_theme(prompt)
    }
    
    return components

def extract_colors_from_prompt(prompt: str) -> list:
    """Extract color preferences from the prompt."""
    colors = []
    color_words = ['blue', 'red', 'green', 'purple', 'orange', 'yellow', 'pink', 'black', 'white', 'gray', 'dark', 'light']
    
    for color in color_words:
        if color in prompt.lower():
            colors.append(color)
    
    return colors if colors else ['blue', 'white']  # Default colors

def determine_layout_type(prompt: str) -> str:
    """Determine the layout type based on the prompt."""
    prompt_lower = prompt.lower()
    
    if any(word in prompt_lower for word in ['dashboard', 'admin', 'panel']):
        return 'dashboard'
    elif any(word in prompt_lower for word in ['landing', 'homepage', 'marketing']):
        return 'landing'
    elif any(word in prompt_lower for word in ['blog', 'article', 'post']):
        return 'blog'
    elif any(word in prompt_lower for word in ['portfolio', 'gallery', 'showcase']):
        return 'portfolio'
    else:
        return 'general'

def determine_style_theme(prompt: str) -> str:
    """Determine the visual style theme."""
    prompt_lower = prompt.lower()
    
    if any(word in prompt_lower for word in ['modern', 'clean', 'minimal']):
        return 'modern'
    elif any(word in prompt_lower for word in ['dark', 'night', 'black']):
        return 'dark'
    elif any(word in prompt_lower for word in ['colorful', 'vibrant', 'bright']):
        return 'colorful'
    elif any(word in prompt_lower for word in ['professional', 'corporate', 'business']):
        return 'professional'
    else:
        return 'modern'

def generate_css_from_prompt(prompt: str, components: dict) -> str:
    """Generate CSS based on the design requirements."""
    
    # Base styles
    css = """
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Arial', sans-serif;
            line-height: 1.6;
            color: #333;
        }
    """
    
    # Add theme-specific styles
    if components['style_theme'] == 'dark':
        css += """
        body {
            background-color: #1a1a1a;
            color: #ffffff;
        }
        """
    elif components['style_theme'] == 'colorful':
        css += """
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #ffffff;
        }
        """
    
    # Add component-specific styles
    if components['has_header']:
        css += """
        .header {
            background-color: #2c3e50;
            color: white;
            padding: 1rem 0;
            position: sticky;
            top: 0;
            z-index: 100;
        }
        
        .nav {
            display: flex;
            justify-content: space-between;
            align-items: center;
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 2rem;
        }
        
        .nav ul {
            display: flex;
            list-style: none;
            gap: 2rem;
        }
        
        .nav a {
            color: white;
            text-decoration: none;
            transition: color 0.3s;
        }
        
        .nav a:hover {
            color: #3498db;
        }
        """
    
    if components['has_hero']:
        css += """
        .hero {
            background: linear-gradient(135deg, #3498db, #2c3e50);
            color: white;
            text-align: center;
            padding: 8rem 2rem;
        }
        
        .hero h1 {
            font-size: 3rem;
            margin-bottom: 1rem;
        }
        
        .hero p {
            font-size: 1.2rem;
            margin-bottom: 2rem;
        }
        
        .btn {
            display: inline-block;
            background-color: #e74c3c;
            color: white;
            padding: 1rem 2rem;
            text-decoration: none;
            border-radius: 5px;
            transition: background-color 0.3s;
        }
        
        .btn:hover {
            background-color: #c0392b;
        }
        """
    
    if components['has_cards']:
        css += """
        .cards-section {
            padding: 4rem 2rem;
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .cards-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 2rem;
            margin-top: 2rem;
        }
        
        .card {
            background: white;
            border-radius: 10px;
            padding: 2rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s, box-shadow 0.3s;
        }
        
        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 15px rgba(0, 0, 0, 0.2);
        }
        """
    
    if components['has_form']:
        css += """
        .form-section {
            padding: 4rem 2rem;
            background-color: #f8f9fa;
        }
        
        .form-container {
            max-width: 600px;
            margin: 0 auto;
            background: white;
            padding: 2rem;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: bold;
        }
        
        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 1rem;
        }
        
        .form-group input:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
        }
        """
    
    if components['has_footer']:
        css += """
        .footer {
            background-color: #2c3e50;
            color: white;
            text-align: center;
            padding: 2rem 0;
            margin-top: 4rem;
        }
        """
    
    # Add animations if requested
    if components['has_animation']:
        css += """
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .animate-on-scroll {
            animation: fadeInUp 0.6s ease-out;
        }
        """
    
    return css

def generate_html_structure(prompt: str, components: dict) -> str:
    """Generate HTML structure based on components."""
    
    html = ""
    
    # Header
    if components['has_header']:
        html += """
    <header class="header">
        <nav class="nav">
            <div class="logo">
                <h2>Your Brand</h2>
            </div>
            <ul>
                <li><a href="#home">Home</a></li>
                <li><a href="#about">About</a></li>
                <li><a href="#services">Services</a></li>
                <li><a href="#contact">Contact</a></li>
            </ul>
        </nav>
    </header>
        """
    
    # Hero section
    if components['has_hero']:
        html += """
    <section class="hero" id="home">
        <div class="hero-content">
            <h1>Welcome to Our Amazing Service</h1>
            <p>Transform your ideas into reality with our cutting-edge solutions</p>
            <a href="#contact" class="btn">Get Started</a>
        </div>
    </section>
        """
    
    # Cards section
    if components['has_cards']:
        html += """
    <section class="cards-section" id="services">
        <div class="container">
            <h2 style="text-align: center; margin-bottom: 2rem;">Our Services</h2>
            <div class="cards-grid">
                <div class="card">
                    <h3>Service One</h3>
                    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore.</p>
                </div>
                <div class="card">
                    <h3>Service Two</h3>
                    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore.</p>
                </div>
                <div class="card">
                    <h3>Service Three</h3>
                    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore.</p>
                </div>
            </div>
        </div>
    </section>
        """
    
    # Form section
    if components['has_form']:
        html += """
    <section class="form-section" id="contact">
        <div class="form-container">
            <h2 style="text-align: center; margin-bottom: 2rem;">Contact Us</h2>
            <form id="contactForm">
                <div class="form-group">
                    <label for="name">Name:</label>
                    <input type="text" id="name" name="name" required>
                </div>
                <div class="form-group">
                    <label for="email">Email:</label>
                    <input type="email" id="email" name="email" required>
                </div>
                <div class="form-group">
                    <label for="message">Message:</label>
                    <textarea id="message" name="message" rows="5" required></textarea>
                </div>
                <button type="submit" class="btn" style="width: 100%;">Send Message</button>
            </form>
        </div>
    </section>
        """
    
    # Footer
    if components['has_footer']:
        html += """
    <footer class="footer">
        <div class="container">
            <p>&copy; 2024 Your Company. All rights reserved.</p>
        </div>
    </footer>
        """
    
    return html

def generate_javascript_features(prompt: str, components: dict) -> str:
    """Generate JavaScript for interactivity."""
    
    js = """
        // Smooth scrolling for navigation links
        document.addEventListener('DOMContentLoaded', function() {
            const links = document.querySelectorAll('a[href^="#"]');
            
            links.forEach(link => {
                link.addEventListener('click', function(e) {
                    e.preventDefault();
                    const target = document.querySelector(this.getAttribute('href'));
                    if (target) {
                        target.scrollIntoView({
                            behavior: 'smooth',
                            block: 'start'
                        });
                    }
                });
            });
    """
    
    # Add form handling if form exists
    if components['has_form']:
        js += """
            // Form submission handling
            const contactForm = document.getElementById('contactForm');
            if (contactForm) {
                contactForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    
                    // Get form data
                    const formData = new FormData(this);
                    const name = formData.get('name');
                    const email = formData.get('email');
                    const message = formData.get('message');
                    
                    // Simple validation
                    if (name && email && message) {
                        alert('Thank you for your message! We will get back to you soon.');
                        this.reset();
                    } else {
                        alert('Please fill in all fields.');
                    }
                });
            }
        """
    
    # Add scroll animations if requested
    if components['has_animation']:
        js += """
            // Scroll animations
            const observerOptions = {
                threshold: 0.1,
                rootMargin: '0px 0px -50px 0px'
            };
            
            const observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        entry.target.classList.add('animate-on-scroll');
                    }
                });
            }, observerOptions);
            
            // Observe cards and other elements
            const animatedElements = document.querySelectorAll('.card, .hero-content');
            animatedElements.forEach(el => observer.observe(el));
        """
    
    js += """
        });
    """
    
    return js

def extract_title_from_prompt(prompt: str) -> str:
    """Extract a suitable title from the design prompt."""
    prompt_lower = prompt.lower()
    
    if 'dashboard' in prompt_lower:
        return 'Dashboard'
    elif 'portfolio' in prompt_lower:
        return 'Portfolio'
    elif 'landing' in prompt_lower or 'homepage' in prompt_lower:
        return 'Welcome'
    elif 'blog' in prompt_lower:
        return 'Blog'
    elif 'contact' in prompt_lower:
        return 'Contact Us'
    else:
        return 'My Website'

@tool
def get_current_time_in_timezone(timezone: str) -> str:
    """A tool that fetches the current local time in a specified timezone.
    
    Args:
        timezone: A string representing a valid timezone (e.g., 'America/New_York').
    """
    try:
        # Create timezone object
        tz = pytz.timezone(timezone)
        # Get current time in that timezone
        local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
        return f"The current local time in {timezone} is: {local_time}"
    except Exception as e:
        return f"Error fetching time for timezone '{timezone}': {str(e)}"

@tool
def image_analyzer_for_design(image_path: str, analysis_type: str = "design") -> str:
    """Analyze an uploaded image to extract design elements and generate code suggestions.
    
    Args:
        image_path: Path to the image file
        analysis_type: Type of analysis to perform ('design', 'layout', 'colors')
    """
    try:
        # This is a placeholder for image analysis
        # In a real implementation, you would use computer vision or AI models
        return f"Image analysis for {image_path}: Detected modern layout with clean design elements. Suggested color scheme: blue and white. Layout appears to be a landing page with header, hero section, and cards."
    except Exception as e:
        return f"Error analyzing image: {str(e)}"

final_answer = FinalAnswerTool()

# Model configuration
model = HfApiModel(
    max_tokens=2096,
    temperature=0.5,
    model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
    custom_role_conversions=None,
)

# Load additional tools
try:
    image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
except:
    print("Image generation tool not available")
    image_generation_tool = None

# Load prompts
with open("prompts.yaml", 'r') as stream:
    prompt_templates = yaml.safe_load(stream)

# Create agent with enhanced tools
tools = [
    final_answer,
    design_to_code_generator,
    get_current_time_in_timezone,
    image_analyzer_for_design,
]

# Add image generation tool if available
if image_generation_tool:
    tools.append(image_generation_tool)

agent = CodeAgent(
    model=model,
    tools=tools,
    max_steps=6,
    verbosity_level=1,
    grammar=None,
    planning_interval=None,
    name="Design-to-Code Agent",
    description="An AI agent that converts design descriptions and images into functional HTML, CSS, and JavaScript code.",
    prompt_templates=prompt_templates
)

# Launch the Gradio interface
GradioUI(agent).launch()