stylesheet_service.dart (8350B)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; // A simple model to hold the extracted design tokens class StylesheetData { final List<Color> colors; final List<String> fonts; final List<String> graphics; final List<String> compositions; final List<String> materialLook; final List<String> textures; final List<String> lighting; final List<String> style; final List<String> era; final List<String> emotions; StylesheetData({ required this.colors, required this.fonts, this.graphics = const [], this.compositions = const [], this.materialLook = const [], this.textures = const [], this.lighting = const [], this.style = const [], this.era = const [], this.emotions = const [], }); } class StylesheetService { // Main entry point: Parses a raw (potentially dirty) JSON string // and returns a structured [StylesheetData] object StylesheetData parse(String? rawJson) { if (rawJson == null || rawJson.isEmpty) { return StylesheetData(colors: [], fonts: []); } // 1. Parse the string into a Map Map<String, dynamic> data = _parseRawJson(rawJson); // 2. Extract and Process Fonts List<String> fonts = _extractFonts(data); // 3. Extract and Process Colors List<Color> colors = _extractColors(data); // 4. Extract other attributes return StylesheetData( colors: colors, fonts: fonts, graphics: _extractStrings(data, [ 'Graphics', 'graphics', ], valueKey: 'path'), compositions: _extractStrings(data, [ 'Compositions', 'Composition', 'compositions', ]), materialLook: _extractStrings(data, [ 'Material look', 'Material Look', 'material_look', ]), textures: _extractStrings(data, [ 'Textures', 'Background/Texture', 'textures', ]), lighting: _extractStrings(data, ['Lighting', 'lighting']), style: _extractStrings(data, ['Style', 'style']), era: _extractStrings(data, ['Era/Cultural Reference', 'Era', 'era']), emotions: _extractStrings(data, ['Emotions', 'Emotional', 'emotions']), ); } // --------------------------------------------------------------------------- // PARSING LOGIC // --------------------------------------------------------------------------- // Safely parses the raw string into a Map, handling dirty AI output Map<String, dynamic> _parseRawJson(String rawString) { try { // Try standard decode first return _normalizeResult(jsonDecode(rawString)); } catch (e) { try { // Try cleaning regex then decoding final cleaned = _cleanJsonString(rawString); return _normalizeResult(jsonDecode(cleaned)); } catch (_) { return {}; } } } /// Cleans "dirty" JSON strings by fixing quotes and unquoted keys String _cleanJsonString(String raw) { String cleaned = raw; // Remove Markdown code blocks if present (common AI artifact) cleaned = cleaned.replaceAll(RegExp(r'^```json\s*|\s*```$'), ''); // Add quotes to keys cleaned = cleaned.replaceAllMapped( RegExp(r'([{,]\s*)([a-zA-Z0-9_\s/]+)(\s*:)'), (match) => '${match[1]}"${match[2]?.trim()}"${match[3]}', ); // Add quotes to string values that aren't booleans or numbers cleaned = cleaned.replaceAllMapped( RegExp(r'(:\s*)([a-zA-Z0-9_\-\.\/\s]+)(?=\s*[,}])'), (match) { String val = match[2]!.trim(); if (val == 'true' || val == 'false' || val == 'null' || double.tryParse(val) != null) { return match[0]!; } return '${match[1]}"$val"'; }, ); return cleaned; } // Normalizes the structure if the API returns { "results": ... } Map<String, dynamic> _normalizeResult(dynamic parsed) { if (parsed is String) { try { parsed = jsonDecode(parsed); } catch (_) {} } if (parsed is Map<String, dynamic>) { if (parsed.containsKey('results') && parsed['results'] is Map) { return parsed['results']; } return parsed; } return {}; } // --------------------------------------------------------------------------- // EXTRACTION LOGIC // --------------------------------------------------------------------------- // Extracts font names and resolves them to valid Google Font strings. List<String> _extractFonts(Map<String, dynamic> data) { dynamic fontData = _findValue(data, [ 'Typography', 'fonts', 'typography', 'Fonts', ]); if (fontData == null) return []; List<String> rawNames = []; if (fontData is List) { for (var item in fontData) { if (item is Map && item.containsKey('label')) { rawNames.add(item['label'].toString().trim()); } else if (item is String) { rawNames.add(item.trim()); } } } else if (fontData is Map && fontData.containsKey('label')) { rawNames.add(fontData['label'].toString().trim()); } else if (fontData is String) { rawNames.add(fontData.trim()); } return rawNames.map((name) => _resolveGoogleFontName(name)).toList(); } // Extracts colors from Hex codes or semantic labels List<Color> _extractColors(Map<String, dynamic> data) { dynamic colorData = _findValue(data, [ 'Colour Palette', 'Color Palette', 'colors', 'Colors', ]); if (colorData == null) return []; List<Color> resolvedColors = []; if (colorData is List) { for (var item in colorData) { String? label; if (item is Map) { label = item['label']?.toString(); } else if (item is String) { label = item; } if (label != null) { resolvedColors.add(_parseColor(label)); } } } return resolvedColors; } // Generic helper to extract a list of strings from various keys // Supports extraction from [{ "label": "val" }] or ["val"] or "val" List<String> _extractStrings( Map<String, dynamic> data, List<String> keys, { String valueKey = 'label', }) { dynamic rawData = _findValue(data, keys); if (rawData == null) return []; List<String> results = []; if (rawData is List) { for (var item in rawData) { if (item is Map && item.containsKey(valueKey)) { results.add(item[valueKey].toString()); } else if (item is String) { results.add(item); } } } else if (rawData is Map && rawData.containsKey(valueKey)) { results.add(rawData[valueKey].toString()); } else if (rawData is String) { results.add(rawData); } return results; } // --------------------------------------------------------------------------- // HELPERS // --------------------------------------------------------------------------- dynamic _findValue(Map<String, dynamic> map, List<String> keys) { for (var k in keys) { if (map.containsKey(k)) return map[k]; // Case-insensitive check for (var mapKey in map.keys) { if (mapKey.toLowerCase() == k.toLowerCase()) return map[mapKey]; } } return null; } String _resolveGoogleFontName(String dirtyName) { // 1. Exact match check (fastest) try { GoogleFonts.getFont(dirtyName); return dirtyName; } catch (_) {} // 2. Fuzzy match String cleanInput = dirtyName .toLowerCase() .replaceAll(RegExp(r'[-_]regular$'), '') .replaceAll(RegExp(r'[^a-z0-9]'), ''); final allFonts = GoogleFonts.asMap().keys; for (String officialName in allFonts) { String cleanOfficial = officialName.toLowerCase().replaceAll( RegExp(r'[^a-z0-9]'), '', ); if (cleanOfficial == cleanInput) { return officialName; } } return dirtyName; // Fallback } Color _parseColor(String input) { if (input.startsWith('#') || input.length == 6) { try { String hex = input.replaceAll('#', ''); if (hex.length == 6) { return Color(int.parse('0xFF$hex')); } } catch (_) {} } return Colors.grey.shade400; // Default fallback } } |