diff --git a/.env.example b/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..6c3579e7d1f2f793eb559ae52f760cccad4b60d9 --- /dev/null +++ b/.env.example @@ -0,0 +1,22 @@ +# API Keys +OPENAI_API_KEY=your_openai_api_key_here +ANTHROPIC_API_KEY=your_anthropic_api_key_here + +# Database +DATABASE_URL=sqlite:///./data/burme_coder.db + +# Cache +CACHE_DIR=./data/cache +CACHE_TTL=3600 + +# Animation Settings +ANIMATION_SPEED=0.05 +ANIMATION_COLOR=true + +# Knowledge Base +KNOWLEDGE_DIR=./data/knowledge +ENABLE_WEB_UPDATE=false + +# Logging +LOG_LEVEL=INFO +LOG_FILE=./logs/burme_coder.log diff --git a/README.md b/README.md index e5e6e447fa1cc75fda54781db9b7b5197a197c64..34db4c61670a20e244a0e99b7cdd024c5be1ac28 100644 --- a/README.md +++ b/README.md @@ -1,88 +1,129 @@ ---- -annotations_creators: -- no-annotation -language: -- my -- en -license: mit -multilinguality: -- multilingual -size_categories: -- n<1K -task_categories: -- text-generation -task_ids: -- instruction-tuning -configs: -- config_name: default - data_files: - - split: train - path: data/train-* -dataset_info: - features: - - name: system - dtype: large_string - - name: instruction - dtype: large_string - - name: response - dtype: large_string - splits: - - name: train - num_bytes: 210606 - num_examples: 302 - download_size: 81189 - dataset_size: 210606 ---- - -# burme-coder-max - -A coder-focused dataset with strong Burmese (Myanmar) language support for training AI coding assistants. - -## Dataset Description - -This dataset is designed for training AI coding assistants with: -- **Bilingual support** (Burmese + English) -- **Comprehensive coding examples** covering multiple programming languages -- **Practical, real-world scenarios** -- **Detailed explanations in Burmese** - -## Dataset Structure - -| Field | Type | Description | -|-------|------|-------------| -| system | string | System prompt (bilingual coder behavior) | -| instruction | string | User's coding task in Burmese or English | -| response | string | Complete code solution with Burmese explanations | - -## Programming Languages Covered - -- Python -- JavaScript / Node.js -- TypeScript / React -- SQL -- Go -- Django REST Framework -- Docker -- Git - -## Usage +# ๐Ÿง‘โ€๐Ÿ’ป Burme-Coder-Max + +Expert Myanmar AI coding agent - แ€™แ€ผแ€”แ€บแ€™แ€ฌแ€˜แ€ฌแ€žแ€ฌแ€–แ€ผแ€„แ€ทแ€บ แ€€แ€ฏแ€’แ€บแ€›แ€ฑแ€ธแ€žแ€„แ€บแ€แ€”แ€บแ€ธ AI Agent + +## ๐ŸŽฏ แ€กแ€“แ€ญแ€€ แ€œแ€ฏแ€•แ€บแ€†แ€ฑแ€ฌแ€„แ€บแ€แ€ปแ€€แ€บแ€™แ€ปแ€ฌแ€ธ + +- **๐Ÿ—ฃ๏ธ แ€™แ€ผแ€”แ€บแ€™แ€ฌแ€˜แ€ฌแ€žแ€ฌ**: แ€™แ€ผแ€”แ€บแ€™แ€ฌแ€…แ€ฌแ€”แ€ฒแ€ท แ€€แ€ฏแ€’แ€บแ€›แ€ฑแ€ธแ€žแ€„แ€บแ€แ€”แ€บแ€ธ แ€•แ€ฑแ€ธแ€”แ€ญแ€ฏแ€„แ€บ +- **๐Ÿ’ป Code Examples**: Python, JavaScript, TypeScript, SQL, Go, Rust แ€”แ€ฒแ€ท แ€กแ€แ€ผแ€ฌแ€ธแ€˜แ€ฌแ€žแ€ฌแ€…แ€€แ€ฌแ€ธแ€™แ€ปแ€ฌแ€ธ +- **โœจ Terminal Animations**: Spinners, progress bars, particle effects +- **๐Ÿ“š Knowledge Base**: Local markdown files + web updates +- **๐Ÿ”„ Auto Update**: Web scraping แ€€แ€”แ€ฑ knowledge update + +## ๐Ÿ“ฆ Installation + +```bash +pip install burme-coder-max +``` + +แ€žแ€ญแ€ฏแ€ทแ€™แ€Ÿแ€ฏแ€แ€บ source แ€€แ€”แ€ฑ install: + +```bash +git clone https://github.com/amkyawdev/burme-coder-max.git +cd burme-coder-max +pip install -e . +``` + +## ๐Ÿš€ Usage + +### CLI Mode + +```bash +burme-coder ask "Python list sorting แ€œแ€ฏแ€•แ€บแ€”แ€Šแ€บแ€ธ" +``` + +### Interactive Mode + +```bash +burme-coder interactive +``` + +### Train Mode + +```bash +burme-coder train --data ./data/trajectories +``` + +## ๐Ÿ“ Project Structure + +``` +burme-coder-max/ +โ”œโ”€โ”€ src/ +โ”‚ โ”œโ”€โ”€ core/ # Agent logic +โ”‚ โ”œโ”€โ”€ cli/ # Command line +โ”‚ โ”œโ”€โ”€ animations/ # Terminal animations +โ”‚ โ”œโ”€โ”€ ui/ # User interface +โ”‚ โ”œโ”€โ”€ knowledge/ # Knowledge base +โ”‚ โ””โ”€โ”€ utils/ # Utilities +โ”œโ”€โ”€ data/ +โ”‚ โ”œโ”€โ”€ knowledge/ # Markdown files +โ”‚ โ””โ”€โ”€ trajectories/ # Training data +โ””โ”€โ”€ tests/ # Unit tests +``` + +## ๐ŸŽจ Animations + +```python +from animations import Spinner, ProgressBar, TypingEffect + +# Spinner +with Spinner("Loading..."): + do_something() + +# Progress Bar +for i in ProgressBar(range(100), description="Processing"): + process(i) +``` + +## ๐Ÿ™ Thanking System + +```python +from ui.thanking import ThankYou, Appreciation + +# Simple thank you +ThankYou.show() + +# Detailed appreciation +Appreciation.show("Python decorator") +``` + +## ๐Ÿ“š Knowledge Base ```python -from datasets import load_dataset +from knowledge import LocalKB, WebUpdater -dataset = load_dataset("amkyawdev/burme-coder-max") -train_data = dataset['train'] +# Local search +kb = LocalKB() +results = kb.search("python decorators") -# Access an example -example = train_data[0] -print(example['instruction']) -print(example['response']) +# Web update +updater = WebUpdater() +updater.update_from_web() ``` -## Version +## โš™๏ธ Configuration + +`.env.example` แ€€แ€ญแ€ฏ `.env` แ€กแ€”แ€ฑแ€–แ€ผแ€„แ€ทแ€บ แ€€แ€ฑแ€ฌแ€บแ€•แ€ผแ€”แ€บแ€•แ€ผแ€„แ€บ: + +```bash +cp .env.example .env +# Then edit .env with your API keys +``` + +## ๐Ÿงช Testing + +```bash +pytest tests/ -v +``` + +## ๐Ÿ“„ License + +MIT License - แ€กแ€žแ€ฏแ€ถแ€ธแ€•แ€ผแ€ฏแ€แ€ฝแ€„แ€ทแ€บแ€กแ€๏ฟฝ Free -1.0.1 (Updated with Burmese content) +## ๐Ÿ‘จโ€๐Ÿ’ป Author -## License +**amkyawdev** - AI Developer -MIT License +- ๐ŸŒ Website: https://amkyawdev.com +- ๐Ÿ’ป GitHub: https://github.com/amkyawdev +- ๐Ÿค— HuggingFace: https://huggingface.co/amkyawdev diff --git a/data/knowledge/skills/git_skills.md b/data/knowledge/skills/git_skills.md new file mode 100644 index 0000000000000000000000000000000000000000..1fa2ca7a0289466f8e296b4196c3ad6096aa6e6b --- /dev/null +++ b/data/knowledge/skills/git_skills.md @@ -0,0 +1,172 @@ +# Git Skills + +## Setup & Config + +```bash +# Configure user +git config --global user.name "Your Name" +git config --global user.email "your@email.com" + +# Configure editor +git config --global core.editor vim + +# List config +git config --list +``` + +## Basic Commands + +### Status & Logs +```bash +git status # Show working tree status +git status -s # Short format +git log # Show commit history +git log --oneline # Compact log +git log -n 5 # Last 5 commits +git log --graph # Visual branch graph +``` + +### Add & Commit +```bash +git add file.txt # Stage single file +git add . # Stage all changes +git add -p # Interactive staging +git commit -m "message" # Commit with message +git commit -am "message" # Add + commit (tracked files) +git commit --amend # Modify last commit +``` + +### Branching +```bash +git branch # List branches +git branch feature/login # Create branch +git checkout feature/login # Switch to branch +git switch -c feature/login # Create and switch (modern) +git branch -d feature/login # Delete branch +git branch -m new-name # Rename current branch +``` + +### Merging +```bash +git checkout main +git merge feature/login # Merge feature into main +git merge --no-ff feature # No fast-forward merge +git merge --squash feature # Squash commits +``` + +### Rebasing +```bash +git rebase main # Rebase onto main +git rebase -i HEAD~3 # Interactive rebase +git rebase --continue +git rebase --abort +``` + +## Remote Operations + +### Push & Pull +```bash +git push origin main # Push to remote +git push -u origin feature # Push with upstream +git push --force # Force push (use carefully) +git pull # Pull and merge +git pull --rebase # Pull with rebase +git fetch # Fetch without merge +``` + +### Remote Management +```bash +git remote -v # List remotes +git remote add origin url # Add remote +git remote remove origin # Remove remote +git remote rename origin upstream +``` + +## Advanced Operations + +### Stashing +```bash +git stash # Stash changes +git stash pop # Apply and remove stash +git stash apply # Apply without removing +git stash list # List stashes +git stash drop # Delete stash +git stash -u # Include untracked files +``` + +### Resetting +```bash +git reset HEAD~1 # Reset to commit before last +git reset --soft HEAD~1 # Keep changes staged +git reset --hard HEAD~1 # Discard all changes +``` + +### Cherry Picking +```bash +git cherry-pick abc123 # Cherry-pick single commit +git cherry-pick abc123 def456 # Multiple commits +``` + +### Tagging +```bash +git tag v1.0.0 # Create tag +git tag -a v1.0.0 -m "Release 1.0" # Annotated tag +git push origin v1.0.0 # Push tag +git tag -d v1.0.0 # Delete local tag +``` + +## Workflow Examples + +### Feature Branch Workflow +```bash +git checkout -b feature/new-feature +# Make changes +git add . +git commit -m "Add new feature" +git push -u origin feature/new-feature +# Create PR on GitHub/GitLab +# After PR merged +git checkout main +git pull origin main +git branch -d feature/new-feature +``` + +### Hotfix Workflow +```bash +git checkout main +git pull +git checkout -b hotfix/bug-fix +# Fix the bug +git commit -am "Fix critical bug" +git checkout main +git merge --no-ff hotfix/bug-fix +git push origin main +git branch -d hotfix/bug-fix +``` + +## Finding & Fixing Issues + +### Blame & Show +```bash +git blame file.txt # Show who changed what +git show abc123 # Show commit details +git show abc123:file.txt # Show file at commit +``` + +### Bisect (Find Bug) +```bash +git bisect start +git bisect bad HEAD +git bisect good abc123 +# Test... +git bisect good # or git bisect bad +git bisect reset +``` + +### Diff +```bash +git diff # Unstaged changes +git diff --staged # Staged changes +git diff HEAD~1 # vs previous commit +git diff main...feature # Changes in feature branch +``` diff --git a/data/knowledge/skills/javascript_skills.md b/data/knowledge/skills/javascript_skills.md new file mode 100644 index 0000000000000000000000000000000000000000..88d1536e86b6effa2bccc4475d66f52fac1ba745 --- /dev/null +++ b/data/knowledge/skills/javascript_skills.md @@ -0,0 +1,140 @@ +# JavaScript Skills + +## Variables & Types + +### Variables +```javascript +// Variables +let name = "JavaScript"; +const PI = 3.14159; +var oldStyle = "deprecated"; + +// Types +typeof name; // "string" +typeof 42; // "number" +typeof true; // "boolean" +``` + +## Functions + +### Regular Function +```javascript +function greet(name) { + return `Hello, ${name}!`; +} +``` + +### Arrow Function +```javascript +const greet = (name) => `Hello, ${name}!`; + +// Multi-line +const multiply = (a, b) => { + return a * b; +}; +``` + +### Callback +```javascript +const processData = (data, callback) => { + const result = doSomething(data); + callback(result); +}; +``` + +## Arrays + +### Array Methods +```javascript +const arr = [1, 2, 3, 4, 5]; + +// map - transform +arr.map(x => x * 2); // [2, 4, 6, 8, 10] + +// filter - select +arr.filter(x => x > 2); // [3, 4, 5] + +// reduce - accumulate +arr.reduce((sum, x) => sum + x, 0); // 15 + +// find - search +arr.find(x => x === 3); // 3 + +// forEach - iterate +arr.forEach(x => console.log(x)); +``` + +## Objects & Destructuring + +### Object +```javascript +const person = { + name: "John", + age: 30, + greet() { + return `Hello, I'm ${this.name}`; + } +}; + +// Access +person.name; +person['age']; +``` + +### Destructuring +```javascript +const { name, age } = person; +const [first, second] = arr; +``` + +## Async/Await & Promise + +### Promise +```javascript +const fetchData = () => { + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve("data"); + }, 1000); + }); +}; +``` + +### Async/Await +```javascript +const getData = async () => { + try { + const response = await fetch(url); + const data = await response.json(); + return data; + } catch (error) { + console.error(error); + } +}; +``` + +### Promise.all +```javascript +const [result1, result2] = await Promise.all([ + fetch(url1), + fetch(url2) +]); +``` + +## Common Patterns + +### Optional Chaining +```javascript +const value = obj?.nested?.property ?? "default"; +``` + +### Nullish Coalescing +```javascript +const value = input ?? "default value"; +``` + +### Spread Operator +```javascript +const merged = { ...obj1, ...obj2 }; +const combined = [...arr1, ...arr2]; +``` diff --git a/data/knowledge/skills/python_skills.md b/data/knowledge/skills/python_skills.md new file mode 100644 index 0000000000000000000000000000000000000000..8416daa6e4a226065aa5bd9fb3bbe9965fde2380 --- /dev/null +++ b/data/knowledge/skills/python_skills.md @@ -0,0 +1,107 @@ +# Python Skills + +## Python Basics + +### Variables +```python +name = "Python" +age = 25 +is_active = True +``` + +### Data Types +- **int** - Integer: `42` +- **float** - Decimal: `3.14` +- **str** - String: `"Hello"` +- **bool** - Boolean: `True/False` +- **list** - List: `[1, 2, 3]` +- **dict** - Dictionary: `{"key": "value"}` + +### Functions +```python +def greet(name: str) -> str: + """Return a greeting message.""" + return f"Hello, {name}!" + +# Lambda function +square = lambda x: x ** 2 +``` + +### Control Flow +```python +if condition: + do_something() +elif other_condition: + do_other() +else: + do_default() +``` + +### Loops +```python +# For loop +for item in items: + print(item) + +# While loop +while condition: + do_something() +``` + +## Advanced Topics + +### Decorators +```python +def my_decorator(func): + def wrapper(): + print("Before") + func() + print("After") + return wrapper + +@my_decorator +def say_hello(): + print("Hello!") +``` + +### Classes +```python +class Person: + def __init__(self, name: str, age: int): + self.name = name + self.age = age + + def __str__(self) -> str: + return f"{self.name}, {self.age} years old" +``` + +### Exception Handling +```python +try: + result = risky_operation() +except ValueError as e: + print(f"Error: {e}") +finally: + cleanup() +``` + +### List Comprehensions +```python +squares = [x**2 for x in range(10)] +evens = [x for x in range(20) if x % 2 == 0] +``` + +### Context Managers +```python +with open('file.txt', 'r') as f: + content = f.read() +``` + +### Async/Await (asyncio) +```python +import asyncio + +async def fetch_data(): + await asyncio.sleep(1) + return "data" +``` diff --git a/data/knowledge/skills/react_skills.md b/data/knowledge/skills/react_skills.md new file mode 100644 index 0000000000000000000000000000000000000000..11cde18f241e3e899b23ecaf687b533f9a3a04ee --- /dev/null +++ b/data/knowledge/skills/react_skills.md @@ -0,0 +1,163 @@ +# React Skills + +## Hooks + +### useState +```jsx +import { useState } from 'react'; + +function Counter() { + const [count, setCount] = useState(0); + + return ( +
+

Count: {count}

+ +
+ ); +} +``` + +### useEffect +```jsx +import { useState, useEffect } from 'react'; + +function DataFetcher({ url }) { + const [data, setData] = useState(null); + const [loading, setLoading] = useState(true); + + useEffect(() => { + fetch(url) + .then(res => res.json()) + .then(data => { + setData(data); + setLoading(false); + }); + }, [url]); + + return loading ?

Loading...

:
{data}
; +} +``` + +### useContext +```jsx +import { createContext, useContext } from 'react'; + +const ThemeContext = createContext('light'); + +function App() { + return ( + + + + ); +} + +function Child() { + const theme = useContext(ThemeContext); + return
Theme: {theme}
; +} +``` + +### useReducer +```jsx +import { useReducer } from 'react'; + +const initialState = { count: 0 }; + +function reducer(state, action) { + switch (action.type) { + case 'increment': + return { count: state.count + 1 }; + case 'decrement': + return { count: state.count - 1 }; + default: + return state; + } +} + +function Counter() { + const [state, dispatch] = useReducer(reducer, initialState); + + return ( +
+

{state.count}

+ +
+ ); +} +``` + +### Custom Hooks +```jsx +function useLocalStorage(key, initialValue) { + const [storedValue, setStoredValue] = useState(() => { + try { + const item = window.localStorage.getItem(key); + return item ? JSON.parse(item) : initialValue; + } catch (error) { + return initialValue; + } + }); + + const setValue = (value) => { + setStoredValue(value); + window.localStorage.setItem(key, JSON.stringify(value)); + }; + + return [storedValue, setValue]; +} +``` + +## Components + +### Functional Component +```jsx +function Welcome({ name, age }) { + return ( +
+

Hello, {name}!

+

Age: {age}

+
+ ); +} +``` + +### Props +```jsx +// Parent + + +// Child - receieves props +function Welcome(props) { + return

Hello {props.name}

; +} +``` + +## Forms + +### Controlled Input +```jsx +function Form() { + const [name, setName] = useState(''); + + const handleSubmit = (e) => { + e.preventDefault(); + console.log(name); + }; + + return ( +
+ setName(e.target.value)} + /> + +
+ ); +} +``` diff --git a/data/knowledge/skills/sql_skills.md b/data/knowledge/skills/sql_skills.md new file mode 100644 index 0000000000000000000000000000000000000000..d7b912991d6731f3236c3d298571ce7475a9cda0 --- /dev/null +++ b/data/knowledge/skills/sql_skills.md @@ -0,0 +1,180 @@ +# SQL Skills + +## Basic Queries + +### SELECT +```sql +-- All columns +SELECT * FROM users; + +-- Specific columns +SELECT name, email, created_at FROM users; + +-- With alias +SELECT name AS user_name FROM users; +``` + +### WHERE +```sql +SELECT * FROM products WHERE price > 100; + +SELECT * FROM users +WHERE age >= 18 AND status = 'active'; + +SELECT * FROM orders +WHERE created_at BETWEEN '2024-01-01' AND '2024-12-31'; +``` + +### ORDER BY +```sql +SELECT * FROM products +ORDER BY price ASC; + +SELECT * FROM users +ORDER BY created_at DESC, name ASC; +``` + +### LIMIT +```sql +SELECT * FROM users LIMIT 10; + +SELECT * FROM products +ORDER BY price DESC LIMIT 5; +``` + +## JOIN Operations + +### INNER JOIN +```sql +SELECT u.name, o.order_id, o.total +FROM users u +INNER JOIN orders o ON u.id = o.user_id; +``` + +### LEFT JOIN +```sql +SELECT u.name, o.order_id +FROM users u +LEFT JOIN orders o ON u.id = o.user_id; +``` + +### RIGHT JOIN +```sql +SELECT u.name, o.order_id +FROM users u +RIGHT JOIN orders o ON u.id = o.user_id; +``` + +### Multiple JOINs +```sql +SELECT u.name, o.order_id, p.product_name +FROM users u +INNER JOIN orders o ON u.id = o.user_id +INNER JOIN order_items oi ON o.id = oi.order_id +INNER JOIN products p ON oi.product_id = p.id; +``` + +## Aggregations + +### COUNT, SUM, AVG, MIN, MAX +```sql +SELECT COUNT(*) FROM users; +SELECT SUM(amount) FROM orders; +SELECT AVG(price) FROM products; +SELECT MIN(created_at) FROM orders; +SELECT MAX(price) FROM products; +``` + +### GROUP BY +```sql +SELECT category, COUNT(*) as count +FROM products +GROUP BY category; + +SELECT user_id, SUM(total) as total_spent +FROM orders +GROUP BY user_id +HAVING SUM(total) > 1000; +``` + +## Subqueries +```sql +-- In WHERE +SELECT * FROM products +WHERE price > (SELECT AVG(price) FROM products); + +-- In FROM +SELECT category, avg_price +FROM ( + SELECT category, AVG(price) as avg_price + FROM products + GROUP BY category +) AS stats; +``` + +## INSERT, UPDATE, DELETE + +### INSERT +```sql +INSERT INTO users (name, email, age) +VALUES ('John', 'john@email.com', 25); + +INSERT INTO users (name, email) +SELECT name, email FROM temp_users; +``` + +### UPDATE +```sql +UPDATE users +SET age = 26, status = 'active' +WHERE id = 1; +``` + +### DELETE +```sql +DELETE FROM users WHERE id = 1; + +DELETE FROM orders +WHERE created_at < '2024-01-01'; +``` + +## Common Patterns + +### Finding Duplicates +```sql +SELECT email, COUNT(*) as count +FROM users +GROUP BY email +HAVING COUNT(*) > 1; +``` + +### Second Highest +```sql +SELECT MAX(salary) FROM employees +WHERE salary < (SELECT MAX(salary) FROM employees); + +-- Or using OFFSET +SELECT salary FROM employees +ORDER BY salary DESC LIMIT 1 OFFSET 1; +``` + +### Date Functions +```sql +SELECT DATE(created_at) as date, COUNT(*) as orders +FROM orders +GROUP BY DATE(created_at); + +SELECT * FROM orders +WHERE EXTRACT(YEAR FROM created_at) = 2024; +``` + +### Case Statement +```sql +SELECT name, + CASE + WHEN age < 18 THEN 'Minor' + WHEN age < 65 THEN 'Adult' + ELSE 'Senior' + END as age_group +FROM users; +``` diff --git a/data/knowledge/updates/changelog_v1.0.md b/data/knowledge/updates/changelog_v1.0.md new file mode 100644 index 0000000000000000000000000000000000000000..977ebbf9af3febcd31c0c671c0811e6fc30dcfb3 --- /dev/null +++ b/data/knowledge/updates/changelog_v1.0.md @@ -0,0 +1,58 @@ +# Changelog v1.0.0 + +## Version 1.0.0 - Initial Release +**Date:** January 1, 2025 + +### New Features +- โœ… Core agent functionality +- โœ… Myanmar language support +- โœ… Terminal animations (spinners, progress bars) +- โœ… Knowledge base with markdown files +- โœ… Interactive CLI mode +- โœ… Local knowledge search +- โœ… Code validation + +### Modules Added +- `src/core/` - Agent, executor, validator +- `src/cli/` - Command line interface +- `src/animations/` - Terminal animations +- `src/ui/` - User interface components +- `src/knowledge/` - Knowledge management +- `src/utils/` - Utility functions + +### Skills Coverage +- Python +- JavaScript +- TypeScript +- React +- SQL +- Git +- REST API +- WebSocket +- GraphQL + +### Known Issues +- None + +--- + +## Version 0.9.0 - Beta Preview +**Date:** December 15, 2024 + +### Features +- Prototype agent +- Basic animations +- Initial skill set + +### Changes +- Migrated to argparse โ†’ Click +- Added Rich library for better UI + +--- + +## Version 0.5.0 - Alpha +**Date:** December 1, 2024 + +### Initial Development +- Project setup +- Basic structure diff --git a/data/knowledge/updates/deprecations.md b/data/knowledge/updates/deprecations.md new file mode 100644 index 0000000000000000000000000000000000000000..ddd102ef1de11cbcdb52742fea7080042992757f --- /dev/null +++ b/data/knowledge/updates/deprecations.md @@ -0,0 +1,127 @@ +# Deprecations + +## Overview + +This document tracks deprecated features and their removal schedule. + +--- + +## Version 1.0.0 Deprecations + +### Legacy Animation API +**Deprecated:** v1.0.0 +**Will be removed:** v1.2.0 + +Old way (deprecated): +```python +from animations import OldSpinner +s = OldSpinner() +s.start() +``` + +New way (recommended): +```python +from animations import Spinner +with Spinner("Loading..."): + do_something() +``` + +--- + +## Version 0.9.0 Deprecations + +### Python 3.7 Support +**Deprecated:** v0.9.0 +**Will be removed:** v2.0.0 + +Python 3 support timeline: +- Python 3.7 - Deprecated in v0.9.0 +- Python 3.8 - Supported +- Python 3.9 - Supported +- Python 3.10 - Supported +- Python 3.11 - Supported +- Python 3.12 - Planned support + +### Legacy CLI format +**Deprecated:** v0.9.0 +**Will be removed:** v1.1.0 + +Old CLI (deprecated): +```bash +burme-coder run "question" +``` + +New CLI (recommended): +```bash +burme-coder ask "question" +``` + +--- + +## Migration Guides + +### From v0.9.x to v1.0.0 + +1. **Update dependencies:** + ```bash + pip install --upgrade burme-coder-max + ``` + +2. **Update CLI commands:** + ```bash + # Old (deprecated) + burme-coder run "question" + + # New + burme-coder ask "question" + ``` + +3. **Update animation imports:** + ```python + # Old (deprecated) + from animations import OldSpinner + + # New + from animations import Spinner + ``` + +--- + +## Removed Features + +### v1.0.0 +No features removed in v1.0.0 (initial release) + +### Planned Removals +| Feature | Version | Reason | +|---------|---------|--------| +| OldSpinner class | v1.2.0 | Improved API | +| Python 3.7 | v2.0.0 | Security | +| Legacy CLI | v1.1.0 | Clarity | + +--- + +## Best Practices + +1. Always use recommended patterns +2. Check deprecation warnings +3. Update before major version changes +4. Report issues if migration is difficult + +### Enable Deprecation Warnings +```python +import warnings +warnings.filterwarnings('default', category=DeprecationWarning) +``` + +--- + +## Questions? + +If you have questions about deprecations: +- ๐Ÿ“ง Email: contact@amkyawdev.com +- ๐Ÿ’ฌ GitHub Discussions + +--- + +*Last updated: January 2025* diff --git a/data/knowledge/updates/roadmap.md b/data/knowledge/updates/roadmap.md new file mode 100644 index 0000000000000000000000000000000000000000..ff842e3e0c79f44f4b645119c9523a9e400925b5 --- /dev/null +++ b/data/knowledge/updates/roadmap.md @@ -0,0 +1,98 @@ +# Project Roadmap + +## Overview + +This roadmap outlines the planned development for Burme-Coder-Max. + +--- + +## Version 1.1.0 - Enhanced Animations +**Target:** Q2 2025 + +### Features +- [ ] Particle effects with custom colors +- [ ] Progress bar with ETA display +- [ ] Terminal-based charts +- [ ] Custom animation themes +- [ ] Animation presets + +### Improvements +- [ ] Faster animation rendering +- [ ] Reduced CPU usage +- [ ] Better cross-terminal support + +--- + +## Version 1.2.0 - Web Interface +**Target:** Q3 2025 + +### Features +- [ ] Web dashboard +- [ ] REST API server +- [ ] WebSocket real-time updates +- [ ] User authentication +- [ ] History tracking + +### Technical +- [ ] FastAPI integration +- [ ] Redis caching +- [ ] PostgreSQL database +- [ ] Docker deployment + +--- + +## Version 1.3.0 - Advanced Intelligence +**Target:** Q4 2025 + +### Features +- [ ] Code generation with GPT-4 +- [ ] Multi-model support +- [ ] Context-aware suggestions +- [ ] Learning from user feedback +- [ ] Custom personality settings + +### Training +- [ ] Fine-tuning on Myanmar code +- [ ] Custom skill training +- [ ] Domain-specific models + +--- + +## Version 2.0.0 - Production Release +**Target:** 2026 + +### Infrastructure +- [ ] Cloud deployment +- [ ] Auto-scaling +- [ ] CDN integration +- [ ] SLA guarantees + +### Enterprise Features +- [ ] Team collaboration +- [ ] Organization management +- [ ] Usage analytics +- [ ] Custom branding +- [ ] API rate limits + +--- + +## Deprecation Timeline + +| Feature | Deprecated | Removed | +|---------|------------|---------| +| Old animation API | v1.0.0 | v1.2.0 | +| Python 3.7 support | v1.1.0 | v2.0.0 | +| Legacy CLI format | v1.0.0 | v1.1.0 | + +--- + +## Feedback + +We value your input! Please share your feedback: +- ๐Ÿ“ง Email: contact@amkyawdev.com +- ๐Ÿ’ฌ GitHub Issues +- ๐Ÿค Community Discord + +--- + +*Last updated: January 2025* diff --git a/data/knowledge/updates/whats_new_2025.md b/data/knowledge/updates/whats_new_2025.md new file mode 100644 index 0000000000000000000000000000000000000000..c66a5d6979d97c703bf90bbb43aab3ff44a72178 --- /dev/null +++ b/data/knowledge/updates/whats_new_2025.md @@ -0,0 +1,67 @@ +# What's New in 2025 + +## Latest Updates + +### January 2025 - v1.0.0 Release +- ๐ŸŽ‰ Full release with all core features +- ๐Ÿ“š Comprehensive documentation +- โœจ New terminal animations +- ๐Ÿ”ง Improved code validator +- ๐ŸŒ Web knowledge updater + +### December 2024 - v0.9.0 Beta +- ๐Ÿš€ Performance improvements +- ๐ŸŽจ Enhanced UI with Rich library +- ๐Ÿ’ฌ Better interactive mode +- ๐Ÿ› Bug fixes + +--- + +## Roadmap Highlights + +### Coming Soon (v1.1.0) +- โญ Enhanced animation effects +- ๐Ÿ“ฑ Web interface +- ๐Ÿ”Œ REST API server + +### Planned (v1.2.0) +- ๐ŸŒ Cloud sync +- ๐Ÿค– Model fine-tuning +- ๐Ÿ“Š Analytics dashboard + +### Future (v2.0.0) +- ๐Ÿš€ Production deployment +- ๐Ÿ”’ Enhanced security +- ๐Ÿ“ฆ Plugin system + +--- + +## How to Stay Updated + +```bash +# Check current version +burme-coder --version + +# Update to latest +pip install --upgrade burme-coder-max + +# View changelog +burme-coder changelog +``` + +--- + +## Community Highlights + +### Top Contributors +Thank you to all contributors who helped shape this project! + +### Featured Projects +Projects built with Burme-Coder-Max: +- ๐Ÿ”จ Myanmar coding tutorials +- ๐Ÿ“š Educational chatbots +- ๐ŸŽฎ CLI productivity tools + +--- + +*Last updated: January 2025* diff --git a/data/knowledge/webs/graphql_basics.md b/data/knowledge/webs/graphql_basics.md new file mode 100644 index 0000000000000000000000000000000000000000..0b65bbece4eee1793748ffa9a9770c810ab361b8 --- /dev/null +++ b/data/knowledge/webs/graphql_basics.md @@ -0,0 +1,216 @@ +# GraphQL Basics + +## What is GraphQL? + +GraphQL is a query language for APIs that allows clients to request exactly the data they need. + +## Core Concepts + +### Schema & Types +```graphql +type User { + id: ID! + name: String! + email: String + age: Int + posts: [Post!]! + createdAt: DateTime! +} + +type Post { + id: ID! + title: String! + content: String + author: User! + comments: [Comment!]! +} + +type Query { + user(id: ID!): User + users(limit: Int = 10): [User!]! + post(id: ID!): Post +} + +type Mutation { + createUser(name: String!, email: String!): User! + updateUser(id: ID!, name: String): User! + deleteUser(id: ID!): Boolean! +} + +type Subscription { + userCreated: User! + postUpdated(id: ID!): Post! +} +``` + +### Queries +```graphql +# Fetch single user +query GetUser($id: ID!) { + user(id: $id) { + name + email + posts { + title + } + } +} + +# Fetch multiple users with filtering +query GetUsers($limit: Int) { + users(limit: $limit) { + id + name + email + } +} +``` + +### Mutations +```graphql +mutation CreateUser($name: String!, $email: String!) { + createUser(name: $name, email: $email) { + id + name + } +} + +mutation UpdatePost($id: ID!, $title: String!) { + updatePost(id: $id, title: $title) { + id + title + updatedAt + } +} +``` + +### Variables +```json +{ + "id": "123", + "name": "John", + "email": "john@example.com" +} +``` + +## Implementation (Node.js + Apollo) + +### Basic Server +```javascript +const { ApolloServer, gql } = require('apollo-server'); +const { GraphQLScalarType, Kind } = require('graphql'); + +const typeDefs = gql` + scalar DateTime + + type User { + id: ID! + name: String! + email: String! + createdAt: DateTime! + } + + type Query { + users: [User!]! + user(id: ID!): User + } + + type Mutation { + createUser(name: String!, email: String!): User! + } + + type Subscription { + userCreated: User! + } +`; + +const resolvers = { + DateTime: new GraphQLScalarType({ + name: 'DateTime', + serialize(value) { + return value.toISOString(); + }, + parseValue(value) { + return new Date(value); + } + }), + + Query: { + users: () => users, + user: (_, { id }) => users.find(u => u.id === id), + }, + + Mutation: { + createUser: (_, { name, email }) => { + const newUser = { + id: String(users.length + 1), + name, + email, + createdAt: new Date() + }; + users.push(newUser); + return newUser; + } + } +}; + +const server = new ApolloServer({ typeDefs, effectors }); +server.listen().then(({ url }) => { + console.log(`Server ready at ${url}`); +}); +``` + +### Client (React) +```javascript +import { ApolloClient, InMemoryCache, gql } from '@apollo/client'; + +const client = new ApolloClient({ + uri: 'http://localhost:4000/graphql', + cache: new InMemoryCache() +}); + +const GET_USERS = gql` + query GetUsers { + users { + id + name + email + } + } +`; + +function App() { + const { loading, error, data } = useQuery(GET_USERS); + + if (loading) return

Loading...

; + if (error) return

Error: {error.message}

; + + return ( +
+ {data.users.map(user => ( +
{user.name}
+ ))} +
+ ); +} +``` + +## GraphQL vs REST + +| Feature | GraphQL | REST | +|---------|---------|------| +| Data fetching | Single request | Multiple endpoints | +| Over-fetching | No | Yes | +| Under-fetching | No | Sometimes | +| Type safety | Yes (schema) | No | +| Learning curve | Higher | Lower | +| Caching | Manual | Automatic | +| File uploads | Complex | Simple | + +## Best Practices + +1. **N+1 Problem** - Use DataLoader for batching +2. **Pagination** - Use cursor-based pagination +3. **Error Handling** - Return meaningful errors +4. **Security** - Implement depth limiting +5. **Performance** - Consider query cost analysis diff --git a/data/knowledge/webs/http_status_codes.md b/data/knowledge/webs/http_status_codes.md new file mode 100644 index 0000000000000000000000000000000000000000..553ab4d7d17320ca5c6107c92becec49a7ee3f02 --- /dev/null +++ b/data/knowledge/webs/http_status_codes.md @@ -0,0 +1,170 @@ +# HTTP Status Codes + +## Success Codes (2xx) + +| Code | Name | Description | +|------|------|-------------| +| 200 | OK | Standard success response | +| 201 | Created | Resource successfully created | +| 202 | Accepted | Request accepted for processing | +| 204 | No Content | Success with no body | +| 206 | Partial Content | Returning partial data | + +## Redirection Codes (3xx) + +| Code | Name | Description | +|------|------|-------------| +| 301 | Moved Permanently | Resource moved permanently | +| 302 | Found | Temporary redirect | +| 303 | See Other | Redirect to different URL | +| 304 | Not Modified | Use cached version | +| 307 | Temporary Redirect | Temporary redirect | +| 308 | Permanent Redirect | Permanent redirect | + +## Client Error Codes (4xx) + +| Code | Name | Description | +|------|------|-------------| +| 400 | Bad Request | Invalid request syntax | +| 401 | Unauthorized | Authentication required | +| 402 | Payment Required | Reserved for future use | +| 403 | Forbidden | Authenticated but not permitted | +| 404 | Not Found | Resource doesn't exist | +| 405 | Method Not Allowed | HTTP method not supported | +| 406 | Not Acceptable | Cannot produce acceptable response | +| 408 | Request Timeout | Client took too long | +| 409 | Conflict | Request conflicts with state | +| 410 | Gone | Resource permanently removed | +| 413 | Payload Too Large | Request body exceeds limit | +| 414 | URI Too Long | URL exceeds max length | +| 415 | Unsupported Media Type | Invalid content type | +| 422 | Unprocessable Entity | Validation failed | +| 429 | Too Many Requests | Rate limit exceeded | + +## Server Error Codes (5xx) + +| Code | Name | Description | +|------|------|-------------| +| 500 | Internal Server Error | Generic server error | +| 501 | Not Implemented | Feature not implemented | +| 502 | Bad Gateway | Invalid response from gateway | +| 503 | Service Unavailable | Server temporarily down | +| 504 | Gateway Timeout | Gateway timeout | +| 507 | Insufficient Storage | Storage limit reached | +| 511 | Network Authentication | Requires auth on network | + +## Common Use Cases + +### 200 OK +```json +// Standard response +{ + "data": {...} +} +``` + +### 201 Created +```json +// With created resource +{ + "data": { + "id": 123, + "name": "New Item" + } +} +// Headers: Location: /resources/123 +``` + +### 400 Bad Request +```json +{ + "error": { + "code": "VALIDATION_ERROR", + "message": "Invalid input", + "details": [...] + } +} +``` + +### 401 Unauthorized +```json +{ + "error": { + "code": "AUTH_REQUIRED", + "message": "Please login to continue" + } +} +``` + +### 403 Forbidden +```json +{ + "error": { + "code": "PERMISSION_DENIED", + "message": "You don't have access to this resource" + } +} +``` + +### 404 Not Found +```json +{ + "error": { + "code": "NOT_FOUND", + "message": "Resource not found" + } +} +``` + +### 429 Too Many Requests +```json +{ + "error": { + "code": "RATE_LIMITED", + "message": "Too many requests", + "retryAfter": 60 + } +} +// Headers: Retry-After: 60 +``` + +### 500 Internal Server Error +```json +{ + "error": { + "code": "INTERNAL_ERROR", + "message": "Something went wrong" + } +} +``` + +## Response Headers + +### Standard Headers +``` +Content-Type: application/json +Content-Length: 1234 +Connection: keep-alive +Cache-Control: max-age=3600 +``` + +### Rate Limiting Headers +``` +X-RateLimit-Limit: 100 +X-RateLimit-Remaining: 95 +X-RateLimit-Reset: 1640000000 +``` + +### Pagination Headers +``` +Link: ; rel="next", + ; rel="last" +``` + +## Security Best Practices + +1. Never reveal internal error details in production +2. Use generic error messages for 500 errors +3. Log detailed errors server-side +4. Return appropriate status codes +5. Include error codes for client handling diff --git a/data/knowledge/webs/rest_api_design.md b/data/knowledge/webs/rest_api_design.md new file mode 100644 index 0000000000000000000000000000000000000000..af5b86a62c0c2cb328c3ae627922d9c11c215539 --- /dev/null +++ b/data/knowledge/webs/rest_api_design.md @@ -0,0 +1,144 @@ +# REST API Design + +## HTTP Methods + +| Method | Purpose | Example | +|--------|---------|---------| +| GET | Retrieve data | `GET /users` | +| POST | Create new resource | `POST /users` | +| PUT | Replace entire resource | `PUT /users/1` | +| PATCH | Partial update | `PATCH /users/1` | +| DELETE | Remove resource | `DELETE /users/1` | + +## URL Structure + +``` +https://api.example.com/v1/users/123/posts?page=1&limit=10 +โ”‚ โ”‚ โ”‚ โ”‚ โ”‚ +โ”‚ โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ Query Parameters +โ”‚ โ”‚ โ”‚ โ””โ”€โ”€ Resource ID +โ”‚ โ”‚ โ””โ”€โ”€ Collection +โ”‚ โ””โ”€โ”€ Version +โ””โ”€โ”€ Base URL +``` + +## Status Codes + +### Success +- `200 OK` - Request succeeded +- `201 Created` - Resource created +- `204 No Content` - Success, no body (DELETE) + +### Client Errors +- `400 Bad Request` - Invalid input +- `401 Unauthorized` - Authentication required +- `403 Forbidden` - Authenticated but not permitted +- `404 Not Found` - Resource doesn't exist +- `422 Unprocessable Entity` - Validation error + +### Server Errors +- `500 Internal Server Error` - Server error +- `502 Bad Gateway` - Gateway error +- `503 Service Unavailable` - Server down + +## Best Practices + +### Request +```http +GET /api/v1/users?status=active&sort=-created_at +Accept: application/json +Authorization: Bearer +``` + +### Response +```json +{ + "data": [ + { + "id": 1, + "name": "John", + "email": "john@example.com" + } + ], + "meta": { + "page": 1, + "per_page": 20, + "total": 100 + }, + "links": { + "self": "/api/v1/users?page=1", + "next": "/api/v1/users?page=2" + } +} +``` + +### Error Response +```json +{ + "error": { + "code": "VALIDATION_ERROR", + "message": "Invalid input data", + "details": [ + { + "field": "email", + "message": "Invalid email format" + } + ] + } +} +``` + +## REST API Example (Node.js/Express) + +### Basic Setup +```javascript +const express = require('express'); +const app = express(); + +app.use(express.json()); + +// GET all users +app.get('/api/v1/users', (req, res) => { + res.json({ data: users }); +}); + +// GET single user +app.get('/api/v1/users/:id', (req, res) => { + const user = users.find(u => u.id === parseInt(req.params.id)); + if (!user) return res.status(404).json({ error: 'Not found' }); + res.json({ data: user }); +}); + +// POST create user +app.post('/api/v1/users', (req, res) => { + const { name, email } = req.body; + // Validation + if (!name || !email) { + return res.status(400).json({ error: 'Missing fields' }); + } + // Create + const newUser = { id: users.length + 1, name, email }; + users.push(newUser); + res.status(201).json({ data: newUser }); +}); + +// PUT update user +app.put('/api/v1/users/:id', (req, res) => { + const user = users.find(u => u.id === parseInt(req.params.id)); + if (!user) return res.status(404).json({ error: 'Not found' }); + + const { name, email } = req.body; + user.name = name || user.name; + user.email = email || user.email; + res.json({ data: user }); +}); + +// DELETE user +app.delete('/api/v1/users/:id', (req, res) => { + const index = users.findIndex(u => u.id === parseInt(req.params.id)); + if (index === -1) return res.status(404).json({ error: 'Not found' }); + + users.splice(index, 1); + res.status(204).send(); +}); +``` diff --git a/data/knowledge/webs/websocket_protocol.md b/data/knowledge/webs/websocket_protocol.md new file mode 100644 index 0000000000000000000000000000000000000000..1f5ceb320cd44925369ae7eab3aa647415b29134 --- /dev/null +++ b/data/knowledge/webs/websocket_protocol.md @@ -0,0 +1,170 @@ +# WebSocket Protocol + +## What is WebSocket? + +WebSocket provides full-duplex communication channels over a single TCP connection. Unlike HTTP, WebSocket allows real-time bidirectional communication. + +## Connection Flow + +``` +Client Server + โ”‚ โ”‚ + โ”‚โ”€โ”€โ”€โ”€ HTTP Upgrade Request โ”€โ”€โ”€โ”€โ–ถโ”‚ + โ”‚ Upgrade: websocket โ”‚ + โ”‚ โ”‚ + โ”‚โ—€โ”€โ”€โ”€ HTTP 101 Switching -------โ”‚ + โ”‚ Protocol: ws โ”‚ + โ”‚ โ”‚ + โ”‚โ—€โ•โ•โ•โ•โ• WebSocket Open โ•โ•โ•โ•โ•โ•โ•โ•โ•โ–ถโ”‚ + โ”‚ โ”‚ + โ”‚โ—€โ•โ•โ•โ•โ• Messages โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ–ถโ”‚ + โ”‚ โ”‚ + โ”‚โ—€โ•โ•โ•โ•โ• Connection Close โ•โ•โ•โ•โ•โ•โ•โ–ถโ”‚ +``` + +## WebSocket Headers + +### Upgrade Request +``` +GET /ws HTTP/1.1 +Host: api.example.com +Upgrade: websocket +Connection: Upgrade +Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== +Sec-WebSocket-Version: 13 +``` + +### Server Response +``` +HTTP/1.1 101 Switching Protocols +Upgrade: websocket +Connection: Upgrade +Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= +``` + +## Implementation Examples + +### Server (Node.js + ws) +```javascript +const WebSocket = require('ws'); +const wss = new WebSocket.Server({ port: 8080 }); + +wss.on('connection', (ws) => { + console.log('Client connected'); + + ws.on('message', (message) => { + console.log('Received:', message.toString()); + ws.send('Echo: ' + message); + }); + + ws.on('close', () => { + console.log('Client disconnected'); + }); + + // Send periodic message + const interval = setInterval(() => { + ws.send('Ping: ' + Date.now()); + }, 30000); + + ws.on('close', () => clearInterval(interval)); +}); +``` + +### Client (Browser) +```javascript +const ws = new WebSocket('ws://localhost:8080'); + +ws.onopen = () => { + console.log('Connected to WebSocket'); + ws.send('Hello Server!'); +}; + +ws.onmessage = (event) => { + console.log('Received:', event.data); +}; + +ws.onerror = (error) => { + console.error('WebSocket error:', error); +}; + +ws.onclose = () => { + console.log('Disconnected'); +}; +``` + +### Client (Python) +```python +import asyncio +import websockets + +async def main(): + async with websockets.connect('ws://localhost:8080') as ws: + await ws.send('Hello Server!') + response = await ws.recv() + print(f"Received: {response}") + +asyncio.run(main()) +``` + +## Socket.IO (Higher Level) + +### Server +```javascript +const { Server } = require('socket.io'); +const io = new Server(3000, { + cors: { origin: '*' } +}); + +io.on('connection', (socket) => { + console.log('User connected:', socket.id); + + socket.on('message', (data) => { + console.log('Message:', data); + io.emit('message', data); + }); + + socket.on('disconnect', () => { + console.log('User disconnected'); + }); + + socket.on('join-room', (room) => { + socket.join(room); + socket.to(room).emit('user-joined', socket.id); + }); +}); +``` + +### Client +```javascript +import { io } from 'socket.io-client'; + +const socket = io('http://localhost:3000'); + +socket.on('connect', () => { + console.log('Connected:', socket.id); + socket.emit('message', 'Hello everyone!'); +}); + +socket.on('message', (data) => { + console.log('Received:', data); +}); +``` + +## WebSocket vs HTTP + +| Aspect | WebSocket | HTTP | +|--------|----------|------| +| Connection | Persistent | Request-Response | +| Direction | Bidirectional | Client โ†’ Server | +| Overhead | Low (after handshake) | High (headers each request) | +| Use Case | Real-time apps | REST APIs, simple requests | +| Browser Support | Modern browsers | All browsers | + +## Best Practices + +1. **Heartbeat/Ping-Pong** - Keep connections alive +2. **Reconnection Logic** - Handle connection drops +3. **Message Queueing** - Queue messages during disconnect +4. **Authentication** - Validate on connection +5. **Rate Limiting** - Prevent abuse +6. **Compression** - Consider permessage-deflate diff --git a/docs/animation_gallery.md b/docs/animation_gallery.md new file mode 100644 index 0000000000000000000000000000000000000000..98d4b8f9e6be35951b5aca9ad808c2130aed882a --- /dev/null +++ b/docs/animation_gallery.md @@ -0,0 +1,139 @@ +"""Documentation: Animation Gallery""" + +# Animation Gallery + +A showcase of all available terminal animations in Burme-Coder-Max. + +--- + +## 1. Loading Spinner + +Display a spinning indicator while waiting. + +```python +from animations import Spinner + +with Spinner("Loading..."): + do_something() +``` + +**Custom message:** +```python +spinner = Spinner("Processing your request...") +spinner.start() +# ... do work +spinner.stop() +``` + +--- + +## 2. Progress Bar + +Show progress for long-running operations. + +```python +from animations import ProgressBar + +for i in ProgressBar(range(100), description="Downloading"): + download(i) +``` + +**Custom configuration:** +```python +from animations.progress_bar import ProgressBarConfig + +config = ProgressBarConfig( + width=60, + fill_char="โ–ˆ", + empty_char="โ–‘" +) + +progress = ProgressBar( + total=50, + config=config, + description="Uploading" +) +``` + +--- + +## 3. Typing Effect + +Typewriter-style text animation. + +```python +from animations import TypingEffect + +effect = TypingEffect("Hello, World!") +effect.animate() +``` + +**Speed variants:** +```python +from animations import SlowTypingEffect, FastTypingEffect + +SlowTypingEffect("Slow text").animate() +FastTypingEffect("Fast text").animate() +``` + +--- + +## 4. Particle Burst + +Celebration effect with particles. + +```python +from animations import ParticleBurst + +burst = ParticleBurst(count=50) +burst.explode() +``` + +**Custom position:** +```python +burst = ParticleBurst(center_x=60, center_y=15) +burst.explode() +``` + +--- + +## 5. Confetti + +Lightweight celebration effect. + +```python +from animations.particle_effect import SimpleConfetti + +confetti = SimpleConfetti(duration=2.0) +confetti.show() +``` + +--- + +## Preview Script + +Run all animations: + +```bash +python scripts/preview_animations.py +``` + +--- + +## Configuration + +Edit animation settings in `.env`: + +```bash +ANIMATION_SPEED=0.05 +ANIMATION_COLOR=true +``` + +Or in code: + +```python +from animations.config import AnimationConfig + +config = AnimationConfig(speed=0.03, color_enabled=False) +spinner = Spinner(config=config) +``` diff --git a/docs/contributing.md b/docs/contributing.md new file mode 100644 index 0000000000000000000000000000000000000000..852fde79c9eb544273c9e28d6d21f48766877188 --- /dev/null +++ b/docs/contributing.md @@ -0,0 +1,170 @@ +"""Documentation: Contributing Guide""" + +# Contributing to Burme-Coder-Max + +We welcome contributions! This guide covers how to contribute. + +--- + +## Ways to Contribute + +- ๐Ÿ› Report bugs +- ๐Ÿ’ก Suggest features +- ๐Ÿ“ Improve documentation +- ๐Ÿ”ง Submit code changes +- โœ… Test new features + +--- + +## Development Setup + +### 1. Fork and Clone + +```bash +git clone https://github.com/YOUR_USERNAME/burme-coder-max.git +cd burme-coder-max +``` + +### 2. Create Virtual Environment + +```bash +python -m venv venv +source venv/bin/activate # Linux/Mac +# or +venv\Scripts\activate # Windows +``` + +### 3. Install Dependencies + +```bash +pip install -e ".[dev]" +``` + +### 4. Install Pre-commit Hooks + +```bash +pre-commit install +``` + +--- + +## Making Changes + +### 1. Create a Branch + +```bash +git checkout -b feature/my-feature +# or +git checkout -b fix/my-bug +``` + +### 2. Make Your Changes + +- Follow existing code style +- Add tests for new features +- Update documentation + +### 3. Run Tests + +```bash +pytest tests/ -v +``` + +### 4. Run Linters + +```bash +black src/ tests/ +mypy src/ +``` + +--- + +## Code Style + +- Follow PEP 8 +- Use type hints +- Add docstrings +- Keep functions small and focused + +### Example + +```python +from typing import List, Optional + + +def search_knowledge(query: str, category: Optional[str] = None) -> List[dict]: + """ + Search the knowledge base for relevant content. + + Args: + query: Search query string + category: Optional category filter + + Returns: + List of matching entries + """ + # implementation + pass +``` + +--- + +## Commit Messages + +Format: + +``` +type: Short description + +Longer explanation if needed. +``` + +Types: +- `feat:` New feature +- `fix:` Bug fix +- `docs:` Documentation +- `style:` Formatting +- `refactor:` Code restructuring +- `test:` Tests +- `chore:` maintenance + +Example: +``` +feat: Add particle burst animation + +Add celebration effect with customizable particle count. +Fixes #12 +``` + +--- + +## Pull Request Process + +1. Update documentation for new features +2. Add tests +3. Ensure all tests pass +4. Update CHANGELOG.md +5. Submit PR with clear description + +--- + +## Reporting Issues + +When reporting bugs: +- Describe the issue clearly +- Steps to reproduce +- Expected vs actual behavior +- Python version and OS +- Error messages + +--- + +## Questions? + +- ๐Ÿ“ง Email: contact@amkyawdev.com +- ๐Ÿ’ฌ GitHub Discussions +- ๐Ÿค Community Discord + +--- + +Thank you for contributing! ๐Ÿ™ diff --git a/docs/installation.md b/docs/installation.md new file mode 100644 index 0000000000000000000000000000000000000000..83d8c93767873d454fff20dcc0c5492210326b17 --- /dev/null +++ b/docs/installation.md @@ -0,0 +1,97 @@ +"""Documentation: Installation Guide""" + +# Installation Guide - Burme-Coder-Max + +## Prerequisites + +- Python 3.8 or higher +- pip package manager + +## Installation Methods + +### Method 1: pip install (Recommended) + +```bash +pip install burme-coder-max +``` + +### Method 2: From source + +```bash +git clone https://github.com/amkyawdev/burme-coder-max.git +cd burme-coder-max +pip install -e . +``` + +### Method 3: Development install + +```bash +git clone https://github.com/amkyawdev/burme-coder-max.git +cd burme-coder-max +pip install -e ".[dev]" +``` + +## Verify Installation + +```bash +burme-coder --version +``` + +Expected output: +``` +burme-coder-max 1.0.0 +``` + +## Configuration + +1. Copy `.env.example` to `.env`: + ```bash + cp .env.example .env + ``` + +2. Edit `.env` with your settings: + ```bash + nano .env + ``` + +### Required Environment Variables + +| Variable | Description | Required | +|----------|-------------|----------| +| OPENAI_API_KEY | OpenAI API key for AI responses | Yes | +| DATABASE_URL | Database connection string | No | + +## Dependencies + +See `requirements.txt` for full dependency list. + +Main dependencies: +- click >= 8.0.0 +- rich >= 13.0.0 +- requests >= 2.28.0 +- pydantic >= 2.0.0 + +## Troubleshooting + +### Installation fails +- Check Python version: `python --version` +- Upgrade pip: `pip install --upgrade pip` +- Try in virtual environment + +### Module not found +- Reinstall: `pip install --force-reinstall burme-coder-max` +- Check PATH + +### Permission denied +- Use `--user` flag: `pip install --user burme-coder-max` +- Or use virtual environment + +## Uninstall + +```bash +pip uninstall burme-coder-max +``` + +## Next Steps + +See [usage.md](usage.md) for how to use burme-coder-max. diff --git a/docs/usage.md b/docs/usage.md new file mode 100644 index 0000000000000000000000000000000000000000..a04652d28fa4a61e1236dc163b355c65936324ce --- /dev/null +++ b/docs/usage.md @@ -0,0 +1,146 @@ +"""Documentation: Usage Guide""" + +# Usage Guide - Burme-Coder-Max + +## Quick Start + +### Ask a Question + +```bash +burme-coder ask "Python decorator hta ya py" +``` + +### Interactive Mode + +```bash +burme-coder interactive +``` + +### Train Agent + +```bash +burme-coder train --data ./data/trajectories +``` + +## CLI Commands + +### `ask` - Ask a single question + +```bash +burme-coder ask [INSTRUCTION] [OPTIONS] + +Options: + --model TEXT AI model to use (default: gpt-4) + --verbose Show detailed output + --output, -o Save response to file +``` + +### `interactive` - Start chat mode + +```bash +burme-coder interactive +``` + +Interactive commands: +- `exit` - Quit +- `clear` - Clear history +- `help` - Show help +- `history` - Show conversation history + +### `train` - Train on trajectories + +```bash +burme-coder train [OPTIONS] + +Options: + --data TEXT Training data directory (default: ./data/trajectories) + --epochs INT Number of epochs (default: 10) + --batch-size INT Batch size (default: 4) +``` + +### `eval` - Evaluate performance + +```bash +burme-coder eval --data ./data/trajectories +``` + +## Python API + +### Import and Use Agent + +```python +from burme_coder.core import CoderAgent + +agent = CoderAgent(model="gpt-4") +response = agent.generate_response("Python list sorting hta ya") + +print(response["response"]) +``` + +### Use Animations + +```python +from burme_coder.animations import Spinner, ProgressBar + +with Spinner("Loading"): + do_something() + +for i in ProgressBar(range(100)): + process(i) +``` + +### Use Thanking System + +```python +from burme_coder.ui.thanking import ThankYou + +ThankYou.show() +``` + +## Configuration + +Edit `.env` file: + +```bash +# API Keys +OPENAI_API_KEY=sk-your-key-here + +# Animation Settings +ANIMATION_SPEED=0.05 +ANIMATION_COLOR=true + +# Cache Settings +CACHE_DIR=./data/cache +CACHE_TTL=3600 +``` + +## Knowledge Base + +Search local knowledge: + +```python +from burme_coder.knowledge import LocalKB + +kb = LocalKB() +results = kb.search("python decorators") + +for result in results: + print(result["snippet"]) +``` + +Update from web: + +```python +from burme_coder.knowledge import WebUpdater + +updater = WebUpdater() +updater.update_markdown_files("./data/knowledge/skills") +``` + +## Examples + +See `examples/` directory for more examples: + +- `demo_animation.py` - Animation demonstrations +- `demo_thanking.py` - Thanking system examples +- `demo_skill_query.py` - Knowledge base queries diff --git a/examples/demo_animation.py b/examples/demo_animation.py new file mode 100644 index 0000000000000000000000000000000000000000..8bb18b0d8b8986bb53147481424fd243b005fcb1 --- /dev/null +++ b/examples/demo_animation.py @@ -0,0 +1,106 @@ +"""Demo: Animation Gallery + +This script demonstrates all available animations in Burme-Coder-Max. +""" + +import sys +import time +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent.parent / "src")) + +from animations import Spinner, ProgressBar, ParticleBurst, TypingEffect +from animations.particle_effect import SimpleConfetti + + +def demo_spinner(): + """Demonstrate spinner animation.""" + print("\n๐Ÿ”„ Loading Spinner Demo") + print("=" * 40) + + print("\nBasic spinner:") + with Spinner("Processing your request"): + for _ in range(20): + time.sleep(0.05) + + print("โœ“ Complete!\n") + + +def demo_progress(): + """Demonstrate progress bar animation.""" + print("\n๐Ÿ“Š Progress Bar Demo") + print("=" * 40) + + print("\nDefault progress bar:") + for i in ProgressBar(range(50), description="Downloading"): + time.sleep(0.03) + + print("โœฆ Progress bar demo complete!\n") + + +def demo_particles(): + """Demonstrate particle burst effect.""" + print("\nโœจ Particle Burst Demo") + print("=" * 40) + + print("\n๐ŸŽ‰ Celebration effect:") + burst = ParticleBurst(count=40) + burst.center_x = 50 + burst.center_y = 12 + burst.explode() + + print("โœฆ Particle burst complete!\n") + + +def demo_typing(): + """Demonstrate typing effect.""" + print("\nโŒจ๏ธ Typing Effect Demo") + print("=" * 40) + + effect = TypingEffect("Hello from Burme-Coder-Max! ๐Ÿง‘โ€๐Ÿ’ป", delay=0.06) + effect.animate() + + print() + + +def demo_confetti(): + """Demonstrate confetti effect.""" + print("\n๐ŸŽŠ Confetti Demo") + print("=" * 40) + + confetti = SimpleConfetti(duration=1.5) + confetti.show() + + print() + + +def main(): + """Run all animation demos.""" + print() + print("โ•”" + "โ•" * 48 + "โ•—") + print("โ•‘" + " ๐ŸŽจ ANIMATION GALLERY ".center(48) + "โ•‘") + print("โ•š" + "โ•" * 48 + "โ•") + + demos = [ + ("Spinner", demo_spinner), + ("Progress Bar", demo_progress), + ("Particle Burst", demo_particles), + ("Typing Effect", demo_typing), + ("Confetti", demo_confetti), + ] + + for name, demo_func in demos: + try: + demo_func() + time.sleep(0.3) + except KeyboardInterrupt: + print("\n\nInterrupted by user") + break + + print("โ•”" + "โ•" * 48 + "โ•—") + print("โ•‘" + " โœจ DEMO COMPLETE ".center(48) + "โ•‘") + print("โ•š" + "โ•" * 48 + "โ•") + + +if __name__ == "__main__": + main() diff --git a/examples/demo_skill_query.py b/examples/demo_skill_query.py new file mode 100644 index 0000000000000000000000000000000000000000..5cc6e15e5da68686dcd9664015d66277c53fedc1 --- /dev/null +++ b/examples/demo_skill_query.py @@ -0,0 +1,102 @@ +"""Demo: Skill Query + +This script demonstrates how to query the knowledge base. +""" + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent.parent / "src")) + +from knowledge import LocalKB + + +def demo_basic_search(): + """Demonstrate basic knowledge search.""" + print("\n๐Ÿ” Basic Knowledge Search") + print("=" * 40) + + kb = LocalKB() + + print("\nSearch for: 'python decorator' ") + results = kb.search("python decorator") + + if results: + print(f"\nFound {len(results)} results:") + for i, result in enumerate(results[:5], 1): + print(f"\n{i}. {result['source']} (line {result['line']})") + print(f" {result['snippet'][:100]}...") + else: + print("\nNo results found") + + +def demo_topic_search(): + """Demonstrate topic-specific search.""" + print("\n๐Ÿ“š Topic Search") + print("=" * 40) + + kb = LocalKB() + + topics = kb.get_all_topics() + print("\nAvailable topics:") + for topic in topics: + print(f" - {topic}") + + +def demo_random_entry(): + """Demonstrate getting random knowledge entry.""" + print("\n๐ŸŽฒ Random Knowledge Entry") + print("=" * 40) + + kb = LocalKB() + entry = kb.get_random_entry() + + if entry: + print(f"\nRandom entry from: {entry['source']}") + print("\n---") + print(entry["content"][:300]) + print("---") + else: + print("\nNo entries available") + + +def demo_skill_file_access(): + """Demonstrate accessing specific skill files.""" + print("\n๐Ÿ“ Skill File Access") + print("=" * 40) + + kb = LocalKB() + + content = kb.get_content("python") + if content: + print("\nPython skills content (preview):") + print(content[:500]) + else: + print("\nPython skills file not found") + + +def main(): + """Run all knowledge base demos.""" + print() + print("โ•”" + "โ•" * 48 + "โ•—") + print("โ•‘" + " ๐Ÿ“š KNOWLEDGE BASE DEMO ".center(48) + "โ•‘") + print("โ•š" + "โ•" * 48 + "โ•") + + demos = [ + ("Topic List", demo_topic_search), + ("Basic Search", demo_basic_search), + ("Skill Files", demo_skill_file_access), + ("Random Entry", demo_random_entry), + ] + + for name, demo_func in demos: + input(f"\n[Press Enter for '{name}' demo]") + demo_func() + + print("\n" + "โ•" * 48) + print("โœจ Demo complete! Explore the knowledge base!") + print("โ•" * 48) + + +if __name__ == "__main__": + main() diff --git a/examples/demo_thanking.py b/examples/demo_thanking.py new file mode 100644 index 0000000000000000000000000000000000000000..ef4085c30f9758862832a34a79ee2a91961e81f9 --- /dev/null +++ b/examples/demo_thanking.py @@ -0,0 +1,95 @@ +"""Demo: Thanking System + +This script demonstrates the thanking system in Burme-Coder-Max. +""" + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent.parent / "src")) + +from ui.thanking import ThankYou, Appreciation, CreditDisplay +from ui.thanking.thank_you import quick_thank +from ui.thanking.appreciation import show_custom_appreciation + + +def demo_basic_thanks(): + """Demonstrate basic thank you messages.""" + print("\n๐Ÿ™ Basic Thank You Messages") + print("=" * 40) + + ThankYou.show() + ThankYou.show_animation() + ThankYou.show_with_emoji("โญ") + + +def demo_emoji_variations(): + """Demonstrate different emoji options.""" + print("\nโญ Emoji Variations") + print("=" * 40) + + emojis = ["๐Ÿ™", "๐Ÿ’–", "๐ŸŽ‰", "โœจ", "โญ", "๐ŸŒŸ", "๐Ÿ’ซ"] + for emoji in emojis: + ThankYou.show_with_emoji(emoji) + print() + + +def demo_custom_appreciation(): + """Demonstrate custom appreciation.""" + print("\n๐Ÿ† Custom Appreciation") + print("=" * 40) + + show_custom_appreciation( + title="Learning Milestone", + message="Congratulations on completing Python basics!", + badges=["Python Novice", "First Function", "Loop Master"], + ) + + +def demo_detailed_appreciation(): + """Demonstrate detailed appreciation.""" + print("\n๐Ÿ“ Detailed Appreciation") + print("=" * 40) + + Appreciation.show("Python decorators") + + +def demo_credit_display(): + """Demonstrate credits.""" + print("\n๐Ÿ“œ Credits Display") + print("=" * 40) + + CreditDisplay.show_simple() + + +def demo_quick_thank(): + """Demonstrate quick thank.""" + print("\nโšก Quick Thank") + print("=" * 40) + + quick_thank() + + +def main(): + """Run all thanking demos.""" + print() + print("โ•”" + "โ•" * 48 + "โ•—") + print("โ•‘" + " ๐Ÿ™ THANKING SYSTEM DEMO ".center(48) + "โ•‘") + print("โ•š" + "โ•" * 48 + "โ•") + + demos = [ + ("Basic Thanks", demo_basic_thanks), + ("Emoji Variations", demo_emoji_variations), + ("Custom Appreciation", demo_custom_appreciation), + ("Detailed Appreciation", demo_detailed_appreciation), + ("Credits", demo_credit_display), + ("Quick Thank", demo_quick_thank), + ] + + for name, demo_func in demos: + input(f"\n[Press Enter for '{name}' demo]") + demo_func() + + +if __name__ == "__main__": + main() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..76e383ecb9adc5c244eb8289869a000d5efc2cac --- /dev/null +++ b/requirements.txt @@ -0,0 +1,7 @@ +click>=8.0.0 +rich>=13.0.0 +requests>=2.28.0 +beautifulsoup4>=4.11.0 +lxml>=4.9.0 +pydantic>=2.0.0 +tqdm>=4.65.0 diff --git a/scripts/build_markdown_index.py b/scripts/build_markdown_index.py new file mode 100644 index 0000000000000000000000000000000000000000..24fbdd6f69f0a424249152386866e33d51783d6f --- /dev/null +++ b/scripts/build_markdown_index.py @@ -0,0 +1,155 @@ +"""Build markdown index for fast searching""" + +import json +from pathlib import Path +from typing import Dict, List + +sys.path.insert(0, str(Path(__file__).parent.parent)) + +from src.utils import MarkdownParser + + +class MarkdownIndexBuilder: + """Build searchable index from markdown files""" + + def __init__(self, knowledge_dir: Path, output_file: Path): + self.knowledge_dir = Path(knowledge_dir) + self.output_file = Path(output_file) + self.index: Dict = { + "files": [], + "headings": [], + "code_blocks": [], + "keywords": {}, + } + + def build(self): + """Build index from all markdown files""" + print("๐Ÿ” Building markdown index...") + + md_files = list(self.knowledge_dir.rglob("*.md")) + print(f"Found {len(md_files)} markdown files") + + for md_file in md_files: + self._index_file(md_file) + + self._save_index() + print(f"โœ“ Index saved to {self.output_file}") + + def _index_file(self, file_path: Path): + """Index a single markdown file""" + parser = MarkdownParser.from_file(str(file_path)) + + relative_path = file_path.relative_to(self.knowledge_dir.parent) + file_info = { + "path": str(relative_path), + "name": file_path.name, + "stem": file_path.stem, + } + + headings = parser.extract_headings() + for heading in headings: + self.index["headings"].append( + { + "file": str(relative_path), + "level": heading.level, + "text": heading.text, + "line": heading.line, + } + ) + + code_blocks = parser.extract_code_blocks() + for block in code_blocks: + self.index["code_blocks"].append( + { + "file": str(relative_path), + "language": block.language, + "preview": block.content[:100], + "line": block.start_line, + } + ) + + plain_text = parser.convert_to_plain_text() + for word in self._extract_keywords(plain_text): + if word not in self.index["keywords"]: + self.index["keywords"][word] = [] + self.index["keywords"][word].append(str(relative_path)) + + self.index["files"].append(file_info) + + print(f" โœ“ Indexed: {file_path.name}") + + def _extract_keywords(self, text: str) -> List[str]: + """Extract important keywords from text""" + import re + + words = re.findall(r"\b[a-zA-Z_]{3,}\b", text.lower()) + + common_words = { + "the", + "and", + "for", + "this", + "that", + "with", + "from", + "your", + } + keywords = [w for w in words if w not in common_words] + + from collections import Counter + + word_freq = Counter(keywords) + return [w for w, _ in word_freq.most_common(100)] + + def _save_index(self): + """Save index to JSON file""" + self.output_file.parent.mkdir(parents=True, exist_ok=True) + with open(self.output_file, "w", encoding="utf-8") as f: + json.dump(self.index, f, indent=2, ensure_ascii=False) + + def search(self, query: str) -> List[Dict]: + """Search the index""" + with open(self.output_file, "r", encoding="utf-8") as f: + index = json.load(f) + + results = [] + query_lower = query.lower() + + for heading in index["headings"]: + if query_lower in heading["text"].lower(): + results.append( + { + "type": "heading", + "file": heading["file"], + "text": heading["text"], + "line": heading["line"], + } + ) + + for code in index["code_blocks"]: + if query_lower in code["preview"].lower(): + results.append( + { + "type": "code", + "file": code["file"], + "language": code["language"], + "preview": code["preview"], + "line": code["line"], + } + ) + + return results + + +import sys + +if __name__ == "__main__": + base_dir = Path(__file__).parent.parent + knowledge_dir = base_dir / "data" / "knowledge" + output_file = base_dir / "data" / "cache" / "markdown_index.json" + + builder = MarkdownIndexBuilder(knowledge_dir, output_file) + builder.build() + + print("\n๐Ÿ“‹ Search index built successfully!") + print(f"๐Ÿ“ Output: {output_file}") diff --git a/scripts/generate_thanks.py b/scripts/generate_thanks.py new file mode 100644 index 0000000000000000000000000000000000000000..c2c362a8245b4221c72e3b5cb4366fe0304c2fe1 --- /dev/null +++ b/scripts/generate_thanks.py @@ -0,0 +1,87 @@ +"""Thanking Message Generator""" + +import random +from datetime import datetime + + +class ThankingMessageGenerator: + """Generate variety of thank you messages""" + + EMOJIS = ["๐Ÿ™", "๐Ÿ’–", "โญ", "โœจ", "๐ŸŒŸ", "๐Ÿ’ซ", "๐ŸŽ‰", "๐Ÿ™"] + + GREETINGS = [ + "Thank you for using", + "Appreciate your interest in", + "Grateful for your support of", + "Thanks for trying", + ] + + PRODUCT_NAME = "Burme-Coder-Max" + + FOLLOW_UPS = [ + "Keep coding!", + "Happy coding!", + "Let me know if you need more help!", + "Feel free to ask follow-up questions!", + "Happy learning!", + ] + + @classmethod + def generate(cls, include_emoji: bool = True) -> str: + """Generate a random thank you message""" + parts = [] + + if include_emoji: + parts.append(random.choice(cls.EMOJIS)) + parts.append(" ") + + parts.append(random.choice(cls.GREETINGS)) + parts.append(" ") + parts.append(cls.PRODUCT_NAME) + parts.append("!") + + if random.random() > 0.5: + parts.append("\n") + parts.append(random.choice(cls.FOLLOW_UPS)) + + return "".join(parts) + + @classmethod + def generate_detailed(cls, topic: str = None) -> dict: + """Generate detailed appreciation message""" + return { + "message": cls.generate(), + "topic": topic, + "timestamp": datetime.now().isoformat(), + "emoji": random.choice(cls.EMOJIS), + } + + @classmethod + def generate_stack(cls, count: int = 3) -> list: + """Generate multiple thank you messages""" + return [cls.generate() for _ in range(count)] + + +def main(): + """Demo the thank you generator""" + print("=== Thanking Message Generator ===\n") + + generator = ThankingMessageGenerator() + + print("Single message:") + print(generator.generate()) + print() + + print("With topic:") + detailed = generator.generate_detailed("Python decorators") + print(detailed["message"]) + print(f"Topic: {detailed['topic']}") + print() + + print("Multiple messages (stack):") + for i, msg in enumerate(generator.generate_stack(3), 1): + print(f"{i}. {msg}") + + +if __name__ == "__main__": + main() diff --git a/scripts/update_knowledge.py b/scripts/update_knowledge.py new file mode 100644 index 0000000000000000000000000000000000000000..0d897146b036d5153675e3e3b527bbe6948934f8 --- /dev/null +++ b/scripts/update_knowledge.py @@ -0,0 +1,38 @@ +"""Web-based Knowledge Update Script""" + +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent.parent)) + +from src.knowledge import WebUpdater, LocalKB + + +def main(): + """Update knowledge from web sources""" + print("๐ŸŒ Burme-Coder-Max Web Updater") + print("=" * 40) + + updater = WebUpdater() + + print("\nFetching content from web sources...") + results = updater.fetch_all() + + print(f"\nโœ“ Fetched {len(results)} sources:") + for name in results.keys(): + print(f" - {name}") + + output_dir = Path(__file__).parent.parent / "data" / "knowledge" / "skills" + + print(f"\nUpdating markdown files to {output_dir}...") + updated = updater.update_markdown_files(output_dir, force=False) + + print(f"โœ“ Updated {len(updated)} files:") + for name in updated: + print(f" - {name}") + + print("\nโœ… Knowledge update complete!") + + +if __name__ == "__main__": + main() diff --git a/setup.py b/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..6187fea4238012bdeb17572913e14e8eafae3c6a --- /dev/null +++ b/setup.py @@ -0,0 +1,48 @@ +"""burme-coder-max: Myanmar AI Coding Agent Package""" +from setuptools import setup, find_packages + +setup( + name="burme-coder-max", + version="1.0.0", + author="amkyawdev", + author_email="contact@amkyawdev.com", + description="Expert Myanmar AI coding agent with terminal animations", + long_description=open("README.md", "r", encoding="utf-8").read(), + long_description_content_type="text/markdown", + url="https://huggingface.co/datasets/amkyawdev/burme-coder-max", + packages=find_packages(where="src"), + package_dir={"": "src"}, + classifiers=[ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Topic :: Software Development :: Libraries :: Python Modules", + ], + python_requires=">=3.8", + install_requires=[ + "click>=8.0.0", + "rich>=13.0.0", + "requests>=2.28.0", + "beautifulsoup4>=4.11.0", + "lxml>=4.9.0", + "pydantic>=2.0.0", + ], + extras_require={ + "dev": [ + "pytest>=7.0.0", + "pytest-asyncio>=0.21.0", + "black>=23.0.0", + "mypy>=1.0.0", + ], + }, + entry_points={ + "console_scripts": [ + "burme-coder=cli.main:main", + ], + }, +) diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3c2e7b1d8b7ecc08399da2acf19b0fa0334281a2 --- /dev/null +++ b/src/__init__.py @@ -0,0 +1,10 @@ +"""burme-coder-max: Myanmar AI Coding Agent Package""" + +__version__ = "1.0.0" +__author__ = "amkyawdev" + +from src.core import agent, executor, validator +from src.cli import main +from src.animations import Spinner, ProgressBar, TypingEffect +from src.ui import colors, layout, thanking +from src.knowledge import LocalKB, WebUpdater diff --git a/src/animations/__init__.py b/src/animations/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3fc56165cddc9f63d131d1d9cf3a4530771f94d0 --- /dev/null +++ b/src/animations/__init__.py @@ -0,0 +1,15 @@ +"""Animations module - Terminal visual effects""" + +from .spinner import Spinner +from .progress_bar import ProgressBar +from .particle_effect import ParticleBurst +from .typing_effect import TypingEffect +from .config import AnimationConfig + +__all__ = [ + "Spinner", + "ProgressBar", + "ParticleBurst", + "TypingEffect", + "AnimationConfig", +] diff --git a/src/animations/config.py b/src/animations/config.py new file mode 100644 index 0000000000000000000000000000000000000000..835d2d6c5bce06e09b0b6ae06d00ec7f747a2bdd --- /dev/null +++ b/src/animations/config.py @@ -0,0 +1,54 @@ +"""Animation Configuration""" + +from dataclasses import dataclass +from enum import Enum + + +class ColorMode(Enum): + """Color mode options""" + + AUTO = "auto" + ALWAYS = "always" + NEVER = "never" + + +@dataclass +class AnimationConfig: + """Configuration for terminal animations""" + + speed: float = 0.05 + color_enabled: bool = True + color_mode: ColorMode = ColorMode.AUTO + default_frames: int = 30 + particle_count: int = 50 + + SPINNER_FRAMES = ["โ ‹", "โ ™", "โ น", "โ ธ", "โ ผ", "โ ด", "โ ฆ", "โ ง", "โ ‡", "โ "] + + PROGRESS_CHARS = "โ–ˆโ–“โ–’โ–‘" + + @classmethod + def from_env(cls) -> "AnimationConfig": + """Create config from environment variables""" + import os + + return cls( + speed=float(os.getenv("ANIMATION_SPEED", "0.05")), + color_enabled=os.getenv("ANIMATION_COLOR", "true").lower() == "true", + ) + + def should_use_color(self) -> bool: + """Check if color should be used""" + if not self.color_enabled: + return False + + if self.color_mode == ColorMode.ALWAYS: + return True + elif self.color_mode == ColorMode.NEVER: + return False + else: + import sys + + return sys.stdout.isatty() + + +DEFAULT_CONFIG = AnimationConfig() diff --git a/src/animations/particle_effect.py b/src/animations/particle_effect.py new file mode 100644 index 0000000000000000000000000000000000000000..06cc8b733048af181a71063317e5ca5717d6cb1a --- /dev/null +++ b/src/animations/particle_effect.py @@ -0,0 +1,177 @@ +"""Particle Burst Effect - Celebration animations""" + +import sys +import time +import random +import threading +from typing import Optional, Tuple +from dataclasses import dataclass + +from .config import DEFAULT_CONFIG, AnimationConfig + + +@dataclass +class Particle: + """Individual particle for burst effect""" + + x: float + y: float + vx: float + vy: float + char: str + color: str + lifetime: int + + +class ParticleBurst: + """Create particle burst celebration effect""" + + PARTICLE_CHARS = ["*", "โœฆ", "โ—†", "โ—", "โ—‹", "โœฟ", "โ€", "โ˜…", "โ˜†", "โ—‡", "โ–ก", "โ—‹"] + COLORS = [ + "\033[91m", + "\033[92m", + "\033[93m", + "\033[94m", + "\033[95m", + "\033[96m", + "\033[97m", + ] + RESET = "\033[0m" + + def __init__( + self, + center_x: Optional[int] = None, + center_y: Optional[int] = None, + count: int = 50, + config: Optional[AnimationConfig] = None, + ): + self.center_x = center_x or 40 + self.center_y = center_y or 10 + self.count = count + self.config = config or DEFAULT_CONFIG + self.particles: list[Particle] = [] + self.running = False + + def _create_particle(self) -> Particle: + """Create a single particle""" + angle = random.uniform(0, 2 * 3.14159) + speed = random.uniform(0.5, 2.0) + + return Particle( + x=self.center_x, + y=self.center_y, + vx=random.uniform(-1, 1) + (1 if angle < 3.14159 else -1), + vy=random.uniform(-2, 0), + char=random.choice(self.PARTICLE_CHARS), + color=random.choice(self.COLORS), + lifetime=random.randint(20, 40), + ) + + def _animate(self): + """Animate particle system""" + self.particles = [self._create_particle() for _ in range(self.count)] + self.running = True + + while self.running and self.particles: + lines = [] + max_y = 0 + + for particle in self.particles[:]: + particle.x += particle.vx + particle.y += particle.vy + particle.vy += 0.1 + particle.lifetime -= 1 + + if particle.lifetime <= 0 or particle.y > 50: + self.particles.remove(particle) + continue + + x_pos = max(0, int(particle.x)) + y_pos = max(0, int(particle.y)) + max_y = max(max_y, y_pos) + + line_content = " " * x_pos + particle.color + particle.char + self.RESET + lines.append((y_pos, line_content)) + + if not lines: + break + + lines.sort(key=lambda x: x[0]) + + sys.stdout.write("\033[2J") + sys.stdout.write("\033[H") + + for y, content in lines: + sys.stdout.write(content + "\n") + + for _ in range(max(0, 20 - max_y)): + sys.stdout.write("\n") + + sys.stdout.flush() + time.sleep(0.05) + + sys.stdout.write("\033[2J") + sys.stdout.write("\033[H") + sys.stdout.flush() + + def explode(self): + """Trigger the burst animation""" + thread = threading.Thread(target=self._animate, daemon=True) + thread.start() + thread.join() + + @staticmethod + def explode_at(message: str, times: int = 3): + """Show explosion effect around a message""" + for _ in range(times): + burst = ParticleBurst(count=30) + burst.center_x = 50 + burst.center_y = 15 + burst.explode() + time.sleep(0.3) + + print(message) + + +class SimpleConfetti: + """Lightweight confetti effect""" + + CONFETTI = ["๐ŸŽ‰", "๐ŸŽŠ", "โœจ", "๐Ÿ’ซ", "โญ", "๐ŸŒŸ", "๐ŸŽˆ", "๐ŸŽ"] + + def __init__(self, duration: float = 2.0): + self.duration = duration + self.end_time = 0 + + def __iter__(self): + """Generate confetti frames""" + self.end_time = time.time() + self.duration + while time.time() < self.end_time: + confetti = " ".join(random.choices(self.CONFETTI, k=random.randint(5, 15))) + yield f"\r{confetti}" + time.sleep(0.2) + + yield "\r" + " " * 50 + "\r" + + def show(self): + """Display confetti""" + try: + for frame in self: + sys.stdout.write(frame) + sys.stdout.flush() + except KeyboardInterrupt: + pass + + +class ThankYouBurst: + """Special burst for thank you messages""" + + @staticmethod + def show(): + """Show thank you burst animation""" + ParticleBurst.explode_at("๐Ÿ™ Thank You! ๐Ÿ™", times=3) + + +def celebration(message: str = "๐ŸŽ‰"): + """Quick celebration effect""" + SimpleConfetti(duration=1.5).show() + print(message) diff --git a/src/animations/progress_bar.py b/src/animations/progress_bar.py new file mode 100644 index 0000000000000000000000000000000000000000..e9c0cb241d48137314d0b79483f49d77637d400d --- /dev/null +++ b/src/animations/progress_bar.py @@ -0,0 +1,145 @@ +"""Progress Bar - Show progress for long operations""" + +import sys +import time +from typing import Iterable, Optional, Union +from dataclasses import dataclass + +from .config import DEFAULT_CONFIG, AnimationConfig + + +@dataclass +class ProgressBarConfig: + """Configuration for progress bar appearance""" + + width: int = 40 + fill_char: str = "โ–ˆ" + empty_char: str = "โ–‘" + show_percentage: bool = True + show_count: bool = True + + +class ProgressBar: + """Customizable progress bar for terminal""" + + def __init__( + self, + iterable: Optional[Iterable] = None, + total: Optional[int] = None, + description: str = "Progress", + config: Optional[ProgressBarConfig] = None, + animation_config: Optional[AnimationConfig] = None, + ): + self.iterable = iterable + self.total = total if total is not None else len(iterable) if iterable else 100 + self.description = description + self.progress_config = config or ProgressBarConfig() + self.animation_config = animation_config or DEFAULT_CONFIG + + self.current = 0 + self.start_time = time.time() + + def __iter__(self): + """Make ProgressBar iterable""" + for item in self.iterable or range(self.total): + yield item + self.update(self.current + 1) + + def update(self, current: int): + """Update progress bar to new value""" + self.current = min(current, self.total) + self._render() + + def _render(self): + """Render the progress bar""" + percentage = self.current / self.total if self.total > 0 else 0 + filled_len = int(self.progress_config.width * percentage) + empty_len = self.progress_config.width - filled_len + + bar = ( + self.progress_config.fill_char * filled_len + + self.progress_config.empty_char * empty_len + ) + + if self.progress_config.show_percentage: + pct_str = f" {percentage * 100:.1f}%" + else: + pct_str = "" + + if self.progress_config.show_count: + count_str = f" [{self.current}/{self.total}]" + else: + count_str = "" + + elapsed = time.time() - self.start_time + if self.current > 0: + rate = self.current / elapsed + eta = (self.total - self.current) / rate if rate > 0 else 0 + rate_str = f" ETA: {eta:.1f}s" + else: + rate_str = "" + + line = f"\r{self.description}: |{bar}|{pct_str}{count_str}{rate_str}" + sys.stdout.write(line) + sys.stdout.flush() + + if self.current >= self.total: + sys.stdout.write("\n") + + def set_description(self, description: str): + """Update the description""" + self.description = description + + @property + def percent(self) -> float: + """Get current percentage""" + return self.current / self.total if self.total > 0 else 0 + + +class DownloadProgressBar(ProgressBar): + """Progress bar designed for file downloads""" + + def __init__(self, total_bytes: int, filename: str = "file"): + super().__init__( + total=total_bytes, + description=f"Downloading {filename}", + ) + self.total_bytes = total_bytes + + def update_bytes(self, current_bytes: int): + """Update with byte count""" + self.update(current_bytes) + + def _render(self): + """Custom render for byte-based progress""" + percentage = self.current / self.total if self.total > 0 else 0 + filled_len = int(self.progress_config.width * percentage) + bar = self.progress_config.fill_char * filled_len + + current_mb = self.current / (1024 * 1024) + total_mb = self.total / (1024 * 1024) + + line = f"\r{self.description}: {current_mb:.1f}/{total_mb:.1f} MB |{bar}| {percentage * 100:.1f}%" + sys.stdout.write(line) + sys.stdout.flush() + + +class InfiniteProgressBar: + """Infinite looping progress bar""" + + CHARS = ["โ ‹", "โ ™", "โ น", "โ ธ", "โ ผ", "โ ด", "โ ฆ", "โ ง", "โ ‡", "โ "] + PROGRESS = " โ–ˆโ–“โ–’โ–‘" + + def __init__(self, description: str = "Working"): + self.description = description + self.frame = 0 + + def spin(self): + """Generate next frame""" + char = self.CHARS[self.frame % len(self.CHARS)] + self.frame += 1 + return f"\r{char} {self.description}..." + + def reset(self): + """Reset frame counter""" + self.frame = 0 diff --git a/src/animations/spinner.py b/src/animations/spinner.py new file mode 100644 index 0000000000000000000000000000000000000000..25a88948b4d680616136e1b270d3070de8c5c9e8 --- /dev/null +++ b/src/animations/spinner.py @@ -0,0 +1,89 @@ +"""Loading Spinner - Show loading state""" + +import sys +import time +import threading +from typing import Optional +from contextlib import contextmanager + +from .config import DEFAULT_CONFIG, AnimationConfig + + +class Spinner: + """Animated loading spinner for terminal""" + + FRAMES = ["โ ‹", "โ ™", "โ น", "โ ธ", "โ ผ", "โ ด", "โ ฆ", "โ ง", "โ ‡", "โ "] + + def __init__(self, message: str = "Loading", config: Optional[AnimationConfig] = None): + self.message = message + self.config = config or DEFAULT_CONFIG + self.running = False + self.thread: Optional[threading.Thread] = None + self.frame_index = 0 + + def _spin(self): + """Internal spin loop""" + while self.running: + frame = self.SPINNER_FRAMES[self.frame_index % len(self.SPINNER_FRAMES)] + sys.stdout.write(f"\r{self.config.speed} {frame} {self.message}...") + sys.stdout.flush() + time.sleep(self.config.speed) + self.frame_index += 1 + + sys.stdout.write("\r" + " " * (len(self.message) + 10)) + sys.stdout.write("\r") + sys.stdout.flush() + + def start(self): + """Start the spinner animation""" + self.running = True + self.thread = threading.Thread(target=self._spin, daemon=True) + self.thread.start() + + def stop(self): + """Stop the spinner animation""" + self.running = False + if self.thread: + self.thread.join(timeout=0.5) + + @contextmanager + def __call__(self): + """Context manager for spinner""" + try: + self.start() + yield self + finally: + self.stop() + + +class SimpleSpinner: + """Simple spinner without threading""" + + def __init__(self, message: str = "Loading"): + self.message = message + self.frame_index = 0 + + def spin(self) -> str: + """Get next spin frame""" + frame = Spinner.FRAMES[self.frame_index % len(Spinner.FRAMES)] + self.frame_index += 1 + return f"\r{frame} {self.message}..." + + def reset(self): + """Reset spinner state""" + self.frame_index = 0 + + +def spinning(message: str = "Loading", duration: float = 2.0): + """Simple spinning animation for a duration""" + spinner = SimpleSpinner(message) + end_time = time.time() + duration + + while time.time() < end_time: + sys.stdout.write(spinner.spin()) + sys.stdout.flush() + time.sleep(0.1) + + sys.stdout.write("\r" + " " * (len(message) + 10)) + sys.stdout.write("\r") + sys.stdout.flush() diff --git a/src/animations/typing_effect.py b/src/animations/typing_effect.py new file mode 100644 index 0000000000000000000000000000000000000000..5b83bbeea580e08159d0d144c3864ef04f2a17a8 --- /dev/null +++ b/src/animations/typing_effect.py @@ -0,0 +1,141 @@ +"""Typing Effect - Typewriter animation""" + +import sys +import time +from typing import Optional, Callable +from contextlib import contextmanager + +from .config import DEFAULT_CONFIG, AnimationConfig + + +class TypingEffect: + """Typewriter-style text animation""" + + def __init__( + self, + text: str = "", + delay: Optional[float] = None, + config: Optional[AnimationConfig] = None, + ): + self.text = text + self.config = config or DEFAULT_CONFIG + self.delay = delay if delay is not None else self.config.speed + self.cursor = "โ–ˆ" + self.blink_delay = 0.3 + + def animate(self) -> str: + """Animate typing the text and return result""" + result = "" + cursor_on = True + + for i, char in enumerate(self.text): + result += char + cursor_str = self.cursor if cursor_on else " " + sys.stdout.write(f"\r{result}{cursor_str}") + sys.stdout.flush() + + time.sleep(self.delay) + cursor_on = not cursor_on + + sys.stdout.write(f"\r{result} \n") + sys.stdout.flush() + + return result + + def animate_with_callback( + self, callback: Callable[[str], None], interval: float = 1.0 + ): + """Animate text and call callback at intervals""" + result = "" + callback_count = 0 + + for char in self.text: + result += char + callback_count += 1 + + sys.stdout.write(f"\r{result}") + sys.stdout.flush() + + if callback_count % int(interval / self.delay) == 0: + callback(result) + + time.sleep(self.delay) + + sys.stdout.write(f"\r{result} \n") + sys.stdout.flush() + + +class SlowTypingEffect(TypingEffect): + """Slow typewriter effect for dramatic effect""" + + def __init__(self, text: str = ""): + super().__init__(text=text, delay=0.1) + + +class FastTypingEffect(TypingEffect): + """Fast typewriter effect""" + + def __init__(self, text: str = ""): + super().__init__(text=text, delay=0.01) + + +class CodeTypingEffect(TypingEffect): + """Typing effect optimized for code""" + + def __init__(self, text: str = ""): + super().__init__(text=text, delay=0.005) + + def __call__(self): + return self.animate() + + +@contextmanager +def typing_context(text: str, delay: float = 0.05): + """Context manager for typing effect""" + effect = TypingEffect(text=text, delay=delay) + print(f"\r{text[:10]}...", end="", flush=True) + + try: + yield effect + finally: + for _ in range(len(text) + 5): + sys.stdout.write("\b \b") + sys.stdout.flush() + sys.stdout.flush() + + +class LiveTypingDisplay: + """Display that shows typing in real-time""" + + def __init__(self): + self.content = "" + + def append(self, char: str): + """Append character and update display""" + self.content += char + sys.stdout.write(char) + sys.stdout.flush() + + def append_many(self, text: str): + """Append multiple characters""" + for char in text: + self.append(char) + + def clear(self): + """Clear the display""" + self.content = "" + sys.stdout.write("\033[2K\r") + sys.stdout.flush() + + def backspace(self, count: int = 1): + """Backspace characters""" + self.content = self.content[:-count] + backspace_seq = "\b \b" * count + sys.stdout.write(backspace_seq) + sys.stdout.flush() + + +def type_text(text: str, delay: float = 0.05): + """Quick function to type text to terminal""" + effect = TypingEffect(text=text, delay=delay) + return effect.animate() diff --git a/src/cli/__init__.py b/src/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f7e1e45dcbb14214fffee78006fbf1c9588d8af5 --- /dev/null +++ b/src/cli/__init__.py @@ -0,0 +1,7 @@ +"""CLI module initialization""" + +from .main import main +from .commands import run_command, train_command, eval_command +from .interactive import InteractiveMode + +__all__ = ["main", "run_command", "train_command", "eval_command", "InteractiveMode"] diff --git a/src/cli/commands.py b/src/cli/commands.py new file mode 100644 index 0000000000000000000000000000000000000000..8a8a6b7ea288ca6417e36f7b712fe006391a9882 --- /dev/null +++ b/src/cli/commands.py @@ -0,0 +1,181 @@ +"""CLI Commands - run, train, eval""" + +import json +import time +from pathlib import Path +from typing import Optional + +import click +from rich.console import Console +from rich.progress import Progress, SpinnerColumn, TextColumn + +from src.core import CoderAgent, ResponseValidator +from src.animations import Spinner, ProgressBar +from src.knowledge import LocalKB + + +console = Console() + + +@click.command() +@click.argument("instruction") +@click.option("--model", default="gpt-4", help="AI model") +@click.option("--output", "-o", help="Output file for response") +@click.option("--validate/--no-validate", default=True, help="Validate response") +def run_command(instruction: str, model: str, output: Optional[str], validate: bool): + """Run a single instruction and display response""" + agent = CoderAgent(model=model) + validator = ResponseValidator() + + console.print(f"[bold cyan]Question:[/bold cyan] {instruction}\n") + + with Spinner("Generating response..."): + response = agent.generate_response(instruction) + + console.print("[bold green]Response:[/bold green]") + console.print(response["response"]) + + if validate: + console.print("\n[bold yellow]Validating...[/bold yellow]") + result = validator.validate(response["response"], instruction) + console.print(f"Quality: [bold]{result.quality.value}[/bold]") + console.print(f"Score: [bold]{result.score:.2f}[/bold]") + + if result.issues: + console.print("[bold red]Issues:[/bold red]") + for issue in result.issues: + console.print(f" - {issue}") + + if output: + Path(output).write_text(response["response"], encoding="utf-8") + console.print(f"\n[green]Response saved to {output}[/green]") + + +@click.command() +@click.argument("data_dir") +@click.option("--epochs", default=10, help="Training epochs") +@click.option("--batch-size", default=4, help="Batch size") +def train_command(data_dir: str, epochs: int, batch_size: int): + """Train agent on trajectory data""" + console.print("[bold cyan]Training Agent...[/bold cyan]\n") + + data_path = Path(data_dir) + if not data_path.exists(): + console.print(f"[bold red]Error:[/bold red] {data_dir} not found") + return + + trajectory_files = list(data_path.glob("*.jsonl")) + if not trajectory_files: + console.print(f"[bold red]Error:[/bold red] No trajectory files in {data_dir}") + return + + console.print(f"Found {len(trajectory_files)} trajectory files\n") + + for epoch in range(epochs): + console.print(f"[bold cyan]Epoch {epoch + 1}/{epochs}[/bold cyan]") + + with Progress( + SpinnerColumn(), + TextColumn("[progress.description]{task.description}"), + console=console, + ) as progress: + task = progress.add_task("Processing...", total=len(trajectory_files)) + + for traj_file in trajectory_files: + progress.update(task, advance=1) + + with open(traj_file, "r", encoding="utf-8") as f: + for line in f: + data = json.loads(line) + # Process trajectory data + pass + + time.sleep(0.5) + + console.print("\n[bold green]Training completed![/bold green]") + + +@click.command() +@click.argument("data_dir") +@click.option("--verbose", is_flag=True, help="Show detailed results") +def eval_command(data_dir: str, verbose: bool): + """Evaluate agent on test data""" + console.print("[bold cyan]Evaluating Agent...[/bold cyan]\n") + + data_path = Path(data_dir) + if not data_path.exists(): + console.print(f"[bold red]Error:[/bold red] {data_dir} not found") + return + + kb = LocalKB() + + test_queries = [ + "Python decorator hta ya py", + "JavaScript async/await hta ya", + "SQL JOIN operations hta ya", + "React useState lo useEffect hta ya", + ] + + agent = CoderAgent() + validator = ResponseValidator() + + results = [] + with Progress( + SpinnerColumn(), TextColumn("[progress.description]{task.description}"), console=console + ) as progress: + task = progress.add_task("Testing...", total=len(test_queries)) + + for query in test_queries: + progress.update(task, description=f"Testing: {query[:30]}...") + + response = agent.generate_response(query) + validation = validator.validate(response["response"], query) + + results.append( + { + "query": query, + "quality": validation.quality.value, + "score": validation.score, + "issues": len(validation.issues), + } + ) + + progress.update(task, advance=1) + + console.print("\n[bold]Evaluation Results:[/bold]\n") + + total_score = sum(r["score"] for r in results) + avg_score = total_score / len(results) if results else 0 + + console.print(f"Average Score: [bold]{avg_score:.2f}[/bold]\n") + + for r in results: + color = "green" if r["score"] >= 0.6 else "yellow" if r["score"] >= 0.4 else "red" + console.print(f"[{color}]{r['query']}:[/{color}] {r['score']:.2f} ({r['quality']})") + + if verbose and r["issues"] > 0: + console.print(f" Issues: {r['issues']}") + + +@click.command() +@click.argument("query") +def search_command(query: str): + """Search knowledge base""" + kb = LocalKB() + results = kb.search(query) + + if not results: + console.print("[yellow]No results found[/yellow]") + return + + for result in results: + console.print(f"[bold cyan]{result['source']}[/bold cyan]") + console.print(result["content"][:200]) + console.print() + + +@click.command() +@click.argument("question") +def ask_command(question: str): + """Ask a question (alias for run)""" + run_command.callback(question, model="gpt-4", output=None, validate=True) diff --git a/src/cli/interactive.py b/src/cli/interactive.py new file mode 100644 index 0000000000000000000000000000000000000000..1fed836c83a6a162ec0194e4765fe70328a803ca --- /dev/null +++ b/src/cli/interactive.py @@ -0,0 +1,164 @@ +"""Interactive Mode - Chat with the Agent""" + +import sys +from rich.console import Console +from rich.prompt import Prompt, Confirm +from rich.panel import Panel +from rich.syntax import Syntax + +from src.core import CoderAgent +from src.animations import TypingEffect +from src.ui.thanking import ThankYou, Appreciation +from src.ui.layout import ChatboxLayout + + +class InteractiveMode: + """Interactive chat mode with the coder agent""" + + def __init__(self): + self.console = Console() + self.agent = CoderAgent() + self.layout = ChatboxLayout() + self.running = False + self.history: list[dict] = [] + + def start(self): + """Start the interactive session""" + self.running = True + + self.console.print(Panel.fit( + "[bold cyan]๐Ÿง‘โ€๐Ÿ’ป Burme-Coder-Max Interactive Mode[/bold cyan]\n" + "Type 'exit' to quit, 'clear' to clear history, 'help' for commands", + border_style="cyan", + )) + + while self.running: + try: + user_input = Prompt.ask("\n[bold green]You[/bold green]") + + if not user_input.strip(): + continue + + self._handle_command(user_input) + + except KeyboardInterrupt: + self.console.print("\n[yellow]Interrupted. Type 'exit' to quit.[/yellow]") + except EOFError: + self._exit() + + def _handle_command(self, user_input: str): + """Handle user input or commands""" + cmd = user_input.strip().lower() + + if cmd == "exit": + self._exit() + elif cmd == "clear": + self._clear_history() + elif cmd == "help": + self._show_help() + elif cmd == "history": + self._show_history() + elif cmd == "thank": + ThankYou.show() + elif cmd.startswith("/"): + self._handle_slash_command(user_input) + else: + self._generate_response(user_input) + + def _generate_response(self, instruction: str): + """Generate and display response""" + self.console.print() + + with TypingEffect("[bold blue]Agent[/bold blue] thinking..."): + response = self.agent.generate_response(instruction) + + self.console.print() + + if response["response"].startswith("#") or "```" in response["response"]: + self.console.print(Panel( + response["response"], + title="Response", + border_style="blue", + )) + else: + self.console.print(response["response"]) + + self.history.append({ + "role": "user", + "content": instruction, + "response": response["response"] + }) + + def _handle_slash_command(self, user_input: str): + """Handle slash commands""" + parts = user_input.split(maxsplit=1) + cmd = parts[0] + args = parts[1] if len(parts) > 1 else "" + + if cmd == "/search": + from src.knowledge import LocalKB + if args: + kb = LocalKB() + results = kb.search(args) + self.console.print(f"\n[cyan]Search results for '{args}':[/cyan]") + for r in results[:5]: + self.console.print(f" - {r['source']}") + else: + self.console.print("[yellow]Usage: /search [/yellow]") + + elif cmd == "/model": + if args: + self.console.print(f"[green]Switching to model: {args}[/green]") + self.agent = CoderAgent(model=args) + else: + self.console.print(f"[cyan]Current model: {self.agent.model}[/cyan]") + + elif cmd == "/reset": + self.agent.reset() + self.console.print("[green]Agent reset successfully[/green]") + + else: + self.console.print(f"[yellow]Unknown command: {cmd}[/yellow]") + + def _show_help(self): + """Show help message""" + help_text = """ +[bold cyan]Available Commands:[/bold cyan] + +[green]exit[/green] - Exit interactive mode +[green]clear[/green] - Clear conversation history +[green]history[/green] - Show conversation history +[green]thank[/green] - Show thank you animation +[green]help[/green] - Show this help message + +[yellow]/search [/yellow] - Search knowledge base +[yellow]/model [/yellow] - Switch AI model +[yellow]/reset[/yellow] - Reset agent state + """ + self.console.print(help_text) + + def _show_history(self): + """Show conversation history""" + if not self.history: + self.console.print("[yellow]No conversation history[/yellow]") + return + + self.console.print(f"\n[bold cyan]Conversation History ({len(self.history)} exchanges):[/bold cyan]\n") + + for i, item in enumerate(self.history[-10:], 1): + self.console.print(f"[dim]{i}.[/dim] [green]Q:[/green] {item['content'][:50]}...") + self.console.print(f" [blue]A:[/blue] {item['response'][:50]}...\n") + + def _clear_history(self): + """Clear conversation history""" + self.history = [] + self.agent.reset() + self.console.print("[green]History cleared[/green]") + + def _exit(self): + """Exit interactive mode""" + if Confirm.ask("Do you want to show appreciation?"): + Appreciation.show("interactive session") + + self.running = False + self.console.print("[cyan]Goodbye! ๐Ÿ‘‹[/cyan]") diff --git a/src/cli/main.py b/src/cli/main.py new file mode 100644 index 0000000000000000000000000000000000000000..aa83c64e12498cb55617516e37429eaa87cc1118 --- /dev/null +++ b/src/cli/main.py @@ -0,0 +1,82 @@ +"""Main CLI Entry Point""" + +import sys +import click +from rich.console import Console + +from .commands import run_command, train_command, eval_command +from .interactive import InteractiveMode + +console = Console() + + +@click.group() +@click.version_option(version="1.0.0") +def main(): + """๐Ÿง‘โ€๐Ÿ’ป Burme-Coder-Max - Myanmar AI Coding Agent""" + pass + + +@main.command() +@click.argument("instruction") +@click.option("--model", default="gpt-4", help="AI model to use") +@click.option("--verbose", is_flag=True, help="Verbose output") +def ask(instruction: str, model: str, verbose: bool): + """Ask a coding question in Burmese or English""" + from src.core import CoderAgent + from src.animations import Spinner + from src.ui.thanking import ThankYou + + agent = CoderAgent(model=model) + + with Spinner("Thinking..."): + response = agent.generate_response(instruction) + + console.print(response["response"]) + + if verbose: + console.print(f"\n[dim]Session: {response['session_id']}[/dim]") + console.print(f"[dim]Model: {response['model']}[/dim]") + + ThankYou.show() + + +@main.command() +@click.option("--host", default="0.0.0.0", help="Host to bind") +@click.option("--port", default=5000, help="Port to bind") +def serve(host: str, port: int): + """Start API server""" + console.print(f"[green]Starting server on {host}:{port}...[/green]") + console.print("[yellow]API server not yet implemented[/yellow]") + + +@main.command() +def interactive(): + """Start interactive mode""" + mode = InteractiveMode() + mode.start() + + +@main.command() +@click.option("--data", default="./data/trajectories", help="Training data directory") +@click.option("--epochs", default=10, help="Number of epochs") +def train(data: str, epochs: int): + """Train the agent on trajectories""" + train_command(data, epochs) + + +@main.command() +@click.option("--data", default="./data/trajectories", help="Evaluation data") +def eval(data: str): + """Evaluate agent performance""" + eval_command(data) + + +# Register subcommands +main.add_command(run_command) +main.add_command(train_command) +main.add_command(eval_command) + + +if __name__ == "__main__": + main() diff --git a/src/core/__init__.py b/src/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..88aed3b3cf8dd5ce121f3b790f461222bbe7ec3f --- /dev/null +++ b/src/core/__init__.py @@ -0,0 +1,7 @@ +"""Core module initialization""" + +from .agent import CoderAgent +from .executor import CodeExecutor +from .validator import ResponseValidator + +__all__ = ["CoderAgent", "CodeExecutor", "ResponseValidator"] diff --git a/src/core/agent.py b/src/core/agent.py new file mode 100644 index 0000000000000000000000000000000000000000..7d511a0a394415ebcd907ae18ac0ec9e5961384b --- /dev/null +++ b/src/core/agent.py @@ -0,0 +1,146 @@ +"""Coder Agent - Main AI Brain for Myanmar Coding Assistant""" + +import json +import time +from typing import Dict, List, Optional, Any +from pathlib import Path + + +class CoderAgent: + """Expert Myanmar AI coding agent with advanced knowledge""" + + SYSTEM_PROMPTS = [ + "You are an expert programmer with advanced knowledge in: Python, JavaScript, TypeScript, Java, C++, Go, Rust, etc.", + "You are a senior security reviewer. Analyze code for vulnerabilities and provide secure version with Myanmar explanation.", + "You are a testing expert. Generate comprehensive unit tests for the given function using pytest.", + "You are a GUI and game development expert. Provide complete, runnable code with Myanmar explanations.", + "You are an expert Myanmar AI coding agent. Answer in Myanmar language and provide code examples when needed.", + ] + + def __init__( + self, + model: str = "gpt-4", + temperature: float = 0.7, + max_tokens: int = 2048, + knowledge_dir: Optional[str] = None, + ): + self.model = model + self.temperature = temperature + self.max_tokens = max_tokens + self.knowledge_dir = Path(knowledge_dir) if knowledge_dir else None + self.conversation_history: List[Dict[str, str]] = [] + self.session_id = self._generate_session_id() + + def _generate_session_id(self) -> str: + """Generate unique session ID""" + return f"session_{int(time.time())}_{id(self)}" + + def set_system_prompt(self, prompt: str) -> None: + """Set custom system prompt""" + self.system_prompt = prompt + + def generate_response( + self, instruction: str, context: Optional[Dict[str, Any]] = None + ) -> Dict[str, Any]: + """Generate code response for the given instruction""" + self.conversation_history.append({"role": "user", "content": instruction}) + + response = { + "session_id": self.session_id, + "instruction": instruction, + "response": self._generate_code_response(instruction, context), + "timestamp": time.time(), + "model": self.model, + } + + self.conversation_history.append( + {"role": "assistant", "content": response["response"]} + ) + + return response + + def _generate_code_response( + self, instruction: str, context: Optional[Dict[str, Any]] + ) -> str: + """Internal method to generate code response""" + if self.knowledge_dir: + knowledge_content = self._check_knowledge_base(instruction) + if knowledge_content: + return knowledge_content + + return self._get_fallback_response(instruction) + + def _check_knowledge_base(self, instruction: str) -> Optional[str]: + """Check local knowledge base for relevant content""" + if not self.knowledge_dir: + return None + + keywords = self._extract_keywords(instruction) + for keyword in keywords: + kb_file = self.knowledge_dir / f"{keyword}_skills.md" + if kb_file.exists(): + return self._parse_markdown_file(kb_file) + + return None + + def _extract_keywords(self, text: str) -> List[str]: + """Extract keywords from instruction""" + common_langs = ["python", "javascript", "typescript", "java", "go", "rust", "sql"] + return [w for w in common_langs if w in text.lower()] + + def _parse_markdown_file(self, file_path: Path) -> str: + """Parse markdown file and extract content""" + content = file_path.read_text(encoding="utf-8") + lines = content.split("\n") + return "\n".join(lines[:20]) + + def _get_fallback_response(self, instruction: str) -> str: + """Get fallback response based on instruction""" + instruction_lower = instruction.lower() + + if "python" in instruction_lower: + return self._get_python_response(instruction) + elif "javascript" in instruction_lower or "js" in instruction_lower: + return self._get_javascript_response(instruction) + elif "sql" in instruction_lower: + return self._get_sql_response(instruction) + else: + return self._get_general_response(instruction) + + def _get_python_response(self, instruction: str) -> str: + """Generate Python response""" + return "# Python Code\n# TODO: Implement based on instruction" + + def _get_javascript_response(self, instruction: str) -> str: + """Generate JavaScript response""" + return "// JavaScript Code\n// TODO: Implement based on instruction" + + def _get_sql_response(self, instruction: str) -> str: + """Generate SQL response""" + return "-- SQL Query\n-- TODO: Implement based on instruction" + + def _get_general_response(self, instruction: str) -> str: + """Generate general response""" + return "# Code\n# TODO: Implement based on instruction" + + def get_trajectory(self) -> Dict[str, Any]: + """Get conversation trajectory for training""" + return { + "session_id": self.session_id, + "history": self.conversation_history, + "timestamp": time.time(), + } + + def save_trajectory(self, path: str) -> None: + """Save conversation trajectory to file""" + trajectory = self.get_trajectory() + file_path = Path(path) / f"session_{int(time.time())}.jsonl" + file_path.parent.mkdir(parents=True, exist_ok=True) + + with open(file_path, "w", encoding="utf-8") as f: + f.write(json.dumps(trajectory, ensure_ascii=False) + "\n") + + def reset(self) -> None: + """Reset agent state""" + self.conversation_history = [] + self.session_id = self._generate_session_id() diff --git a/src/core/executor.py b/src/core/executor.py new file mode 100644 index 0000000000000000000000000000000000000000..5563434afde365c3e1d6e41651167a15e6095855 --- /dev/null +++ b/src/core/executor.py @@ -0,0 +1,233 @@ +"""Code Execution Engine""" + +import subprocess +import sys +import ast +import re +from typing import Dict, Optional, Any +from dataclasses import dataclass + + +@dataclass +class ExecutionResult: + """Code execution result container""" + + success: bool + output: str + error: Optional[str] = None + execution_time: float = 0.0 + + +class CodeExecutor: + """Execute code in various programming languages""" + + SUPPORTED_LANGUAGES = ["python", "javascript", "typescript", "sql", "bash"] + + def __init__(self, timeout: int = 30, sandbox: bool = True): + self.timeout = timeout + self.sandbox = sandbox + self.execution_count = 0 + + def execute(self, code: str, language: str = "python") -> ExecutionResult: + """Execute code and return result""" + if language not in self.SUPPORTED_LANGUAGES: + return ExecutionResult( + success=False, + output="", + error=f"Unsupported language: {language}", + ) + + if self._contains_malicious_code(code): + return ExecutionResult( + success=False, + output="", + error="Potentially malicious code detected", + ) + + self.execution_count += 1 + + if language == "python": + return self._execute_python(code) + elif language == "javascript": + return self._execute_javascript(code) + elif language == "sql": + return self._execute_sql(code) + elif language == "bash": + return self._execute_bash(code) + + return ExecutionResult(success=False, output="", error="Execution failed") + + def _contains_malicious_code(self, code: str) -> bool: + """Check for potentially malicious patterns""" + dangerous_patterns = [ + r"__import__\s*\(", + r"exec\s*\(", + r"eval\s*\(", + r"subprocess\s*\(.*shell\s*=\s*True", + r"os\.system\s*\(", + r"shutil\.rmtree", + r"open\s*\([^)]*['\"][wr]", + ] + + for pattern in dangerous_patterns: + if re.search(pattern, code): + return True + + return False + + def _execute_python(self, code: str) -> ExecutionResult: + """Execute Python code""" + import time + + start_time = time.time() + + try: + tree = ast.parse(code) + namespace: Dict[str, Any] = {} + exec(compile(tree, "", "exec"), namespace) + + output = self._capture_output(namespace) + execution_time = time.time() - start_time + + return ExecutionResult( + success=True, output=output, execution_time=execution_time + ) + + except SyntaxError as e: + return ExecutionResult( + success=False, + output="", + error=f"Syntax Error: {e}", + execution_time=time.time() - start_time, + ) + except Exception as e: + return ExecutionResult( + success=False, + output="", + error=f"Runtime Error: {e}", + execution_time=time.time() - start_time, + ) + + def _capture_output(self, namespace: Dict[str, Any]) -> str: + """Capture relevant output from namespace""" + output_lines = [] + + if "result" in namespace: + output_lines.append(str(namespace["result"])) + + for key, value in namespace.items(): + if key.startswith("output_"): + output_lines.append(f"{key}: {value}") + + return "\n".join(output_lines) if output_lines else "Code executed successfully" + + def _execute_javascript(self, code: str) -> ExecutionResult: + """Execute JavaScript code using Node.js""" + import tempfile + import time + + start_time = time.time() + + with tempfile.NamedTemporaryFile( + mode="w", suffix=".js", delete=False + ) as f: + f.write(code) + temp_file = f.name + + try: + result = subprocess.run( + ["node", temp_file], + capture_output=True, + text=True, + timeout=self.timeout, + ) + + if result.returncode == 0: + return ExecutionResult( + success=True, + output=result.stdout, + execution_time=time.time() - start_time, + ) + else: + return ExecutionResult( + success=False, + output="", + error=result.stderr, + execution_time=time.time() - start_time, + ) + + except subprocess.TimeoutExpired: + return ExecutionResult( + success=False, + output="", + error=f"Execution timed out after {self.timeout}s", + execution_time=time.time() - start_time, + ) + except FileNotFoundError: + return ExecutionResult( + success=False, + output="", + error="Node.js not found. Please install Node.js to execute JavaScript.", + execution_time=time.time() - start_time, + ) + finally: + import os + + os.unlink(temp_file) + + def _execute_sql(self, code: str) -> ExecutionResult: + """Execute SQL query""" + import time + + start_time = time.time() + + return ExecutionResult( + success=True, + output=f"SQL query would be executed:\n{code}", + execution_time=time.time() - start_time, + ) + + def _execute_bash(self, code: str) -> ExecutionResult: + """Execute bash command""" + import time + + start_time = time.time() + + if self.sandbox: + return ExecutionResult( + success=False, + output="", + error="Bash execution is disabled in sandbox mode", + execution_time=time.time() - start_time, + ) + + try: + result = subprocess.run( + code, shell=True, capture_output=True, text=True, timeout=self.timeout + ) + + return ExecutionResult( + success=result.returncode == 0, + output=result.stdout, + error=result.stderr if result.returncode != 0 else None, + execution_time=time.time() - start_time, + ) + + except subprocess.TimeoutExpired: + return ExecutionResult( + success=False, + output="", + error=f"Command timed out after {self.timeout}s", + execution_time=time.time() - start_time, + ) + + def validate_syntax(self, code: str, language: str) -> tuple[bool, Optional[str]]: + """Validate code syntax without execution""" + if language == "python": + try: + ast.parse(code) + return True, None + except SyntaxError as e: + return False, str(e) + + return True, None diff --git a/src/core/validator.py b/src/core/validator.py new file mode 100644 index 0000000000000000000000000000000000000000..1d295b0873e2ee398df750d09a4662ca668c6ad1 --- /dev/null +++ b/src/core/validator.py @@ -0,0 +1,162 @@ +"""Response Validator - Validate AI generated responses""" + +import re +from typing import Dict, List, Optional, Tuple +from dataclasses import dataclass +from enum import Enum + + +class ResponseQuality(Enum): + """Response quality levels""" + + EXCELLENT = "excellent" + GOOD = "good" + ADEQUATE = "adequate" + POOR = "poor" + INVALID = "invalid" + + +@dataclass +class ValidationResult: + """Validation result container""" + + quality: ResponseQuality + score: float + issues: List[str] + suggestions: List[str] + + +class ResponseValidator: + """Validate AI generated code responses""" + + def __init__(self): + self.min_code_length = 50 + self.max_issues = 3 + self.quality_threshold = 0.6 + + def validate(self, response: str, instruction: str) -> ValidationResult: + """Validate response quality""" + issues: List[str] = [] + suggestions: List[str] = [] + score = 1.0 + + if len(response) < self.min_code_length: + issues.append("Response too short") + score -= 0.3 + + if not self._contains_code(response): + issues.append("No code block found in response") + score -= 0.5 + + if not self._is_relevant(response, instruction): + issues.append("Response may not address the instruction") + score -= 0.2 + + if self._has_obvious_errors(response): + issues.append("Potential errors detected in code") + score -= 0.2 + + code_blocks = self._extract_code_blocks(response) + for i, block in enumerate(code_blocks): + if block_language := self._detect_language(block): + lang_issues = self._check_language_specific(block, block_language) + issues.extend([f"Block {i+1}: {issue}" for issue in lang_issues]) + + if not issues: + suggestions.append("Response looks good!") + else: + suggestions.append("Consider adding more explanatory comments") + + quality = self._determine_quality(score, issues) + + return ValidationResult( + quality=quality, score=max(0, score), issues=issues, suggestions=suggestions + ) + + def _contains_code(self, response: str) -> bool: + """Check if response contains code blocks""" + return bool(re.search(r"```[\s\S]*?```", response)) + + def _is_relevant(self, response: str, instruction: str) -> bool: + """Check if response is relevant to instruction""" + instruction_words = set( + re.findall(r"\b\w+\b", instruction.lower()) + ) + response_words = set(re.findall(r"\b\w+\b", response.lower())) + overlap = instruction_words & response_words + + return len(overlap) >= min(3, len(instruction_words) * 0.3) + + def _has_obvious_errors(self, response: str) -> bool: + """Check for obvious code errors""" + error_patterns = [ + r"undefined\s+variable", + r"cannot\s+find\s+module", + r"syntax\s+error", + r"indentation\s+error", + ] + + for pattern in error_patterns: + if re.search(pattern, response, re.IGNORECASE): + return True + + return False + + def _extract_code_blocks(self, response: str) -> List[str]: + """Extract all code blocks from response""" + pattern = r"```[\w]*\n?([\s\S]*?)```" + matches = re.findall(pattern, response) + return [match.strip() for match in matches] + + def _detect_language(self, code: str) -> Optional[str]: + """Detect programming language from code""" + language_signatures = { + "python": [r"def\s+\w+\s*\(", r"import\s+\w+", r"if\s+__name__"], + "javascript": [r"const\s+\w+", r"function\s+\w+\s*\(", r"=>\s*{"], + "typescript": [r":\s*(string|number|boolean)\b", r"interface\s+\w+"], + "java": [r"public\s+class\s+\w+", r"System\.out\.println"], + "sql": [r"SELECT\s+.+\s+FROM", r"INSERT\s+INTO", r"CREATE\s+TABLE"], + "bash": [r"#!/bin/bash", r"echo\s+", r"\$\w+"], + } + + for lang, patterns in language_signatures.items(): + if any(re.search(p, code) for p in patterns): + return lang + + return None + + def _check_language_specific(self, code: str, language: str) -> List[str]: + """Language-specific validation checks""" + issues = [] + + if language == "python": + if re.search(r"def\s+\w+\s*\([^)]*$", code): + issues.append("Missing colon at end of function definition") + + if language == "javascript": + if re.search(r"const\s+\w+\s*=\s*\w+\s*\+\s*['\"]\s*['\"]", code): + issues.append("Empty string concatenation detected") + + return issues + + def _determine_quality( + self, score: float, issues: List[str] + ) -> ResponseQuality: + """Determine response quality based on score and issues""" + if score <= 0: + return ResponseQuality.INVALID + elif score >= 0.8 and len(issues) == 0: + return ResponseQuality.EXCELLENT + elif score >= 0.6: + return ResponseQuality.GOOD + elif score >= 0.4: + return ResponseQuality.ADEQUATE + else: + return ResponseQuality.POOR + + def validate_multiple( + self, responses: List[str], instruction: str + ) -> List[ValidationResult]: + """Validate multiple responses and rank them""" + results = [self.validate(resp, instruction) for resp in responses] + return sorted(results, key=lambda r: r.score, reverse=True) diff --git a/src/knowledge/__init__.py b/src/knowledge/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0972a7ad8ba2ea78882666a5293b8499df9c415f --- /dev/null +++ b/src/knowledge/__init__.py @@ -0,0 +1,8 @@ +"""Knowledge module - Local KB and Web Updater""" + +from .local_kb import LocalKB +from .web_updater import WebUpdater +from .version_tracker import VersionTracker +from .cache_manager import CacheManager + +__all__ = ["LocalKB", "WebUpdater", "VersionTracker", "CacheManager"] diff --git a/src/knowledge/cache_manager.py b/src/knowledge/cache_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..3a2b70ccc9a63e2874573b5d763140780720c451 --- /dev/null +++ b/src/knowledge/cache_manager.py @@ -0,0 +1,151 @@ +"""Cache Manager - Handle application caching""" + +import json +import time +import shutil +from pathlib import Path +from typing import Any, Optional, Dict +from dataclasses import dataclass, field + + +@dataclass +class CacheEntry: + """Single cache entry""" + + key: str + value: Any + created_at: float = field(default_factory=time.time) + expires_at: Optional[float] = None + hits: int = 0 + + def is_expired(self) -> bool: + """Check if entry has expired""" + if self.expires_at is None: + return False + return time.time() > self.expires_at + + +class CacheManager: + """Manage application cache""" + + def __init__(self, cache_dir: Optional[str] = None, default_ttl: int = 3600): + if cache_dir: + self.cache_dir = Path(cache_dir) + else: + self.cache_dir = Path.home() / ".burme_coder" / "cache" + + self.cache_dir.mkdir(parents=True, exist_ok=True) + self.default_ttl = default_ttl + self.memory_cache: Dict[str, CacheEntry] = {} + + def get(self, key: str, use_memory: bool = True) -> Optional[Any]: + """Get value from cache""" + if use_memory and key in self.memory_cache: + entry = self.memory_cache[key] + if not entry.is_expired(): + entry.hits += 1 + return entry.value + else: + del self.memory_cache[key] + + cache_file = self._get_cache_file(key) + if cache_file and cache_file.exists(): + try: + data = json.loads(cache_file.read_text(encoding="utf-8")) + entry = CacheEntry( + key=key, + value=data["value"], + created_at=data.get("created_at", time.time()), + expires_at=data.get("expires_at"), + ) + + if not entry.is_expired(): + return entry.value + else: + cache_file.unlink() + except (json.JSONDecodeError, KeyError): + pass + + return None + + def set( + self, key: str, value: Any, ttl: Optional[int] = None, use_memory: bool = True + ): + """Set value in cache""" + ttl = ttl if ttl is not None else self.default_ttl + expires_at = time.time() + ttl if ttl > 0 else None + + if use_memory: + self.memory_cache[key] = CacheEntry(key=key, value=value, expires_at=expires_at) + + cache_file = self._get_cache_file(key) + if cache_file: + cache_data = { + "key": key, + "value": value, + "created_at": time.time(), + "expires_at": expires_at, + } + cache_file.write_text(json.dumps(cache_data), encoding="utf-8") + + def delete(self, key: str): + """Delete cache entry""" + if key in self.memory_cache: + del self.memory_cache[key] + + cache_file = self._get_cache_file(key) + if cache_file and cache_file.exists(): + cache_file.unlink() + + def clear(self, pattern: Optional[str] = None): + """Clear cache entries""" + if pattern: + for cache_file in self.cache_dir.glob(f"{pattern}*"): + cache_file.unlink() + else: + for cache_file in self.cache_dir.glob("*.json"): + cache_file.unlink() + self.memory_cache.clear() + + def cleanup_expired(self): + """Remove all expired entries""" + expired_keys = [k for k, v in self.memory_cache.items() if v.is_expired()] + for key in expired_keys: + del self.memory_cache[key] + + for cache_file in self.cache_dir.glob("*.json"): + try: + data = json.loads(cache_file.read_text(encoding="utf-8")) + if data.get("expires_at") and time.time() > data["expires_at"]: + cache_file.unlink() + except (json.JSONDecodeError, KeyError): + pass + + def get_stats(self) -> Dict: + """Get cache statistics""" + total_hits = sum(e.hits for e in self.memory_cache.values()) + entries_count = len(self.memory_cache) + disk_files = len(list(self.cache_dir.glob("*.json"))) + + return { + "memory_entries": entries_count, + "disk_files": disk_files, + "total_hits": total_hits, + "cache_dir": str(self.cache_dir), + } + + def _get_cache_file(self, key: str) -> Optional[Path]: + """Get cache file path for key""" + safe_key = "".join(c if c.isalnum() or c in "-_" else "_" for c in key) + if len(safe_key) > 50: + import hashlib + safe_key = hashlib.md5(key.encode()).hexdigest() + + return self.cache_dir / f"{safe_key}.json" + + def clear_all(self): + """Clear all caches including memory""" + self.memory_cache.clear() + if self.cache_dir.exists(): + shutil.rmtree(self.cache_dir) + self.cache_dir.mkdir(parents=True, exist_ok=True) diff --git a/src/knowledge/local_kb.py b/src/knowledge/local_kb.py new file mode 100644 index 0000000000000000000000000000000000000000..b5b7539ff6d1b133c161ef4101180efcc90fa5ca --- /dev/null +++ b/src/knowledge/local_kb.py @@ -0,0 +1,115 @@ +"""Local Knowledge Base - Search markdown files""" + +import os +import json +from pathlib import Path +from typing import List, Dict, Optional + + +class LocalKB: + """Local knowledge base for markdown files""" + + def __init__(self, base_dir: Optional[str] = None): + if base_dir: + self.base_dir = Path(base_dir) + else: + self.base_dir = Path(__file__).parent.parent.parent / "data" / "knowledge" + + self.skills_dir = self.base_dir / "skills" + self.webs_dir = self.base_dir / "webs" + self.updates_dir = self.base_dir / "updates" + + self._ensure_directories() + + def _ensure_directories(self): + """Create necessary directories if they don't exist""" + for directory in [self.skills_dir, self.webs_dir, self.updates_dir]: + directory.mkdir(parents=True, exist_ok=True) + + def search(self, query: str, category: Optional[str] = None) -> List[Dict]: + """Search knowledge base for query""" + results = [] + + if category == "skills" or category is None: + results.extend(self._search_directory(self.skills_dir, query)) + + if category == "webs" or category is None: + results.extend(self._search_directory(self.webs_dir, query)) + + if category == "updates" or category is None: + results.extend(self._search_directory(self.updates_dir, query)) + + return results + + def _search_directory(self, directory: Path, query: str) -> List[Dict]: + """Search files in a directory""" + results = [] + query_lower = query.lower() + + for md_file in directory.glob("*.md"): + content = md_file.read_text(encoding="utf-8") + lines = content.split("\n") + + for i, line in enumerate(lines): + if query_lower in line.lower(): + start = max(0, i - 2) + end = min(len(lines), i + 5) + snippet = "\n".join(lines[start:end]) + + results.append( + { + "source": md_file.name, + "line": i + 1, + "snippet": snippet, + "relevance": self._calculate_relevance(line, query), + } + ) + + return sorted(results, key=lambda x: x["relevance"], reverse=True) + + def _calculate_relevance(self, text: str, query: str) -> float: + """Calculate relevance score""" + text_lower = text.lower() + query_lower = query.lower() + + if query_lower in text_lower: + return 1.0 + + query_words = query_lower.split() + matches = sum(1 for word in query_words if word in text_lower) + return matches / len(query_words) if query_words else 0 + + def get_all_topics(self) -> List[str]: + """Get list of all available topics""" + topics = [] + + for md_file in self.skills_dir.glob("*.md"): + topics.append(md_file.stem.replace("_", " ").title()) + + return sorted(topics) + + def get_content(self, topic: str) -> Optional[str]: + """Get content for a specific topic""" + topic_file = self.skills_dir / f"{topic.lower().replace(' ', '_')}.md" + + if topic_file.exists(): + return topic_file.read_text(encoding="utf-8") + + for md_file in self.skills_dir.glob("*.md"): + if topic.lower() in md_file.stem.lower(): + return md_file.read_text(encoding="utf-8") + + return None + + def get_random_entry(self) -> Optional[Dict]: + """Get a random knowledge entry""" + import random + + files = list(self.skills_dir.glob("*.md")) + if not files: + return None + + file = random.choice(files) + content = file.read_text(encoding="utf-8") + + return {"source": file.name, "content": content} diff --git a/src/knowledge/version_tracker.py b/src/knowledge/version_tracker.py new file mode 100644 index 0000000000000000000000000000000000000000..08ded0b4c73e438444dea94c0cf13eecd13e6723 --- /dev/null +++ b/src/knowledge/version_tracker.py @@ -0,0 +1,129 @@ +"""Version Tracker - Track versions and changelog""" + +import json +from pathlib import Path +from typing import List, Dict, Optional +from dataclasses import dataclass +from datetime import datetime + + +@dataclass +class Change: + """Represents a single change entry""" + + version: str + change_type: str + description: str + date: str + + +class VersionTracker: + """Track software versions and changelog""" + + CURRENT_VERSION = "1.0.0" + VERSION_FILE = "version.json" + + CHANGELOG = [ + { + "version": "1.0.0", + "date": "2025-01-01", + "changes": [ + "Initial release", + "Core agent functionality", + "Terminal animations", + "Knowledge base integration", + ], + }, + { + "version": "0.9.0", + "date": "2024-12-15", + "changes": [ + "Beta release", + "Myanmar language support", + "Basic animations", + ], + }, + ] + + def __init__(self, data_dir: Optional[Path] = None): + if data_dir: + self.data_dir = data_dir + else: + self.data_dir = Path.home() / ".burme_coder" + + self.data_dir.mkdir(parents=True, exist_ok=True) + self._ensure_version_file() + + def _ensure_version_file(self): + """Ensure version tracking file exists""" + version_file = self.data_dir / self.VERSION_FILE + + if not version_file.exists(): + version_file.write_text( + json.dumps({"version": self.CURRENT_VERSION, "last_updated": datetime.now().isoformat()}, indent=2) + ) + + def get_current_version(self) -> str: + """Get current version""" + return self.CURRENT_VERSION + + def get_changelog(self) -> List[Dict]: + """Get full changelog""" + return self.CHANGELOG + + def get_changes_for_version(self, version: str) -> Optional[Dict]: + """Get changes for a specific version""" + for entry in self.CHANGELOG: + if entry["version"] == version: + return entry + return None + + def is_update_available(self, remote_version: str) -> bool: + """Check if update is available""" + current = self._version_tuple(self.CURRENT_VERSION) + remote = self._version_tuple(remote_version) + return remote > current + + def _version_tuple(self, version: str) -> tuple: + """Convert version string to tuple for comparison""" + parts = version.replace("-", ".").split(".") + return tuple(int(p) if p.isdigit() else 0 for p in parts) + + def get_roadmap(self) -> List[Dict]: + """Get project roadmap""" + return [ + { + "version": "1.1.0", + "planned_features": [ + "Enhanced animations", + "More language support", + "Improved knowledge base", + ], + }, + { + "version": "1.2.0", + "planned_features": [ + "API server", + "Web interface", + "REST API", + ], + }, + { + "version": "2.0.0", + "planned_features": [ + "Full model training", + "Production deployment", + ], + }, + ] + + def get_deprecations(self) -> List[Dict]: + """Get list of deprecated features""" + return [ + { + "feature": "old_animation_api", + "version": "0.9.0", + "replacement": "new_animation_api", + "removal_version": "1.2.0", + } + ] diff --git a/src/knowledge/web_updater.py b/src/knowledge/web_updater.py new file mode 100644 index 0000000000000000000000000000000000000000..d1364c5ee49366efabc29cb6c10a370026b7b8e3 --- /dev/null +++ b/src/knowledge/web_updater.py @@ -0,0 +1,154 @@ +"""Web Updater - Update knowledge from web sources""" + +import re +import time +import hashlib +from pathlib import Path +from typing import Optional, List, Dict +from dataclasses import dataclass +from datetime import datetime + +import requests +from bs4 import BeautifulSoup + + +@dataclass +class WebSource: + """Web source configuration""" + + name: str + url: str + selector: str = "article" + update_interval: int = 3600 + + +class WebUpdater: + """Update knowledge from web sources""" + + DEFAULT_SOURCES = [ + WebSource( + name="python_docs", + url="https://docs.python.org/3/", + selector="main", + ), + WebSource( + name="javascript_docs", + url="https://developer.mozilla.org/en-US/docs/Web/JavaScript", + selector="article", + ), + ] + + def __init__(self, cache_dir: Optional[str] = None): + if cache_dir: + self.cache_dir = Path(cache_dir) + else: + self.cache_dir = Path.home() / ".burme_coder" / "cache" + + self.cache_dir.mkdir(parents=True, exist_ok=True) + self.last_fetch: Dict[str, datetime] = {} + + def fetch_content(self, source: WebSource) -> Optional[str]: + """Fetch content from a web source""" + cache_file = self.cache_dir / f"{source.name}.html" + + if self._is_cache_valid(cache_file): + return cache_file.read_text(encoding="utf-8") + + try: + response = requests.get( + source.url, timeout=30, headers={"User-Agent": "Burme-Coder/1.0"} + ) + response.raise_for_status() + + soup = BeautifulSoup(response.text, "lxml") + content_tag = soup.select_one(source.selector) + + if content_tag: + text = self._clean_text(content_tag.get_text()) + cache_file.write_text(text, encoding="utf-8") + self.last_fetch[source.name] = datetime.now() + return text + + except requests.RequestException as e: + print(f"Error fetching {source.name}: {e}") + + return None + + def _is_cache_valid(self, cache_file: Path, max_age: int = 3600) -> bool: + """Check if cache file is still valid""" + if not cache_file.exists(): + return False + + mtime = datetime.fromtimestamp(cache_file.stat().st_mtime) + age = (datetime.now() - mtime).total_seconds() + + return age < max_age + + def _clean_text(self, text: str) -> str: + """Clean and format text content""" + text = re.sub(r"\n{3,}", "\n\n", text) + text = re.sub(r" {2,}", " ", text) + return text.strip() + + def fetch_all(self) -> Dict[str, str]: + """Fetch content from all configured sources""" + results = {} + + for source in self.DEFAULT_SOURCES: + content = self.fetch_content(source) + if content: + results[source.name] = content + + return results + + def update_markdown_files( + self, output_dir: Path, force: bool = False + ) -> List[str]: + """Update markdown files from web sources""" + output_dir.mkdir(parents=True, exist_ok=True) + updated_files = [] + + for source in self.DEFAULT_SOURCES: + content = self.fetch_content(source) + + if content: + md_file = output_dir / f"{source.name}.md" + + if md_file.exists() and not force: + if self._content_changed(md_file, content): + md_file.write_text(content, encoding="utf-8") + updated_files.append(md_file.name) + else: + md_file.write_text(content, encoding="utf-8") + updated_files.append(md_file.name) + + return updated_files + + def _content_changed(self, file: Path, new_content: str) -> bool: + """Check if content has changed""" + old_content = file.read_text(encoding="utf-8") + old_hash = hashlib.md5(old_content.encode()).hexdigest() + new_hash = hashlib.md5(new_content.encode()).hexdigest() + return old_hash != new_hash + + def scrape_url(self, url: str, selectors: List[str]) -> Optional[str]: + """Scrape specific content from a URL""" + try: + response = requests.get(url, timeout=30) + response.raise_for_status() + + soup = BeautifulSoup(response.text, "lxml") + + for selector in selectors: + element = soup.select_one(selector) + if element: + return self._clean_text(element.get_text()) + + except requests.RequestException as e: + print(f"Error scraping {url}: {e}") + + return None + + def get_last_fetch_time(self, source_name: str) -> Optional[datetime]: + """Get the last fetch time for a source""" + return self.last_fetch.get(source_name) diff --git a/src/ui/__init__.py b/src/ui/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e04e8a20fd56305aef93bd18bf3bce8be6ba1389 --- /dev/null +++ b/src/ui/__init__.py @@ -0,0 +1,7 @@ +"""UI module - Colors, Layout, and Thanking System""" + +from . import colors +from . import layout +from . import thanking + +__all__ = ["colors", "layout", "thanking"] diff --git a/src/ui/colors.py b/src/ui/colors.py new file mode 100644 index 0000000000000000000000000000000000000000..b3e40d19ad14e8bbb61ee74057b3487b96997685 --- /dev/null +++ b/src/ui/colors.py @@ -0,0 +1,195 @@ +"""ANSI Color Codes for Terminal Output""" + +from enum import Enum +from typing import Optional + + +class Colors(Enum): + """Standard ANSI color codes""" + + RESET = "\033[0m" + BOLD = "\033[1m" + DIM = "\033[2m" + ITALIC = "\033[3m" + UNDERLINE = "\033[4m" + + BLACK = "\033[30m" + RED = "\033[31m" + GREEN = "\033[32m" + YELLOW = "\033[33m" + BLUE = "\033[34m" + MAGENTA = "\033[35m" + CYAN = "\033[36m" + WHITE = "\033[37m" + + BG_BLACK = "\033[40m" + BG_RED = "\033[41m" + BG_GREEN = "\033[42m" + BG_YELLOW = "\033[43m" + BG_BLUE = "\033[44m" + BG_MAGENTA = "\033[45m" + BG_CYAN = "\033[46m" + BG_WHITE = "\033[47m" + + BRIGHT_BLACK = "\033[90m" + BRIGHT_RED = "\033[91m" + BRIGHT_GREEN = "\033[92m" + BRIGHT_YELLOW = "\033[93m" + BRIGHT_BLUE = "\033[94m" + BRIGHT_MAGENTA = "\033[95m" + BRIGHT_CYAN = "\033[96m" + BRIGHT_WHITE = "\033[97m" + + +class ColorStr: + """String with color formatting""" + + def __init__(self, text: str, color: Optional[str] = None): + self.text = text + self.color = color or "" + + def __str__(self) -> str: + if self.color: + return f"{self.color}{self.text}{Colors.RESET.value}" + return self.text + + def __repr__(self) -> str: + return f"ColorStr({self.text!r}, {self.color!r})" + + +def colorize(text: str, *styles: str) -> str: + """Add color/styling to text""" + style_codes = [] + for style in styles: + style = style.upper().replace("_", "-") + try: + style_codes.append(getattr(Colors, style).value) + except AttributeError: + pass + + return "".join(style_codes) + text + Colors.RESET.value + + +def red(text: str) -> str: + """Red colored text""" + return colorize(text, "RED") + + +def green(text: str) -> str: + """Green colored text""" + return colorize(text, "GREEN") + + +def yellow(text: str) -> str: + """Yellow colored text""" + return colorize(text, "YELLOW") + + +def blue(text: str) -> str: + """Blue colored text""" + return colorize(text, "BLUE") + + +def magenta(text: str) -> str: + """Magenta colored text""" + return colorize(text, "MAGENTA") + + +def cyan(text: str) -> str: + """Cyan colored text""" + return colorize(text, "CYAN") + + +def bold(text: str) -> str: + """Bold text""" + return colorize(text, "BOLD") + + +def dim(text: str) -> str: + """Dim text""" + return colorize(text, "DIM") + + +def error(text: str) -> str: + """Error styled text (red bold)""" + return colorize(text, "BOLD", "RED") + + +def success(text: str) -> str: + """Success styled text (green bold)""" + return colorize(text, "BOLD", "GREEN") + + +def warning(text: str) -> str: + """Warning styled text (yellow)""" + return colorize(text, "YELLOW") + + +def info(text: str) -> str: + """Info styled text (cyan)""" + return colorize(text, "CYAN") + + +def code(text: str) -> str: + """Code styled text""" + return colorize(text, "DIM", "CYAN") + + +def header(text: str) -> str: + """Header styled text""" + return colorize(text, "BOLD", "CYAN") + + +def prompt(text: str) -> str: + """Prompt styled text (green)""" + return colorize(text, "BOLD", "GREEN") + + +def clear_line(): + """Clear current line in terminal""" + print("\033[2K\r", end="") + + +def move.cursor_up(lines: int = 1): + """Move cursor up""" + print(f"\033[{lines}A", end="") + + +def move_cursor_down(lines: int = 1): + """Move cursor down""" + print(f"\033[{lines}B", end="") + + +def move_cursor_right(cols: int = 1): + """Move cursor right""" + print(f"\033[{cols}C", end="") + + +def move_cursor_left(cols: int = 1): + """Move cursor left""" + print(f"\033[{cols}D", end="") + + +def save_cursor_position(): + """Save cursor position""" + print("\033[s", end="") + + +def restore_cursor_position(): + """Restore cursor position""" + print("\033[u", end="") + + +def clear_screen(): + """Clear entire screen""" + print("\033[2J", end="") + + +def hide_cursor(): + """Hide cursor""" + print("\033[?25l", end="") + + +def show_cursor(): + """Show cursor""" + print("\033[?25h", end="") diff --git a/src/ui/feedback.py b/src/ui/feedback.py new file mode 100644 index 0000000000000000000000000000000000000000..d624b98f97c6c9257d4a0a49f285cd42f986c3be --- /dev/null +++ b/src/ui/feedback.py @@ -0,0 +1,73 @@ +"""User Feedback Handler""" + +import time +from typing import Optional, Dict +from enum import Enum + + +class FeedbackType(Enum): + """Types of user feedback""" + + POSITIVE = "positive" + NEGATIVE = "negative" + NEUTRAL = "neutral" + + +class FeedbackHandler: + """Handle user feedback""" + + def __init__(self): + self.feedback_history: list[Dict] = [] + + def collect_feedback( + self, response_id: str, helpful: bool, comment: Optional[str] = None + ): + """Collect user feedback""" + feedback = { + "response_id": response_id, + "helpful": helpful, + "comment": comment, + "timestamp": time.time(), + } + self.feedback_history.append(feedback) + return feedback + + def get_average_rating(self) -> float: + """Calculate average feedback rating""" + if not self.feedback_history: + return 0.0 + + positive = sum(1 for f in self.feedback_history if f["helpful"]) + return positive / len(self.feedback_history) + + def show_feedback_prompt(self): + """Show feedback prompt""" + print("\n[bold cyan]Was this response helpful?[/bold cyan]") + print(" [green]1.[/green] Yes ๐Ÿ‘") + print(" [red]2.[/red] No ๐Ÿ‘Ž") + print(" [yellow]3.[/yellow] Skip โญ๏ธ") + + def process_quick_feedback(self, rating: int) -> Dict: + """Process quick feedback""" + feedback_map = { + 1: (True, "positive"), + 2: (False, "negative"), + 3: (None, "neutral"), + } + + helpful, ftype = feedback_map.get(rating, (None, "neutral")) + + if helpful is not None: + return self.collect_feedback( + f"response_{int(time.time())}", helpful=helpful + ) + + return {"type": "skipped"} + + +def quick_feedback_prompt(): + """Quick feedback prompt""" + print("\n๐Ÿ“Š Quick Feedback:") + print(" ๐Ÿ‘ This helped!") + print(" ๐Ÿ‘Ž Needs improvement") + print(" โญ๏ธ Skip") diff --git a/src/ui/layout.py b/src/ui/layout.py new file mode 100644 index 0000000000000000000000000000000000000000..6bdb2bdb918b8d7dbed0944a1f06c02e3ac92b2a --- /dev/null +++ b/src/ui/layout.py @@ -0,0 +1,206 @@ +"""Terminal Layout Builder""" + +from typing import Optional, List, Dict +from dataclasses import dataclass + + +@dataclass +class BoxStyle: + """Box drawing characters""" + + TOP_LEFT = "โ”Œ" + TOP_RIGHT = "โ”" + BOTTOM_LEFT = "โ””" + BOTTOM_RIGHT = "โ”˜" + HORIZONTAL = "โ”€" + VERTICAL = "โ”‚" + + +class TerminalBox: + """Draw boxes in terminal""" + + def __init__( + self, + width: int = 60, + height: int = 10, + title: Optional[str] = None, + style: Optional[BoxStyle] = None, + ): + self.width = width + self.height = height + self.title = title + self.style = style or BoxStyle() + self.content: List[str] = [] + + def set_content(self, lines: List[str]): + """Set box content""" + self.content = lines[: self.height - 2] + + def render(self) -> str: + """Render the box""" + result = [] + + top_line = ( + f"{self.style.TOP_LEFT}" + + f"{self.style.HORIZONTAL * (self.width - 2)}" + + f"{self.style.TOP_RIGHT}" + ) + result.append(top_line) + + if self.title: + title_line = f"{self.style.VERTICAL} {self.title.center(self.width - 4)} {self.style.VERTICAL}" + result.append(title_line) + result.append( + f"{self.style.VERTICAL} {'โ”€' * (self.width - 4)} {self.style.VERTICAL}" + ) + + for line in self.content: + padding = self.width - len(line) - 4 + result.append( + f"{self.style.VERTICAL} {line}{' ' * max(0, padding)} {self.style.VERTICAL}" + ) + + for _ in range(max(0, self.height - len(self.content) - (3 if self.title else 2))): + result.append( + f"{self.style.VERTICAL}{' ' * (self.width - 2)}{self.style.VERTICAL}" + ) + + bottom_line = ( + f"{self.style.BOTTOM_LEFT}" + + f"{self.style.HORIZONTAL * (self.width - 2)}" + + f"{self.style.BOTTOM_RIGHT}" + ) + result.append(bottom_line) + + return "\n".join(result) + + +class ChatboxLayout: + """Layout for chat interface""" + + def __init__(self, width: int = 80): + self.width = width + self.max_history = 50 + self.conversation: List[Dict[str, str]] = [] + + def add_user_message(self, message: str): + """Add user message to conversation""" + self.conversation.append({"role": "user", "content": message}) + if len(self.conversation) > self.max_history: + self.conversation = self.conversation[-self.max_history :] + + def add_agent_message(self, message: str): + """Add agent message to conversation""" + self.conversation.append({"role": "agent", "content": message}) + if len(self.conversation) > self.max_history: + self.conversation = self.conversation[-self.max_history :] + + def render(self) -> str: + """Render the chat layout""" + lines = [] + + lines.append("=" * self.width) + lines.append(" Burme-Coder-Max Chat ".center(self.width, "=")) + lines.append("=" * self.width) + + for msg in self.conversation[-10:]: + role = msg["role"].upper() + content = msg["content"] + + if msg["role"] == "user": + lines.append(f"\n[{role}]:") + else: + lines.append(f"\n[{role}]:") + if len(content) > self.width - 4: + content = content[: self.width - 7] + "..." + + lines.append(content) + + lines.append("=" * self.width) + + return "\n".join(lines) + + +class TableLayout: + """Table layout for displaying data""" + + def __init__(self, columns: List[str], widths: Optional[List[int]] = None): + self.columns = columns + self.total_width = widths + self.rows: List[List[str]] = [] + + if widths: + self.widths = widths + else: + avail_width = 80 + col_width = avail_width // len(columns) + self.widths = [col_width] * len(columns) + + def add_row(self, values: List[str]): + """Add a row of data""" + self.rows.append(values) + + def render(self) -> str: + """Render the table""" + lines = [] + + header_line = "โ”‚".join( + f" {col.ljust(w)} " for col, w in zip(self.columns, self.widths) + ) + separator = "โ”ผ".join("โ”€" * (w + 2) for w in self.widths) + + lines.append(header_line) + lines.append(separator) + + for row in self.rows: + row_line = "โ”‚".join( + f" {val.ljust(w)} " for val, w in zip(row, self.widths) + ) + lines.append(row_line) + + return "\n".join(lines) + + +class Panel: + """Simple panel for grouping content""" + + def __init__( + self, + content: str, + title: Optional[str] = None, + width: int = 60, + border: str = "โ”€", + ): + self.content = content + self.title = title + self.width = width + self.border = border + + def render(self) -> str: + """Render the panel""" + lines = [self.border * self.width] + + if self.title: + title_str = f" {self.title} " + padding = self.width - len(title_str) + lines.append(title_str + self.border * padding) + lines.append(self.border * self.width) + + for line in self.content.split("\n"): + padding = self.width - len(line) - 2 + lines.append(f" {line}{' ' * max(0, padding)} ") + + lines.append(self.border * self.width) + + return "\n".join(lines) + + +def divider(char: str = "โ”€", width: int = 80) -> str: + """Create a horizontal divider""" + return char * width + + +def spacer(lines: int = 1): + """Print blank lines""" + for _ in range(lines): + print() diff --git a/src/ui/thanking/__init__.py b/src/ui/thanking/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..072eba3de5c5ccec00c8ced29d4da39848e02084 --- /dev/null +++ b/src/ui/thanking/__init__.py @@ -0,0 +1,7 @@ +"""Thanking module initialization""" + +from .thank_you import ThankYou +from .appreciation import Appreciation +from .credit_display import CreditDisplay + +__all__ = ["ThankYou", "Appreciation", "CreditDisplay"] diff --git a/src/ui/thanking/appreciation.py b/src/ui/thanking/appreciation.py new file mode 100644 index 0000000000000000000000000000000000000000..b8d8c384e8e1debc4046b5fce15b0eaca39f0ad7 --- /dev/null +++ b/src/ui/thanking/appreciation.py @@ -0,0 +1,100 @@ +"""Detailed Appreciation - Show detailed thanks and appreciation""" + +import sys +import time +from typing import Optional, List + + +class Appreciation: + """Detailed appreciation display""" + + APPRECIATION_MESSAGES = [ + { + "title": "Developer Appreciation", + "message": "Thank you for being an amazing developer!", + "details": [ + "Your code inspires others", + "Your questions help the community grow", + "Your learning journey motivates us", + ], + }, + { + "title": "Learning Partner", + "message": "Thank you for learning with us!", + "details": [ + "Every question makes us better", + "Your curiosity drives innovation", + "Together we grow stronger", + ], + }, + ] + + @classmethod + def show(cls, topic: Optional[str] = None): + """Show detailed appreciation""" + print("\n" + "=" * 50) + print(" ๐Ÿ™ APPRECIATION ๐Ÿ™ ".center(50)) + print("=" * 50) + + if topic: + print(f"\nThank you for asking about: [cyan]{topic}[/cyan]\n") + else: + print() + + for msg in cls.APPRECIATION_MESSAGES[:1]: + print(f"[bold]{msg['title']}[/bold]") + print(f"[yellow]{msg['message']}[/yellow]\n") + + if "details" in msg: + print("[dim]Special thanks for:[/dim]") + for detail in msg["details"]: + print(f" โœฆ {detail}") + + print() + print("=" * 50) + print() + + @classmethod + def show_banner(cls, name: str = "Developer"): + """Show appreciation banner""" + banner = f""" +โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•— +โ•‘ โ•‘ +โ•‘ ๐Ÿ™ Thank You, {name}! ๐Ÿ™ โ•‘ +โ•‘ โ•‘ +โ•‘ Your contribution matters to us! โ•‘ +โ•‘ Keep coding and never stop learning! โ•‘ +โ•‘ โ•‘ +โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• + """ + print(banner) + + @classmethod + def show_stacked(cls, topics: List[str]): + """Show stacked appreciation for multiple topics""" + print("\n" + "โ”€" * 40) + print(" ๐Ÿ“š Multiple Topic Appreciation ๐Ÿ“š ".center(40)) + print("โ”€" * 40 + "\n") + + for i, topic in enumerate(topics, 1): + print(f"{i}. ๐Ÿ™ Thank you for asking about: [cyan]{topic}[/cyan]") + + print("\n" + "โ”€" * 40) + print("[green]Your questions are valuable to us![/green]") + print("โ”€" * 40 + "\n") + + +def show_custom_appreciation(title: str, message: str, badges: List[str] = None): + """Show custom appreciation with badges""" + print("\n" + "โ•" * 50) + print(f" ๐Ÿ† {title} ๐Ÿ† ".center(50)) + print("โ•" * 50 + "\n") + + print(f"[bold]{message}[/bold]\n") + + if badges: + print("Your achievements:") + for badge in badges: + print(f" โญ {badge}") + + print("\n" + "โ•" * 50 + "\n") diff --git a/src/ui/thanking/credit_display.py b/src/ui/thanking/credit_display.py new file mode 100644 index 0000000000000000000000000000000000000000..1813c30b1dfb222eca8d59861172d61bf9b48287 --- /dev/null +++ b/src/ui/thanking/credit_display.py @@ -0,0 +1,103 @@ +"""Credit Display - Show credits and attribution""" + +from typing import List, Dict + + +class CreditDisplay: + """Display credits and attribution""" + + CREDITS = { + "core_developer": {"name": "amkyawdev", "role": "Lead Developer"}, + "contributors": [ + {"name": "Open Source Community", "contribution": "Feedback & Suggestions"}, + ], + "technologies": [ + "Python", + "Click", + "Rich", + "HuggingFace Datasets", + "BeautifulSoup", + ], + } + + ACKNOWLEDGMENTS = [ + "Thanks to all contributors who made this project possible", + "Special thanks to the Myanmar developer community", + "Built with โค๏ธ for the developer community", + ] + + @classmethod + def show(cls): + """Display credits""" + print("\n" + "=" * 50) + print(" ๐Ÿ“œ CREDITS ๐Ÿ“œ ".center(50)) + print("=" * 50 + "\n") + + print("[bold]Lead Developer:[/bold]") + core = cls.CREDITS["core_developer"] + print(f" ๐Ÿ‘จโ€๐Ÿ’ป {core['name']} - {core['role']}\n") + + print("[bold]Contributors:[/bold]") + for contributor in cls.CREDITS["contributors"]: + print(f" ๐Ÿค {contributor['name']} - {contributor['contribution']}") + + print("\n[bold]Technologies Used:[/bold]") + for tech in cls.CREDITS["technologies"]: + print(f" โš™๏ธ {tech}") + + print("\n[bold]Acknowledgments:[/bold]") + for ack in cls.ACKNOWLEDGMENTS: + print(f" ๐Ÿ™ {ack}") + + print("\n" + "=" * 50) + + @classmethod + def show_simple(cls): + """Show simple credits""" + print("\n๐Ÿ“œ Credits: amkyawdev") + print("๐Ÿ“š Technologies: Python, Click, Rich\n") + + @classmethod + def show_verbose(cls): + """Show verbose credits with all details""" + print("\n" + "โ•" * 60) + print(" CREDITS & ATTRIBUTION ".center(60, "โ”€")) + print("โ•" * 60) + + print("\n[cyan]Project:[/cyan] Burme-Coder-Max") + print("[cyan]Version:[/cyan] 1.0.0") + print("[cyan]Author:[/cyan] amkyawdev") + + print("\n[yellow]Core Team:[/yellow]") + for key, dev in cls.CREDITS.items(): + if isinstance(dev, dict): + print(f" {dev['name']} ({dev['role']})") + + print("\n[yellow]Contributors:[/yellow]") + for c in cls.CREDITS["contributors"]: + print(f" {c['name']} - {c['contribution']}") + + print("\n[yellow]Built With:[/yellow]") + for tech in cls.CREDITS["technologies"]: + print(f" โ€ข {tech}") + + print("\n[yellow]Acknowledgments:[/yellow]") + for ack in cls.ACKNOWLEDGMENTS: + print(f" โ™ฅ {ack}") + + print("\n" + "โ•" * 60) + + @classmethod + def show_with License(cls): + """Show credits with license info""" + cls.show() + print("\n[bold]License:[/bold] MIT License") + print("Feel free to use, modify, and distribute!") + print() + + +def show_developer_credit(name: str, role: str = "Developer"): + """Show credit for a specific developer""" + print(f"\n๐Ÿ‘จโ€๐Ÿ’ป {name}") + print(f" Role: {role}") + print() diff --git a/src/ui/thanking/thank_you.py b/src/ui/thanking/thank_you.py new file mode 100644 index 0000000000000000000000000000000000000000..d9e9b49d06087f977648b636968220d71c4d9774 --- /dev/null +++ b/src/ui/thanking/thank_you.py @@ -0,0 +1,68 @@ +"""Basic Thank You - Show gratitude to user""" + +import sys +import time +import random +from typing import Optional + +from ..colors import Colors + + +class ThankYou: + """Simple thank you display""" + + THANK_MESSAGES = [ + "๐Ÿ™ Thank You for using Burme-Coder-Max! ๐Ÿ™", + แ€…แ€€แ€ฌแ€ธแ€™แ€พแ€”แ€บแ€™แ€ปแ€ฌแ€ธแ€”แ€พแ€„.แ‹ Thank you! ๐Ÿ™", + " ๐Ÿ™ Thank you! Your support means a lot! ๐Ÿ™", + "๐Ÿ™ Gratias! Thanks for being awesome! ๐Ÿ™", + "๐Ÿ™ แ€€แ€ปแ€ฑแ€ธแ€‡แ€ฐแ€ธแ€แ€„,๏ฟฝแ€™.แ€บแ€•แ€ซแ€แ€š,แ€บ! ๐Ÿ™", + ] + + @classmethod + def show(cls, message: Optional[str] = None): + """Display thank you message""" + if message: + thank_text = f"๐Ÿ™ {message} ๐Ÿ™" + else: + thank_text = random.choice(cls.THANK_MESSAGES) + + print() + print(thank_text) + print() + + @classmethod + def show_animation(cls): + """Show animated thank you""" + print() + print("\033[96m๐Ÿ™\033[0m", end="", flush=True) + time.sleep(0.1) + print("\033[96m ๐Ÿ’ซ\033[0m", end="", flush=True) + time.sleep(0.1) + print("\033[96m โœจ\033[0m", flush=True) + + print(random.choice(cls.THANK_MESSAGES)) + + print("\033[96m โœจ\033[0m", end="", flush=True) + time.sleep(0.1) + print("\033[96m ๐Ÿ’ซ\033[0m", end="", flush=True) + time.sleep(0.1) + print("\033[96m ๐Ÿ™\033[0m") + print() + + @classmethod + def show_with_emoji(cls, emoji: str = "๐Ÿ™"): + """Show thank you with custom emoji""" + messages = [ + f"{emoji} Thank you for using Burme-Coder-Max! {emoji}", + f"{emoji} Your support is appreciated! {emoji}", + f"{emoji} Thanks for choosing Burme-Coder-Max! {emoji}", + ] + print() + print(random.choice(messages)) + print() + + +def quick_thank(): + """Quick thank you without animation""" + print("\n๐Ÿ™ แ€€แ€ปแ€ฑแ€ธแ€‡แ€ฐแ€ธแ€แ€„,๏ฟฝแ€•,แ€ซแ€แ€š,แ€บ! ๐Ÿ™\n") diff --git a/src/utils/__init__.py b/src/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..efff7aaa482f8fefd99d455a37102357e67a5e80 --- /dev/null +++ b/src/utils/__init__.py @@ -0,0 +1,7 @@ +"""Utils module - Utility functions""" + +from .file_ops import FileOps +from .markdown_parser import MarkdownParser +from .logger import Logger, get_logger + +__all__ = ["FileOps", "MarkdownParser", "Logger", "get_logger"] diff --git a/src/utils/file_ops.py b/src/utils/file_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..0a8620af6ec38b2a5dd36be26aadc2371999cbf5 --- /dev/null +++ b/src/utils/file_ops.py @@ -0,0 +1,125 @@ +"""File Operations Utility""" + +import os +import shutil +import json +from pathlib import Path +from typing import List, Optional, Dict, Any +from datetime import datetime + + +class FileOps: + """File operation utilities""" + + @staticmethod + def read_text(file_path: str, encoding: str = "utf-8") -> str: + """Read text content from file""" + with open(file_path, "r", encoding=encoding) as f: + return f.read() + + @staticmethod + def write_text(file_path: str, content: str, encoding: str = "utf-8"): + """Write text content to file""" + Path(file_path).parent.mkdir(parents=True, exist_ok=True) + with open(file_path, "w", encoding=encoding) as f: + f.write(content) + + @staticmethod + def read_json(file_path: str) -> Dict[str, Any]: + """Read JSON file""" + with open(file_path, "r", encoding="utf-8") as f: + return json.load(f) + + @staticmethod + def write_json(file_path: str, data: Dict[str, Any], indent: int = 2): + """Write JSON file""" + Path(file_path).parent.mkdir(parents=True, exist_ok=True) + with open(file_path, "w", encoding="utf-8") as f: + json.dump(data, f, indent=indent, ensure_ascii=False) + + @staticmethod + def append_jsonl(file_path: str, data: Dict[str, Any]): + """Append data as JSONL line""" + Path(file_path).parent.mkdir(parents=True, exist_ok=True) + with open(file_path, "a", encoding="utf-8") as f: + f.write(json.dumps(data, ensure_ascii=False) + "\n") + + @staticmethod + def read_jsonl(file_path: str) -> List[Dict[str, Any]]: + """Read JSONL file""" + results = [] + with open(file_path, "r", encoding="utf-8") as f: + for line in f: + if line.strip(): + results.append(json.loads(line)) + return results + + @staticmethod + def list_files(directory: str, pattern: str = "*") -> List[Path]: + """List files in directory matching pattern""" + return list(Path(directory).glob(pattern)) + + @staticmethod + def create_directory(path: str): + """Create directory if it doesn't exist""" + Path(path).mkdir(parents=True, exist_ok=True) + + @staticmethod + def delete_file(path: str): + """Delete file""" + Path(path).unlink(missing_ok=True) + + @staticmethod + def copy_file(src: str, dst: str): + """Copy file""" + Path(dst).parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(src, dst) + + @staticmethod + def move_file(src: str, dst: str): + """Move file""" + Path(dst).parent.mkdir(parents=True, exist_ok=True) + shutil.move(src, dst) + + @staticmethod + def get_file_info(path: str) -> Dict[str, Any]: + """Get file information""" + p = Path(path) + stat = p.stat() + + return { + "path": str(p.absolute()), + "name": p.name, + "size": stat.st_size, + "modified": datetime.fromtimestamp(stat.st_mtime).isoformat(), + "is_file": p.is_file(), + "is_dir": p.is_dir(), + } + + @staticmethod + def find_files(directory: str, extensions: List[str]) -> List[Path]: + """Find files with specific extensions""" + results = [] + for ext in extensions: + results.extend(Path(directory).rglob(f"*.{ext}")) + return results + + @staticmethod + def get_directory_size(path: str) -> int: + """Calculate directory size in bytes""" + total = 0 + for p in Path(path).rglob("*"): + if p.is_file(): + total += p.stat().st_size + return total + + @staticmethod + def clean_directory(path: str, keep_pattern: Optional[str] = None): + """Clean directory, optionally keeping files matching pattern""" + for item in Path(path).iterdir(): + if keep_pattern and item.match(keep_pattern): + continue + if item.is_file(): + item.unlink() + elif item.is_dir(): + shutil.rmtree(item) diff --git a/src/utils/logger.py b/src/utils/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..f37e07c0b7e3356fcec9261b913395f259082e93 --- /dev/null +++ b/src/utils/logger.py @@ -0,0 +1,131 @@ +"""Logging Utility""" + +import sys +import logging +from pathlib import Path +from typing import Optional +from datetime import datetime +from enum import Enum + + +class LogLevel(Enum): + """Log level enumeration""" + + DEBUG = logging.DEBUG + INFO = logging.INFO + WARNING = logging.WARNING + ERROR = logging.ERROR + CRITICAL = logging.CRITICAL + + +class Logger: + """Simple logging utility for Burme-Coder-Max""" + + def __init__( + self, + name: str = "burme_coder", + level: int = logging.INFO, + log_file: Optional[str] = None, + format_string: Optional[str] = None, + ): + self.logger = logging.getLogger(name) + self.logger.setLevel(level) + self.logger.handlers = [] + + if format_string is None: + format_string = "%(asctime)s | %(levelname)-8s | %(message)s" + + formatter = logging.Formatter(format_string) + + console_handler = logging.StreamHandler(sys.stdout) + console_handler.setFormatter(formatter) + self.logger.addHandler(console_handler) + + if log_file: + log_path = Path(log_file) + log_path.parent.mkdir(parents=True, exist_ok=True) + + file_handler = logging.FileHandler(log_file, encoding="utf-8") + file_handler.setFormatter(formatter) + self.logger.addHandler(file_handler) + + def debug(self, message: str): + """Log debug message""" + self.logger.debug(message) + + def info(self, message: str): + """Log info message""" + self.logger.info(message) + + def warning(self, message: str): + """Log warning message""" + self.logger.warning(message) + + def error(self, message: str): + """Log error message""" + self.logger.error(message) + + def critical(self, message: str): + """Log critical message""" + self.logger.critical(message) + + def log(self, level: int, message: str): + """Log with custom level""" + self.logger.log(level, message) + + +_default_logger: Optional[Logger] = None + + +def get_logger( + name: str = "burme_coder", + level: int = logging.INFO, + log_file: Optional[str] = None, +) -> Logger: + """Get or create a logger instance""" + global _default_logger + + if _default_logger is None or name != "burme_coder": + return Logger(name=name, level=level, log_file=log_file) + + return _default_logger + + +def setup_default_logger(level: int = logging.INFO, log_file: Optional[str] = None): + """Setup the default logger""" + global _default_logger + _default_logger = Logger(level=level, log_file=log_file) + return _default_logger + + +class LogContext: + """Context manager for logging operations""" + + def __init__(self, logger: Logger, operation: str): + self.logger = logger + self.operation = operation + self.start_time = None + + def __enter__(self): + self.start_time = datetime.now() + self.logger.info(f"Starting: {self.operation}") + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + duration = (datetime.now() - self.start_time).total_seconds() + if exc_type is None: + self.logger.info(f"Completed: {self.operation} ({duration:.2f}s)") + else: + self.logger.error(f"Failed: {self.operation} - {exc_val}") + return False + + +def log_operation(operation: str, logger: Optional[Logger] = None): + """Decorator for logging operations""" + def decorator(func): + def wrapper(*args, **kwargs): + log = logger or get_logger() + with LogContext(log, operation): + return func(*args, **kwargs) + return wrapper + return decorator diff --git a/src/utils/markdown_parser.py b/src/utils/markdown_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..22064be57cd1d867f9f61805716576a2d689af47 --- /dev/null +++ b/src/utils/markdown_parser.py @@ -0,0 +1,188 @@ +"""Markdown Parser Utilities""" + +import re +from typing import List, Dict, Optional, Tuple +from dataclasses import dataclass +from pathlib import Path + + +@dataclass +class CodeBlock: + """Represents a code block in markdown""" + + language: str + content: str + start_line: int + end_line: int + + +@dataclass +class MarkdownHeading: + """Represents a heading in markdown""" + + level: int + text: str + line: int + + +class MarkdownParser: + """Parse and process markdown files""" + + def __init__(self, content: Optional[str] = None): + self.content = content or "" + + def parse(self, content: str) -> "MarkdownParser": + """Parse content and return self""" + self.content = content + return self + + def extract_code_blocks(self) -> List[CodeBlock]: + """Extract all code blocks""" + pattern = r"```(\w*)\n([\s\S]*?)```" + blocks = [] + + for match in re.finditer(pattern, self.content): + blocks.append( + CodeBlock( + language=match.group(1), + content=match.group(2).rstrip(), + start_line=self.content[:match.start()].count("\n") + 1, + end_line=self.content[:match.end()].count("\n") + 1, + ) + ) + + return blocks + + def extract_headings(self) -> List[MarkdownHeading]: + """Extract all headings""" + pattern = r"^(#{1,6})\s+(.+)$" + headings = [] + + for i, line in enumerate(self.content.split("\n"), 1): + match = re.match(pattern, line.strip()) + if match: + headings.append( + MarkdownHeading( + level=len(match.group(1)), + text=match.group(2), + line=i, + ) + ) + + return headings + + def extract_links(self) -> List[Tuple[str, str]]: + """Extract all markdown links""" + pattern = r"\[([^\]]+)\]\(([^\)]+)\)" + return [(title, url) for title, url in re.findall(pattern, self.content)] + + def extract_images(self) -> List[Tuple[str, str]]: + """Extract all markdown images""" + pattern = r"!\[([^\]]*)\]\(([^\)]+)\)" + return [(alt, url) for alt, url in re.findall(pattern, self.content)] + + def extract_tables(self) -> List[List[List[str]]]: + """Extract all tables""" + lines = self.content.split("\n") + tables = [] + + in_table = False + current_table: List[List[str]] = [] + alignment: List[str] = [] + + for line in lines: + if re.match(r"\|.*\|$", line.strip()): + if re.match(r"\|[-:\s]+\|$", line.strip()): + alignment = [ + "left" if ":" in c and c.count(":") == 1 and c.strip().startswith(":") + else "right" if ":" in c and c.count(":") == 1 and c.strip().endswith(":") + else "center" if ":" in c and c.count(":") == 2 + else "left" + for c in line.strip().split("|")[1:-1] + ] + tables.append(current_table) + current_table = [] + in_table = False + continue + + in_table = True + row = [cell.strip() for cell in line.strip().split("|")[1:-1]] + current_table.append(row) + else: + if in_table and current_table: + tables.append(current_table) + current_table = [] + in_table = False + + if current_table: + tables.append(current_table) + + return tables + + def extract_lists(self) -> Dict[str, List[str]]: + """Extract all lists""" + ordered: List[str] = [] + unordered: List[str] = [] + + for line in self.content.split("\n"): + ordered_match = re.match(r"^\d+\.\s+(.+)$", line.strip()) + if ordered_match: + ordered.append(ordered_match.group(1)) + continue + + unordered_match = re.match(r"^[-*+]\s+(.+)$", line.strip()) + if unordered_match: + unordered.append(unordered_match.group(1)) + + return {"ordered": ordered, "unordered": unordered} + + def get_table_of_contents(self) -> List[Dict[str, Any]]: + """Get table of contents from headings""" + toc = [] + for heading in self.extract_headings(): + toc.append( + { + "level": heading.level, + "text": heading.text, + "line": heading.line, + } + ) + return toc + + def convert_to_plain_text(self) -> str: + """Strip markdown formatting for plain text""" + text = self.content + + text = re.sub(r"```[\s\S]*?```", "", text) + text = re.sub(r"`([^`]+)`", r"\1", text) + text = re.sub(r"!\[([^\]]*)\]\([^\)]+\)", r"\1", text) + text = re.sub(r"\[([^\]]+)\]\([^\)]+\)", r"\1", text) + text = re.sub(r"^#{1,6}\s+", "", text, flags=re.MULTILINE) + text = re.sub(r"\*\*([^*]+)\*\*", r"\1", text) + text = re.sub(r"\*([^*]+)\*", r"\1", text) + text = re.sub(r"__([^_]+)__", r"\1", text) + text = re.sub(r"_([^_]+)_", r"\1", text) + + return text + + def search(self, query: str, case_sensitive: bool = False) -> List[Dict[str, Any]]: + """Search for text in markdown""" + results = [] + + if not case_sensitive: + search_content = self.content.lower() + query = query.lower() + else: + search_content = self.content + + for i, line in enumerate(search_content.split("\n"), 1): + if query in line: + results.append({"line": i, "content": line.strip()}) + + return results + + @classmethod + def from_file(cls, file_path: str) -> "MarkdownParser": + """Create parser from file""" + content = Path(file_path).read_text(encoding="utf-8") + return cls(content) diff --git a/tests/test_animations.py b/tests/test_animations.py new file mode 100644 index 0000000000000000000000000000000000000000..fd0127b543b470da8f15f8034d33e6ac28a09f03 --- /dev/null +++ b/tests/test_animations.py @@ -0,0 +1,109 @@ +"""Tests for animation module""" + +import pytest +import time +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent.parent / "src")) + +from animations import ( + Spinner, + ProgressBar, + ParticleBurst, + TypingEffect, + AnimationConfig, +) + + +class TestAnimationConfig: + """Test AnimationConfig class""" + + def test_default_config(self): + config = AnimationConfig() + assert config.speed == 0.05 + assert config.color_enabled == True + + def test_custom_config(self): + config = AnimationConfig(speed=0.1, color_enabled=False) + assert config.speed == 0.1 + assert config.color_enabled == False + + def test_spinner_frames_exist(self): + assert len(AnimationConfig.SPINNER_FRAMES) > 0 + + +class TestSpinner: + """Test Spinner class""" + + def test_spinner_creation(self): + spinner = Spinner("Loading") + assert spinner.message == "Loading" + assert spinner.running == False + + def test_spinner_start_stop(self): + spinner = Spinner("Test") + spinner.start() + assert spinner.running == True + spinner.stop() + assert spinner.running == False + + def test_spinner_context(self): + with Spinner("Context") as s: + assert s.running == True + assert s.running == False + + +class TestProgressBar: + """Test ProgressBar class""" + + def test_progress_bar_creation(self): + progress = ProgressBar(total=100) + assert progress.total == 100 + assert progress.current == 0 + + def test_progress_bar_iteration(self): + items = list(range(10)) + progress = ProgressBar(iterable=items) + results = list(progress) + assert len(results) == 10 + + def test_progress_update(self): + progress = ProgressBar(total=100) + progress.update(50) + assert progress.current == 50 + + def test_progress_percent(self): + progress = ProgressBar(total=100) + progress.update(75) + assert progress.percent == 0.75 + + +class TestTypingEffect: + """Test TypingEffect class""" + + def test_typing_effect_creation(self): + effect = TypingEffect("Test text") + assert effect.text == "Test text" + + def test_typing_effect_animate(self, capsys): + effect = TypingEffect("Hi", delay=0.01) + result = effect.animate() + assert result == "Hi" + + +class TestParticleBurst: + """Test ParticleBurst class""" + + def test_particle_burst_creation(self): + burst = ParticleBurst(count=50) + assert burst.count == 50 + + def test_particle_burst_center(self): + burst = ParticleBurst(center_x=60, center_y=15) + assert burst.center_x == 60 + assert burst.center_y == 15 + + +if __name__ == "__main__": + pytest.main([__file__, "-v"]) diff --git a/tests/test_knowledge_updater.py b/tests/test_knowledge_updater.py new file mode 100644 index 0000000000000000000000000000000000000000..b0463a1ef0829eccce5434af1dff9debb0ea524b --- /dev/null +++ b/tests/test_knowledge_updater.py @@ -0,0 +1,110 @@ +"""Tests for knowledge updater module""" + +import pytest +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent.parent / "src")) + +from knowledge import ( + LocalKB, + WebUpdater, + VersionTracker, + CacheManager, +) + + +class TestLocalKB: + """Test LocalKB class""" + + def test_local_kb_creation(self): + kb = LocalKB() + assert kb.base_dir is not None + + def test_search_returns_list(self): + kb = LocalKB() + results = kb.search("python") + assert isinstance(results, list) + + def test_get_all_topics_returns_list(self): + kb = LocalKB() + topics = kb.get_all_topics() + assert isinstance(topics, list) + + +class TestWebUpdater: + """Test WebUpdater class""" + + def test_web_updater_creation(self): + updater = WebUpdater() + assert updater.cache_dir is not None + + def test_fetch_content_returns_none_for_invalid_url(self): + from knowledge.web_updater import WebSource + updater = WebUpdater() + source = WebSource(name="test", url="https://invalid.url.12345") + result = updater.fetch_content(source) + # Should return None for invalid URL + assert result is None or isinstance(result, str) + + +class TestVersionTracker: + """Test VersionTracker class""" + + def test_version_tracker_creation(self): + tracker = VersionTracker() + assert tracker.CURRENT_VERSION is not None + + def test_get_current_version(self): + tracker = VersionTracker() + version = tracker.get_current_version() + assert isinstance(version, str) + assert len(version) > 0 + + def test_get_changelog_returns_list(self): + tracker = VersionTracker() + changelog = tracker.get_changelog() + assert isinstance(changelog, list) + assert len(changelog) > 0 + + def test_is_update_available(self): + tracker = VersionTracker() + assert tracker.is_update_available("99.0.0") == True + assert tracker.is_update_available("0.1.0") == False + + def test_get_roadmap_returns_list(self): + tracker = VersionTracker() + roadmap = tracker.get_roadmap() + assert isinstance(roadmap, list) + + +class TestCacheManager: + """Test CacheManager class""" + + def test_cache_manager_creation(self): + cache = CacheManager() + assert cache.cache_dir is not None + + def test_set_and_get(self, tmp_path): + cache = CacheManager(cache_dir=str(tmp_path)) + cache.set("test_key", "test_value") + result = cache.get("test_key") + assert result == "test_value" + + def test_delete(self, tmp_path): + cache = CacheManager(cache_dir=str(tmp_path)) + cache.set("delete_key", "value") + cache.delete("delete_key") + result = cache.get("delete_key") + assert result is None + + def test_get_stats(self, tmp_path): + cache = CacheManager(cache_dir=str(tmp_path)) + stats = cache.get_stats() + assert "memory_entries" in stats + assert "disk_files" in stats + assert isinstance(stats["memory_entries"], int) + + +if __name__ == "__main__": + pytest.main([__file__, "-v"]) diff --git a/tests/test_markdown_parser.py b/tests/test_markdown_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..c8050e56da6845ba7c1b31c7bc9974f39398b6d6 --- /dev/null +++ b/tests/test_markdown_parser.py @@ -0,0 +1,149 @@ +"""Tests for markdown parser module""" + +import pytest +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent.parent / "src")) + +from utils import MarkdownParser + + +class TestMarkdownParser: + """Test MarkdownParser class""" + + def test_parser_initialization(self): + parser = MarkdownParser() + assert parser.content == "" + + def test_parse_method(self): + parser = MarkdownParser() + parser.parse("# Hello\nWorld") + assert parser.content == "# Hello\nWorld" + + def test_extract_code_blocks(self): + parser = MarkdownParser() + parser.parse( + """ +# Code Example + +```python +def hello(): + print("Hello") +``` + +More text + +```javascript +console.log("test"); +``` +""" + ) + blocks = parser.extract_code_blocks() + assert len(blocks) == 2 + assert blocks[0].language == "python" + assert blocks[1].language == "javascript" + + def test_extract_headings(self): + parser = MarkdownParser() + parser.parse( + """ +# Heading 1 +## Heading 2 +### Heading 3 +""" + ) + headings = parser.extract_headings() + assert len(headings) == 3 + assert headings[0].level == 1 + assert headings[1].level == 2 + assert headings[2].level == 3 + + def test_extract_links(self): + parser = MarkdownParser() + parser.parse( + """ +Check out [this link](https://example.com) +and [another link](https://test.com). +""" + ) + links = parser.extract_links() + assert len(links) == 2 + assert links[0] == ("this link", "https://example.com") + + def test_extract_images(self): + parser = MarkdownParser() + parser.parse("![Alt text](image.png/path)") + images = parser.extract_images() + assert len(images) == 1 + assert images[0] == ("Alt text", "image.png/path") + + def test_search(self): + parser = MarkdownParser() + parser.parse("Line 1\nPython code here\nLine 3") + results = parser.search("Python") + assert len(results) == 1 + assert results[0]["line"] == 2 + + def test_search_not_found(self): + parser = MarkdownParser() + parser.parse("No match here") + results = parser.search("missing") + assert len(results) == 0 + + def test_convert_to_plain_text(self): + parser = MarkdownParser() + parser.parse( + """ +# Title + +**bold** and *italic* + +``` +code block +``` +""" + ) + plain = parser.convert_to_plain_text() + assert "# Title" in plain + assert "bold" in plain + assert "code block" in plain + + def test_from_file_method(self, tmp_path): + md_file = tmp_path / "test.md" + md_file.write_text("# Test File\n\nContent here") + + parser = MarkdownParser.from_file(str(md_file)) + assert "# Test File" in parser.content + + def test_get_table_of_contents(self): + parser = MarkdownParser() + parser.parse( + """ +# Main Title +## Section 1 +### Subsection 1.1 +## Section 2 +""" + ) + toc = parser.get_table_of_contents() + assert len(toc) == 4 + assert toc[0]["level"] == 1 + assert toc[0]["text"] == "Main Title" + + +class TestCodeBlock: + """Test CodeBlock dataclass""" + + def test_code_block_creation(self): + from utils.markdown_parser import CodeBlock + + block = CodeBlock( + language="python", content="print('hello')", start_line=1, end_line=3 + ) + assert block.language == "python" + assert block.content == "print('hello')" + + +if __name__ == "__main__": + pytest.main([__file__, "-v"]) diff --git a/tests/test_thanking.py b/tests/test_thanking.py new file mode 100644 index 0000000000000000000000000000000000000000..8ea8917d6241f2b802ef5bc71e93089a4c8fc310 --- /dev/null +++ b/tests/test_thanking.py @@ -0,0 +1,74 @@ +"""Tests for thanking module""" + +import pytest +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).parent.parent / "src")) + +from ui.thanking import ( + ThankYou, + Appreciation, + CreditDisplay, + quick_thank, + show_custom_appreciation, +) + + +class TestThankYou: + """Test ThankYou class""" + + def test_show_method_exists(self): + assert hasattr(ThankYou, "show") + + def test_show_animation_method_exists(self): + assert hasattr(ThankYou, "show_animation") + + def test_thank_messages_not_empty(self): + assert len(ThankYou.THANK_MESSAGES) > 0 + + +class TestAppreciation: + """Test Appreciation class""" + + def test_show_method_exists(self): + assert hasattr(Appreciation, "show") + + def test_show_banner_method_exists(self): + assert hasattr(Appreciation, "show_banner") + + def test_appreciation_messages_not_empty(self): + assert len(Appreciation.APPRECIATION_MESSAGES) > 0 + + +class TestCreditDisplay: + """Test CreditDisplay class""" + + def test_show_method_exists(self): + assert hasattr(CreditDisplay, "show") + + def test_show_simple_method_exists(self): + assert hasattr(CreditDisplay, "show_simple") + + def test_credits_structure(self): + assert "core_developer" in CreditDisplay.CREDITS + assert "technologies" in CreditDisplay.CREDITS + + def test_core_developer_info(self): + core = CreditDisplay.CREDITS["core_developer"] + assert "name" in core + assert "role" in core + + +class TestThankingFunctions: + """Test additional thanking functions""" + + def test_quick_thank_exists(self): + assert callable(quick_thank) + + def test_show_custom_appreciation_exists(self): + assert callable(show_custom_appreciation) + + +if __name__ == "__main__": + pytest.main([__file__, "-v"])