Spaces:
Paused
Paused
Download yui_code_discipline.py from BachDaThan/Ural-AI: direct link, hf CLI and curl.
- Browser
- Download file 15.8 kB
-
https://huggingface.co/spaces/BachDaThan/Ural-AI/resolve/main/yui_code_discipline.py
- Command line
-
hf download hf://spaces/BachDaThan/Ural-AI/yui_code_discipline.py
-
curl -L -o yui_code_discipline.py https://huggingface.co/spaces/BachDaThan/Ural-AI/resolve/main/yui_code_discipline.py
15.8 kB
| # ╔══════════════════════════════════════════════════════════════════════════╗ | |
| # ║ YUI CODE DISCIPLINE ENGINE v1.0 ║ | |
| # ║ "Superpowers" cho Yui — 7-step kỷ luật kỹ sư trước khi viết code ║ | |
| # ╠══════════════════════════════════════════════════════════════════════════╣ | |
| # ║ Cảm hứng: Superpowers repo (195K stars) + Andrej Karpathy claude.md ║ | |
| # ║ KHÁC BIỆT: Không chỉ là Markdown — tích hợp sâu vào Code Engine ║ | |
| # ║ [1] Pre-code brainstorm [5] Self-review tier 1 (logic) ║ | |
| # ║ [2] Decompose intent [6] Self-review tier 2 (style/edge) ║ | |
| # ║ [3] Algorithm plan [7] Output verification ║ | |
| # ║ [4] Write → verify loop ║ | |
| # ╚══════════════════════════════════════════════════════════════════════════╝ | |
| import re | |
| from typing import Dict, Tuple, Optional, List | |
| from dataclasses import dataclass, field | |
| # ══════════════════════════════════════════════════════════════════ | |
| # [LAYER 1] TASK CLASSIFIER — Phân loại yêu cầu code | |
| # ══════════════════════════════════════════════════════════════════ | |
| class CodeTask: | |
| raw_query: str | |
| task_category: str # algorithm|ui|data|api|fix|refactor|explain|design | |
| complexity: str # simple|medium|complex|architecture | |
| language: str # python|js|html|css|sql|bash|other | |
| has_ui: bool # Có cần render giao diện không | |
| has_animation: bool # Có cần animation không | |
| needs_math: bool # Có cần tính toán/vật lý không | |
| is_visual: bool # Output là visual (canvas, chart, game) | |
| priority_rules: List[str] # Rules quan trọng nhất cho task này | |
| _LANG_PATTERNS = { | |
| "python": r"\bpython\b|\.py\b|pandas|numpy|fastapi|flask|django", | |
| "js": r"\bjavascript\b|\bjs\b|node\.js|react|vue|angular|typescript", | |
| "html": r"\bhtml\b|\.html|webpage|web page|trang web|giao diện web", | |
| "css": r"\bcss\b|styling|stylesheet", | |
| "sql": r"\bsql\b|mysql|postgresql|sqlite|query|database", | |
| "bash": r"\bbash\b|shell|linux command|terminal", | |
| } | |
| _CATEGORY_PATTERNS = { | |
| "algorithm": r"thuật toán|algorithm|sort|search|dynamic programming|đệ quy|recursion|BFS|DFS|graph", | |
| "ui": r"giao diện|UI|UX|component|button|form|layout|responsive|dark mode|design", | |
| "animation": r"animation|animate|dao động|chuyển động|particle|hiệu ứng|effect|transition|canvas|WebGL", | |
| "data": r"data|csv|excel|json|parse|extract|transform|clean|analyze", | |
| "api": r"API|endpoint|request|fetch|axios|REST|webhook|server|backend", | |
| "fix": r"fix|bug|lỗi|error|sửa|debug|không chạy|không hoạt động", | |
| "refactor": r"refactor|tối ưu|optimize|clean up|restructure|cải thiện", | |
| "explain": r"giải thích|explain|how does|tại sao|what is|review code", | |
| } | |
| _COMPLEXITY_SIGNALS = { | |
| "architecture": r"kiến trúc|architecture|system design|microservice|scalab|database schema", | |
| "complex": r"nhiều (chức năng|tính năng|module)|phức tạp|advanced|enterprise|full(stack|-.app)", | |
| "medium": r"class|function|module|component|algorithm|OOP|async", | |
| "simple": r"ví dụ đơn giản|hello world|basic|cơ bản|in ra|print|simple", | |
| } | |
| def classify_code_task(query: str) -> CodeTask: | |
| """Phân loại yêu cầu code để chọn đúng discipline rules.""" | |
| q = query.lower() | |
| # Detect language | |
| lang = "other" | |
| for l, p in _LANG_PATTERNS.items(): | |
| if re.search(p, q, re.I): | |
| lang = l | |
| break | |
| if lang == "other" and re.search(r"html|canvas|lò xo|spring|dao động|particle|vật lý|physics|visual|mô phỏng|simulation", q, re.I): | |
| lang = "html" | |
| # Detect category | |
| category = "general" | |
| for cat, pat in _CATEGORY_PATTERNS.items(): | |
| if re.search(pat, q, re.I): | |
| category = cat | |
| break | |
| # Detect complexity | |
| complexity = "medium" | |
| for cmx in ["architecture", "complex", "medium", "simple"]: | |
| if re.search(_COMPLEXITY_SIGNALS[cmx], q, re.I): | |
| complexity = cmx | |
| break | |
| # Special flags | |
| has_animation = bool(re.search(r"dao động|animation|animate|chuyển động|particle|lò xo|spring|physics|vật lý|canvas|wave|sóng|move|float", q, re.I)) | |
| has_ui = bool(re.search(r"html|giao diện|UI|button|form|page|dark|theme|responsive|layout", q, re.I)) | |
| is_visual = has_animation or bool(re.search(r"canvas|chart|biểu đồ|vẽ|draw|render|3D|WebGL|simulation|mô phỏng", q, re.I)) | |
| needs_math = bool(re.search(r"vật lý|physics|toán|math|calculate|tính|sin|cos|oscillat|dao động|wave|frequency|amplitude", q, re.I)) | |
| # Build priority rules | |
| priority_rules = _build_priority_rules(category, complexity, lang, has_animation, is_visual, needs_math) | |
| return CodeTask( | |
| raw_query=query, task_category=category, complexity=complexity, | |
| language=lang, has_ui=has_ui, has_animation=has_animation, | |
| needs_math=needs_math, is_visual=is_visual, priority_rules=priority_rules | |
| ) | |
| def _build_priority_rules(cat: str, cmx: str, lang: str, | |
| animation: bool, visual: bool, math: bool) -> List[str]: | |
| rules = [] | |
| if visual or animation: | |
| rules.extend([ | |
| "🎨 VISUAL QUALITY: Background tối (dark) mặc định — không bao giờ trắng trơn", | |
| "🎨 COLOR PALETTE: Dùng gradient, glow effect, màu sắc có chiều sâu", | |
| "🎨 POLISH: Shadow, blur, rounded corners — không bare-bones", | |
| ]) | |
| if animation: | |
| rules.extend([ | |
| "⚡ PHYSICS: Công thức vật lý chính xác (sin/cos cho dao động điều hòa)", | |
| "⚡ SMOOTHNESS: requestAnimationFrame, delta-time compensation", | |
| "⚡ LIFE: Thêm subtle randomness để trông tự nhiên — không quá cơ học", | |
| ]) | |
| if math: | |
| rules.extend([ | |
| "🔢 MATH ACCURACY: Kiểm tra công thức trước khi code, test boundary values", | |
| "🔢 COMMENTS: Ghi chú công thức bằng ký hiệu toán học trong comment", | |
| ]) | |
| if lang == "html": | |
| rules.extend([ | |
| "📦 SELF-CONTAINED: 1 file duy nhất, không external dependencies trừ CDN", | |
| "📦 RESPONSIVE: canvas resize đúng cách, mobile-friendly", | |
| ]) | |
| if cat in ("algorithm", "data"): | |
| rules.extend([ | |
| "🧪 TEST INLINE: Thêm test cases với giá trị cụ thể vào cuối code", | |
| "🧪 EDGE CASES: Xử lý empty input, null, boundary values", | |
| ]) | |
| if cmx in ("complex", "architecture"): | |
| rules.extend([ | |
| "🏗️ STRUCTURE FIRST: Comment outline toàn bộ architecture trước khi code", | |
| "🏗️ SEPARATION: Tách UI / Logic / State rõ ràng", | |
| ]) | |
| # Universal rules | |
| rules.append("✅ RUNS IMMEDIATELY: Copy-paste phải chạy được ngay — không thiếu gì") | |
| return rules | |
| # ══════════════════════════════════════════════════════════════════ | |
| # [LAYER 2] 7-STEP DISCIPLINE PROMPT | |
| # ══════════════════════════════════════════════════════════════════ | |
| _STEP_TEMPLATES = { | |
| "simple": """[CODE DISCIPLINE — SIMPLE MODE] | |
| Trước khi viết, đảm bảo: | |
| • Đọc kỹ yêu cầu — output cụ thể là gì? | |
| • Code phải chạy ngay khi copy-paste | |
| • Không stub, không placeholder | |
| {priority_rules}""", | |
| "medium": """[CODE DISCIPLINE — 7 STEPS] | |
| Yui PHẢI thực hiện 7 bước này TRONG ĐẦU trước khi xuất code: | |
| STEP 1 BRAINSTORM: Yêu cầu cốt lõi là gì? Edge cases nào? | |
| STEP 2 DECOMPOSE: Chia nhỏ thành sub-tasks có thể test độc lập | |
| STEP 3 ALGORITHM: Chọn approach đơn giản nhất đúng với yêu cầu | |
| STEP 4 WRITE: Viết code — tên biến rõ nghĩa, comment cho logic phức tạp | |
| STEP 5 REVIEW-1: Logic đúng không? Công thức chính xác không? | |
| STEP 6 REVIEW-2: Edge cases? Memory leaks? Performance? | |
| STEP 7 VERIFY: Test với ví dụ cụ thể — output đúng không? | |
| PRIORITY RULES CHO TASK NÀY: | |
| {priority_rules} | |
| OUTPUT YÊU CẦU: | |
| • Code đầy đủ, chạy được ngay | |
| • Không viết "TODO", "placeholder", "implement later" | |
| • Comment giải thích logic phức tạp""", | |
| "complex": """[CODE DISCIPLINE — ARCHITECT MODE] | |
| Task này phức tạp — Yui cần lập kế hoạch trước. | |
| [BRAINSTORM] | |
| • Requirements: [liệt kê functional + non-functional] | |
| • Constraints: [giới hạn về performance, compatibility, size] | |
| • Success criteria: [khi nào coi là xong?] | |
| [ARCHITECTURE PLAN] | |
| • Component breakdown: [các phần chính] | |
| • Data flow: [dữ liệu đi qua đâu] | |
| • State management: [state ở đâu, ai quản lý] | |
| [IMPLEMENTATION ORDER] | |
| 1. Core logic first (không UI) | |
| 2. UI/rendering layer | |
| 3. Polish + edge cases | |
| PRIORITY RULES: | |
| {priority_rules} | |
| SAU KHI CODE XONG: | |
| • Self-review: đọc lại toàn bộ 1 lần | |
| • Verify: chạy thử với scenario cụ thể | |
| • Note: ghi chú những trade-off đã quyết định""", | |
| } | |
| def get_discipline_prompt(task: CodeTask) -> str: | |
| """Tạo discipline prompt phù hợp với complexity của task.""" | |
| template = _STEP_TEMPLATES.get(task.complexity, _STEP_TEMPLATES["medium"]) | |
| rules_str = "\n".join(f" {r}" for r in task.priority_rules) | |
| return template.format(priority_rules=rules_str) | |
| # ══════════════════════════════════════════════════════════════════ | |
| # [LAYER 3] VISUAL QUALITY ENFORCER | |
| # Đây là vấn đề của Yui: code chạy được nhưng thiếu "hồn" | |
| # ══════════════════════════════════════════════════════════════════ | |
| VISUAL_QUALITY_STANDARDS = """ | |
| [TIÊU CHUẨN VISUAL CHẤT LƯỢNG CAO — BẮT BUỘC CHO MỌI OUTPUT VISUAL] | |
| 🎨 COLOR & THEME: | |
| • Background: #0a0a0a hoặc gradient tối — KHÔNG BAO GIỜ trắng trơn (#fff) | |
| • Primary accent: màu neon/glow phù hợp theme (cyan, purple, gold...) | |
| • Contrast: text và elements phải readable, không bị lẫn | |
| • Consistency: palette 2-3 màu chính, sử dụng nhất quán | |
| ✨ POLISH ELEMENTS (ít nhất 3 trong số sau): | |
| • Glow/shadow effect: box-shadow, filter: drop-shadow, hoặc canvas shadow | |
| • Gradient: linear-gradient hoặc radial-gradient thay solid color | |
| • Smooth animation: easing functions, không linear cứng đơ | |
| • Particle/trail effect: thêm chiều sâu cho animation | |
| • Blur backdrop: glassmorphism nếu có overlay | |
| • Typography: Google Fonts hoặc system font stack đẹp | |
| 🎬 ANIMATION QUALITY: | |
| • requestAnimationFrame — không dùng setInterval cho animation | |
| • Delta-time: chuẩn hóa speed theo thời gian thực | |
| • Subtle variation: random seed nhỏ để trông "sống" | |
| • Loop seamless: khi loop lại phải không giật | |
| 📐 LAYOUT & UX: | |
| • Center elements đúng cách | |
| • Padding/margin hợp lý | |
| • Mobile-aware: không bị vỡ trên màn nhỏ | |
| • Optional controls: thêm slider/button nếu phù hợp | |
| 📝 CODE QUALITY: | |
| • Constants ở đầu file với tên rõ nghĩa | |
| • Comment giải thích physics/math formula | |
| • requestAnimationFrame ID để có thể cancel | |
| • Cleanup listeners khi cần | |
| """ | |
| # ══════════════════════════════════════════════════════════════════ | |
| # [LAYER 4] POST-REVIEW CHECKLIST | |
| # ══════════════════════════════════════════════════════════════════ | |
| def get_post_review_prompt(task: CodeTask) -> str: | |
| """Checklist tự review sau khi code xong.""" | |
| checks = [ | |
| "✓ Code chạy được ngay khi copy-paste?", | |
| "✓ Không có TODO / placeholder / stub?", | |
| "✓ Import đủ, không thiếu dependency?", | |
| ] | |
| if task.is_visual: | |
| checks += [ | |
| "✓ Background không phải trắng trơn?", | |
| "✓ Có ít nhất 3 polish elements?", | |
| "✓ Animation mượt không giật?", | |
| ] | |
| if task.needs_math: | |
| checks += [ | |
| "✓ Công thức vật lý/toán đã verify?", | |
| "✓ Edge cases (zero, negative, large) được handle?", | |
| ] | |
| if task.has_animation: | |
| checks += [ | |
| "✓ requestAnimationFrame (không phải setInterval)?", | |
| "✓ Loop seamless?", | |
| ] | |
| return "[POST-CODE SELF-REVIEW]\n" + "\n".join(checks) | |
| # ══════════════════════════════════════════════════════════════════ | |
| # PUBLIC API | |
| # ══════════════════════════════════════════════════════════════════ | |
| def get_code_discipline_context(query: str) -> Tuple[str, CodeTask]: | |
| """ | |
| Public API: Lấy full discipline context để inject vào system_prompt. | |
| Trả về (context_string, CodeTask) để Smart Router có thể dùng. | |
| """ | |
| task = classify_code_task(query) | |
| parts = [] | |
| # Discipline steps | |
| parts.append(get_discipline_prompt(task)) | |
| # Visual quality nếu là task visual | |
| if task.is_visual or task.has_animation or task.has_ui: | |
| parts.append(VISUAL_QUALITY_STANDARDS) | |
| # Post-review checklist | |
| parts.append(get_post_review_prompt(task)) | |
| return "\n\n".join(parts), task | |
| def should_apply_discipline(task_type: str, query: str) -> bool: | |
| """Kiểm tra có nên inject discipline không.""" | |
| code_tasks = {"code", "debug", "ui", "math"} | |
| if task_type not in code_tasks: | |
| return False | |
| # Không inject cho explain-only requests | |
| explain_only = re.search(r"^(giải thích|explain|review|đọc|phân tích).{0,30}(code|đoạn|hàm)", query.lower()) | |
| return not explain_only | |
| _discipline_stats = {"applied": 0, "visual_enhanced": 0} | |
| def get_discipline_stats() -> Dict: | |
| return _discipline_stats.copy() | |
| print("[CODE-DISCIPLINE] ✅ Yui Code Discipline Engine v1.0 loaded") | |
| print("[CODE-DISCIPLINE] 7-step process | Visual enforcer | Post-review checklist") | |