riazmo commited on
Commit
0c0c17c
·
verified ·
1 Parent(s): 45326f9

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -1725
app.py DELETED
@@ -1,1725 +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.upgrade_recommendations = None # UpgradeRecommendations
44
- self.selected_upgrades = {} # User selections
45
- self.logs = []
46
-
47
- def log(self, message: str):
48
- timestamp = datetime.now().strftime("%H:%M:%S")
49
- self.logs.append(f"[{timestamp}] {message}")
50
- if len(self.logs) > 100:
51
- self.logs.pop(0)
52
-
53
- def get_logs(self) -> str:
54
- return "\n".join(self.logs)
55
-
56
- state = AppState()
57
-
58
-
59
- # =============================================================================
60
- # LAZY IMPORTS
61
- # =============================================================================
62
-
63
- def get_crawler():
64
- import agents.crawler
65
- return agents.crawler
66
-
67
- def get_extractor():
68
- import agents.extractor
69
- return agents.extractor
70
-
71
- def get_normalizer():
72
- import agents.normalizer
73
- return agents.normalizer
74
-
75
- def get_advisor():
76
- import agents.advisor
77
- return agents.advisor
78
-
79
- def get_schema():
80
- import core.token_schema
81
- return core.token_schema
82
-
83
-
84
- # =============================================================================
85
- # PHASE 1: DISCOVER PAGES
86
- # =============================================================================
87
-
88
- async def discover_pages(url: str, progress=gr.Progress()):
89
- """Discover pages from URL."""
90
- state.reset()
91
-
92
- if not url or not url.startswith(("http://", "https://")):
93
- return "❌ Please enter a valid URL", "", None
94
-
95
- state.log(f"🚀 Starting discovery for: {url}")
96
- progress(0.1, desc="🔍 Discovering pages...")
97
-
98
- try:
99
- crawler = get_crawler()
100
- discoverer = crawler.PageDiscoverer()
101
-
102
- pages = await discoverer.discover(url)
103
-
104
- state.discovered_pages = pages
105
- state.base_url = url
106
-
107
- state.log(f"✅ Found {len(pages)} pages")
108
-
109
- # Format for display
110
- pages_data = []
111
- for page in pages:
112
- pages_data.append([
113
- True, # Selected by default
114
- page.url,
115
- page.title if page.title else "(No title)",
116
- page.page_type.value,
117
- "✓" if not page.error else f"⚠ {page.error}"
118
- ])
119
-
120
- progress(1.0, desc="✅ Discovery complete!")
121
-
122
- status = f"✅ Found {len(pages)} pages. Review and click 'Extract Tokens' to continue."
123
-
124
- return status, state.get_logs(), pages_data
125
-
126
- except Exception as e:
127
- import traceback
128
- state.log(f"❌ Error: {str(e)}")
129
- return f"❌ Error: {str(e)}", state.get_logs(), None
130
-
131
-
132
- # =============================================================================
133
- # PHASE 2: EXTRACT TOKENS
134
- # =============================================================================
135
-
136
- async def extract_tokens(pages_data, progress=gr.Progress()):
137
- """Extract tokens from selected pages (both viewports)."""
138
-
139
- state.log(f"📥 Received pages_data type: {type(pages_data)}")
140
-
141
- if pages_data is None:
142
- return "❌ Please discover pages first", state.get_logs(), None, None
143
-
144
- # Get selected URLs - handle pandas DataFrame
145
- selected_urls = []
146
-
147
- try:
148
- # Check if it's a pandas DataFrame
149
- if hasattr(pages_data, 'iterrows'):
150
- state.log(f"📥 DataFrame with {len(pages_data)} rows, columns: {list(pages_data.columns)}")
151
-
152
- for idx, row in pages_data.iterrows():
153
- # Get values by column name or position
154
- try:
155
- # Try column names first
156
- is_selected = row.get('Select', row.iloc[0] if len(row) > 0 else False)
157
- url = row.get('URL', row.iloc[1] if len(row) > 1 else '')
158
- except:
159
- # Fallback to positional
160
- is_selected = row.iloc[0] if len(row) > 0 else False
161
- url = row.iloc[1] if len(row) > 1 else ''
162
-
163
- if is_selected and url:
164
- selected_urls.append(url)
165
-
166
- # If it's a dict (Gradio sometimes sends this)
167
- elif isinstance(pages_data, dict):
168
- state.log(f"📥 Dict with keys: {list(pages_data.keys())}")
169
- data = pages_data.get('data', [])
170
- for row in data:
171
- if isinstance(row, (list, tuple)) and len(row) >= 2 and row[0]:
172
- selected_urls.append(row[1])
173
-
174
- # If it's a list
175
- elif isinstance(pages_data, (list, tuple)):
176
- state.log(f"📥 List with {len(pages_data)} items")
177
- for row in pages_data:
178
- if isinstance(row, (list, tuple)) and len(row) >= 2 and row[0]:
179
- selected_urls.append(row[1])
180
-
181
- except Exception as e:
182
- state.log(f"❌ Error parsing pages_data: {str(e)}")
183
- import traceback
184
- state.log(traceback.format_exc())
185
-
186
- state.log(f"📋 Found {len(selected_urls)} selected URLs")
187
-
188
- # If still no URLs, try using stored discovered pages
189
- if not selected_urls and state.discovered_pages:
190
- state.log("⚠️ No URLs from table, using all discovered pages")
191
- selected_urls = [p.url for p in state.discovered_pages if not p.error][:10]
192
-
193
- if not selected_urls:
194
- return "❌ No pages selected. Please select pages or rediscover.", state.get_logs(), None, None
195
-
196
- # Limit to 10 pages for performance
197
- selected_urls = selected_urls[:10]
198
-
199
- state.log(f"📋 Extracting from {len(selected_urls)} pages:")
200
- for url in selected_urls[:3]:
201
- state.log(f" • {url}")
202
- if len(selected_urls) > 3:
203
- state.log(f" ... and {len(selected_urls) - 3} more")
204
-
205
- progress(0.05, desc="🚀 Starting extraction...")
206
-
207
- try:
208
- schema = get_schema()
209
- extractor_mod = get_extractor()
210
- normalizer_mod = get_normalizer()
211
-
212
- # === DESKTOP EXTRACTION ===
213
- state.log("")
214
- state.log("🖥️ DESKTOP EXTRACTION (1440px)")
215
- progress(0.1, desc="🖥️ Extracting desktop tokens...")
216
-
217
- desktop_extractor = extractor_mod.TokenExtractor(viewport=schema.Viewport.DESKTOP)
218
-
219
- def desktop_progress(p):
220
- progress(0.1 + (p * 0.35), desc=f"🖥️ Desktop... {int(p*100)}%")
221
-
222
- state.desktop_raw = await desktop_extractor.extract(selected_urls, progress_callback=desktop_progress)
223
-
224
- state.log(f" Raw: {len(state.desktop_raw.colors)} colors, {len(state.desktop_raw.typography)} typography, {len(state.desktop_raw.spacing)} spacing")
225
-
226
- # Normalize desktop
227
- state.log(" Normalizing...")
228
- state.desktop_normalized = normalizer_mod.normalize_tokens(state.desktop_raw)
229
- state.log(f" Normalized: {len(state.desktop_normalized.colors)} colors, {len(state.desktop_normalized.typography)} typography, {len(state.desktop_normalized.spacing)} spacing")
230
-
231
- # === MOBILE EXTRACTION ===
232
- state.log("")
233
- state.log("📱 MOBILE EXTRACTION (375px)")
234
- progress(0.5, desc="📱 Extracting mobile tokens...")
235
-
236
- mobile_extractor = extractor_mod.TokenExtractor(viewport=schema.Viewport.MOBILE)
237
-
238
- def mobile_progress(p):
239
- progress(0.5 + (p * 0.35), desc=f"📱 Mobile... {int(p*100)}%")
240
-
241
- state.mobile_raw = await mobile_extractor.extract(selected_urls, progress_callback=mobile_progress)
242
-
243
- state.log(f" Raw: {len(state.mobile_raw.colors)} colors, {len(state.mobile_raw.typography)} typography, {len(state.mobile_raw.spacing)} spacing")
244
-
245
- # Normalize mobile
246
- state.log(" Normalizing...")
247
- state.mobile_normalized = normalizer_mod.normalize_tokens(state.mobile_raw)
248
- state.log(f" Normalized: {len(state.mobile_normalized.colors)} colors, {len(state.mobile_normalized.typography)} typography, {len(state.mobile_normalized.spacing)} spacing")
249
-
250
- progress(0.95, desc="📊 Preparing results...")
251
-
252
- # Format results for Stage 1 UI
253
- desktop_data = format_tokens_for_display(state.desktop_normalized)
254
- mobile_data = format_tokens_for_display(state.mobile_normalized)
255
-
256
- state.log("")
257
- state.log("=" * 50)
258
- state.log("✅ EXTRACTION COMPLETE!")
259
- state.log("=" * 50)
260
-
261
- progress(1.0, desc="✅ Complete!")
262
-
263
- status = f"""## ✅ Extraction Complete!
264
-
265
- | Viewport | Colors | Typography | Spacing |
266
- |----------|--------|------------|---------|
267
- | Desktop | {len(state.desktop_normalized.colors)} | {len(state.desktop_normalized.typography)} | {len(state.desktop_normalized.spacing)} |
268
- | Mobile | {len(state.mobile_normalized.colors)} | {len(state.mobile_normalized.typography)} | {len(state.mobile_normalized.spacing)} |
269
-
270
- **Next:** Review the tokens below. Accept or reject, then proceed to Stage 2.
271
- """
272
-
273
- return status, state.get_logs(), desktop_data, mobile_data
274
-
275
- except Exception as e:
276
- import traceback
277
- state.log(f"❌ Error: {str(e)}")
278
- state.log(traceback.format_exc())
279
- return f"❌ Error: {str(e)}", state.get_logs(), None, None
280
-
281
-
282
- def format_tokens_for_display(normalized) -> dict:
283
- """Format normalized tokens for Gradio display."""
284
- if normalized is None:
285
- return {"colors": [], "typography": [], "spacing": []}
286
-
287
- # Colors are now a dict
288
- colors = []
289
- color_items = list(normalized.colors.values()) if isinstance(normalized.colors, dict) else normalized.colors
290
- for c in sorted(color_items, key=lambda x: -x.frequency)[:50]:
291
- colors.append([
292
- True, # Accept checkbox
293
- c.value,
294
- c.suggested_name or "",
295
- c.frequency,
296
- c.confidence.value if c.confidence else "medium",
297
- f"{c.contrast_white:.1f}:1" if c.contrast_white else "N/A",
298
- "✓" if c.wcag_aa_small_text else "✗",
299
- ", ".join(c.contexts[:2]) if c.contexts else "",
300
- ])
301
-
302
- # Typography
303
- typography = []
304
- typo_items = list(normalized.typography.values()) if isinstance(normalized.typography, dict) else normalized.typography
305
- for t in sorted(typo_items, key=lambda x: -x.frequency)[:30]:
306
- typography.append([
307
- True, # Accept checkbox
308
- t.font_family,
309
- t.font_size,
310
- str(t.font_weight),
311
- t.line_height or "",
312
- t.suggested_name or "",
313
- t.frequency,
314
- t.confidence.value if t.confidence else "medium",
315
- ])
316
-
317
- # Spacing
318
- spacing = []
319
- spacing_items = list(normalized.spacing.values()) if isinstance(normalized.spacing, dict) else normalized.spacing
320
- for s in sorted(spacing_items, key=lambda x: x.value_px)[:20]:
321
- spacing.append([
322
- True, # Accept checkbox
323
- s.value,
324
- f"{s.value_px}px",
325
- s.suggested_name or "",
326
- s.frequency,
327
- "✓" if s.fits_base_8 else "",
328
- s.confidence.value if s.confidence else "medium",
329
- ])
330
-
331
- return {
332
- "colors": colors,
333
- "typography": typography,
334
- "spacing": spacing,
335
- }
336
-
337
-
338
- def switch_viewport(viewport: str):
339
- """Switch between desktop and mobile view."""
340
- if viewport == "Desktop (1440px)":
341
- data = format_tokens_for_display(state.desktop_normalized)
342
- else:
343
- data = format_tokens_for_display(state.mobile_normalized)
344
-
345
- return data["colors"], data["typography"], data["spacing"]
346
-
347
-
348
- # =============================================================================
349
- # STAGE 2: AI ANALYSIS (Multi-Agent)
350
- # =============================================================================
351
-
352
- async def run_stage2_analysis(competitors_str: str = "", progress=gr.Progress()):
353
- """Run multi-agent analysis on extracted tokens."""
354
-
355
- if not state.desktop_normalized or not state.mobile_normalized:
356
- return ("❌ Please complete Stage 1 first", "", "", "", None, None, None, "", "", "", "")
357
-
358
- # Parse competitors from input
359
- default_competitors = [
360
- "Material Design 3",
361
- "Apple Human Interface Guidelines",
362
- "Shopify Polaris",
363
- "IBM Carbon",
364
- "Atlassian Design System"
365
- ]
366
-
367
- if competitors_str and competitors_str.strip():
368
- competitors = [c.strip() for c in competitors_str.split(",") if c.strip()]
369
- else:
370
- competitors = default_competitors
371
-
372
- progress(0.05, desc="🤖 Initializing multi-agent analysis...")
373
-
374
- try:
375
- # Import the multi-agent workflow
376
- from agents.stage2_graph import run_stage2_multi_agent
377
-
378
- # Convert normalized tokens to dict for the workflow
379
- desktop_dict = normalized_to_dict(state.desktop_normalized)
380
- mobile_dict = normalized_to_dict(state.mobile_normalized)
381
-
382
- # Run multi-agent analysis
383
- progress(0.1, desc="🚀 Running parallel LLM analysis...")
384
-
385
- result = await run_stage2_multi_agent(
386
- desktop_tokens=desktop_dict,
387
- mobile_tokens=mobile_dict,
388
- competitors=competitors,
389
- log_callback=state.log,
390
- )
391
-
392
- progress(0.8, desc="📊 Processing results...")
393
-
394
- # Extract results
395
- final_recs = result.get("final_recommendations", {})
396
- llm1_analysis = result.get("llm1_analysis", {})
397
- llm2_analysis = result.get("llm2_analysis", {})
398
- rule_calculations = result.get("rule_calculations", {})
399
- cost_tracking = result.get("cost_tracking", {})
400
-
401
- # Store for later use
402
- state.upgrade_recommendations = final_recs
403
- state.multi_agent_result = result
404
-
405
- # Get font info
406
- fonts = get_detected_fonts()
407
- base_size = get_base_font_size()
408
-
409
- progress(0.9, desc="📊 Formatting results...")
410
-
411
- # Build status markdown
412
- status = build_analysis_status(final_recs, cost_tracking, result.get("errors", []))
413
-
414
- # Format brand/competitor comparison from LLM analyses
415
- brand_md = format_multi_agent_comparison(llm1_analysis, llm2_analysis, final_recs)
416
-
417
- # Format font families display
418
- font_families_md = format_font_families_display(fonts)
419
-
420
- # Format typography with BOTH desktop and mobile
421
- typography_desktop_data = format_typography_comparison_viewport(
422
- state.desktop_normalized, base_size, "desktop"
423
- )
424
- typography_mobile_data = format_typography_comparison_viewport(
425
- state.mobile_normalized, base_size, "mobile"
426
- )
427
-
428
- # Format spacing comparison table
429
- spacing_data = format_spacing_comparison_from_rules(rule_calculations)
430
-
431
- # Format color display: BASE colors + ramps separately
432
- base_colors_md = format_base_colors()
433
- color_ramps_md = format_color_ramps_from_rules(rule_calculations)
434
-
435
- # Format radius display (with token suggestions)
436
- radius_md = format_radius_with_tokens()
437
-
438
- # Format shadows display (with token suggestions)
439
- shadows_md = format_shadows_with_tokens()
440
-
441
- progress(1.0, desc="✅ Analysis complete!")
442
-
443
- return (status, state.get_logs(), brand_md, font_families_md,
444
- typography_desktop_data, typography_mobile_data, spacing_data,
445
- base_colors_md, color_ramps_md, radius_md, shadows_md)
446
-
447
- except Exception as e:
448
- import traceback
449
- state.log(f"❌ Error: {str(e)}")
450
- state.log(traceback.format_exc())
451
- return (f"❌ Analysis failed: {str(e)}", state.get_logs(), "", "", None, None, None, "", "", "", "")
452
-
453
-
454
- def normalized_to_dict(normalized) -> dict:
455
- """Convert NormalizedTokens to dict for workflow."""
456
- if not normalized:
457
- return {}
458
-
459
- result = {
460
- "colors": {},
461
- "typography": {},
462
- "spacing": {},
463
- "radius": {},
464
- "shadows": {},
465
- }
466
-
467
- # Colors
468
- for name, c in normalized.colors.items():
469
- result["colors"][name] = {
470
- "value": c.value,
471
- "frequency": c.frequency,
472
- "suggested_name": c.suggested_name,
473
- "contrast_white": c.contrast_white,
474
- "contrast_black": c.contrast_black,
475
- }
476
-
477
- # Typography
478
- for name, t in normalized.typography.items():
479
- result["typography"][name] = {
480
- "font_family": t.font_family,
481
- "font_size": t.font_size,
482
- "font_weight": t.font_weight,
483
- "line_height": t.line_height,
484
- "frequency": t.frequency,
485
- }
486
-
487
- # Spacing
488
- for name, s in normalized.spacing.items():
489
- result["spacing"][name] = {
490
- "value": s.value,
491
- "value_px": s.value_px,
492
- "frequency": s.frequency,
493
- }
494
-
495
- # Radius
496
- for name, r in normalized.radius.items():
497
- result["radius"][name] = {
498
- "value": r.value,
499
- "frequency": r.frequency,
500
- }
501
-
502
- # Shadows
503
- for name, s in normalized.shadows.items():
504
- result["shadows"][name] = {
505
- "value": s.value,
506
- "frequency": s.frequency,
507
- }
508
-
509
- return result
510
-
511
-
512
- def build_analysis_status(final_recs: dict, cost_tracking: dict, errors: list) -> str:
513
- """Build status markdown from analysis results."""
514
-
515
- lines = ["## 🧠 Multi-Agent Analysis Complete!"]
516
- lines.append("")
517
-
518
- # Cost summary
519
- if cost_tracking:
520
- total_cost = cost_tracking.get("total_cost", 0)
521
- lines.append(f"### 💰 Cost Summary")
522
- lines.append(f"**Total estimated cost:** ${total_cost:.4f}")
523
- lines.append(f"*(Free tier: $0.10/mo | Pro: $2.00/mo)*")
524
- lines.append("")
525
-
526
- # Final recommendations
527
- if final_recs and "final_recommendations" in final_recs:
528
- recs = final_recs["final_recommendations"]
529
- lines.append("### 📋 Recommendations")
530
-
531
- if recs.get("type_scale"):
532
- lines.append(f"**Type Scale:** {recs['type_scale']}")
533
- if recs.get("type_scale_rationale"):
534
- lines.append(f" *{recs['type_scale_rationale'][:100]}*")
535
-
536
- if recs.get("spacing_base"):
537
- lines.append(f"**Spacing:** {recs['spacing_base']}")
538
-
539
- lines.append("")
540
-
541
- # Summary
542
- if final_recs.get("summary"):
543
- lines.append("### 📝 Summary")
544
- lines.append(final_recs["summary"])
545
- lines.append("")
546
-
547
- # Confidence
548
- if final_recs.get("overall_confidence"):
549
- lines.append(f"**Confidence:** {final_recs['overall_confidence']}%")
550
-
551
- # Errors
552
- if errors:
553
- lines.append("")
554
- lines.append("### ⚠️ Warnings")
555
- for err in errors[:3]:
556
- lines.append(f"- {err[:100]}")
557
-
558
- return "\n".join(lines)
559
-
560
-
561
- def format_multi_agent_comparison(llm1: dict, llm2: dict, final: dict) -> str:
562
- """Format comparison from multi-agent analysis."""
563
-
564
- lines = ["### 📊 Multi-Agent Analysis Comparison"]
565
- lines.append("")
566
-
567
- # Agreements
568
- if final.get("agreements"):
569
- lines.append("#### ✅ Agreements (High Confidence)")
570
- for a in final["agreements"][:5]:
571
- topic = a.get("topic", "?")
572
- finding = a.get("finding", "?")[:80]
573
- lines.append(f"- **{topic}**: {finding}")
574
- lines.append("")
575
-
576
- # Disagreements and resolutions
577
- if final.get("disagreements"):
578
- lines.append("#### 🔄 Resolved Disagreements")
579
- for d in final["disagreements"][:3]:
580
- topic = d.get("topic", "?")
581
- resolution = d.get("resolution", "?")[:100]
582
- lines.append(f"- **{topic}**: {resolution}")
583
- lines.append("")
584
-
585
- # Score comparison
586
- lines.append("#### 📈 Score Comparison")
587
- lines.append("")
588
- lines.append("| Category | LLM 1 (Qwen) | LLM 2 (Llama) |")
589
- lines.append("|----------|--------------|---------------|")
590
-
591
- categories = ["typography", "colors", "accessibility", "spacing"]
592
- for cat in categories:
593
- llm1_score = llm1.get(cat, {}).get("score", "?") if isinstance(llm1.get(cat), dict) else "?"
594
- llm2_score = llm2.get(cat, {}).get("score", "?") if isinstance(llm2.get(cat), dict) else "?"
595
- lines.append(f"| {cat.title()} | {llm1_score}/10 | {llm2_score}/10 |")
596
-
597
- return "\n".join(lines)
598
-
599
-
600
- def format_spacing_comparison_from_rules(rule_calculations: dict) -> list:
601
- """Format spacing comparison from rule engine."""
602
- if not rule_calculations:
603
- return []
604
-
605
- spacing_options = rule_calculations.get("spacing_options", {})
606
-
607
- data = []
608
- for i in range(10):
609
- current = f"{(i+1) * 4}px" if i < 5 else f"{(i+1) * 8}px"
610
- grid_8 = spacing_options.get("8px", [])
611
- grid_4 = spacing_options.get("4px", [])
612
-
613
- val_8 = f"{grid_8[i+1]}px" if i+1 < len(grid_8) else "—"
614
- val_4 = f"{grid_4[i+1]}px" if i+1 < len(grid_4) else "—"
615
-
616
- data.append([current, val_8, val_4])
617
-
618
- return data
619
-
620
-
621
- def format_color_ramps_from_rules(rule_calculations: dict) -> str:
622
- """Format color ramps from rule engine."""
623
- if not rule_calculations:
624
- return "*No color ramps generated*"
625
-
626
- ramps = rule_calculations.get("color_ramps", {})
627
- if not ramps:
628
- return "*No color ramps generated*"
629
-
630
- lines = ["### 🌈 Generated Color Ramps"]
631
- lines.append("")
632
-
633
- for name, ramp in list(ramps.items())[:6]:
634
- lines.append(f"**{name}**")
635
- if isinstance(ramp, list) and len(ramp) >= 10:
636
- lines.append("| 50 | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 |")
637
- lines.append("|---|---|---|---|---|---|---|---|---|---|")
638
- row = "| " + " | ".join([f"`{ramp[i]}`" for i in range(10)]) + " |"
639
- lines.append(row)
640
- lines.append("")
641
-
642
- return "\n".join(lines)
643
-
644
-
645
- def get_detected_fonts() -> dict:
646
- """Get detected font information."""
647
- if not state.desktop_normalized:
648
- return {"primary": "Unknown", "weights": []}
649
-
650
- fonts = {}
651
- weights = set()
652
-
653
- for t in state.desktop_normalized.typography.values():
654
- family = t.font_family
655
- weight = t.font_weight
656
-
657
- if family not in fonts:
658
- fonts[family] = 0
659
- fonts[family] += t.frequency
660
-
661
- if weight:
662
- try:
663
- weights.add(int(weight))
664
- except:
665
- pass
666
-
667
- primary = max(fonts.items(), key=lambda x: x[1])[0] if fonts else "Unknown"
668
-
669
- return {
670
- "primary": primary,
671
- "weights": sorted(weights) if weights else [400],
672
- "all_fonts": fonts,
673
- }
674
-
675
-
676
- def get_base_font_size() -> int:
677
- """Detect base font size from typography."""
678
- if not state.desktop_normalized:
679
- return 16
680
-
681
- # Find most common size in body range (14-18px)
682
- sizes = {}
683
- for t in state.desktop_normalized.typography.values():
684
- size_str = str(t.font_size).replace('px', '').replace('rem', '').replace('em', '')
685
- try:
686
- size = float(size_str)
687
- if 14 <= size <= 18:
688
- sizes[size] = sizes.get(size, 0) + t.frequency
689
- except:
690
- pass
691
-
692
- if sizes:
693
- return int(max(sizes.items(), key=lambda x: x[1])[0])
694
- return 16
695
-
696
-
697
- def format_brand_comparison(recommendations) -> str:
698
- """Format brand comparison as markdown table."""
699
- if not recommendations.brand_analysis:
700
- return "*Brand analysis not available*"
701
-
702
- lines = [
703
- "### 📊 Design System Comparison (5 Top Brands)",
704
- "",
705
- "| Brand | Type Ratio | Base Size | Spacing | Notes |",
706
- "|-------|------------|-----------|---------|-------|",
707
- ]
708
-
709
- for brand in recommendations.brand_analysis[:5]:
710
- name = brand.get("brand", "Unknown")
711
- ratio = brand.get("ratio", "?")
712
- base = brand.get("base", "?")
713
- spacing = brand.get("spacing", "?")
714
- notes = brand.get("notes", "")[:50] + ("..." if len(brand.get("notes", "")) > 50 else "")
715
- lines.append(f"| {name} | {ratio} | {base}px | {spacing} | {notes} |")
716
-
717
- return "\n".join(lines)
718
-
719
-
720
- def format_font_families_display(fonts: dict) -> str:
721
- """Format detected font families for display."""
722
- lines = []
723
-
724
- primary = fonts.get("primary", "Unknown")
725
- weights = fonts.get("weights", [400])
726
- all_fonts = fonts.get("all_fonts", {})
727
-
728
- lines.append(f"### Primary Font: **{primary}**")
729
- lines.append("")
730
- lines.append(f"**Weights detected:** {', '.join(map(str, weights))}")
731
- lines.append("")
732
-
733
- if all_fonts and len(all_fonts) > 1:
734
- lines.append("### All Fonts Detected")
735
- lines.append("")
736
- lines.append("| Font Family | Usage Count |")
737
- lines.append("|-------------|-------------|")
738
-
739
- sorted_fonts = sorted(all_fonts.items(), key=lambda x: -x[1])
740
- for font, count in sorted_fonts[:5]:
741
- lines.append(f"| {font} | {count:,} |")
742
-
743
- lines.append("")
744
- lines.append("*Note: This analysis focuses on English typography only.*")
745
-
746
- return "\n".join(lines)
747
-
748
-
749
- def format_typography_comparison_viewport(normalized_tokens, base_size: int, viewport: str) -> list:
750
- """Format typography comparison for a specific viewport."""
751
- if not normalized_tokens:
752
- return []
753
-
754
- # Get current typography sorted by size
755
- current_typo = list(normalized_tokens.typography.values())
756
-
757
- # Parse and sort sizes
758
- def parse_size(t):
759
- size_str = str(t.font_size).replace('px', '').replace('rem', '').replace('em', '')
760
- try:
761
- return float(size_str)
762
- except:
763
- return 16
764
-
765
- current_typo.sort(key=lambda t: -parse_size(t))
766
- sizes = [parse_size(t) for t in current_typo]
767
-
768
- # Use detected base or default
769
- base = base_size if base_size else 16
770
-
771
- # Scale factors for mobile (typically 0.85-0.9 of desktop)
772
- mobile_factor = 0.875 if viewport == "mobile" else 1.0
773
-
774
- # Token names (13 levels)
775
- token_names = [
776
- "display.2xl", "display.xl", "display.lg", "display.md",
777
- "heading.xl", "heading.lg", "heading.md", "heading.sm",
778
- "body.lg", "body.md", "body.sm",
779
- "caption", "overline"
780
- ]
781
-
782
- # Generate scales - use base size and round to sensible values
783
- def round_to_even(val):
784
- """Round to even numbers for cleaner type scales."""
785
- return int(round(val / 2) * 2)
786
-
787
- scales = {
788
- "1.2": [round_to_even(base * mobile_factor * (1.2 ** (8-i))) for i in range(13)],
789
- "1.25": [round_to_even(base * mobile_factor * (1.25 ** (8-i))) for i in range(13)],
790
- "1.333": [round_to_even(base * mobile_factor * (1.333 ** (8-i))) for i in range(13)],
791
- }
792
-
793
- # Build comparison table
794
- data = []
795
- for i, name in enumerate(token_names):
796
- current = f"{int(sizes[i])}px" if i < len(sizes) else "—"
797
- s12 = f"{scales['1.2'][i]}px"
798
- s125 = f"{scales['1.25'][i]}px"
799
- s133 = f"{scales['1.333'][i]}px"
800
- keep = current
801
- data.append([name, current, s12, s125, s133, keep])
802
-
803
- return data
804
-
805
-
806
- def format_base_colors() -> str:
807
- """Format base colors (detected) separately from ramps."""
808
- if not state.desktop_normalized:
809
- return "*No colors detected*"
810
-
811
- colors = list(state.desktop_normalized.colors.values())
812
- colors.sort(key=lambda c: -c.frequency)
813
-
814
- lines = [
815
- "### 🎨 Base Colors (Detected)",
816
- "",
817
- "These are the primary colors extracted from your website:",
818
- "",
819
- "| Color | Hex | Role | Frequency | Contrast |",
820
- "|-------|-----|------|-----------|----------|",
821
- ]
822
-
823
- for color in colors[:10]:
824
- hex_val = color.value
825
- role = "Primary" if color.suggested_name and "primary" in color.suggested_name.lower() else \
826
- "Text" if color.suggested_name and "text" in color.suggested_name.lower() else \
827
- "Background" if color.suggested_name and "background" in color.suggested_name.lower() else \
828
- "Border" if color.suggested_name and "border" in color.suggested_name.lower() else \
829
- "Accent"
830
- freq = f"{color.frequency:,}"
831
- contrast = f"{color.contrast_white:.1f}:1" if color.contrast_white else "—"
832
-
833
- # Create a simple color indicator
834
- lines.append(f"| 🟦 | `{hex_val}` | {role} | {freq} | {contrast} |")
835
-
836
- return "\n".join(lines)
837
-
838
-
839
- def format_color_ramps_visual(recommendations) -> str:
840
- """Format color ramps with visual display showing all shades."""
841
- if not state.desktop_normalized:
842
- return "*No colors to display*"
843
-
844
- colors = list(state.desktop_normalized.colors.values())
845
- colors.sort(key=lambda c: -c.frequency)
846
-
847
- lines = [
848
- "### 🌈 Generated Color Ramps",
849
- "",
850
- "Full ramp (50-950) generated for each base color:",
851
- "",
852
- ]
853
-
854
- from core.color_utils import generate_color_ramp
855
-
856
- for color in colors[:6]: # Top 6 colors
857
- hex_val = color.value
858
- role = color.suggested_name.split('.')[1] if color.suggested_name and '.' in color.suggested_name else "color"
859
-
860
- # Generate ramp
861
- try:
862
- ramp = generate_color_ramp(hex_val)
863
-
864
- lines.append(f"**{role.upper()}** (base: `{hex_val}`)")
865
- lines.append("")
866
- lines.append("| 50 | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 |")
867
- lines.append("|---|---|---|---|---|---|---|---|---|---|")
868
-
869
- # Create row with hex values
870
- row = "|"
871
- for i in range(10):
872
- if i < len(ramp):
873
- row += f" `{ramp[i]}` |"
874
- else:
875
- row += " — |"
876
- lines.append(row)
877
- lines.append("")
878
-
879
- except Exception as e:
880
- lines.append(f"**{role}** (`{hex_val}`) — Could not generate ramp: {str(e)}")
881
- lines.append("")
882
-
883
- return "\n".join(lines)
884
-
885
-
886
- def format_radius_with_tokens() -> str:
887
- """Format radius with token name suggestions."""
888
- if not state.desktop_normalized or not state.desktop_normalized.radius:
889
- return "*No border radius values detected.*"
890
-
891
- radii = list(state.desktop_normalized.radius.values())
892
-
893
- lines = [
894
- "### 🔘 Border Radius Tokens",
895
- "",
896
- "| Detected | Suggested Token | Usage |",
897
- "|----------|-----------------|-------|",
898
- ]
899
-
900
- # Sort by pixel value
901
- def parse_radius(r):
902
- val = str(r.value).replace('px', '').replace('%', '')
903
- try:
904
- return float(val)
905
- except:
906
- return 999
907
-
908
- radii.sort(key=lambda r: parse_radius(r))
909
-
910
- token_map = {
911
- (0, 2): ("radius.none", "Sharp corners"),
912
- (2, 4): ("radius.xs", "Subtle rounding"),
913
- (4, 6): ("radius.sm", "Small elements"),
914
- (6, 10): ("radius.md", "Buttons, cards"),
915
- (10, 16): ("radius.lg", "Modals, panels"),
916
- (16, 32): ("radius.xl", "Large containers"),
917
- (32, 100): ("radius.2xl", "Pill shapes"),
918
- }
919
-
920
- for r in radii[:8]:
921
- val = str(r.value)
922
- px = parse_radius(r)
923
-
924
- if "%" in str(r.value) or px >= 50:
925
- token = "radius.full"
926
- usage = "Circles, avatars"
927
- else:
928
- token = "radius.md"
929
- usage = "General use"
930
- for (low, high), (t, u) in token_map.items():
931
- if low <= px < high:
932
- token = t
933
- usage = u
934
- break
935
-
936
- lines.append(f"| {val} | `{token}` | {usage} |")
937
-
938
- return "\n".join(lines)
939
-
940
-
941
- def format_shadows_with_tokens() -> str:
942
- """Format shadows with token name suggestions."""
943
- if not state.desktop_normalized or not state.desktop_normalized.shadows:
944
- return "*No shadow values detected.*"
945
-
946
- shadows = list(state.desktop_normalized.shadows.values())
947
-
948
- lines = [
949
- "### 🌫️ Shadow Tokens",
950
- "",
951
- "| Detected Value | Suggested Token | Use Case |",
952
- "|----------------|-----------------|----------|",
953
- ]
954
-
955
- shadow_sizes = ["shadow.xs", "shadow.sm", "shadow.md", "shadow.lg", "shadow.xl", "shadow.2xl"]
956
-
957
- for i, s in enumerate(shadows[:6]):
958
- val = str(s.value)[:40] + ("..." if len(str(s.value)) > 40 else "")
959
- token = shadow_sizes[i] if i < len(shadow_sizes) else f"shadow.custom-{i}"
960
-
961
- # Guess use case based on index
962
- use_cases = ["Subtle elevation", "Cards, dropdowns", "Modals, dialogs", "Popovers", "Floating elements", "Dramatic effect"]
963
- use = use_cases[i] if i < len(use_cases) else "Custom"
964
-
965
- lines.append(f"| `{val}` | `{token}` | {use} |")
966
-
967
- return "\n".join(lines)
968
-
969
-
970
- def format_spacing_comparison(recommendations) -> list:
971
- """Format spacing comparison table."""
972
- if not state.desktop_normalized:
973
- return []
974
-
975
- # Get current spacing
976
- current_spacing = list(state.desktop_normalized.spacing.values())
977
- current_spacing.sort(key=lambda s: s.value_px)
978
-
979
- data = []
980
- for s in current_spacing[:10]:
981
- current = f"{s.value_px}px"
982
- grid_8 = f"{snap_to_grid(s.value_px, 8)}px"
983
- grid_4 = f"{snap_to_grid(s.value_px, 4)}px"
984
-
985
- # Mark if value fits
986
- if s.value_px == snap_to_grid(s.value_px, 8):
987
- grid_8 += " ✓"
988
- if s.value_px == snap_to_grid(s.value_px, 4):
989
- grid_4 += " ✓"
990
-
991
- data.append([current, grid_8, grid_4])
992
-
993
- return data
994
-
995
-
996
- def snap_to_grid(value: float, base: int) -> int:
997
- """Snap value to grid."""
998
- return round(value / base) * base
999
-
1000
-
1001
- def apply_selected_upgrades(type_choice: str, spacing_choice: str, apply_ramps: bool):
1002
- """Apply selected upgrade options."""
1003
- if not state.upgrade_recommendations:
1004
- return "❌ Run analysis first", ""
1005
-
1006
- state.log("✨ Applying selected upgrades...")
1007
-
1008
- # Store selections
1009
- state.selected_upgrades = {
1010
- "type_scale": type_choice,
1011
- "spacing": spacing_choice,
1012
- "color_ramps": apply_ramps,
1013
- }
1014
-
1015
- state.log(f" Type Scale: {type_choice}")
1016
- state.log(f" Spacing: {spacing_choice}")
1017
- state.log(f" Color Ramps: {'Yes' if apply_ramps else 'No'}")
1018
-
1019
- state.log("✅ Upgrades applied! Proceed to Stage 3 for export.")
1020
-
1021
- return "✅ Upgrades applied! Proceed to Stage 3 to export.", state.get_logs()
1022
-
1023
-
1024
- def export_stage1_json():
1025
- """Export Stage 1 tokens (as-is extraction) to JSON."""
1026
- if not state.desktop_normalized:
1027
- return json.dumps({"error": "No tokens extracted. Please run extraction first."}, indent=2)
1028
-
1029
- result = {
1030
- "metadata": {
1031
- "source_url": state.base_url,
1032
- "extracted_at": datetime.now().isoformat(),
1033
- "version": "v1-stage1-as-is",
1034
- "stage": "extraction",
1035
- "description": "Raw extracted tokens before upgrades",
1036
- },
1037
- "fonts": {}, # Detected font families
1038
- "colors": {}, # Viewport-agnostic
1039
- "typography": {
1040
- "desktop": {},
1041
- "mobile": {},
1042
- },
1043
- "spacing": {
1044
- "desktop": {},
1045
- "mobile": {},
1046
- },
1047
- "radius": {}, # Viewport-agnostic
1048
- "shadows": {}, # Viewport-agnostic
1049
- }
1050
-
1051
- # Font families detected
1052
- fonts_info = get_detected_fonts()
1053
- result["fonts"] = {
1054
- "primary": fonts_info.get("primary", "Unknown"),
1055
- "weights": fonts_info.get("weights", [400]),
1056
- "all_fonts": fonts_info.get("all_fonts", {}),
1057
- }
1058
-
1059
- # Colors (no viewport prefix - same across devices)
1060
- if state.desktop_normalized and state.desktop_normalized.colors:
1061
- for name, c in state.desktop_normalized.colors.items():
1062
- key = c.suggested_name or c.value
1063
- result["colors"][key] = {
1064
- "value": c.value,
1065
- "frequency": c.frequency,
1066
- "confidence": c.confidence.value if c.confidence else "medium",
1067
- "contrast_white": round(c.contrast_white, 2) if c.contrast_white else None,
1068
- "contrast_black": round(c.contrast_black, 2) if c.contrast_black else None,
1069
- "contexts": c.contexts[:3] if c.contexts else [],
1070
- }
1071
-
1072
- # Typography Desktop
1073
- if state.desktop_normalized and state.desktop_normalized.typography:
1074
- for name, t in state.desktop_normalized.typography.items():
1075
- key = t.suggested_name or f"{t.font_family}-{t.font_size}"
1076
- result["typography"]["desktop"][key] = {
1077
- "font_family": t.font_family,
1078
- "font_size": t.font_size,
1079
- "font_weight": t.font_weight,
1080
- "line_height": t.line_height,
1081
- "frequency": t.frequency,
1082
- }
1083
-
1084
- # Typography Mobile
1085
- if state.mobile_normalized and state.mobile_normalized.typography:
1086
- for name, t in state.mobile_normalized.typography.items():
1087
- key = t.suggested_name or f"{t.font_family}-{t.font_size}"
1088
- result["typography"]["mobile"][key] = {
1089
- "font_family": t.font_family,
1090
- "font_size": t.font_size,
1091
- "font_weight": t.font_weight,
1092
- "line_height": t.line_height,
1093
- "frequency": t.frequency,
1094
- }
1095
-
1096
- # Spacing Desktop
1097
- if state.desktop_normalized and state.desktop_normalized.spacing:
1098
- for name, s in state.desktop_normalized.spacing.items():
1099
- key = s.suggested_name or s.value
1100
- result["spacing"]["desktop"][key] = {
1101
- "value": s.value,
1102
- "value_px": s.value_px,
1103
- "fits_base_8": s.fits_base_8,
1104
- "frequency": s.frequency,
1105
- }
1106
-
1107
- # Spacing Mobile
1108
- if state.mobile_normalized and state.mobile_normalized.spacing:
1109
- for name, s in state.mobile_normalized.spacing.items():
1110
- key = s.suggested_name or s.value
1111
- result["spacing"]["mobile"][key] = {
1112
- "value": s.value,
1113
- "value_px": s.value_px,
1114
- "fits_base_8": s.fits_base_8,
1115
- "frequency": s.frequency,
1116
- }
1117
-
1118
- # Radius (no viewport prefix)
1119
- if state.desktop_normalized and state.desktop_normalized.radius:
1120
- for name, r in state.desktop_normalized.radius.items():
1121
- result["radius"][name] = {
1122
- "value": r.value,
1123
- "frequency": r.frequency,
1124
- }
1125
-
1126
- # Shadows (no viewport prefix)
1127
- if state.desktop_normalized and state.desktop_normalized.shadows:
1128
- for name, s in state.desktop_normalized.shadows.items():
1129
- result["shadows"][name] = {
1130
- "value": s.value,
1131
- "frequency": s.frequency,
1132
- }
1133
-
1134
- return json.dumps(result, indent=2, default=str)
1135
-
1136
-
1137
- def export_tokens_json():
1138
- """Export final tokens with selected upgrades applied."""
1139
- if not state.desktop_normalized:
1140
- return json.dumps({"error": "No tokens extracted. Please run extraction first."}, indent=2)
1141
-
1142
- # Get selected upgrades
1143
- upgrades = getattr(state, 'selected_upgrades', {})
1144
- type_scale_choice = upgrades.get('type_scale', 'Keep Current')
1145
- spacing_choice = upgrades.get('spacing', 'Keep Current')
1146
- apply_ramps = upgrades.get('color_ramps', True)
1147
-
1148
- # Determine ratio from choice
1149
- ratio = None
1150
- if "1.2" in type_scale_choice:
1151
- ratio = 1.2
1152
- elif "1.25" in type_scale_choice:
1153
- ratio = 1.25
1154
- elif "1.333" in type_scale_choice:
1155
- ratio = 1.333
1156
-
1157
- # Determine spacing base
1158
- spacing_base = None
1159
- if "8px" in spacing_choice:
1160
- spacing_base = 8
1161
- elif "4px" in spacing_choice:
1162
- spacing_base = 4
1163
-
1164
- result = {
1165
- "metadata": {
1166
- "source_url": state.base_url,
1167
- "extracted_at": datetime.now().isoformat(),
1168
- "version": "v2-upgraded",
1169
- "stage": "final",
1170
- "upgrades_applied": {
1171
- "type_scale": type_scale_choice,
1172
- "spacing": spacing_choice,
1173
- "color_ramps": apply_ramps,
1174
- },
1175
- },
1176
- "fonts": {},
1177
- "colors": {},
1178
- "typography": {
1179
- "desktop": {},
1180
- "mobile": {},
1181
- },
1182
- "spacing": {
1183
- "desktop": {},
1184
- "mobile": {},
1185
- },
1186
- "radius": {},
1187
- "shadows": {},
1188
- }
1189
-
1190
- # Font families
1191
- fonts_info = get_detected_fonts()
1192
- result["fonts"] = {
1193
- "primary": fonts_info.get("primary", "Unknown"),
1194
- "weights": fonts_info.get("weights", [400]),
1195
- }
1196
-
1197
- # Colors with optional ramps
1198
- if state.desktop_normalized and state.desktop_normalized.colors:
1199
- from core.color_utils import generate_color_ramp
1200
-
1201
- for name, c in state.desktop_normalized.colors.items():
1202
- base_key = c.suggested_name or c.value
1203
-
1204
- if apply_ramps:
1205
- # Generate full ramp
1206
- try:
1207
- ramp = generate_color_ramp(c.value)
1208
- shades = ["50", "100", "200", "300", "400", "500", "600", "700", "800", "900"]
1209
- for i, shade in enumerate(shades):
1210
- if i < len(ramp):
1211
- result["colors"][f"{base_key}.{shade}"] = {
1212
- "value": ramp[i],
1213
- "source": "upgraded" if shade != "500" else "detected",
1214
- }
1215
- except:
1216
- result["colors"][base_key] = {"value": c.value, "source": "detected"}
1217
- else:
1218
- result["colors"][base_key] = {"value": c.value, "source": "detected"}
1219
-
1220
- # Typography with optional type scale
1221
- base_size = get_base_font_size()
1222
- token_names = [
1223
- "display.2xl", "display.xl", "display.lg", "display.md",
1224
- "heading.xl", "heading.lg", "heading.md", "heading.sm",
1225
- "body.lg", "body.md", "body.sm", "caption", "overline"
1226
- ]
1227
-
1228
- # Desktop typography
1229
- if state.desktop_normalized and state.desktop_normalized.typography:
1230
- if ratio:
1231
- # Apply type scale
1232
- scales = [int(round(base_size * (ratio ** (8-i)) / 2) * 2) for i in range(13)]
1233
- for i, token_name in enumerate(token_names):
1234
- result["typography"]["desktop"][token_name] = {
1235
- "font_family": fonts_info.get("primary", "sans-serif"),
1236
- "font_size": f"{scales[i]}px",
1237
- "source": "upgraded",
1238
- }
1239
- else:
1240
- # Keep original
1241
- for name, t in state.desktop_normalized.typography.items():
1242
- key = t.suggested_name or f"{t.font_family}-{t.font_size}"
1243
- result["typography"]["desktop"][key] = {
1244
- "font_family": t.font_family,
1245
- "font_size": t.font_size,
1246
- "font_weight": t.font_weight,
1247
- "line_height": t.line_height,
1248
- "source": "detected",
1249
- }
1250
-
1251
- # Mobile typography
1252
- if state.mobile_normalized and state.mobile_normalized.typography:
1253
- if ratio:
1254
- # Apply type scale with mobile factor
1255
- mobile_factor = 0.875
1256
- scales = [int(round(base_size * mobile_factor * (ratio ** (8-i)) / 2) * 2) for i in range(13)]
1257
- for i, token_name in enumerate(token_names):
1258
- result["typography"]["mobile"][token_name] = {
1259
- "font_family": fonts_info.get("primary", "sans-serif"),
1260
- "font_size": f"{scales[i]}px",
1261
- "source": "upgraded",
1262
- }
1263
- else:
1264
- for name, t in state.mobile_normalized.typography.items():
1265
- key = t.suggested_name or f"{t.font_family}-{t.font_size}"
1266
- result["typography"]["mobile"][key] = {
1267
- "font_family": t.font_family,
1268
- "font_size": t.font_size,
1269
- "font_weight": t.font_weight,
1270
- "line_height": t.line_height,
1271
- "source": "detected",
1272
- }
1273
-
1274
- # Spacing with optional grid alignment
1275
- spacing_tokens = ["space.1", "space.2", "space.3", "space.4", "space.5",
1276
- "space.6", "space.8", "space.10", "space.12", "space.16"]
1277
-
1278
- if state.desktop_normalized and state.desktop_normalized.spacing:
1279
- if spacing_base:
1280
- # Generate grid-aligned spacing
1281
- for i, token_name in enumerate(spacing_tokens):
1282
- value = spacing_base * (i + 1)
1283
- result["spacing"]["desktop"][token_name] = {
1284
- "value": f"{value}px",
1285
- "value_px": value,
1286
- "source": "upgraded",
1287
- }
1288
- else:
1289
- for name, s in state.desktop_normalized.spacing.items():
1290
- key = s.suggested_name or s.value
1291
- result["spacing"]["desktop"][key] = {
1292
- "value": s.value,
1293
- "value_px": s.value_px,
1294
- "source": "detected",
1295
- }
1296
-
1297
- if state.mobile_normalized and state.mobile_normalized.spacing:
1298
- if spacing_base:
1299
- for i, token_name in enumerate(spacing_tokens):
1300
- value = spacing_base * (i + 1)
1301
- result["spacing"]["mobile"][token_name] = {
1302
- "value": f"{value}px",
1303
- "value_px": value,
1304
- "source": "upgraded",
1305
- }
1306
- else:
1307
- for name, s in state.mobile_normalized.spacing.items():
1308
- key = s.suggested_name or s.value
1309
- result["spacing"]["mobile"][key] = {
1310
- "value": s.value,
1311
- "value_px": s.value_px,
1312
- "source": "detected",
1313
- }
1314
-
1315
- # Radius
1316
- if state.desktop_normalized and state.desktop_normalized.radius:
1317
- for name, r in state.desktop_normalized.radius.items():
1318
- result["radius"][name] = {
1319
- "value": r.value,
1320
- "source": "detected",
1321
- }
1322
-
1323
- # Shadows
1324
- if state.desktop_normalized and state.desktop_normalized.shadows:
1325
- for name, s in state.desktop_normalized.shadows.items():
1326
- result["shadows"][name] = {
1327
- "value": s.value,
1328
- "source": "detected",
1329
- }
1330
-
1331
- return json.dumps(result, indent=2, default=str)
1332
-
1333
-
1334
- # =============================================================================
1335
- # UI BUILDING
1336
- # =============================================================================
1337
-
1338
- def create_ui():
1339
- """Create the Gradio interface."""
1340
-
1341
- with gr.Blocks(
1342
- title="Design System Extractor v2",
1343
- theme=gr.themes.Soft(),
1344
- css="""
1345
- .color-swatch { display: inline-block; width: 24px; height: 24px; border-radius: 4px; margin-right: 8px; vertical-align: middle; }
1346
- """
1347
- ) as app:
1348
-
1349
- gr.Markdown("""
1350
- # 🎨 Design System Extractor v2
1351
-
1352
- **Reverse-engineer design systems from live websites.**
1353
-
1354
- A semi-automated, human-in-the-loop system that extracts, normalizes, and upgrades design tokens.
1355
-
1356
- ---
1357
- """)
1358
-
1359
- # =================================================================
1360
- # CONFIGURATION
1361
- # =================================================================
1362
-
1363
- with gr.Accordion("⚙️ Configuration", open=not bool(HF_TOKEN_FROM_ENV)):
1364
- gr.Markdown("**HuggingFace Token** — Required for Stage 2 (AI upgrades)")
1365
- with gr.Row():
1366
- hf_token_input = gr.Textbox(
1367
- label="HF Token", placeholder="hf_xxxx", type="password",
1368
- scale=4, value=HF_TOKEN_FROM_ENV,
1369
- )
1370
- save_token_btn = gr.Button("💾 Save", scale=1)
1371
- token_status = gr.Markdown("✅ Token loaded" if HF_TOKEN_FROM_ENV else "⏳ Enter token")
1372
-
1373
- def save_token(token):
1374
- if token and len(token) > 10:
1375
- os.environ["HF_TOKEN"] = token.strip()
1376
- return "✅ Token saved!"
1377
- return "❌ Invalid token"
1378
-
1379
- save_token_btn.click(save_token, [hf_token_input], [token_status])
1380
-
1381
- # =================================================================
1382
- # URL INPUT & PAGE DISCOVERY
1383
- # =================================================================
1384
-
1385
- with gr.Accordion("🔍 Step 1: Discover Pages", open=True):
1386
- gr.Markdown("Enter your website URL to discover pages for extraction.")
1387
-
1388
- with gr.Row():
1389
- url_input = gr.Textbox(label="Website URL", placeholder="https://example.com", scale=4)
1390
- discover_btn = gr.Button("🔍 Discover Pages", variant="primary", scale=1)
1391
-
1392
- discover_status = gr.Markdown("")
1393
-
1394
- with gr.Row():
1395
- log_output = gr.Textbox(label="📋 Log", lines=8, interactive=False)
1396
-
1397
- pages_table = gr.Dataframe(
1398
- headers=["Select", "URL", "Title", "Type", "Status"],
1399
- datatype=["bool", "str", "str", "str", "str"],
1400
- label="Discovered Pages",
1401
- interactive=True,
1402
- visible=False,
1403
- )
1404
-
1405
- extract_btn = gr.Button("🚀 Extract Tokens (Desktop + Mobile)", variant="primary", visible=False)
1406
-
1407
- # =================================================================
1408
- # STAGE 1: EXTRACTION REVIEW
1409
- # =================================================================
1410
-
1411
- with gr.Accordion("📊 Stage 1: Review Extracted Tokens", open=False) as stage1_accordion:
1412
-
1413
- extraction_status = gr.Markdown("")
1414
-
1415
- gr.Markdown("""
1416
- **Review the extracted tokens.** Toggle between Desktop and Mobile viewports.
1417
- Accept or reject tokens, then proceed to Stage 2 for AI-powered upgrades.
1418
- """)
1419
-
1420
- viewport_toggle = gr.Radio(
1421
- choices=["Desktop (1440px)", "Mobile (375px)"],
1422
- value="Desktop (1440px)",
1423
- label="Viewport",
1424
- )
1425
-
1426
- with gr.Tabs():
1427
- with gr.Tab("🎨 Colors"):
1428
- colors_table = gr.Dataframe(
1429
- headers=["Accept", "Color", "Suggested Name", "Frequency", "Confidence", "Contrast", "AA", "Context"],
1430
- datatype=["bool", "str", "str", "number", "str", "str", "str", "str"],
1431
- label="Colors",
1432
- interactive=True,
1433
- )
1434
-
1435
- with gr.Tab("📝 Typography"):
1436
- typography_table = gr.Dataframe(
1437
- headers=["Accept", "Font", "Size", "Weight", "Line Height", "Suggested Name", "Frequency", "Confidence"],
1438
- datatype=["bool", "str", "str", "str", "str", "str", "number", "str"],
1439
- label="Typography",
1440
- interactive=True,
1441
- )
1442
-
1443
- with gr.Tab("📏 Spacing"):
1444
- spacing_table = gr.Dataframe(
1445
- headers=["Accept", "Value", "Pixels", "Suggested Name", "Frequency", "Base 8", "Confidence"],
1446
- datatype=["bool", "str", "str", "str", "number", "str", "str"],
1447
- label="Spacing",
1448
- interactive=True,
1449
- )
1450
-
1451
- with gr.Tab("🔘 Radius"):
1452
- radius_table = gr.Dataframe(
1453
- headers=["Accept", "Value", "Frequency", "Context"],
1454
- datatype=["bool", "str", "number", "str"],
1455
- label="Border Radius",
1456
- interactive=True,
1457
- )
1458
-
1459
- with gr.Row():
1460
- proceed_stage2_btn = gr.Button("➡️ Proceed to Stage 2: AI Upgrades", variant="primary")
1461
- download_stage1_btn = gr.Button("📥 Download Stage 1 JSON", variant="secondary")
1462
-
1463
- # =================================================================
1464
- # STAGE 2: AI UPGRADES
1465
- # =================================================================
1466
-
1467
- with gr.Accordion("🧠 Stage 2: AI-Powered Upgrades", open=False) as stage2_accordion:
1468
-
1469
- stage2_status = gr.Markdown("Click 'Analyze' to start AI-powered design system analysis.")
1470
-
1471
- # =============================================================
1472
- # LLM CONFIGURATION & COMPETITORS
1473
- # =============================================================
1474
- with gr.Accordion("⚙️ Analysis Configuration", open=False):
1475
- gr.Markdown("""
1476
- ### 🤖 LLM Models Used
1477
-
1478
- | Role | Model | Expertise |
1479
- |------|-------|-----------|
1480
- | **Typography Analyst** | meta-llama/Llama-3.1-70B | Type scale patterns, readability |
1481
- | **Color Analyst** | meta-llama/Llama-3.1-70B | Color theory, accessibility |
1482
- | **Spacing Analyst** | Rule-based | Grid alignment, consistency |
1483
-
1484
- *Analysis compares your design against industry leaders.*
1485
- """)
1486
-
1487
- gr.Markdown("### 🎯 Competitor Design Systems")
1488
- gr.Markdown("Enter design systems to compare against (comma-separated):")
1489
- competitors_input = gr.Textbox(
1490
- value="Material Design 3, Apple HIG, Shopify Polaris, IBM Carbon, Atlassian",
1491
- label="Competitors",
1492
- placeholder="Material Design 3, Apple HIG, Shopify Polaris...",
1493
- )
1494
- gr.Markdown("*Suggestions: Ant Design, Chakra UI, Tailwind, Bootstrap, Salesforce Lightning*")
1495
-
1496
- analyze_btn = gr.Button("🤖 Analyze Design System", variant="primary", size="lg")
1497
-
1498
- with gr.Accordion("📋 AI Analysis Log", open=True):
1499
- stage2_log = gr.Textbox(label="Log", lines=18, interactive=False)
1500
-
1501
- # =============================================================
1502
- # BRAND COMPARISON (LLM Research)
1503
- # =============================================================
1504
- gr.Markdown("---")
1505
- brand_comparison = gr.Markdown("*Brand comparison will appear after analysis*")
1506
-
1507
- # =============================================================
1508
- # FONT FAMILIES DETECTED
1509
- # =============================================================
1510
- gr.Markdown("---")
1511
- gr.Markdown("## 🔤 Font Families Detected")
1512
- font_families_display = gr.Markdown("*Font information will appear after analysis*")
1513
-
1514
- # =============================================================
1515
- # TYPOGRAPHY SECTION - Desktop & Mobile
1516
- # =============================================================
1517
- gr.Markdown("---")
1518
- gr.Markdown("## 📐 Typography")
1519
-
1520
- with gr.Row():
1521
- with gr.Column(scale=2):
1522
- gr.Markdown("### 🖥️ Desktop (1440px)")
1523
- typography_desktop = gr.Dataframe(
1524
- headers=["Token", "Current", "Scale 1.2", "Scale 1.25 ⭐", "Scale 1.333", "Keep"],
1525
- datatype=["str", "str", "str", "str", "str", "str"],
1526
- label="Desktop Typography",
1527
- interactive=False,
1528
- )
1529
-
1530
- with gr.Column(scale=2):
1531
- gr.Markdown("### 📱 Mobile (375px)")
1532
- typography_mobile = gr.Dataframe(
1533
- headers=["Token", "Current", "Scale 1.2", "Scale 1.25 ⭐", "Scale 1.333", "Keep"],
1534
- datatype=["str", "str", "str", "str", "str", "str"],
1535
- label="Mobile Typography",
1536
- interactive=False,
1537
- )
1538
-
1539
- with gr.Row():
1540
- with gr.Column():
1541
- gr.Markdown("### Select Type Scale Option")
1542
- type_scale_radio = gr.Radio(
1543
- choices=["Keep Current", "Scale 1.2 (Minor Third)", "Scale 1.25 (Major Third) ⭐", "Scale 1.333 (Perfect Fourth)"],
1544
- value="Scale 1.25 (Major Third) ⭐",
1545
- label="Type Scale",
1546
- interactive=True,
1547
- )
1548
- gr.Markdown("*Font family will be preserved. Sizes rounded to even numbers.*")
1549
-
1550
- # =============================================================
1551
- # COLORS SECTION - Base Colors + Ramps
1552
- # =============================================================
1553
- gr.Markdown("---")
1554
- gr.Markdown("## 🎨 Colors")
1555
-
1556
- base_colors_display = gr.Markdown("*Base colors will appear after analysis*")
1557
-
1558
- gr.Markdown("---")
1559
-
1560
- color_ramps_display = gr.Markdown("*Color ramps will appear after analysis*")
1561
-
1562
- color_ramps_checkbox = gr.Checkbox(
1563
- label="✓ Generate color ramps (keeps base colors, adds 50-950 shades)",
1564
- value=True,
1565
- )
1566
-
1567
- # =============================================================
1568
- # SPACING SECTION
1569
- # =============================================================
1570
- gr.Markdown("---")
1571
- gr.Markdown("## 📏 Spacing (Rule-Based)")
1572
-
1573
- with gr.Row():
1574
- with gr.Column(scale=2):
1575
- spacing_comparison = gr.Dataframe(
1576
- headers=["Current", "8px Grid", "4px Grid"],
1577
- datatype=["str", "str", "str"],
1578
- label="Spacing Comparison",
1579
- interactive=False,
1580
- )
1581
-
1582
- with gr.Column(scale=1):
1583
- spacing_radio = gr.Radio(
1584
- choices=["Keep Current", "8px Base Grid ⭐", "4px Base Grid"],
1585
- value="8px Base Grid ⭐",
1586
- label="Spacing System",
1587
- interactive=True,
1588
- )
1589
-
1590
- # =============================================================
1591
- # RADIUS SECTION
1592
- # =============================================================
1593
- gr.Markdown("---")
1594
- gr.Markdown("## 🔘 Border Radius (Rule-Based)")
1595
-
1596
- radius_display = gr.Markdown("*Radius tokens will appear after analysis*")
1597
-
1598
- # =============================================================
1599
- # SHADOWS SECTION
1600
- # =============================================================
1601
- gr.Markdown("---")
1602
- gr.Markdown("## 🌫️ Shadows (Rule-Based)")
1603
-
1604
- shadows_display = gr.Markdown("*Shadow tokens will appear after analysis*")
1605
-
1606
- # =============================================================
1607
- # APPLY SECTION
1608
- # =============================================================
1609
- gr.Markdown("---")
1610
-
1611
- with gr.Row():
1612
- apply_upgrades_btn = gr.Button("✨ Apply Selected Upgrades", variant="primary", scale=2)
1613
- reset_btn = gr.Button("↩️ Reset to Original", variant="secondary", scale=1)
1614
-
1615
- apply_status = gr.Markdown("")
1616
-
1617
- # =================================================================
1618
- # STAGE 3: EXPORT
1619
- # =================================================================
1620
-
1621
- with gr.Accordion("📦 Stage 3: Export", open=False):
1622
- gr.Markdown("""
1623
- Export your design tokens to JSON (compatible with Figma Tokens Studio).
1624
-
1625
- - **Stage 1 JSON**: Raw extracted tokens (as-is)
1626
- - **Final JSON**: Upgraded tokens with selected improvements
1627
- """)
1628
-
1629
- with gr.Row():
1630
- export_stage1_btn = gr.Button("📥 Export Stage 1 (As-Is)", variant="secondary")
1631
- export_final_btn = gr.Button("📥 Export Final (Upgraded)", variant="primary")
1632
-
1633
- export_output = gr.Code(label="Tokens JSON", language="json", lines=25)
1634
-
1635
- export_stage1_btn.click(export_stage1_json, outputs=[export_output])
1636
- export_final_btn.click(export_tokens_json, outputs=[export_output])
1637
-
1638
- # =================================================================
1639
- # EVENT HANDLERS
1640
- # =================================================================
1641
-
1642
- # Store data for viewport toggle
1643
- desktop_data = gr.State({})
1644
- mobile_data = gr.State({})
1645
-
1646
- # Discover pages
1647
- discover_btn.click(
1648
- fn=discover_pages,
1649
- inputs=[url_input],
1650
- outputs=[discover_status, log_output, pages_table],
1651
- ).then(
1652
- fn=lambda: (gr.update(visible=True), gr.update(visible=True)),
1653
- outputs=[pages_table, extract_btn],
1654
- )
1655
-
1656
- # Extract tokens
1657
- extract_btn.click(
1658
- fn=extract_tokens,
1659
- inputs=[pages_table],
1660
- outputs=[extraction_status, log_output, desktop_data, mobile_data],
1661
- ).then(
1662
- fn=lambda d: (d.get("colors", []), d.get("typography", []), d.get("spacing", [])),
1663
- inputs=[desktop_data],
1664
- outputs=[colors_table, typography_table, spacing_table],
1665
- ).then(
1666
- fn=lambda: gr.update(open=True),
1667
- outputs=[stage1_accordion],
1668
- )
1669
-
1670
- # Viewport toggle
1671
- viewport_toggle.change(
1672
- fn=switch_viewport,
1673
- inputs=[viewport_toggle],
1674
- outputs=[colors_table, typography_table, spacing_table],
1675
- )
1676
-
1677
- # Stage 2: Analyze
1678
- analyze_btn.click(
1679
- fn=run_stage2_analysis,
1680
- inputs=[competitors_input],
1681
- outputs=[stage2_status, stage2_log, brand_comparison, font_families_display,
1682
- typography_desktop, typography_mobile, spacing_comparison,
1683
- base_colors_display, color_ramps_display, radius_display, shadows_display],
1684
- )
1685
-
1686
- # Stage 2: Apply upgrades
1687
- apply_upgrades_btn.click(
1688
- fn=apply_selected_upgrades,
1689
- inputs=[type_scale_radio, spacing_radio, color_ramps_checkbox],
1690
- outputs=[apply_status, stage2_log],
1691
- )
1692
-
1693
- # Stage 1: Download JSON
1694
- download_stage1_btn.click(
1695
- fn=export_stage1_json,
1696
- outputs=[export_output],
1697
- )
1698
-
1699
- # Proceed to Stage 2 button
1700
- proceed_stage2_btn.click(
1701
- fn=lambda: gr.update(open=True),
1702
- outputs=[stage2_accordion],
1703
- )
1704
-
1705
- # =================================================================
1706
- # FOOTER
1707
- # =================================================================
1708
-
1709
- gr.Markdown("""
1710
- ---
1711
- **Design System Extractor v2** | Built with Playwright + Gradio + LangGraph + HuggingFace
1712
-
1713
- *A semi-automated co-pilot for design system recovery and modernization.*
1714
- """)
1715
-
1716
- return app
1717
-
1718
-
1719
- # =============================================================================
1720
- # MAIN
1721
- # =============================================================================
1722
-
1723
- if __name__ == "__main__":
1724
- app = create_ui()
1725
- app.launch(server_name="0.0.0.0", server_port=7860)