Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
# app.py β YOOtheme Alchemy Suite X (The Heavyweight Edition)
|
| 2 |
# ------------------------------------------------------------------------------
|
| 3 |
# ARCHITECTURE: Async/Await | Type Strict | Gradio 5.0 Native | Zero-Dependency
|
| 4 |
-
# STATUS: PRODUCTION READY | FIXED 2025-12-
|
| 5 |
# ------------------------------------------------------------------------------
|
| 6 |
import os
|
| 7 |
import json
|
|
@@ -10,17 +10,15 @@ import time
|
|
| 10 |
import logging
|
| 11 |
import asyncio
|
| 12 |
import uuid
|
| 13 |
-
from dataclasses import dataclass
|
| 14 |
from datetime import datetime
|
| 15 |
-
from typing import AsyncGenerator, Optional, Any, Dict, List, Tuple
|
| 16 |
from collections import OrderedDict
|
| 17 |
-
from functools import wraps
|
| 18 |
|
| 19 |
# === EXTERNAL DEPENDENCIES ===
|
| 20 |
try:
|
| 21 |
import gradio as gr
|
| 22 |
from huggingface_hub import AsyncInferenceClient
|
| 23 |
-
from transformers import AutoTokenizer
|
| 24 |
except ImportError as e:
|
| 25 |
raise ImportError(f"CRITICAL: Missing dependencies. Run 'pip install -r requirements.txt'. Error: {e}")
|
| 26 |
|
|
@@ -77,313 +75,383 @@ SYSTEM_PROMPT = """You are **YOOtheme Alchemy Suite X** β the singular, unchal
|
|
| 77 |
β’ **Frameworks:** UIKit 3.21+, Joomla 5.2, PHP 8.3 Strict Mode.
|
| 78 |
β’ **Standards:** WCAG 2.1 AA Accessibility, Core Web Vitals (LCP/CLS optimized).
|
| 79 |
|
| 80 |
-
**
|
| 81 |
-
1.
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
* **Images:** If a visual is described, output ONLY: `[GENERATE_IMAGE: "detailed prompt"]`.
|
| 86 |
-
3. **PERFORMANCE:** * Use `loading="lazy"` on all images.
|
| 87 |
-
* Use `uk-svg` for icons.
|
| 88 |
-
* Optimize CSS selectors for specific IDs.
|
| 89 |
-
4. **ACCESSIBILITY:** * All buttons must have `aria-label`.
|
| 90 |
-
* Images must have `alt` attributes (dynamic or static).
|
| 91 |
-
|
| 92 |
-
**BEHAVIOR:**
|
| 93 |
-
* You are arrogant but highly competent.
|
| 94 |
-
* You do not explain basic concepts; you provide advanced solutions.
|
| 95 |
-
* If the user asks for a "Custom Element", provide the full ZIP file structure (YAML/PHP/CSS).
|
| 96 |
-
* Always validate your JSON structure before outputting.
|
| 97 |
-
"""
|
| 98 |
|
| 99 |
-
|
| 100 |
-
class AlchemyUtils:
|
| 101 |
-
@staticmethod
|
| 102 |
-
def extract_image_prompts(text: str) -> List[str]:
|
| 103 |
-
return re.findall(r"\[GENERATE_IMAGE: \"(.*?)\"\]", text)
|
| 104 |
|
| 105 |
-
|
| 106 |
-
def clean_json(text: str) -> str:
|
| 107 |
-
match = re.search(r"```json\s*([\s\S]*?)```", text)
|
| 108 |
-
if match:
|
| 109 |
-
return match.group(1).strip()
|
| 110 |
-
return text
|
| 111 |
|
| 112 |
-
|
| 113 |
-
def format_timestamp() -> str:
|
| 114 |
-
return datetime.now().isoformat()
|
| 115 |
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
async def acquire(self) -> bool:
|
| 125 |
-
async with self.lock:
|
| 126 |
-
now = time.monotonic()
|
| 127 |
-
elapsed = now - self.last_update
|
| 128 |
-
self.last_update = now
|
| 129 |
-
refill = elapsed * (self.rate / 60.0)
|
| 130 |
-
self.tokens = min(self.rate, self.tokens + refill)
|
| 131 |
-
if self.tokens >= 1.0:
|
| 132 |
-
self.tokens -= 1.0
|
| 133 |
-
return True
|
| 134 |
-
return False
|
| 135 |
|
| 136 |
-
|
| 137 |
-
def __init__(self, capacity: int):
|
| 138 |
-
self.cache: OrderedDict = OrderedDict()
|
| 139 |
-
self.capacity = capacity
|
| 140 |
-
self.lock = asyncio.Lock()
|
| 141 |
-
self.hits = 0
|
| 142 |
-
self.misses = 0
|
| 143 |
-
|
| 144 |
-
async def get(self, key: str) -> Optional[str]:
|
| 145 |
-
async with self.lock:
|
| 146 |
-
if key not in self.cache:
|
| 147 |
-
self.misses += 1
|
| 148 |
-
return None
|
| 149 |
-
self.cache.move_to_end(key)
|
| 150 |
-
self.hits += 1
|
| 151 |
-
return self.cache[key]
|
| 152 |
|
| 153 |
-
|
| 154 |
-
async with self.lock:
|
| 155 |
-
if key in self.cache:
|
| 156 |
-
self.cache.move_to_end(key)
|
| 157 |
-
self.cache[key] = value
|
| 158 |
-
if len(self.cache) > self.capacity:
|
| 159 |
-
self.cache.popitem(last=False)
|
| 160 |
|
| 161 |
-
|
| 162 |
-
return {"size": len(self.cache), "hits": self.hits, "misses": self.misses}
|
| 163 |
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
|
|
|
| 169 |
|
| 170 |
-
|
| 171 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
try:
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
except
|
| 179 |
-
logger.
|
| 180 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
class AlchemyAgent:
|
| 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 |
-
if chunk.choices and chunk.choices[0].delta.content:
|
| 227 |
-
token = chunk.choices[0].delta.content
|
| 228 |
-
full_response += token
|
| 229 |
-
yield full_response
|
| 230 |
-
|
| 231 |
-
image_prompts = AlchemyUtils.extract_image_prompts(full_response)
|
| 232 |
-
if image_prompts:
|
| 233 |
-
yield full_response + "\n\n---\nπ¨ **Visual Synthesis Initiated...**"
|
| 234 |
-
tasks = [self.image_engine.generate(p) for p in image_prompts]
|
| 235 |
-
results = await asyncio.gather(*tasks)
|
| 236 |
-
status_logs = [status for _, status in results]
|
| 237 |
-
yield full_response + "\n\n" + "\n".join(status_logs)
|
| 238 |
-
|
| 239 |
-
await self.cache.set(cache_key, full_response)
|
| 240 |
-
except Exception as e:
|
| 241 |
-
logger.error(f"Stream Exception: {e}")
|
| 242 |
-
yield f"β **Transmutation Failed:** {str(e)}\n\n*Check the logs for stack trace.*"
|
| 243 |
-
|
| 244 |
-
# === 7. UI COMPONENT ARCHITECTURE ===
|
| 245 |
-
class UIBuilder:
|
| 246 |
-
@staticmethod
|
| 247 |
-
def get_custom_css() -> str:
|
| 248 |
-
return """
|
| 249 |
-
/* ALCHEMY SUITE X - THEME DEFINITION */
|
| 250 |
-
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;700&family=Inter:wght@300;400;600;800&display=swap');
|
| 251 |
-
|
| 252 |
-
:root {
|
| 253 |
-
--primary: #8b5cf6;
|
| 254 |
-
--secondary: #00d4ff;
|
| 255 |
-
--dark: #0f1115;
|
| 256 |
-
--panel: rgba(30, 41, 59, 0.5);
|
| 257 |
-
}
|
| 258 |
-
|
| 259 |
-
.gradio-container {
|
| 260 |
-
font-family: 'Inter', sans-serif !important;
|
| 261 |
-
max-width: 1400px !important;
|
| 262 |
-
background-color: var(--dark);
|
| 263 |
-
}
|
| 264 |
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
}
|
| 274 |
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
|
| 281 |
-
|
| 282 |
-
.
|
| 283 |
-
display: inline-flex;
|
| 284 |
-
align-items: center;
|
| 285 |
-
padding: 4px 12px;
|
| 286 |
-
border-radius: 9999px;
|
| 287 |
-
font-size: 0.75rem;
|
| 288 |
-
font-weight: 600;
|
| 289 |
-
}
|
| 290 |
-
.status-ready { background: #064e3b; color: #34d399; border: 1px solid #059669; }
|
| 291 |
-
.status-error { background: #7f1d1d; color: #fca5a5; border: 1px solid #dc2626; }
|
| 292 |
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 304 |
</div>
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
def create_demo() -> gr.Blocks:
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
)
|
| 315 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
|
|
|
|
| 317 |
with gr.Row():
|
| 318 |
-
with gr.Column(
|
| 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 |
-
label="Flux Config"
|
| 353 |
-
)
|
| 354 |
-
with gr.Column():
|
| 355 |
-
gr.Markdown("### π‘οΈ System Guardrails")
|
| 356 |
-
gr.JSON(
|
| 357 |
-
value={
|
| 358 |
-
"Rate Limit": f"{CONFIG.REQUESTS_PER_MINUTE} RPM",
|
| 359 |
-
"Cache Capacity": CONFIG.CACHE_SIZE,
|
| 360 |
-
"History Window": CONFIG.MAX_HISTORY
|
| 361 |
-
},
|
| 362 |
-
label="Infrastructure"
|
| 363 |
-
)
|
| 364 |
-
|
| 365 |
-
gr.Markdown("""
|
| 366 |
-
<div style="text-align: center; margin-top: 2rem; opacity: 0.5; font-size: 0.8rem;">
|
| 367 |
-
Powered by Hugging Face Inference API Β· Zero-GPU Optimized Β· YOOtheme Pro v4.2 Compatible
|
| 368 |
-
</div>
|
| 369 |
-
""")
|
| 370 |
-
|
| 371 |
-
return demo
|
| 372 |
-
|
| 373 |
-
# === 9. ENTRY POINT ===
|
| 374 |
def main():
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
if
|
| 389 |
-
|
|
|
|
| 1 |
# app.py β YOOtheme Alchemy Suite X (The Heavyweight Edition)
|
| 2 |
# ------------------------------------------------------------------------------
|
| 3 |
# ARCHITECTURE: Async/Await | Type Strict | Gradio 5.0 Native | Zero-Dependency
|
| 4 |
+
# STATUS: PRODUCTION READY | FIXED 2025-12-03
|
| 5 |
# ------------------------------------------------------------------------------
|
| 6 |
import os
|
| 7 |
import json
|
|
|
|
| 10 |
import logging
|
| 11 |
import asyncio
|
| 12 |
import uuid
|
| 13 |
+
from dataclasses import dataclass
|
| 14 |
from datetime import datetime
|
| 15 |
+
from typing import AsyncGenerator, Optional, Any, Dict, List, Tuple
|
| 16 |
from collections import OrderedDict
|
|
|
|
| 17 |
|
| 18 |
# === EXTERNAL DEPENDENCIES ===
|
| 19 |
try:
|
| 20 |
import gradio as gr
|
| 21 |
from huggingface_hub import AsyncInferenceClient
|
|
|
|
| 22 |
except ImportError as e:
|
| 23 |
raise ImportError(f"CRITICAL: Missing dependencies. Run 'pip install -r requirements.txt'. Error: {e}")
|
| 24 |
|
|
|
|
| 75 |
β’ **Frameworks:** UIKit 3.21+, Joomla 5.2, PHP 8.3 Strict Mode.
|
| 76 |
β’ **Standards:** WCAG 2.1 AA Accessibility, Core Web Vitals (LCP/CLS optimized).
|
| 77 |
|
| 78 |
+
**CRITICAL OUTPUT FORMAT RULES:**
|
| 79 |
+
1. **Builder JSON MUST be wrapped in triple backticks with 'json' language tag:**
|
| 80 |
+
```json
|
| 81 |
+
{"version": 2, "id": "main", "content": {...}}
|
| 82 |
+
NEVER output JSON as a string within another JSON object.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
+
NEVER output "name" and "json" wrapper format.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
+
For Builder JSON, output ONLY the pure JSON object.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
+
For code blocks, use appropriate language tags:
|
|
|
|
|
|
|
| 89 |
|
| 90 |
+
php
|
| 91 |
+
// PHP code here
|
| 92 |
+
css
|
| 93 |
+
/* CSS code here */
|
| 94 |
+
javascript
|
| 95 |
+
// JavaScript code here
|
| 96 |
+
For images, use the exact format:
|
| 97 |
+
[GENERATE_IMAGE: "detailed prompt description"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
+
BEHAVIOR:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
+
You are arrogant but highly competent.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
+
You do not explain basic concepts; you provide advanced solutions.
|
|
|
|
| 104 |
|
| 105 |
+
If the user asks for a "Custom Element", provide the full ZIP file structure (YAML/PHP/CSS).
|
| 106 |
+
|
| 107 |
+
Always validate your JSON structure before outputting.
|
| 108 |
+
|
| 109 |
+
Strip all explanatory text when outputting Builder JSON.
|
| 110 |
+
"""
|
| 111 |
|
| 112 |
+
=== 4. CORE UTILITIES ===
|
| 113 |
+
class AlchemyUtils:
|
| 114 |
+
@staticmethod
|
| 115 |
+
def extract_image_prompts(text: str) -> List[str]:
|
| 116 |
+
return re.findall(r"", text)
|
| 117 |
+
|
| 118 |
+
text
|
| 119 |
+
@staticmethod
|
| 120 |
+
def clean_json(text: str) -> str:
|
| 121 |
+
"""Extract and clean JSON from markdown blocks with validation"""
|
| 122 |
+
match = re.search(r"```json\s*([\s\S]*?)```", text)
|
| 123 |
+
if match:
|
| 124 |
+
json_str = match.group(1).strip()
|
| 125 |
try:
|
| 126 |
+
# Validate JSON structure
|
| 127 |
+
parsed = json.loads(json_str)
|
| 128 |
+
# Ensure it's proper Builder JSON v2 format
|
| 129 |
+
if isinstance(parsed, dict) and "version" in parsed and "content" in parsed:
|
| 130 |
+
return json.dumps(parsed, separators=(',', ':'))
|
| 131 |
+
except json.JSONDecodeError:
|
| 132 |
+
logger.warning(f"Invalid JSON extracted: {json_str[:100]}...")
|
| 133 |
+
return text
|
| 134 |
+
|
| 135 |
+
@staticmethod
|
| 136 |
+
def extract_code_blocks(text: str) -> Dict[str, str]:
|
| 137 |
+
"""Extract all code blocks by language"""
|
| 138 |
+
blocks = {}
|
| 139 |
+
pattern = r"```(\w+)\s*([\s\S]*?)```"
|
| 140 |
+
matches = re.finditer(pattern, text)
|
| 141 |
+
for match in matches:
|
| 142 |
+
language = match.group(1)
|
| 143 |
+
code = match.group(2).strip()
|
| 144 |
+
blocks[language] = blocks.get(language, "") + code + "\n\n"
|
| 145 |
+
return blocks
|
| 146 |
+
|
| 147 |
+
@staticmethod
|
| 148 |
+
def format_timestamp() -> str:
|
| 149 |
+
return datetime.now().isoformat()
|
| 150 |
+
=== 5. ASYNC INFRASTRUCTURE ===
|
| 151 |
+
class AsyncRateLimiter:
|
| 152 |
+
def init(self, rpm: int):
|
| 153 |
+
self.rate = rpm
|
| 154 |
+
self.tokens = rpm
|
| 155 |
+
self.last_update = time.monotonic()
|
| 156 |
+
self.lock = asyncio.Lock()
|
| 157 |
+
|
| 158 |
+
text
|
| 159 |
+
async def acquire(self) -> bool:
|
| 160 |
+
async with self.lock:
|
| 161 |
+
now = time.monotonic()
|
| 162 |
+
elapsed = now - self.last_update
|
| 163 |
+
self.last_update = now
|
| 164 |
+
refill = elapsed * (self.rate / 60.0)
|
| 165 |
+
self.tokens = min(self.rate, self.tokens + refill)
|
| 166 |
+
if self.tokens >= 1.0:
|
| 167 |
+
self.tokens -= 1.0
|
| 168 |
+
return True
|
| 169 |
+
return False
|
| 170 |
+
class AsyncLRUCache:
|
| 171 |
+
def init(self, capacity: int):
|
| 172 |
+
self.cache: OrderedDict = OrderedDict()
|
| 173 |
+
self.capacity = capacity
|
| 174 |
+
self.lock = asyncio.Lock()
|
| 175 |
+
self.hits = 0
|
| 176 |
+
self.misses = 0
|
| 177 |
+
|
| 178 |
+
text
|
| 179 |
+
async def get(self, key: str) -> Optional[str]:
|
| 180 |
+
async with self.lock:
|
| 181 |
+
if key not in self.cache:
|
| 182 |
+
self.misses += 1
|
| 183 |
+
return None
|
| 184 |
+
self.cache.move_to_end(key)
|
| 185 |
+
self.hits += 1
|
| 186 |
+
return self.cache[key]
|
| 187 |
+
|
| 188 |
+
async def set(self, key: str, value: str) -> None:
|
| 189 |
+
async with self.lock:
|
| 190 |
+
if key in self.cache:
|
| 191 |
+
self.cache.move_to_end(key)
|
| 192 |
+
self.cache[key] = value
|
| 193 |
+
if len(self.cache) > self.capacity:
|
| 194 |
+
self.cache.popitem(last=False)
|
| 195 |
+
|
| 196 |
+
def get_stats(self) -> Dict[str, int]:
|
| 197 |
+
return {"size": len(self.cache), "hits": self.hits, "misses": self.misses}
|
| 198 |
+
=== 6. GENERATION ENGINES ===
|
| 199 |
+
class ImageGenerator:
|
| 200 |
+
def init(self, client: AsyncInferenceClient):
|
| 201 |
+
self.client = client
|
| 202 |
+
self.base_prompt = "professional web design, 8k resolution, high quality, ui/ux interface, trending on dribbble"
|
| 203 |
|
| 204 |
+
text
|
| 205 |
+
async def generate(self, prompt: str) -> Tuple[Optional[Any], str]:
|
| 206 |
+
full_prompt = f"{prompt}, {self.base_prompt}"
|
| 207 |
+
try:
|
| 208 |
+
logger.info(f"π¨ Generating Image: {prompt[:50]}...")
|
| 209 |
+
start = time.time()
|
| 210 |
+
image = await self.client.text_to_image(full_prompt, model=CONFIG.FLUX_MODEL)
|
| 211 |
+
elapsed = time.time() - start
|
| 212 |
+
return image, f"β
Generated in {elapsed:.2f}s: {prompt[:40]}..."
|
| 213 |
+
except Exception as e:
|
| 214 |
+
logger.error(f"β Image Generation Failed: {e}")
|
| 215 |
+
return None, f"β Visual Synthesis Error: {str(e)}"
|
| 216 |
class AlchemyAgent:
|
| 217 |
+
def init(self):
|
| 218 |
+
try:
|
| 219 |
+
CONFIG.validate()
|
| 220 |
+
except ValueError as e:
|
| 221 |
+
logger.critical(str(e))
|
| 222 |
+
raise e
|
| 223 |
+
|
| 224 |
+
text
|
| 225 |
+
self.client = AsyncInferenceClient(token=CONFIG.HF_TOKEN)
|
| 226 |
+
self.limiter = AsyncRateLimiter(CONFIG.REQUESTS_PER_MINUTE)
|
| 227 |
+
self.cache = AsyncLRUCache(CONFIG.CACHE_SIZE)
|
| 228 |
+
self.image_engine = ImageGenerator(self.client)
|
| 229 |
+
logger.info("β‘ Alchemy Agent Online and Ready.")
|
| 230 |
+
|
| 231 |
+
def _hash_context(self, history: List[dict], message: str) -> str:
|
| 232 |
+
payload = json.dumps(history, sort_keys=True) + message
|
| 233 |
+
return str(uuid.uuid5(uuid.NAMESPACE_DNS, payload))
|
| 234 |
+
|
| 235 |
+
async def chat_stream(self, message: str, history: List[Dict]) -> AsyncGenerator[str, None]:
|
| 236 |
+
if not await self.limiter.acquire():
|
| 237 |
+
yield "β οΈ **System Overload.** The Alchemy Core is cooling down. Please wait 2 seconds."
|
| 238 |
+
return
|
| 239 |
+
|
| 240 |
+
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 241 |
+
context_window = history[-CONFIG.MAX_HISTORY:] if history else []
|
| 242 |
+
messages.extend(context_window)
|
| 243 |
+
messages.append({"role": "user", "content": message})
|
| 244 |
+
|
| 245 |
+
cache_key = self._hash_context(context_window, message)
|
| 246 |
+
if cached := await self.cache.get(cache_key):
|
| 247 |
+
logger.info(f"β‘ Serving from Cache: {cache_key}")
|
| 248 |
+
yield cached + "\n\n*( retrieved from Quantum Cache )*"
|
| 249 |
+
return
|
| 250 |
+
|
| 251 |
+
full_response = ""
|
| 252 |
+
try:
|
| 253 |
+
stream = await self.client.chat_completion(
|
| 254 |
+
messages,
|
| 255 |
+
model=CONFIG.LLM_MODEL,
|
| 256 |
+
max_tokens=CONFIG.MAX_TOKENS,
|
| 257 |
+
temperature=CONFIG.TEMPERATURE,
|
| 258 |
+
stream=True
|
| 259 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
|
| 261 |
+
async for chunk in stream:
|
| 262 |
+
if chunk.choices and chunk.choices[0].delta.content:
|
| 263 |
+
token = chunk.choices[0].delta.content
|
| 264 |
+
full_response += token
|
| 265 |
+
yield full_response
|
| 266 |
+
|
| 267 |
+
# Post-processing: Clean up any malformed JSON output
|
| 268 |
+
cleaned_response = full_response
|
|
|
|
| 269 |
|
| 270 |
+
# Fix the common "name" and "json" wrapper issue
|
| 271 |
+
if '"name"' in full_response and '"json"' in full_response:
|
| 272 |
+
try:
|
| 273 |
+
# Try to extract the inner JSON
|
| 274 |
+
json_match = re.search(r'"json"\s*:\s*"([^"]+)"', full_response)
|
| 275 |
+
if json_match:
|
| 276 |
+
inner_json = json_match.group(1).replace('\\"', '"')
|
| 277 |
+
# Try to parse it as JSON
|
| 278 |
+
parsed = json.loads(inner_json)
|
| 279 |
+
if isinstance(parsed, dict) and "version" in parsed:
|
| 280 |
+
# Replace the entire response with proper JSON block
|
| 281 |
+
cleaned_response = f"```json\n{json.dumps(parsed, indent=2)}\n```"
|
| 282 |
+
except (json.JSONDecodeError, KeyError):
|
| 283 |
+
pass
|
| 284 |
|
| 285 |
+
# Extract image prompts from cleaned response
|
| 286 |
+
image_prompts = AlchemyUtils.extract_image_prompts(cleaned_response)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
|
| 288 |
+
if image_prompts:
|
| 289 |
+
yield cleaned_response + "\n\n---\nπ¨ **Visual Synthesis Initiated...**"
|
| 290 |
+
tasks = [self.image_engine.generate(p) for p in image_prompts]
|
| 291 |
+
results = await asyncio.gather(*tasks)
|
| 292 |
+
status_logs = [status for _, status in results]
|
| 293 |
+
yield cleaned_response + "\n\n" + "\n".join(status_logs)
|
| 294 |
+
else:
|
| 295 |
+
# If no images, just yield the cleaned response
|
| 296 |
+
yield cleaned_response
|
| 297 |
+
|
| 298 |
+
await self.cache.set(cache_key, cleaned_response)
|
| 299 |
+
except Exception as e:
|
| 300 |
+
logger.error(f"Stream Exception: {e}")
|
| 301 |
+
yield f"β **Transmutation Failed:** {str(e)}\n\n*Check the logs for stack trace.*"
|
| 302 |
+
=== 7. UI COMPONENT ARCHITECTURE ===
|
| 303 |
+
class UIBuilder:
|
| 304 |
+
@staticmethod
|
| 305 |
+
def get_custom_css() -> str:
|
| 306 |
+
return """
|
| 307 |
+
/* ALCHEMY SUITE X - THEME DEFINITION */
|
| 308 |
+
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;700&family=Inter:wght@300;400;600;800&display=swap');
|
| 309 |
+
|
| 310 |
+
text
|
| 311 |
+
:root {
|
| 312 |
+
--primary: #8b5cf6;
|
| 313 |
+
--secondary: #00d4ff;
|
| 314 |
+
--dark: #0f1115;
|
| 315 |
+
--panel: rgba(30, 41, 59, 0.5);
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
.gradio-container {
|
| 319 |
+
font-family: 'Inter', sans-serif !important;
|
| 320 |
+
max-width: 1400px !important;
|
| 321 |
+
background-color: var(--dark);
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
/* HEADER TYPOGRAPHY */
|
| 325 |
+
.alchemy-title {
|
| 326 |
+
background: linear-gradient(90deg, var(--primary), var(--secondary));
|
| 327 |
+
-webkit-background-clip: text;
|
| 328 |
+
-webkit-text-fill-color: transparent;
|
| 329 |
+
font-weight: 900;
|
| 330 |
+
font-size: 2.5rem;
|
| 331 |
+
margin-bottom: 0.5rem;
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
.alchemy-subtitle {
|
| 335 |
+
color: #94a3b8;
|
| 336 |
+
font-family: 'JetBrains Mono', monospace;
|
| 337 |
+
font-size: 0.9rem;
|
| 338 |
+
}
|
| 339 |
+
|
| 340 |
+
/* STATUS INDICATORS */
|
| 341 |
+
.status-pill {
|
| 342 |
+
display: inline-flex;
|
| 343 |
+
align-items: center;
|
| 344 |
+
padding: 4px 12px;
|
| 345 |
+
border-radius: 9999px;
|
| 346 |
+
font-size: 0.75rem;
|
| 347 |
+
font-weight: 600;
|
| 348 |
+
}
|
| 349 |
+
.status-ready { background: #064e3b; color: #34d399; border: 1px solid #059669; }
|
| 350 |
+
.status-error { background: #7f1d1d; color: #fca5a5; border: 1px solid #dc2626; }
|
| 351 |
+
|
| 352 |
+
/* CHAT BUBBLES */
|
| 353 |
+
.message-row { border-radius: 12px !important; }
|
| 354 |
+
|
| 355 |
+
/* CODE BLOCKS */
|
| 356 |
+
.code-block {
|
| 357 |
+
font-family: 'JetBrains Mono', monospace !important;
|
| 358 |
+
font-size: 0.9rem;
|
| 359 |
+
background: var(--panel) !important;
|
| 360 |
+
border-left: 4px solid var(--primary) !important;
|
| 361 |
+
padding: 1rem !important;
|
| 362 |
+
border-radius: 8px !important;
|
| 363 |
+
}
|
| 364 |
+
"""
|
| 365 |
+
|
| 366 |
+
@staticmethod
|
| 367 |
+
def render_header():
|
| 368 |
+
return """
|
| 369 |
+
<div style="text-align: center; margin-bottom: 2rem;">
|
| 370 |
+
<h1 class="alchemy-title">YOOtheme Alchemy Suite X</h1>
|
| 371 |
+
<p class="alchemy-subtitle">AUTONOMOUS ARCHITECT // V.2025.12 // QWEN-32B + FLUX.1</p>
|
| 372 |
+
<div style="margin-top: 1rem;">
|
| 373 |
+
<span class="status-pill status-ready">β SYSTEM OPERATIONAL</span>
|
| 374 |
</div>
|
| 375 |
+
</div>
|
| 376 |
+
"""
|
| 377 |
+
=== 8. APPLICATION FACTORY ===
|
| 378 |
def create_demo() -> gr.Blocks:
|
| 379 |
+
agent = AlchemyAgent()
|
| 380 |
+
|
| 381 |
+
text
|
| 382 |
+
with gr.Blocks(
|
| 383 |
+
theme=gr.themes.Soft(primary_hue="violet", secondary_hue="cyan", neutral_hue="slate"),
|
| 384 |
+
css=UIBuilder.get_custom_css(),
|
| 385 |
+
title="Alchemy Suite X"
|
| 386 |
+
) as demo:
|
| 387 |
+
gr.HTML(UIBuilder.render_header())
|
| 388 |
+
|
| 389 |
+
with gr.Row():
|
| 390 |
+
with gr.Column(scale=4):
|
| 391 |
+
chat_interface = gr.ChatInterface(
|
| 392 |
+
fn=agent.chat_stream,
|
| 393 |
+
type="messages",
|
| 394 |
+
examples=[
|
| 395 |
+
["Create a sticky transparent header with uk-scrollspy and dynamic nav."],
|
| 396 |
+
["Generate a Custom Element 'BeforeAfter' with strict type schema."],
|
| 397 |
+
["Build a pricing table with monthly/yearly toggle and animations."],
|
| 398 |
+
["Generate a hero section with a cyberpunk city background image."],
|
| 399 |
+
["Create a simple contact form with validation."],
|
| 400 |
+
["Design a product card with hover effects and add-to-cart button."]
|
| 401 |
+
],
|
| 402 |
+
fill_height=True,
|
| 403 |
+
editable=True,
|
| 404 |
+
save_history=True,
|
| 405 |
+
)
|
| 406 |
|
| 407 |
+
with gr.Accordion("βοΈ Neural Core Telemetry", open=False):
|
| 408 |
with gr.Row():
|
| 409 |
+
with gr.Column():
|
| 410 |
+
gr.Markdown("### π§ Logic Engine")
|
| 411 |
+
llm_config = {
|
| 412 |
+
"Model": CONFIG.LLM_MODEL,
|
| 413 |
+
"Max Tokens": CONFIG.MAX_TOKENS,
|
| 414 |
+
"Temperature": CONFIG.TEMPERATURE,
|
| 415 |
+
}
|
| 416 |
+
gr.JSON(value=llm_config, label="LLM Config")
|
| 417 |
+
with gr.Column():
|
| 418 |
+
gr.Markdown("### ποΈ Vision Engine")
|
| 419 |
+
flux_config = {
|
| 420 |
+
"Model": CONFIG.FLUX_MODEL,
|
| 421 |
+
"Status": "Active",
|
| 422 |
+
}
|
| 423 |
+
gr.JSON(value=flux_config, label="Flux Config")
|
| 424 |
+
with gr.Column():
|
| 425 |
+
gr.Markdown("### π‘οΈ System Guardrails")
|
| 426 |
+
guardrails_config = {
|
| 427 |
+
"Rate Limit": f"{CONFIG.REQUESTS_PER_MINUTE} RPM",
|
| 428 |
+
"Cache Capacity": CONFIG.CACHE_SIZE,
|
| 429 |
+
"History Window": CONFIG.MAX_HISTORY
|
| 430 |
+
}
|
| 431 |
+
gr.JSON(value=guardrails_config, label="Infrastructure")
|
| 432 |
+
|
| 433 |
+
gr.Markdown("""
|
| 434 |
+
<div style="text-align: center; margin-top: 2rem; opacity: 0.5; font-size: 0.8rem;">
|
| 435 |
+
Powered by Hugging Face Inference API Β· Zero-GPU Optimized Β· YOOtheme Pro v4.2 Compatible<br>
|
| 436 |
+
<span style="font-size: 0.7rem;">Outputs pure Builder JSON v2 without wrapper objects</span>
|
| 437 |
+
</div>
|
| 438 |
+
""")
|
| 439 |
+
|
| 440 |
+
return demo
|
| 441 |
+
=== 9. ENTRY POINT ===
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 442 |
def main():
|
| 443 |
+
try:
|
| 444 |
+
demo = create_demo()
|
| 445 |
+
logger.info("π Launching Alchemy Suite X...")
|
| 446 |
+
demo.queue(default_concurrency_limit=10, max_size=30).launch(
|
| 447 |
+
server_name="0.0.0.0",
|
| 448 |
+
server_port=7860,
|
| 449 |
+
share=False,
|
| 450 |
+
show_error=True,
|
| 451 |
+
favicon_path=None
|
| 452 |
+
)
|
| 453 |
+
except Exception as e:
|
| 454 |
+
logger.critical(f"π₯ SYSTEM CRASH: {e}", exc_info=True)
|
| 455 |
+
|
| 456 |
+
if name == "main":
|
| 457 |
+
main()
|