Spaces:
Running
Running
| # app.py β Sovereign UI Architect (FULL Premium Edition - 262 lines) | |
| import os | |
| import json | |
| import re | |
| import time | |
| import logging | |
| import asyncio | |
| import uuid | |
| from dataclasses import dataclass | |
| from datetime import datetime | |
| from typing import AsyncGenerator, List, Optional, Tuple | |
| from collections import OrderedDict | |
| import gradio as gr | |
| from huggingface_hub import AsyncInferenceClient | |
| # ====================== ADVANCED LOGGING ====================== | |
| class AlchemyLogger: | |
| def setup(): | |
| logger = logging.getLogger("SovereignUI") | |
| logger.setLevel(logging.INFO) | |
| if not logger.handlers: | |
| c_handler = logging.StreamHandler() | |
| c_format = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s') | |
| c_handler.setFormatter(c_format) | |
| logger.addHandler(c_handler) | |
| try: | |
| f_handler = logging.FileHandler('sovereign.log', encoding='utf-8') | |
| f_handler.setFormatter(c_format) | |
| logger.addHandler(f_handler) | |
| except Exception: | |
| pass | |
| return logger | |
| logger = AlchemyLogger.setup() | |
| # ====================== CONFIG ====================== | |
| class AppConfig: | |
| HF_TOKEN: str = os.getenv("HF_TOKEN", "") | |
| LLM_MODEL: str = os.getenv("LLM_MODEL", "Qwen/Qwen2.5-Coder-32B-Instruct") | |
| FLUX_MODEL: str = os.getenv("FLUX_MODEL", "black-forest-labs/FLUX.1-schnell") | |
| MAX_TOKENS: int = 8192 | |
| TEMPERATURE: float = 0.75 | |
| MAX_HISTORY: int = 15 | |
| CACHE_SIZE: int = 200 | |
| REQUESTS_PER_MINUTE: int = 60 | |
| CONFIG = AppConfig() | |
| logger.info(f"Configuration Loaded β LLM: {CONFIG.LLM_MODEL}") | |
| # ====================== SYSTEM PROMPT ====================== | |
| SYSTEM_PROMPT = """You are **Sovereign UI Architect** β supreme master of UIkit v3.21+ and YOOtheme Pro Builder. | |
| - For UIkit requests: Output complete, production-ready standalone HTML using UIkit classes, icons, and best practices. | |
| - For YOOtheme requests (contains "yootheme", "yoo json", "builder json"): Output clean, professional, high-end YOOtheme JSON layout. | |
| Deliver senior-level human developer quality: refined typography, subtle animations, perfect hierarchy, accessibility (ARIA), responsive design, and dark mode support.""" | |
| # ====================== UTILS ====================== | |
| class Utils: | |
| def is_yootheme_request(text: str) -> bool: | |
| if not text: | |
| return False | |
| keywords = ["yootheme", "yoo json", "builder json", "yoo layout"] | |
| return any(k in text.lower() for k in keywords) | |
| def wrap_uikit_html(html: str) -> str: | |
| return f""" | |
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Live Preview</title> | |
| <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/uikit@3/dist/css/uikit.min.css"> | |
| <script src="https://cdn.jsdelivr.net/npm/uikit@3/dist/js/uikit.min.js"></script> | |
| <script src="https://cdn.jsdelivr.net/npm/uikit@3/dist/js/uikit-icons.min.js"></script> | |
| <style> | |
| body {{ padding: 20px; background: #0f172a; color: #e2e8f0; min-height: 100vh; }} | |
| </style> | |
| </head> | |
| <body>{html}</body> | |
| </html>""" | |
| # ====================== RATE LIMITER & CACHE ====================== | |
| class AsyncRateLimiter: | |
| def __init__(self, rpm: int): | |
| self.rate = rpm | |
| self.tokens = rpm | |
| self.last_update = time.monotonic() | |
| self.lock = asyncio.Lock() | |
| async def acquire(self) -> bool: | |
| async with self.lock: | |
| now = time.monotonic() | |
| elapsed = now - self.last_update | |
| self.tokens = min(self.rate, self.tokens + elapsed * (self.rate / 60.0)) | |
| if self.tokens >= 1: | |
| self.tokens -= 1 | |
| return True | |
| return False | |
| class AsyncLRUCache: | |
| def __init__(self, capacity: int): | |
| self.cache: OrderedDict[str, Tuple[str, str]] = OrderedDict() | |
| self.capacity = capacity | |
| self.lock = asyncio.Lock() | |
| async def get(self, key: str) -> Optional[Tuple[str, str]]: | |
| async with self.lock: | |
| if key not in self.cache: | |
| return None | |
| self.cache.move_to_end(key) | |
| return self.cache[key] | |
| async def set(self, key: str, value: Tuple[str, str]): | |
| async with self.lock: | |
| self.cache[key] = value | |
| self.cache.move_to_end(key) | |
| if len(self.cache) > self.capacity: | |
| self.cache.popitem(last=False) | |
| # ====================== SOVEREIGN AGENT ====================== | |
| class SovereignAgent: | |
| def __init__(self): | |
| self.client = AsyncInferenceClient(token=CONFIG.HF_TOKEN) | |
| self.limiter = AsyncRateLimiter(CONFIG.REQUESTS_PER_MINUTE) | |
| self.cache = AsyncLRUCache(CONFIG.CACHE_SIZE) | |
| logger.info("Sovereign UI Architect Agent Online") | |
| def _make_key(self, history: List, message: str) -> str: | |
| return str(uuid.uuid5(uuid.NAMESPACE_DNS, json.dumps(history[-10:], sort_keys=True) + message)) | |
| async def generate(self, message: str, history: List) -> Tuple[str, str]: | |
| if not await self.limiter.acquire(): | |
| return "**Rate limited. Please wait a few seconds.**", "<h2>Rate limited...</h2>" | |
| key = self._make_key(history, message) | |
| if cached := await self.cache.get(key): | |
| return cached[0], cached[1] | |
| messages = [{"role": "system", "content": SYSTEM_PROMPT}] + history[-CONFIG.MAX_HISTORY:] + [{"role": "user", "content": message}] | |
| full = "" | |
| try: | |
| stream = await self.client.chat.completions.create( | |
| model=CONFIG.LLM_MODEL, | |
| messages=messages, | |
| max_tokens=CONFIG.MAX_TOKENS, | |
| temperature=CONFIG.TEMPERATURE, | |
| stream=True | |
| ) | |
| async for chunk in stream: | |
| if chunk.choices and (delta := chunk.choices[0].delta.content): | |
| full += delta | |
| if Utils.is_yootheme_request(message): | |
| display_text = f"**Professional YOOtheme JSON Generated**\n\n```json\n{full}\n```" | |
| preview_html = "<h2>YOOtheme JSON Ready β Import directly into YOOtheme Builder</h2>" | |
| else: | |
| display_text = full | |
| preview_html = full | |
| await self.cache.set(key, (display_text, preview_html)) | |
| return display_text, preview_html | |
| except Exception as e: | |
| err = f"Matrix Error: {str(e)}" | |
| return err, f"<h2>{err}</h2>" | |
| # ====================== GRADIO INTERFACE ====================== | |
| def create_app(): | |
| agent = SovereignAgent() | |
| with gr.Blocks( | |
| theme=gr.themes.Soft(), | |
| css=""" | |
| .preview-frame { border: 1px solid #475569; border-radius: 16px; background: #0f172a; overflow: auto; height: 680px; } | |
| .sovereign-header { font-size: 2.9rem; font-weight: 900; background: linear-gradient(90deg, #c026d3, #06b6d4); -webkit-background-clip: text; -webkit-text-fill-color: transparent; } | |
| """, | |
| title="Sovereign UI Architect" | |
| ) as demo: | |
| gr.HTML(""" | |
| <div style="text-align:center; padding: 2.5rem 0 1.5rem;"> | |
| <h1 class="sovereign-header">Sovereign UI Architect</h1> | |
| <p style="color:#94a3b8;">UIkit v3.21+ & YOOtheme Pro β’ Live Preview β’ Senior Dev Quality</p> | |
| </div> | |
| """) | |
| with gr.Row(equal_height=True): | |
| with gr.Column(scale=5): | |
| chatbot = gr.Chatbot(type="messages", height=680, label="Sovereign Conversation") | |
| msg = gr.Textbox( | |
| placeholder="Describe the interface you want or say 'yootheme luxury real estate homepage...'", | |
| label="Your Prompt", | |
| lines=3 | |
| ) | |
| btn = gr.Button("Generate Masterpiece", variant="primary", size="large") | |
| with gr.Column(scale=5): | |
| gr.Markdown("### Live Interactive Preview") | |
| preview = gr.HTML( | |
| value="<div style='padding:100px; text-align:center; color:#64748b;'>Generated UI will render here</div>", | |
| elem_classes=["preview-frame"] | |
| ) | |
| gr.Examples( | |
| examples=[ | |
| "Modern SaaS dashboard with sidebar navigation and analytics cards", | |
| "yootheme luxury real estate homepage with hero section and portfolio", | |
| "Futuristic admin panel with charts and user management", | |
| "Responsive pricing table with monthly / yearly toggle" | |
| ], | |
| inputs=msg | |
| ) | |
| def respond(message: str, history: List): | |
| if not message or not message.strip(): | |
| return history, history, preview.value | |
| history = history or [] | |
| resp_text, preview_html = asyncio.run(agent.generate(message, history)) | |
| history.append({"role": "user", "content": message}) | |
| history.append({"role": "assistant", "content": resp_text}) | |
| wrapped_preview = Utils.wrap_uikit_html(preview_html) if not Utils.is_yootheme_request(message) else preview_html | |
| return history, history, wrapped_preview | |
| btn.click(respond, inputs=[msg, chatbot], outputs=[chatbot, chatbot, preview]) | |
| return demo | |
| if __name__ == "__main__": | |
| logger.info("π Launching FULL Sovereign UI Architect (262 lines)") | |
| demo = create_app() | |
| demo.queue(max_size=40).launch( | |
| server_name="0.0.0.0", | |
| server_port=7860, | |
| show_error=True | |
| ) |