riazmo commited on
Commit
1a8a455
Β·
verified Β·
1 Parent(s): c512dca

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +596 -0
app.py ADDED
@@ -0,0 +1,596 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Debug: log the data structure
139
+ state.log(f"πŸ“₯ Data length: {len(pages_data) if hasattr(pages_data, '__len__') else 'N/A'}")
140
+ if hasattr(pages_data, '__len__') and len(pages_data) > 0:
141
+ state.log(f"πŸ“₯ First row type: {type(pages_data[0])}")
142
+ state.log(f"πŸ“₯ First row: {pages_data[0]}")
143
+
144
+ # Get selected URLs - handle multiple formats
145
+ selected_urls = []
146
+
147
+ # Try to iterate through the data
148
+ try:
149
+ # If it's a pandas DataFrame
150
+ if hasattr(pages_data, 'iterrows'):
151
+ for idx, row in pages_data.iterrows():
152
+ if row.iloc[0]: # First column is Select checkbox
153
+ selected_urls.append(row.iloc[1]) # Second column is URL
154
+ # If it's a list of lists/tuples
155
+ elif isinstance(pages_data, (list, tuple)):
156
+ for row in pages_data:
157
+ if isinstance(row, (list, tuple)) and len(row) >= 2:
158
+ # row[0] is Select, row[1] is URL
159
+ if row[0] == True or row[0] == "true" or row[0] == 1:
160
+ selected_urls.append(row[1])
161
+ elif isinstance(row, dict):
162
+ if row.get("Select") or row.get("select"):
163
+ selected_urls.append(row.get("URL") or row.get("url"))
164
+ # If it's a dict with 'data' key (Gradio format)
165
+ elif isinstance(pages_data, dict):
166
+ data = pages_data.get("data", pages_data)
167
+ for row in data:
168
+ if isinstance(row, (list, tuple)) and len(row) >= 2:
169
+ if row[0]:
170
+ selected_urls.append(row[1])
171
+ except Exception as e:
172
+ state.log(f"❌ Error parsing pages_data: {str(e)}")
173
+ import traceback
174
+ state.log(traceback.format_exc())
175
+
176
+ state.log(f"πŸ“‹ Found {len(selected_urls)} selected URLs")
177
+
178
+ # If still no URLs, try using stored discovered pages
179
+ if not selected_urls and state.discovered_pages:
180
+ state.log("⚠️ No URLs from table, using all discovered pages")
181
+ selected_urls = [p.url for p in state.discovered_pages if not p.error][:10]
182
+
183
+ if not selected_urls:
184
+ return "❌ No pages selected. Please select pages or rediscover.", state.get_logs(), None, None
185
+
186
+ state.log(f"πŸ“‹ Extracting from {len(selected_urls)} pages:")
187
+ for url in selected_urls[:3]:
188
+ state.log(f" β€’ {url}")
189
+ if len(selected_urls) > 3:
190
+ state.log(f" ... and {len(selected_urls) - 3} more")
191
+
192
+ progress(0.05, desc="πŸš€ Starting extraction...")
193
+
194
+ try:
195
+ schema = get_schema()
196
+ extractor_mod = get_extractor()
197
+ normalizer_mod = get_normalizer()
198
+
199
+ # === DESKTOP EXTRACTION ===
200
+ state.log("")
201
+ state.log("πŸ–₯️ DESKTOP EXTRACTION (1440px)")
202
+ progress(0.1, desc="πŸ–₯️ Extracting desktop tokens...")
203
+
204
+ desktop_extractor = extractor_mod.TokenExtractor(viewport=schema.Viewport.DESKTOP)
205
+
206
+ def desktop_progress(p):
207
+ progress(0.1 + (p * 0.35), desc=f"πŸ–₯️ Desktop... {int(p*100)}%")
208
+
209
+ state.desktop_raw = await desktop_extractor.extract(selected_urls, progress_callback=desktop_progress)
210
+
211
+ state.log(f" Raw: {len(state.desktop_raw.colors)} colors, {len(state.desktop_raw.typography)} typography, {len(state.desktop_raw.spacing)} spacing")
212
+
213
+ # Normalize desktop
214
+ state.log(" Normalizing...")
215
+ state.desktop_normalized = normalizer_mod.normalize_tokens(state.desktop_raw)
216
+ state.log(f" Normalized: {len(state.desktop_normalized.colors)} colors, {len(state.desktop_normalized.typography)} typography, {len(state.desktop_normalized.spacing)} spacing")
217
+
218
+ # === MOBILE EXTRACTION ===
219
+ state.log("")
220
+ state.log("πŸ“± MOBILE EXTRACTION (375px)")
221
+ progress(0.5, desc="πŸ“± Extracting mobile tokens...")
222
+
223
+ mobile_extractor = extractor_mod.TokenExtractor(viewport=schema.Viewport.MOBILE)
224
+
225
+ def mobile_progress(p):
226
+ progress(0.5 + (p * 0.35), desc=f"πŸ“± Mobile... {int(p*100)}%")
227
+
228
+ state.mobile_raw = await mobile_extractor.extract(selected_urls, progress_callback=mobile_progress)
229
+
230
+ state.log(f" Raw: {len(state.mobile_raw.colors)} colors, {len(state.mobile_raw.typography)} typography, {len(state.mobile_raw.spacing)} spacing")
231
+
232
+ # Normalize mobile
233
+ state.log(" Normalizing...")
234
+ state.mobile_normalized = normalizer_mod.normalize_tokens(state.mobile_raw)
235
+ state.log(f" Normalized: {len(state.mobile_normalized.colors)} colors, {len(state.mobile_normalized.typography)} typography, {len(state.mobile_normalized.spacing)} spacing")
236
+
237
+ progress(0.95, desc="πŸ“Š Preparing results...")
238
+
239
+ # Format results for Stage 1 UI
240
+ desktop_data = format_tokens_for_display(state.desktop_normalized)
241
+ mobile_data = format_tokens_for_display(state.mobile_normalized)
242
+
243
+ state.log("")
244
+ state.log("=" * 50)
245
+ state.log("βœ… EXTRACTION COMPLETE!")
246
+ state.log("=" * 50)
247
+
248
+ progress(1.0, desc="βœ… Complete!")
249
+
250
+ status = f"""## βœ… Extraction Complete!
251
+
252
+ | Viewport | Colors | Typography | Spacing |
253
+ |----------|--------|------------|---------|
254
+ | Desktop | {len(state.desktop_normalized.colors)} | {len(state.desktop_normalized.typography)} | {len(state.desktop_normalized.spacing)} |
255
+ | Mobile | {len(state.mobile_normalized.colors)} | {len(state.mobile_normalized.typography)} | {len(state.mobile_normalized.spacing)} |
256
+
257
+ **Next:** Review the tokens below. Accept or reject, then proceed to Stage 2.
258
+ """
259
+
260
+ return status, state.get_logs(), desktop_data, mobile_data
261
+
262
+ except Exception as e:
263
+ import traceback
264
+ state.log(f"❌ Error: {str(e)}")
265
+ state.log(traceback.format_exc())
266
+ return f"❌ Error: {str(e)}", state.get_logs(), None, None
267
+
268
+
269
+ def format_tokens_for_display(normalized) -> dict:
270
+ """Format normalized tokens for Gradio display."""
271
+ if normalized is None:
272
+ return {"colors": [], "typography": [], "spacing": []}
273
+
274
+ colors = []
275
+ for c in normalized.colors[:50]:
276
+ colors.append([
277
+ True, # Accept checkbox
278
+ c.value,
279
+ c.suggested_name or "",
280
+ c.frequency,
281
+ c.confidence.value if c.confidence else "medium",
282
+ f"{c.contrast_white:.1f}:1" if c.contrast_white else "N/A",
283
+ "βœ“" if c.wcag_aa_small_text else "βœ—",
284
+ ", ".join(c.contexts[:2]) if c.contexts else "",
285
+ ])
286
+
287
+ typography = []
288
+ for t in normalized.typography[:30]:
289
+ typography.append([
290
+ True, # Accept checkbox
291
+ t.font_family,
292
+ t.font_size,
293
+ str(t.font_weight),
294
+ t.line_height or "",
295
+ t.suggested_name or "",
296
+ t.frequency,
297
+ t.confidence.value if t.confidence else "medium",
298
+ ])
299
+
300
+ spacing = []
301
+ for s in normalized.spacing[:20]:
302
+ spacing.append([
303
+ True, # Accept checkbox
304
+ s.value,
305
+ f"{s.value_px}px",
306
+ s.suggested_name or "",
307
+ s.frequency,
308
+ "βœ“" if s.fits_base_8 else "",
309
+ s.confidence.value if s.confidence else "medium",
310
+ ])
311
+
312
+ return {
313
+ "colors": colors,
314
+ "typography": typography,
315
+ "spacing": spacing,
316
+ }
317
+
318
+
319
+ def switch_viewport(viewport: str):
320
+ """Switch between desktop and mobile view."""
321
+ if viewport == "Desktop (1440px)":
322
+ data = format_tokens_for_display(state.desktop_normalized)
323
+ else:
324
+ data = format_tokens_for_display(state.mobile_normalized)
325
+
326
+ return data["colors"], data["typography"], data["spacing"]
327
+
328
+
329
+ # =============================================================================
330
+ # STAGE 3: EXPORT
331
+ # =============================================================================
332
+
333
+ def export_tokens_json():
334
+ """Export tokens to JSON."""
335
+ result = {
336
+ "metadata": {
337
+ "source_url": state.base_url,
338
+ "extracted_at": datetime.now().isoformat(),
339
+ "version": "v1-extracted",
340
+ },
341
+ "desktop": None,
342
+ "mobile": None,
343
+ }
344
+
345
+ if state.desktop_normalized:
346
+ result["desktop"] = {
347
+ "colors": [
348
+ {"value": c.value, "name": c.suggested_name, "frequency": c.frequency,
349
+ "confidence": c.confidence.value if c.confidence else "medium"}
350
+ for c in state.desktop_normalized.colors
351
+ ],
352
+ "typography": [
353
+ {"font_family": t.font_family, "font_size": t.font_size,
354
+ "font_weight": t.font_weight, "line_height": t.line_height,
355
+ "name": t.suggested_name, "frequency": t.frequency}
356
+ for t in state.desktop_normalized.typography
357
+ ],
358
+ "spacing": [
359
+ {"value": s.value, "value_px": s.value_px, "name": s.suggested_name,
360
+ "frequency": s.frequency, "fits_base_8": s.fits_base_8}
361
+ for s in state.desktop_normalized.spacing
362
+ ],
363
+ }
364
+
365
+ if state.mobile_normalized:
366
+ result["mobile"] = {
367
+ "colors": [
368
+ {"value": c.value, "name": c.suggested_name, "frequency": c.frequency,
369
+ "confidence": c.confidence.value if c.confidence else "medium"}
370
+ for c in state.mobile_normalized.colors
371
+ ],
372
+ "typography": [
373
+ {"font_family": t.font_family, "font_size": t.font_size,
374
+ "font_weight": t.font_weight, "line_height": t.line_height,
375
+ "name": t.suggested_name, "frequency": t.frequency}
376
+ for t in state.mobile_normalized.typography
377
+ ],
378
+ "spacing": [
379
+ {"value": s.value, "value_px": s.value_px, "name": s.suggested_name,
380
+ "frequency": s.frequency, "fits_base_8": s.fits_base_8}
381
+ for s in state.mobile_normalized.spacing
382
+ ],
383
+ }
384
+
385
+ return json.dumps(result, indent=2, default=str)
386
+
387
+
388
+ # =============================================================================
389
+ # UI BUILDING
390
+ # =============================================================================
391
+
392
+ def create_ui():
393
+ """Create the Gradio interface."""
394
+
395
+ with gr.Blocks(
396
+ title="Design System Extractor v2",
397
+ theme=gr.themes.Soft(),
398
+ css="""
399
+ .color-swatch { display: inline-block; width: 24px; height: 24px; border-radius: 4px; margin-right: 8px; vertical-align: middle; }
400
+ """
401
+ ) as app:
402
+
403
+ gr.Markdown("""
404
+ # 🎨 Design System Extractor v2
405
+
406
+ **Reverse-engineer design systems from live websites.**
407
+
408
+ A semi-automated, human-in-the-loop system that extracts, normalizes, and upgrades design tokens.
409
+
410
+ ---
411
+ """)
412
+
413
+ # =================================================================
414
+ # CONFIGURATION
415
+ # =================================================================
416
+
417
+ with gr.Accordion("βš™οΈ Configuration", open=not bool(HF_TOKEN_FROM_ENV)):
418
+ gr.Markdown("**HuggingFace Token** β€” Required for Stage 2 (AI upgrades)")
419
+ with gr.Row():
420
+ hf_token_input = gr.Textbox(
421
+ label="HF Token", placeholder="hf_xxxx", type="password",
422
+ scale=4, value=HF_TOKEN_FROM_ENV,
423
+ )
424
+ save_token_btn = gr.Button("πŸ’Ύ Save", scale=1)
425
+ token_status = gr.Markdown("βœ… Token loaded" if HF_TOKEN_FROM_ENV else "⏳ Enter token")
426
+
427
+ def save_token(token):
428
+ if token and len(token) > 10:
429
+ os.environ["HF_TOKEN"] = token.strip()
430
+ return "βœ… Token saved!"
431
+ return "❌ Invalid token"
432
+
433
+ save_token_btn.click(save_token, [hf_token_input], [token_status])
434
+
435
+ # =================================================================
436
+ # URL INPUT & PAGE DISCOVERY
437
+ # =================================================================
438
+
439
+ with gr.Accordion("πŸ” Step 1: Discover Pages", open=True):
440
+ gr.Markdown("Enter your website URL to discover pages for extraction.")
441
+
442
+ with gr.Row():
443
+ url_input = gr.Textbox(label="Website URL", placeholder="https://example.com", scale=4)
444
+ discover_btn = gr.Button("πŸ” Discover Pages", variant="primary", scale=1)
445
+
446
+ discover_status = gr.Markdown("")
447
+
448
+ with gr.Row():
449
+ log_output = gr.Textbox(label="πŸ“‹ Log", lines=8, interactive=False)
450
+
451
+ pages_table = gr.Dataframe(
452
+ headers=["Select", "URL", "Title", "Type", "Status"],
453
+ datatype=["bool", "str", "str", "str", "str"],
454
+ label="Discovered Pages",
455
+ interactive=True,
456
+ visible=False,
457
+ )
458
+
459
+ extract_btn = gr.Button("πŸš€ Extract Tokens (Desktop + Mobile)", variant="primary", visible=False)
460
+
461
+ # =================================================================
462
+ # STAGE 1: EXTRACTION REVIEW
463
+ # =================================================================
464
+
465
+ with gr.Accordion("πŸ“Š Stage 1: Review Extracted Tokens", open=False) as stage1_accordion:
466
+
467
+ extraction_status = gr.Markdown("")
468
+
469
+ gr.Markdown("""
470
+ **Review the extracted tokens.** Toggle between Desktop and Mobile viewports.
471
+ Accept or reject tokens, then proceed to Stage 2 for AI-powered upgrades.
472
+ """)
473
+
474
+ viewport_toggle = gr.Radio(
475
+ choices=["Desktop (1440px)", "Mobile (375px)"],
476
+ value="Desktop (1440px)",
477
+ label="Viewport",
478
+ )
479
+
480
+ with gr.Tabs():
481
+ with gr.Tab("🎨 Colors"):
482
+ colors_table = gr.Dataframe(
483
+ headers=["Accept", "Color", "Suggested Name", "Frequency", "Confidence", "Contrast", "AA", "Context"],
484
+ datatype=["bool", "str", "str", "number", "str", "str", "str", "str"],
485
+ label="Colors",
486
+ interactive=True,
487
+ )
488
+
489
+ with gr.Tab("πŸ“ Typography"):
490
+ typography_table = gr.Dataframe(
491
+ headers=["Accept", "Font", "Size", "Weight", "Line Height", "Suggested Name", "Frequency", "Confidence"],
492
+ datatype=["bool", "str", "str", "str", "str", "str", "number", "str"],
493
+ label="Typography",
494
+ interactive=True,
495
+ )
496
+
497
+ with gr.Tab("πŸ“ Spacing"):
498
+ spacing_table = gr.Dataframe(
499
+ headers=["Accept", "Value", "Pixels", "Suggested Name", "Frequency", "Base 8", "Confidence"],
500
+ datatype=["bool", "str", "str", "str", "number", "str", "str"],
501
+ label="Spacing",
502
+ interactive=True,
503
+ )
504
+
505
+ proceed_stage2_btn = gr.Button("➑️ Proceed to Stage 2: AI Upgrades", variant="primary")
506
+
507
+ # =================================================================
508
+ # STAGE 2: AI UPGRADES (Placeholder)
509
+ # =================================================================
510
+
511
+ with gr.Accordion("🧠 Stage 2: AI-Powered Upgrades (Coming Soon)", open=False):
512
+ gr.Markdown("""
513
+ **Agent 3 (Design System Advisor)** will analyze your tokens and propose:
514
+
515
+ - **Type Scale Options:** Choose from A/B/C (1.25, 1.333, 1.414 ratios)
516
+ - **Color Ramp Generation:** AA-compliant tints and shades
517
+ - **Spacing System:** Aligned to 8px base grid
518
+ - **Naming Conventions:** Semantic token names
519
+
520
+ Each option will show a **live preview** so you can see the changes before accepting.
521
+
522
+ *Requires HuggingFace token for LLM inference.*
523
+ """)
524
+
525
+ # =================================================================
526
+ # STAGE 3: EXPORT
527
+ # =================================================================
528
+
529
+ with gr.Accordion("πŸ“¦ Stage 3: Export", open=False):
530
+ gr.Markdown("Export your design tokens to JSON (compatible with Figma Tokens Studio).")
531
+
532
+ export_btn = gr.Button("πŸ“₯ Export JSON", variant="secondary")
533
+ export_output = gr.Code(label="Tokens JSON", language="json", lines=20)
534
+
535
+ export_btn.click(export_tokens_json, outputs=[export_output])
536
+
537
+ # =================================================================
538
+ # EVENT HANDLERS
539
+ # =================================================================
540
+
541
+ # Store data for viewport toggle
542
+ desktop_data = gr.State({})
543
+ mobile_data = gr.State({})
544
+
545
+ # Discover pages
546
+ discover_btn.click(
547
+ fn=discover_pages,
548
+ inputs=[url_input],
549
+ outputs=[discover_status, log_output, pages_table],
550
+ ).then(
551
+ fn=lambda: (gr.update(visible=True), gr.update(visible=True)),
552
+ outputs=[pages_table, extract_btn],
553
+ )
554
+
555
+ # Extract tokens
556
+ extract_btn.click(
557
+ fn=extract_tokens,
558
+ inputs=[pages_table],
559
+ outputs=[extraction_status, log_output, desktop_data, mobile_data],
560
+ ).then(
561
+ fn=lambda d: (d.get("colors", []), d.get("typography", []), d.get("spacing", [])),
562
+ inputs=[desktop_data],
563
+ outputs=[colors_table, typography_table, spacing_table],
564
+ ).then(
565
+ fn=lambda: gr.update(open=True),
566
+ outputs=[stage1_accordion],
567
+ )
568
+
569
+ # Viewport toggle
570
+ viewport_toggle.change(
571
+ fn=switch_viewport,
572
+ inputs=[viewport_toggle],
573
+ outputs=[colors_table, typography_table, spacing_table],
574
+ )
575
+
576
+ # =================================================================
577
+ # FOOTER
578
+ # =================================================================
579
+
580
+ gr.Markdown("""
581
+ ---
582
+ **Design System Extractor v2** | Built with Playwright + Gradio + LangGraph + HuggingFace
583
+
584
+ *A semi-automated co-pilot for design system recovery and modernization.*
585
+ """)
586
+
587
+ return app
588
+
589
+
590
+ # =============================================================================
591
+ # MAIN
592
+ # =============================================================================
593
+
594
+ if __name__ == "__main__":
595
+ app = create_ui()
596
+ app.launch(server_name="0.0.0.0", server_port=7860)