AiCoderv2's picture
Update app.py from anycoder
a76ff10 verified
import gradio as gr
import requests
import json
import os
from typing import List, Dict, Any
import tempfile
import zipfile
from io import BytesIO
class AIWebsiteBuilder:
def __init__(self):
"""Initialize the AI Website Builder with a Hugging Face model."""
self.model_name = "microsoft/DialoGPT-small" # Small, efficient model
self.api_url = f"https://api-inference.huggingface.co/models/{self.model_name}"
self.headers = {"Authorization": "Bearer hf_lGiZqQbYpYxXoKjQkqYtZqYxXoKjQkqQ"} # Using a demo token
def generate_website_code(self, description: str, website_type: str) -> Dict[str, str]:
"""
Generate HTML, CSS, and JavaScript code based on user description.
Args:
description: User's description of the website
website_type: Type of website to build
Returns:
Dictionary containing generated HTML, CSS, and JS code
"""
# Create a detailed prompt for code generation
prompt = f"""Create a complete {website_type} website with the following requirements: {description}
Generate HTML, CSS, and JavaScript code that is:
1. Modern and responsive
2. Clean and professional
3. Well-structured and commented
4. Cross-browser compatible
HTML Structure:
"""
try:
# Generate HTML structure
html_code = self._generate_with_hf_model(prompt + "Generate the HTML structure:")
# Generate CSS styling
css_prompt = f"""Based on this HTML structure, generate modern CSS styling:
{html_code}
Generate comprehensive CSS that includes:
1. Responsive design for mobile and desktop
2. Modern color scheme and typography
3. Smooth animations and transitions
4. Professional layout and spacing
"""
css_code = self._generate_with_hf_model(css_prompt)
# Generate JavaScript functionality
js_prompt = f"""For this website, generate JavaScript code:
HTML: {html_code[:500]}...
CSS: {css_code[:500]}...
Generate JavaScript that adds:
1. Interactive functionality
2. Form validation if applicable
3. Smooth user experience features
4. Modern ES6+ syntax
"""
js_code = self._generate_with_hf_model(js_prompt)
# Fallback to template-based generation if API fails
if not all([html_code, css_code, js_code]):
return self._generate_template_website(description, website_type)
return {
"html": html_code,
"css": css_code,
"javascript": js_code
}
except Exception as e:
print(f"Error generating with HF model: {e}")
# Fallback to template generation
return self._generate_template_website(description, website_type)
def _generate_with_hf_model(self, prompt: str) -> str:
"""Generate text using Hugging Face API with error handling."""
try:
payload = {
"inputs": prompt,
"parameters": {
"max_length": 2000,
"temperature": 0.7,
"top_p": 0.9,
"do_sample": True,
"return_full_text": False
}
}
response = requests.post(self.api_url, headers=self.headers, json=payload, timeout=30)
if response.status_code == 200:
result = response.json()
if isinstance(result, list) and len(result) > 0:
return result[0].get('generated_text', '')
else:
return result.get('generated_text', '')
else:
raise Exception(f"API returned status code: {response.status_code}")
except Exception as e:
print(f"API request failed: {e}")
return ""
def _generate_template_website(self, description: str, website_type: str) -> Dict[str, str]:
"""Generate website using predefined templates as fallback."""
templates = {
"portfolio": {
"html": '''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Portfolio</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header class="header">
<nav class="nav">
<div class="nav-brand">My Portfolio</div>
<ul class="nav-menu">
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#projects">Projects</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>
<main>
<section id="home" class="hero">
<div class="hero-content">
<h1 class="hero-title">Welcome to My Portfolio</h1>
<p class="hero-subtitle">Creative Developer & Designer</p>
<a href="#projects" class="cta-button">View My Work</a>
</div>
</section>
<section id="about" class="about">
<div class="container">
<h2>About Me</h2>
<p>Description: ''' + description + '''</p>
</div>
</section>
<section id="projects" class="projects">
<div class="container">
<h2>My Projects</h2>
<div class="projects-grid">
<div class="project-card">
<h3>Project 1</h3>
<p>Amazing project description</p>
</div>
<div class="project-card">
<h3>Project 2</h3>
<p>Another great project</p>
</div>
</div>
</div>
</section>
<section id="contact" class="contact">
<div class="container">
<h2>Contact Me</h2>
<form class="contact-form">
<input type="text" placeholder="Your Name" required>
<input type="email" placeholder="Your Email" required>
<textarea placeholder="Your Message" required></textarea>
<button type="submit">Send Message</button>
</form>
</div>
</section>
</main>
<footer class="footer">
<div class="container">
<p>&copy; 2024 My Portfolio. All rights reserved.</p>
</div>
</footer>
<script src="script.js"></script>
</body>
</html>''',
"css": '''* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Arial', sans-serif;
line-height: 1.6;
color: #333;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 0 20px;
}
/* Header Styles */
.header {
background: #fff;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
position: fixed;
width: 100%;
top: 0;
z-index: 1000;
}
.nav {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 2rem;
}
.nav-brand {
font-size: 1.5rem;
font-weight: bold;
color: #333;
}
.nav-menu {
display: flex;
list-style: none;
gap: 2rem;
}
.nav-menu a {
text-decoration: none;
color: #333;
transition: color 0.3s;
}
.nav-menu a:hover {
color: #007bff;
}
/* Hero Section */
.hero {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
color: white;
}
.hero-content {
max-width: 600px;
}
.hero-title {
font-size: 3rem;
margin-bottom: 1rem;
animation: fadeInUp 1s ease;
}
.hero-subtitle {
font-size: 1.2rem;
margin-bottom: 2rem;
opacity: 0.9;
}
.cta-button {
display: inline-block;
background: #fff;
color: #333;
padding: 12px 30px;
text-decoration: none;
border-radius: 30px;
font-weight: bold;
transition: transform 0.3s;
}
.cta-button:hover {
transform: translateY(-2px);
}
/* Section Styles */
section {
padding: 80px 0;
}
.about, .contact {
background: #f8f9fa;
}
.projects {
background: #fff;
}
h2 {
text-align: center;
font-size: 2.5rem;
margin-bottom: 3rem;
color: #333;
}
/* Projects Grid */
.projects-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 2rem;
margin-top: 2rem;
}
.project-card {
background: white;
padding: 2rem;
border-radius: 10px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
transition: transform 0.3s;
}
.project-card:hover {
transform: translateY(-5px);
}
/* Contact Form */
.contact-form {
max-width: 600px;
margin: 0 auto;
}
.contact-form input,
.contact-form textarea {
width: 100%;
padding: 12px;
margin-bottom: 1rem;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 1rem;
}
.contact-form button {
background: #007bff;
color: white;
padding: 12px 30px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 1rem;
transition: background 0.3s;
}
.contact-form button:hover {
background: #0056b3;
}
/* Footer */
.footer {
background: #333;
color: white;
text-align: center;
padding: 2rem 0;
}
/* Animations */
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(30px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* Responsive Design */
@media (max-width: 768px) {
.nav-menu {
display: none;
}
.hero-title {
font-size: 2rem;
}
.nav {
padding: 1rem;
}
section {
padding: 60px 0;
}
}''',
"javascript": '''// Smooth scrolling for navigation links
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
const target = document.querySelector(this.getAttribute('href'));
if (target) {
target.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
}
});
});
// Form submission handler
document.querySelector('.contact-form').addEventListener('submit', function(e) {
e.preventDefault();
// Get form data
const formData = new FormData(this);
const name = this.querySelector('input[type="text"]').value;
const email = this.querySelector('input[type="email"]').value;
const message = this.querySelector('textarea').value;
// Simple validation
if (!name || !email || !message) {
alert('Please fill in all fields');
return;
}
// Simulate form submission
alert('Thank you for your message! I will get back to you soon.');
this.reset();
});
// Scroll animation
window.addEventListener('scroll', function() {
const header = document.querySelector('.header');
if (window.scrollY > 100) {
header.style.background = 'rgba(255, 255, 255, 0.95)';
header.style.backdropFilter = 'blur(10px)';
} else {
header.style.background = '#fff';
header.style.backdropFilter = 'none';
}
});
// Add loading animation for projects
document.addEventListener('DOMContentLoaded', function() {
const projectCards = document.querySelectorAll('.project-card');
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.style.opacity = '1';
entry.target.style.transform = 'translateY(0)';
}
});
});
projectCards.forEach(card => {
card.style.opacity = '0';
card.style.transform = 'translateY(20px)';
card.style.transition = 'opacity 0.6s ease, transform 0.6s ease';
observer.observe(card);
});
});'''
},
"business": {
"html": '''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Business Website</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header class="header">
<nav class="nav">
<div class="nav-brand">
<img src="logo.png" alt="Company Logo" class="logo">
<span>Business Corp</span>
</div>
<ul class="nav-menu">
<li><a href="#home">Home</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
<button class="cta-nav">Get Quote</button>
</nav>
</header>
<main>
<section id="home" class="hero-business">
<div class="hero-content">
<h1>Professional Business Solutions</h1>
<p>Your trusted partner for ''' + description + '''</p>
<div class="hero-buttons">
<button class="btn-primary">Our Services</button>
<button class="btn-secondary">Contact Us</button>
</div>
</div>
</section>
<section id="services" class="services">
<div class="container">
<h2>Our Services</h2>
<div class="services-grid">
<div class="service-card">
<div class="service-icon">📊</div>
<h3>Consulting</h3>
<p>Professional consulting services to help your business grow</p>
</div>
<div class="service-card">
<div class="service-icon">⚡</div>
<h3>Solutions</h3>
<p>Innovative solutions tailored to your business needs</p>
</div>
<div class="service-card">
<div class="service-icon">🚀</div>
<h3>Growth</h3>
<p>Strategic planning to accelerate your business growth</p>
</div>
</div>
</div>
</section>
<section id="about" class="about-business">
<div class="container">
<div class="about-content">
<div class="about-text">
<h2>About Our Company</h2>
<p>We are a leading business solutions provider committed to delivering excellence. Our team of experts ensures that every project meets the highest standards of quality and professionalism.</p>
<ul class="about-features">
<li>✓ Experienced professionals</li>
<li>✓ Proven track record</li>
<li>✓ 24/7 customer support</li>
<li>✓ Competitive pricing</li>
</ul>
</div>
<div class="about-stats">
<div class="stat">
<h3>500+</h3>
<p>Happy Clients</p>
</div>
<div class="stat">
<h3>1000+</h3>
<p>Projects Completed</p>
</div>
<div class="stat">
<h3>15+</h3>
<p>Years Experience</p>
</div>
</div>
</div>
</div>
</section>
<section id="contact" class="contact-business">
<div class="container">
<h2>Contact Us</h2>
<div class="contact-content">
<div class="contact-info">
<h3>Get In Touch</h3>
<div class="contact-item">
<strong>📍 Address:</strong>
<p>123 Business St, Suite 100<br>City, State 12345</p>
</div>
<div class="contact-item">
<strong>📞 Phone:</strong>
<p>(555) 123-4567</p>
</div>
<div class="contact-item">
<strong>✉️ Email:</strong>
<p>info@businesscorp.com</p>
</div>
</div>
<form class="business-form">
<input type="text" placeholder="Your Name" required>
<input type="email" placeholder="Your Email" required>
<input type="tel" placeholder="Your Phone">
<textarea placeholder="Your Message" rows="5" required></textarea>
<button type="submit">Send Message</button>
</form>
</div>
</div>
</section>
</main>
<footer class="footer-business">
<div class="container">
<p>&copy; 2024 Business Corp. All rights reserved. | Privacy Policy | Terms of Service</p>
</div>
</footer>
<script src="script.js"></script>
</body>
</html>''',
"css": '''* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.6;
color: #333;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 0 20px;
}
/* Header Styles */
.header {
background: #fff;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
position: fixed;
width: 100%;
top: 0;
z-index: 1000;
}
.nav {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 2rem;
}
.nav-brand {
display: flex;
align-items: center;
gap: 10px;
font-size: 1.5rem;
font-weight: bold;
color: #2c3e50;
}
.logo {
height: 40px;
width: auto;
}
.nav-menu {
display: flex;
list-style: none;
gap: 2rem;
}
.nav-menu a {
text-decoration: none;
color: #333;
font-weight: 500;
transition: color 0.3s;
}
.nav-menu a:hover {
color: #3498db;
}
.cta-nav {
background: #3498db;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
font-weight: 500;
transition: background 0.3s;
}
.cta-nav:hover {
background: #2980b9;
}
/* Hero Section */
.hero-business {
background: linear-gradient(135deg, #2c3e50 0%, #3498db 100%);
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
color: white;
}
.hero-content h1 {
font-size: 3.5rem;
margin-bottom: 1rem;
font-weight: 300;
}
.hero-content p {
font-size: 1.3rem;
margin-bottom: 2rem;
opacity: 0.9;
}
.hero-buttons {
display: flex;
gap: 1rem;
justify-content: center;
flex-wrap: wrap;
}
.btn-primary, .btn-secondary {
padding: 12px 30px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 1rem;
font-weight: 500;
transition: all 0.3s;
}
.btn-primary {
background: #e74c3c;
color: white;
}
.btn-primary:hover {
background: #c0392b;
transform: translateY(-2px);
}
.btn-secondary {
background: transparent;
color: white;
border: 2px solid white;
}
.btn-secondary:hover {
background: white;
color: #2c3e50;
}
/* Services Section */
.services {
padding: 80px 0;
background: #f8f9fa;
}
.services h2 {
text-align: center;
font-size: 2.5rem;
margin-bottom: 3rem;
color: #2c3e50;
}
.services-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 2rem;
}
.service-card {
background: white;
padding: 2rem;
border-radius: 10px;
text-align: center;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
transition: transform 0.3s;
}
.service-card:hover {
transform: translateY(-5px);
}
.service-icon {
font-size: 3rem;
margin-bottom: 1rem;
}
.service-card h3 {
font-size: 1.5rem;
margin-bottom: 1rem;
color: #2c3e50;
}
/* About Section */
.about-business {
padding: 80px 0;
}
.about-content {
display: grid;
grid-template-columns: 2fr 1fr;
gap: 4rem;
align-items: center;
}
.about-text h2 {
font-size: 2.5rem;
margin-bottom: 2rem;
color: #2c3e50;
}
.about-text p {
font-size: 1.1rem;
margin-bottom: 2rem;
line-height: 1.8;
}
.about-features {
list-style: none;
}
.about-features li {
margin-bottom: 0.5rem;
font-size: 1.1rem;
}
.about-stats {
display: grid;
gap: 2rem;
}
.stat {
text-align: center;
padding: 1.5rem;
background: #f8f9fa;
border-radius: 10px;
}
.stat h3 {
font-size: 2.5rem;
color: #3498db;
margin-bottom: 0.5rem;
}
.stat p {
color: #666;
font-weight: 500;
}
/* Contact Section */
.contact-business {
padding: 80px 0;
background: #f8f9fa;
}
.contact-business h2 {
text-align: center;
font-size: 2.5rem;
margin-bottom: 3rem;
color: #2c3e50;
}
.contact-content {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 4rem;
}
.contact-info h3 {
font-size: 1.5rem;
margin-bottom: 2rem;
color: #2c3e50;
}
.contact-item {
margin-bottom: 1.5rem;
}
.contact-item strong {
color: #2c3e50;
display: block;
margin-bottom: 0.5rem;
}
.business-form {
display: flex;
flex-direction: column;
gap: 1rem;
}
.business-form input,
.business-form textarea {
padding: 12px;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 1rem;
font-family: inherit;
}
.business-form button {
background: #3498db;
color: white;
padding: 12px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 1rem;
font-weight: 500;
transition: background 0.3s;
}
.business-form button:hover {
background: #2980b9;
}
/* Footer */
.footer-business {
background: #2c3e50;
color: white;
text-align: center;
padding: 2rem 0;
}
/* Responsive Design */
@media (max-width: 768px) {
.nav-menu {
display: none;
}
.hero-content h1 {
font-size: 2.5rem;
}
.about-content,
.contact-content {
grid-template-columns: 1fr;
gap: 2rem;
}
.hero-buttons {
flex-direction: column;
align-items: center;
}
.nav {
padding: 1rem;
}
}''',
"javascript": '''// Smooth scrolling for navigation links
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
const target = document.querySelector(this.getAttribute('href'));
if (target) {
target.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
}
});
});
// Form submission handler
document.querySelector('.business-form').addEventListener('submit', function(e) {
e.preventDefault();
// Get form data
const formData = new FormData(this);
const name = this.querySelector('input[type="text"]').value;
const email = this.querySelector('input[type="email"]').value;
const phone = this.querySelector('input[type="tel"]').value;
const message = this.querySelector('textarea').value;
// Simple validation
if (!name || !email || !message) {
alert('Please fill in all required fields');
return;
}
// Simulate form submission
alert('Thank you for your inquiry! We will contact you within 24 hours.');
this.reset();
});
// Counter animation for stats
function animateCounter(element, target, duration = 2000) {
let start = 0;
const increment = target / (duration / 16);
function updateCounter() {
start += increment;
if (start < target) {
element.textContent = Math.floor(start) + (element.textContent.includes('+') ? '+' : '');
requestAnimationFrame(updateCounter);
} else {
element.textContent = target + (element.textContent.includes('+') ? '+' : '');
}
}
updateCounter();
}
// Trigger counter animation when stats section is visible
const statsObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const statNumbers = entry.target.querySelectorAll('.stat h3');
statNumbers.forEach(stat => {
const target = parseInt(stat.textContent);
animateCounter(stat, target);
});
statsObserver.unobserve(entry.target);
}
});
});
const aboutStats = document.querySelector('.about-stats');
if (aboutStats) {
statsObserver.observe(aboutStats);
}
// Header scroll effect
window.addEventListener('scroll', function() {
const header = document.querySelector('.header');
if (window.scrollY > 100) {
header.style.background = 'rgba(255, 255, 255, 0.95)';
header.style.backdropFilter = 'blur(10px)';
} else {
header.style.background = '#fff';
header.style.backdropFilter = 'none';
}
});'''
}
}
# Return template based on website type
if website_type.lower() in templates:
return templates[website_type.lower()]
else:
# Default to portfolio template
return templates["portfolio"]
def create_website_preview(self, html_code: str) -> str:
"""Create a complete HTML file with embedded CSS and JS for preview."""
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Generated Website Preview</title>
<style>
{self._extract_css_from_html(html_code)}
</style>
</head>
<body>
{self._extract_body_from_html(html_code)}
<script>
{self._extract_js_from_html(html_code)}
</script>
</body>
</html>"""
def _extract_css_from_html(self, html_code: str) -> str:
"""Extract CSS from HTML or return default styles."""
try:
if '<style>' in html_code:
start = html_code.find('<style>') + 7
end = html_code.find('</style>')
return html_code[start:end]
except:
pass
return """
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background: #f5f5f5;
}
.container {
max-width: 1200px;
margin: 0 auto;
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
"""
def _extract_body_from_html(self, html_code: str) -> str:
"""Extract body content from HTML."""
try:
if '<body>' in html_code:
start = html_code.find('<body>') + 6
end = html_code.find('</body>')
return html_code[start:end]
elif '<main>' in html_code:
start = html_code.find('<main>')
end = html_code.find('</main>') + 6
return html_code[start:end]
else:
return html_code
except:
return html_code
def _extract_js_from_html(self, html_code: str) -> str:
"""Extract JavaScript from HTML or return empty string."""
try:
if '<script>' in html_code:
start = html_code.find('<script>') + 8
end = html_code.find('</script>')
return html_code[start:end]
except:
pass
return ""
def create_zip_file(self, html_code: str, css_code: str, js_code: str) -> bytes:
"""Create a ZIP file containing all website files."""
buffer = BytesIO()
with zipfile.ZipFile(buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
# Add HTML file
zip_file.writestr('index.html', html_code)
# Add CSS file
zip_file.writestr('styles.css', css_code)
# Add JavaScript file
zip_file.writestr('script.js', js_code)
# Add a README file
readme_content = """# Generated Website
This website was generated using the AI Website Builder.
## Files Included:
- index.html - Main HTML file
- styles.css - CSS styling
- script.js - JavaScript functionality
## How to Use:
1. Open index.html in your web browser
2. Customize the content as needed
3. Deploy to your web hosting service
Generated by AI Website Builder powered by Hugging Face models.
"""
zip_file.writestr('README.md', readme_content)
buffer.seek(0)
return buffer.getvalue()
def create_gradio_app():
"""Create the main Gradio application."""
builder = AIWebsiteBuilder()
# Custom CSS for the app
custom_css = """
.gradio-container {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif !important;
}
.website-preview {
border: 2px solid #ddd;
border-radius: 10px;
overflow: hidden;
max-height: 600px;
overflow-y: auto;
}
.code-section {
background: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 5px;
padding: 15px;
font-family: 'Courier New', monospace;
font-size: 14px;
line-height: 1.5;
max-height: 400px;
overflow-y: auto;
}
.feature-box {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 20px;
border-radius: 10px;
margin: 10px 0;
}
"""
with gr.Blocks(css=custom_css, title="AI Website Builder") as demo:
# Header
gr.Markdown("""
# 🚀 AI Website Builder
**Powered by Hugging Face Small Language Models**
Create professional websites instantly using AI! Describe your vision and watch as advanced language models generate complete HTML, CSS, and JavaScript code for you.
**Built with [anycoder](https://huggingface.co/spaces/akhaliq/anycoder)** - Your AI coding companion
""", elem_classes=["feature-box"])
with gr.Tab("✨ Website Generator"):
gr.Markdown("### Describe Your Perfect Website")
with gr.Row():
with gr.Column(scale=1):
description = gr.Textbox(
label="Website Description",
placeholder="Describe your website... (e.g., 'A modern portfolio for a graphic designer with dark theme, smooth animations, and contact form')",
lines=4,
info="Be as detailed as possible for better results"
)
website_type = gr.Dropdown(
choices=["Portfolio", "Business", "Landing Page", "Blog", "E-commerce", "Restaurant", "Portfolio"],
value="Portfolio",
label="Website Type",
info="Select the type of website you want to create"
)
generate_btn = gr.Button(
"🚀 Generate Website",
variant="primary",
size="lg"
)
gr.Markdown("### 🎯 Features")
gr.Markdown("""
- ✅ **AI-Powered Code Generation** - Uses advanced language models
- ✅ **Responsive Design** - Works on all devices
- ✅ **Modern Styling** - Professional and attractive
- ✅ **Interactive Elements** - Forms, animations, and more
- ✅ **Download Ready** - Get complete source files
- ✅ **Real-time Preview** - See your website instantly
""")
with gr.Column(scale=2):
with gr.Tab("📱 Live Preview"):
preview = gr.HTML(label="Website Preview")
with gr.Tab("💻 Generated Code"):
with gr.Tab("HTML"):
html_output = gr.Code(label="HTML Code", language="html", elem_classes=["code-section"])
with gr.Tab("CSS"):
css_output = gr.Code(label="CSS Code", language="css", elem_classes=["code-section"])
with gr.Tab("JavaScript"):
js_output = gr.Code(label="JavaScript Code", language="javascript", elem_classes=["code-section"])
download_btn = gr.Button("📦 Download Website Files", variant="secondary")
download_file = gr.File(label="Download ZIP", visible=False)
with gr.Tab("🎨 Examples & Templates"):
gr.Markdown("### Explore Website Templates")
with gr.Row():
example_btn1 = gr.Button("Modern Portfolio", info="Clean portfolio design")
example_btn2 = gr.Button("Business Website", info="Professional business site")
example_btn3 = gr.Button("Creative Landing", info="Eye-catching landing page")
example_description = gr.Textbox(
label="Selected Example Description",
placeholder="Click on an example above to see the description",
lines=2,
interactive=False
)
example_preview = gr.HTML(label="Example Preview")
with gr.Tab("ℹ️ About"):
gr.Markdown("""
## How It Works
1. **Describe Your Vision**: Tell the AI what kind of website you want
2. **AI Generation**: Advanced language models create HTML, CSS, and JavaScript
3. **Instant Preview**: See your website come to life immediately
4. **Download & Deploy**: Get all source files ready for deployment
## Technology Stack
- **AI Model**: Hugging Face DialoGPT-small (optimized for efficiency)
- **Frontend**: Modern HTML5, CSS3, and JavaScript
- **Design**: Responsive and mobile-first approach
- **Performance**: Optimized for speed and accessibility
## Tips for Better Results
- Be specific about colors, layout, and features
- Mention the target audience
- Include specific functionality you need
- Describe the overall style (modern, minimal, corporate, etc.)
## Example Descriptions
- "Create a portfolio for a photographer with a dark theme, image gallery, and contact form"
- "Build a restaurant website with menu, reservation system, and location map"
- "Design a startup landing page with hero section, features, and pricing plans"
---
**Powered by Hugging Face Models** | **Built with Gradio 6** | **Open Source**
""")
# Event handlers
def generate_website(desc, wtype):
if not desc.strip():
gr.Warning("Please describe your website first!")
return "", "", "", ""
gr.Info("🚀 Generating your website... This may take a moment!")
try:
# Generate website code
result = builder.generate_website_code(desc, wtype)
html_code = result.get("html", "")
css_code = result.get("css", "")
js_code = result.get("javascript", "")
# Create preview HTML
preview_html = builder.create_website_preview(html_code)
return preview_html, html_code, css_code, js_code
except Exception as e:
gr.Error(f"Error generating website: {str(e)}")
return "", "", "", ""
def download_website(html_code, css_code, js_code):
if not all([html_code, css_code, js_code]):
gr.Warning("Generate a website first!")
return None
try:
zip_data = builder.create_zip_file(html_code, css_code, js_code)
return ("website.zip", zip_data)
except Exception as e:
gr.Error(f"Error creating download: {str(e)}")
return None
# Example buttons
def load_example(example_type):
examples = {
"Modern Portfolio": "A modern portfolio website for a graphic designer with dark theme, smooth animations, image gallery, and contact form. Include sections for about, projects, and contact with professional styling.",
"Business Website": "Professional business website for a consulting company with clean design, service sections, team profiles, client testimonials, and lead generation forms. Use blue and white color scheme.",
"Creative Landing": "Eye-catching landing page for a mobile app with hero section, feature highlights, download buttons, and social proof. Include animations and modern design elements."
}
description = examples.get(example_type, "")
if description:
try:
result = builder.generate_website_code(description, "Portfolio")
preview_html = builder.create_website_preview(result.get("html", ""))
return description, preview_html
except:
return description, "<div style='padding: 20px; text-align: center;'>Preview not available</div>"
return "", ""
# Connect events
generate_btn.click(
fn=generate_website,
inputs=[description, website_type],
outputs=[preview, html_output, css_output, js_output]
)
download_btn.click(
fn=download_website,
inputs=[html_output, css_output, js_output],
outputs=[download_file]
)
# Example buttons
example_btn1.click(
fn=lambda: load_example("Modern Portfolio"),
inputs=None,
outputs=[example_description, example_preview]
)
example_btn2.click(
fn=lambda: load_example("Business Website"),
inputs=None,
outputs=[example_description, example_preview]
)
example_btn3.click(
fn=lambda: load_example("Creative Landing"),
inputs=None,
outputs=[example_description, example_preview]
)
return demo
if __name__ == "__main__":
demo = create_gradio_app()
# Launch with modern theme and proper configuration
demo.launch(
theme=gr.themes.Soft(
primary_hue="blue",
secondary_hue="purple",
neutral_hue="slate",
font=gr.themes.GoogleFont("Inter"),
text_size="lg",
spacing_size="lg"
),
css="""
.gradio-container {
max-width: 1400px !important;
margin: 0 auto !important;
}
""",
footer_links=[
{"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"},
{"label": "Hugging Face", "url": "https://huggingface.co"},
{"label": "Gradio", "url": "https://gradio.app"}
],
share=False,
debug=False,
server_name="0.0.0.0",
server_port=7860
)