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": "",
"footer": "",
"styles": """
"""
},
"minimal": {
"header": "",
"footer": "",
"styles": """
"""
},
"creative": {
"header": "",
"footer": "",
"styles": """
"""
}
}
@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"",
"about": f"",
"services": f"",
"contact": f"",
"gallery": f""
}
return sections.get(section_type, f"")
def generate_navigation(self, pages: List[str]) -> str:
"""Generate navigation menu"""
nav_items = []
for page in pages:
nav_items.append(f"{page.title()}")
return f""
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"""
{site_name}
{tmpl['styles']}
{tmpl['header'].format(nav=nav, site_name=site_name)}
{''.join(generated_sections)}
{tmpl['footer'].format(footer_text=footer_text)}
"""
# 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
)