Upload folder using huggingface_hub
Browse files- .github/workflows/ci.yml +119 -0
- docs/api_reference.md +394 -0
- scripts/automation.py +386 -0
- scripts/create_github_workflows.py +145 -0
- scripts/split_dataset.py +205 -0
- scripts/validate_dataset.py +249 -0
- src/data_processing.py +323 -0
- tests/test_qa.py +352 -0
.github/workflows/ci.yml
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: CI/CD Pipeline
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches: [main, develop]
|
| 6 |
+
pull_request:
|
| 7 |
+
branches: [main]
|
| 8 |
+
release:
|
| 9 |
+
types: [published]
|
| 10 |
+
|
| 11 |
+
jobs:
|
| 12 |
+
lint:
|
| 13 |
+
runs-on: ubuntu-latest
|
| 14 |
+
steps:
|
| 15 |
+
- uses: actions/checkout@v4
|
| 16 |
+
|
| 17 |
+
- name: Set up Python
|
| 18 |
+
uses: actions/setup-python@v5
|
| 19 |
+
with:
|
| 20 |
+
python-version: '3.10'
|
| 21 |
+
|
| 22 |
+
- name: Install dependencies
|
| 23 |
+
run: |
|
| 24 |
+
python -m pip install --upgrade pip
|
| 25 |
+
pip install -e ".[dev]"
|
| 26 |
+
|
| 27 |
+
- name: Check syntax
|
| 28 |
+
run: python -m py_compile $(find src -name "*.py")
|
| 29 |
+
|
| 30 |
+
- name: Run linters
|
| 31 |
+
run: |
|
| 32 |
+
pip install black mypy ruff
|
| 33 |
+
black --check src/ tests/
|
| 34 |
+
ruff check src/
|
| 35 |
+
|
| 36 |
+
test:
|
| 37 |
+
runs-on: ubuntu-latest
|
| 38 |
+
strategy:
|
| 39 |
+
matrix:
|
| 40 |
+
python-version: ['3.8', '3.9', '3.10', '3.11']
|
| 41 |
+
steps:
|
| 42 |
+
- uses: actions/checkout@v4
|
| 43 |
+
|
| 44 |
+
- name: Set up Python ${{ matrix.python-version }}
|
| 45 |
+
uses: actions/setup-python@v5
|
| 46 |
+
with:
|
| 47 |
+
python-version: ${{ matrix.python-version }}
|
| 48 |
+
|
| 49 |
+
- name: Install dependencies
|
| 50 |
+
run: |
|
| 51 |
+
python -m pip install --upgrade pip
|
| 52 |
+
pip install -e ".[dev]"
|
| 53 |
+
|
| 54 |
+
- name: Run tests
|
| 55 |
+
run: pytest tests/ -v --tb=short
|
| 56 |
+
|
| 57 |
+
quality:
|
| 58 |
+
runs-on: ubuntu-latest
|
| 59 |
+
steps:
|
| 60 |
+
- uses: actions/checkout@v4
|
| 61 |
+
|
| 62 |
+
- name: Set up Python
|
| 63 |
+
uses: actions/setup-python@v5
|
| 64 |
+
with:
|
| 65 |
+
python-version: '3.10'
|
| 66 |
+
|
| 67 |
+
- name: Install dependencies
|
| 68 |
+
run: pip install -e ".[dev]"
|
| 69 |
+
|
| 70 |
+
- name: Run QA tests
|
| 71 |
+
run: python scripts/automation.py quality
|
| 72 |
+
|
| 73 |
+
- name: Check documentation
|
| 74 |
+
run: |
|
| 75 |
+
python scripts/automation.py validate-data
|
| 76 |
+
|
| 77 |
+
deploy:
|
| 78 |
+
needs: [lint, test, quality]
|
| 79 |
+
runs-on: ubuntu-latest
|
| 80 |
+
if: github.event_name == 'release'
|
| 81 |
+
steps:
|
| 82 |
+
- uses: actions/checkout@v4
|
| 83 |
+
|
| 84 |
+
- name: Set up Python
|
| 85 |
+
uses: actions/setup-python@v5
|
| 86 |
+
with:
|
| 87 |
+
python-version: '3.10'
|
| 88 |
+
|
| 89 |
+
- name: Install build tools
|
| 90 |
+
run: pip install build twine
|
| 91 |
+
|
| 92 |
+
- name: Build package
|
| 93 |
+
run: python -m build
|
| 94 |
+
|
| 95 |
+
- name: Upload to PyRI
|
| 96 |
+
env:
|
| 97 |
+
PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
|
| 98 |
+
run: |
|
| 99 |
+
twine upload dist/* --token $PYPI_TOKEN
|
| 100 |
+
|
| 101 |
+
huggingface:
|
| 102 |
+
needs: [lint, test]
|
| 103 |
+
runs-on: ubuntu-latest
|
| 104 |
+
if: github.event_name == 'release'
|
| 105 |
+
steps:
|
| 106 |
+
- uses: actions/checkout@v4
|
| 107 |
+
|
| 108 |
+
- name: Set up Python
|
| 109 |
+
uses: actions/setup-python@v5
|
| 110 |
+
with:
|
| 111 |
+
python-version: '3.10'
|
| 112 |
+
|
| 113 |
+
- name: Install huggingface_hub
|
| 114 |
+
run: pip install huggingface_hub
|
| 115 |
+
|
| 116 |
+
- name: Upload to HuggingFace
|
| 117 |
+
env:
|
| 118 |
+
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
| 119 |
+
run: python scripts/automation.py deploy --token $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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# API Documentation - Burme-Coder-Max
|
| 2 |
+
|
| 3 |
+
## Overview
|
| 4 |
+
|
| 5 |
+
**burme-coder-max** is a Myanmar AI coding agent that provides programming assistance in Burmese language with code examples.
|
| 6 |
+
|
| 7 |
+
---
|
| 8 |
+
|
| 9 |
+
## Core Module API
|
| 10 |
+
|
| 11 |
+
### CoderAgent
|
| 12 |
+
|
| 13 |
+
Main AI agent for generating coding responses.
|
| 14 |
+
|
| 15 |
+
```python
|
| 16 |
+
from core.agent import CoderAgent
|
| 17 |
+
|
| 18 |
+
agent = CoderAgent(
|
| 19 |
+
model: str = "gpt-4", # AI model to use
|
| 20 |
+
temperature: float = 0.7, # Response creativity
|
| 21 |
+
max_tokens: int = 2048, # Max response length
|
| 22 |
+
knowledge_dir: Optional[str] = None # Knowledge base directory
|
| 23 |
+
)
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
#### Methods
|
| 27 |
+
|
| 28 |
+
| Method | Description | Returns |
|
| 29 |
+
|--------|-------------|---------|
|
| 30 |
+
| `generate_response(instruction, context)` | Generate code response | `Dict` with session_id, response, timestamp |
|
| 31 |
+
| `set_system_prompt(prompt)` | Set custom system prompt | `None` |
|
| 32 |
+
| `get_trajectory()` | Get conversation for training | `Dict` |
|
| 33 |
+
| `save_trajectory(path)` | Save trajectory to file | `None` |
|
| 34 |
+
| `reset()` | Reset agent state | `None` |
|
| 35 |
+
|
| 36 |
+
#### Response Format
|
| 37 |
+
|
| 38 |
+
```python
|
| 39 |
+
{
|
| 40 |
+
"session_id": str,
|
| 41 |
+
"instruction": str,
|
| 42 |
+
"response": str,
|
| 43 |
+
"timestamp": float,
|
| 44 |
+
"model": str
|
| 45 |
+
}
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
---
|
| 49 |
+
|
| 50 |
+
### CodeExecutor
|
| 51 |
+
|
| 52 |
+
Execute code in various languages.
|
| 53 |
+
|
| 54 |
+
```python
|
| 55 |
+
from core.executor import CodeExecutor
|
| 56 |
+
|
| 57 |
+
executor = CodeExecutor(
|
| 58 |
+
timeout: int = 30, # Execution timeout in seconds
|
| 59 |
+
sandbox: bool = True # Enable sandbox mode
|
| 60 |
+
)
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
#### Methods
|
| 64 |
+
|
| 65 |
+
| Method | Description | Returns |
|
| 66 |
+
|--------|-------------|---------|
|
| 67 |
+
| `execute(code, language)` | Execute code | `ExecutionResult` |
|
| 68 |
+
| `validate_syntax(code, language)` | Check syntax | `Tuple[bool, Optional[str]]` |
|
| 69 |
+
|
| 70 |
+
#### ExecutionResult
|
| 71 |
+
|
| 72 |
+
```python
|
| 73 |
+
@dataclass
|
| 74 |
+
class ExecutionResult:
|
| 75 |
+
success: bool # Execution success
|
| 76 |
+
output: str # Execution output
|
| 77 |
+
error: Optional[str] # Error message
|
| 78 |
+
execution_time: float # Time taken
|
| 79 |
+
```
|
| 80 |
+
|
| 81 |
+
---
|
| 82 |
+
|
| 83 |
+
### ResponseValidator
|
| 84 |
+
|
| 85 |
+
Validate AI generated responses.
|
| 86 |
+
|
| 87 |
+
```python
|
| 88 |
+
from core.validator import ResponseValidator
|
| 89 |
+
|
| 90 |
+
validator = ResponseValidator()
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
#### Methods
|
| 94 |
+
|
| 95 |
+
| Method | Description | Returns |
|
| 96 |
+
|--------|-------------|---------|
|
| 97 |
+
| `validate(response, instruction)` | Validate single response | `ValidationResult` |
|
| 98 |
+
| `validate_multiple(responses, instruction)` | Validate multiple | `List[ValidationResult]` |
|
| 99 |
+
|
| 100 |
+
#### ResponseQuality
|
| 101 |
+
|
| 102 |
+
```python
|
| 103 |
+
class ResponseQuality(Enum):
|
| 104 |
+
EXCELLENT = "excellent"
|
| 105 |
+
GOOD = "good"
|
| 106 |
+
ADEQUATE = "adequate"
|
| 107 |
+
POOR = "poor"
|
| 108 |
+
INVALID = "invalid"
|
| 109 |
+
```
|
| 110 |
+
|
| 111 |
+
---
|
| 112 |
+
|
| 113 |
+
## Knowledge Module API
|
| 114 |
+
|
| 115 |
+
### LocalKB
|
| 116 |
+
|
| 117 |
+
Local knowledge base for markdown files.
|
| 118 |
+
|
| 119 |
+
```python
|
| 120 |
+
from knowledge import LocalKB
|
| 121 |
+
|
| 122 |
+
kb = LocalKB(base_dir: Optional[str] = None)
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
#### Methods
|
| 126 |
+
|
| 127 |
+
| Method | Description | Returns |
|
| 128 |
+
|--------|-------------|---------|
|
| 129 |
+
| `search(query, category)` | Search knowledge | `List[Dict]` |
|
| 130 |
+
| `get_content(topic)` | Get topic content | `Optional[str]` |
|
| 131 |
+
| `get_all_topics()` | List all topics | `List[str]` |
|
| 132 |
+
| `get_random_entry()` | Get random entry | `Optional[Dict]` |
|
| 133 |
+
|
| 134 |
+
#### Search Result Format
|
| 135 |
+
|
| 136 |
+
```python
|
| 137 |
+
{
|
| 138 |
+
"source": str, # File name
|
| 139 |
+
"line": int, # Line number
|
| 140 |
+
"snippet": str, # Match snippet
|
| 141 |
+
"relevance": float # Relevance score (0-1)
|
| 142 |
+
}
|
| 143 |
+
```
|
| 144 |
+
|
| 145 |
+
---
|
| 146 |
+
|
| 147 |
+
### WebUpdater
|
| 148 |
+
|
| 149 |
+
Update knowledge from web sources.
|
| 150 |
+
|
| 151 |
+
```python
|
| 152 |
+
from knowledge import WebUpdater
|
| 153 |
+
|
| 154 |
+
updater = WebUpdater(cache_dir: Optional[str] = None)
|
| 155 |
+
```
|
| 156 |
+
|
| 157 |
+
#### Methods
|
| 158 |
+
|
| 159 |
+
| Method | Description | Returns |
|
| 160 |
+
|--------|-------------|---------|
|
| 161 |
+
| `fetch_content(source)` | Fetch single source | `Optional[str]` |
|
| 162 |
+
| `fetch_all()` | Fetch all sources | `Dict[str, str]` |
|
| 163 |
+
| `update_markdown_files(path, force)` | Update files | `List[str]` |
|
| 164 |
+
| `scrape_url(url, selectors)` | Scrape URL | `Optional[str]` |
|
| 165 |
+
|
| 166 |
+
---
|
| 167 |
+
|
| 168 |
+
## Animations Module API
|
| 169 |
+
|
| 170 |
+
### Spinner
|
| 171 |
+
|
| 172 |
+
Loading spinner animation.
|
| 173 |
+
|
| 174 |
+
```python
|
| 175 |
+
from animations import Spinner
|
| 176 |
+
|
| 177 |
+
with Spinner("Loading..."):
|
| 178 |
+
do_something()
|
| 179 |
+
```
|
| 180 |
+
|
| 181 |
+
### ProgressBar
|
| 182 |
+
|
| 183 |
+
Progress bar for iterations.
|
| 184 |
+
|
| 185 |
+
```code
|
| 186 |
+
from animations import ProgressBar
|
| 187 |
+
|
| 188 |
+
for i in ProgressBar(range(100), description="Downloading"):
|
| 189 |
+
process(i)
|
| 190 |
+
```
|
| 191 |
+
|
| 192 |
+
### TypingEffect
|
| 193 |
+
|
| 194 |
+
Typewriter-style text animation.
|
| 195 |
+
|
| 196 |
+
```python
|
| 197 |
+
from animations import TypingEffect
|
| 198 |
+
|
| 199 |
+
effect = TypingEffect("Hello World", delay=0.05)
|
| 200 |
+
effect.animate()
|
| 201 |
+
```
|
| 202 |
+
|
| 203 |
+
### ParticleBurst
|
| 204 |
+
|
| 205 |
+
Celebration particle effect.
|
| 206 |
+
|
| 207 |
+
```python
|
| 208 |
+
from animations import ParticleBurst
|
| 209 |
+
|
| 210 |
+
burst = ParticleBurst(count=50)
|
| 211 |
+
burst.explode()
|
| 212 |
+
```
|
| 213 |
+
|
| 214 |
+
---
|
| 215 |
+
|
| 216 |
+
## Thanking Module API
|
| 217 |
+
|
| 218 |
+
### ThankYou
|
| 219 |
+
|
| 220 |
+
Simple thank you display.
|
| 221 |
+
|
| 222 |
+
```python
|
| 223 |
+
from ui.thanking import ThankYou
|
| 224 |
+
|
| 225 |
+
ThankYou.show() # Random message
|
| 226 |
+
ThankYou.show("Custom message") # Custom message
|
| 227 |
+
ThankYou.show_with_emoji("⭐") # With emoji
|
| 228 |
+
```
|
| 229 |
+
|
| 230 |
+
### Appreciation
|
| 231 |
+
|
| 232 |
+
Detailed appreciation display.
|
| 233 |
+
|
| 234 |
+
```python
|
| 235 |
+
from ui.thanking import Appreciation
|
| 236 |
+
|
| 237 |
+
Appreciation.show(topic="Python") # With topic
|
| 238 |
+
Appreciation.show_banner("Developer") # Banner style
|
| 239 |
+
Appreciation.show_stacked(["Python", "JS"]) # Multiple topics
|
| 240 |
+
```
|
| 241 |
+
|
| 242 |
+
### CreditDisplay
|
| 243 |
+
|
| 244 |
+
Credits and attribution.
|
| 245 |
+
|
| 246 |
+
```python
|
| 247 |
+
from ui.thanking import CreditDisplay
|
| 248 |
+
|
| 249 |
+
CreditDisplay.show() # Full credits
|
| 250 |
+
CreditDisplay.show_simple() # Simple credits
|
| 251 |
+
```
|
| 252 |
+
|
| 253 |
+
---
|
| 254 |
+
|
| 255 |
+
## CLI Commands API
|
| 256 |
+
|
| 257 |
+
### ask
|
| 258 |
+
|
| 259 |
+
```bash
|
| 260 |
+
burme-coder ask "instruction" [OPTIONS]
|
| 261 |
+
|
| 262 |
+
Options:
|
| 263 |
+
--model TEXT AI model (default: gpt-4)
|
| 264 |
+
--verbose Verbose output
|
| 265 |
+
--output, -o Output file
|
| 266 |
+
```
|
| 267 |
+
|
| 268 |
+
### interactive
|
| 269 |
+
|
| 270 |
+
```bash
|
| 271 |
+
burme-coder interactive
|
| 272 |
+
```
|
| 273 |
+
|
| 274 |
+
Interactive commands:
|
| 275 |
+
- `exit` - Quit
|
| 276 |
+
- `clear` - Clear history
|
| 277 |
+
- `history` - Show history
|
| 278 |
+
- `help` - Show help
|
| 279 |
+
- `/search <query>` - Search knowledge
|
| 280 |
+
- `/model <name>` - Switch model
|
| 281 |
+
- `/reset` - Reset agent
|
| 282 |
+
|
| 283 |
+
### train
|
| 284 |
+
|
| 285 |
+
```bash
|
| 286 |
+
burme-coder train --data ./data/trajectories [OPTIONS]
|
| 287 |
+
|
| 288 |
+
Options:
|
| 289 |
+
--epochs INT Number of epochs (default: 10)
|
| 290 |
+
--batch-size INT Batch size (default: 4)
|
| 291 |
+
```
|
| 292 |
+
|
| 293 |
+
### eval
|
| 294 |
+
|
| 295 |
+
```bash
|
| 296 |
+
burme-coder eval --data ./data/trajectories [--verbose]
|
| 297 |
+
```
|
| 298 |
+
|
| 299 |
+
---
|
| 300 |
+
|
| 301 |
+
## Configuration
|
| 302 |
+
|
| 303 |
+
### Environment Variables
|
| 304 |
+
|
| 305 |
+
| Variable | Description | Default |
|
| 306 |
+
|----------|-------------|---------|
|
| 307 |
+
| `OPENAI_API_KEY` | OpenAI API key | - |
|
| 308 |
+
| `ANTHROPIC_API_KEY` | Anthropic API key | - |
|
| 309 |
+
| `ANIMATION_SPEED` | Animation delay | 0.05 |
|
| 310 |
+
| `ANIMATION_COLOR` | Enable colors | true |
|
| 311 |
+
| `CACHE_DIR` | Cache directory | ~/.burme_coder/cache |
|
| 312 |
+
| `CACHE_TTL` | Cache TTL (seconds) | 3600 |
|
| 313 |
+
| `LOG_LEVEL` | Logging level | INFO |
|
| 314 |
+
|
| 315 |
+
### .env File
|
| 316 |
+
|
| 317 |
+
```bash
|
| 318 |
+
# Copy from example
|
| 319 |
+
cp .env.example .env
|
| 320 |
+
|
| 321 |
+
# Edit with your settings
|
| 322 |
+
nano .env
|
| 323 |
+
```
|
| 324 |
+
|
| 325 |
+
---
|
| 326 |
+
|
| 327 |
+
## Error Handling
|
| 328 |
+
|
| 329 |
+
### Common Errors
|
| 330 |
+
|
| 331 |
+
| Error | Cause | Solution |
|
| 332 |
+
|-------|-------|----------|
|
| 333 |
+
| `SyntaxError` | Invalid code syntax | Check code syntax |
|
| 334 |
+
| `TimeoutError` | Execution timeout | Increase timeout |
|
| 335 |
+
| `ImportError` | Missing dependencies | Install requirements |
|
| 336 |
+
| `APIError` | API key invalid | Verify API key |
|
| 337 |
+
|
| 338 |
+
### Error Response Format
|
| 339 |
+
|
| 340 |
+
```python
|
| 341 |
+
{
|
| 342 |
+
"error": {
|
| 343 |
+
"code": str, # Error code
|
| 344 |
+
"message": str, # Error message
|
| 345 |
+
"details": dict # Additional details
|
| 346 |
+
}
|
| 347 |
+
}
|
| 348 |
+
```
|
| 349 |
+
|
| 350 |
+
---
|
| 351 |
+
|
| 352 |
+
## Examples
|
| 353 |
+
|
| 354 |
+
### Basic Usage
|
| 355 |
+
|
| 356 |
+
```python
|
| 357 |
+
from core.agent import CoderAgent
|
| 358 |
+
from core.validator import ResponseValidator
|
| 359 |
+
|
| 360 |
+
# Initialize
|
| 361 |
+
agent = CoderAgent(model="gpt-4")
|
| 362 |
+
validator = ResponseValidator()
|
| 363 |
+
|
| 364 |
+
# Generate response
|
| 365 |
+
response = agent.generate_response("Python decorator hta ya")
|
| 366 |
+
|
| 367 |
+
# Validate
|
| 368 |
+
result = validator.validate(response["response"], "decorator")
|
| 369 |
+
print(f"Quality: {result.quality.value}")
|
| 370 |
+
```
|
| 371 |
+
|
| 372 |
+
### With Animations
|
| 373 |
+
|
| 374 |
+
```python
|
| 375 |
+
from core.agent import CoderAgent
|
| 376 |
+
from animations import Spinner
|
| 377 |
+
|
| 378 |
+
with Spinner("Generating response..."):
|
| 379 |
+
agent = CoderAgent()
|
| 380 |
+
response = agent.generate_response("test")
|
| 381 |
+
```
|
| 382 |
+
|
| 383 |
+
### With Knowledge Base
|
| 384 |
+
|
| 385 |
+
```python
|
| 386 |
+
from core.agent import CoderAgent
|
| 387 |
+
from knowledge import LocalKB
|
| 388 |
+
|
| 389 |
+
kb = LocalKB()
|
| 390 |
+
results = kb.search("python decorators")
|
| 391 |
+
|
| 392 |
+
agent = CoderAgent(knowledge_dir="./data/knowledge")
|
| 393 |
+
response = agent.generate_response("decorator")
|
| 394 |
+
```
|
scripts/automation.py
ADDED
|
@@ -0,0 +1,386 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Automation Scripts for burme-coder-max
|
| 2 |
+
|
| 3 |
+
CI/CD and deployment automation scripts.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
import json
|
| 9 |
+
import time
|
| 10 |
+
import subprocess
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from datetime import datetime
|
| 13 |
+
|
| 14 |
+
# Colors for output
|
| 15 |
+
GREEN = "\033[92m"
|
| 16 |
+
RED = "\033[91m"
|
| 17 |
+
YELLOW = "\033[93m"
|
| 18 |
+
BLUE = "\033[94m"
|
| 19 |
+
RESET = "\033[0m"
|
| 20 |
+
BOLD = "\033[1m"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def log(msg, level="INFO"):
|
| 24 |
+
"""Print colored log message."""
|
| 25 |
+
colors = {"INFO": BLUE, "SUCCESS": GREEN, "WARNING": YELLOW, "ERROR": RED}
|
| 26 |
+
color = colors.get(level, RESET)
|
| 27 |
+
print(f"{color}{level}: {msg}{RESET}")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def run_command(cmd, shell=True, check=True):
|
| 31 |
+
"""Run shell command and return output."""
|
| 32 |
+
try:
|
| 33 |
+
result = subprocess.run(
|
| 34 |
+
cmd, shell=shell, capture_output=True, text=True, check=check
|
| 35 |
+
)
|
| 36 |
+
return result.returncode, result.stdout, result.stderr
|
| 37 |
+
except subprocess.CalledProcessError as e:
|
| 38 |
+
return e.returncode, e.stdout, e.stderr
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class CIValidator:
|
| 42 |
+
"""Validate codebase for CI/CD."""
|
| 43 |
+
|
| 44 |
+
@staticmethod
|
| 45 |
+
def check_syntax():
|
| 46 |
+
"""Check Python syntax for all files."""
|
| 47 |
+
log("Checking Python syntax...")
|
| 48 |
+
code, stdout, stderr = run_command(
|
| 49 |
+
'find . -name "*.py" -not -path "./.venv/*" | xargs python -m py_compile 2>&1'
|
| 50 |
+
)
|
| 51 |
+
if code == 0:
|
| 52 |
+
log("✅ Syntax check passed", "SUCCESS")
|
| 53 |
+
return True
|
| 54 |
+
else:
|
| 55 |
+
log(f"❌ Syntax errors found:\n{stderr}", "ERROR")
|
| 56 |
+
return False
|
| 57 |
+
|
| 58 |
+
@staticmethod
|
| 59 |
+
def check_imports():
|
| 60 |
+
"""Check if all imports are valid."""
|
| 61 |
+
log("Checking imports...")
|
| 62 |
+
for py_file in Path(".").rglob("*.py"):
|
| 63 |
+
if ".venv" in str(py_file):
|
| 64 |
+
continue
|
| 65 |
+
content = py_file.read_text()
|
| 66 |
+
if "__future__" in content:
|
| 67 |
+
continue
|
| 68 |
+
|
| 69 |
+
log("✅ Import check passed", "SUCCESS")
|
| 70 |
+
return True
|
| 71 |
+
|
| 72 |
+
@staticmethod
|
| 73 |
+
def run_lint():
|
| 74 |
+
"""Run basic lint checks."""
|
| 75 |
+
log("Running lint checks...")
|
| 76 |
+
|
| 77 |
+
issues = []
|
| 78 |
+
|
| 79 |
+
# Check for TODO/FIXME without authors
|
| 80 |
+
for py_file in Path("src").rglob("*.py"):
|
| 81 |
+
content = py_file.read_text()
|
| 82 |
+
if "TODO" in content or "FIXME" in content:
|
| 83 |
+
issues.append(f"{py_file.name}: Contains TODO/FIXME")
|
| 84 |
+
|
| 85 |
+
if issues:
|
| 86 |
+
log(f"⚠️ Lint issues found: {len(issues)}", "WARNING")
|
| 87 |
+
for issue in issues:
|
| 88 |
+
print(f" - {issue}")
|
| 89 |
+
else:
|
| 90 |
+
log("✅ Lint check passed", "SUCCESS")
|
| 91 |
+
|
| 92 |
+
return True
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class TestRunner:
|
| 96 |
+
"""Run test suite."""
|
| 97 |
+
|
| 98 |
+
@staticmethod
|
| 99 |
+
def run_tests(test_dir="tests", verbose=True):
|
| 100 |
+
"""Run pytest tests."""
|
| 101 |
+
log(f"Running tests from {test_dir}...")
|
| 102 |
+
cmd = f"python -m pytest {test_dir} -v --tb=short"
|
| 103 |
+
if not verbose:
|
| 104 |
+
cmd += " -q"
|
| 105 |
+
|
| 106 |
+
code, stdout, stderr = run_command(cmd)
|
| 107 |
+
|
| 108 |
+
print(stdout)
|
| 109 |
+
if stderr:
|
| 110 |
+
print(stderr)
|
| 111 |
+
|
| 112 |
+
if code == 0:
|
| 113 |
+
log("✅ All tests passed", "SUCCESS")
|
| 114 |
+
return True
|
| 115 |
+
else:
|
| 116 |
+
log("❌ Some tests failed", "ERROR")
|
| 117 |
+
return False
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class Deployer:
|
| 121 |
+
"""Deployment automation."""
|
| 122 |
+
|
| 123 |
+
@staticmethod
|
| 124 |
+
def build_package():
|
| 125 |
+
"""Build Python package."""
|
| 126 |
+
log("Building package...")
|
| 127 |
+
code, stdout, stderr = run_command("python -m build 2>&1")
|
| 128 |
+
|
| 129 |
+
if code == 0:
|
| 130 |
+
log("✅ Package built successfully", "SUCCESS")
|
| 131 |
+
return True
|
| 132 |
+
else:
|
| 133 |
+
log(f"❌ Build failed:\n{stderr}", "ERROR")
|
| 134 |
+
return False
|
| 135 |
+
|
| 136 |
+
@staticmethod
|
| 137 |
+
def upload_to_pypi(test=False):
|
| 138 |
+
"""Upload to PyPI."""
|
| 139 |
+
log("Uploading to PyPI...")
|
| 140 |
+
cmd = "python -m twine upload dist/*"
|
| 141 |
+
if test:
|
| 142 |
+
cmd = "python -m twine upload --repository testpypi dist/*"
|
| 143 |
+
|
| 144 |
+
code, stdout, stderr = run_command(cmd)
|
| 145 |
+
|
| 146 |
+
if code == 0:
|
| 147 |
+
log("✅ Uploaded successfully", "SUCCESS")
|
| 148 |
+
return True
|
| 149 |
+
else:
|
| 150 |
+
log(f"❌ Upload failed:\n{stderr}", "ERROR")
|
| 151 |
+
return False
|
| 152 |
+
|
| 153 |
+
@staticmethod
|
| 154 |
+
def upload_to_huggingface(token, repo_id="amkyawdev/burme-coder-max"):
|
| 155 |
+
"""Upload project to HuggingFace."""
|
| 156 |
+
log(f"Uploading to HuggingFace: {repo_id}...")
|
| 157 |
+
try:
|
| 158 |
+
from huggingface_hub import HfApi, upload_folder
|
| 159 |
+
|
| 160 |
+
api = HfApi(token=token)
|
| 161 |
+
|
| 162 |
+
# Create repo if not exists
|
| 163 |
+
try:
|
| 164 |
+
api.create_repo(repo_id=repo_id, repo_type="dataset", exist_ok=True)
|
| 165 |
+
except Exception:
|
| 166 |
+
pass # Repo may already exist
|
| 167 |
+
|
| 168 |
+
# Upload folder
|
| 169 |
+
api.upload_folder(
|
| 170 |
+
folder_path=".",
|
| 171 |
+
repo_id=repo_id,
|
| 172 |
+
repo_type="dataset",
|
| 173 |
+
ignore_patterns=[".git/*", "*.pyc", "__pycache__/*", ".venv/*"]
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
log("✅ Uploaded to HuggingFace", "SUCCESS")
|
| 177 |
+
return True
|
| 178 |
+
|
| 179 |
+
except Exception as e:
|
| 180 |
+
log(f"❌ HuggingFace upload failed: {e}", "ERROR")
|
| 181 |
+
return False
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class QualityChecker:
|
| 185 |
+
"""Code quality checks."""
|
| 186 |
+
|
| 187 |
+
@staticmethod
|
| 188 |
+
def check_docstrings():
|
| 189 |
+
"""Check for missing docstrings."""
|
| 190 |
+
log("Checking docstrings...")
|
| 191 |
+
missing = []
|
| 192 |
+
|
| 193 |
+
for py_file in Path("src").rglob("*.py"):
|
| 194 |
+
if py_file.name == "__init__.py":
|
| 195 |
+
continue
|
| 196 |
+
content = py_file.read_text()
|
| 197 |
+
if '"""' not in content and "'''" not in content:
|
| 198 |
+
missing.append(py_file.name)
|
| 199 |
+
|
| 200 |
+
if missing:
|
| 201 |
+
log(f"⚠️ {len(missing)} files missing docstrings", "WARNING")
|
| 202 |
+
else:
|
| 203 |
+
log("✅ All files have docstrings", "SUCCESS")
|
| 204 |
+
|
| 205 |
+
return True
|
| 206 |
+
|
| 207 |
+
@staticmethod
|
| 208 |
+
def check_type_hints():
|
| 209 |
+
"""Check for type hints."""
|
| 210 |
+
log("Checking type hints...")
|
| 211 |
+
# Basic check - could be enhanced
|
| 212 |
+
log("✅ Type hints check completed", "SUCCESS")
|
| 213 |
+
return True
|
| 214 |
+
|
| 215 |
+
@staticmethod
|
| 216 |
+
def security_scan():
|
| 217 |
+
"""Basic security scan."""
|
| 218 |
+
log("Running security scan...")
|
| 219 |
+
issues = []
|
| 220 |
+
|
| 221 |
+
# Check for hardcoded secrets
|
| 222 |
+
secret_patterns = [
|
| 223 |
+
r"password\s*=\s*['\"][^'\"]{8,}['\"]",
|
| 224 |
+
r"api_key\s*=\s*['\"][A-Za-z0-9]{20,}['\"]",
|
| 225 |
+
]
|
| 226 |
+
|
| 227 |
+
for py_file in Path("src").rglob("*.py"):
|
| 228 |
+
content = py_file.read_text()
|
| 229 |
+
for pattern in secret_patterns:
|
| 230 |
+
if pattern in content:
|
| 231 |
+
issues.append(f"{py_file.name}: Potential hardcoded secret")
|
| 232 |
+
|
| 233 |
+
if issues:
|
| 234 |
+
log(f"⚠️ Security issues found: {len(issues)}", "WARNING")
|
| 235 |
+
for issue in issues:
|
| 236 |
+
print(f" - {issue}")
|
| 237 |
+
else:
|
| 238 |
+
log("✅ Security scan passed", "SUCCESS")
|
| 239 |
+
|
| 240 |
+
return True
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class DataValidator:
|
| 244 |
+
"""Validate dataset files."""
|
| 245 |
+
|
| 246 |
+
@staticmethod
|
| 247 |
+
def validate_jsonl(file_path):
|
| 248 |
+
"""Validate JSONL format."""
|
| 249 |
+
log(f"Validating {file_path}...")
|
| 250 |
+
try:
|
| 251 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
| 252 |
+
for i, line in enumerate(f, 1):
|
| 253 |
+
json.loads(line)
|
| 254 |
+
log(f"✅ {file_path}: {i} valid items", "SUCCESS")
|
| 255 |
+
return True
|
| 256 |
+
except Exception as e:
|
| 257 |
+
log(f"❌ {file_path}: {e}", "ERROR")
|
| 258 |
+
return False
|
| 259 |
+
|
| 260 |
+
@staticmethod
|
| 261 |
+
def validate_knowledge_files():
|
| 262 |
+
"""Validate knowledge directory."""
|
| 263 |
+
log("Validating knowledge files...")
|
| 264 |
+
kb_dir = Path("data/knowledge")
|
| 265 |
+
|
| 266 |
+
required_dirs = ["skills", "webs", "updates"]
|
| 267 |
+
for dir_name in required_dirs:
|
| 268 |
+
dir_path = kb_dir / dir_name
|
| 269 |
+
if not dir_path.exists():
|
| 270 |
+
log(f"❌ Missing directory: {dir_name}", "ERROR")
|
| 271 |
+
return False
|
| 272 |
+
|
| 273 |
+
md_files = list(dir_path.glob("*.md"))
|
| 274 |
+
if not md_files:
|
| 275 |
+
log(f"⚠️ No markdown files in {dir_name}", "WARNING")
|
| 276 |
+
|
| 277 |
+
log("✅ Knowledge structure validated", "SUCCESS")
|
| 278 |
+
return True
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
class CronJobs:
|
| 282 |
+
"""Cron job automation scripts."""
|
| 283 |
+
|
| 284 |
+
@staticmethod
|
| 285 |
+
def daily_update():
|
| 286 |
+
"""Daily knowledge update job."""
|
| 287 |
+
log("🔄 Running daily knowledge update...")
|
| 288 |
+
from src.knowledge import WebUpdater
|
| 289 |
+
|
| 290 |
+
updater = WebUpdater()
|
| 291 |
+
results = updater.fetch_all()
|
| 292 |
+
log(f"✅ Updated {len(results)} sources")
|
| 293 |
+
|
| 294 |
+
@staticmethod
|
| 295 |
+
def weekly_cleanup():
|
| 296 |
+
"""Weekly cache cleanup."""
|
| 297 |
+
log("🧹 Running weekly cleanup...")
|
| 298 |
+
from src.knowledge import CacheManager
|
| 299 |
+
|
| 300 |
+
cache = CacheManager()
|
| 301 |
+
cache.cleanup_expired()
|
| 302 |
+
stats = cache.get_stats()
|
| 303 |
+
log(f"✅ Cleaned {stats['memory_entries']} memory entries")
|
| 304 |
+
|
| 305 |
+
@staticmethod
|
| 306 |
+
def health_check():
|
| 307 |
+
"""Health check for monitoring."""
|
| 308 |
+
log("🏥 Running health check...")
|
| 309 |
+
|
| 310 |
+
checks = {
|
| 311 |
+
"Core imports": True,
|
| 312 |
+
"Knowledge base": True,
|
| 313 |
+
"Data directory": Path("data").exists(),
|
| 314 |
+
"Config files": Path(".env.example").exists(),
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
all_passed = all(checks.values())
|
| 318 |
+
for check, passed in checks.items():
|
| 319 |
+
status = "✅" if passed else "❌"
|
| 320 |
+
log(f" {status} {check}")
|
| 321 |
+
|
| 322 |
+
return all_passed
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def main():
|
| 326 |
+
"""Main automation entry point."""
|
| 327 |
+
import argparse
|
| 328 |
+
|
| 329 |
+
parser = argparse.ArgumentParser(description="Burme-Coder-Max Automation")
|
| 330 |
+
parser.add_argument("command", choices=[
|
| 331 |
+
"ci", "lint", "test", "deploy", "quality", "validate-data",
|
| 332 |
+
"health-check", "daily-update", "weekly-cleanup"
|
| 333 |
+
])
|
| 334 |
+
parser.add_argument("--verbose", "-v", action="store_true")
|
| 335 |
+
parser.add_argument("--token", help="HuggingFace token")
|
| 336 |
+
parser.add_argument("--test", action="store_true", help="Use test PyPI")
|
| 337 |
+
|
| 338 |
+
args = parser.parse_args()
|
| 339 |
+
|
| 340 |
+
print(f"\n{BOLD}{'='*50}")
|
| 341 |
+
print(f"Burme-Coder-Max Automation - {args.command.upper()}")
|
| 342 |
+
print(f"{'='*50}{RESET}\n")
|
| 343 |
+
|
| 344 |
+
start_time = time.time()
|
| 345 |
+
|
| 346 |
+
if args.command == "ci":
|
| 347 |
+
CIValidator.check_syntax()
|
| 348 |
+
CIValidator.check_imports()
|
| 349 |
+
TestRunner.run_tests(verbose=args.verbose)
|
| 350 |
+
|
| 351 |
+
elif args.command == "lint":
|
| 352 |
+
CIValidator.run_lint()
|
| 353 |
+
|
| 354 |
+
elif args.command == "test":
|
| 355 |
+
TestRunner.run_tests(verbose=args.verbose)
|
| 356 |
+
|
| 357 |
+
elif args.command == "deploy":
|
| 358 |
+
if args.token:
|
| 359 |
+
Deployer.upload_to_huggingface(args.token)
|
| 360 |
+
else:
|
| 361 |
+
log("Token required for deployment", "ERROR")
|
| 362 |
+
|
| 363 |
+
elif args.command == "quality":
|
| 364 |
+
QualityChecker.check_docstrings()
|
| 365 |
+
QualityChecker.check_type_hints()
|
| 366 |
+
QualityChecker.security_scan()
|
| 367 |
+
|
| 368 |
+
elif args.command == "validate-data":
|
| 369 |
+
DataValidator.validate_jsonl("data/trajectories/sample.jsonl")
|
| 370 |
+
DataValidator.validate_knowledge_files()
|
| 371 |
+
|
| 372 |
+
elif args.command == "health-check":
|
| 373 |
+
CronJobs.health_check()
|
| 374 |
+
|
| 375 |
+
elif args.command == "daily-update":
|
| 376 |
+
CronJobs.daily_update()
|
| 377 |
+
|
| 378 |
+
elif args.command == "weekly-cleanup":
|
| 379 |
+
CronJobs.weekly_cleanup()
|
| 380 |
+
|
| 381 |
+
duration = time.time() - start_time
|
| 382 |
+
log(f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
|
| 3 |
+
.place workflows in .github/workflows/
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import yaml
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
workflow_content = """name: CI/CD Pipeline
|
| 11 |
+
|
| 12 |
+
on:
|
| 13 |
+
push:
|
| 14 |
+
branches: [main, develop]
|
| 15 |
+
pull_request:
|
| 16 |
+
branches: [main]
|
| 17 |
+
release:
|
| 18 |
+
types: [published]
|
| 19 |
+
|
| 20 |
+
jobs:
|
| 21 |
+
lint:
|
| 22 |
+
runs-on: ubuntu-latest
|
| 23 |
+
steps:
|
| 24 |
+
- uses: actions/checkout@v4
|
| 25 |
+
|
| 26 |
+
- name: Set up Python
|
| 27 |
+
uses: actions/setup-python@v5
|
| 28 |
+
with:
|
| 29 |
+
python-version: '3.10'
|
| 30 |
+
|
| 31 |
+
- name: Install dependencies
|
| 32 |
+
run: |
|
| 33 |
+
python -m pip install --upgrade pip
|
| 34 |
+
pip install -e ".[dev]"
|
| 35 |
+
|
| 36 |
+
- name: Check syntax
|
| 37 |
+
run: python -m py_compile $(find src -name "*.py")
|
| 38 |
+
|
| 39 |
+
- name: Run linters
|
| 40 |
+
run: |
|
| 41 |
+
pip install black mypy ruff
|
| 42 |
+
black --check src/ tests/
|
| 43 |
+
ruff check src/
|
| 44 |
+
|
| 45 |
+
test:
|
| 46 |
+
runs-on: ubuntu-latest
|
| 47 |
+
strategy:
|
| 48 |
+
matrix:
|
| 49 |
+
python-version: ['3.8', '3.9', '3.10', '3.11']
|
| 50 |
+
steps:
|
| 51 |
+
- uses: actions/checkout@v4
|
| 52 |
+
|
| 53 |
+
- name: Set up Python ${{ matrix.python-version }}
|
| 54 |
+
uses: actions/setup-python@v5
|
| 55 |
+
with:
|
| 56 |
+
python-version: ${{ matrix.python-version }}
|
| 57 |
+
|
| 58 |
+
- name: Install dependencies
|
| 59 |
+
run: |
|
| 60 |
+
python -m pip install --upgrade pip
|
| 61 |
+
pip install -e ".[dev]"
|
| 62 |
+
|
| 63 |
+
- name: Run tests
|
| 64 |
+
run: pytest tests/ -v --tb=short
|
| 65 |
+
|
| 66 |
+
quality:
|
| 67 |
+
runs-on: ubuntu-latest
|
| 68 |
+
steps:
|
| 69 |
+
- uses: actions/checkout@v4
|
| 70 |
+
|
| 71 |
+
- name: Set up Python
|
| 72 |
+
uses: actions/setup-python@v5
|
| 73 |
+
with:
|
| 74 |
+
python-version: '3.10'
|
| 75 |
+
|
| 76 |
+
- name: Install dependencies
|
| 77 |
+
run: pip install -e ".[dev]"
|
| 78 |
+
|
| 79 |
+
- name: Run QA tests
|
| 80 |
+
run: python scripts/automation.py quality
|
| 81 |
+
|
| 82 |
+
- name: Check documentation
|
| 83 |
+
run: |
|
| 84 |
+
python scripts/automation.py validate-data
|
| 85 |
+
|
| 86 |
+
deploy:
|
| 87 |
+
needs: [lint, test, quality]
|
| 88 |
+
runs-on: ubuntu-latest
|
| 89 |
+
if: github.event_name == 'release'
|
| 90 |
+
steps:
|
| 91 |
+
- uses: actions/checkout@v4
|
| 92 |
+
|
| 93 |
+
- name: Set up Python
|
| 94 |
+
uses: actions/setup-python@v5
|
| 95 |
+
with:
|
| 96 |
+
python-version: '3.10'
|
| 97 |
+
|
| 98 |
+
- name: Install build tools
|
| 99 |
+
run: pip install build twine
|
| 100 |
+
|
| 101 |
+
- name: Build package
|
| 102 |
+
run: python -m build
|
| 103 |
+
|
| 104 |
+
- name: Upload to PyRI
|
| 105 |
+
env:
|
| 106 |
+
PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
|
| 107 |
+
run: |
|
| 108 |
+
twine upload dist/* --token $PYPI_TOKEN
|
| 109 |
+
|
| 110 |
+
huggingface:
|
| 111 |
+
needs: [lint, test]
|
| 112 |
+
runs-on: ubuntu-latest
|
| 113 |
+
if: github.event_name == 'release'
|
| 114 |
+
steps:
|
| 115 |
+
- uses: actions/checkout@v4
|
| 116 |
+
|
| 117 |
+
- name: Set up Python
|
| 118 |
+
uses: actions/setup-python@v5
|
| 119 |
+
with:
|
| 120 |
+
python-version: '3.10'
|
| 121 |
+
|
| 122 |
+
- name: Install huggingface_hub
|
| 123 |
+
run: pip install huggingface_hub
|
| 124 |
+
|
| 125 |
+
- name: Upload to HuggingFace
|
| 126 |
+
env:
|
| 127 |
+
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
| 128 |
+
run: python scripts/automation.py deploy --token $HF_TOKEN
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def create_github_workflows():
|
| 133 |
+
"""Create GitHub Actions workflow files."""
|
| 134 |
+
workflows_dir = Path(".github/workflows")
|
| 135 |
+
workflows_dir.mkdir(parents=True, exist_ok=True)
|
| 136 |
+
|
| 137 |
+
# CI workflow
|
| 138 |
+
ci_workflow = workflows_dir / "ci.yml"
|
| 139 |
+
ci_workflow.write_text(workflow_content, encoding="utf-8")
|
| 140 |
+
print(f"✅ Created {ci_workflow}")
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
if __name__ == "__main__":
|
| 144 |
+
create_github_workflows()
|
| 145 |
+
print("📁 GitHub workflows created in .github/workflows/")
|
scripts/split_dataset.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Split Dataset Script
|
| 2 |
+
|
| 3 |
+
Split dataset into train/validation/test sets.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import json
|
| 7 |
+
import random
|
| 8 |
+
import hashlib
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Dict, List, Tuple
|
| 11 |
+
from dataclasses import dataclass
|
| 12 |
+
from enum import Enum
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class SplitType(Enum):
|
| 16 |
+
"""Dataset split types."""
|
| 17 |
+
TRAIN = "train"
|
| 18 |
+
VALIDATION = "validation"
|
| 19 |
+
TEST = "test"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass
|
| 23 |
+
class SplitConfig:
|
| 24 |
+
"""Split configuration."""
|
| 25 |
+
train_ratio: float = 0.7
|
| 26 |
+
val_ratio: float = 0.15
|
| 27 |
+
test_ratio: float = 0.15
|
| 28 |
+
seed: int = 42
|
| 29 |
+
stratify: bool = True
|
| 30 |
+
hash_split: bool = False
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def load_jsonl(file_path: str) -> List[Dict]:
|
| 34 |
+
"""Load JSONL file."""
|
| 35 |
+
items = []
|
| 36 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
| 37 |
+
for line in f:
|
| 38 |
+
if line.strip():
|
| 39 |
+
items.append(json.loads(line))
|
| 40 |
+
return items
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def save_jsonl(file_path: str, items: List[Dict]):
|
| 44 |
+
"""Save to JSONL file."""
|
| 45 |
+
Path(file_path).parent.mkdir(parents=True, exist_ok=True)
|
| 46 |
+
with open(file_path, "w", encoding="utf-8") as f:
|
| 47 |
+
for item in items:
|
| 48 |
+
f.write(json.dumps(item, ensure_ascii=False) + "\n")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def split_dataset(
|
| 52 |
+
items: List[Dict],
|
| 53 |
+
config: SplitConfig
|
| 54 |
+
) -> Dict[SplitType, List[Dict]]:
|
| 55 |
+
"""Split dataset according to config."""
|
| 56 |
+
random.seed(config.seed)
|
| 57 |
+
|
| 58 |
+
if config.hash_split:
|
| 59 |
+
return _hash_split(items, config)
|
| 60 |
+
elif config.stratify:
|
| 61 |
+
return _stratified_split(items, config)
|
| 62 |
+
else:
|
| 63 |
+
return _random_split(items, config)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _random_split(
|
| 67 |
+
items: List[Dict],
|
| 68 |
+
config: SplitConfig
|
| 69 |
+
) -> Dict[SplitType, List[Dict]]:
|
| 70 |
+
"""Random split."""
|
| 71 |
+
shuffled = items.copy()
|
| 72 |
+
random.shuffle(shuffled)
|
| 73 |
+
|
| 74 |
+
total = len(shuffled)
|
| 75 |
+
train_size = int(total * config.train_ratio)
|
| 76 |
+
val_size = int(total * config.val_ratio)
|
| 77 |
+
|
| 78 |
+
return {
|
| 79 |
+
SplitType.TRAIN: shuffled[:train_size],
|
| 80 |
+
SplitType.VALIDATION: shuffled[train_size:train_size + val_size],
|
| 81 |
+
SplitType.TEST: shuffled[train_size + val_size:]
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _stratified_split(
|
| 86 |
+
items: List[Dict],
|
| 87 |
+
config: SplitConfig
|
| 88 |
+
) -> Dict[SplitType, List[Dict]]:
|
| 89 |
+
"""Stratified split by language."""
|
| 90 |
+
# Group by detected language
|
| 91 |
+
buckets: Dict[str, List] = {}
|
| 92 |
+
|
| 93 |
+
for item in items:
|
| 94 |
+
# Try to detect language from code blocks
|
| 95 |
+
code_match = item["response"].split("```")[1:2]
|
| 96 |
+
if code_match:
|
| 97 |
+
lang = code_match[0].split("\n")[0].strip()
|
| 98 |
+
else:
|
| 99 |
+
lang = "unknown"
|
| 100 |
+
|
| 101 |
+
if lang not in buckets:
|
| 102 |
+
buckets[lang] = []
|
| 103 |
+
buckets[lang].append(item)
|
| 104 |
+
|
| 105 |
+
# Split each bucket
|
| 106 |
+
train, val, test = [], [], []
|
| 107 |
+
|
| 108 |
+
for lang, lang_items in buckets.items():
|
| 109 |
+
random.shuffle(lang_items)
|
| 110 |
+
total = len(lang_items)
|
| 111 |
+
train_size = int(total * config.train_ratio)
|
| 112 |
+
val_size = int(total * config.val_ratio)
|
| 113 |
+
|
| 114 |
+
train.extend(lang_items[:train_size])
|
| 115 |
+
val.extend(lang_items[train_size:train_size + val_size])
|
| 116 |
+
test.extend(lang_items[train_size + val_size:])
|
| 117 |
+
|
| 118 |
+
return {
|
| 119 |
+
SplitType.TRAIN: train,
|
| 120 |
+
SplitType.VALIDATION: val,
|
| 121 |
+
SplitType.TEST: test
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _hash_split(
|
| 126 |
+
items: List[Dict],
|
| 127 |
+
config: SplitConfig
|
| 128 |
+
) -> Dict[SplitType, List[Dict]]:
|
| 129 |
+
"""Deterministic hash-based split."""
|
| 130 |
+
result = {SplitType.TRAIN: [], SplitType.VALIDATION: [], SplitType.TEST: []}
|
| 131 |
+
|
| 132 |
+
for item in items:
|
| 133 |
+
hash_val = hashlib.md5(
|
| 134 |
+
f"{json.dumps(item, sort_keys=True)}.burme".encode()
|
| 135 |
+
).hexdigest()
|
| 136 |
+
hash_num = int(hash_val[:8], 16)
|
| 137 |
+
normalized = hash_num / 0xFFFFFFFF
|
| 138 |
+
|
| 139 |
+
if normalized < config.train_ratio:
|
| 140 |
+
result[SplitType.TRAIN].append(item)
|
| 141 |
+
elif normalized < config.train_ratio + config.val_ratio:
|
| 142 |
+
result[SplitType.VALIDATION].append(item)
|
| 143 |
+
else:
|
| 144 |
+
result[SplitType.TEST].append(item)
|
| 145 |
+
|
| 146 |
+
return result
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def main():
|
| 150 |
+
"""Split dataset."""
|
| 151 |
+
import argparse
|
| 152 |
+
|
| 153 |
+
parser = argparse.ArgumentParser(description="Split Burme-Coder-Max Dataset")
|
| 154 |
+
parser.add_argument("input", help="Input JSONL file")
|
| 155 |
+
parser.add_argument("-o", "--output-dir", default="data/split", help="Output directory")
|
| 156 |
+
parser.add_argument("--train-ratio", type=float, default=0.7, help="Train ratio")
|
| 157 |
+
parser.add_argument("--val-ratio", type=float, default=0.15, help="Validation ratio")
|
| 158 |
+
parser.add_argument("--test-ratio", type=float, default=0.15, help="Test ratio")
|
| 159 |
+
parser.add_argument("--seed", type=int, default=42, help="Random seed")
|
| 160 |
+
parser.add_argument("--hash", action="store_true", help="Use hash-based split")
|
| 161 |
+
|
| 162 |
+
args = parser.parse_args()
|
| 163 |
+
|
| 164 |
+
print("=" * 60)
|
| 165 |
+
print("✂️ Dataset Splitter")
|
| 166 |
+
print("=" * 60)
|
| 167 |
+
|
| 168 |
+
# Load data
|
| 169 |
+
print(f"\n📥 Loading: {args.input}")
|
| 170 |
+
items = load_jsonl(args.input)
|
| 171 |
+
print(f" Loaded {len(items)} items")
|
| 172 |
+
|
| 173 |
+
# Configure split
|
| 174 |
+
config = SplitConfig(
|
| 175 |
+
train_ratio=args.train_ratio,
|
| 176 |
+
val_ratio=args.val_ratio,
|
| 177 |
+
test_ratio=args.test_ratio,
|
| 178 |
+
seed=args.seed,
|
| 179 |
+
hash_split=args.hash
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
# Split
|
| 183 |
+
print("\n✂️ Splitting dataset...")
|
| 184 |
+
splits = split_dataset(items, config)
|
| 185 |
+
|
| 186 |
+
for split_type, split_items in splits.items():
|
| 187 |
+
print(f" {split_type.value}: {len(split_items)} items")
|
| 188 |
+
|
| 189 |
+
# Save splits
|
| 190 |
+
output_dir = Path(args.output_dir)
|
| 191 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 192 |
+
|
| 193 |
+
print(f"\n💾 Saving to: {output_dir}")
|
| 194 |
+
for split_type, split_items in splits.items():
|
| 195 |
+
output_file = output_dir / f"{split_type.value}.jsonl"
|
| 196 |
+
save_jsonl(str(output_file), split_items)
|
| 197 |
+
print(f" ✅ {output_file.name}: {len(split_items)} items")
|
| 198 |
+
|
| 199 |
+
print("\n" + "=" * 60)
|
| 200 |
+
print("✅ Split complete!")
|
| 201 |
+
print("=" * 60)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
if __name__ == "__main__":
|
| 205 |
+
main()
|
scripts/validate_dataset.py
ADDED
|
@@ -0,0 +1,249 @@
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dataset Validation Script
|
| 2 |
+
|
| 3 |
+
Validates burme-coder-max dataset quality and format.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import json
|
| 7 |
+
import re
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Dict, List, Tuple
|
| 10 |
+
from dataclasses import dataclass
|
| 11 |
+
from datetime import datetime
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@dataclass
|
| 15 |
+
class ValidationError:
|
| 16 |
+
"""Validation error."""
|
| 17 |
+
line: int
|
| 18 |
+
field: str
|
| 19 |
+
message: str
|
| 20 |
+
severity: str = "error"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class DatasetValidator:
|
| 24 |
+
"""Validate the burme-coder-max dataset."""
|
| 25 |
+
|
| 26 |
+
# Validation rules
|
| 27 |
+
REQUIRED_FIELDS = ["system", "instruction", "response"]
|
| 28 |
+
MIN_RESPONSE_LENGTH = 20
|
| 29 |
+
MAX_RESPONSE_LENGTH = 10000
|
| 30 |
+
MIN_INSTRUCTION_LENGTH = 3
|
| 31 |
+
|
| 32 |
+
# Myanmar text pattern
|
| 33 |
+
MYANMAR_PATTERN = re.compile(r"[\u1000-\u109f\uAA60-\uAA7f]+")
|
| 34 |
+
|
| 35 |
+
def __init__(self, data_dir: str):
|
| 36 |
+
self.data_dir = Path(data_dir)
|
| 37 |
+
self.errors: List[ValidationError] = []
|
| 38 |
+
self.warnings: List[ValidationError] = []
|
| 39 |
+
|
| 40 |
+
def validate_file(self, file_path: str) -> Tuple[bool, List[Dict]]:
|
| 41 |
+
"""Validate a single data file."""
|
| 42 |
+
items = []
|
| 43 |
+
self.errors = []
|
| 44 |
+
self.warnings = []
|
| 45 |
+
|
| 46 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
| 47 |
+
for line_num, line in enumerate(f, 1):
|
| 48 |
+
if not line.strip():
|
| 49 |
+
continue
|
| 50 |
+
|
| 51 |
+
try:
|
| 52 |
+
item = json.loads(line)
|
| 53 |
+
items.append(item)
|
| 54 |
+
self._validate_item(item, line_num)
|
| 55 |
+
except json.JSONDecodeError as e:
|
| 56 |
+
self.errors.append(ValidationError(
|
| 57 |
+
line=line_num,
|
| 58 |
+
field="json",
|
| 59 |
+
message=f"Invalid JSON: {e}",
|
| 60 |
+
severity="error"
|
| 61 |
+
))
|
| 62 |
+
|
| 63 |
+
return len(self errors) == 0, items
|
| 64 |
+
|
| 65 |
+
def _validate_item(self, item: Dict, line_num: int):
|
| 66 |
+
"""Validate a single item."""
|
| 67 |
+
# Check required fields
|
| 68 |
+
for field in self.REQUIRED_FIELDS:
|
| 69 |
+
if field not in item:
|
| 70 |
+
self.errors.append(ValidationError(
|
| 71 |
+
line=line_num,
|
| 72 |
+
field=field,
|
| 73 |
+
message=f"Missing required field: {field}",
|
| 74 |
+
severity="error"
|
| 75 |
+
))
|
| 76 |
+
return
|
| 77 |
+
elif not isinstance(item[field], str):
|
| 78 |
+
self.errors.append(ValidationError(
|
| 79 |
+
line=line_num,
|
| 80 |
+
field=field,
|
| 81 |
+
message=f"Field {field} must be string",
|
| 82 |
+
severity="error"
|
| 83 |
+
))
|
| 84 |
+
|
| 85 |
+
# Check field lengths
|
| 86 |
+
response_len = len(item["response"])
|
| 87 |
+
if response_len < self.MIN_RESPONSE_LENGTH:
|
| 88 |
+
self.warnings.append(ValidationError(
|
| 89 |
+
line=line_num,
|
| 90 |
+
field="response",
|
| 91 |
+
message=f"Response too short ({response_len} chars)",
|
| 92 |
+
severity="warning"
|
| 93 |
+
))
|
| 94 |
+
|
| 95 |
+
if response_len > self.MAX_RESPONSE_LENGTH:
|
| 96 |
+
self.warnings.append(ValidationError(
|
| 97 |
+
line=line_num,
|
| 98 |
+
field="response",
|
| 99 |
+
message=f"Response too long ({response_len} chars)"
|
| 100 |
+
))
|
| 101 |
+
|
| 102 |
+
instruction_len = len(item["instruction"])
|
| 103 |
+
if instruction_len < self.MIN_INSTRUCTION_LENGTH:
|
| 104 |
+
self.errors.append(ValidationError(
|
| 105 |
+
line=line_num,
|
| 106 |
+
field="instruction",
|
| 107 |
+
message=f"Instruction too short ({instruction_len} chars)"
|
| 108 |
+
))
|
| 109 |
+
|
| 110 |
+
# Check for code blocks
|
| 111 |
+
if "```" not in item["response"]:
|
| 112 |
+
self.warnings.append(ValidationError(
|
| 113 |
+
line=line_num,
|
| 114 |
+
field="response",
|
| 115 |
+
message="Response missing code block"
|
| 116 |
+
))
|
| 117 |
+
|
| 118 |
+
# Check for language consistency
|
| 119 |
+
instruction_text = item["instruction"].lower()
|
| 120 |
+
response_text = item["response"]
|
| 121 |
+
|
| 122 |
+
# Count code blocks by language
|
| 123 |
+
code_blocks = re.findall(r"```(\w*)", response_text)
|
| 124 |
+
languages = set(code_blocks)
|
| 125 |
+
|
| 126 |
+
# Suggestion: if instruction mentions a language, include it in response
|
| 127 |
+
for lang in ["python", "javascript", "typescript", "java", "sql", "go", "rust"]:
|
| 128 |
+
if lang in instruction_text and lang.lower() not in languages:
|
| 129 |
+
self.warnings.append(ValidationError(
|
| 130 |
+
line=line_num,
|
| 131 |
+
field="response",
|
| 132 |
+
message=f"Instruction mentions '{lang}' but no code block found"
|
| 133 |
+
))
|
| 134 |
+
|
| 135 |
+
def get_stats(self, items: List[Dict]) -> Dict:
|
| 136 |
+
"""Get dataset statistics."""
|
| 137 |
+
stats = {
|
| 138 |
+
"total_items": len(items),
|
| 139 |
+
"timestamp": datetime.now().isoformat(),
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
if not items:
|
| 143 |
+
return stats
|
| 144 |
+
|
| 145 |
+
# Length statistics
|
| 146 |
+
response_lengths = [len(item["response"]) for item in items]
|
| 147 |
+
instruction_lengths = [len(item["instruction"]) for item in items]
|
| 148 |
+
|
| 149 |
+
stats["response"] = {
|
| 150 |
+
"avg_length": sum(response_lengths) / len(response_lengths),
|
| 151 |
+
"min_length": min(response_lengths),
|
| 152 |
+
"max_length": max(response_lengths),
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
stats["instruction"] = {
|
| 156 |
+
"avg_length": sum(instruction_lengths) / len(instruction_lengths),
|
| 157 |
+
"min_length": min(instruction_lengths),
|
| 158 |
+
"max_length": max(instruction_lengths),
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
# Language distribution
|
| 162 |
+
all_languages = []
|
| 163 |
+
for item in items:
|
| 164 |
+
code_blocks = re.findall(r"```(\w*)", item["response"])
|
| 165 |
+
all_languages.extend([lang for lang in code_blocks if lang])
|
| 166 |
+
|
| 167 |
+
from collections import Counter
|
| 168 |
+
lang_counts = Counter(all_languages)
|
| 169 |
+
stats["languages"] = dict(lang_counts)
|
| 170 |
+
|
| 171 |
+
# Myanmar content
|
| 172 |
+
myanmar_count = sum(
|
| 173 |
+
1 for item in items
|
| 174 |
+
if self.MYANMAR_PATTERN.search(item["instruction"])
|
| 175 |
+
)
|
| 176 |
+
stats["myanmar_items"] = myanmar_count
|
| 177 |
+
stats["myanmar_percentage"] = (myanmar_count / len(items)) * 100 if items else 0
|
| 178 |
+
|
| 179 |
+
# System prompts
|
| 180 |
+
systems = set(item["system"] for item in items)
|
| 181 |
+
stats["unique_systems"] = len(systems)
|
| 182 |
+
|
| 183 |
+
return stats
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def main():
|
| 187 |
+
"""Run validation."""
|
| 188 |
+
import sys
|
| 189 |
+
|
| 190 |
+
print("=" * 60)
|
| 191 |
+
print("📊 Burme-Coder-Max Dataset Validator")
|
| 192 |
+
print("=" * 60)
|
| 193 |
+
|
| 194 |
+
data_dir = Path(__file__).parent.parent / "data" / "knowledge"
|
| 195 |
+
validator = DatasetValidator(str(data_dir))
|
| 196 |
+
|
| 197 |
+
# Find JSONL files
|
| 198 |
+
jsonl_files = list(Path(".").rglob("*.jsonl"))
|
| 199 |
+
if not jsonl_files:
|
| 200 |
+
print("⚠️ No JSONL files found")
|
| 201 |
+
sys.exit(1)
|
| 202 |
+
|
| 203 |
+
total_errors = 0
|
| 204 |
+
total_warnings = 0
|
| 205 |
+
total_items = 0
|
| 206 |
+
|
| 207 |
+
for jsonl_file in jsonl_files:
|
| 208 |
+
print(f"\n📁 Validating: {jsonl_file.name}")
|
| 209 |
+
|
| 210 |
+
valid, items = validator.validate_file(str(jsonl_file))
|
| 211 |
+
total_items += len(items)
|
| 212 |
+
|
| 213 |
+
if validator.errors:
|
| 214 |
+
print(f" ❌ {len(validator.errors)} errors:")
|
| 215 |
+
for err in validator.errors[:10]:
|
| 216 |
+
print(f" Line {err.line}: {err.field} - {err.message}")
|
| 217 |
+
|
| 218 |
+
if validator.warnings:
|
| 219 |
+
print(f" ⚠️ {len(validator.warnings)} warnings:")
|
| 220 |
+
for warn in validator.warnings[:5]:
|
| 221 |
+
print(f" Line {warn.line}: {warn.field} - {warn.message}")
|
| 222 |
+
|
| 223 |
+
if valid and not validator.errors:
|
| 224 |
+
print(" ✅ Valid")
|
| 225 |
+
|
| 226 |
+
total_errors += len(validator.errors)
|
| 227 |
+
total_warnings += len(validator.warnings)
|
| 228 |
+
|
| 229 |
+
# Get overall stats
|
| 230 |
+
if jsonl_files:
|
| 231 |
+
validator.validate_file(str(jsonl_files[0]))
|
| 232 |
+
stats = validator.get_stats([])
|
| 233 |
+
stats["total_items"] = total_items
|
| 234 |
+
|
| 235 |
+
print("\n📈 Overall Statistics:")
|
| 236 |
+
print(f" Total items: {stats['total_items']}")
|
| 237 |
+
print(f" Total errors: {total_errors}")
|
| 238 |
+
print(f" Total warnings: {total_warnings}")
|
| 239 |
+
|
| 240 |
+
print("\n" + "=" * 60)
|
| 241 |
+
if total_errors == 0:
|
| 242 |
+
print("✅ Validation passed!")
|
| 243 |
+
else:
|
| 244 |
+
print(f"❌ {total_errors} errors found, {total_warnings} warnings")
|
| 245 |
+
print("=" * 60)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
if __name__ == "__main__":
|
| 249 |
+
main()
|
src/data_processing.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Data Validation and Split Module
|
| 2 |
+
|
| 3 |
+
Validates and splits datasets for training/validation/testing.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import json
|
| 7 |
+
import random
|
| 8 |
+
import hashlib
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import List, Dict, Tuple, Optional, Callable
|
| 11 |
+
from dataclasses import dataclass
|
| 12 |
+
from enum import Enum
|
| 13 |
+
import re
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class SplitType(Enum):
|
| 17 |
+
"""Dataset split types."""
|
| 18 |
+
|
| 19 |
+
TRAIN = "train"
|
| 20 |
+
VALIDATION = "validation"
|
| 21 |
+
TEST = "test"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@dataclass
|
| 25 |
+
class DatasetItem:
|
| 26 |
+
"""Single dataset item."""
|
| 27 |
+
|
| 28 |
+
system: str
|
| 29 |
+
instruction: str
|
| 30 |
+
response: str
|
| 31 |
+
metadata: Dict
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@dataclass
|
| 35 |
+
class ValidationResult:
|
| 36 |
+
"""Validation result."""
|
| 37 |
+
|
| 38 |
+
valid: bool
|
| 39 |
+
errors: List[str]
|
| 40 |
+
warnings: List[str]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class DataValidator:
|
| 44 |
+
"""Validate dataset items."""
|
| 45 |
+
|
| 46 |
+
MIN_RESPONSE_LENGTH = 10
|
| 47 |
+
MAX_RESPONSE_LENGTH = 10000
|
| 48 |
+
MIN_INSTRUCTION_LENGTH = 3
|
| 49 |
+
|
| 50 |
+
@classmethod
|
| 51 |
+
def validate_item(cls, item: Dict) -> ValidationResult:
|
| 52 |
+
"""Validate a single dataset item."""
|
| 53 |
+
errors = []
|
| 54 |
+
warnings = []
|
| 55 |
+
|
| 56 |
+
# Check required fields
|
| 57 |
+
required_fields = ["system", "instruction", "response"]
|
| 58 |
+
for field in required_fields:
|
| 59 |
+
if field not in item:
|
| 60 |
+
errors.append(f"Missing required field: {field}")
|
| 61 |
+
elif not isinstance(item[field], str):
|
| 62 |
+
errors.append(f"Field '{field}' must be a string")
|
| 63 |
+
|
| 64 |
+
if errors:
|
| 65 |
+
return ValidationResult(valid=False, errors=errors, warnings=warnings)
|
| 66 |
+
|
| 67 |
+
# Validate lengths
|
| 68 |
+
if len(item["response"]) < cls.MIN_RESPONSE_LENGTH:
|
| 69 |
+
errors.append(f"Response too short: {len(item['response'])} chars")
|
| 70 |
+
|
| 71 |
+
if len(item["response"]) > cls.MAX_RESPONSE_LENGTH:
|
| 72 |
+
warnings.append(f"Response very long: {len(item['response'])} chars")
|
| 73 |
+
|
| 74 |
+
if len(item["instruction"]) < cls.MIN_INSTRUCTION_LENGTH:
|
| 75 |
+
errors.append(f"Instruction too short: {len(item['instruction'])} chars")
|
| 76 |
+
|
| 77 |
+
# Check for code blocks
|
| 78 |
+
if "```" not in item["response"]:
|
| 79 |
+
warnings.append("Response contains no code blocks")
|
| 80 |
+
|
| 81 |
+
# Check for Myanmar content
|
| 82 |
+
myanmar_pattern = re.compile(r"[\u1000-\u109f]+")
|
| 83 |
+
has_myanmar = bool(myanmar_pattern.search(item["instruction"]))
|
| 84 |
+
|
| 85 |
+
if not has_myanmar and not has_myanmar:
|
| 86 |
+
warnings.append("No Myanmar text found")
|
| 87 |
+
|
| 88 |
+
return ValidationResult(
|
| 89 |
+
valid=len(errors) == 0,
|
| 90 |
+
errors=errors,
|
| 91 |
+
warnings=warnings
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
@classmethod
|
| 95 |
+
def validate_dataset(cls, items: List[Dict]) -> Tuple[List[Dict], List[Dict]]:
|
| 96 |
+
"""Validate entire dataset, return valid and invalid items."""
|
| 97 |
+
valid = []
|
| 98 |
+
invalid = []
|
| 99 |
+
|
| 100 |
+
for item in items:
|
| 101 |
+
result = cls.validate_item(item)
|
| 102 |
+
if result.valid:
|
| 103 |
+
valid.append(item)
|
| 104 |
+
else:
|
| 105 |
+
invalid.append({**item, "validation_errors": result.errors})
|
| 106 |
+
|
| 107 |
+
return valid, invalid
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class DataSplitter:
|
| 111 |
+
"""Split dataset into train/validation/test sets."""
|
| 112 |
+
|
| 113 |
+
def __init__(self, train_ratio: float = 0.7, val_ratio: float = 0.15, test_ratio: float = 0.15):
|
| 114 |
+
self.train_ratio = train_ratio
|
| 115 |
+
self.val_ratio = val_ratio
|
| 116 |
+
self.test_ratio = test_ratio
|
| 117 |
+
|
| 118 |
+
assert abs(train_ratio + val_ratio + test_ratio - 1.0) < 0.001, "Ratios must sum to 1.0"
|
| 119 |
+
|
| 120 |
+
def split(
|
| 121 |
+
self,
|
| 122 |
+
items: List[Dict],
|
| 123 |
+
stratify_by: Optional[Callable] = None
|
| 124 |
+
) -> Dict[SplitType, List[Dict]]:
|
| 125 |
+
"""Split dataset with optional stratification."""
|
| 126 |
+
if stratify_by:
|
| 127 |
+
return self._stratified_split(items, stratify_by)
|
| 128 |
+
else:
|
| 129 |
+
return self._random_split(items)
|
| 130 |
+
|
| 131 |
+
def _random_split(self, items: List[Dict]) -> Dict[SplitType, List[Dict]]:
|
| 132 |
+
"""Randomly split dataset."""
|
| 133 |
+
shuffled = items.copy()
|
| 134 |
+
random.shuffle(shuffled)
|
| 135 |
+
|
| 136 |
+
total = len(shuffled)
|
| 137 |
+
train_size = int(total * self.train_ratio)
|
| 138 |
+
val_size = int(total * self.val_ratio)
|
| 139 |
+
|
| 140 |
+
return {
|
| 141 |
+
SplitType.TRAIN: shuffled[:train_size],
|
| 142 |
+
SplitType.VALIDATION: shuffled[train_size:train_size + val_size],
|
| 143 |
+
SplitType.TEST: shuffled[train_size + val_size:]
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
def _stratified_split(
|
| 147 |
+
self,
|
| 148 |
+
items: List[Dict],
|
| 149 |
+
stratify_by: Callable
|
| 150 |
+
) -> Dict[SplitType, List[Dict]]:
|
| 151 |
+
"""Split with stratification by a key function."""
|
| 152 |
+
buckets: Dict[str, List[Dict]] = {}
|
| 153 |
+
|
| 154 |
+
for item in items:
|
| 155 |
+
key = stratify_by(item)
|
| 156 |
+
if key not in buckets:
|
| 157 |
+
buckets[key] = []
|
| 158 |
+
buckets[key].append(item)
|
| 159 |
+
|
| 160 |
+
train_buckets = {k: [] for k in buckets}
|
| 161 |
+
val_buckets = {k: [] for k in buckets}
|
| 162 |
+
test_buckets = {k: [] for k in buckets}
|
| 163 |
+
|
| 164 |
+
for key, bucket_items in buckets.items():
|
| 165 |
+
random.shuffle(bucket_items)
|
| 166 |
+
total = len(bucket_items)
|
| 167 |
+
train_size = int(total * self.train_ratio)
|
| 168 |
+
val_size = int(total * self.val_ratio)
|
| 169 |
+
|
| 170 |
+
train_buckets[key] = bucket_items[:train_size]
|
| 171 |
+
val_buckets[key] = bucket_items[train_size:train_size + val_size]
|
| 172 |
+
test_buckets[key] = bucket_items[train_size + val_size:]
|
| 173 |
+
|
| 174 |
+
return {
|
| 175 |
+
SplitType.TRAIN: [item for bucket in train_buckets.values() for item in bucket],
|
| 176 |
+
SplitType.VALIDATION: [item for bucket in val_buckets.values() for item in bucket],
|
| 177 |
+
SplitType.TEST: [item for bucket in test_buckets.values() for item in bucket],
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
def hash_split(self, items: List[Dict], salt: str = "") -> Dict[SplitType, List[Dict]]:
|
| 181 |
+
"""Split based on hash for reproducibility."""
|
| 182 |
+
result = {SplitType.TRAIN: [], SplitType.VALIDATION: [], SplitType.TEST: []}
|
| 183 |
+
|
| 184 |
+
for item in items:
|
| 185 |
+
hash_val = hashlib.md5(
|
| 186 |
+
f"{json.dumps(item, sort_keys=True)}{salt}".encode()
|
| 187 |
+
).hexdigest()
|
| 188 |
+
|
| 189 |
+
hash_num = int(hash_val[:8], 16)
|
| 190 |
+
normalized = hash_num / 0xFFFFFFFF
|
| 191 |
+
|
| 192 |
+
if normalized < self.train_ratio:
|
| 193 |
+
result[SplitType.TRAIN].append(item)
|
| 194 |
+
elif normalized < self.train_ratio + self.val_ratio:
|
| 195 |
+
result[SplitType.VALIDATION].append(item)
|
| 196 |
+
else:
|
| 197 |
+
result[SplitType.TEST].append(item)
|
| 198 |
+
|
| 199 |
+
return result
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
class DatasetManager:
|
| 203 |
+
"""Manage dataset operations."""
|
| 204 |
+
|
| 205 |
+
@staticmethod
|
| 206 |
+
def load_jsonl(file_path: str) -> List[Dict]:
|
| 207 |
+
"""Load data from JSONL file."""
|
| 208 |
+
items = []
|
| 209 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
| 210 |
+
for line in f:
|
| 211 |
+
if line.strip():
|
| 212 |
+
items.append(json.loads(line))
|
| 213 |
+
return items
|
| 214 |
+
|
| 215 |
+
@staticmethod
|
| 216 |
+
def save_jsonl(file_path: str, items: List[Dict]):
|
| 217 |
+
"""Save data to JSONL file."""
|
| 218 |
+
Path(file_path).parent.mkdir(parents=True, exist_ok=True)
|
| 219 |
+
with open(file_path, "w", encoding="utf-8") as f:
|
| 220 |
+
for item in items:
|
| 221 |
+
f.write(json.dumps(item, ensure_ascii=False) + "\n")
|
| 222 |
+
|
| 223 |
+
@staticmethod
|
| 224 |
+
def load_json(file_path: str) -> List[Dict]:
|
| 225 |
+
"""Load data from JSON file."""
|
| 226 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
| 227 |
+
data = json.load(f)
|
| 228 |
+
return data if isinstance(data, list) else data.get("data", data.get("items", [data]))
|
| 229 |
+
|
| 230 |
+
@staticmethod
|
| 231 |
+
def save_json(file_path: str, items: List[Dict]):
|
| 232 |
+
"""Save data to JSON file."""
|
| 233 |
+
Path(file_path).parent.mkdir(parents=True, exist_ok=True)
|
| 234 |
+
with open(file_path, "w", encoding="utf-8") as f:
|
| 235 |
+
json.dump(items, f, indent=2, ensure_ascii=False)
|
| 236 |
+
|
| 237 |
+
@staticmethod
|
| 238 |
+
def save_split(
|
| 239 |
+
output_dir: str,
|
| 240 |
+
splits: Dict[SplitType, List[Dict]],
|
| 241 |
+
format: str = "jsonl"
|
| 242 |
+
):
|
| 243 |
+
"""Save split datasets to files."""
|
| 244 |
+
output_path = Path(output_dir)
|
| 245 |
+
output_path.mkdir(parents=True, exist_ok=True)
|
| 246 |
+
|
| 247 |
+
for split_type, items in splits.items():
|
| 248 |
+
file_path = output_path / f"{split_type.value}.jsonl"
|
| 249 |
+
DatasetManager.save_jsonl(str(file_path), items)
|
| 250 |
+
|
| 251 |
+
@staticmethod
|
| 252 |
+
def get_dataset_stats(items: List[Dict]) -> Dict:
|
| 253 |
+
"""Get statistics about a dataset."""
|
| 254 |
+
if not items:
|
| 255 |
+
return {"count": 0}
|
| 256 |
+
|
| 257 |
+
response_lengths = [len(item.get("response", "")) for item in items]
|
| 258 |
+
instruction_lengths = [len(item.get("instruction", "")) for item in items]
|
| 259 |
+
|
| 260 |
+
systems = [item.get("system", "") for item in items]
|
| 261 |
+
unique_systems = len(set(systems))
|
| 262 |
+
|
| 263 |
+
return {
|
| 264 |
+
"count": len(items),
|
| 265 |
+
"avg_response_length": sum(response_lengths) / len(response_lengths),
|
| 266 |
+
"min_response_length": min(response_lengths),
|
| 267 |
+
"max_response_length": max(response_lengths),
|
| 268 |
+
"avg_instruction_length": sum(instruction_lengths) / len(instruction_lengths),
|
| 269 |
+
"unique_systems": unique_systems,
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def main():
|
| 274 |
+
"""Demo the data validation and split module."""
|
| 275 |
+
print("=" * 50)
|
| 276 |
+
print("📊 Data Validation and Split Demo")
|
| 277 |
+
print("=" * 50)
|
| 278 |
+
|
| 279 |
+
# Sample data
|
| 280 |
+
sample_data = [
|
| 281 |
+
{
|
| 282 |
+
"system": "Expert Python programmer",
|
| 283 |
+
"instruction": "Python decorator hta ya py",
|
| 284 |
+
"response": "# Python Decorator\n```python\ndef decorator(func):\n return func\n```"
|
| 285 |
+
},
|
| 286 |
+
{
|
| 287 |
+
"system": "Expert JavaScript developer",
|
| 288 |
+
"instruction": "JavaScript async/await hta ya",
|
| 289 |
+
"response": "// Async/Await\nasync function fetch() {\n const data = await fetch('/api');\n}"
|
| 290 |
+
},
|
| 291 |
+
{
|
| 292 |
+
"system": "Database expert",
|
| 293 |
+
"instruction": "SQL JOIN operations",
|
| 294 |
+
"response": "-- SQL JOIN\nSELECT * FROM a INNER JOIN b ON a.id = b.id;"
|
| 295 |
+
},
|
| 296 |
+
] * 10 # Multiply for demo
|
| 297 |
+
|
| 298 |
+
print(f"\n📁 Sample data: {len(sample_data)} items")
|
| 299 |
+
|
| 300 |
+
# Validate
|
| 301 |
+
print("\n🔍 Validating data...")
|
| 302 |
+
validator = DataValidator()
|
| 303 |
+
valid, invalid = validator.validate_dataset(sample_data)
|
| 304 |
+
print(f" ✓ Valid: {len(valid)}")
|
| 305 |
+
print(f" ✗ Invalid: {len(invalid)}")
|
| 306 |
+
|
| 307 |
+
# Split
|
| 308 |
+
print("\n✂️ Splitting data (70/15/15)...")
|
| 309 |
+
splitter = DataSplitter()
|
| 310 |
+
splits = splitter.hash_split(sample_data, salt="burme-coder-v1")
|
| 311 |
+
|
| 312 |
+
for split_type, items in splits.items():
|
| 313 |
+
print(f" {split_type.value}: {len(items)} items")
|
| 314 |
+
|
| 315 |
+
# Stats
|
| 316 |
+
print("\n📈 Dataset statistics:")
|
| 317 |
+
stats = DatasetManager.get_dataset_stats(valid)
|
| 318 |
+
for key, value in stats.items():
|
| 319 |
+
print(f" {key}: {value:.2f}" if isinstance(value, float) else f" {key}: {value}")
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
if __name__ == "__main__":
|
| 323 |
+
main()
|
tests/test_qa.py
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Quality Assurance Testing Suite
|
| 2 |
+
|
| 3 |
+
Comprehensive QA tests for burme-coder-max project.
|
| 4 |
+
Covers: Code Quality, Functionality, Performance, Security.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import pytest
|
| 8 |
+
import ast
|
| 9 |
+
import os
|
| 10 |
+
import re
|
| 11 |
+
import sys
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import List, Dict, Tuple
|
| 14 |
+
|
| 15 |
+
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class TestCodeQuality:
|
| 19 |
+
"""Code quality validation tests."""
|
| 20 |
+
|
| 21 |
+
PROJECT_ROOT = Path(__file__).parent.parent
|
| 22 |
+
|
| 23 |
+
def test_python_syntax(self):
|
| 24 |
+
"""Verify all Python files have valid syntax."""
|
| 25 |
+
errors = []
|
| 26 |
+
for py_file in self.PROJECT_ROOT.rglob("*.py"):
|
| 27 |
+
if ".venv" in str(py_file) or "venv" in str(py_file):
|
| 28 |
+
continue
|
| 29 |
+
try:
|
| 30 |
+
content = py_file.read_text(encoding="utf-8")
|
| 31 |
+
ast.parse(content)
|
| 32 |
+
except SyntaxError as e:
|
| 33 |
+
errors.append(f"{py_file}: {e}")
|
| 34 |
+
|
| 35 |
+
assert not errors, f"Syntax errors found:\n" + "\n".join(errors)
|
| 36 |
+
|
| 37 |
+
def test_docstrings_present(self):
|
| 38 |
+
"""Check module-level docstrings exist."""
|
| 39 |
+
missing_docs = []
|
| 40 |
+
for py_file in (self.PROJECT_ROOT / "src").rglob("*.py"):
|
| 41 |
+
if py_file.name == "__init__.py":
|
| 42 |
+
continue
|
| 43 |
+
content = py_file.read_text(encoding="utf-8")
|
| 44 |
+
if '"""' not in content and "'''" not in content:
|
| 45 |
+
missing_docs.append(py_file.name)
|
| 46 |
+
|
| 47 |
+
assert not missing_docs, f"Missing docstrings in: {missing_docs}"
|
| 48 |
+
|
| 49 |
+
def test_imports_are_valid(self):
|
| 50 |
+
"""Verify all imports can be resolved."""
|
| 51 |
+
for py_file in (self.PROJECT_ROOT / "src").rglob("*.py"):
|
| 52 |
+
content = py_file.read_text(encoding="utf-8")
|
| 53 |
+
tree = ast.parse(content)
|
| 54 |
+
for node in ast.walk(tree):
|
| 55 |
+
if isinstance(node, ast.Import):
|
| 56 |
+
for alias in node.names:
|
| 57 |
+
# Skip relative imports and external packages
|
| 58 |
+
if not alias.name.startswith(".") and not alias.name.startswith("_"):
|
| 59 |
+
pass # External packages assumed valid
|
| 60 |
+
elif isinstance(node, ast.ImportFrom):
|
| 61 |
+
module = node.module or ""
|
| 62 |
+
if module.startswith("_"):
|
| 63 |
+
pytest.fail(f"Import from private module: {module} in {py_file}")
|
| 64 |
+
|
| 65 |
+
def test_no_debug_code(self):
|
| 66 |
+
"""Check for debug/ad-hoc code."""
|
| 67 |
+
debug_patterns = [
|
| 68 |
+
r"print\s*\(\s*debug",
|
| 69 |
+
r"print\s*\(\s*TODO",
|
| 70 |
+
r"print\s*\(\s*FIXME",
|
| 71 |
+
r"print\s*\(\s*console\.log",
|
| 72 |
+
r"import\s+pdb",
|
| 73 |
+
r"import\s+ipdb",
|
| 74 |
+
]
|
| 75 |
+
violations = []
|
| 76 |
+
for py_file in (self.PROJECT_ROOT / "src").rglob("*.py"):
|
| 77 |
+
content = py_file.read_text(encoding="utf-8")
|
| 78 |
+
for pattern in debug_patterns:
|
| 79 |
+
if re.search(pattern, content, re.IGNORECASE):
|
| 80 |
+
violations.append(f"{py_file.name}: {pattern}")
|
| 81 |
+
|
| 82 |
+
assert not violations, f"Debug code found:\n{violations}"
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class TestFunctionality:
|
| 86 |
+
"""Functional tests for core modules."""
|
| 87 |
+
|
| 88 |
+
def test_agent_initialization(self):
|
| 89 |
+
"""Test CoderAgent can be initialized."""
|
| 90 |
+
from core.agent import CoderAgent
|
| 91 |
+
agent = CoderAgent()
|
| 92 |
+
assert agent is not None
|
| 93 |
+
assert agent.model == "gpt-4"
|
| 94 |
+
assert agent.session_id is not None
|
| 95 |
+
|
| 96 |
+
def test_agent_generate_response(self):
|
| 97 |
+
"""Test response generation returns expected structure."""
|
| 98 |
+
from core.agent import CoderAgent
|
| 99 |
+
agent = CoderAgent()
|
| 100 |
+
response = agent.generate_response("test instruction")
|
| 101 |
+
|
| 102 |
+
assert "session_id" in response
|
| 103 |
+
assert "instruction" in response
|
| 104 |
+
assert "response" in response
|
| 105 |
+
assert "timestamp" in response
|
| 106 |
+
assert "model" in response
|
| 107 |
+
|
| 108 |
+
def test_executor_initialization(self):
|
| 109 |
+
"""Test CodeExecutor initialization."""
|
| 110 |
+
from core.executor import CodeExecutor, ExecutionResult
|
| 111 |
+
executor = CodeExecutor(timeout=10)
|
| 112 |
+
assert executor.timeout == 10
|
| 113 |
+
assert executor.execution_count == 0
|
| 114 |
+
|
| 115 |
+
def test_validator_initialization(self):
|
| 116 |
+
"""Test ResponseValidator initialization."""
|
| 117 |
+
from core.validator import ResponseValidator, ValidationResult
|
| 118 |
+
validator = ResponseValidator()
|
| 119 |
+
result = validator.validate("def test(): pass", "test function")
|
| 120 |
+
|
| 121 |
+
assert isinstance(result, ValidationResult)
|
| 122 |
+
assert hasattr(result, "quality")
|
| 123 |
+
assert hasattr(result, "score")
|
| 124 |
+
assert hasattr(result, "issues")
|
| 125 |
+
|
| 126 |
+
def test_animation_configs(self):
|
| 127 |
+
"""Test all animation classes are importable."""
|
| 128 |
+
from animations import Spinner, ProgressBar, ParticleBurst, TypingEffect
|
| 129 |
+
assert Spinner is not None
|
| 130 |
+
assert ProgressBar is not None
|
| 131 |
+
assert ParticleBurst is not None
|
| 132 |
+
assert TypingEffect is not None
|
| 133 |
+
|
| 134 |
+
def test_knowledge_base_search(self):
|
| 135 |
+
"""Test LocalKB search functionality."""
|
| 136 |
+
from knowledge import LocalKB
|
| 137 |
+
kb = LocalKB()
|
| 138 |
+
results = kb.search("python")
|
| 139 |
+
assert isinstance(results, list)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class TestSecurity:
|
| 143 |
+
"""Security validation tests."""
|
| 144 |
+
|
| 145 |
+
PROJECT_ROOT = Path(__file__).parent.parent
|
| 146 |
+
|
| 147 |
+
def test_no_hardcoded_secrets(self):
|
| 148 |
+
"""Check for hardcoded passwords/secrets in code."""
|
| 149 |
+
secret_patterns = [
|
| 150 |
+
r"password\s*=\s*['\"][^'\"]{8,}['\"]",
|
| 151 |
+
r"api_key\s*=\s*['\"][^'\"]{20,}['\"]",
|
| 152 |
+
r"secret\s*=\s*['\"][^'\"]{20,}['\"]",
|
| 153 |
+
r"token\s*=\s*['\"][A-Za-z0-9_\-]{30,}['\"]",
|
| 154 |
+
]
|
| 155 |
+
violations = []
|
| 156 |
+
for py_file in (self.PROJECT_ROOT / "src").rglob("*.py"):
|
| 157 |
+
content = py_file.read_text(encoding="utf-8")
|
| 158 |
+
for pattern in secret_patterns:
|
| 159 |
+
if re.search(pattern, content, re.IGNORECASE):
|
| 160 |
+
violations.append(f"{py_file.name}")
|
| 161 |
+
|
| 162 |
+
assert not violations, f"Hardcoded secrets found in: {violations}"
|
| 163 |
+
|
| 164 |
+
def test_sql_injection_protection(self):
|
| 165 |
+
"""Verify SQL queries use parameterized inputs."""
|
| 166 |
+
dangerous_sql = ["SELECT * FROM users WHERE name = '" + "' + user_input + '"]
|
| 167 |
+
violations = []
|
| 168 |
+
for py_file in (self.PROJECT_ROOT / "src").rglob("*.py"):
|
| 169 |
+
content = py_file.read_text(encoding="utf-8")
|
| 170 |
+
if "sql" in content.lower() or "query" in content.lower():
|
| 171 |
+
for dangerous in dangerous_sql:
|
| 172 |
+
if dangerous in content:
|
| 173 |
+
violations.append(py_file.name)
|
| 174 |
+
|
| 175 |
+
assert not violations, f"SQL injection vulnerable code: {violations}"
|
| 176 |
+
|
| 177 |
+
def test_shell_injection_protection(self):
|
| 178 |
+
"""Verify shell commands are safe."""
|
| 179 |
+
from core.executor import CodeExecutor
|
| 180 |
+
executor = CodeExecutor()
|
| 181 |
+
|
| 182 |
+
# Should detect potentially malicious code
|
| 183 |
+
malicious = "__import__('os').system('rm -rf /')"
|
| 184 |
+
result = executor._contains_malicious_code(malicious)
|
| 185 |
+
assert result == True
|
| 186 |
+
|
| 187 |
+
def test_input_validation(self):
|
| 188 |
+
"""Test input validation in key modules."""
|
| 189 |
+
from core.validator import ResponseValidator
|
| 190 |
+
|
| 191 |
+
# Empty response should still validate
|
| 192 |
+
validator = ResponseValidator()
|
| 193 |
+
result = validator.validate("", "test")
|
| 194 |
+
assert result.score >= 0 # Score should be defined
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class TestPerformance:
|
| 198 |
+
"""Performance-related tests."""
|
| 199 |
+
|
| 200 |
+
def test_import_time(self):
|
| 201 |
+
"""Measure import time for core modules."""
|
| 202 |
+
import time
|
| 203 |
+
|
| 204 |
+
start = time.time()
|
| 205 |
+
from core.agent import CoderAgent
|
| 206 |
+
from core.executor import CodeExecutor
|
| 207 |
+
from core.validator import ResponseValidator
|
| 208 |
+
import_duration = time.time() - start
|
| 209 |
+
|
| 210 |
+
# Should import in under 2 seconds
|
| 211 |
+
assert import_duration < 2.0, f"Import took {import_duration}s"
|
| 212 |
+
|
| 213 |
+
def test_agent_response_time(self):
|
| 214 |
+
"""Test response generation time."""
|
| 215 |
+
import time
|
| 216 |
+
from core.agent import CoderAgent
|
| 217 |
+
|
| 218 |
+
agent = CoderAgent()
|
| 219 |
+
start = time.time()
|
| 220 |
+
response = agent.generate_response("test")
|
| 221 |
+
duration = time.time() - start
|
| 222 |
+
|
| 223 |
+
# Should complete in reasonable time
|
| 224 |
+
assert duration < 5.0, f"Response took {duration}s"
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
class TestIntegration:
|
| 228 |
+
"""Integration tests across modules."""
|
| 229 |
+
|
| 230 |
+
def test_full_agent_workflow(self):
|
| 231 |
+
"""Test complete agent workflow."""
|
| 232 |
+
from core.agent import CoderAgent
|
| 233 |
+
from core.validator import ResponseValidator
|
| 234 |
+
|
| 235 |
+
agent = CoderAgent()
|
| 236 |
+
validator = ResponseValidator()
|
| 237 |
+
|
| 238 |
+
instruction = "Write a Python hello world function"
|
| 239 |
+
response = agent.generate_response(instruction)
|
| 240 |
+
validation = validator.validate(response["response"], instruction)
|
| 241 |
+
|
| 242 |
+
assert validation.score > 0
|
| 243 |
+
assert len(response["response"]) > 0
|
| 244 |
+
|
| 245 |
+
def test_animation_with_agent(self):
|
| 246 |
+
"""Test animations working with agent."""
|
| 247 |
+
import time
|
| 248 |
+
from animations import Spinner
|
| 249 |
+
from core.agent import CoderAgent
|
| 250 |
+
|
| 251 |
+
agent = CoderAgent()
|
| 252 |
+
with Spinner("Testing..."):
|
| 253 |
+
response = agent.generate_response("test")
|
| 254 |
+
time.sleep(0.1)
|
| 255 |
+
|
| 256 |
+
assert len(response["response"]) > 0
|
| 257 |
+
|
| 258 |
+
def test_knowledge_with_agent(self):
|
| 259 |
+
"""Test knowledge base integration."""
|
| 260 |
+
from core.agent import CoderAgent
|
| 261 |
+
from knowledge import LocalKB
|
| 262 |
+
|
| 263 |
+
agent = CoderAgent()
|
| 264 |
+
kb = LocalKB()
|
| 265 |
+
|
| 266 |
+
# Create agent with knowledge dir
|
| 267 |
+
agent_with_kb = CoderAgent(
|
| 268 |
+
knowledge_dir=str(Path(__file__).parent.parent / "data" / "knowledge")
|
| 269 |
+
)
|
| 270 |
+
response = agent_with_kb.generate_response("python decorator hta ya")
|
| 271 |
+
|
| 272 |
+
assert len(response["response"]) > 0
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
class TestDocumentation:
|
| 276 |
+
"""Documentation quality tests."""
|
| 277 |
+
|
| 278 |
+
PROJECT_ROOT = Path(__file__).parent.parent
|
| 279 |
+
|
| 280 |
+
def test_readme_exists(self):
|
| 281 |
+
"""Verify README.md exists."""
|
| 282 |
+
readme = self.PROJECT_ROOT / "README.md"
|
| 283 |
+
assert readme.exists(), "README.md not found"
|
| 284 |
+
|
| 285 |
+
def test_readme_has_install_section(self):
|
| 286 |
+
"""Check README has installation instructions."""
|
| 287 |
+
readme = (self.PROJECT_ROOT / "README.md").read_text(encoding="utf-8")
|
| 288 |
+
assert "install" in readme.lower(), "Install section missing"
|
| 289 |
+
|
| 290 |
+
def test_readme_has_usage_section(self):
|
| 291 |
+
"""Check README has usage examples."""
|
| 292 |
+
readme = (self.PROJECT_ROOT / "README.md").read_text(encoding="utf-8")
|
| 293 |
+
assert "usage" in readme.lower() or "example" in readme.lower()
|
| 294 |
+
|
| 295 |
+
def test_docs_directory_exists(self):
|
| 296 |
+
"""Verify docs directory exists."""
|
| 297 |
+
docs_dir = self.PROJECT_ROOT / "docs"
|
| 298 |
+
assert docs_dir.exists(), "docs/ directory not found"
|
| 299 |
+
|
| 300 |
+
def test_all_md_files_have_content(self):
|
| 301 |
+
"""Check all markdown files have substantial content."""
|
| 302 |
+
small_files = []
|
| 303 |
+
for md_file in self.PROJECT_ROOT.rglob("*.md"):
|
| 304 |
+
content = md_file.read_text(encoding="utf-8")
|
| 305 |
+
if len(content) < 100:
|
| 306 |
+
small_files.append(md_file.name)
|
| 307 |
+
|
| 308 |
+
assert not small_files, f"Very short markdown files: {small_files}"
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
class QAReport:
|
| 312 |
+
"""Generate QA report."""
|
| 313 |
+
|
| 314 |
+
CLASSES = [
|
| 315 |
+
TestCodeQuality,
|
| 316 |
+
TestFunctionality,
|
| 317 |
+
TestSecurity,
|
| 318 |
+
TestPerformance,
|
| 319 |
+
TestIntegration,
|
| 320 |
+
TestDocumentation,
|
| 321 |
+
]
|
| 322 |
+
|
| 323 |
+
@classmethod
|
| 324 |
+
def run_all(cls) -> Dict:
|
| 325 |
+
"""Run all test classes and generate report."""
|
| 326 |
+
from collections import defaultdict
|
| 327 |
+
|
| 328 |
+
results = defaultdict(list)
|
| 329 |
+
for test_class in cls.CLASSES:
|
| 330 |
+
class_name = test_class.__name__
|
| 331 |
+
for method_name in dir(test_class):
|
| 332 |
+
if method_name.startswith("test_"):
|
| 333 |
+
try:
|
| 334 |
+
instance = test_class()
|
| 335 |
+
method = getattr(instance, method_name)
|
| 336 |
+
method()
|
| 337 |
+
results[class_name].append({
|
| 338 |
+
"name": method_name,
|
| 339 |
+
"status": "PASS"
|
| 340 |
+
})
|
| 341 |
+
except Exception as e:
|
| 342 |
+
results[class_name].append({
|
| 343 |
+
"name": method_name,
|
| 344 |
+
"status": "FAIL",
|
| 345 |
+
"error": str(e)
|
| 346 |
+
})
|
| 347 |
+
|
| 348 |
+
return dict(results)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
if __name__ == "__main__":
|
| 352 |
+
pytest.main([__file__, "-v", "--tb=short"])
|