core.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. UI/UX Pro Max Core - BM25 search engine for UI/UX style guides
  5. """
  6. import csv
  7. import re
  8. from pathlib import Path
  9. from math import log
  10. from collections import defaultdict
  11. # ============ CONFIGURATION ============
  12. DATA_DIR = Path(__file__).parent.parent / "data"
  13. MAX_RESULTS = 3
  14. CSV_CONFIG = {
  15. "style": {
  16. "file": "styles.csv",
  17. "search_cols": ["Style Category", "Keywords", "Best For", "Type"],
  18. "output_cols": ["Style Category", "Type", "Keywords", "Primary Colors", "Effects & Animation", "Best For", "Performance", "Accessibility", "Framework Compatibility", "Complexity"]
  19. },
  20. "prompt": {
  21. "file": "prompts.csv",
  22. "search_cols": ["Style Category", "AI Prompt Keywords (Copy-Paste Ready)", "CSS/Technical Keywords"],
  23. "output_cols": ["Style Category", "AI Prompt Keywords (Copy-Paste Ready)", "CSS/Technical Keywords", "Implementation Checklist"]
  24. },
  25. "color": {
  26. "file": "colors.csv",
  27. "search_cols": ["Product Type", "Keywords", "Notes"],
  28. "output_cols": ["Product Type", "Keywords", "Primary (Hex)", "Secondary (Hex)", "CTA (Hex)", "Background (Hex)", "Text (Hex)", "Border (Hex)", "Notes"]
  29. },
  30. "chart": {
  31. "file": "charts.csv",
  32. "search_cols": ["Data Type", "Keywords", "Best Chart Type", "Accessibility Notes"],
  33. "output_cols": ["Data Type", "Keywords", "Best Chart Type", "Secondary Options", "Color Guidance", "Accessibility Notes", "Library Recommendation", "Interactive Level"]
  34. },
  35. "landing": {
  36. "file": "landing.csv",
  37. "search_cols": ["Pattern Name", "Keywords", "Conversion Optimization", "Section Order"],
  38. "output_cols": ["Pattern Name", "Keywords", "Section Order", "Primary CTA Placement", "Color Strategy", "Conversion Optimization"]
  39. },
  40. "product": {
  41. "file": "products.csv",
  42. "search_cols": ["Product Type", "Keywords", "Primary Style Recommendation", "Key Considerations"],
  43. "output_cols": ["Product Type", "Keywords", "Primary Style Recommendation", "Secondary Styles", "Landing Page Pattern", "Dashboard Style (if applicable)", "Color Palette Focus"]
  44. },
  45. "ux": {
  46. "file": "ux-guidelines.csv",
  47. "search_cols": ["Category", "Issue", "Description", "Platform"],
  48. "output_cols": ["Category", "Issue", "Platform", "Description", "Do", "Don't", "Code Example Good", "Code Example Bad", "Severity"]
  49. },
  50. "typography": {
  51. "file": "typography.csv",
  52. "search_cols": ["Font Pairing Name", "Category", "Mood/Style Keywords", "Best For", "Heading Font", "Body Font"],
  53. "output_cols": ["Font Pairing Name", "Category", "Heading Font", "Body Font", "Mood/Style Keywords", "Best For", "Google Fonts URL", "CSS Import", "Tailwind Config", "Notes"]
  54. },
  55. "icons": {
  56. "file": "icons.csv",
  57. "search_cols": ["Category", "Icon Name", "Keywords", "Best For"],
  58. "output_cols": ["Category", "Icon Name", "Keywords", "Library", "Import Code", "Usage", "Best For", "Style"]
  59. },
  60. "react": {
  61. "file": "react-performance.csv",
  62. "search_cols": ["Category", "Issue", "Keywords", "Description"],
  63. "output_cols": ["Category", "Issue", "Platform", "Description", "Do", "Don't", "Code Example Good", "Code Example Bad", "Severity"]
  64. },
  65. "web": {
  66. "file": "web-interface.csv",
  67. "search_cols": ["Category", "Issue", "Keywords", "Description"],
  68. "output_cols": ["Category", "Issue", "Platform", "Description", "Do", "Don't", "Code Example Good", "Code Example Bad", "Severity"]
  69. }
  70. }
  71. STACK_CONFIG = {
  72. "html-tailwind": {"file": "stacks/html-tailwind.csv"},
  73. "react": {"file": "stacks/react.csv"},
  74. "nextjs": {"file": "stacks/nextjs.csv"},
  75. "vue": {"file": "stacks/vue.csv"},
  76. "nuxtjs": {"file": "stacks/nuxtjs.csv"},
  77. "nuxt-ui": {"file": "stacks/nuxt-ui.csv"},
  78. "svelte": {"file": "stacks/svelte.csv"},
  79. "swiftui": {"file": "stacks/swiftui.csv"},
  80. "react-native": {"file": "stacks/react-native.csv"},
  81. "flutter": {"file": "stacks/flutter.csv"},
  82. "shadcn": {"file": "stacks/shadcn.csv"},
  83. "jetpack-compose": {"file": "stacks/jetpack-compose.csv"}
  84. }
  85. # Common columns for all stacks
  86. _STACK_COLS = {
  87. "search_cols": ["Category", "Guideline", "Description", "Do", "Don't"],
  88. "output_cols": ["Category", "Guideline", "Description", "Do", "Don't", "Code Good", "Code Bad", "Severity", "Docs URL"]
  89. }
  90. AVAILABLE_STACKS = list(STACK_CONFIG.keys())
  91. # ============ BM25 IMPLEMENTATION ============
  92. class BM25:
  93. """BM25 ranking algorithm for text search"""
  94. def __init__(self, k1=1.5, b=0.75):
  95. self.k1 = k1
  96. self.b = b
  97. self.corpus = []
  98. self.doc_lengths = []
  99. self.avgdl = 0
  100. self.idf = {}
  101. self.doc_freqs = defaultdict(int)
  102. self.N = 0
  103. def tokenize(self, text):
  104. """Lowercase, split, remove punctuation, filter short words"""
  105. text = re.sub(r'[^\w\s]', ' ', str(text).lower())
  106. return [w for w in text.split() if len(w) > 2]
  107. def fit(self, documents):
  108. """Build BM25 index from documents"""
  109. self.corpus = [self.tokenize(doc) for doc in documents]
  110. self.N = len(self.corpus)
  111. if self.N == 0:
  112. return
  113. self.doc_lengths = [len(doc) for doc in self.corpus]
  114. self.avgdl = sum(self.doc_lengths) / self.N
  115. for doc in self.corpus:
  116. seen = set()
  117. for word in doc:
  118. if word not in seen:
  119. self.doc_freqs[word] += 1
  120. seen.add(word)
  121. for word, freq in self.doc_freqs.items():
  122. self.idf[word] = log((self.N - freq + 0.5) / (freq + 0.5) + 1)
  123. def score(self, query):
  124. """Score all documents against query"""
  125. query_tokens = self.tokenize(query)
  126. scores = []
  127. for idx, doc in enumerate(self.corpus):
  128. score = 0
  129. doc_len = self.doc_lengths[idx]
  130. term_freqs = defaultdict(int)
  131. for word in doc:
  132. term_freqs[word] += 1
  133. for token in query_tokens:
  134. if token in self.idf:
  135. tf = term_freqs[token]
  136. idf = self.idf[token]
  137. numerator = tf * (self.k1 + 1)
  138. denominator = tf + self.k1 * (1 - self.b + self.b * doc_len / self.avgdl)
  139. score += idf * numerator / denominator
  140. scores.append((idx, score))
  141. return sorted(scores, key=lambda x: x[1], reverse=True)
  142. # ============ SEARCH FUNCTIONS ============
  143. def _load_csv(filepath):
  144. """Load CSV and return list of dicts"""
  145. with open(filepath, 'r', encoding='utf-8') as f:
  146. return list(csv.DictReader(f))
  147. def _search_csv(filepath, search_cols, output_cols, query, max_results):
  148. """Core search function using BM25"""
  149. if not filepath.exists():
  150. return []
  151. data = _load_csv(filepath)
  152. # Build documents from search columns
  153. documents = [" ".join(str(row.get(col, "")) for col in search_cols) for row in data]
  154. # BM25 search
  155. bm25 = BM25()
  156. bm25.fit(documents)
  157. ranked = bm25.score(query)
  158. # Get top results with score > 0
  159. results = []
  160. for idx, score in ranked[:max_results]:
  161. if score > 0:
  162. row = data[idx]
  163. results.append({col: row.get(col, "") for col in output_cols if col in row})
  164. return results
  165. def detect_domain(query):
  166. """Auto-detect the most relevant domain from query"""
  167. query_lower = query.lower()
  168. domain_keywords = {
  169. "color": ["color", "palette", "hex", "#", "rgb"],
  170. "chart": ["chart", "graph", "visualization", "trend", "bar", "pie", "scatter", "heatmap", "funnel"],
  171. "landing": ["landing", "page", "cta", "conversion", "hero", "testimonial", "pricing", "section"],
  172. "product": ["saas", "ecommerce", "e-commerce", "fintech", "healthcare", "gaming", "portfolio", "crypto", "dashboard"],
  173. "prompt": ["prompt", "css", "implementation", "variable", "checklist", "tailwind"],
  174. "style": ["style", "design", "ui", "minimalism", "glassmorphism", "neumorphism", "brutalism", "dark mode", "flat", "aurora"],
  175. "ux": ["ux", "usability", "accessibility", "wcag", "touch", "scroll", "animation", "keyboard", "navigation", "mobile"],
  176. "typography": ["font", "typography", "heading", "serif", "sans"],
  177. "icons": ["icon", "icons", "lucide", "heroicons", "symbol", "glyph", "pictogram", "svg icon"],
  178. "react": ["react", "next.js", "nextjs", "suspense", "memo", "usecallback", "useeffect", "rerender", "bundle", "waterfall", "barrel", "dynamic import", "rsc", "server component"],
  179. "web": ["aria", "focus", "outline", "semantic", "virtualize", "autocomplete", "form", "input type", "preconnect"]
  180. }
  181. scores = {domain: sum(1 for kw in keywords if kw in query_lower) for domain, keywords in domain_keywords.items()}
  182. best = max(scores, key=scores.get)
  183. return best if scores[best] > 0 else "style"
  184. def search(query, domain=None, max_results=MAX_RESULTS):
  185. """Main search function with auto-domain detection"""
  186. if domain is None:
  187. domain = detect_domain(query)
  188. config = CSV_CONFIG.get(domain, CSV_CONFIG["style"])
  189. filepath = DATA_DIR / config["file"]
  190. if not filepath.exists():
  191. return {"error": f"File not found: {filepath}", "domain": domain}
  192. results = _search_csv(filepath, config["search_cols"], config["output_cols"], query, max_results)
  193. return {
  194. "domain": domain,
  195. "query": query,
  196. "file": config["file"],
  197. "count": len(results),
  198. "results": results
  199. }
  200. def search_stack(query, stack, max_results=MAX_RESULTS):
  201. """Search stack-specific guidelines"""
  202. if stack not in STACK_CONFIG:
  203. return {"error": f"Unknown stack: {stack}. Available: {', '.join(AVAILABLE_STACKS)}"}
  204. filepath = DATA_DIR / STACK_CONFIG[stack]["file"]
  205. if not filepath.exists():
  206. return {"error": f"Stack file not found: {filepath}", "stack": stack}
  207. results = _search_csv(filepath, _STACK_COLS["search_cols"], _STACK_COLS["output_cols"], query, max_results)
  208. return {
  209. "domain": "stack",
  210. "stack": stack,
  211. "query": query,
  212. "file": STACK_CONFIG[stack]["file"],
  213. "count": len(results),
  214. "results": results
  215. }