File size: 21,803 Bytes
50203b3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 | """
π» EKALAVYA Coding AI - Advanced Code Intelligence
ποΈ Large Project Understanding β’ π§ Refactoring β’ π Debugging β’ π€ Autonomous Agent
"""
import os
import ast
import re
from typing import Dict, List, Optional, Tuple
from pathlib import Path
from dataclasses import dataclass
@dataclass
class CodeFile:
"""π Represents a code file"""
path: str
content: str
language: str
size: int
functions: List[str]
classes: List[str]
imports: List[str]
@dataclass
class CodeIssue:
"""π Represents a code issue"""
file: str
line: int
severity: str # π΄ critical, π‘ warning, π΅ info
message: str
suggestion: str
category: str # bug, security, performance, style
class CodingAI:
"""π» Advanced coding intelligence"""
def __init__(self):
self.codebase_cache = {}
self.analysis_history = []
# ποΈ LARGE PROJECT UNDERSTANDING
def analyze_codebase(self, project_path: str) -> Dict:
"""ποΈ Understand entire codebase structure"""
print(f"ποΈ Analyzing codebase: {project_path}")
codebase = {
"path": project_path,
"files": [],
"languages": {},
"dependencies": {},
"architecture": {},
"complexity": {},
"patterns": []
}
# Walk through project
for root, dirs, files in os.walk(project_path):
# Skip common non-code directories
dirs[:] = [d for d in dirs if d not in ['node_modules', '__pycache__', '.git', 'venv', 'env']]
for file in files:
if file.endswith(('.py', '.js', '.ts', '.java', '.cpp', '.c', '.go', '.rs')):
file_path = os.path.join(root, file)
code_file = self._analyze_file(file_path)
if code_file:
codebase["files"].append(code_file)
# Track languages
lang = code_file.language
codebase["languages"][lang] = codebase["languages"].get(lang, 0) + 1
# Track dependencies
for imp in code_file.imports:
codebase["dependencies"][imp] = codebase["dependencies"].get(imp, 0) + 1
# Analyze architecture
codebase["architecture"] = self._detect_architecture(codebase["files"])
codebase["complexity"] = self._calculate_complexity(codebase["files"])
codebase["patterns"] = self._detect_patterns(codebase["files"])
return {
"status": "β
success",
"analysis": codebase,
"total_files": len(codebase["files"]),
"total_lines": sum(f.size for f in codebase["files"]),
"emoji": "ποΈ",
"message": "ποΈ Codebase analysis complete!"
}
def _analyze_file(self, file_path: str) -> Optional[CodeFile]:
"""π Analyze individual code file"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# Detect language
ext = Path(file_path).suffix
lang_map = {
'.py': 'python', '.js': 'javascript', '.ts': 'typescript',
'.java': 'java', '.cpp': 'cpp', '.c': 'c', '.go': 'go', '.rs': 'rust'
}
language = lang_map.get(ext, 'unknown')
# Extract functions and classes
functions = []
classes = []
imports = []
if language == 'python':
tree = ast.parse(content)
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
functions.append(node.name)
elif isinstance(node, ast.ClassDef):
classes.append(node.name)
elif isinstance(node, ast.Import):
for alias in node.names:
imports.append(alias.name)
elif isinstance(node, ast.ImportFrom):
if node.module:
imports.append(node.module)
else:
# Regex-based extraction for other languages
functions = re.findall(r'function\s+(\w+)|def\s+(\w+)|func\s+(\w+)', content)
classes = re.findall(r'class\s+(\w+)', content)
imports = re.findall(r'import\s+(\w+)|from\s+(\w+)', content)
return CodeFile(
path=file_path,
content=content,
language=language,
size=len(content.split('\n')),
functions=[f for f in functions if f],
classes=classes,
imports=imports
)
except Exception as e:
print(f"β οΈ Error analyzing {file_path}: {e}")
return None
def _detect_architecture(self, files: List[CodeFile]) -> Dict:
"""ποΈ Detect project architecture"""
architecture = {
"type": "unknown",
"patterns": [],
"layers": []
}
# Check for common patterns
has_routes = any('route' in f.path.lower() or 'router' in f.path.lower() for f in files)
has_models = any('model' in f.path.lower() for f in files)
has_views = any('view' in f.path.lower() or 'controller' in f.path.lower() for f in files)
has_services = any('service' in f.path.lower() for f in files)
if has_routes and has_models and has_views:
architecture["type"] = "MVC (Model-View-Controller)"
architecture["patterns"].append("ποΈ MVC Architecture")
elif has_services and has_models:
architecture["type"] = "Service-Oriented"
architecture["patterns"].append("π§ Service Layer")
# Check for microservices
if len([f for f in files if 'api' in f.path.lower()]) > 5:
architecture["patterns"].append("π API-Driven")
return architecture
def _calculate_complexity(self, files: List[CodeFile]) -> Dict:
"""π Calculate code complexity"""
total_functions = sum(len(f.functions) for f in files)
total_classes = sum(len(f.classes) for f in files)
avg_file_size = sum(f.size for f in files) / len(files) if files else 0
return {
"total_functions": total_functions,
"total_classes": total_classes,
"avg_file_size": avg_file_size,
"complexity_score": self._score_complexity(total_functions, total_classes, avg_file_size),
"rating": self._rate_complexity(total_functions, total_classes, avg_file_size)
}
def _score_complexity(self, functions: int, classes: int, avg_size: float) -> int:
"""π Score complexity (0-100)"""
score = min(100, (functions * 2) + (classes * 5) + (avg_size * 0.5))
return int(score)
def _rate_complexity(self, functions: int, classes: int, avg_size: float) -> str:
"""π Rate complexity"""
score = self._score_complexity(functions, classes, avg_size)
if score < 30:
return "π’ Simple"
elif score < 60:
return "π‘ Moderate"
else:
return "π΄ Complex"
def _detect_patterns(self, files: List[CodeFile]) -> List[str]:
"""π Detect code patterns"""
patterns = []
# Check for common patterns
all_content = ' '.join(f.content for f in files)
if 'async def' in all_content or 'async/await' in all_content:
patterns.append("β‘ Asynchronous Programming")
if '@app.route' in all_content or '@router' in all_content:
patterns.append("π RESTful API")
if 'class ' in all_content and 'def __init__' in all_content:
patterns.append("π Object-Oriented Design")
if 'lambda' in all_content or '=>' in all_content:
patterns.append("Ξ» Functional Programming")
if 'try:' in all_content or 'try {' in all_content:
patterns.append("π‘οΈ Error Handling")
if 'def test_' in all_content or 'describe(' in all_content:
patterns.append("π§ͺ Test-Driven Development")
return patterns
# π§ REFACTORING
def refactor_code(self, code: str, language: str = "python", goal: str = "improve") -> Dict:
"""π§ Refactor code"""
print(f"π§ Refactoring {language} code...")
refactored = code
improvements = []
if language == "python":
# PEP 8 improvements
if ' ' not in code and '\t' in code:
refactored = refactored.replace('\t', ' ')
improvements.append("π Converted tabs to spaces (PEP 8)")
# Naming conventions
if re.search(r'def [A-Z]\w+\(', refactored):
improvements.append("π Consider using snake_case for function names")
# Docstrings
if 'def ' in refactored and '"""' not in refactored:
improvements.append("π Add docstrings to functions")
# Type hints
if 'def ' in refactored and '->' not in refactored:
improvements.append("π‘ Add type hints for better code clarity")
# Magic numbers
if re.search(r'[=<>]=?\s*\d{2,}', refactored):
improvements.append("π’ Replace magic numbers with named constants")
elif language in ["javascript", "typescript"]:
# Modern JS improvements
if 'var ' in refactored:
refactored = refactored.replace('var ', 'const ')
improvements.append("π Replaced 'var' with 'const' (modern JS)")
if 'function(' in refactored and '=>' not in refactored:
improvements.append("β‘ Consider using arrow functions")
if 'console.log' in refactored:
improvements.append("ποΈ Remove console.log statements in production")
# Common improvements
if len(refactored.split('\n')) > 50:
improvements.append("π¦ Consider breaking into smaller functions")
if 'if ' in refactored and refactored.count('if ') > 5:
improvements.append("π Consider using polymorphism instead of conditionals")
return {
"status": "β
success",
"original": code,
"refactored": refactored,
"improvements": improvements,
"emoji": "π§",
"message": "π§ Code refactored successfully!"
}
# π DEBUGGING
def debug_code(self, code: str, error_message: str = None) -> Dict:
"""π Debug code and find issues"""
print("π Debugging code...")
issues = []
# Syntax errors
try:
if code.strip().startswith(('def ', 'class ', 'import ', 'from ')):
ast.parse(code)
except SyntaxError as e:
issues.append(CodeIssue(
file="code",
line=e.lineno or 0,
severity="π΄ critical",
message=f"Syntax error: {e.msg}",
suggestion="Fix the syntax error at the indicated line",
category="bug"
))
# Common bugs
if '==' in code and '=' in code.replace('==', '').replace('!=', ''):
if re.search(r'[^=!<>]=[^=]', code):
issues.append(CodeIssue(
file="code",
line=0,
severity="π΄ critical",
message="Assignment (=) instead of comparison (==)",
suggestion="Use '==' for comparison, '=' for assignment",
category="bug"
))
# Security issues
if 'eval(' in code or 'exec(' in code:
issues.append(CodeIssue(
file="code",
line=0,
severity="π΄ critical",
message="Use of eval()/exec() is a security risk",
suggestion="Avoid eval/exec - use safer alternatives",
category="security"
))
if 'password' in code.lower() and 'hash' not in code.lower():
issues.append(CodeIssue(
file="code",
line=0,
severity="π‘ warning",
message="Password handling detected without hashing",
suggestion="Always hash passwords using bcrypt or similar",
category="security"
))
# Performance issues
if code.count('for ') > 3 and 'append' in code:
issues.append(CodeIssue(
file="code",
line=0,
severity="π‘ warning",
message="Multiple loops with append - potential performance issue",
suggestion="Consider list comprehensions or vectorized operations",
category="performance"
))
# Style issues
if len(code.split('\n')) > 0:
for i, line in enumerate(code.split('\n'), 1):
if len(line) > 100:
issues.append(CodeIssue(
file="code",
line=i,
severity="π΅ info",
message="Line too long (>100 characters)",
suggestion="Break into multiple lines for readability",
category="style"
))
return {
"status": "β
success",
"issues_found": len(issues),
"issues": [
{
"file": issue.file,
"line": issue.line,
"severity": issue.severity,
"message": issue.message,
"suggestion": issue.suggestion,
"category": issue.category
}
for issue in issues
],
"emoji": "π",
"message": "π Debugging complete!"
}
# π€ AUTONOMOUS AGENT
def autonomous_task(self, task: str, project_path: str = None) -> Dict:
"""π€ Execute autonomous coding task"""
print(f"π€ Executing autonomous task: {task}")
result = {
"task": task,
"steps": [],
"status": "completed",
"emoji": "π€"
}
# Parse task
task_lower = task.lower()
if 'create' in task_lower or 'build' in task_lower:
result["steps"].append("π Analyzing requirements")
result["steps"].append("ποΈ Designing architecture")
result["steps"].append("π» Writing code")
result["steps"].append("π§ͺ Testing code")
result["steps"].append("π Adding documentation")
elif 'fix' in task_lower or 'bug' in task_lower:
result["steps"].append("π Identifying bug location")
result["steps"].append("π Analyzing root cause")
result["steps"].append("π§ Implementing fix")
result["steps"].append("β
Verifying fix")
result["steps"].append("π§ͺ Testing solution")
elif 'refactor' in task_lower or 'improve' in task_lower:
result["steps"].append("π Analyzing current code")
result["steps"].append("π― Identifying improvements")
result["steps"].append("π§ Refactoring code")
result["steps"].append("β
Verifying improvements")
result["steps"].append("π§ͺ Running tests")
elif 'test' in task_lower:
result["steps"].append("π Analyzing code structure")
result["steps"].append("π§ͺ Writing unit tests")
result["steps"].append("π§ͺ Writing integration tests")
result["steps"].append("β
Running test suite")
result["steps"].append("π Generating coverage report")
elif 'document' in task_lower:
result["steps"].append("π Analyzing code structure")
result["steps"].append("π Writing docstrings")
result["steps"].append("π Creating README")
result["steps"].append("π Adding examples")
result["steps"].append("β
Verifying documentation")
result["message"] = f"π€ Task '{task}' completed successfully!"
return result
# π§ͺ CODE GENERATION
def generate_code(self, requirement: str, language: str = "python") -> Dict:
"""π» Generate code from requirements"""
print(f"π» Generating {language} code...")
# Template-based generation
if language == "python":
if 'api' in requirement.lower() or 'rest' in requirement.lower():
code = self._generate_python_api(requirement)
elif 'class' in requirement.lower():
code = self._generate_python_class(requirement)
elif 'function' in requirement.lower():
code = self._generate_python_function(requirement)
else:
code = self._generate_python_generic(requirement)
else:
code = f"// Code generation for {language}\n// Requirement: {requirement}"
return {
"status": "β
success",
"requirement": requirement,
"language": language,
"code": code,
"emoji": "π»",
"message": "π» Code generated successfully!"
}
def _generate_python_api(self, requirement: str) -> str:
"""π Generate Python API code"""
return f'''"""
π RESTful API
Requirement: {requirement}
"""
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
app = FastAPI(title="{requirement}")
# π¦ Data Models
class Item(BaseModel):
id: int
name: str
description: Optional[str] = None
# ποΈ In-memory storage
items_db = []
# π API Endpoints
@app.get("/")
async def root():
"""π Root endpoint"""
return {{"message": "Welcome to {requirement}"}}
@app.get("/items", response_model=List[Item])
async def get_items():
"""π Get all items"""
return items_db
@app.post("/items", response_model=Item)
async def create_item(item: Item):
"""β Create new item"""
items_db.append(item)
return item
@app.get("/items/{{item_id}}", response_model=Item)
async def get_item(item_id: int):
"""π Get item by ID"""
for item in items_db:
if item.id == item_id:
return item
raise HTTPException(status_code=404, detail="Item not found")
@app.delete("/items/{{item_id}}")
async def delete_item(item_id: int):
"""ποΈ Delete item"""
for i, item in enumerate(items_db):
if item.id == item_id:
items_db.pop(i)
return {{"message": "Item deleted"}}
raise HTTPException(status_code=404, detail="Item not found")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
'''
def _generate_python_class(self, requirement: str) -> str:
"""π Generate Python class"""
return f'''"""
π {requirement}
"""
class {requirement.replace(' ', '')}:
"""π¦ {requirement} class"""
def __init__(self, name: str):
"""π― Initialize {requirement}"""
self.name = name
self.data = []
def add(self, item):
"""β Add item"""
self.data.append(item)
def get(self, index: int):
"""π Get item by index"""
if 0 <= index < len(self.data):
return self.data[index]
return None
def __str__(self):
"""π String representation"""
return f"{requirement}(name={{self.name}}, items={{len(self.data)}})"
# π‘ Example usage
if __name__ == "__main__":
obj = {requirement.replace(' ', '')}("Example")
obj.add("Item 1")
obj.add("Item 2")
print(obj)
'''
def _generate_python_function(self, requirement: str) -> str:
"""π§ Generate Python function"""
return f'''"""
π§ {requirement}
"""
def {requirement.replace(' ', '_').lower()}(input_data):
"""
π― {requirement}
Args:
input_data: Input data to process
Returns:
Processed result
"""
# π Process data
result = input_data
# π‘ Add your logic here
return result
# π‘ Example usage
if __name__ == "__main__":
result = {requirement.replace(' ', '_').lower()}("sample data")
print(f"Result: {{result}}")
'''
def _generate_python_generic(self, requirement: str) -> str:
"""π Generate generic Python code"""
return f'''"""
π {requirement}
"""
def main():
"""π― Main function"""
print("π Starting: {requirement}")
# π‘ Add your code here
print("β
Completed: {requirement}")
if __name__ == "__main__":
main()
'''
# Export classes
__all__ = ['CodingAI', 'CodeFile', 'CodeIssue']
|