Spaces:
Sleeping
Sleeping
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,603 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Design System Extractor v2 — Main Application
|
| 3 |
-
==============================================
|
| 4 |
-
|
| 5 |
-
Flow:
|
| 6 |
-
1. User enters URL
|
| 7 |
-
2. Agent 1 discovers pages → User confirms
|
| 8 |
-
3. Agent 1 extracts tokens (Desktop + Mobile)
|
| 9 |
-
4. Agent 2 normalizes tokens
|
| 10 |
-
5. Stage 1 UI: User reviews tokens (accept/reject, Desktop↔Mobile toggle)
|
| 11 |
-
6. Agent 3 proposes upgrades
|
| 12 |
-
7. Stage 2 UI: User selects options with live preview
|
| 13 |
-
8. Agent 4 generates JSON
|
| 14 |
-
9. Stage 3 UI: User exports
|
| 15 |
-
"""
|
| 16 |
-
|
| 17 |
-
import os
|
| 18 |
-
import asyncio
|
| 19 |
-
import json
|
| 20 |
-
import gradio as gr
|
| 21 |
-
from datetime import datetime
|
| 22 |
-
from typing import Optional
|
| 23 |
-
|
| 24 |
-
# Get HF token from environment
|
| 25 |
-
HF_TOKEN_FROM_ENV = os.getenv("HF_TOKEN", "")
|
| 26 |
-
|
| 27 |
-
# =============================================================================
|
| 28 |
-
# GLOBAL STATE
|
| 29 |
-
# =============================================================================
|
| 30 |
-
|
| 31 |
-
class AppState:
|
| 32 |
-
"""Global application state."""
|
| 33 |
-
def __init__(self):
|
| 34 |
-
self.reset()
|
| 35 |
-
|
| 36 |
-
def reset(self):
|
| 37 |
-
self.discovered_pages = []
|
| 38 |
-
self.base_url = ""
|
| 39 |
-
self.desktop_raw = None # ExtractedTokens
|
| 40 |
-
self.mobile_raw = None # ExtractedTokens
|
| 41 |
-
self.desktop_normalized = None # NormalizedTokens
|
| 42 |
-
self.mobile_normalized = None # NormalizedTokens
|
| 43 |
-
self.logs = []
|
| 44 |
-
|
| 45 |
-
def log(self, message: str):
|
| 46 |
-
timestamp = datetime.now().strftime("%H:%M:%S")
|
| 47 |
-
self.logs.append(f"[{timestamp}] {message}")
|
| 48 |
-
if len(self.logs) > 100:
|
| 49 |
-
self.logs.pop(0)
|
| 50 |
-
|
| 51 |
-
def get_logs(self) -> str:
|
| 52 |
-
return "\n".join(self.logs)
|
| 53 |
-
|
| 54 |
-
state = AppState()
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
# =============================================================================
|
| 58 |
-
# LAZY IMPORTS
|
| 59 |
-
# =============================================================================
|
| 60 |
-
|
| 61 |
-
def get_crawler():
|
| 62 |
-
import agents.crawler
|
| 63 |
-
return agents.crawler
|
| 64 |
-
|
| 65 |
-
def get_extractor():
|
| 66 |
-
import agents.extractor
|
| 67 |
-
return agents.extractor
|
| 68 |
-
|
| 69 |
-
def get_normalizer():
|
| 70 |
-
import agents.normalizer
|
| 71 |
-
return agents.normalizer
|
| 72 |
-
|
| 73 |
-
def get_schema():
|
| 74 |
-
import core.token_schema
|
| 75 |
-
return core.token_schema
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
# =============================================================================
|
| 79 |
-
# PHASE 1: DISCOVER PAGES
|
| 80 |
-
# =============================================================================
|
| 81 |
-
|
| 82 |
-
async def discover_pages(url: str, progress=gr.Progress()):
|
| 83 |
-
"""Discover pages from URL."""
|
| 84 |
-
state.reset()
|
| 85 |
-
|
| 86 |
-
if not url or not url.startswith(("http://", "https://")):
|
| 87 |
-
return "❌ Please enter a valid URL", "", None
|
| 88 |
-
|
| 89 |
-
state.log(f"🚀 Starting discovery for: {url}")
|
| 90 |
-
progress(0.1, desc="🔍 Discovering pages...")
|
| 91 |
-
|
| 92 |
-
try:
|
| 93 |
-
crawler = get_crawler()
|
| 94 |
-
discoverer = crawler.PageDiscoverer()
|
| 95 |
-
|
| 96 |
-
pages = await discoverer.discover(url)
|
| 97 |
-
|
| 98 |
-
state.discovered_pages = pages
|
| 99 |
-
state.base_url = url
|
| 100 |
-
|
| 101 |
-
state.log(f"✅ Found {len(pages)} pages")
|
| 102 |
-
|
| 103 |
-
# Format for display
|
| 104 |
-
pages_data = []
|
| 105 |
-
for page in pages:
|
| 106 |
-
pages_data.append([
|
| 107 |
-
True, # Selected by default
|
| 108 |
-
page.url,
|
| 109 |
-
page.title if page.title else "(No title)",
|
| 110 |
-
page.page_type.value,
|
| 111 |
-
"✓" if not page.error else f"⚠ {page.error}"
|
| 112 |
-
])
|
| 113 |
-
|
| 114 |
-
progress(1.0, desc="✅ Discovery complete!")
|
| 115 |
-
|
| 116 |
-
status = f"✅ Found {len(pages)} pages. Review and click 'Extract Tokens' to continue."
|
| 117 |
-
|
| 118 |
-
return status, state.get_logs(), pages_data
|
| 119 |
-
|
| 120 |
-
except Exception as e:
|
| 121 |
-
import traceback
|
| 122 |
-
state.log(f"❌ Error: {str(e)}")
|
| 123 |
-
return f"❌ Error: {str(e)}", state.get_logs(), None
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
# =============================================================================
|
| 127 |
-
# PHASE 2: EXTRACT TOKENS
|
| 128 |
-
# =============================================================================
|
| 129 |
-
|
| 130 |
-
async def extract_tokens(pages_data, progress=gr.Progress()):
|
| 131 |
-
"""Extract tokens from selected pages (both viewports)."""
|
| 132 |
-
|
| 133 |
-
state.log(f"📥 Received pages_data type: {type(pages_data)}")
|
| 134 |
-
|
| 135 |
-
if pages_data is None:
|
| 136 |
-
return "❌ Please discover pages first", state.get_logs(), None, None
|
| 137 |
-
|
| 138 |
-
# Get selected URLs - handle pandas DataFrame
|
| 139 |
-
selected_urls = []
|
| 140 |
-
|
| 141 |
-
try:
|
| 142 |
-
# Check if it's a pandas DataFrame
|
| 143 |
-
if hasattr(pages_data, 'iterrows'):
|
| 144 |
-
state.log(f"📥 DataFrame with {len(pages_data)} rows, columns: {list(pages_data.columns)}")
|
| 145 |
-
|
| 146 |
-
for idx, row in pages_data.iterrows():
|
| 147 |
-
# Get values by column name or position
|
| 148 |
-
try:
|
| 149 |
-
# Try column names first
|
| 150 |
-
is_selected = row.get('Select', row.iloc[0] if len(row) > 0 else False)
|
| 151 |
-
url = row.get('URL', row.iloc[1] if len(row) > 1 else '')
|
| 152 |
-
except:
|
| 153 |
-
# Fallback to positional
|
| 154 |
-
is_selected = row.iloc[0] if len(row) > 0 else False
|
| 155 |
-
url = row.iloc[1] if len(row) > 1 else ''
|
| 156 |
-
|
| 157 |
-
if is_selected and url:
|
| 158 |
-
selected_urls.append(url)
|
| 159 |
-
|
| 160 |
-
# If it's a dict (Gradio sometimes sends this)
|
| 161 |
-
elif isinstance(pages_data, dict):
|
| 162 |
-
state.log(f"📥 Dict with keys: {list(pages_data.keys())}")
|
| 163 |
-
data = pages_data.get('data', [])
|
| 164 |
-
for row in data:
|
| 165 |
-
if isinstance(row, (list, tuple)) and len(row) >= 2 and row[0]:
|
| 166 |
-
selected_urls.append(row[1])
|
| 167 |
-
|
| 168 |
-
# If it's a list
|
| 169 |
-
elif isinstance(pages_data, (list, tuple)):
|
| 170 |
-
state.log(f"📥 List with {len(pages_data)} items")
|
| 171 |
-
for row in pages_data:
|
| 172 |
-
if isinstance(row, (list, tuple)) and len(row) >= 2 and row[0]:
|
| 173 |
-
selected_urls.append(row[1])
|
| 174 |
-
|
| 175 |
-
except Exception as e:
|
| 176 |
-
state.log(f"❌ Error parsing pages_data: {str(e)}")
|
| 177 |
-
import traceback
|
| 178 |
-
state.log(traceback.format_exc())
|
| 179 |
-
|
| 180 |
-
state.log(f"📋 Found {len(selected_urls)} selected URLs")
|
| 181 |
-
|
| 182 |
-
# If still no URLs, try using stored discovered pages
|
| 183 |
-
if not selected_urls and state.discovered_pages:
|
| 184 |
-
state.log("⚠️ No URLs from table, using all discovered pages")
|
| 185 |
-
selected_urls = [p.url for p in state.discovered_pages if not p.error][:10]
|
| 186 |
-
|
| 187 |
-
if not selected_urls:
|
| 188 |
-
return "❌ No pages selected. Please select pages or rediscover.", state.get_logs(), None, None
|
| 189 |
-
|
| 190 |
-
# Limit to 10 pages for performance
|
| 191 |
-
selected_urls = selected_urls[:10]
|
| 192 |
-
|
| 193 |
-
state.log(f"📋 Extracting from {len(selected_urls)} pages:")
|
| 194 |
-
for url in selected_urls[:3]:
|
| 195 |
-
state.log(f" • {url}")
|
| 196 |
-
if len(selected_urls) > 3:
|
| 197 |
-
state.log(f" ... and {len(selected_urls) - 3} more")
|
| 198 |
-
|
| 199 |
-
progress(0.05, desc="🚀 Starting extraction...")
|
| 200 |
-
|
| 201 |
-
try:
|
| 202 |
-
schema = get_schema()
|
| 203 |
-
extractor_mod = get_extractor()
|
| 204 |
-
normalizer_mod = get_normalizer()
|
| 205 |
-
|
| 206 |
-
# === DESKTOP EXTRACTION ===
|
| 207 |
-
state.log("")
|
| 208 |
-
state.log("🖥️ DESKTOP EXTRACTION (1440px)")
|
| 209 |
-
progress(0.1, desc="🖥️ Extracting desktop tokens...")
|
| 210 |
-
|
| 211 |
-
desktop_extractor = extractor_mod.TokenExtractor(viewport=schema.Viewport.DESKTOP)
|
| 212 |
-
|
| 213 |
-
def desktop_progress(p):
|
| 214 |
-
progress(0.1 + (p * 0.35), desc=f"🖥️ Desktop... {int(p*100)}%")
|
| 215 |
-
|
| 216 |
-
state.desktop_raw = await desktop_extractor.extract(selected_urls, progress_callback=desktop_progress)
|
| 217 |
-
|
| 218 |
-
state.log(f" Raw: {len(state.desktop_raw.colors)} colors, {len(state.desktop_raw.typography)} typography, {len(state.desktop_raw.spacing)} spacing")
|
| 219 |
-
|
| 220 |
-
# Normalize desktop
|
| 221 |
-
state.log(" Normalizing...")
|
| 222 |
-
state.desktop_normalized = normalizer_mod.normalize_tokens(state.desktop_raw)
|
| 223 |
-
state.log(f" Normalized: {len(state.desktop_normalized.colors)} colors, {len(state.desktop_normalized.typography)} typography, {len(state.desktop_normalized.spacing)} spacing")
|
| 224 |
-
|
| 225 |
-
# === MOBILE EXTRACTION ===
|
| 226 |
-
state.log("")
|
| 227 |
-
state.log("📱 MOBILE EXTRACTION (375px)")
|
| 228 |
-
progress(0.5, desc="📱 Extracting mobile tokens...")
|
| 229 |
-
|
| 230 |
-
mobile_extractor = extractor_mod.TokenExtractor(viewport=schema.Viewport.MOBILE)
|
| 231 |
-
|
| 232 |
-
def mobile_progress(p):
|
| 233 |
-
progress(0.5 + (p * 0.35), desc=f"📱 Mobile... {int(p*100)}%")
|
| 234 |
-
|
| 235 |
-
state.mobile_raw = await mobile_extractor.extract(selected_urls, progress_callback=mobile_progress)
|
| 236 |
-
|
| 237 |
-
state.log(f" Raw: {len(state.mobile_raw.colors)} colors, {len(state.mobile_raw.typography)} typography, {len(state.mobile_raw.spacing)} spacing")
|
| 238 |
-
|
| 239 |
-
# Normalize mobile
|
| 240 |
-
state.log(" Normalizing...")
|
| 241 |
-
state.mobile_normalized = normalizer_mod.normalize_tokens(state.mobile_raw)
|
| 242 |
-
state.log(f" Normalized: {len(state.mobile_normalized.colors)} colors, {len(state.mobile_normalized.typography)} typography, {len(state.mobile_normalized.spacing)} spacing")
|
| 243 |
-
|
| 244 |
-
progress(0.95, desc="📊 Preparing results...")
|
| 245 |
-
|
| 246 |
-
# Format results for Stage 1 UI
|
| 247 |
-
desktop_data = format_tokens_for_display(state.desktop_normalized)
|
| 248 |
-
mobile_data = format_tokens_for_display(state.mobile_normalized)
|
| 249 |
-
|
| 250 |
-
state.log("")
|
| 251 |
-
state.log("=" * 50)
|
| 252 |
-
state.log("✅ EXTRACTION COMPLETE!")
|
| 253 |
-
state.log("=" * 50)
|
| 254 |
-
|
| 255 |
-
progress(1.0, desc="✅ Complete!")
|
| 256 |
-
|
| 257 |
-
status = f"""## ✅ Extraction Complete!
|
| 258 |
-
|
| 259 |
-
| Viewport | Colors | Typography | Spacing |
|
| 260 |
-
|----------|--------|------------|---------|
|
| 261 |
-
| Desktop | {len(state.desktop_normalized.colors)} | {len(state.desktop_normalized.typography)} | {len(state.desktop_normalized.spacing)} |
|
| 262 |
-
| Mobile | {len(state.mobile_normalized.colors)} | {len(state.mobile_normalized.typography)} | {len(state.mobile_normalized.spacing)} |
|
| 263 |
-
|
| 264 |
-
**Next:** Review the tokens below. Accept or reject, then proceed to Stage 2.
|
| 265 |
-
"""
|
| 266 |
-
|
| 267 |
-
return status, state.get_logs(), desktop_data, mobile_data
|
| 268 |
-
|
| 269 |
-
except Exception as e:
|
| 270 |
-
import traceback
|
| 271 |
-
state.log(f"❌ Error: {str(e)}")
|
| 272 |
-
state.log(traceback.format_exc())
|
| 273 |
-
return f"❌ Error: {str(e)}", state.get_logs(), None, None
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
def format_tokens_for_display(normalized) -> dict:
|
| 277 |
-
"""Format normalized tokens for Gradio display."""
|
| 278 |
-
if normalized is None:
|
| 279 |
-
return {"colors": [], "typography": [], "spacing": []}
|
| 280 |
-
|
| 281 |
-
colors = []
|
| 282 |
-
for c in normalized.colors[:50]:
|
| 283 |
-
colors.append([
|
| 284 |
-
True, # Accept checkbox
|
| 285 |
-
c.value,
|
| 286 |
-
c.suggested_name or "",
|
| 287 |
-
c.frequency,
|
| 288 |
-
c.confidence.value if c.confidence else "medium",
|
| 289 |
-
f"{c.contrast_white:.1f}:1" if c.contrast_white else "N/A",
|
| 290 |
-
"✓" if c.wcag_aa_small_text else "✗",
|
| 291 |
-
", ".join(c.contexts[:2]) if c.contexts else "",
|
| 292 |
-
])
|
| 293 |
-
|
| 294 |
-
typography = []
|
| 295 |
-
for t in normalized.typography[:30]:
|
| 296 |
-
typography.append([
|
| 297 |
-
True, # Accept checkbox
|
| 298 |
-
t.font_family,
|
| 299 |
-
t.font_size,
|
| 300 |
-
str(t.font_weight),
|
| 301 |
-
t.line_height or "",
|
| 302 |
-
t.suggested_name or "",
|
| 303 |
-
t.frequency,
|
| 304 |
-
t.confidence.value if t.confidence else "medium",
|
| 305 |
-
])
|
| 306 |
-
|
| 307 |
-
spacing = []
|
| 308 |
-
for s in normalized.spacing[:20]:
|
| 309 |
-
spacing.append([
|
| 310 |
-
True, # Accept checkbox
|
| 311 |
-
s.value,
|
| 312 |
-
f"{s.value_px}px",
|
| 313 |
-
s.suggested_name or "",
|
| 314 |
-
s.frequency,
|
| 315 |
-
"✓" if s.fits_base_8 else "",
|
| 316 |
-
s.confidence.value if s.confidence else "medium",
|
| 317 |
-
])
|
| 318 |
-
|
| 319 |
-
return {
|
| 320 |
-
"colors": colors,
|
| 321 |
-
"typography": typography,
|
| 322 |
-
"spacing": spacing,
|
| 323 |
-
}
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
def switch_viewport(viewport: str):
|
| 327 |
-
"""Switch between desktop and mobile view."""
|
| 328 |
-
if viewport == "Desktop (1440px)":
|
| 329 |
-
data = format_tokens_for_display(state.desktop_normalized)
|
| 330 |
-
else:
|
| 331 |
-
data = format_tokens_for_display(state.mobile_normalized)
|
| 332 |
-
|
| 333 |
-
return data["colors"], data["typography"], data["spacing"]
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
# =============================================================================
|
| 337 |
-
# STAGE 3: EXPORT
|
| 338 |
-
# =============================================================================
|
| 339 |
-
|
| 340 |
-
def export_tokens_json():
|
| 341 |
-
"""Export tokens to JSON."""
|
| 342 |
-
result = {
|
| 343 |
-
"metadata": {
|
| 344 |
-
"source_url": state.base_url,
|
| 345 |
-
"extracted_at": datetime.now().isoformat(),
|
| 346 |
-
"version": "v1-extracted",
|
| 347 |
-
},
|
| 348 |
-
"desktop": None,
|
| 349 |
-
"mobile": None,
|
| 350 |
-
}
|
| 351 |
-
|
| 352 |
-
if state.desktop_normalized:
|
| 353 |
-
result["desktop"] = {
|
| 354 |
-
"colors": [
|
| 355 |
-
{"value": c.value, "name": c.suggested_name, "frequency": c.frequency,
|
| 356 |
-
"confidence": c.confidence.value if c.confidence else "medium"}
|
| 357 |
-
for c in state.desktop_normalized.colors
|
| 358 |
-
],
|
| 359 |
-
"typography": [
|
| 360 |
-
{"font_family": t.font_family, "font_size": t.font_size,
|
| 361 |
-
"font_weight": t.font_weight, "line_height": t.line_height,
|
| 362 |
-
"name": t.suggested_name, "frequency": t.frequency}
|
| 363 |
-
for t in state.desktop_normalized.typography
|
| 364 |
-
],
|
| 365 |
-
"spacing": [
|
| 366 |
-
{"value": s.value, "value_px": s.value_px, "name": s.suggested_name,
|
| 367 |
-
"frequency": s.frequency, "fits_base_8": s.fits_base_8}
|
| 368 |
-
for s in state.desktop_normalized.spacing
|
| 369 |
-
],
|
| 370 |
-
}
|
| 371 |
-
|
| 372 |
-
if state.mobile_normalized:
|
| 373 |
-
result["mobile"] = {
|
| 374 |
-
"colors": [
|
| 375 |
-
{"value": c.value, "name": c.suggested_name, "frequency": c.frequency,
|
| 376 |
-
"confidence": c.confidence.value if c.confidence else "medium"}
|
| 377 |
-
for c in state.mobile_normalized.colors
|
| 378 |
-
],
|
| 379 |
-
"typography": [
|
| 380 |
-
{"font_family": t.font_family, "font_size": t.font_size,
|
| 381 |
-
"font_weight": t.font_weight, "line_height": t.line_height,
|
| 382 |
-
"name": t.suggested_name, "frequency": t.frequency}
|
| 383 |
-
for t in state.mobile_normalized.typography
|
| 384 |
-
],
|
| 385 |
-
"spacing": [
|
| 386 |
-
{"value": s.value, "value_px": s.value_px, "name": s.suggested_name,
|
| 387 |
-
"frequency": s.frequency, "fits_base_8": s.fits_base_8}
|
| 388 |
-
for s in state.mobile_normalized.spacing
|
| 389 |
-
],
|
| 390 |
-
}
|
| 391 |
-
|
| 392 |
-
return json.dumps(result, indent=2, default=str)
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
# =============================================================================
|
| 396 |
-
# UI BUILDING
|
| 397 |
-
# =============================================================================
|
| 398 |
-
|
| 399 |
-
def create_ui():
|
| 400 |
-
"""Create the Gradio interface."""
|
| 401 |
-
|
| 402 |
-
with gr.Blocks(
|
| 403 |
-
title="Design System Extractor v2",
|
| 404 |
-
theme=gr.themes.Soft(),
|
| 405 |
-
css="""
|
| 406 |
-
.color-swatch { display: inline-block; width: 24px; height: 24px; border-radius: 4px; margin-right: 8px; vertical-align: middle; }
|
| 407 |
-
"""
|
| 408 |
-
) as app:
|
| 409 |
-
|
| 410 |
-
gr.Markdown("""
|
| 411 |
-
# 🎨 Design System Extractor v2
|
| 412 |
-
|
| 413 |
-
**Reverse-engineer design systems from live websites.**
|
| 414 |
-
|
| 415 |
-
A semi-automated, human-in-the-loop system that extracts, normalizes, and upgrades design tokens.
|
| 416 |
-
|
| 417 |
-
---
|
| 418 |
-
""")
|
| 419 |
-
|
| 420 |
-
# =================================================================
|
| 421 |
-
# CONFIGURATION
|
| 422 |
-
# =================================================================
|
| 423 |
-
|
| 424 |
-
with gr.Accordion("⚙️ Configuration", open=not bool(HF_TOKEN_FROM_ENV)):
|
| 425 |
-
gr.Markdown("**HuggingFace Token** — Required for Stage 2 (AI upgrades)")
|
| 426 |
-
with gr.Row():
|
| 427 |
-
hf_token_input = gr.Textbox(
|
| 428 |
-
label="HF Token", placeholder="hf_xxxx", type="password",
|
| 429 |
-
scale=4, value=HF_TOKEN_FROM_ENV,
|
| 430 |
-
)
|
| 431 |
-
save_token_btn = gr.Button("💾 Save", scale=1)
|
| 432 |
-
token_status = gr.Markdown("✅ Token loaded" if HF_TOKEN_FROM_ENV else "⏳ Enter token")
|
| 433 |
-
|
| 434 |
-
def save_token(token):
|
| 435 |
-
if token and len(token) > 10:
|
| 436 |
-
os.environ["HF_TOKEN"] = token.strip()
|
| 437 |
-
return "✅ Token saved!"
|
| 438 |
-
return "❌ Invalid token"
|
| 439 |
-
|
| 440 |
-
save_token_btn.click(save_token, [hf_token_input], [token_status])
|
| 441 |
-
|
| 442 |
-
# =================================================================
|
| 443 |
-
# URL INPUT & PAGE DISCOVERY
|
| 444 |
-
# =================================================================
|
| 445 |
-
|
| 446 |
-
with gr.Accordion("🔍 Step 1: Discover Pages", open=True):
|
| 447 |
-
gr.Markdown("Enter your website URL to discover pages for extraction.")
|
| 448 |
-
|
| 449 |
-
with gr.Row():
|
| 450 |
-
url_input = gr.Textbox(label="Website URL", placeholder="https://example.com", scale=4)
|
| 451 |
-
discover_btn = gr.Button("🔍 Discover Pages", variant="primary", scale=1)
|
| 452 |
-
|
| 453 |
-
discover_status = gr.Markdown("")
|
| 454 |
-
|
| 455 |
-
with gr.Row():
|
| 456 |
-
log_output = gr.Textbox(label="📋 Log", lines=8, interactive=False)
|
| 457 |
-
|
| 458 |
-
pages_table = gr.Dataframe(
|
| 459 |
-
headers=["Select", "URL", "Title", "Type", "Status"],
|
| 460 |
-
datatype=["bool", "str", "str", "str", "str"],
|
| 461 |
-
label="Discovered Pages",
|
| 462 |
-
interactive=True,
|
| 463 |
-
visible=False,
|
| 464 |
-
)
|
| 465 |
-
|
| 466 |
-
extract_btn = gr.Button("🚀 Extract Tokens (Desktop + Mobile)", variant="primary", visible=False)
|
| 467 |
-
|
| 468 |
-
# =================================================================
|
| 469 |
-
# STAGE 1: EXTRACTION REVIEW
|
| 470 |
-
# =================================================================
|
| 471 |
-
|
| 472 |
-
with gr.Accordion("📊 Stage 1: Review Extracted Tokens", open=False) as stage1_accordion:
|
| 473 |
-
|
| 474 |
-
extraction_status = gr.Markdown("")
|
| 475 |
-
|
| 476 |
-
gr.Markdown("""
|
| 477 |
-
**Review the extracted tokens.** Toggle between Desktop and Mobile viewports.
|
| 478 |
-
Accept or reject tokens, then proceed to Stage 2 for AI-powered upgrades.
|
| 479 |
-
""")
|
| 480 |
-
|
| 481 |
-
viewport_toggle = gr.Radio(
|
| 482 |
-
choices=["Desktop (1440px)", "Mobile (375px)"],
|
| 483 |
-
value="Desktop (1440px)",
|
| 484 |
-
label="Viewport",
|
| 485 |
-
)
|
| 486 |
-
|
| 487 |
-
with gr.Tabs():
|
| 488 |
-
with gr.Tab("🎨 Colors"):
|
| 489 |
-
colors_table = gr.Dataframe(
|
| 490 |
-
headers=["Accept", "Color", "Suggested Name", "Frequency", "Confidence", "Contrast", "AA", "Context"],
|
| 491 |
-
datatype=["bool", "str", "str", "number", "str", "str", "str", "str"],
|
| 492 |
-
label="Colors",
|
| 493 |
-
interactive=True,
|
| 494 |
-
)
|
| 495 |
-
|
| 496 |
-
with gr.Tab("📝 Typography"):
|
| 497 |
-
typography_table = gr.Dataframe(
|
| 498 |
-
headers=["Accept", "Font", "Size", "Weight", "Line Height", "Suggested Name", "Frequency", "Confidence"],
|
| 499 |
-
datatype=["bool", "str", "str", "str", "str", "str", "number", "str"],
|
| 500 |
-
label="Typography",
|
| 501 |
-
interactive=True,
|
| 502 |
-
)
|
| 503 |
-
|
| 504 |
-
with gr.Tab("📏 Spacing"):
|
| 505 |
-
spacing_table = gr.Dataframe(
|
| 506 |
-
headers=["Accept", "Value", "Pixels", "Suggested Name", "Frequency", "Base 8", "Confidence"],
|
| 507 |
-
datatype=["bool", "str", "str", "str", "number", "str", "str"],
|
| 508 |
-
label="Spacing",
|
| 509 |
-
interactive=True,
|
| 510 |
-
)
|
| 511 |
-
|
| 512 |
-
proceed_stage2_btn = gr.Button("➡️ Proceed to Stage 2: AI Upgrades", variant="primary")
|
| 513 |
-
|
| 514 |
-
# =================================================================
|
| 515 |
-
# STAGE 2: AI UPGRADES (Placeholder)
|
| 516 |
-
# =================================================================
|
| 517 |
-
|
| 518 |
-
with gr.Accordion("🧠 Stage 2: AI-Powered Upgrades (Coming Soon)", open=False):
|
| 519 |
-
gr.Markdown("""
|
| 520 |
-
**Agent 3 (Design System Advisor)** will analyze your tokens and propose:
|
| 521 |
-
|
| 522 |
-
- **Type Scale Options:** Choose from A/B/C (1.25, 1.333, 1.414 ratios)
|
| 523 |
-
- **Color Ramp Generation:** AA-compliant tints and shades
|
| 524 |
-
- **Spacing System:** Aligned to 8px base grid
|
| 525 |
-
- **Naming Conventions:** Semantic token names
|
| 526 |
-
|
| 527 |
-
Each option will show a **live preview** so you can see the changes before accepting.
|
| 528 |
-
|
| 529 |
-
*Requires HuggingFace token for LLM inference.*
|
| 530 |
-
""")
|
| 531 |
-
|
| 532 |
-
# =================================================================
|
| 533 |
-
# STAGE 3: EXPORT
|
| 534 |
-
# =================================================================
|
| 535 |
-
|
| 536 |
-
with gr.Accordion("📦 Stage 3: Export", open=False):
|
| 537 |
-
gr.Markdown("Export your design tokens to JSON (compatible with Figma Tokens Studio).")
|
| 538 |
-
|
| 539 |
-
export_btn = gr.Button("📥 Export JSON", variant="secondary")
|
| 540 |
-
export_output = gr.Code(label="Tokens JSON", language="json", lines=20)
|
| 541 |
-
|
| 542 |
-
export_btn.click(export_tokens_json, outputs=[export_output])
|
| 543 |
-
|
| 544 |
-
# =================================================================
|
| 545 |
-
# EVENT HANDLERS
|
| 546 |
-
# =================================================================
|
| 547 |
-
|
| 548 |
-
# Store data for viewport toggle
|
| 549 |
-
desktop_data = gr.State({})
|
| 550 |
-
mobile_data = gr.State({})
|
| 551 |
-
|
| 552 |
-
# Discover pages
|
| 553 |
-
discover_btn.click(
|
| 554 |
-
fn=discover_pages,
|
| 555 |
-
inputs=[url_input],
|
| 556 |
-
outputs=[discover_status, log_output, pages_table],
|
| 557 |
-
).then(
|
| 558 |
-
fn=lambda: (gr.update(visible=True), gr.update(visible=True)),
|
| 559 |
-
outputs=[pages_table, extract_btn],
|
| 560 |
-
)
|
| 561 |
-
|
| 562 |
-
# Extract tokens
|
| 563 |
-
extract_btn.click(
|
| 564 |
-
fn=extract_tokens,
|
| 565 |
-
inputs=[pages_table],
|
| 566 |
-
outputs=[extraction_status, log_output, desktop_data, mobile_data],
|
| 567 |
-
).then(
|
| 568 |
-
fn=lambda d: (d.get("colors", []), d.get("typography", []), d.get("spacing", [])),
|
| 569 |
-
inputs=[desktop_data],
|
| 570 |
-
outputs=[colors_table, typography_table, spacing_table],
|
| 571 |
-
).then(
|
| 572 |
-
fn=lambda: gr.update(open=True),
|
| 573 |
-
outputs=[stage1_accordion],
|
| 574 |
-
)
|
| 575 |
-
|
| 576 |
-
# Viewport toggle
|
| 577 |
-
viewport_toggle.change(
|
| 578 |
-
fn=switch_viewport,
|
| 579 |
-
inputs=[viewport_toggle],
|
| 580 |
-
outputs=[colors_table, typography_table, spacing_table],
|
| 581 |
-
)
|
| 582 |
-
|
| 583 |
-
# =================================================================
|
| 584 |
-
# FOOTER
|
| 585 |
-
# =================================================================
|
| 586 |
-
|
| 587 |
-
gr.Markdown("""
|
| 588 |
-
---
|
| 589 |
-
**Design System Extractor v2** | Built with Playwright + Gradio + LangGraph + HuggingFace
|
| 590 |
-
|
| 591 |
-
*A semi-automated co-pilot for design system recovery and modernization.*
|
| 592 |
-
""")
|
| 593 |
-
|
| 594 |
-
return app
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
# =============================================================================
|
| 598 |
-
# MAIN
|
| 599 |
-
# =============================================================================
|
| 600 |
-
|
| 601 |
-
if __name__ == "__main__":
|
| 602 |
-
app = create_ui()
|
| 603 |
-
app.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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