CodeCommunity commited on
Commit
ca73a25
·
verified ·
1 Parent(s): 649dabc

Update app/main.py

Browse files
Files changed (1) hide show
  1. app/main.py +13 -43
app/main.py CHANGED
@@ -29,6 +29,8 @@ app = FastAPI(title="GitGud AI Service")
29
  # Global embedding cache
30
  REPO_CACHE: Dict[str, Dict[str, List[float]]] = {}
31
 
 
 
32
  # 3. Data Models
33
  class FileRequest(BaseModel):
34
  fileName: str
@@ -58,10 +60,8 @@ def calculate_repo_health(total_vulns: int, avg_maint: float) -> int:
58
  penalty = total_vulns * 8
59
  return int(max(10, min(100, base_score - penalty)))
60
 
61
- def sync_review_worker(file_req: FileRequest):
62
- """Wrapper for the synchronous reviewer service"""
63
- # Note: We pass the individual file object directly
64
- return reviewer.service.review_batch_code([file_req])
65
 
66
  def parse_tree_to_list(raw_tree: str):
67
  """Parses text tree into JSON objects for Compose LazyColumn"""
@@ -117,31 +117,9 @@ async def classify_file(request: FileRequest):
117
  async def review_batch_code(request: BatchReviewRequest):
118
  try:
119
  loop = asyncio.get_running_loop()
120
-
121
- # Dispatch all files to the thread pool immediately
122
- tasks = [
123
- loop.run_in_executor(executor, sync_review_worker, f)
124
- for f in request.files
125
- ]
126
-
127
- # Wait for all to complete
128
- raw_results = await asyncio.gather(*tasks, return_exceptions=True)
129
-
130
- final_reviews = []
131
- for i, result in enumerate(raw_results):
132
- if isinstance(result, Exception):
133
- logger.error(f"Error reviewing {request.files[i].fileName}: {result}")
134
- # We return a placeholder error for this specific file so the UI knows it failed
135
- final_reviews.append({
136
- "fileName": request.files[i].fileName,
137
- "error": "Analysis failed",
138
- "details": str(result)
139
- })
140
- else:
141
- final_reviews.append(result)
142
-
143
  return {"results": final_reviews}
144
-
145
  except Exception as e:
146
  logger.error(f"Batch review critical failure: {traceback.format_exc()}")
147
  raise HTTPException(status_code=500, detail="Internal processing error")
@@ -150,31 +128,23 @@ async def review_batch_code(request: BatchReviewRequest):
150
  async def get_dashboard_stats(request: BatchReviewRequest):
151
  try:
152
  loop = asyncio.get_running_loop()
153
-
154
- # Parallel execution for stats
155
- tasks = [loop.run_in_executor(executor, sync_review_worker, f) for f in request.files]
156
- raw_reviews = await asyncio.gather(*tasks, return_exceptions=True)
157
 
158
  total_vulns = 0
159
  maint_scores = []
160
  found_apis = set()
161
  api_regex = re.compile(r'(?:get|post|put|delete|patch)\([\'"]\/(.*?)[\'"]', re.IGNORECASE)
162
 
163
- for i, review in enumerate(raw_reviews):
164
- if isinstance(review, Exception):
165
- continue
166
-
167
- # Handle the structure returned by your reviewer service
168
- # (Assuming it returns a list or a dict based on your current service)
169
- current_review = review[0] if isinstance(review, list) else review
170
-
171
  vulns = current_review.get("vulnerabilities", [])
172
  total_vulns += len(vulns)
173
-
174
  m_score = current_review.get("metrics", {}).get("maintainability", 8.0)
175
  maint_scores.append(m_score)
176
-
177
- content = request.files[i].content
178
  if content:
179
  matches = api_regex.findall(content)
180
  for match in matches:
 
29
  # Global embedding cache
30
  REPO_CACHE: Dict[str, Dict[str, List[float]]] = {}
31
 
32
+ executor = ThreadPoolExecutor(max_workers=4)
33
+
34
  # 3. Data Models
35
  class FileRequest(BaseModel):
36
  fileName: str
 
60
  penalty = total_vulns * 8
61
  return int(max(10, min(100, base_score - penalty)))
62
 
63
+ def sync_review_worker(file_list: List[FileRequest]):
64
+ return reviewer.service.review_batch_code(file_list)
 
 
65
 
66
  def parse_tree_to_list(raw_tree: str):
67
  """Parses text tree into JSON objects for Compose LazyColumn"""
 
117
  async def review_batch_code(request: BatchReviewRequest):
118
  try:
119
  loop = asyncio.get_running_loop()
120
+ raw_results = await loop.run_in_executor(executor, sync_review_worker, request.files)
121
+ final_reviews = raw_results if isinstance(raw_results, list) else [raw_results]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  return {"results": final_reviews}
 
123
  except Exception as e:
124
  logger.error(f"Batch review critical failure: {traceback.format_exc()}")
125
  raise HTTPException(status_code=500, detail="Internal processing error")
 
128
  async def get_dashboard_stats(request: BatchReviewRequest):
129
  try:
130
  loop = asyncio.get_running_loop()
131
+ raw_reviews = await loop.run_in_executor(executor, sync_review_worker, request.files)
132
+ if not isinstance(raw_reviews, list):
133
+ raw_reviews = [raw_reviews]
 
134
 
135
  total_vulns = 0
136
  maint_scores = []
137
  found_apis = set()
138
  api_regex = re.compile(r'(?:get|post|put|delete|patch)\([\'"]\/(.*?)[\'"]', re.IGNORECASE)
139
 
140
+ for i, current_review in enumerate(raw_reviews):
 
 
 
 
 
 
 
141
  vulns = current_review.get("vulnerabilities", [])
142
  total_vulns += len(vulns)
143
+
144
  m_score = current_review.get("metrics", {}).get("maintainability", 8.0)
145
  maint_scores.append(m_score)
146
+
147
+ content = request.files[i].content if i < len(request.files) else None
148
  if content:
149
  matches = api_regex.findall(content)
150
  for match in matches: