Spaces:
Sleeping
Sleeping
Joash
commited on
Commit
·
b4ae3b7
1
Parent(s):
a01c4ae
Optimize code reviewer with memory management and improved parsing
Browse files- src/code_reviewer.py +61 -39
src/code_reviewer.py
CHANGED
|
@@ -1,8 +1,9 @@
|
|
| 1 |
from typing import Dict, List, Optional
|
| 2 |
import logging
|
| 3 |
-
from datetime import datetime
|
| 4 |
from .model_manager import ModelManager
|
| 5 |
from .config import Config
|
|
|
|
| 6 |
|
| 7 |
logger = logging.getLogger(__name__)
|
| 8 |
|
|
@@ -19,32 +20,38 @@ class CodeReviewer:
|
|
| 19 |
def __init__(self, model_manager: ModelManager):
|
| 20 |
self.model_manager = model_manager
|
| 21 |
self.review_history: List[CodeReview] = []
|
|
|
|
| 22 |
|
| 23 |
def _create_review_prompt(self, code: str, language: str) -> str:
|
| 24 |
"""Create a structured prompt for code review."""
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
| 30 |
|
| 31 |
-
Code
|
| 32 |
```{language}
|
| 33 |
{code}
|
| 34 |
-
```
|
| 35 |
-
|
| 36 |
-
Provide your review in exactly these sections: Issues, Improvements, Best Practices, Security.
|
| 37 |
-
Each section should contain a list of specific points.
|
| 38 |
-
"""
|
| 39 |
|
| 40 |
def review_code(self, code: str, language: str, review_id: str) -> CodeReview:
|
| 41 |
"""Perform code review using the LLM."""
|
| 42 |
try:
|
| 43 |
start_time = datetime.now()
|
| 44 |
|
|
|
|
|
|
|
|
|
|
| 45 |
# Create review instance
|
| 46 |
review = CodeReview(code, language, review_id)
|
| 47 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
# Generate review prompt
|
| 49 |
prompt = self._create_review_prompt(code, language)
|
| 50 |
|
|
@@ -71,6 +78,9 @@ Each section should contain a list of specific points.
|
|
| 71 |
# Store review in history
|
| 72 |
self._add_to_history(review)
|
| 73 |
|
|
|
|
|
|
|
|
|
|
| 74 |
return review
|
| 75 |
|
| 76 |
except Exception as e:
|
|
@@ -81,34 +91,38 @@ Each section should contain a list of specific points.
|
|
| 81 |
"""Parse the LLM response into structured sections."""
|
| 82 |
sections = []
|
| 83 |
current_section = None
|
|
|
|
| 84 |
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
line
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
current_section['items']
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
# Ensure all required sections exist
|
| 111 |
-
required_sections = ['Issues', 'Improvements', 'Best Practices', 'Security']
|
| 112 |
result = []
|
| 113 |
for section_type in required_sections:
|
| 114 |
found_section = next((s for s in sections if s['type'] == section_type), None)
|
|
@@ -125,9 +139,17 @@ Each section should contain a list of specific points.
|
|
| 125 |
def _add_to_history(self, review: CodeReview):
|
| 126 |
"""Add review to history and maintain size limit."""
|
| 127 |
self.review_history.append(review)
|
| 128 |
-
|
| 129 |
self.review_history.pop(0)
|
| 130 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
def get_review_metrics(self) -> Dict:
|
| 132 |
"""Calculate aggregate metrics from review history."""
|
| 133 |
if not self.review_history:
|
|
@@ -153,4 +175,4 @@ Each section should contain a list of specific points.
|
|
| 153 |
"""Get review history with optional limit."""
|
| 154 |
if limit:
|
| 155 |
return self.review_history[-limit:]
|
| 156 |
-
return self.review_history
|
|
|
|
| 1 |
from typing import Dict, List, Optional
|
| 2 |
import logging
|
| 3 |
+
from datetime import datetime, timedelta
|
| 4 |
from .model_manager import ModelManager
|
| 5 |
from .config import Config
|
| 6 |
+
import gc
|
| 7 |
|
| 8 |
logger = logging.getLogger(__name__)
|
| 9 |
|
|
|
|
| 20 |
def __init__(self, model_manager: ModelManager):
|
| 21 |
self.model_manager = model_manager
|
| 22 |
self.review_history: List[CodeReview] = []
|
| 23 |
+
self._last_cleanup = datetime.now()
|
| 24 |
|
| 25 |
def _create_review_prompt(self, code: str, language: str) -> str:
|
| 26 |
"""Create a structured prompt for code review."""
|
| 27 |
+
# More concise prompt to reduce token usage
|
| 28 |
+
return f"""Review this {language} code. List specific points in these sections:
|
| 29 |
+
Issues:
|
| 30 |
+
Improvements:
|
| 31 |
+
Best Practices:
|
| 32 |
+
Security:
|
| 33 |
|
| 34 |
+
Code:
|
| 35 |
```{language}
|
| 36 |
{code}
|
| 37 |
+
```"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
def review_code(self, code: str, language: str, review_id: str) -> CodeReview:
|
| 40 |
"""Perform code review using the LLM."""
|
| 41 |
try:
|
| 42 |
start_time = datetime.now()
|
| 43 |
|
| 44 |
+
# Clean up old reviews periodically
|
| 45 |
+
self._cleanup_old_reviews()
|
| 46 |
+
|
| 47 |
# Create review instance
|
| 48 |
review = CodeReview(code, language, review_id)
|
| 49 |
|
| 50 |
+
# Truncate code if too long
|
| 51 |
+
max_code_length = Config.MAX_INPUT_LENGTH - 200 # Reserve tokens for prompt
|
| 52 |
+
if len(code) > max_code_length:
|
| 53 |
+
code = code[:max_code_length] + "\n# ... (code truncated for length)"
|
| 54 |
+
|
| 55 |
# Generate review prompt
|
| 56 |
prompt = self._create_review_prompt(code, language)
|
| 57 |
|
|
|
|
| 78 |
# Store review in history
|
| 79 |
self._add_to_history(review)
|
| 80 |
|
| 81 |
+
# Force garbage collection
|
| 82 |
+
gc.collect()
|
| 83 |
+
|
| 84 |
return review
|
| 85 |
|
| 86 |
except Exception as e:
|
|
|
|
| 91 |
"""Parse the LLM response into structured sections."""
|
| 92 |
sections = []
|
| 93 |
current_section = None
|
| 94 |
+
required_sections = ['Issues', 'Improvements', 'Best Practices', 'Security']
|
| 95 |
|
| 96 |
+
try:
|
| 97 |
+
# Split response into lines and process each line
|
| 98 |
+
lines = response.split('\n')
|
| 99 |
+
for line in lines:
|
| 100 |
+
line = line.strip()
|
| 101 |
+
if not line:
|
| 102 |
+
continue
|
| 103 |
+
|
| 104 |
+
# Check for section headers
|
| 105 |
+
for section in required_sections:
|
| 106 |
+
if line.lower().startswith(section.lower()):
|
| 107 |
+
current_section = {
|
| 108 |
+
'type': section,
|
| 109 |
+
'items': []
|
| 110 |
+
}
|
| 111 |
+
sections.append(current_section)
|
| 112 |
+
break
|
| 113 |
+
|
| 114 |
+
# Add items to current section if not a section header
|
| 115 |
+
if current_section and line.strip('-* ') and not any(
|
| 116 |
+
line.lower().startswith(s.lower()) for s in required_sections
|
| 117 |
+
):
|
| 118 |
+
item = line.strip('-* ')
|
| 119 |
+
if item and not any(item == existing for existing in current_section['items']):
|
| 120 |
+
current_section['items'].append(item)
|
| 121 |
+
|
| 122 |
+
except Exception as e:
|
| 123 |
+
logger.error(f"Error parsing response: {str(e)}")
|
| 124 |
|
| 125 |
# Ensure all required sections exist
|
|
|
|
| 126 |
result = []
|
| 127 |
for section_type in required_sections:
|
| 128 |
found_section = next((s for s in sections if s['type'] == section_type), None)
|
|
|
|
| 139 |
def _add_to_history(self, review: CodeReview):
|
| 140 |
"""Add review to history and maintain size limit."""
|
| 141 |
self.review_history.append(review)
|
| 142 |
+
while len(self.review_history) > Config.MAX_HISTORY_ITEMS:
|
| 143 |
self.review_history.pop(0)
|
| 144 |
|
| 145 |
+
def _cleanup_old_reviews(self):
|
| 146 |
+
"""Clean up reviews older than retention period."""
|
| 147 |
+
if (datetime.now() - self._last_cleanup) > timedelta(hours=1):
|
| 148 |
+
cutoff_date = datetime.now() - timedelta(days=Config.HISTORY_RETENTION_DAYS)
|
| 149 |
+
self.review_history = [r for r in self.review_history if r.timestamp > cutoff_date]
|
| 150 |
+
self._last_cleanup = datetime.now()
|
| 151 |
+
gc.collect()
|
| 152 |
+
|
| 153 |
def get_review_metrics(self) -> Dict:
|
| 154 |
"""Calculate aggregate metrics from review history."""
|
| 155 |
if not self.review_history:
|
|
|
|
| 175 |
"""Get review history with optional limit."""
|
| 176 |
if limit:
|
| 177 |
return self.review_history[-limit:]
|
| 178 |
+
return self.review_history.copy() # Return copy to prevent external modifications
|