Spaces:
Running on Zero
Running on Zero
File size: 15,021 Bytes
d420bb2 | 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 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 | """
theme_engine.py β Prompt-based UI theme generation for UI-Genius.
Uses Google Gemini API to interpret natural language style prompts
and generate structured CSS theme dictionaries. Falls back to
keyword-matched preset themes if no API key is provided.
"""
import json
import re
import time
import gradio as gr
# βββ Default Theme (used when no prompt is given) βββββββββββββββββββββββββββββ
DEFAULT_THEME = {
"name": "Default Dark",
"colors": {
"bg_page": "#09090b",
"bg_card": "#09090b",
"bg_input": "#18181b",
"border": "#27272a",
"border_focus": "#3b82f6",
"text_primary": "#f4f4f5",
"text_secondary": "#a1a1aa",
"text_placeholder": "#52525b",
"accent": "#3b82f6",
"accent_hover": "#2563eb",
"button_text": "#ffffff",
},
"border_radius": "6px",
"font_family": "Inter, system-ui, sans-serif",
"style_notes": "Default dark zinc theme with blue accents",
}
# βββ Preset Themes (keyword-matched fallback) ββββββββββββββββββββββββββββββββ
PRESET_THEMES = {
"green": {
"name": "Professional Green",
"colors": {
"bg_page": "#021a02",
"bg_card": "#05200a",
"bg_input": "#0a2e10",
"border": "#14532d",
"border_focus": "#22c55e",
"text_primary": "#dcfce7",
"text_secondary": "#86efac",
"text_placeholder": "#3a7a4a",
"accent": "#22c55e",
"accent_hover": "#16a34a",
"button_text": "#ffffff",
},
"border_radius": "8px",
"font_family": "Inter, system-ui, sans-serif",
"style_notes": "Dark forest theme with vibrant green accents",
},
"blue": {
"name": "Modern Blue",
"colors": {
"bg_page": "#020617",
"bg_card": "#0f172a",
"bg_input": "#1e293b",
"border": "#334155",
"border_focus": "#3b82f6",
"text_primary": "#e2e8f0",
"text_secondary": "#94a3b8",
"text_placeholder": "#475569",
"accent": "#3b82f6",
"accent_hover": "#2563eb",
"button_text": "#ffffff",
},
"border_radius": "8px",
"font_family": "Inter, system-ui, sans-serif",
"style_notes": "Sleek slate-blue modern theme",
},
"red": {
"name": "Bold Red",
"colors": {
"bg_page": "#1a0505",
"bg_card": "#200a0a",
"bg_input": "#2e0f0f",
"border": "#7f1d1d",
"border_focus": "#ef4444",
"text_primary": "#fecaca",
"text_secondary": "#fca5a5",
"text_placeholder": "#7a3a3a",
"accent": "#ef4444",
"accent_hover": "#dc2626",
"button_text": "#ffffff",
},
"border_radius": "8px",
"font_family": "Inter, system-ui, sans-serif",
"style_notes": "Dark crimson theme with red accents",
},
"purple": {
"name": "Elegant Purple",
"colors": {
"bg_page": "#0d0520",
"bg_card": "#140a28",
"bg_input": "#1e1035",
"border": "#581c87",
"border_focus": "#a855f7",
"text_primary": "#e9d5ff",
"text_secondary": "#c084fc",
"text_placeholder": "#6b3fa0",
"accent": "#a855f7",
"accent_hover": "#9333ea",
"button_text": "#ffffff",
},
"border_radius": "10px",
"font_family": "'Outfit', system-ui, sans-serif",
"style_notes": "Rich violet/purple dark theme",
},
"orange": {
"name": "Warm Orange",
"colors": {
"bg_page": "#1a0f02",
"bg_card": "#201505",
"bg_input": "#2e1e0a",
"border": "#9a3412",
"border_focus": "#f97316",
"text_primary": "#fed7aa",
"text_secondary": "#fb923c",
"text_placeholder": "#7a5a3a",
"accent": "#f97316",
"accent_hover": "#ea580c",
"button_text": "#ffffff",
},
"border_radius": "8px",
"font_family": "Inter, system-ui, sans-serif",
"style_notes": "Warm sunset orange theme",
},
"cyberpunk": {
"name": "Cyberpunk Neon",
"colors": {
"bg_page": "#0a0a0a",
"bg_card": "#111111",
"bg_input": "#1a1a2e",
"border": "#e2007a",
"border_focus": "#00fff5",
"text_primary": "#00fff5",
"text_secondary": "#e2007a",
"text_placeholder": "#4a4a6a",
"accent": "#e2007a",
"accent_hover": "#ff1493",
"button_text": "#0a0a0a",
},
"border_radius": "2px",
"font_family": "'Roboto Mono', monospace",
"style_notes": "Neon cyberpunk with hot pink and cyan",
},
"minimal": {
"name": "Clean Minimal White",
"colors": {
"bg_page": "#fafafa",
"bg_card": "#ffffff",
"bg_input": "#f4f4f5",
"border": "#e4e4e7",
"border_focus": "#18181b",
"text_primary": "#18181b",
"text_secondary": "#52525b",
"text_placeholder": "#a1a1aa",
"accent": "#18181b",
"accent_hover": "#27272a",
"button_text": "#ffffff",
},
"border_radius": "6px",
"font_family": "Inter, system-ui, sans-serif",
"style_notes": "Light minimal theme with dark accents",
},
"corporate": {
"name": "Corporate Professional",
"colors": {
"bg_page": "#f8fafc",
"bg_card": "#ffffff",
"bg_input": "#f1f5f9",
"border": "#cbd5e1",
"border_focus": "#0369a1",
"text_primary": "#0f172a",
"text_secondary": "#475569",
"text_placeholder": "#94a3b8",
"accent": "#0284c7",
"accent_hover": "#0369a1",
"button_text": "#ffffff",
},
"border_radius": "6px",
"font_family": "'Roboto', system-ui, sans-serif",
"style_notes": "Professional corporate light theme",
},
"glassmorphism": {
"name": "Glassmorphism",
"colors": {
"bg_page": "#0f0f23",
"bg_card": "rgba(255, 255, 255, 0.05)",
"bg_input": "rgba(255, 255, 255, 0.08)",
"border": "rgba(255, 255, 255, 0.15)",
"border_focus": "#818cf8",
"text_primary": "#e0e7ff",
"text_secondary": "#a5b4fc",
"text_placeholder": "#6366a0",
"accent": "#818cf8",
"accent_hover": "#6366f1",
"button_text": "#ffffff",
},
"border_radius": "16px",
"font_family": "'Outfit', system-ui, sans-serif",
"style_notes": "Frosted glass effect with indigo accents",
},
"sunset": {
"name": "Sunset Gradient",
"colors": {
"bg_page": "#1a0a1e",
"bg_card": "#2d1035",
"bg_input": "#3a1540",
"border": "#6d2885",
"border_focus": "#f472b6",
"text_primary": "#fce7f3",
"text_secondary": "#f9a8d4",
"text_placeholder": "#8a4a6a",
"accent": "#f472b6",
"accent_hover": "#ec4899",
"button_text": "#ffffff",
},
"border_radius": "12px",
"font_family": "'Outfit', system-ui, sans-serif",
"style_notes": "Pink/purple sunset theme",
},
}
# βββ Keyword β Preset Mapping ββββββββββββββββββββββββββββββββββββββββββββββββ
KEYWORD_MAP = {
"green": "green",
"emerald": "green",
"forest": "green",
"nature": "green",
"eco": "green",
"blue": "blue",
"ocean": "blue",
"sky": "blue",
"marine": "blue",
"navy": "blue",
"red": "red",
"crimson": "red",
"ruby": "red",
"cherry": "red",
"purple": "purple",
"violet": "purple",
"lavender": "purple",
"plum": "purple",
"indigo": "purple",
"orange": "orange",
"amber": "orange",
"warm": "orange",
"sunset": "sunset",
"pink": "sunset",
"rose": "sunset",
"cyberpunk": "cyberpunk",
"neon": "cyberpunk",
"retro": "cyberpunk",
"hacker": "cyberpunk",
"minimal": "minimal",
"minimalist": "minimal",
"clean": "minimal",
"light": "minimal",
"white": "minimal",
"corporate": "corporate",
"professional": "corporate",
"business": "corporate",
"formal": "corporate",
"glass": "glassmorphism",
"glassmorphism": "glassmorphism",
"frosted": "glassmorphism",
"blur": "glassmorphism",
"translucent": "glassmorphism",
}
def _match_preset(prompt: str) -> dict | None:
"""Try to match a prompt to a preset theme by keyword."""
prompt_lower = prompt.lower()
# Check for exact preset name match first
for preset_key, preset_theme in PRESET_THEMES.items():
if preset_key in prompt_lower:
return preset_theme
# Then check keyword map
for keyword, preset_key in KEYWORD_MAP.items():
if keyword in prompt_lower:
return PRESET_THEMES[preset_key]
return None
# βββ Gemini System Prompt ββββββββββββββββββββββββββββββββββββββββββββββββββββ
GEMINI_SYSTEM_PROMPT = """You are a master UI/UX designer. Given a natural language description, generate a complete CSS color theme as a JSON object.
Your goal is to generate designs that WOW the user and feel extremely premium, innovative, and state-of-the-art.
RULES FOR PREMIUM AESTHETICS:
1. Avoid generic or flat colors. Use curated, sophisticated, and harmonious color palettes (e.g., sleek dark modes with subtle deep blue/purple undertones, or light modes with soft, warm off-whites).
2. The `bg_card` should contrast beautifully with `bg_page`.
3. The `border` should be subtle and elegant, not harsh.
4. The `border_focus` and `accent` colors must be highly vibrant and eye-catching to draw attention to interactive elements.
5. All colors must be valid CSS color values (hex like #1a2b3c, or rgba() for transparency effects).
6. Provide a highly modern font family (e.g., 'Inter', 'Outfit', 'Plus Jakarta Sans', or 'Space Grotesk').
Return ONLY a valid JSON object with this exact structure (no markdown, no explanation):
{
"name": "Theme Name",
"colors": {
"bg_page": "#hex",
"bg_card": "#hex",
"bg_input": "#hex",
"border": "#hex",
"border_focus": "#hex",
"text_primary": "#hex",
"text_secondary": "#hex",
"text_placeholder": "#hex",
"accent": "#hex",
"accent_hover": "#hex",
"button_text": "#hex"
},
"border_radius": "Npx",
"font_family": "Font Name, fallback",
"style_notes": "Brief description of the premium aesthetic"
}"""
def _generate_with_groq(prompt: str, api_key: str) -> dict | None:
"""Call Groq API to generate a theme from a natural language prompt."""
try:
from groq import Groq
client = Groq(api_key=api_key)
max_retries = 3
for attempt in range(max_retries):
try:
response = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=[
{"role": "system", "content": GEMINI_SYSTEM_PROMPT},
{"role": "user", "content": f"Generate a UI color theme for: {prompt}"}
],
response_format={"type": "json_object"},
temperature=0.7,
)
# Parse the JSON response
content = response.choices[0].message.content
theme = json.loads(content)
# Validate the required keys exist
required_color_keys = [
"bg_page", "bg_card", "bg_input", "border", "border_focus",
"text_primary", "text_secondary", "text_placeholder",
"accent", "accent_hover", "button_text",
]
if "colors" not in theme:
return None
for key in required_color_keys:
if key not in theme["colors"]:
return None
# Ensure optional keys have defaults
theme.setdefault("border_radius", "8px")
theme.setdefault("font_family", "Inter, system-ui, sans-serif")
theme.setdefault("style_notes", "AI-generated theme")
theme.setdefault("name", "AI Theme")
return theme
except Exception as e:
error_str = str(e)
if "429" in error_str or "rate_limit" in error_str.lower():
if attempt < max_retries - 1:
wait_time = 5
print(f"Groq API rate limit hit. Retrying in {wait_time}s... (Attempt {attempt+1}/{max_retries})")
try:
gr.Warning(f"Groq API rate limit hit. Pausing for {wait_time}s to retry theme generation...")
except:
pass
time.sleep(wait_time)
continue
raise e
except ImportError:
print("groq not installed. Falling back to preset themes.")
return None
except Exception as e:
print(f"Groq API error: {e}")
return None
def generate_theme(prompt: str = "", api_key: str = "") -> dict:
"""
Generate a UI theme from a natural language prompt.
Args:
prompt: Natural language description (e.g. "professional green colour")
api_key: Optional Gemini API key for AI-powered generation
Returns:
A theme dictionary with colors, border_radius, font_family, etc.
"""
# No prompt β default theme
if not prompt or not prompt.strip():
return DEFAULT_THEME
prompt = prompt.strip()
# 1. Try Groq API if key is provided
if api_key and api_key.strip():
theme = _generate_with_groq(prompt, api_key.strip())
if theme:
return theme
print("Groq API failed. Falling back to preset themes.")
# 2. Fall back to preset matching
preset = _match_preset(prompt)
if preset:
return preset
# 3. Final fallback β default theme
print(f"No preset matched for '{prompt}'. Using default theme.")
return DEFAULT_THEME
|