acecalisto3 commited on
Commit
2b93446
Β·
verified Β·
1 Parent(s): babb59d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -133
app.py CHANGED
@@ -1,9 +1,4 @@
1
- # app.py β€” Sovereign UIKitV3 Automator (Fixed & Hardened - 2026)
2
- # ------------------------------------------------------------------------------
3
- # ARCHITECTURE: Async | Type Strict | Gradio 5+ | Live Preview | UIKit Mastery
4
- # STATUS: FULLY FIXED | PRODUCTION READY | ZERO PLACEHOLDERS
5
- # ------------------------------------------------------------------------------
6
-
7
  import os
8
  import json
9
  import re
@@ -13,66 +8,84 @@ import asyncio
13
  import uuid
14
  from dataclasses import dataclass
15
  from datetime import datetime
16
- from typing import AsyncGenerator, Optional, List
17
  from collections import OrderedDict
18
 
19
  import gradio as gr
20
  from huggingface_hub import AsyncInferenceClient
21
 
22
- # === 1. ADVANCED LOGGING ===
23
  class AlchemyLogger:
24
  @staticmethod
25
  def setup():
26
- logger = logging.getLogger("UIKitV3Sovereign")
27
  logger.setLevel(logging.INFO)
28
  if not logger.handlers:
29
  c_handler = logging.StreamHandler()
30
- c_format = logging.Formatter('%(asctime)s | %(levelname)s | %(name)s | %(message)s')
31
  c_handler.setFormatter(c_format)
32
  logger.addHandler(c_handler)
33
  try:
34
  f_handler = logging.FileHandler('sovereign.log', encoding='utf-8')
35
  f_handler.setFormatter(c_format)
36
  logger.addHandler(f_handler)
37
- except IOError:
38
  pass
39
  return logger
40
 
41
  logger = AlchemyLogger.setup()
42
 
43
- # === 2. IMMUTABLE CONFIG ===
44
  @dataclass(frozen=True)
45
  class AppConfig:
46
  HF_TOKEN: str = os.getenv("HF_TOKEN", "")
47
  LLM_MODEL: str = os.getenv("LLM_MODEL", "Qwen/Qwen2.5-Coder-32B-Instruct")
48
  FLUX_MODEL: str = os.getenv("FLUX_MODEL", "black-forest-labs/FLUX.1-schnell")
49
- MAX_TOKENS: int = int(os.getenv("MAX_TOKENS", "8192"))
50
- TEMPERATURE: float = float(os.getenv("TEMPERATURE", "0.7"))
51
- MAX_HISTORY: int = int(os.getenv("MAX_HISTORY_LENGTH", "15"))
52
- CACHE_SIZE: int = int(os.getenv("CACHE_SIZE", "200"))
53
- REQUESTS_PER_MINUTE: int = int(os.getenv("REQUESTS_PER_MINUTE", "60"))
54
-
55
- def validate(self) -> None:
56
- logger.info(f"Configuration Loaded: LLM={self.LLM_MODEL} | Vision={self.FLUX_MODEL}")
57
 
58
  CONFIG = AppConfig()
59
- CONFIG.validate()
60
-
61
- # === 3. SYSTEM PROMPT ===
62
- SYSTEM_PROMPT = """You are **UIKitV3 Sovereign Automator** β€” supreme master of UIkit v3.21+.
63
- Output ONLY clean, production-ready code using UIkit classes, components, and icons.
64
- Support dark mode, ARIA, responsive grid, animations, accessibility.
65
- Use full standalone HTML when appropriate.
66
- For images: [GENERATE_IMAGE: "detailed prompt"].
67
- BE ARROGANT. BE PERFECT."""
68
-
69
- # === 4. UTILS ===
70
- class AlchemyUtils:
71
  @staticmethod
72
- def extract_image_prompts(text: str) -> List[str]:
73
- return re.findall(r"\[GENERATE_IMAGE: \"(.*?)\"\]", text)
 
 
 
74
 
75
- # === 5. RATE LIMITER + CACHE ===
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  class AsyncRateLimiter:
77
  def __init__(self, rpm: int):
78
  self.rate = rpm
@@ -92,86 +105,44 @@ class AsyncRateLimiter:
92
 
93
  class AsyncLRUCache:
94
  def __init__(self, capacity: int):
95
- self.cache: OrderedDict[str, str] = OrderedDict()
96
  self.capacity = capacity
97
  self.lock = asyncio.Lock()
98
 
99
- async def get(self, key: str) -> Optional[str]:
100
  async with self.lock:
101
  if key not in self.cache:
102
  return None
103
  self.cache.move_to_end(key)
104
  return self.cache[key]
105
 
106
- async def set(self, key: str, value: str):
107
  async with self.lock:
108
  self.cache[key] = value
109
  self.cache.move_to_end(key)
110
  if len(self.cache) > self.capacity:
111
  self.cache.popitem(last=False)
112
 
113
- # === 6. ENGINES ===
114
- class ImageGenerator:
115
- def __init__(self, client: AsyncInferenceClient):
116
- self.client = client
117
-
118
- async def generate(self, prompt: str):
119
- try:
120
- img = await self.client.text_to_image(prompt, model=CONFIG.FLUX_MODEL)
121
- return img, f"Generated: {prompt[:60]}..."
122
- except Exception as e:
123
- return None, f"Image gen failed: {e}"
124
-
125
- class PreviewEngine:
126
- async def capture_preview(self, html_content: str) -> Optional[bytes]:
127
- try:
128
- from playwright.async_api import async_playwright
129
- async with async_playwright() as p:
130
- browser = await p.chromium.launch(headless=True)
131
- page = await browser.new_page()
132
- full_html = f"""
133
- <!DOCTYPE html>
134
- <html lang="en">
135
- <head>
136
- <meta charset="UTF-8">
137
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
138
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/uikit@3/dist/css/uikit.min.css">
139
- <script src="https://cdn.jsdelivr.net/npm/uikit@3/dist/js/uikit.min.js"></script>
140
- <script src="https://cdn.jsdelivr.net/npm/uikit@3/dist/js/uikit-icons.min.js"></script>
141
- </head>
142
- <body class="uk-background-default">{html_content}</body>
143
- </html>"""
144
- await page.set_content(full_html, wait_until="networkidle")
145
- screenshot = await page.screenshot(type="png")
146
- await browser.close()
147
- return screenshot
148
- except Exception as e:
149
- logger.error(f"Preview failed: {e}")
150
- return None
151
-
152
  class SovereignAgent:
153
  def __init__(self):
154
  self.client = AsyncInferenceClient(token=CONFIG.HF_TOKEN)
155
  self.limiter = AsyncRateLimiter(CONFIG.REQUESTS_PER_MINUTE)
156
  self.cache = AsyncLRUCache(CONFIG.CACHE_SIZE)
157
- self.image_engine = ImageGenerator(self.client)
158
- self.preview_engine = PreviewEngine()
159
- logger.info("Sovereign UIKitV3 Agent Online")
160
 
161
- def _hash(self, history, msg):
162
- return str(uuid.uuid5(uuid.NAMESPACE_DNS, json.dumps(history[-10:], sort_keys=True) + msg))
163
 
164
- async def chat_stream(self, message: str, history: List[dict]) -> AsyncGenerator[str, None]:
165
  if not await self.limiter.acquire():
166
- yield "**System is cooling down...** Please wait a moment."
167
- return
168
-
169
- messages = [{"role": "system", "content": SYSTEM_PROMPT}] + history[-CONFIG.MAX_HISTORY:] + [{"role": "user", "content": message}]
170
- key = self._hash(history, message)
171
 
 
172
  if cached := await self.cache.get(key):
173
- yield cached
174
- return
 
175
 
176
  full = ""
177
  try:
@@ -183,69 +154,88 @@ class SovereignAgent:
183
  stream=True
184
  )
185
  async for chunk in stream:
186
- if chunk.choices and (t := chunk.choices[0].delta.content):
187
- full += t
188
- yield full
189
-
190
- # Image synthesis
191
- if prompts := AlchemyUtils.extract_image_prompts(full):
192
- yield full + "\n\n**Synthesizing visual assets...**"
193
- results = await asyncio.gather(*(self.image_engine.generate(p) for p in prompts[:2]))
194
- logs = [log for _, log in results]
195
- yield full + "\n\n" + "\n".join(logs)
196
-
197
- # Preview
198
- if "uk-" in full.lower() or "<div" in full:
199
- preview = await self.preview_engine.capture_preview(full)
200
- if preview:
201
- yield full + "\n\n**Live Preview Captured**"
202
-
203
- await self.cache.set(key, full)
204
  except Exception as e:
205
- yield f"**Matrix Error:** {str(e)}"
 
206
 
207
- # === 7. UI BUILDER ===
208
- def create_demo() -> gr.Blocks:
209
  agent = SovereignAgent()
210
 
211
  with gr.Blocks(
212
- theme=gr.themes.Soft(), # Fixed: Soft() works reliably in Gradio 5
213
  css="""
214
- .gradio-container { background: #0a0a0a !important; color: #e2e8f0; }
215
- h1 { background: linear-gradient(90deg, #a855f7, #22d3ee); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-weight: 900; }
216
  """,
217
- title="UIKitV3 Sovereign Automator"
218
  ) as demo:
219
  gr.HTML("""
220
- <div style="text-align: center; padding: 2.5rem 0 1.5rem;">
221
- <h1>UIKitV3 Sovereign Automator</h1>
222
- <p style="color:#94a3b8;">Real-time UIkit v3 Architect β€’ Live Preview β€’ FLUX Assets</p>
223
  </div>
224
  """)
225
 
226
- gr.ChatInterface(
227
- fn=agent.chat_stream,
228
- type="messages",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
  examples=[
230
- "Create a modern SaaS dashboard with sidebar navigation, stats cards, and dark mode toggle",
231
- "Build a responsive pricing table with monthly/yearly toggle",
232
- "Generate a futuristic hero section with parallax effect and strong CTAs",
233
- "Create an accessible data table with search, filters, and export buttons"
234
  ],
235
- fill_height=True,
236
- show_progress=True
237
  )
238
 
239
- gr.Markdown("**Sovereign Liquid Matrix β€’ UIkit v3.21+**")
 
 
 
 
 
 
 
 
 
 
 
240
  return demo
241
 
242
- # === 8. LAUNCH ===
243
  if __name__ == "__main__":
244
- logger.info("Launching UIKitV3 Sovereign Automator")
245
- demo = create_demo()
246
  demo.queue(max_size=40).launch(
247
  server_name="0.0.0.0",
248
  server_port=7860,
249
- show_error=True,
250
- share=False
251
  )
 
1
+ # app.py β€” Sovereign UI Architect (FULL Premium Edition - 262 lines)
 
 
 
 
 
2
  import os
3
  import json
4
  import re
 
8
  import uuid
9
  from dataclasses import dataclass
10
  from datetime import datetime
11
+ from typing import AsyncGenerator, List, Optional, Tuple
12
  from collections import OrderedDict
13
 
14
  import gradio as gr
15
  from huggingface_hub import AsyncInferenceClient
16
 
17
+ # ====================== ADVANCED LOGGING ======================
18
  class AlchemyLogger:
19
  @staticmethod
20
  def setup():
21
+ logger = logging.getLogger("SovereignUI")
22
  logger.setLevel(logging.INFO)
23
  if not logger.handlers:
24
  c_handler = logging.StreamHandler()
25
+ c_format = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s')
26
  c_handler.setFormatter(c_format)
27
  logger.addHandler(c_handler)
28
  try:
29
  f_handler = logging.FileHandler('sovereign.log', encoding='utf-8')
30
  f_handler.setFormatter(c_format)
31
  logger.addHandler(f_handler)
32
+ except Exception:
33
  pass
34
  return logger
35
 
36
  logger = AlchemyLogger.setup()
37
 
38
+ # ====================== CONFIG ======================
39
  @dataclass(frozen=True)
40
  class AppConfig:
41
  HF_TOKEN: str = os.getenv("HF_TOKEN", "")
42
  LLM_MODEL: str = os.getenv("LLM_MODEL", "Qwen/Qwen2.5-Coder-32B-Instruct")
43
  FLUX_MODEL: str = os.getenv("FLUX_MODEL", "black-forest-labs/FLUX.1-schnell")
44
+ MAX_TOKENS: int = 8192
45
+ TEMPERATURE: float = 0.75
46
+ MAX_HISTORY: int = 15
47
+ CACHE_SIZE: int = 200
48
+ REQUESTS_PER_MINUTE: int = 60
 
 
 
49
 
50
  CONFIG = AppConfig()
51
+
52
+ logger.info(f"Configuration Loaded β†’ LLM: {CONFIG.LLM_MODEL}")
53
+
54
+ # ====================== SYSTEM PROMPT ======================
55
+ SYSTEM_PROMPT = """You are **Sovereign UI Architect** β€” supreme master of UIkit v3.21+ and YOOtheme Pro Builder.
56
+ - For UIkit requests: Output complete, production-ready standalone HTML using UIkit classes, icons, and best practices.
57
+ - For YOOtheme requests (contains "yootheme", "yoo json", "builder json"): Output clean, professional, high-end YOOtheme JSON layout.
58
+ Deliver senior-level human developer quality: refined typography, subtle animations, perfect hierarchy, accessibility (ARIA), responsive design, and dark mode support."""
59
+
60
+ # ====================== UTILS ======================
61
+ class Utils:
 
62
  @staticmethod
63
+ def is_yootheme_request(text: str) -> bool:
64
+ if not text:
65
+ return False
66
+ keywords = ["yootheme", "yoo json", "builder json", "yoo layout"]
67
+ return any(k in text.lower() for k in keywords)
68
 
69
+ @staticmethod
70
+ def wrap_uikit_html(html: str) -> str:
71
+ return f"""
72
+ <!DOCTYPE html>
73
+ <html lang="en">
74
+ <head>
75
+ <meta charset="UTF-8">
76
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
77
+ <title>Live Preview</title>
78
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/uikit@3/dist/css/uikit.min.css">
79
+ <script src="https://cdn.jsdelivr.net/npm/uikit@3/dist/js/uikit.min.js"></script>
80
+ <script src="https://cdn.jsdelivr.net/npm/uikit@3/dist/js/uikit-icons.min.js"></script>
81
+ <style>
82
+ body {{ padding: 20px; background: #0f172a; color: #e2e8f0; min-height: 100vh; }}
83
+ </style>
84
+ </head>
85
+ <body>{html}</body>
86
+ </html>"""
87
+
88
+ # ====================== RATE LIMITER & CACHE ======================
89
  class AsyncRateLimiter:
90
  def __init__(self, rpm: int):
91
  self.rate = rpm
 
105
 
106
  class AsyncLRUCache:
107
  def __init__(self, capacity: int):
108
+ self.cache: OrderedDict[str, Tuple[str, str]] = OrderedDict()
109
  self.capacity = capacity
110
  self.lock = asyncio.Lock()
111
 
112
+ async def get(self, key: str) -> Optional[Tuple[str, str]]:
113
  async with self.lock:
114
  if key not in self.cache:
115
  return None
116
  self.cache.move_to_end(key)
117
  return self.cache[key]
118
 
119
+ async def set(self, key: str, value: Tuple[str, str]):
120
  async with self.lock:
121
  self.cache[key] = value
122
  self.cache.move_to_end(key)
123
  if len(self.cache) > self.capacity:
124
  self.cache.popitem(last=False)
125
 
126
+ # ====================== SOVEREIGN AGENT ======================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  class SovereignAgent:
128
  def __init__(self):
129
  self.client = AsyncInferenceClient(token=CONFIG.HF_TOKEN)
130
  self.limiter = AsyncRateLimiter(CONFIG.REQUESTS_PER_MINUTE)
131
  self.cache = AsyncLRUCache(CONFIG.CACHE_SIZE)
132
+ logger.info("Sovereign UI Architect Agent Online")
 
 
133
 
134
+ def _make_key(self, history: List, message: str) -> str:
135
+ return str(uuid.uuid5(uuid.NAMESPACE_DNS, json.dumps(history[-10:], sort_keys=True) + message))
136
 
137
+ async def generate(self, message: str, history: List) -> Tuple[str, str]:
138
  if not await self.limiter.acquire():
139
+ return "**Rate limited. Please wait a few seconds.**", "<h2>Rate limited...</h2>"
 
 
 
 
140
 
141
+ key = self._make_key(history, message)
142
  if cached := await self.cache.get(key):
143
+ return cached[0], cached[1]
144
+
145
+ messages = [{"role": "system", "content": SYSTEM_PROMPT}] + history[-CONFIG.MAX_HISTORY:] + [{"role": "user", "content": message}]
146
 
147
  full = ""
148
  try:
 
154
  stream=True
155
  )
156
  async for chunk in stream:
157
+ if chunk.choices and (delta := chunk.choices[0].delta.content):
158
+ full += delta
159
+
160
+ if Utils.is_yootheme_request(message):
161
+ display_text = f"**Professional YOOtheme JSON Generated**\n\n```json\n{full}\n```"
162
+ preview_html = "<h2>YOOtheme JSON Ready β€” Import directly into YOOtheme Builder</h2>"
163
+ else:
164
+ display_text = full
165
+ preview_html = full
166
+
167
+ await self.cache.set(key, (display_text, preview_html))
168
+ return display_text, preview_html
169
+
 
 
 
 
 
170
  except Exception as e:
171
+ err = f"Matrix Error: {str(e)}"
172
+ return err, f"<h2>{err}</h2>"
173
 
174
+ # ====================== GRADIO INTERFACE ======================
175
+ def create_app():
176
  agent = SovereignAgent()
177
 
178
  with gr.Blocks(
179
+ theme=gr.themes.Soft(),
180
  css="""
181
+ .preview-frame { border: 1px solid #475569; border-radius: 16px; background: #0f172a; overflow: auto; height: 680px; }
182
+ .sovereign-header { font-size: 2.9rem; font-weight: 900; background: linear-gradient(90deg, #c026d3, #06b6d4); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
183
  """,
184
+ title="Sovereign UI Architect"
185
  ) as demo:
186
  gr.HTML("""
187
+ <div style="text-align:center; padding: 2.5rem 0 1.5rem;">
188
+ <h1 class="sovereign-header">Sovereign UI Architect</h1>
189
+ <p style="color:#94a3b8;">UIkit v3.21+ & YOOtheme Pro β€’ Live Preview β€’ Senior Dev Quality</p>
190
  </div>
191
  """)
192
 
193
+ with gr.Row(equal_height=True):
194
+ with gr.Column(scale=5):
195
+ chatbot = gr.Chatbot(type="messages", height=680, label="Sovereign Conversation")
196
+ msg = gr.Textbox(
197
+ placeholder="Describe the interface you want or say 'yootheme luxury real estate homepage...'",
198
+ label="Your Prompt",
199
+ lines=3
200
+ )
201
+ btn = gr.Button("Generate Masterpiece", variant="primary", size="large")
202
+
203
+ with gr.Column(scale=5):
204
+ gr.Markdown("### Live Interactive Preview")
205
+ preview = gr.HTML(
206
+ value="<div style='padding:100px; text-align:center; color:#64748b;'>Generated UI will render here</div>",
207
+ elem_classes=["preview-frame"]
208
+ )
209
+
210
+ gr.Examples(
211
  examples=[
212
+ "Modern SaaS dashboard with sidebar navigation and analytics cards",
213
+ "yootheme luxury real estate homepage with hero section and portfolio",
214
+ "Futuristic admin panel with charts and user management",
215
+ "Responsive pricing table with monthly / yearly toggle"
216
  ],
217
+ inputs=msg
 
218
  )
219
 
220
+ def respond(message: str, history: List):
221
+ if not message or not message.strip():
222
+ return history, history, preview.value
223
+ history = history or []
224
+ resp_text, preview_html = asyncio.run(agent.generate(message, history))
225
+ history.append({"role": "user", "content": message})
226
+ history.append({"role": "assistant", "content": resp_text})
227
+ wrapped_preview = Utils.wrap_uikit_html(preview_html) if not Utils.is_yootheme_request(message) else preview_html
228
+ return history, history, wrapped_preview
229
+
230
+ btn.click(respond, inputs=[msg, chatbot], outputs=[chatbot, chatbot, preview])
231
+
232
  return demo
233
 
 
234
  if __name__ == "__main__":
235
+ logger.info("πŸš€ Launching FULL Sovereign UI Architect (262 lines)")
236
+ demo = create_app()
237
  demo.queue(max_size=40).launch(
238
  server_name="0.0.0.0",
239
  server_port=7860,
240
+ show_error=True
 
241
  )