Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- app.py +892 -56
- requirements.txt +54 -1
app.py
CHANGED
|
@@ -1,64 +1,900 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from huggingface_hub import InferenceClient
|
| 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 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
if __name__ == "__main__":
|
| 64 |
demo.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
|
| 4 |
+
|
| 5 |
+
#!/usr/bin/env python3
|
| 6 |
+
# import gradio as gr
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
import logging
|
| 10 |
+
import os
|
| 11 |
+
import traceback
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from urllib.parse import urlparse
|
| 14 |
+
from typing import Dict, Any, List, Set
|
| 15 |
+
from git import Repo
|
| 16 |
+
import io
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
import numpy as np
|
| 20 |
+
import faiss
|
| 21 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 22 |
+
from sentence_transformers import SentenceTransformer, util
|
| 23 |
+
from huggingface_hub import snapshot_download
|
| 24 |
+
import os
|
| 25 |
+
from openai import AzureOpenAI
|
| 26 |
+
import requests
|
| 27 |
+
import re
|
| 28 |
+
|
| 29 |
+
import matplotlib.pyplot as plt
|
| 30 |
+
from sklearn.manifold import TSNE
|
| 31 |
+
from sklearn.cluster import KMeans
|
| 32 |
+
import plotly.graph_objects as go
|
| 33 |
+
import plotly.express as px
|
| 34 |
+
import random
|
| 35 |
+
|
| 36 |
+
from sklearn.cluster import AgglomerativeClustering
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def load_env():
|
| 40 |
+
from dotenv import load_dotenv
|
| 41 |
+
env_path = Path(__file__).parent.parent / '.env'
|
| 42 |
+
load_dotenv(dotenv_path=env_path)
|
| 43 |
+
|
| 44 |
+
load_env()
|
| 45 |
+
|
| 46 |
+
# Centralized env parameters
|
| 47 |
+
HUGGINGFACE_HUB_TOKEN = os.getenv("HUGGINGFACE_HUB_TOKEN")
|
| 48 |
+
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
|
| 49 |
+
AZURE_OPENAI_ENDPOINT = os.getenv("AZURE_OPENAI_ENDPOINT")
|
| 50 |
+
AZURE_OPENAI_API_KEY = os.getenv("AZURE_OPENAI_API_KEY")
|
| 51 |
+
MODEL_NAME = "gpt-4o-mini"
|
| 52 |
+
DEPLOYMENT = "gpt-4o-mini"
|
| 53 |
+
API_VERSION = "2024-12-01-preview"
|
| 54 |
+
|
| 55 |
+
FILE_REGEX = re.compile(r"^diff --git a/(.+?) b/(.+)")
|
| 56 |
+
LINE_HUNK = re.compile(r"@@ -(?P<old_start>\d+),(?P<old_len>\d+) \+(?P<new_start>\d+),(?P<new_len>\d+) @@")
|
| 57 |
+
|
| 58 |
+
# Configure logging to capture all output
|
| 59 |
+
log_stream = io.StringIO()
|
| 60 |
+
log_handler = logging.StreamHandler(log_stream)
|
| 61 |
+
log_handler.setLevel(logging.INFO)
|
| 62 |
+
log_formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
|
| 63 |
+
log_handler.setFormatter(log_formatter)
|
| 64 |
+
|
| 65 |
+
logging.basicConfig(
|
| 66 |
+
level=logging.INFO,
|
| 67 |
+
format="%(asctime)s %(levelname)s %(message)s",
|
| 68 |
+
handlers=[log_handler, logging.StreamHandler()]
|
| 69 |
)
|
| 70 |
+
logger = logging.getLogger(__name__)
|
| 71 |
+
|
| 72 |
+
class InferenceContext:
|
| 73 |
+
def __init__(self, repo_url: str):
|
| 74 |
+
self.repo_url = repo_url
|
| 75 |
+
owner, name = self._parse_owner_repo(repo_url)
|
| 76 |
+
self.repo_id = f"{owner}/{name}"
|
| 77 |
+
self.repo_dir = f"{owner}-{name}"
|
| 78 |
+
self.hf_repo_id = "kotlarmilos/repository-learning"
|
| 79 |
+
|
| 80 |
+
# Local paths for downloaded models
|
| 81 |
+
self.base = Path("artifacts") / self.repo_dir
|
| 82 |
+
self.model_dirs = {
|
| 83 |
+
'fine_tune': self.base / 'fine_tune',
|
| 84 |
+
'contrastive': self.base / 'contrastive',
|
| 85 |
+
'index': self.base / 'index'
|
| 86 |
+
}
|
| 87 |
+
self.code_dir = self.base / 'code'
|
| 88 |
+
|
| 89 |
+
# Create directories
|
| 90 |
+
for d in (*self.model_dirs.values(), self.code_dir):
|
| 91 |
+
d.mkdir(parents=True, exist_ok=True)
|
| 92 |
+
|
| 93 |
+
@staticmethod
|
| 94 |
+
def _parse_owner_repo(url: str) -> tuple[str, str]:
|
| 95 |
+
parts = urlparse(url).path.strip("/").split("/")
|
| 96 |
+
if len(parts) < 2:
|
| 97 |
+
raise ValueError(f"Invalid GitHub URL: {url}")
|
| 98 |
+
return parts[-2], parts[-1]
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class InferencePipeline:
|
| 102 |
+
def __init__(self, ctx: InferenceContext):
|
| 103 |
+
self.ctx = ctx
|
| 104 |
+
self.tokenizer = None
|
| 105 |
+
self.llm = None
|
| 106 |
+
self.embedder = None
|
| 107 |
+
self.faiss_index = None
|
| 108 |
+
self.faiss_metadata = None
|
| 109 |
+
|
| 110 |
+
self.download_artifacts()
|
| 111 |
+
self.load_models()
|
| 112 |
+
|
| 113 |
+
def download_artifacts(self):
|
| 114 |
+
"""Download models and index from Hugging Face if they don't exist locally."""
|
| 115 |
+
|
| 116 |
+
self.repo_files = self._clone_or_pull()
|
| 117 |
+
|
| 118 |
+
snapshot_download(
|
| 119 |
+
repo_id=self.ctx.hf_repo_id,
|
| 120 |
+
allow_patterns=f"{self.ctx.repo_dir}/**",
|
| 121 |
+
local_dir=str(self.ctx.base.parent),
|
| 122 |
+
local_dir_use_symlinks=False,
|
| 123 |
+
token=HUGGINGFACE_HUB_TOKEN
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
logger.info("All artifacts download complete.")
|
| 127 |
+
|
| 128 |
+
def _clone_or_pull(self) -> bool:
|
| 129 |
+
dest = self.ctx.code_dir
|
| 130 |
+
git_dir = dest / ".git"
|
| 131 |
+
if git_dir.exists():
|
| 132 |
+
Repo(dest).remotes.origin.pull()
|
| 133 |
+
logger.info("Pulled latest code into %s", dest)
|
| 134 |
+
else:
|
| 135 |
+
Repo.clone_from(self.ctx.repo_url, dest)
|
| 136 |
+
logger.info("Cloned repo %s into %s", self.ctx.repo_url, dest)
|
| 137 |
+
|
| 138 |
+
return [str(f.relative_to(dest)) for f in dest.rglob("*") if f.is_file()]
|
| 139 |
+
|
| 140 |
+
def load_models(self):
|
| 141 |
+
"""Load the fine-tuned LLM model."""
|
| 142 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self.ctx.model_dirs['fine_tune'])
|
| 143 |
+
self.local_llm = AutoModelForCausalLM.from_pretrained(
|
| 144 |
+
self.ctx.model_dirs['fine_tune'],
|
| 145 |
+
device_map="auto",
|
| 146 |
+
torch_dtype=torch.bfloat16
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
self.enterprise_llm = AzureOpenAI(
|
| 150 |
+
api_version=API_VERSION,
|
| 151 |
+
azure_endpoint=AZURE_OPENAI_ENDPOINT,
|
| 152 |
+
api_key=AZURE_OPENAI_API_KEY,
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
self.embedder = SentenceTransformer(str(self.ctx.model_dirs['contrastive']))
|
| 156 |
+
|
| 157 |
+
self.faiss_index = faiss.read_index(str(self.ctx.model_dirs['index'] / "index.faiss"))
|
| 158 |
+
self.faiss_metadata = json.loads((self.ctx.model_dirs['index'] / "metadata.json").read_text())
|
| 159 |
+
logger.info("FAISS index loaded successfully")
|
| 160 |
+
|
| 161 |
+
def _extract_pr_data(self, pr_url: str) -> dict:
|
| 162 |
+
"""
|
| 163 |
+
Collect PR data using GitHub API.
|
| 164 |
+
"""
|
| 165 |
+
|
| 166 |
+
match = re.search(r'/pull/(\d+)', pr_url)
|
| 167 |
+
pr_number = int(match.group(1))
|
| 168 |
+
|
| 169 |
+
pr_url = f"https://api.github.com/repos/{self.ctx.repo_id}/pulls/{pr_number}"
|
| 170 |
+
comments_url = f"https://api.github.com/repos/{self.ctx.repo_id}/pulls/{pr_number}/comments"
|
| 171 |
+
|
| 172 |
+
headers = {}
|
| 173 |
+
headers["Authorization"] = f"token {GITHUB_TOKEN}"
|
| 174 |
+
headers["Accept"] = "application/vnd.github.v3+json"
|
| 175 |
+
|
| 176 |
+
try:
|
| 177 |
+
logger.info(f"Fetching PR #{pr_number} details...")
|
| 178 |
+
pr_response = requests.get(pr_url, headers=headers)
|
| 179 |
+
pr_response.raise_for_status()
|
| 180 |
+
pr_data = pr_response.json()
|
| 181 |
+
|
| 182 |
+
logger.info(f"Fetching PR #{pr_number} review comments...")
|
| 183 |
+
comments_response = requests.get(comments_url, headers=headers)
|
| 184 |
+
comments_response.raise_for_status()
|
| 185 |
+
comments_data = comments_response.json()
|
| 186 |
+
|
| 187 |
+
grouped = {}
|
| 188 |
+
for comment in comments_data:
|
| 189 |
+
hunk = comment.get("diff_hunk", "")
|
| 190 |
+
grouped.setdefault(hunk, []).append(comment.get("body", ""))
|
| 191 |
+
|
| 192 |
+
review_comments = [
|
| 193 |
+
{"diff_hunk": hunk, "comments": comments}
|
| 194 |
+
for hunk, comments in grouped.items()
|
| 195 |
+
]
|
| 196 |
+
|
| 197 |
+
logger.info(f"Fetching PR #{pr_number} diff...")
|
| 198 |
+
diff_headers = headers.copy()
|
| 199 |
+
diff_headers["Accept"] = "application/vnd.github.v3.diff"
|
| 200 |
+
diff_response = requests.get(pr_url, headers=diff_headers)
|
| 201 |
+
diff_response.raise_for_status()
|
| 202 |
+
|
| 203 |
+
parsed_diff = self.parse_diff_with_lines(diff_response.text)
|
| 204 |
+
|
| 205 |
+
result = {
|
| 206 |
+
"title": pr_data.get("title", ""),
|
| 207 |
+
"body": pr_data.get("body", ""),
|
| 208 |
+
"review_comments": review_comments,
|
| 209 |
+
"diff": diff_response.text,
|
| 210 |
+
"changed_files": list(parsed_diff['changed_files']),
|
| 211 |
+
"diff_hunks": parsed_diff['diff_hunks']
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
logger.info(f"Successfully collected PR #{pr_number} data")
|
| 215 |
+
return result
|
| 216 |
+
|
| 217 |
+
except Exception as e:
|
| 218 |
+
logger.error(f"Error processing PR #{pr_number} data: {e}")
|
| 219 |
+
raise
|
| 220 |
+
|
| 221 |
+
def parse_diff_with_lines(self, diff_text: str) -> Dict[str, Any]:
|
| 222 |
+
lines = diff_text.splitlines()
|
| 223 |
+
|
| 224 |
+
result = {
|
| 225 |
+
'changed_files': set(),
|
| 226 |
+
'diff_hunks': {}
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
current_file = None
|
| 230 |
+
current_hunk_content = []
|
| 231 |
+
current_line_range = None
|
| 232 |
+
file_header_lines = []
|
| 233 |
+
|
| 234 |
+
for line in lines:
|
| 235 |
+
# Check if this is a new file header
|
| 236 |
+
file_match = FILE_REGEX.match(line)
|
| 237 |
+
if file_match:
|
| 238 |
+
# Save previous file data if exists
|
| 239 |
+
if current_file and current_hunk_content and current_line_range:
|
| 240 |
+
if current_file not in result['diff_hunks']:
|
| 241 |
+
result['diff_hunks'][current_file] = []
|
| 242 |
+
result['diff_hunks'][current_file].append({
|
| 243 |
+
'line_range': current_line_range,
|
| 244 |
+
'content': '\n'.join(current_hunk_content)
|
| 245 |
+
})
|
| 246 |
+
|
| 247 |
+
# Start new file
|
| 248 |
+
current_file = file_match.group(2) # Use the 'b/' file path (new file)
|
| 249 |
+
result['changed_files'].add(current_file)
|
| 250 |
+
file_header_lines = [line]
|
| 251 |
+
current_hunk_content = []
|
| 252 |
+
current_line_range = None
|
| 253 |
+
|
| 254 |
+
elif current_file: # Only process if we're inside a file
|
| 255 |
+
# Check for hunk headers to extract line ranges
|
| 256 |
+
hunk_match = LINE_HUNK.match(line)
|
| 257 |
+
if hunk_match:
|
| 258 |
+
# Save previous hunk if exists
|
| 259 |
+
if current_hunk_content and current_line_range:
|
| 260 |
+
if current_file not in result['diff_hunks']:
|
| 261 |
+
result['diff_hunks'][current_file] = []
|
| 262 |
+
result['diff_hunks'][current_file].append({
|
| 263 |
+
'line_range': current_line_range,
|
| 264 |
+
'content': '\n'.join(current_hunk_content)
|
| 265 |
+
})
|
| 266 |
+
|
| 267 |
+
# Start new hunk
|
| 268 |
+
old_start = int(hunk_match.group('old_start'))
|
| 269 |
+
old_len = int(hunk_match.group('old_len'))
|
| 270 |
+
new_start = int(hunk_match.group('new_start'))
|
| 271 |
+
new_len = int(hunk_match.group('new_len'))
|
| 272 |
+
|
| 273 |
+
# Calculate the range of changed lines
|
| 274 |
+
if new_len > 0:
|
| 275 |
+
line_start = new_start
|
| 276 |
+
line_end = new_start + new_len - 1
|
| 277 |
+
current_line_range = (line_start, line_end)
|
| 278 |
+
else:
|
| 279 |
+
current_line_range = (new_start, new_start)
|
| 280 |
+
|
| 281 |
+
# Start fresh hunk content with file headers and current hunk header
|
| 282 |
+
current_hunk_content = file_header_lines + [line]
|
| 283 |
+
else:
|
| 284 |
+
# Add content line to current hunk
|
| 285 |
+
if current_hunk_content is not None:
|
| 286 |
+
current_hunk_content.append(line)
|
| 287 |
+
|
| 288 |
+
# Save the last hunk data
|
| 289 |
+
if current_file and current_hunk_content and current_line_range:
|
| 290 |
+
if current_file not in result['diff_hunks']:
|
| 291 |
+
result['diff_hunks'][current_file] = []
|
| 292 |
+
result['diff_hunks'][current_file].append({
|
| 293 |
+
'line_range': current_line_range,
|
| 294 |
+
'content': '\n'.join(current_hunk_content)
|
| 295 |
+
})
|
| 296 |
+
|
| 297 |
+
return result
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def analyze_file_similarity(self, changed_files: List[str]) -> Dict[str, Any]:
|
| 301 |
+
result = {
|
| 302 |
+
'similar_file_groups': [],
|
| 303 |
+
'anomalous_files': [],
|
| 304 |
+
'analysis_summary': {
|
| 305 |
+
'total_files': len(changed_files),
|
| 306 |
+
'num_groups': 0,
|
| 307 |
+
'num_anomalies': 0,
|
| 308 |
+
'avg_group_size': 0
|
| 309 |
+
}
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
# Handle edge cases
|
| 313 |
+
if len(changed_files) == 0:
|
| 314 |
+
logger.info("No changed files to analyze")
|
| 315 |
+
return result
|
| 316 |
+
|
| 317 |
+
if len(changed_files) == 1:
|
| 318 |
+
logger.info(f"Only one file changed: {changed_files[0]} - no similarity analysis needed")
|
| 319 |
+
result['analysis_summary']['num_anomalies'] = 1
|
| 320 |
+
result['anomalous_files'].append({
|
| 321 |
+
'file': changed_files[0],
|
| 322 |
+
'reason': 'single_file',
|
| 323 |
+
'max_similarity_to_others': 0.0,
|
| 324 |
+
'most_similar_file': None,
|
| 325 |
+
'is_anomaly': False
|
| 326 |
+
})
|
| 327 |
+
return result
|
| 328 |
+
|
| 329 |
+
# Encode all changed files
|
| 330 |
+
file_embeddings = self.embedder.encode(changed_files, convert_to_tensor=True)
|
| 331 |
+
similarity_matrix = util.pytorch_cos_sim(file_embeddings, file_embeddings)
|
| 332 |
+
|
| 333 |
+
# Convert similarity matrix to distance matrix for clustering
|
| 334 |
+
distance_matrix = 1 - similarity_matrix.cpu().numpy()
|
| 335 |
+
|
| 336 |
+
# Perform hierarchical clustering
|
| 337 |
+
clustering = AgglomerativeClustering(
|
| 338 |
+
n_clusters=None,
|
| 339 |
+
distance_threshold=0.3, # 1 - 0.7 = 0.3 (similarity threshold of 0.7)
|
| 340 |
+
metric='precomputed',
|
| 341 |
+
linkage='average'
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
cluster_labels = clustering.fit_predict(distance_matrix)
|
| 345 |
+
|
| 346 |
+
# Group files by cluster
|
| 347 |
+
clusters = {}
|
| 348 |
+
for i, label in enumerate(cluster_labels):
|
| 349 |
+
if label not in clusters:
|
| 350 |
+
clusters[label] = []
|
| 351 |
+
clusters[label].append((changed_files[i], i)) # Store file and its index
|
| 352 |
+
|
| 353 |
+
# Process clusters to identify groups and anomalies
|
| 354 |
+
for cluster_id, files_with_indices in clusters.items():
|
| 355 |
+
files_in_cluster = [f[0] for f in files_with_indices]
|
| 356 |
+
|
| 357 |
+
if len(files_in_cluster) > 1:
|
| 358 |
+
# This is a group of similar files
|
| 359 |
+
group_similarities = []
|
| 360 |
+
pairwise_similarities = []
|
| 361 |
+
|
| 362 |
+
for i in range(len(files_with_indices)):
|
| 363 |
+
for j in range(i+1, len(files_with_indices)):
|
| 364 |
+
file_i_idx = files_with_indices[i][1]
|
| 365 |
+
file_j_idx = files_with_indices[j][1]
|
| 366 |
+
similarity = float(similarity_matrix[file_i_idx][file_j_idx])
|
| 367 |
+
group_similarities.append(similarity)
|
| 368 |
+
pairwise_similarities.append({
|
| 369 |
+
'file1': files_with_indices[i][0],
|
| 370 |
+
'file2': files_with_indices[j][0],
|
| 371 |
+
'similarity': similarity
|
| 372 |
+
})
|
| 373 |
+
|
| 374 |
+
avg_similarity = sum(group_similarities) / len(group_similarities) if group_similarities else 0
|
| 375 |
+
min_similarity = min(group_similarities) if group_similarities else 0
|
| 376 |
+
max_similarity = max(group_similarities) if group_similarities else 0
|
| 377 |
+
|
| 378 |
+
result['similar_file_groups'].append({
|
| 379 |
+
'cluster_id': cluster_id,
|
| 380 |
+
'files': files_in_cluster,
|
| 381 |
+
'avg_similarity': avg_similarity,
|
| 382 |
+
'min_similarity': min_similarity,
|
| 383 |
+
'max_similarity': max_similarity,
|
| 384 |
+
'pairwise_similarities': pairwise_similarities,
|
| 385 |
+
'coherence': 'high' if min_similarity > 0.6 else 'medium' if min_similarity > 0.4 else 'low'
|
| 386 |
+
})
|
| 387 |
+
else:
|
| 388 |
+
# This is a singleton cluster - potentially anomalous
|
| 389 |
+
file = files_in_cluster[0]
|
| 390 |
+
file_idx = files_with_indices[0][1]
|
| 391 |
+
|
| 392 |
+
# Calculate maximum similarity to any other file
|
| 393 |
+
max_similarity = 0
|
| 394 |
+
most_similar_file = None
|
| 395 |
+
similarities_to_others = []
|
| 396 |
+
|
| 397 |
+
for other_idx, other_file in enumerate(changed_files):
|
| 398 |
+
if other_idx != file_idx:
|
| 399 |
+
similarity = float(similarity_matrix[file_idx][other_idx])
|
| 400 |
+
similarities_to_others.append({
|
| 401 |
+
'file': other_file,
|
| 402 |
+
'similarity': similarity
|
| 403 |
+
})
|
| 404 |
+
if similarity > max_similarity:
|
| 405 |
+
max_similarity = similarity
|
| 406 |
+
most_similar_file = other_file
|
| 407 |
+
|
| 408 |
+
result['anomalous_files'].append({
|
| 409 |
+
'file': file,
|
| 410 |
+
'cluster_id': cluster_id,
|
| 411 |
+
'max_similarity_to_others': max_similarity,
|
| 412 |
+
'most_similar_file': most_similar_file,
|
| 413 |
+
'similarities_to_others': similarities_to_others,
|
| 414 |
+
'is_anomaly': max_similarity < 0.5, # Strong anomaly threshold
|
| 415 |
+
'anomaly_strength': 'strong' if max_similarity < 0.3 else 'medium' if max_similarity < 0.5 else 'weak',
|
| 416 |
+
'reason': 'isolated_cluster'
|
| 417 |
+
})
|
| 418 |
+
|
| 419 |
+
# Additional anomaly detection: files that are far from the group average
|
| 420 |
+
if len(changed_files) >= 3:
|
| 421 |
+
# Calculate average embedding of all changed files
|
| 422 |
+
avg_embedding = torch.mean(file_embeddings, dim=0)
|
| 423 |
+
|
| 424 |
+
# Find files that are far from the average
|
| 425 |
+
for i, file in enumerate(changed_files):
|
| 426 |
+
file_embedding = file_embeddings[i]
|
| 427 |
+
similarity_to_avg = float(util.pytorch_cos_sim(file_embedding.unsqueeze(0), avg_embedding.unsqueeze(0))[0][0])
|
| 428 |
+
|
| 429 |
+
# Check if this file is already in anomalous_files
|
| 430 |
+
existing_anomaly = next((a for a in result['anomalous_files'] if a['file'] == file), None)
|
| 431 |
+
|
| 432 |
+
if existing_anomaly:
|
| 433 |
+
# Update existing anomaly record
|
| 434 |
+
existing_anomaly['similarity_to_group_avg'] = similarity_to_avg
|
| 435 |
+
existing_anomaly['is_strong_anomaly'] = (
|
| 436 |
+
similarity_to_avg < 0.4 and existing_anomaly['max_similarity_to_others'] < 0.5
|
| 437 |
+
)
|
| 438 |
+
if existing_anomaly['is_strong_anomaly']:
|
| 439 |
+
existing_anomaly['anomaly_strength'] = 'very_strong'
|
| 440 |
+
elif similarity_to_avg < 0.4: # Low similarity to group average
|
| 441 |
+
# Calculate similarities to all other files
|
| 442 |
+
similarities_to_others = []
|
| 443 |
+
max_sim = 0
|
| 444 |
+
most_sim_file = None
|
| 445 |
+
|
| 446 |
+
for j, other_file in enumerate(changed_files):
|
| 447 |
+
if i != j:
|
| 448 |
+
sim = float(similarity_matrix[i][j])
|
| 449 |
+
similarities_to_others.append({
|
| 450 |
+
'file': other_file,
|
| 451 |
+
'similarity': sim
|
| 452 |
+
})
|
| 453 |
+
if sim > max_sim:
|
| 454 |
+
max_sim = sim
|
| 455 |
+
most_sim_file = other_file
|
| 456 |
+
|
| 457 |
+
result['anomalous_files'].append({
|
| 458 |
+
'file': file,
|
| 459 |
+
'cluster_id': None,
|
| 460 |
+
'max_similarity_to_others': max_sim,
|
| 461 |
+
'most_similar_file': most_sim_file,
|
| 462 |
+
'similarities_to_others': similarities_to_others,
|
| 463 |
+
'similarity_to_group_avg': similarity_to_avg,
|
| 464 |
+
'is_anomaly': True,
|
| 465 |
+
'is_strong_anomaly': max_sim < 0.5,
|
| 466 |
+
'anomaly_strength': 'very_strong' if max_sim < 0.3 else 'strong' if max_sim < 0.5 else 'medium',
|
| 467 |
+
'reason': 'distant_from_group_average'
|
| 468 |
+
})
|
| 469 |
+
|
| 470 |
+
# Update analysis summary
|
| 471 |
+
result['analysis_summary']['num_groups'] = len(result['similar_file_groups'])
|
| 472 |
+
result['analysis_summary']['num_anomalies'] = len(result['anomalous_files'])
|
| 473 |
+
|
| 474 |
+
if result['similar_file_groups']:
|
| 475 |
+
total_files_in_groups = sum(len(group['files']) for group in result['similar_file_groups'])
|
| 476 |
+
result['analysis_summary']['avg_group_size'] = total_files_in_groups / len(result['similar_file_groups'])
|
| 477 |
+
|
| 478 |
+
# Log results
|
| 479 |
+
logger.info(f"File similarity analysis complete:")
|
| 480 |
+
logger.info(f" Total files: {result['analysis_summary']['total_files']}")
|
| 481 |
+
logger.info(f" Similar groups: {result['analysis_summary']['num_groups']}")
|
| 482 |
+
logger.info(f" Anomalous files: {result['analysis_summary']['num_anomalies']}")
|
| 483 |
+
|
| 484 |
+
for i, group in enumerate(result['similar_file_groups']):
|
| 485 |
+
logger.info(f" Group {i+1} ({group['coherence']} coherence): {group['files']} (avg: {group['avg_similarity']:.3f})")
|
| 486 |
+
|
| 487 |
+
for anomaly in result['anomalous_files']:
|
| 488 |
+
logger.info(f" {anomaly['anomaly_strength'].upper()} ANOMALY: {anomaly['file']} (reason: {anomaly['reason']}, max_sim: {anomaly['max_similarity_to_others']:.3f})")
|
| 489 |
+
|
| 490 |
+
return result
|
| 491 |
+
|
| 492 |
+
# TODO: Add local LLM reasoning
|
| 493 |
+
# def generate_llm_response(self, prompt: str, max_new_tokens: int = 256) -> str:
|
| 494 |
+
# """Generate response using the fine-tuned LLM."""
|
| 495 |
+
# if not self.tokenizer or not self.local_llm:
|
| 496 |
+
# raise ValueError("LLM not loaded. Call load_llm() first.")
|
| 497 |
+
|
| 498 |
+
# inputs = self.tokenizer(prompt, return_tensors="pt").to(self.local_llm.device)
|
| 499 |
+
# outputs = self.local_llm.generate(
|
| 500 |
+
# **inputs,
|
| 501 |
+
# max_new_tokens=max_new_tokens,
|
| 502 |
+
# pad_token_id=self.tokenizer.eos_token_id
|
| 503 |
+
# )
|
| 504 |
+
# return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 505 |
+
|
| 506 |
+
def search_code_snippets(self, diff_hunks) -> list:
|
| 507 |
+
metadata_file = self.ctx.model_dirs["index"] / "metadata.json"
|
| 508 |
+
with open(metadata_file, 'r', encoding='utf-8') as f:
|
| 509 |
+
metadata = json.load(f)
|
| 510 |
+
|
| 511 |
+
result = []
|
| 512 |
+
|
| 513 |
+
# Process each file's diff hunks
|
| 514 |
+
for file_path, hunks in diff_hunks.items():
|
| 515 |
+
logger.info(f"Searching functions for file: {file_path}")
|
| 516 |
+
|
| 517 |
+
for hunk in hunks:
|
| 518 |
+
line_range = hunk.get('line_range')
|
| 519 |
+
if not line_range:
|
| 520 |
+
continue
|
| 521 |
+
|
| 522 |
+
start_line, end_line = line_range
|
| 523 |
+
logger.debug(f"Processing hunk at lines {start_line}-{end_line}")
|
| 524 |
+
|
| 525 |
+
# Find functions that overlap with this line range
|
| 526 |
+
overlapping_functions = []
|
| 527 |
+
|
| 528 |
+
for func_metadata in metadata:
|
| 529 |
+
func_file = func_metadata.get('file', '')
|
| 530 |
+
func_start = func_metadata.get('start_line')
|
| 531 |
+
func_end = func_metadata.get('end_line')
|
| 532 |
+
func_name = func_metadata.get('name', 'unknown')
|
| 533 |
+
func_description = func_metadata.get('llm_description', '')
|
| 534 |
+
|
| 535 |
+
# Check if this function is in the same file
|
| 536 |
+
if func_file != file_path:
|
| 537 |
+
continue
|
| 538 |
+
|
| 539 |
+
# Check if function line range overlaps with diff hunk line range
|
| 540 |
+
if func_start is not None and func_end is not None:
|
| 541 |
+
# Check for overlap: function overlaps if it starts before diff ends
|
| 542 |
+
# and ends after diff starts
|
| 543 |
+
if func_start <= end_line and func_end >= start_line:
|
| 544 |
+
overlap_start = max(func_start, start_line)
|
| 545 |
+
overlap_end = min(func_end, end_line)
|
| 546 |
+
|
| 547 |
+
overlapping_functions.append({
|
| 548 |
+
'function_name': func_name,
|
| 549 |
+
'function_description': func_description,
|
| 550 |
+
'function_start_line': func_start,
|
| 551 |
+
'function_end_line': func_end,
|
| 552 |
+
# 'overlap_start': overlap_start,
|
| 553 |
+
# 'overlap_end': overlap_end,
|
| 554 |
+
# 'overlap_lines': overlap_end - overlap_start + 1
|
| 555 |
+
})
|
| 556 |
+
|
| 557 |
+
# if len(overlapping_functions) > 0:
|
| 558 |
+
hunk_result = {
|
| 559 |
+
'file_name': file_path,
|
| 560 |
+
'diff_hunk': hunk.get('content', ''),
|
| 561 |
+
'overlapping_functions': overlapping_functions
|
| 562 |
+
}
|
| 563 |
+
|
| 564 |
+
result.append(hunk_result)
|
| 565 |
+
|
| 566 |
+
total_hunks = sum(len(hunks) for hunks in diff_hunks.values())
|
| 567 |
+
total_functions = sum(len(entry['overlapping_functions']) for entry in result)
|
| 568 |
+
logger.info(f"Processed {total_hunks} diff hunks across {len(diff_hunks)} files, found {total_functions} overlapping functions")
|
| 569 |
+
|
| 570 |
+
return result
|
| 571 |
+
|
| 572 |
+
def _select_files_around_changed(self, changed_files: List[str] = None, max_files: int = 500) -> List[str]:
|
| 573 |
+
"""Select files to visualize, prioritizing changed files and semantically similar ones."""
|
| 574 |
+
|
| 575 |
+
logger.info(f"Selecting {max_files} files around {len(changed_files)} changed files...")
|
| 576 |
+
|
| 577 |
+
# Start with changed files
|
| 578 |
+
selected_files = set(changed_files)
|
| 579 |
+
|
| 580 |
+
# Find files similar to changed files using embeddings
|
| 581 |
+
try:
|
| 582 |
+
# Encode changed files
|
| 583 |
+
changed_embeddings = self.embedder.encode(changed_files, convert_to_tensor=False)
|
| 584 |
+
|
| 585 |
+
# Calculate target number of similar files to find
|
| 586 |
+
target_similar = min(max_files - len(changed_files), 200) # Leave room for random files
|
| 587 |
+
|
| 588 |
+
# Get a sample of repo files to compare against (for performance)
|
| 589 |
+
sample_size = min(2000, len(self.repo_files))
|
| 590 |
+
repo_sample = self.repo_files[:sample_size]
|
| 591 |
+
|
| 592 |
+
# Remove already selected files from sample
|
| 593 |
+
repo_sample = [f for f in repo_sample if f not in selected_files]
|
| 594 |
+
|
| 595 |
+
if len(repo_sample) > 0:
|
| 596 |
+
# Encode sample files
|
| 597 |
+
sample_embeddings = self.embedder.encode(repo_sample, convert_to_tensor=False, show_progress_bar=False)
|
| 598 |
+
|
| 599 |
+
# Calculate similarities
|
| 600 |
+
similarities = []
|
| 601 |
+
for i, repo_file in enumerate(repo_sample):
|
| 602 |
+
# Calculate max similarity to any changed file
|
| 603 |
+
max_sim = 0
|
| 604 |
+
for changed_emb in changed_embeddings:
|
| 605 |
+
sim = np.dot(changed_emb, sample_embeddings[i]) / (
|
| 606 |
+
np.linalg.norm(changed_emb) * np.linalg.norm(sample_embeddings[i])
|
| 607 |
+
)
|
| 608 |
+
max_sim = max(max_sim, sim)
|
| 609 |
+
# Only add if not already selected (avoid duplicates)
|
| 610 |
+
similarities.append((repo_file, max_sim))
|
| 611 |
+
|
| 612 |
+
# Sort by similarity and take top ones, avoiding duplicates
|
| 613 |
+
added = 0
|
| 614 |
+
for file_path, sim in sorted(similarities, key=lambda x: x[1], reverse=True):
|
| 615 |
+
if file_path not in selected_files:
|
| 616 |
+
selected_files.add(file_path)
|
| 617 |
+
added += 1
|
| 618 |
+
if len(selected_files) >= max_files or added >= target_similar:
|
| 619 |
+
break
|
| 620 |
+
logger.info(f"Added {len(similarities[:target_similar])} similar files to visualization")
|
| 621 |
+
|
| 622 |
+
except Exception as e:
|
| 623 |
+
logger.warning(f"Could not compute file similarities: {e}")
|
| 624 |
+
|
| 625 |
+
# Fill remaining slots with random files
|
| 626 |
+
remaining_slots = max_files - len(selected_files)
|
| 627 |
+
if remaining_slots > 0:
|
| 628 |
+
remaining_files = [f for f in self.repo_files if f not in selected_files]
|
| 629 |
+
random.shuffle(remaining_files)
|
| 630 |
+
for file_path in remaining_files[:remaining_slots]:
|
| 631 |
+
selected_files.add(file_path)
|
| 632 |
+
|
| 633 |
+
result = list(selected_files)
|
| 634 |
+
logger.info(f"Selected {len(result)} files total: {len(changed_files)} changed, {len(result) - len(changed_files)} related/random")
|
| 635 |
+
return result
|
| 636 |
+
|
| 637 |
+
def create_repo_visualization(self, changed_files: List[str] = None, max_files: int = 500):
|
| 638 |
+
files_to_plot = self._select_files_around_changed(changed_files, max_files * len(changed_files))
|
| 639 |
+
logger.info(f"Creating visualization for {len(files_to_plot)} files...")
|
| 640 |
+
|
| 641 |
+
if len(files_to_plot) < 2:
|
| 642 |
+
return self._create_dummy_plot(f"Only {len(files_to_plot)} files available")
|
| 643 |
+
|
| 644 |
+
embeddings = self.embedder.encode(files_to_plot, convert_to_tensor=False, show_progress_bar=False)
|
| 645 |
+
logger.info(f"Embeddings computed successfully: shape {getattr(embeddings, 'shape', None)}")
|
| 646 |
+
|
| 647 |
+
n = len(files_to_plot)
|
| 648 |
+
perplexity = min(30, max(1, n - 1))
|
| 649 |
+
tsne = TSNE(n_components=3, perplexity=perplexity, init='random', random_state=42)
|
| 650 |
+
reduced = tsne.fit_transform(embeddings)
|
| 651 |
+
|
| 652 |
+
fig = go.Figure()
|
| 653 |
+
|
| 654 |
+
colors = []
|
| 655 |
+
sizes = []
|
| 656 |
+
hover_texts = []
|
| 657 |
+
|
| 658 |
+
for i, file_path in enumerate(files_to_plot):
|
| 659 |
+
if changed_files and file_path in changed_files:
|
| 660 |
+
colors.append('red')
|
| 661 |
+
else:
|
| 662 |
+
# Color by file type
|
| 663 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 664 |
+
if ext in ['.py', '.js', '.ts', '.java', '.cpp', '.c', '.cs', '.rb', '.go', '.rs']:
|
| 665 |
+
colors.append('blue')
|
| 666 |
+
elif ext in ['.md', '.txt', '.rst', '.doc']:
|
| 667 |
+
colors.append('green')
|
| 668 |
+
elif ext in ['.json', '.yaml', '.yml', '.xml', '.toml', '.ini']:
|
| 669 |
+
colors.append('orange')
|
| 670 |
+
elif ext in ['.html', '.css', '.scss', '.sass']:
|
| 671 |
+
colors.append('purple')
|
| 672 |
+
else:
|
| 673 |
+
colors.append('gray')
|
| 674 |
+
sizes.append(8)
|
| 675 |
+
hover_texts.append(f"{os.path.basename(file_path)}")
|
| 676 |
+
|
| 677 |
+
fig.add_trace(go.Scatter3d(
|
| 678 |
+
x=reduced[:, 0].tolist(),
|
| 679 |
+
y=reduced[:, 1].tolist(),
|
| 680 |
+
z=reduced[:, 2].tolist(),
|
| 681 |
+
mode='markers+text',
|
| 682 |
+
marker=dict(size=sizes, color=colors),
|
| 683 |
+
text=[os.path.basename(f) for f in files_to_plot],
|
| 684 |
+
hovertext=hover_texts,
|
| 685 |
+
textposition='middle center',
|
| 686 |
+
name='Repository Files'
|
| 687 |
+
))
|
| 688 |
+
|
| 689 |
+
title_text = 'Repository File Embeddings (3D t-SNE)'
|
| 690 |
+
if changed_files:
|
| 691 |
+
title_text += f' - {len(changed_files)} Changed Files Highlighted in Red'
|
| 692 |
+
|
| 693 |
+
fig.update_layout(
|
| 694 |
+
title=title_text,
|
| 695 |
+
scene=dict(
|
| 696 |
+
xaxis_title='t-SNE 1',
|
| 697 |
+
yaxis_title='t-SNE 2',
|
| 698 |
+
zaxis_title='t-SNE 3',
|
| 699 |
+
camera=dict(eye=dict(x=1.5, y=1.5, z=1.5))
|
| 700 |
+
),
|
| 701 |
+
width=800,
|
| 702 |
+
height=600,
|
| 703 |
+
margin=dict(r=20, b=10, l=10, t=60)
|
| 704 |
+
)
|
| 705 |
+
|
| 706 |
+
return fig
|
| 707 |
+
|
| 708 |
+
def get_current_logs():
|
| 709 |
+
return log_stream.getvalue()
|
| 710 |
+
|
| 711 |
+
# Pipeline
|
| 712 |
+
|
| 713 |
+
pipeline = InferencePipeline(InferenceContext("https://github.com/dotnet/xharness"))
|
| 714 |
+
|
| 715 |
+
def analyze_pr_streaming(pr_url):
|
| 716 |
+
log_stream.seek(0)
|
| 717 |
+
log_stream.truncate()
|
| 718 |
+
|
| 719 |
+
response = {}
|
| 720 |
+
base_review = ""
|
| 721 |
+
final_review = ""
|
| 722 |
+
visualization = None
|
| 723 |
+
|
| 724 |
+
data = pipeline._extract_pr_data(pr_url)
|
| 725 |
+
yield base_review, final_review, get_current_logs(), visualization
|
| 726 |
+
|
| 727 |
+
visualization = pipeline.create_repo_visualization(list(data["changed_files"]), max_files=20)
|
| 728 |
+
yield "", "", get_current_logs(), visualization
|
| 729 |
+
|
| 730 |
+
similarity_analysis = pipeline.analyze_file_similarity(list(data["changed_files"]))
|
| 731 |
+
similar_file_groups = similarity_analysis['similar_file_groups']
|
| 732 |
+
anomalous_files = similarity_analysis['anomalous_files']
|
| 733 |
+
yield "", "", get_current_logs(), visualization
|
| 734 |
+
|
| 735 |
+
code_description = pipeline.search_code_snippets(data["diff_hunks"])
|
| 736 |
+
|
| 737 |
+
# Base prompt
|
| 738 |
+
base_prompt = f"""You are an expert code reviewer. Analyze the PR below and provide detailed feedback with specific line-by-line suggestions:
|
| 739 |
+
Provide a detailed code review including:
|
| 740 |
+
1. **Code Quality Issues**: Point out specific lines with problems
|
| 741 |
+
2. **Suggested Fixes**: Provide exact code suggestions with diff format
|
| 742 |
+
3. **Security Concerns**: Highlight any security vulnerabilities
|
| 743 |
+
4. **Performance Issues**: Identify potential performance problems
|
| 744 |
+
5. **Best Practices**: Suggest improvements following coding standards
|
| 745 |
+
6. **Testing Recommendations**: What tests should be added/modified
|
| 746 |
+
|
| 747 |
+
Format your suggestions like this for each issue:
|
| 748 |
+
**File: `filename.ext` Line X**
|
| 749 |
+
Problem: [description]
|
| 750 |
+
```diff
|
| 751 |
+
- old code line
|
| 752 |
+
+ suggested new code line
|
| 753 |
+
```
|
| 754 |
+
|
| 755 |
+
TITLE: {data['title']}
|
| 756 |
+
|
| 757 |
+
DESCRIPTION: {data['body']}
|
| 758 |
+
|
| 759 |
+
CHANGED FILES: {', '.join(data['changed_files'])}
|
| 760 |
+
"""
|
| 761 |
+
|
| 762 |
+
similar_file_groups_formatted = []
|
| 763 |
+
for i, group in enumerate(similar_file_groups):
|
| 764 |
+
files_str = ", ".join(group['files'])
|
| 765 |
+
similar_file_groups_formatted.append(f"group {i}: {files_str}")
|
| 766 |
+
|
| 767 |
+
anomalous_files_formatted = []
|
| 768 |
+
for anomaly in anomalous_files:
|
| 769 |
+
anomalous_files_formatted.append(f"anomaly: {anomaly['file']} (reason: {anomaly['reason']}, strength: {anomaly['anomaly_strength']})")
|
| 770 |
+
|
| 771 |
+
grounding_formatted = ""
|
| 772 |
+
for entry in code_description:
|
| 773 |
+
file_name = entry['file_name']
|
| 774 |
+
overlapping_functions = entry['overlapping_functions']
|
| 775 |
+
diff_hunk = entry['diff_hunk']
|
| 776 |
+
|
| 777 |
+
if len(overlapping_functions) > 0:
|
| 778 |
+
grounding_formatted += f"In file {file_name}, the following changes were made: {diff_hunk}\n"
|
| 779 |
+
grounding_formatted += f"These changes affected the following functions:\n"
|
| 780 |
+
for func in overlapping_functions:
|
| 781 |
+
grounding_formatted += f"{func['function_name']} - {func['function_description']}\n"
|
| 782 |
+
else:
|
| 783 |
+
grounding_formatted += f"In file {file_name}, the following changes were made: {diff_hunk}\n"
|
| 784 |
+
|
| 785 |
+
grounding_formatted += "\n"
|
| 786 |
+
|
| 787 |
+
# Create formatted strings for f-string
|
| 788 |
+
similar_groups_text = "\n".join(similar_file_groups_formatted)
|
| 789 |
+
anomalous_files_text = "\n".join(anomalous_files_formatted)
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
# TODO: Add local LLM reasoning
|
| 793 |
+
# TODO: Add relevant files from the directory not included
|
| 794 |
+
comprehensive_prompt = f"""{base_prompt}
|
| 795 |
+
FILES THAT ARE SEMANTICALLY CLOSE CHANGED IN THIS PR:
|
| 796 |
+
{similar_groups_text}
|
| 797 |
+
|
| 798 |
+
UNEXPECTED CHANGES IN FILES:
|
| 799 |
+
{anomalous_files_text}
|
| 800 |
+
|
| 801 |
+
GROUNDING DATA: The following provides specific information about which functions are affected by each diff hunk:
|
| 802 |
+
{grounding_formatted}
|
| 803 |
+
"""
|
| 804 |
+
|
| 805 |
+
base_prompt += f"""
|
| 806 |
+
DIFF: {data['diff']}
|
| 807 |
+
"""
|
| 808 |
+
|
| 809 |
+
logger.info(f"Base prompt word count: {len(base_prompt.split())}")
|
| 810 |
+
# logger.info(f"Base prompt: {base_prompt}")
|
| 811 |
+
|
| 812 |
+
logger.info(f"Comprehensive prompt word count: {len(comprehensive_prompt.split())}")
|
| 813 |
+
# logger.info(f"Comprehensive prompt: {comprehensive_prompt}")
|
| 814 |
+
|
| 815 |
+
logger.info("Calling Azure OpenAI...")
|
| 816 |
+
yield "", "", get_current_logs(), visualization
|
| 817 |
+
|
| 818 |
+
base_review_response = pipeline.enterprise_llm.chat.completions.create(
|
| 819 |
+
model=DEPLOYMENT,
|
| 820 |
+
messages=[
|
| 821 |
+
{"role": "system", "content": "You are an expert code reviewer. Provide thorough, constructive feedback."},
|
| 822 |
+
{"role": "user", "content": base_prompt}
|
| 823 |
+
],
|
| 824 |
+
max_tokens=8192,
|
| 825 |
+
temperature=0.3
|
| 826 |
+
)
|
| 827 |
+
|
| 828 |
+
base_review = base_review_response.choices[0].message.content
|
| 829 |
+
logger.info("Base review completed")
|
| 830 |
+
|
| 831 |
+
final_review_response = pipeline.enterprise_llm.chat.completions.create(
|
| 832 |
+
model=DEPLOYMENT,
|
| 833 |
+
messages=[
|
| 834 |
+
{"role": "system", "content": "You are an expert code reviewer. Provide thorough, constructive feedback."},
|
| 835 |
+
{"role": "user", "content": comprehensive_prompt}
|
| 836 |
+
],
|
| 837 |
+
max_tokens=8192,
|
| 838 |
+
temperature=0.3
|
| 839 |
+
)
|
| 840 |
+
|
| 841 |
+
final_review = final_review_response.choices[0].message.content
|
| 842 |
+
logger.info("Final review completed")
|
| 843 |
+
|
| 844 |
+
yield base_review, final_review, get_current_logs(), visualization
|
| 845 |
|
| 846 |
+
with gr.Blocks(title="PR Code Review Assistant") as demo:
|
| 847 |
+
gr.Markdown("# PR Code Review Assistant")
|
| 848 |
+
gr.Markdown("Enter a GitHub PR URL to get comprehensive code review analysis with interactive repository visualization.")
|
| 849 |
+
|
| 850 |
+
with gr.Row():
|
| 851 |
+
pr_url_input = gr.Textbox(
|
| 852 |
+
label="GitHub PR URL",
|
| 853 |
+
placeholder="https://github.com/owner/repo/pull/123",
|
| 854 |
+
value="https://github.com/dotnet/xharness/pull/1416"
|
| 855 |
+
)
|
| 856 |
+
|
| 857 |
+
analyze_btn = gr.Button("Analyze PR", variant="primary")
|
| 858 |
+
|
| 859 |
+
with gr.Row():
|
| 860 |
+
with gr.Column(scale=1):
|
| 861 |
+
base_review_output = gr.Textbox(
|
| 862 |
+
label="Base Review",
|
| 863 |
+
lines=15,
|
| 864 |
+
max_lines=30,
|
| 865 |
+
interactive=False
|
| 866 |
+
)
|
| 867 |
+
|
| 868 |
+
with gr.Column(scale=1):
|
| 869 |
+
final_review_output = gr.Textbox(
|
| 870 |
+
label="Comprehensive Review",
|
| 871 |
+
lines=15,
|
| 872 |
+
max_lines=30,
|
| 873 |
+
interactive=False
|
| 874 |
+
)
|
| 875 |
+
|
| 876 |
+
with gr.Row():
|
| 877 |
+
with gr.Column(scale=1):
|
| 878 |
+
visualization_output = gr.Plot(
|
| 879 |
+
label="Repository Files Visualization (3D)",
|
| 880 |
+
value=None
|
| 881 |
+
)
|
| 882 |
+
|
| 883 |
+
with gr.Column(scale=1):
|
| 884 |
+
logs_output = gr.Textbox(
|
| 885 |
+
label="Analysis Logs",
|
| 886 |
+
lines=15,
|
| 887 |
+
max_lines=25,
|
| 888 |
+
interactive=False,
|
| 889 |
+
show_copy_button=True
|
| 890 |
+
)
|
| 891 |
+
|
| 892 |
+
analyze_btn.click(
|
| 893 |
+
fn=analyze_pr_streaming,
|
| 894 |
+
inputs=[pr_url_input],
|
| 895 |
+
outputs=[base_review_output, final_review_output, logs_output, visualization_output],
|
| 896 |
+
show_progress=True
|
| 897 |
+
)
|
| 898 |
|
| 899 |
if __name__ == "__main__":
|
| 900 |
demo.launch()
|
requirements.txt
CHANGED
|
@@ -1 +1,54 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Core ML dependencies
|
| 2 |
+
torch>=2.0.0
|
| 3 |
+
transformers>=4.30.0
|
| 4 |
+
sentence-transformers>=2.2.2
|
| 5 |
+
faiss-cpu>=1.7.4
|
| 6 |
+
numpy>=1.21.0
|
| 7 |
+
|
| 8 |
+
# Data processing
|
| 9 |
+
pandas>=1.5.0
|
| 10 |
+
datasets>=2.12.0
|
| 11 |
+
accelerate>=0.20.0
|
| 12 |
+
peft>=0.4.0
|
| 13 |
+
bitsandbytes>=0.39.0
|
| 14 |
+
huggingface_hub>=0.16.0
|
| 15 |
+
|
| 16 |
+
# GitHub integration
|
| 17 |
+
PyGithub
|
| 18 |
+
GitPython>=3.1.0
|
| 19 |
+
requests>=2.28.0
|
| 20 |
+
python-dotenv>=1.0.0
|
| 21 |
+
tenacity>=8.2.0
|
| 22 |
+
|
| 23 |
+
# Tree-sitter parsers
|
| 24 |
+
tree-sitter>=0.20.0
|
| 25 |
+
tree-sitter-python>=0.20.0
|
| 26 |
+
tree-sitter-c>=0.20.0
|
| 27 |
+
tree-sitter-cpp>=0.20.0
|
| 28 |
+
tree-sitter-java>=0.20.0
|
| 29 |
+
tree-sitter-c-sharp>=0.20.0
|
| 30 |
+
tree-sitter-javascript>=0.20.0
|
| 31 |
+
|
| 32 |
+
# Web interface
|
| 33 |
+
flask>=2.3.0
|
| 34 |
+
flask-session>=0.5.0
|
| 35 |
+
|
| 36 |
+
# Utilities
|
| 37 |
+
tqdm>=4.64.0
|
| 38 |
+
schedule>=1.2.0
|
| 39 |
+
openai
|
| 40 |
+
|
| 41 |
+
# Development
|
| 42 |
+
pytest>=7.0.0
|
| 43 |
+
black>=23.0.0
|
| 44 |
+
flake8>=6.0.0
|
| 45 |
+
|
| 46 |
+
# Transformers library for NLP tasks
|
| 47 |
+
transformers
|
| 48 |
+
matplotlib>=3.5.0
|
| 49 |
+
scikit-learn>=1.1.0
|
| 50 |
+
gradio>=4.0.0
|
| 51 |
+
|
| 52 |
+
# Visualization dependencies
|
| 53 |
+
plotly>=5.0.0
|
| 54 |
+
openai
|