File size: 5,941 Bytes
25e927f |
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 |
"""
CRANE AI - Kod Yazım Modülü
"""
import re
from typing import Dict, Any
from core.base_module import BaseMicroModule
import logging
logger = logging.getLogger(__name__)
class CodeModule(BaseMicroModule):
"""Kod yazımı için özelleşmiş modül"""
def __init__(self, config: Dict[str, Any]):
super().__init__(
model_id="deepseek-ai/deepseek-coder-1.3b-instruct",
config=config
)
# Kod kelime anahtar kelimeleri
self.code_keywords = {
"function", "class", "def", "import", "from", "return",
"if", "else", "for", "while", "try", "except", "with",
"python", "javascript", "java", "c++", "html", "css",
"kod", "kodu", "script", "fonksiyon", "sınıf", "algoritma",
"program", "yazılım", "debug", "hata", "fix", "düzelt"
}
# Programlama dilleri
self.programming_languages = {
"python", "javascript", "java", "c++", "c#", "php", "ruby",
"go", "rust", "kotlin", "swift", "typescript", "html", "css",
"sql", "bash", "powershell", "r", "matlab", "scala"
}
def can_handle(self, query: str, context: Dict[str, Any]) -> float:
"""Kod yazımı sorguları için uygunluk skoru"""
query_lower = query.lower()
# Kod anahtar kelimelerini kontrol et
code_score = 0
for keyword in self.code_keywords:
if keyword in query_lower:
code_score += 0.15
# Programlama dili belirtilmişse
for lang in self.programming_languages:
if lang in query_lower:
code_score += 0.3
# Kod yazımı action kelimeleri
action_keywords = ["yaz", "oluştur", "geliştir", "kur", "hazırla", "tasarla"]
for action in action_keywords:
if action in query_lower:
code_score += 0.2
# Kod karakteristik işaretlerini kontrol et
if any(char in query for char in ["()", "{}", "[]", "==", "!=", "<=", ">="]):
code_score += 0.15
# Kod blokları varsa
if "```" in query or "def " in query or "class " in query:
code_score += 0.3
# Spesifik kod türleri
code_types = ["hesap", "makinesi", "calculator", "app", "uygulama", "website", "site"]
for code_type in code_types:
if code_type in query_lower:
code_score += 0.25
# Maksimum 1.0 skor
return min(code_score, 1.0)
async def process(self, query: str, context: Dict[str, Any]) -> Dict[str, Any]:
"""Kod yazımı işlemi"""
try:
# Kod yazımı için özel prompt
prompt = self._build_code_prompt(query, context)
# Kod üretimi
response = await self.generate_response(
prompt,
max_tokens=self.config.get("max_tokens", 2048),
temperature=0.1 # Kod için düşük temperature
)
# Kod bloklarını ayıkla
code_blocks = self._extract_code_blocks(response)
return {
"response": response,
"code_blocks": code_blocks,
"language": self._detect_language(query),
"module": "code_module",
"confidence": self.can_handle(query, context)
}
except Exception as e:
logger.error(f"Code processing error: {str(e)}")
return {
"error": str(e),
"module": "code_module"
}
def _build_code_prompt(self, query: str, context: Dict[str, Any]) -> str:
"""Kod yazımı için prompt hazırlar"""
# Dil tespiti
language = self._detect_language(query)
# Temel prompt
prompt = f"""Sen bir uzman programcısın. Kullanıcının sorusunu anla ve en iyi kodu yaz.
Kullanıcı sorusu: {query}
Lütfen:
1. Temiz, okunabilir kod yaz
2. Kod açıklamalarını Türkçe yap
3. En iyi pratikleri kullan
4. Gerekirse örnek kullanımı göster
"""
# Dil özelinde ekleme
if language:
prompt += f"Programlama dili: {language}\n"
# Bağlam varsa ekle
if context.get("history"):
prompt += f"Önceki konuşma: {context['history'][-1]}\n"
return prompt
def _detect_language(self, query: str) -> str:
"""Sorgudan programlama dilini tespit eder"""
query_lower = query.lower()
for lang in self.programming_languages:
if lang in query_lower:
return lang
# Varsayılan dil
return "python"
def _extract_code_blocks(self, response: str) -> list:
"""Yanıttan kod bloklarını ayıklar"""
code_blocks = []
# Markdown kod blokları
pattern = r'```(\w+)?\n(.*?)\n```'
matches = re.findall(pattern, response, re.DOTALL)
for match in matches:
lang, code = match
code_blocks.append({
"language": lang or "text",
"code": code.strip()
})
# Tek satır kod blokları
inline_pattern = r'`([^`]+)`'
inline_matches = re.findall(inline_pattern, response)
for code in inline_matches:
if len(code) > 5: # Çok kısa olanları atla
code_blocks.append({
"language": "inline",
"code": code.strip()
})
return code_blocks |