sketch-to-ui / theme_engine.py
CyborgAB's picture
Upload folder using huggingface_hub
d420bb2 verified
Raw History Blame Contribute Delete
15 kB
"""
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