auto-light-app / app.py
AiCoderv2's picture
Update app.py
028baa1 verified
import gradio as gr
import time
import asyncio
from typing import Dict, List, Optional
import json
from functools import lru_cache
# Configuration
CONFIG = {
"max_concurrent_generations": 3,
"generation_timeout": 30,
"cache_size": 100,
"chunk_size": 1024
}
class OptimizedWebsiteGenerator:
def __init__(self):
self.generation_cache = {}
self.template_cache = {}
self._load_templates()
def _load_templates(self):
"""Load and cache templates once at startup"""
self.template_cache = {
"modern": {
"header": "<header class='modern-header'><nav>{nav}</nav></header>",
"footer": "<footer class='modern-footer'><p>{footer_text}</p></footer>",
"styles": """
<style>
.modern-header { background: #2c3e50; padding: 1rem; }
.modern-footer { background: #34495e; color: white; padding: 2rem; text-align: center; }
.content { max-width: 1200px; margin: 0 auto; padding: 2rem; }
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 0; }
</style>
"""
},
"minimal": {
"header": "<header>{nav}</header>",
"footer": "<footer><p>{footer_text}</p></footer>",
"styles": """
<style>
header, footer { padding: 1rem; border-bottom: 1px solid #eee; }
.content { max-width: 800px; margin: 0 auto; padding: 2rem; }
body { font-family: Arial, sans-serif; margin: 0; color: #333; }
</style>
"""
},
"creative": {
"header": "<header class='creative-header'><h1>{site_name}</h1></header>",
"footer": "<footer class='creative-footer'><div class='footer-content'>{footer_text}</div></footer>",
"styles": """
<style>
.creative-header { background: linear-gradient(45deg, #667eea 0%, #764ba2 100%); color: white; padding: 3rem; text-align: center; }
.creative-footer { background: #f8f9fa; padding: 2rem; }
.content { padding: 2rem; }
body { font-family: 'Georgia', serif; margin: 0; }
</style>
"""
}
}
@lru_cache(maxsize=CONFIG["cache_size"])
def generate_section(self, section_type: str, content: str, style_class: str = "") -> str:
"""Generate individual sections with caching"""
sections = {
"hero": f"<section class='hero {style_class}'><div class='hero-content'>{content}</div></section>",
"about": f"<section class='about {style_class}'><div class='about-content'>{content}</div></section>",
"services": f"<section class='services {style_class}'><div class='services-grid'>{content}</div></section>",
"contact": f"<section class='contact {style_class}'><div class='contact-form'>{content}</div></section>",
"gallery": f"<section class='gallery {style_class}'><div class='gallery-grid'>{content}</div></section>"
}
return sections.get(section_type, f"<section class='{style_class}'>{content}</section>")
def generate_navigation(self, pages: List[str]) -> str:
"""Generate navigation menu"""
nav_items = []
for page in pages:
nav_items.append(f"<a href='#{page.lower()}'>{page.title()}</a>")
return f"<nav>{' '.join(nav_items)}</nav>"
async def generate_website_async(self,
site_name: str,
template: str,
sections: Dict[str, str],
footer_text: str = "© 2024 Your Website") -> str:
"""Async website generation for better performance"""
# Check cache first
cache_key = f"{site_name}_{template}_{hash(str(sections))}"
if cache_key in self.generation_cache:
return self.generation_cache[cache_key]
# Get template
tmpl = self.template_cache.get(template, self.template_cache["modern"])
# Generate sections concurrently
section_tasks = []
for section_type, content in sections.items():
task = asyncio.create_task(
asyncio.get_event_loop().run_in_executor(
None, self.generate_section, section_type, content
)
)
section_tasks.append(task)
generated_sections = await asyncio.gather(*section_tasks)
# Build HTML
nav = self.generate_navigation(list(sections.keys()))
html = f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{site_name}</title>
{tmpl['styles']}
</head>
<body>
{tmpl['header'].format(nav=nav, site_name=site_name)}
<main class="content">
{''.join(generated_sections)}
</main>
{tmpl['footer'].format(footer_text=footer_text)}
</body>
</html>
"""
# Cache result
self.generation_cache[cache_key] = html
return html
# Initialize generator
generator = OptimizedWebsiteGenerator()
# Synchronous wrapper for Gradio
def generate_website(site_name: str,
template: str,
hero_content: str,
about_content: str,
services_content: str,
contact_content: str,
footer_text: str = "© 2024 Your Website") -> str:
"""Synchronous wrapper for async generation"""
# Create sections dictionary
sections = {}
if hero_content.strip():
sections["hero"] = hero_content
if about_content.strip():
sections["about"] = about_content
if services_content.strip():
sections["services"] = services_content
if contact_content.strip():
sections["contact"] = contact_content
# Run async generation
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
result = loop.run_until_complete(
generator.generate_website_async(
site_name, template, sections, footer_text
)
)
finally:
loop.close()
return result
# Progress tracking function
def generate_with_progress(site_name: str,
template: str,
hero_content: str,
about_content: str,
services_content: str,
contact_content: str,
footer_text: str,
progress=gr.Progress()):
"""Generate website with progress tracking"""
progress(0.1, desc="Initializing...")
time.sleep(0.1) # Simulate initialization
progress(0.3, desc="Processing sections...")
time.sleep(0.2) # Simulate processing
progress(0.6, desc="Generating HTML...")
result = generate_website(
site_name, template, hero_content, about_content,
services_content, contact_content, footer_text
)
progress(0.9, desc="Finalizing...")
time.sleep(0.1)
progress(1.0, desc="Complete!")
return result
# Create Gradio interface
def create_interface():
with gr.Blocks(title="Optimized Website Generator", theme=gr.themes.Soft()) as demo:
gr.Markdown("""
# 🚀 Optimized Website Generator
Generate professional websites instantly with our optimized engine.
**Built with [anycoder](https://huggingface.co/spaces/akhaliq/anycoder)**
""")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### 📝 Website Configuration")
site_name = gr.Textbox(
label="Site Name",
placeholder="My Awesome Website",
value="My Awesome Website"
)
template = gr.Dropdown(
choices=["modern", "minimal", "creative"],
label="Template Style",
value="modern"
)
footer_text = gr.Textbox(
label="Footer Text",
placeholder="© 2024 Your Website",
value="© 2024 Your Website"
)
gr.Markdown("### 📄 Content Sections")
hero_content = gr.Textbox(
label="Hero Section",
placeholder="Welcome to our website!",
lines=3,
value="Welcome to our amazing website! We create stunning digital experiences."
)
about_content = gr.Textbox(
label="About Section",
placeholder="Tell us about your business...",
lines=3,
value="We are a team of passionate professionals dedicated to excellence."
)
services_content = gr.Textbox(
label="Services Section",
placeholder="What services do you offer?",
lines=3,
value="• Web Design\n• Development\n• Consulting\n• Support"
)
contact_content = gr.Textbox(
label="Contact Section",
placeholder="Contact information...",
lines=3,
value="📧 contact@example.com\n📱 +1 234 567 890\n📍 123 Main St, City"
)
generate_btn = gr.Button(
"🚀 Generate Website",
variant="primary",
size="lg"
)
with gr.Column(scale=2):
gr.Markdown("### 🌐 Generated Website")
output_html = gr.HTML(
label="Website Preview",
container=True
)
# Download button for the HTML
download_btn = gr.DownloadButton(
label="📥 Download HTML",
variant="secondary"
)
# Stats display
with gr.Row():
generation_time = gr.Number(
label="Generation Time (seconds)",
value=0,
interactive=False
)
cache_hits = gr.Number(
label="Cache Hits",
value=0,
interactive=False
)
# Examples
gr.Examples(
examples=[
[
"Tech Startup",
"modern",
"Transform Your Business with AI",
"We build cutting-edge AI solutions for modern businesses.",
"• Machine Learning\n• Data Analytics\n• Cloud Solutions",
"📧 hello@techstartup.com\n📱 +1 555 0123",
"© 2024 Tech Startup Inc."
],
[
"Creative Agency",
"creative",
"Design That Inspires",
"We create beautiful designs that tell your story.",
"• Brand Design\n• Web Design\n• Marketing",
"📧 create@agency.com\n📱 +1 555 0456",
"© 2024 Creative Agency"
],
[
"Consulting Firm",
"minimal",
"Expert Business Solutions",
"Professional consulting services for growing companies.",
"• Strategy\n• Operations\n• Finance",
"📧 info@consulting.com\n📱 +1 555 0789",
"© 2024 Consulting Firm"
]
],
inputs=[site_name, template, hero_content, about_content, services_content, contact_content, footer_text]
)
# Event handlers
def generate_and_track(*args):
start_time = time.time()
result = generate_with_progress(*args[:-2]) # Exclude progress and stats
generation_time_value = round(time.time() - start_time, 2)
cache_hits_value = len(generator.generation_cache)
# Save to file for download
filename = f"website_{int(time.time())}.html"
with open(filename, "w", encoding="utf-8") as f:
f.write(result)
return result, filename, generation_time_value, cache_hits_value
generate_btn.click(
fn=generate_and_track,
inputs=[site_name, template, hero_content, about_content,
services_content, contact_content, footer_text],
outputs=[output_html, download_btn, generation_time, cache_hits]
)
# Clear cache button
def clear_cache():
generator.generation_cache.clear()
return 0
with gr.Row():
clear_cache_btn = gr.Button("🗑️ Clear Cache", variant="secondary", size="sm")
clear_cache_btn.click(
fn=clear_cache,
outputs=[cache_hits]
)
return demo
# Launch the application
if __name__ == "__main__":
demo = create_interface()
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=False,
show_error=True,
show_api=True
)