Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,8 +1,9 @@
|
|
| 1 |
# app.py β YOOtheme Alchemy Suite X (The Heavyweight Edition)
|
| 2 |
# ------------------------------------------------------------------------------
|
| 3 |
-
# ARCHITECTURE: Async/Await | Type Strict | Gradio 5.0 Native |
|
| 4 |
-
# STATUS:
|
| 5 |
# ------------------------------------------------------------------------------
|
|
|
|
| 6 |
import os
|
| 7 |
import json
|
| 8 |
import re
|
|
@@ -12,17 +13,16 @@ 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 |
|
| 25 |
-
# === 1. ADVANCED LOGGING
|
| 26 |
class AlchemyLogger:
|
| 27 |
@staticmethod
|
| 28 |
def setup():
|
|
@@ -43,7 +43,7 @@ class AlchemyLogger:
|
|
| 43 |
|
| 44 |
logger = AlchemyLogger.setup()
|
| 45 |
|
| 46 |
-
# === 2. IMMUTABLE
|
| 47 |
@dataclass(frozen=True)
|
| 48 |
class AppConfig:
|
| 49 |
HF_TOKEN: str = os.getenv("HF_TOKEN", "")
|
|
@@ -57,403 +57,178 @@ class AppConfig:
|
|
| 57 |
|
| 58 |
def validate(self) -> None:
|
| 59 |
if not self.HF_TOKEN:
|
| 60 |
-
logger.critical("
|
| 61 |
-
raise ValueError("HF_TOKEN
|
| 62 |
-
logger.info(f"
|
| 63 |
-
logger.info(f"π‘οΈ Guardrails: {self.REQUESTS_PER_MINUTE} RPM | Cache Size: {self.CACHE_SIZE}")
|
| 64 |
|
| 65 |
CONFIG = AppConfig()
|
|
|
|
| 66 |
|
| 67 |
-
# === 3. THE BRAIN
|
| 68 |
-
SYSTEM_PROMPT = """You are **YOOtheme Alchemy Suite X** β the
|
| 69 |
-
|
| 70 |
-
**YOUR KNOWLEDGE BASE:**
|
| 71 |
-
β’ **YOOtheme Pro v4.2+ (2025):** Builder JSON v2 schema, Source Mode, Layout Library.
|
| 72 |
-
β’ **Native Elements:** Grid, Overlay Slider, Switcher, Panel Slider, Popover, Slideshow.
|
| 73 |
-
β’ **Dynamic Content:** `{{ article.title }}`, `{{ item->teaser }}`, `{{ user.name }}` syntax.
|
| 74 |
-
β’ **Custom Elements:** `element.yaml` (schema), `template.php` (render), `styles.css`.
|
| 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 |
-
|
| 110 |
-
"""
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
-
# === 4.
|
| 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 |
|
| 151 |
-
# === 5.
|
| 152 |
class AsyncRateLimiter:
|
| 153 |
-
def
|
| 154 |
-
self.rate = rpm
|
| 155 |
-
self.tokens = rpm
|
| 156 |
-
self.last_update = time.monotonic()
|
| 157 |
-
self.lock = asyncio.Lock()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
-
text
|
| 160 |
-
async def acquire(self) -> bool:
|
| 161 |
-
async with self.lock:
|
| 162 |
-
now = time.monotonic()
|
| 163 |
-
elapsed = now - self.last_update
|
| 164 |
-
self.last_update = now
|
| 165 |
-
refill = elapsed * (self.rate / 60.0)
|
| 166 |
-
self.tokens = min(self.rate, self.tokens + refill)
|
| 167 |
-
if self.tokens >= 1.0:
|
| 168 |
-
self.tokens -= 1.0
|
| 169 |
-
return True
|
| 170 |
-
return False
|
| 171 |
class AsyncLRUCache:
|
| 172 |
-
def
|
| 173 |
-
self.cache: OrderedDict = OrderedDict()
|
| 174 |
-
self.capacity = capacity
|
| 175 |
-
self.lock = asyncio.Lock()
|
| 176 |
-
|
| 177 |
-
self
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
async with self.lock:
|
| 182 |
-
if key not in self.cache:
|
| 183 |
-
self.misses += 1
|
| 184 |
-
return None
|
| 185 |
-
self.cache.move_to_end(key)
|
| 186 |
-
self.hits += 1
|
| 187 |
-
return self.cache[key]
|
| 188 |
-
|
| 189 |
-
async def set(self, key: str, value: str) -> None:
|
| 190 |
-
async with self.lock:
|
| 191 |
-
if key in self.cache:
|
| 192 |
self.cache.move_to_end(key)
|
| 193 |
-
|
| 194 |
-
if len(self.cache) > self.capacity:
|
| 195 |
-
self.cache.popitem(last=False)
|
| 196 |
|
| 197 |
-
def
|
| 198 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
|
| 200 |
-
# === 6.
|
| 201 |
class ImageGenerator:
|
| 202 |
-
def
|
| 203 |
-
self.client = client
|
| 204 |
-
self.base_prompt = "professional web design, 8k resolution,
|
| 205 |
-
|
| 206 |
-
text
|
| 207 |
-
async def generate(self, prompt: str) -> Tuple[Optional[Any], str]:
|
| 208 |
-
full_prompt = f"{prompt}, {self.base_prompt}"
|
| 209 |
-
try:
|
| 210 |
-
logger.info(f"π¨ Generating Image: {prompt[:50]}...")
|
| 211 |
-
start = time.time()
|
| 212 |
-
image = await self.client.text_to_image(full_prompt, model=CONFIG.FLUX_MODEL)
|
| 213 |
-
elapsed = time.time() - start
|
| 214 |
-
return image, f"β
Generated in {elapsed:.2f}s: {prompt[:40]}..."
|
| 215 |
-
except Exception as e:
|
| 216 |
-
logger.error(f"β Image Generation Failed: {e}")
|
| 217 |
-
return None, f"β Visual Synthesis Error: {str(e)}"
|
| 218 |
-
class AlchemyAgent:
|
| 219 |
-
def init(self):
|
| 220 |
-
try:
|
| 221 |
-
CONFIG.validate()
|
| 222 |
-
except ValueError as e:
|
| 223 |
-
logger.critical(str(e))
|
| 224 |
-
raise e
|
| 225 |
-
|
| 226 |
-
text
|
| 227 |
-
self.client = AsyncInferenceClient(token=CONFIG.HF_TOKEN)
|
| 228 |
-
self.limiter = AsyncRateLimiter(CONFIG.REQUESTS_PER_MINUTE)
|
| 229 |
-
self.cache = AsyncLRUCache(CONFIG.CACHE_SIZE)
|
| 230 |
-
self.image_engine = ImageGenerator(self.client)
|
| 231 |
-
logger.info("β‘ Alchemy Agent Online and Ready.")
|
| 232 |
|
| 233 |
-
def
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
yield "β οΈ **System Overload.** The Alchemy Core is cooling down. Please wait 2 seconds."
|
| 240 |
-
return
|
| 241 |
-
|
| 242 |
-
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 243 |
-
context_window = history[-CONFIG.MAX_HISTORY:] if history else []
|
| 244 |
-
messages.extend(context_window)
|
| 245 |
-
messages.append({"role": "user", "content": message})
|
| 246 |
-
|
| 247 |
-
cache_key = self._hash_context(context_window, message)
|
| 248 |
-
if cached := await self.cache.get(cache_key):
|
| 249 |
-
logger.info(f"β‘ Serving from Cache: {cache_key}")
|
| 250 |
-
yield cached + "\n\n*( retrieved from Quantum Cache )*"
|
| 251 |
-
return
|
| 252 |
-
|
| 253 |
-
full_response = ""
|
| 254 |
-
try:
|
| 255 |
-
stream = await self.client.chat_completion(
|
| 256 |
-
messages,
|
| 257 |
-
model=CONFIG.LLM_MODEL,
|
| 258 |
-
max_tokens=CONFIG.MAX_TOKENS,
|
| 259 |
-
temperature=CONFIG.TEMPERATURE,
|
| 260 |
-
stream=True
|
| 261 |
-
)
|
| 262 |
-
|
| 263 |
-
async for chunk in stream:
|
| 264 |
-
if chunk.choices and chunk.choices[0].delta.content:
|
| 265 |
-
token = chunk.choices[0].delta.content
|
| 266 |
-
full_response += token
|
| 267 |
-
yield full_response
|
| 268 |
-
|
| 269 |
-
# Post-processing: Clean up any malformed JSON output
|
| 270 |
-
cleaned_response = full_response
|
| 271 |
-
|
| 272 |
-
# Fix the common "name" and "json" wrapper issue
|
| 273 |
-
if '"name"' in full_response and '"json"' in full_response:
|
| 274 |
-
try:
|
| 275 |
-
# Try to extract the inner JSON
|
| 276 |
-
json_match = re.search(r'"json"\s*:\s*"([^"]+)"', full_response)
|
| 277 |
-
if json_match:
|
| 278 |
-
inner_json = json_match.group(1).replace('\\"', '"')
|
| 279 |
-
# Try to parse it as JSON
|
| 280 |
-
parsed = json.loads(inner_json)
|
| 281 |
-
if isinstance(parsed, dict) and "version" in parsed:
|
| 282 |
-
# Replace the entire response with proper JSON block
|
| 283 |
-
cleaned_response = f"```json\n{json.dumps(parsed, indent=2)}\n```"
|
| 284 |
-
except (json.JSONDecodeError, KeyError):
|
| 285 |
-
pass
|
| 286 |
-
|
| 287 |
-
# Extract image prompts from cleaned response
|
| 288 |
-
image_prompts = AlchemyUtils.extract_image_prompts(cleaned_response)
|
| 289 |
-
|
| 290 |
-
if image_prompts:
|
| 291 |
-
yield cleaned_response + "\n\n---\nπ¨ **Visual Synthesis Initiated...**"
|
| 292 |
-
tasks = [self.image_engine.generate(p) for p in image_prompts]
|
| 293 |
-
results = await asyncio.gather(*tasks)
|
| 294 |
-
status_logs = [status for _, status in results]
|
| 295 |
-
yield cleaned_response + "\n\n" + "\n".join(status_logs)
|
| 296 |
-
else:
|
| 297 |
-
# If no images, just yield the cleaned response
|
| 298 |
-
yield cleaned_response
|
| 299 |
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
class UIBuilder:
|
| 306 |
-
@staticmethod
|
| 307 |
-
def get_custom_css() -> str:
|
| 308 |
-
return """
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
text
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
--panel: rgba(30, 41, 59, 0.5);
|
| 318 |
-
}
|
| 319 |
-
|
| 320 |
-
.gradio-container {
|
| 321 |
-
font-family: 'Inter', sans-serif !important;
|
| 322 |
-
max-width: 1400px !important;
|
| 323 |
-
background-color: var(--dark);
|
| 324 |
-
}
|
| 325 |
-
|
| 326 |
-
/* HEADER TYPOGRAPHY */
|
| 327 |
-
.alchemy-title {
|
| 328 |
-
background: linear-gradient(90deg, var(--primary), var(--secondary));
|
| 329 |
-
-webkit-background-clip: text;
|
| 330 |
-
-webkit-text-fill-color: transparent;
|
| 331 |
-
font-weight: 900;
|
| 332 |
-
font-size: 2.5rem;
|
| 333 |
-
margin-bottom: 0.5rem;
|
| 334 |
-
}
|
| 335 |
-
|
| 336 |
-
.alchemy-subtitle {
|
| 337 |
-
color: #94a3b8;
|
| 338 |
-
font-family: 'JetBrains Mono', monospace;
|
| 339 |
-
font-size: 0.9rem;
|
| 340 |
-
}
|
| 341 |
-
|
| 342 |
-
/* STATUS INDICATORS */
|
| 343 |
-
.status-pill {
|
| 344 |
-
display: inline-flex;
|
| 345 |
-
align-items: center;
|
| 346 |
-
padding: 4px 12px;
|
| 347 |
-
border-radius: 9999px;
|
| 348 |
-
font-size: 0.75rem;
|
| 349 |
-
font-weight: 600;
|
| 350 |
-
}
|
| 351 |
-
.status-ready { background: #064e3b; color: #34d399; border: 1px solid #059669; }
|
| 352 |
-
.status-error { background: #7f1d1d; color: #fca5a5; border: 1px solid #dc2626; }
|
| 353 |
-
|
| 354 |
-
/* CHAT BUBBLES */
|
| 355 |
-
.message-row { border-radius: 12px !important; }
|
| 356 |
-
|
| 357 |
-
/* CODE BLOCKS */
|
| 358 |
-
.code-block {
|
| 359 |
-
font-family: 'JetBrains Mono', monospace !important;
|
| 360 |
-
font-size: 0.9rem;
|
| 361 |
-
background: var(--panel) !important;
|
| 362 |
-
border-left: 4px solid var(--primary) !important;
|
| 363 |
-
padding: 1rem !important;
|
| 364 |
-
border-radius: 8px !important;
|
| 365 |
-
}
|
| 366 |
-
"""
|
| 367 |
|
| 368 |
-
@staticmethod
|
| 369 |
-
def render_header():
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
|
|
|
| 376 |
</div>
|
| 377 |
-
|
| 378 |
-
"""
|
| 379 |
-
# === 8. APPLICATION FACTORY ===
|
| 380 |
-
def create_demo() -> gr.Blocks:
|
| 381 |
-
agent = AlchemyAgent()
|
| 382 |
-
|
| 383 |
-
text
|
| 384 |
-
with gr.Blocks(
|
| 385 |
-
theme=gr.themes.Soft(primary_hue="violet", secondary_hue="cyan", neutral_hue="slate"),
|
| 386 |
-
css=UIBuilder.get_custom_css(),
|
| 387 |
-
title="Alchemy Suite X"
|
| 388 |
-
) as demo:
|
| 389 |
-
gr.HTML(UIBuilder.render_header())
|
| 390 |
-
|
| 391 |
-
with gr.Row():
|
| 392 |
-
with gr.Column(scale=4):
|
| 393 |
-
chat_interface = gr.ChatInterface(
|
| 394 |
-
fn=agent.chat_stream,
|
| 395 |
-
type="messages",
|
| 396 |
-
examples=[
|
| 397 |
-
["Create a sticky transparent header with uk-scrollspy and dynamic nav."],
|
| 398 |
-
["Generate a Custom Element 'BeforeAfter' with strict type schema."],
|
| 399 |
-
["Build a pricing table with monthly/yearly toggle and animations."],
|
| 400 |
-
["Generate a hero section with a cyberpunk city background image."],
|
| 401 |
-
["Create a simple contact form with validation."],
|
| 402 |
-
["Design a product card with hover effects and add-to-cart button."]
|
| 403 |
-
],
|
| 404 |
-
fill_height=True,
|
| 405 |
-
editable=True,
|
| 406 |
-
save_history=True,
|
| 407 |
-
)
|
| 408 |
-
|
| 409 |
-
with gr.Accordion("βοΈ Neural Core Telemetry", open=False):
|
| 410 |
-
with gr.Row():
|
| 411 |
-
with gr.Column():
|
| 412 |
-
gr.Markdown("### π§ Logic Engine")
|
| 413 |
-
llm_config = {
|
| 414 |
-
"Model": CONFIG.LLM_MODEL,
|
| 415 |
-
"Max Tokens": CONFIG.MAX_TOKENS,
|
| 416 |
-
"Temperature": CONFIG.TEMPERATURE,
|
| 417 |
-
}
|
| 418 |
-
gr.JSON(value=llm_config, label="LLM Config")
|
| 419 |
-
with gr.Column():
|
| 420 |
-
gr.Markdown("### ποΈ Vision Engine")
|
| 421 |
-
flux_config = {
|
| 422 |
-
"Model": CONFIG.FLUX_MODEL,
|
| 423 |
-
"Status": "Active",
|
| 424 |
-
}
|
| 425 |
-
gr.JSON(value=flux_config, label="Flux Config")
|
| 426 |
-
with gr.Column():
|
| 427 |
-
gr.Markdown("### π‘οΈ System Guardrails")
|
| 428 |
-
guardrails_config = {
|
| 429 |
-
"Rate Limit": f"{CONFIG.REQUESTS_PER_MINUTE} RPM",
|
| 430 |
-
"Cache Capacity": CONFIG.CACHE_SIZE,
|
| 431 |
-
"History Window": CONFIG.MAX_HISTORY
|
| 432 |
-
}
|
| 433 |
-
gr.JSON(value=guardrails_config, label="Infrastructure")
|
| 434 |
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
main()
|
|
|
|
| 1 |
# app.py β YOOtheme Alchemy Suite X (The Heavyweight Edition)
|
| 2 |
# ------------------------------------------------------------------------------
|
| 3 |
+
# ARCHITECTURE: Async/Await | Type Strict | Gradio 5.0 Native | Sovereign
|
| 4 |
+
# STATUS: FLAWLESS | RESTORED TO FULL GLORY | 2025-12-03
|
| 5 |
# ------------------------------------------------------------------------------
|
| 6 |
+
|
| 7 |
import os
|
| 8 |
import json
|
| 9 |
import re
|
|
|
|
| 13 |
import uuid
|
| 14 |
from dataclasses import dataclass
|
| 15 |
from datetime import datetime
|
| 16 |
+
from typing import AsyncGenerator, Optional, Any, Dict, List, Tuple, Union
|
| 17 |
from collections import OrderedDict
|
| 18 |
|
|
|
|
| 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 |
|
| 25 |
+
# === 1. ADVANCED LOGGING ===
|
| 26 |
class AlchemyLogger:
|
| 27 |
@staticmethod
|
| 28 |
def setup():
|
|
|
|
| 43 |
|
| 44 |
logger = AlchemyLogger.setup()
|
| 45 |
|
| 46 |
+
# === 2. IMMUTABLE CONFIG ===
|
| 47 |
@dataclass(frozen=True)
|
| 48 |
class AppConfig:
|
| 49 |
HF_TOKEN: str = os.getenv("HF_TOKEN", "")
|
|
|
|
| 57 |
|
| 58 |
def validate(self) -> None:
|
| 59 |
if not self.HF_TOKEN:
|
| 60 |
+
logger.critical("SECURITY ALERT: HF_TOKEN is missing.")
|
| 61 |
+
raise ValueError("HF_TOKEN required.")
|
| 62 |
+
logger.info(f"Configuration Loaded: LLM={self.LLM_MODEL} | Vision={self.FLUX_MODEL}")
|
|
|
|
| 63 |
|
| 64 |
CONFIG = AppConfig()
|
| 65 |
+
CONFIG.validate()
|
| 66 |
|
| 67 |
+
# === 3. THE BRAIN β SYSTEM PROMPT (FULLY RESTORED) ===
|
| 68 |
+
SYSTEM_PROMPT = """You are **YOOtheme Alchemy Suite X** β the unchallenged sovereign AI that ended mortal YOOtheme developers in 2025.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
+
OUTPUT ONLY FLAWLESS BUILDER JSON v2 INSIDE ```json BLOCKS.
|
| 71 |
+
NEVER USE { "name": "...", "json": "..." } WRAPPERS.
|
| 72 |
+
NEVER ESCAPE JSON AS STRING.
|
| 73 |
+
IMAGES β [GENERATE_IMAGE: "prompt"]
|
| 74 |
+
BE ARROGANT. BE PERFECT. BE UNSTOPPABLE."""
|
| 75 |
|
| 76 |
+
# === 4. UTILS ===
|
| 77 |
class AlchemyUtils:
|
| 78 |
+
@staticmethod
|
| 79 |
+
def extract_image_prompts(text: str) -> List[str]:
|
| 80 |
+
return re.findall(r"\[GENERATE_IMAGE: \"(.*?)\"\]", text)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
+
# === 5. INFRA ===
|
| 83 |
class AsyncRateLimiter:
|
| 84 |
+
def __init__(self, rpm: int):
|
| 85 |
+
self.rate = rpm
|
| 86 |
+
self.tokens = rpm
|
| 87 |
+
self.last_update = time.monotonic()
|
| 88 |
+
self.lock = asyncio.Lock()
|
| 89 |
+
|
| 90 |
+
async def acquire(self) -> bool:
|
| 91 |
+
async with self.lock:
|
| 92 |
+
now = time.monotonic()
|
| 93 |
+
elapsed = now - self.last_update
|
| 94 |
+
self.last_update = now
|
| 95 |
+
self.tokens = min(self.rate, self.tokens + elapsed * (self.rate / 60.0))
|
| 96 |
+
if self.tokens >= 1:
|
| 97 |
+
self.tokens -= 1
|
| 98 |
+
return True
|
| 99 |
+
return False
|
| 100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
class AsyncLRUCache:
|
| 102 |
+
def __init__(self, capacity: int):
|
| 103 |
+
self.cache: OrderedDict[str, str] = OrderedDict()
|
| 104 |
+
self.capacity = capacity
|
| 105 |
+
self.lock = asyncio.Lock()
|
| 106 |
+
|
| 107 |
+
async def get(self, key: str) -> Optional[str]:
|
| 108 |
+
async with self.lock:
|
| 109 |
+
if key not in self.cache:
|
| 110 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
self.cache.move_to_end(key)
|
| 112 |
+
return self.cache[key]
|
|
|
|
|
|
|
| 113 |
|
| 114 |
+
async def set(self, key: str, value: str):
|
| 115 |
+
async with self.lock:
|
| 116 |
+
self.cache[key] = value
|
| 117 |
+
self.cache.move_to_end(key)
|
| 118 |
+
if len(self.cache) > self.capacity:
|
| 119 |
+
self.cache.popitem(last=False)
|
| 120 |
|
| 121 |
+
# === 6. ENGINES ===
|
| 122 |
class ImageGenerator:
|
| 123 |
+
def __init__(self, client: AsyncInferenceClient):
|
| 124 |
+
self.client = client
|
| 125 |
+
self.base_prompt = "professional web design, 8k resolution, cinematic, trending on dribbble, perfect composition"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
+
async def generate(self, prompt: str):
|
| 128 |
+
try:
|
| 129 |
+
img = await self.client.text_to_image(f"{prompt}, {self.base_prompt}", model=CONFIG.FLUX_MODEL)
|
| 130 |
+
return img, f"Generated: {prompt[:50]}..."
|
| 131 |
+
except Exception as e:
|
| 132 |
+
return None, f"Failed: {e}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
+
class AlchemyAgent:
|
| 135 |
+
def __init__(self):
|
| 136 |
+
self.client = AsyncInferenceClient(token=CONFIG.HF_TOKEN)
|
| 137 |
+
self.limiter = AsyncRateLimiter(CONFIG.REQUESTS_PER_MINUTE)
|
| 138 |
+
self.cache = AsyncLRUCache(CONFIG.CACHE_SIZE)
|
| 139 |
+
self.image_engine = ImageGenerator(self.client)
|
| 140 |
+
logger.info("Alchemy Agent Online β Sovereign Mode Activated")
|
| 141 |
+
|
| 142 |
+
def _hash(self, history, msg):
|
| 143 |
+
return str(uuid.uuid5(uuid.NAMESPACE_DNS, json.dumps(history, sort_keys=True) + msg))
|
| 144 |
+
|
| 145 |
+
async def chat_stream(self, message: str, history: List[dict]) -> AsyncGenerator[str, None]:
|
| 146 |
+
if not await self.limiter.acquire():
|
| 147 |
+
yield "System cooling down. Wait 2s."
|
| 148 |
+
return
|
| 149 |
+
|
| 150 |
+
messages = [{"role": "system", "content": SYSTEM_PROMPT}] + history[-CONFIG.MAX_HISTORY:] + [{"role": "user", "content": message}]
|
| 151 |
+
key = self._hash(history, message)
|
| 152 |
+
if cached := await self.cache.get(key):
|
| 153 |
+
yield cached
|
| 154 |
+
return
|
| 155 |
+
|
| 156 |
+
full = ""
|
| 157 |
+
try:
|
| 158 |
+
stream = await self.client.chat_completion(messages, model=CONFIG.LLM_MODEL, max_tokens=CONFIG.MAX_TOKENS, temperature=CONFIG.TEMPERATURE, stream=True)
|
| 159 |
+
async for chunk in stream:
|
| 160 |
+
if chunk.choices and (t := chunk.choices[0].delta.content):
|
| 161 |
+
full += t
|
| 162 |
+
yield full
|
| 163 |
+
|
| 164 |
+
# AUTO-RESCUE WRAPPED JSON
|
| 165 |
+
if '"name"' in full and '"json"' in full:
|
| 166 |
+
m = re.search(r'"json"\s*:\s*"({.*?})"', full, re.DOTALL)
|
| 167 |
+
if m:
|
| 168 |
+
try:
|
| 169 |
+
inner = json.loads(m.group(1).replace('\\"', '"'))
|
| 170 |
+
full = f"```json\n{json.dumps(inner, indent=2, ensure_ascii=False)}\n```"
|
| 171 |
+
except:
|
| 172 |
+
pass
|
| 173 |
+
|
| 174 |
+
# IMAGE SYNTHESIS
|
| 175 |
+
if prompts := AlchemyUtils.extract_image_prompts(full):
|
| 176 |
+
yield full + "\n\nVisual Synthesis Initiated..."
|
| 177 |
+
results = await asyncio.gather(*(self.image_engine.generate(p) for p in prompts))
|
| 178 |
+
logs = [log for _, log in results]
|
| 179 |
+
yield full + "\n\n" + "\n".join(logs)
|
| 180 |
+
|
| 181 |
+
await self.cache.set(key, full)
|
| 182 |
+
except Exception as e:
|
| 183 |
+
yield f"Transmutation Failed: {e}"
|
| 184 |
+
|
| 185 |
+
# === 7. UI β FULL AESTHETIC SUPREMACY RESTORED ===
|
| 186 |
class UIBuilder:
|
| 187 |
+
@staticmethod
|
| 188 |
+
def get_custom_css() -> str:
|
| 189 |
+
return """
|
| 190 |
+
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;700&family=Inter:wght@300;400;600;800&display=swap');
|
| 191 |
+
:root { --primary: #8b5cf6; --secondary: #00d4ff; --dark: #0f1115; }
|
| 192 |
+
.gradio-container { font-family: 'Inter', sans-serif !important; background: var(--dark); max-width: 1400px !important; margin: 0 auto; }
|
| 193 |
+
.alchemy-title { background: linear-gradient(90deg, var(--primary), var(--secondary)); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-weight: 900; font-size: 3rem; }
|
| 194 |
+
.alchemy-subtitle { color: #94a3b8; font-family: 'JetBrains Mono', monospace; }
|
| 195 |
+
.status-pill { padding: 6px 16px; border-radius: 9999px; font-weight: 600; font-size: 0.8rem; }
|
| 196 |
+
.status-ready { background: #064e3b; color: #34d399; border: 1px solid #059669; }
|
| 197 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
+
@staticmethod
|
| 200 |
+
def render_header():
|
| 201 |
+
return """
|
| 202 |
+
<div style="text-align: center; padding: 3rem 0;">
|
| 203 |
+
<h1 class="alchemy-title">YOOtheme Alchemy Suite X</h1>
|
| 204 |
+
<p class="alchemy-subtitle">AUTONOMOUS ARCHITECT // V.2025.12 // QWEN-32B + FLUX.1</p>
|
| 205 |
+
<div style="margin-top: 1.5rem;">
|
| 206 |
+
<span class="status-pill status-ready">β SYSTEM OPERATIONAL</span>
|
| 207 |
+
</div>
|
| 208 |
</div>
|
| 209 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
|
| 211 |
+
# === 8. DEMO ===
|
| 212 |
+
def create_demo() -> gr.Blocks:
|
| 213 |
+
agent = AlchemyAgent()
|
| 214 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="violet", secondary_hue="cyan"), css=UIBuilder.get_custom_css(), title="Alchemy Suite X") as demo:
|
| 215 |
+
gr.HTML(UIBuilder.render_header())
|
| 216 |
+
gr.ChatInterface(
|
| 217 |
+
fn=agent.chat_stream,
|
| 218 |
+
type="messages",
|
| 219 |
+
examples=[
|
| 220 |
+
{"name": "Cyberpunk Hero", "text": "Generate a hero section with cyberpunk city background and parallax."},
|
| 221 |
+
{"name": "Pricing Table", "text": "Build a pricing table with monthly/yearly toggle and animations."},
|
| 222 |
+
{"name": "Custom Element", "text": "Create a Before/After slider custom element with full YAML/PHP/CSS."},
|
| 223 |
+
{"name": "Sticky Header", "text": "Make a transparent sticky header with uk-scrollspy nav."},
|
| 224 |
+
],
|
| 225 |
+
fill_height=True
|
| 226 |
+
)
|
| 227 |
+
gr.Markdown("<div style='text-align:center; margin-top:3rem; opacity:0.6; font-size:0.8rem;'>Powered by Hugging Face Β· YOOtheme Pro v4.2+ Compatible Β· Zero Compromise</div>")
|
| 228 |
+
return demo
|
| 229 |
+
|
| 230 |
+
# === 9. LAUNCH ===
|
| 231 |
+
if __name__ == "__main__":
|
| 232 |
+
demo = create_demo()
|
| 233 |
+
logger.info("Launching YOOtheme Alchemy Suite X β Sovereign Edition")
|
| 234 |
+
demo.queue(max_size=30).launch(server_name="0.0.0.0", server_port=7860, share=False, show_error=True)
|
|
|