riazmo commited on
Commit
ebb4c83
·
verified ·
1 Parent(s): a72d929

Upload advisor.py

Browse files
Files changed (1) hide show
  1. agents/advisor.py +697 -0
agents/advisor.py ADDED
@@ -0,0 +1,697 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Agent 3: Design System Best Practices Advisor
3
+ Design System Extractor v2
4
+
5
+ Persona: Senior Staff Design Systems Architect
6
+
7
+ Responsibilities:
8
+ - Analyze extracted tokens against best practices (Material, Polaris, Carbon)
9
+ - Propose upgrade OPTIONS with rationale (LLM-powered reasoning)
10
+ - Generate type scales, color ramps, spacing grids (Rule-based calculation)
11
+ - Never change: font families, primary/secondary base colors
12
+
13
+ Hybrid Approach:
14
+ - LLM: Analyzes patterns, recommends options, explains rationale
15
+ - Rules: Calculates actual values (math-based)
16
+ """
17
+
18
+ import os
19
+ import json
20
+ from typing import Optional, Callable
21
+ from dataclasses import dataclass, field
22
+ from enum import Enum
23
+
24
+ from core.token_schema import (
25
+ NormalizedTokens,
26
+ ColorToken,
27
+ TypographyToken,
28
+ SpacingToken,
29
+ UpgradeOption,
30
+ UpgradeRecommendations,
31
+ )
32
+ from core.color_utils import (
33
+ parse_color,
34
+ generate_color_ramp,
35
+ get_contrast_ratio,
36
+ )
37
+
38
+
39
+ # =============================================================================
40
+ # TYPE SCALE CALCULATIONS (Rule-Based)
41
+ # =============================================================================
42
+
43
+ class TypeScaleRatio(Enum):
44
+ """Common type scale ratios."""
45
+ MINOR_SECOND = 1.067
46
+ MAJOR_SECOND = 1.125
47
+ MINOR_THIRD = 1.200
48
+ MAJOR_THIRD = 1.250
49
+ PERFECT_FOURTH = 1.333
50
+ AUGMENTED_FOURTH = 1.414
51
+ PERFECT_FIFTH = 1.500
52
+
53
+
54
+ def generate_type_scale(base_size: float, ratio: float, steps_up: int = 5, steps_down: int = 2) -> dict:
55
+ """
56
+ Generate a type scale from a base size.
57
+
58
+ Args:
59
+ base_size: Base font size in pixels (e.g., 16)
60
+ ratio: Scale ratio (e.g., 1.25)
61
+ steps_up: Number of sizes larger than base
62
+ steps_down: Number of sizes smaller than base
63
+
64
+ Returns:
65
+ Dict with size names and values
66
+ """
67
+ scale = {}
68
+
69
+ # Generate sizes below base
70
+ for i in range(steps_down, 0, -1):
71
+ size = base_size / (ratio ** i)
72
+ name = f"text.{['xs', 'sm'][steps_down - i] if i <= 2 else f'xs-{i}'}"
73
+ scale[name] = round(size)
74
+
75
+ # Base size
76
+ scale["text.base"] = round(base_size)
77
+
78
+ # Generate sizes above base
79
+ size_names = ["text.lg", "text.xl", "heading.sm", "heading.md", "heading.lg", "heading.xl", "heading.2xl", "display"]
80
+ for i in range(1, steps_up + 1):
81
+ size = base_size * (ratio ** i)
82
+ name = size_names[i - 1] if i <= len(size_names) else f"heading.{i}xl"
83
+ scale[name] = round(size)
84
+
85
+ return scale
86
+
87
+
88
+ # =============================================================================
89
+ # SPACING GRID CALCULATIONS (Rule-Based)
90
+ # =============================================================================
91
+
92
+ def snap_to_grid(value: float, base: int = 8) -> int:
93
+ """Snap a value to the nearest grid unit."""
94
+ return round(value / base) * base
95
+
96
+
97
+ def generate_spacing_scale(base: int = 8, max_value: int = 96) -> dict:
98
+ """
99
+ Generate a spacing scale based on a base unit.
100
+
101
+ Args:
102
+ base: Base unit (4 or 8)
103
+ max_value: Maximum spacing value
104
+
105
+ Returns:
106
+ Dict with spacing names and values
107
+ """
108
+ scale = {}
109
+ multipliers = [0.5, 1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10, 12, 16, 20, 24]
110
+ names = ["0.5", "1", "1.5", "2", "2.5", "3", "4", "5", "6", "8", "10", "12", "16", "20", "24"]
111
+
112
+ for mult, name in zip(multipliers, names):
113
+ value = int(base * mult)
114
+ if value <= max_value:
115
+ scale[f"space.{name}"] = f"{value}px"
116
+
117
+ return scale
118
+
119
+
120
+ def analyze_spacing_fit(detected_values: list[int], base: int = 8) -> dict:
121
+ """
122
+ Analyze how well detected spacing values fit a grid.
123
+
124
+ Returns:
125
+ Dict with fit percentage and adjustments needed
126
+ """
127
+ fits = 0
128
+ adjustments = []
129
+
130
+ for value in detected_values:
131
+ snapped = snap_to_grid(value, base)
132
+ if value == snapped:
133
+ fits += 1
134
+ else:
135
+ adjustments.append({
136
+ "original": value,
137
+ "snapped": snapped,
138
+ "delta": snapped - value
139
+ })
140
+
141
+ return {
142
+ "base": base,
143
+ "fit_percentage": (fits / len(detected_values) * 100) if detected_values else 0,
144
+ "adjustments": adjustments,
145
+ "already_aligned": fits,
146
+ "needs_adjustment": len(adjustments)
147
+ }
148
+
149
+
150
+ # =============================================================================
151
+ # COLOR RAMP GENERATION (Rule-Based)
152
+ # =============================================================================
153
+
154
+ def generate_semantic_color_ramp(base_color: str, role: str = "primary") -> dict:
155
+ """
156
+ Generate a full color ramp from a base color.
157
+
158
+ Args:
159
+ base_color: Hex color (e.g., "#373737")
160
+ role: Semantic role (primary, secondary, neutral, etc.)
161
+
162
+ Returns:
163
+ Dict with shade names (50-900) and hex values
164
+ """
165
+ ramp = generate_color_ramp(base_color)
166
+
167
+ result = {}
168
+ shades = ["50", "100", "200", "300", "400", "500", "600", "700", "800", "900"]
169
+
170
+ for shade, color in zip(shades, ramp):
171
+ result[f"{role}.{shade}"] = color
172
+
173
+ return result
174
+
175
+
176
+ # =============================================================================
177
+ # LLM-POWERED ANALYSIS (Agent 3 Brain)
178
+ # =============================================================================
179
+
180
+ class DesignSystemAdvisor:
181
+ """
182
+ Agent 3: Analyzes tokens and proposes upgrades.
183
+
184
+ Uses LLM for reasoning and recommendations.
185
+ Uses rules for calculating actual values.
186
+ """
187
+
188
+ def __init__(self, log_callback: Optional[Callable[[str], None]] = None):
189
+ self.log = log_callback or print
190
+ self.hf_token = os.getenv("HF_TOKEN", "")
191
+ self.model = os.getenv("AGENT3_MODEL", "meta-llama/Llama-3.1-70B-Instruct")
192
+
193
+ async def analyze(
194
+ self,
195
+ desktop_tokens: NormalizedTokens,
196
+ mobile_tokens: NormalizedTokens,
197
+ ) -> UpgradeRecommendations:
198
+ """
199
+ Analyze tokens and generate upgrade recommendations.
200
+
201
+ Args:
202
+ desktop_tokens: Normalized desktop tokens
203
+ mobile_tokens: Normalized mobile tokens
204
+
205
+ Returns:
206
+ UpgradeRecommendations with options for each category
207
+ """
208
+ self.log("🤖 Agent 3: Starting design system analysis...")
209
+
210
+ # Gather token statistics
211
+ stats = self._gather_statistics(desktop_tokens, mobile_tokens)
212
+ self.log(f"📊 Gathered statistics: {len(stats['colors'])} colors, {len(stats['typography'])} typography, {len(stats['spacing'])} spacing")
213
+
214
+ # Generate rule-based options first
215
+ self.log("🔧 Generating rule-based options...")
216
+ type_scale_options = self._generate_type_scale_options(stats)
217
+ spacing_options = self._generate_spacing_options(stats)
218
+ color_ramp_options = self._generate_color_ramp_options(stats)
219
+
220
+ # Get LLM analysis and recommendations
221
+ self.log(f"🤖 Calling LLM ({self.model}) for analysis...")
222
+ llm_analysis = await self._get_llm_analysis(stats, type_scale_options, spacing_options)
223
+
224
+ # Apply LLM recommendations to options
225
+ self._apply_llm_recommendations(type_scale_options, spacing_options, color_ramp_options, llm_analysis)
226
+
227
+ self.log("✅ Analysis complete!")
228
+
229
+ return UpgradeRecommendations(
230
+ typography_scales=type_scale_options,
231
+ spacing_systems=spacing_options,
232
+ color_ramps=color_ramp_options,
233
+ naming_conventions=[],
234
+ llm_rationale=llm_analysis.get("rationale", ""),
235
+ detected_patterns=llm_analysis.get("patterns", []),
236
+ brand_analysis=llm_analysis.get("brand_analysis", []),
237
+ color_observations=llm_analysis.get("color_observations", ""),
238
+ accessibility_issues=llm_analysis.get("accessibility_issues", []),
239
+ )
240
+
241
+ def _gather_statistics(self, desktop: NormalizedTokens, mobile: NormalizedTokens) -> dict:
242
+ """Gather statistics from tokens for analysis."""
243
+
244
+ # Combine colors (colors are viewport-agnostic)
245
+ colors = {}
246
+ for name, token in desktop.colors.items():
247
+ colors[token.value] = {
248
+ "value": token.value,
249
+ "frequency": token.frequency,
250
+ "contexts": token.contexts,
251
+ "suggested_name": token.suggested_name,
252
+ }
253
+
254
+ # Typography (viewport-specific)
255
+ typography = {
256
+ "desktop": [],
257
+ "mobile": [],
258
+ }
259
+ for name, token in desktop.typography.items():
260
+ typography["desktop"].append({
261
+ "font_family": token.font_family,
262
+ "font_size": token.font_size,
263
+ "font_weight": token.font_weight,
264
+ "frequency": token.frequency,
265
+ })
266
+ for name, token in mobile.typography.items():
267
+ typography["mobile"].append({
268
+ "font_family": token.font_family,
269
+ "font_size": token.font_size,
270
+ "font_weight": token.font_weight,
271
+ "frequency": token.frequency,
272
+ })
273
+
274
+ # Spacing
275
+ spacing = {
276
+ "desktop": [],
277
+ "mobile": [],
278
+ }
279
+ for name, token in desktop.spacing.items():
280
+ spacing["desktop"].append(token.value_px)
281
+ for name, token in mobile.spacing.items():
282
+ spacing["mobile"].append(token.value_px)
283
+
284
+ # Find most used font family
285
+ font_families = {}
286
+ for t in typography["desktop"]:
287
+ family = t["font_family"]
288
+ font_families[family] = font_families.get(family, 0) + t["frequency"]
289
+
290
+ primary_font = max(font_families.items(), key=lambda x: x[1])[0] if font_families else "sans-serif"
291
+
292
+ # Find base font size (most frequent in body context)
293
+ font_sizes = [self._parse_size(t["font_size"]) for t in typography["desktop"]]
294
+ base_font_size = 16 # Default
295
+ if font_sizes:
296
+ # Find most common size between 14-18px (typical body text)
297
+ body_sizes = [s for s in font_sizes if 14 <= s <= 18]
298
+ if body_sizes:
299
+ base_font_size = max(set(body_sizes), key=body_sizes.count)
300
+
301
+ return {
302
+ "colors": colors,
303
+ "typography": typography,
304
+ "spacing": spacing,
305
+ "primary_font": primary_font,
306
+ "base_font_size": base_font_size,
307
+ "all_font_sizes": list(set(font_sizes)),
308
+ }
309
+
310
+ def _parse_size(self, size_str: str) -> float:
311
+ """Parse a size string to pixels."""
312
+ if not size_str:
313
+ return 16
314
+ size_str = str(size_str).lower().strip()
315
+ if "px" in size_str:
316
+ return float(size_str.replace("px", ""))
317
+ if "rem" in size_str:
318
+ return float(size_str.replace("rem", "")) * 16
319
+ if "em" in size_str:
320
+ return float(size_str.replace("em", "")) * 16
321
+ try:
322
+ return float(size_str)
323
+ except:
324
+ return 16
325
+
326
+ def _generate_type_scale_options(self, stats: dict) -> list[UpgradeOption]:
327
+ """Generate type scale options."""
328
+ base = stats["base_font_size"]
329
+ options = []
330
+
331
+ ratios = [
332
+ ("minor_third", 1.200, "Conservative — subtle size differences"),
333
+ ("major_third", 1.250, "Balanced — clear hierarchy without extremes"),
334
+ ("perfect_fourth", 1.333, "Bold — strong visual hierarchy"),
335
+ ]
336
+
337
+ for id_name, ratio, desc in ratios:
338
+ scale = generate_type_scale(base, ratio)
339
+ options.append(UpgradeOption(
340
+ id=f"type_scale_{id_name}",
341
+ name=f"Type Scale {ratio}",
342
+ description=desc,
343
+ category="typography",
344
+ values={
345
+ "ratio": ratio,
346
+ "base": base,
347
+ "scale": scale,
348
+ },
349
+ pros=[
350
+ f"Based on {base}px base (detected)",
351
+ f"Ratio {ratio} is industry standard",
352
+ ],
353
+ cons=[],
354
+ effort="low",
355
+ recommended=False,
356
+ ))
357
+
358
+ # Add "keep original" option
359
+ options.append(UpgradeOption(
360
+ id="type_scale_keep",
361
+ name="Keep Original",
362
+ description="Preserve detected font sizes without scaling",
363
+ category="typography",
364
+ values={
365
+ "ratio": None,
366
+ "base": base,
367
+ "scale": {f"size_{i}": s for i, s in enumerate(stats["all_font_sizes"])},
368
+ },
369
+ pros=["No changes needed", "Preserves original design"],
370
+ cons=["May have inconsistent scale"],
371
+ effort="none",
372
+ recommended=False,
373
+ ))
374
+
375
+ return options
376
+
377
+ def _generate_spacing_options(self, stats: dict) -> list[UpgradeOption]:
378
+ """Generate spacing system options."""
379
+ desktop_spacing = stats["spacing"]["desktop"]
380
+
381
+ options = []
382
+
383
+ for base in [8, 4]:
384
+ fit_analysis = analyze_spacing_fit(desktop_spacing, base)
385
+ scale = generate_spacing_scale(base)
386
+
387
+ options.append(UpgradeOption(
388
+ id=f"spacing_{base}px",
389
+ name=f"{base}px Base Grid",
390
+ description=f"{'Modern standard' if base == 8 else 'Finer control'} — {fit_analysis['fit_percentage']:.0f}% of your values already fit",
391
+ category="spacing",
392
+ values={
393
+ "base": base,
394
+ "scale": scale,
395
+ "fit_analysis": fit_analysis,
396
+ },
397
+ pros=[
398
+ f"{fit_analysis['already_aligned']} values already aligned",
399
+ "Consistent visual rhythm" if base == 8 else "More granular control",
400
+ ],
401
+ cons=[
402
+ f"{fit_analysis['needs_adjustment']} values need adjustment" if fit_analysis['needs_adjustment'] > 0 else None,
403
+ ],
404
+ effort="low" if fit_analysis['fit_percentage'] > 70 else "medium",
405
+ recommended=False,
406
+ ))
407
+
408
+ # Add "keep original" option
409
+ options.append(UpgradeOption(
410
+ id="spacing_keep",
411
+ name="Keep Original",
412
+ description="Preserve detected spacing values",
413
+ category="spacing",
414
+ values={
415
+ "base": None,
416
+ "scale": {f"space_{v}": f"{v}px" for v in desktop_spacing},
417
+ },
418
+ pros=["No changes needed"],
419
+ cons=["May have irregular spacing"],
420
+ effort="none",
421
+ recommended=False,
422
+ ))
423
+
424
+ return options
425
+
426
+ def _generate_color_ramp_options(self, stats: dict) -> list[UpgradeOption]:
427
+ """Generate color ramp options."""
428
+ options = []
429
+
430
+ # Find primary colors (high frequency, used in text/background)
431
+ primary_candidates = []
432
+ for hex_val, data in stats["colors"].items():
433
+ if data["frequency"] > 10:
434
+ primary_candidates.append((hex_val, data))
435
+
436
+ # Sort by frequency
437
+ primary_candidates.sort(key=lambda x: -x[1]["frequency"])
438
+
439
+ # Generate ramps for top colors
440
+ for hex_val, data in primary_candidates[:5]:
441
+ role = self._infer_color_role(data)
442
+ ramp = generate_semantic_color_ramp(hex_val, role)
443
+
444
+ options.append(UpgradeOption(
445
+ id=f"color_ramp_{role}",
446
+ name=f"{role.title()} Ramp",
447
+ description=f"Generate 50-900 shades from {hex_val}",
448
+ category="colors",
449
+ values={
450
+ "base_color": hex_val,
451
+ "role": role,
452
+ "ramp": ramp,
453
+ "preserve_base": True,
454
+ },
455
+ pros=[
456
+ f"Base color {hex_val} preserved",
457
+ "Full shade range for UI states",
458
+ "AA contrast compliant",
459
+ ],
460
+ cons=[],
461
+ effort="low",
462
+ recommended=True,
463
+ ))
464
+
465
+ return options
466
+
467
+ def _infer_color_role(self, color_data: dict) -> str:
468
+ """Infer semantic role from color context."""
469
+ contexts = " ".join(color_data.get("contexts", [])).lower()
470
+
471
+ if "primary" in contexts or "brand" in contexts:
472
+ return "primary"
473
+ if "secondary" in contexts or "accent" in contexts:
474
+ return "secondary"
475
+ if "background" in contexts or "surface" in contexts:
476
+ return "surface"
477
+ if "text" in contexts or "foreground" in contexts:
478
+ return "text"
479
+ if "border" in contexts or "divider" in contexts:
480
+ return "border"
481
+ if "success" in contexts or "green" in contexts:
482
+ return "success"
483
+ if "error" in contexts or "red" in contexts:
484
+ return "error"
485
+ if "warning" in contexts or "yellow" in contexts:
486
+ return "warning"
487
+
488
+ return "neutral"
489
+
490
+ async def _get_llm_analysis(self, stats: dict, type_options: list, spacing_options: list) -> dict:
491
+ """Get LLM analysis and recommendations."""
492
+
493
+ if not self.hf_token:
494
+ self.log("⚠️ No HF token, using default recommendations")
495
+ return self._get_default_recommendations(stats, type_options, spacing_options)
496
+
497
+ try:
498
+ from core.hf_inference import HFInferenceClient
499
+
500
+ # HFInferenceClient gets token from settings/env
501
+ client = HFInferenceClient()
502
+
503
+ # Build prompt
504
+ prompt = self._build_analysis_prompt(stats, type_options, spacing_options)
505
+
506
+ self.log("📤 Sending analysis request to LLM...")
507
+
508
+ # Use the agent-specific complete method
509
+ response = await client.complete_async(
510
+ agent_name="advisor",
511
+ system_prompt="You are a Senior Design Systems Architect analyzing design tokens.",
512
+ user_message=prompt,
513
+ max_tokens=1500,
514
+ )
515
+
516
+ self.log("📥 Received LLM response")
517
+
518
+ # Parse LLM response
519
+ return self._parse_llm_response(response)
520
+
521
+ except Exception as e:
522
+ self.log(f"⚠️ LLM error: {str(e)}, using default recommendations")
523
+ return self._get_default_recommendations(stats, type_options, spacing_options)
524
+
525
+ def _build_analysis_prompt(self, stats: dict, type_options: list, spacing_options: list) -> str:
526
+ """Build the prompt for LLM analysis."""
527
+
528
+ # Format colors
529
+ colors_str = "\n".join([
530
+ f" - {data['value']}: frequency={data['frequency']}, contexts={data['contexts'][:3]}"
531
+ for hex_val, data in list(stats['colors'].items())[:10]
532
+ ])
533
+
534
+ # Format typography
535
+ typo_str = "\n".join([
536
+ f" - {t['font_family']} {t['font_size']} (weight: {t['font_weight']}, freq: {t['frequency']})"
537
+ for t in stats['typography']['desktop'][:10]
538
+ ])
539
+
540
+ # Format spacing
541
+ spacing_str = f"Desktop: {sorted(stats['spacing']['desktop'])[:15]}"
542
+
543
+ return f"""You are a Senior Design Systems Architect. Analyze these extracted design tokens and provide recommendations based on industry best practices.
544
+
545
+ ## EXTRACTED TOKENS
546
+
547
+ ### Colors (top 10 by frequency):
548
+ {colors_str}
549
+
550
+ ### Typography:
551
+ Primary font: {stats['primary_font']}
552
+ Base size: {stats['base_font_size']}px
553
+ {typo_str}
554
+
555
+ ### Spacing:
556
+ {spacing_str}
557
+
558
+ ## YOUR TASK
559
+
560
+ Research and compare against these top design systems:
561
+ 1. **Material Design 3** (Google) - Type scale, spacing grid, color system
562
+ 2. **Apple Human Interface Guidelines** - Typography scale, spacing
563
+ 3. **Shopify Polaris** - Type scale ratios, spacing system
564
+ 4. **IBM Carbon** - Type tokens, spacing tokens
565
+ 5. **Atlassian Design System** - Typography, spacing patterns
566
+
567
+ For each, note:
568
+ - Type scale ratio used
569
+ - Base font size
570
+ - Spacing grid (4px or 8px)
571
+ - Key observations
572
+
573
+ Then recommend:
574
+ 1. Which TYPE SCALE ratio (1.2, 1.25, or 1.333) best matches this site's existing design?
575
+ 2. Which SPACING BASE (4px or 8px) fits better?
576
+ 3. Any ACCESSIBILITY concerns with the detected colors?
577
+
578
+ Respond in this JSON format:
579
+ {{
580
+ "brand_analysis": [
581
+ {{"brand": "Material Design 3", "ratio": 1.2, "base": 16, "spacing": "8px", "notes": "..."}},
582
+ {{"brand": "Apple HIG", "ratio": 1.19, "base": 17, "spacing": "4px", "notes": "..."}},
583
+ {{"brand": "Shopify Polaris", "ratio": 1.25, "base": 16, "spacing": "4px", "notes": "..."}},
584
+ {{"brand": "IBM Carbon", "ratio": 1.25, "base": 14, "spacing": "8px", "notes": "..."}},
585
+ {{"brand": "Atlassian", "ratio": 1.14, "base": 14, "spacing": "8px", "notes": "..."}}
586
+ ],
587
+ "recommended_type_scale": "minor_third|major_third|perfect_fourth|keep",
588
+ "recommended_spacing": "8px|4px|keep",
589
+ "rationale": "Detailed explanation comparing the extracted tokens to the brand analysis...",
590
+ "color_observations": "Analysis of the color palette compared to industry standards...",
591
+ "accessibility_issues": ["issue 1", "issue 2"]
592
+ }}"""
593
+
594
+ def _parse_llm_response(self, response: str) -> dict:
595
+ """Parse LLM response into structured recommendations."""
596
+ try:
597
+ # Try to extract JSON from response
598
+ import re
599
+ json_match = re.search(r'\{[\s\S]*\}', response)
600
+ if json_match:
601
+ parsed = json.loads(json_match.group())
602
+ # Ensure all expected fields exist
603
+ parsed.setdefault("brand_analysis", [])
604
+ parsed.setdefault("recommended_type_scale", "major_third")
605
+ parsed.setdefault("recommended_spacing", "8px")
606
+ parsed.setdefault("rationale", "")
607
+ parsed.setdefault("color_observations", "")
608
+ parsed.setdefault("accessibility_issues", [])
609
+ return parsed
610
+ except Exception as e:
611
+ self.log(f" JSON parse error: {str(e)}")
612
+
613
+ # Default if parsing fails
614
+ return self._get_default_recommendations({}, [], [])
615
+
616
+ def _get_default_recommendations(self, stats: dict, type_options: list, spacing_options: list) -> dict:
617
+ """Get default recommendations without LLM."""
618
+
619
+ # Default brand analysis (rule-based knowledge)
620
+ brand_analysis = [
621
+ {"brand": "Material Design 3", "ratio": 1.2, "base": 16, "spacing": "8px",
622
+ "notes": "Google's design system uses Major Second (1.125) to Minor Third (1.2) scales"},
623
+ {"brand": "Apple HIG", "ratio": 1.19, "base": 17, "spacing": "4px",
624
+ "notes": "Apple uses SF Pro with dynamic type scaling, 4pt grid"},
625
+ {"brand": "Shopify Polaris", "ratio": 1.25, "base": 16, "spacing": "4px",
626
+ "notes": "Polaris uses Major Third (1.25) with 4px spacing unit"},
627
+ {"brand": "IBM Carbon", "ratio": 1.25, "base": 14, "spacing": "8px",
628
+ "notes": "Carbon uses productive (14px) and expressive (16px) type sets"},
629
+ {"brand": "Atlassian", "ratio": 1.14, "base": 14, "spacing": "8px",
630
+ "notes": "Atlassian uses a compact scale for dense interfaces"},
631
+ ]
632
+
633
+ # Recommend based on fit analysis if available
634
+ spacing_8_fit = 0
635
+ spacing_4_fit = 0
636
+ for opt in spacing_options:
637
+ if opt and hasattr(opt, 'id'):
638
+ if opt.id == "spacing_8px":
639
+ spacing_8_fit = opt.values.get("fit_analysis", {}).get("fit_percentage", 0)
640
+ elif opt.id == "spacing_4px":
641
+ spacing_4_fit = opt.values.get("fit_analysis", {}).get("fit_percentage", 0)
642
+
643
+ return {
644
+ "brand_analysis": brand_analysis,
645
+ "recommended_type_scale": "major_third",
646
+ "recommended_spacing": "8px" if spacing_8_fit >= spacing_4_fit else "4px",
647
+ "rationale": "Based on industry analysis: Major Third (1.25) type scale is the most commonly used ratio across modern design systems including Shopify Polaris and IBM Carbon. The 8px spacing grid is the modern standard used by Material Design and most enterprise design systems, providing a good balance between flexibility and consistency.",
648
+ "color_observations": "The detected color palette shows a neutral-heavy design with good contrast potential. Consider generating full color ramps for better UI state coverage (hover, active, disabled states).",
649
+ "accessibility_issues": [],
650
+ }
651
+
652
+ def _apply_llm_recommendations(
653
+ self,
654
+ type_options: list[UpgradeOption],
655
+ spacing_options: list[UpgradeOption],
656
+ color_options: list[UpgradeOption],
657
+ llm_analysis: dict
658
+ ):
659
+ """Apply LLM recommendations to options."""
660
+
661
+ # Mark recommended type scale
662
+ rec_type = llm_analysis.get("recommended_type_scale", "major_third")
663
+ for opt in type_options:
664
+ if rec_type in opt.id:
665
+ opt.recommended = True
666
+ opt.description += " ⭐ LLM Recommended"
667
+
668
+ # Mark recommended spacing
669
+ rec_spacing = llm_analysis.get("recommended_spacing", "8px")
670
+ for opt in spacing_options:
671
+ if rec_spacing.replace("px", "") in opt.id:
672
+ opt.recommended = True
673
+ opt.description += " ⭐ LLM Recommended"
674
+
675
+
676
+ # =============================================================================
677
+ # CONVENIENCE FUNCTIONS
678
+ # =============================================================================
679
+
680
+ async def analyze_design_system(
681
+ desktop_tokens: NormalizedTokens,
682
+ mobile_tokens: NormalizedTokens,
683
+ log_callback: Optional[Callable[[str], None]] = None
684
+ ) -> UpgradeRecommendations:
685
+ """
686
+ Convenience function to analyze a design system.
687
+
688
+ Args:
689
+ desktop_tokens: Normalized desktop tokens
690
+ mobile_tokens: Normalized mobile tokens
691
+ log_callback: Optional callback for logging
692
+
693
+ Returns:
694
+ UpgradeRecommendations
695
+ """
696
+ advisor = DesignSystemAdvisor(log_callback=log_callback)
697
+ return await advisor.analyze(desktop_tokens, mobile_tokens)