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": '''
Professional consulting services to help your business grow
âĄ
Solutions
Innovative solutions tailored to your business needs
đ
Growth
Strategic planning to accelerate your business growth
About Our Company
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.
â Experienced professionals
â Proven track record
â 24/7 customer support
â Competitive pricing
500+
Happy Clients
1000+
Projects Completed
15+
Years Experience
Contact Us
Get In Touch
đ Address:
123 Business St, Suite 100 City, State 12345
đ Phone:
(555) 123-4567
âī¸ Email:
info@businesscorp.com
''',
"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"""
Generated Website Preview
{self._extract_body_from_html(html_code)}
"""
def _extract_css_from_html(self, html_code: str) -> str:
"""Extract CSS from HTML or return default styles."""
try:
if '')
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 '' in html_code:
start = html_code.find('') + 6
end = html_code.find('')
return html_code[start:end]
elif '' in html_code:
start = html_code.find('')
end = html_code.find('') + 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 '')
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, "