core.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. }
  56. STACK_CONFIG = {
  57. "html-tailwind": {"file": "stacks/html-tailwind.csv"},
  58. "react": {"file": "stacks/react.csv"},
  59. "nextjs": {"file": "stacks/nextjs.csv"},
  60. "vue": {"file": "stacks/vue.csv"},
  61. "svelte": {"file": "stacks/svelte.csv"},
  62. "swiftui": {"file": "stacks/swiftui.csv"},
  63. "react-native": {"file": "stacks/react-native.csv"},
  64. "flutter": {"file": "stacks/flutter.csv"}
  65. }
  66. # Common columns for all stacks
  67. _STACK_COLS = {
  68. "search_cols": ["Category", "Guideline", "Description", "Do", "Don't"],
  69. "output_cols": ["Category", "Guideline", "Description", "Do", "Don't", "Code Good", "Code Bad", "Severity", "Docs URL"]
  70. }
  71. AVAILABLE_STACKS = list(STACK_CONFIG.keys())
  72. # ============ BM25 IMPLEMENTATION ============
  73. class BM25:
  74. """BM25 ranking algorithm for text search"""
  75. def __init__(self, k1=1.5, b=0.75):
  76. self.k1 = k1
  77. self.b = b
  78. self.corpus = []
  79. self.doc_lengths = []
  80. self.avgdl = 0
  81. self.idf = {}
  82. self.doc_freqs = defaultdict(int)
  83. self.N = 0
  84. def tokenize(self, text):
  85. """Lowercase, split, remove punctuation, filter short words"""
  86. text = re.sub(r'[^\w\s]', ' ', str(text).lower())
  87. return [w for w in text.split() if len(w) > 2]
  88. def fit(self, documents):
  89. """Build BM25 index from documents"""
  90. self.corpus = [self.tokenize(doc) for doc in documents]
  91. self.N = len(self.corpus)
  92. if self.N == 0:
  93. return
  94. self.doc_lengths = [len(doc) for doc in self.corpus]
  95. self.avgdl = sum(self.doc_lengths) / self.N
  96. for doc in self.corpus:
  97. seen = set()
  98. for word in doc:
  99. if word not in seen:
  100. self.doc_freqs[word] += 1
  101. seen.add(word)
  102. for word, freq in self.doc_freqs.items():
  103. self.idf[word] = log((self.N - freq + 0.5) / (freq + 0.5) + 1)
  104. def score(self, query):
  105. """Score all documents against query"""
  106. query_tokens = self.tokenize(query)
  107. scores = []
  108. for idx, doc in enumerate(self.corpus):
  109. score = 0
  110. doc_len = self.doc_lengths[idx]
  111. term_freqs = defaultdict(int)
  112. for word in doc:
  113. term_freqs[word] += 1
  114. for token in query_tokens:
  115. if token in self.idf:
  116. tf = term_freqs[token]
  117. idf = self.idf[token]
  118. numerator = tf * (self.k1 + 1)
  119. denominator = tf + self.k1 * (1 - self.b + self.b * doc_len / self.avgdl)
  120. score += idf * numerator / denominator
  121. scores.append((idx, score))
  122. return sorted(scores, key=lambda x: x[1], reverse=True)
  123. # ============ SEARCH FUNCTIONS ============
  124. def _load_csv(filepath):
  125. """Load CSV and return list of dicts"""
  126. with open(filepath, 'r', encoding='utf-8') as f:
  127. return list(csv.DictReader(f))
  128. def _search_csv(filepath, search_cols, output_cols, query, max_results):
  129. """Core search function using BM25"""
  130. if not filepath.exists():
  131. return []
  132. data = _load_csv(filepath)
  133. # Build documents from search columns
  134. documents = [" ".join(str(row.get(col, "")) for col in search_cols) for row in data]
  135. # BM25 search
  136. bm25 = BM25()
  137. bm25.fit(documents)
  138. ranked = bm25.score(query)
  139. # Get top results with score > 0
  140. results = []
  141. for idx, score in ranked[:max_results]:
  142. if score > 0:
  143. row = data[idx]
  144. results.append({col: row.get(col, "") for col in output_cols if col in row})
  145. return results
  146. def detect_domain(query):
  147. """Auto-detect the most relevant domain from query"""
  148. query_lower = query.lower()
  149. domain_keywords = {
  150. "color": ["color", "palette", "hex", "#", "rgb"],
  151. "chart": ["chart", "graph", "visualization", "trend", "bar", "pie", "scatter", "heatmap", "funnel"],
  152. "landing": ["landing", "page", "cta", "conversion", "hero", "testimonial", "pricing", "section"],
  153. "product": ["saas", "ecommerce", "e-commerce", "fintech", "healthcare", "gaming", "portfolio", "crypto", "dashboard"],
  154. "prompt": ["prompt", "css", "implementation", "variable", "checklist", "tailwind"],
  155. "style": ["style", "design", "ui", "minimalism", "glassmorphism", "neumorphism", "brutalism", "dark mode", "flat", "aurora"],
  156. "ux": ["ux", "usability", "accessibility", "wcag", "touch", "scroll", "animation", "keyboard", "navigation", "mobile"],
  157. "typography": ["font", "typography", "heading", "serif", "sans"]
  158. }
  159. scores = {domain: sum(1 for kw in keywords if kw in query_lower) for domain, keywords in domain_keywords.items()}
  160. best = max(scores, key=scores.get)
  161. return best if scores[best] > 0 else "style"
  162. def search(query, domain=None, max_results=MAX_RESULTS):
  163. """Main search function with auto-domain detection"""
  164. if domain is None:
  165. domain = detect_domain(query)
  166. config = CSV_CONFIG.get(domain, CSV_CONFIG["style"])
  167. filepath = DATA_DIR / config["file"]
  168. if not filepath.exists():
  169. return {"error": f"File not found: {filepath}", "domain": domain}
  170. results = _search_csv(filepath, config["search_cols"], config["output_cols"], query, max_results)
  171. return {
  172. "domain": domain,
  173. "query": query,
  174. "file": config["file"],
  175. "count": len(results),
  176. "results": results
  177. }
  178. def search_stack(query, stack, max_results=MAX_RESULTS):
  179. """Search stack-specific guidelines"""
  180. if stack not in STACK_CONFIG:
  181. return {"error": f"Unknown stack: {stack}. Available: {', '.join(AVAILABLE_STACKS)}"}
  182. filepath = DATA_DIR / STACK_CONFIG[stack]["file"]
  183. if not filepath.exists():
  184. return {"error": f"Stack file not found: {filepath}", "stack": stack}
  185. results = _search_csv(filepath, _STACK_COLS["search_cols"], _STACK_COLS["output_cols"], query, max_results)
  186. return {
  187. "domain": "stack",
  188. "stack": stack,
  189. "query": query,
  190. "file": STACK_CONFIG[stack]["file"],
  191. "count": len(results),
  192. "results": results
  193. }