Spaces:
Sleeping
Sleeping
File size: 14,363 Bytes
f81cd3e 028baa1 | 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 | 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
) |