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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import requests
|
| 4 |
+
from groq import Groq
|
| 5 |
+
import json
|
| 6 |
+
from typing import Dict, List, Tuple, Optional
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
import re
|
| 9 |
+
|
| 10 |
+
# Get API keys from Hugging Face secrets (environment variables)
|
| 11 |
+
GROQ_API_KEY = os.getenv('GROQ_API_KEY')
|
| 12 |
+
BLACKBOX_API_KEY = os.getenv('BLACKBOX_API_KEY')
|
| 13 |
+
|
| 14 |
+
# Initialize Groq client
|
| 15 |
+
client = Groq(api_key=GROQ_API_KEY) if GROQ_API_KEY else None
|
| 16 |
+
|
| 17 |
+
# BLACKBOX API configuration
|
| 18 |
+
BLACKBOX_API_URL = "https://api.blackbox.ai/v1/chat/completions"
|
| 19 |
+
|
| 20 |
+
def comprehensive_code_review(code: str) -> Dict[str, str]:
|
| 21 |
+
"""
|
| 22 |
+
Perform comprehensive automated code review using Groq + Llama
|
| 23 |
+
"""
|
| 24 |
+
if not client:
|
| 25 |
+
return {
|
| 26 |
+
"groq_review": "Error: Groq API key not configured. Please set GROQ_API_KEY in environment variables.",
|
| 27 |
+
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 28 |
+
"model": "error"
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
# Enhanced prompt for comprehensive code review
|
| 33 |
+
review_prompt = f"""
|
| 34 |
+
Perform a comprehensive automated code review for the following code:
|
| 35 |
+
|
| 36 |
+
```
|
| 37 |
+
{code}
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
Provide detailed analysis in the following categories:
|
| 41 |
+
|
| 42 |
+
1. **CODE QUALITY ASSESSMENT**
|
| 43 |
+
- Overall code quality score (1-10)
|
| 44 |
+
- Readability and maintainability
|
| 45 |
+
- Code structure and organization
|
| 46 |
+
|
| 47 |
+
2. **STYLE & BEST PRACTICES**
|
| 48 |
+
- Coding style compliance
|
| 49 |
+
- Naming conventions
|
| 50 |
+
- Best practices adherence
|
| 51 |
+
- Documentation quality
|
| 52 |
+
|
| 53 |
+
3. **BUG DETECTION**
|
| 54 |
+
- Syntax errors
|
| 55 |
+
- Logic errors
|
| 56 |
+
- Potential runtime issues
|
| 57 |
+
- Edge case handling
|
| 58 |
+
|
| 59 |
+
4. **SECURITY ANALYSIS**
|
| 60 |
+
- Security vulnerabilities
|
| 61 |
+
- Input validation issues
|
| 62 |
+
- Authentication/authorization concerns
|
| 63 |
+
- Data exposure risks
|
| 64 |
+
|
| 65 |
+
5. **PERFORMANCE OPTIMIZATION**
|
| 66 |
+
- Performance bottlenecks
|
| 67 |
+
- Memory usage optimization
|
| 68 |
+
- Algorithm efficiency
|
| 69 |
+
- Database query optimization (if applicable)
|
| 70 |
+
|
| 71 |
+
6. **IMPROVEMENT SUGGESTIONS**
|
| 72 |
+
- Specific code improvements
|
| 73 |
+
- Refactoring recommendations
|
| 74 |
+
- Alternative implementations
|
| 75 |
+
- Testing suggestions
|
| 76 |
+
|
| 77 |
+
7. **REVIEW COMMENTS**
|
| 78 |
+
- Line-by-line review comments
|
| 79 |
+
- Priority levels (Critical, High, Medium, Low)
|
| 80 |
+
- Actionable recommendations
|
| 81 |
+
|
| 82 |
+
Format your response with clear headings and provide specific examples where possible.
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
chat_completion = client.chat.completions.create(
|
| 86 |
+
messages=[
|
| 87 |
+
{
|
| 88 |
+
"role": "system",
|
| 89 |
+
"content": "You are a senior software engineer and code review expert. Provide detailed, constructive, and actionable code review feedback."
|
| 90 |
+
},
|
| 91 |
+
{
|
| 92 |
+
"role": "user",
|
| 93 |
+
"content": review_prompt
|
| 94 |
+
}
|
| 95 |
+
],
|
| 96 |
+
model="llama3-8b-8192",
|
| 97 |
+
temperature=0.1,
|
| 98 |
+
max_tokens=2000,
|
| 99 |
+
top_p=1,
|
| 100 |
+
stream=False,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
return {
|
| 104 |
+
"groq_review": chat_completion.choices[0].message.content,
|
| 105 |
+
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 106 |
+
"model": "llama3-8b-8192"
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
except Exception as e:
|
| 110 |
+
return {
|
| 111 |
+
"groq_review": f"Error performing code review: {str(e)}",
|
| 112 |
+
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 113 |
+
"model": "error"
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
def enhanced_blackbox_review(code: str, groq_review: str) -> str:
|
| 117 |
+
"""
|
| 118 |
+
Enhanced BLACKBOX.AI review with focus on automated review features
|
| 119 |
+
"""
|
| 120 |
+
if not BLACKBOX_API_KEY:
|
| 121 |
+
return "Error: BLACKBOX API key not configured. Please set BLACKBOX_API_KEY in environment variables."
|
| 122 |
+
|
| 123 |
+
try:
|
| 124 |
+
headers = {
|
| 125 |
+
"Authorization": f"Bearer {BLACKBOX_API_KEY}",
|
| 126 |
+
"Content-Type": "application/json"
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
payload = {
|
| 130 |
+
"model": "blackbox",
|
| 131 |
+
"messages": [
|
| 132 |
+
{
|
| 133 |
+
"role": "system",
|
| 134 |
+
"content": "You are BLACKBOX.AI, an expert automated code review assistant. Focus on providing additional insights, alternative solutions, and integration recommendations."
|
| 135 |
+
},
|
| 136 |
+
{
|
| 137 |
+
"role": "user",
|
| 138 |
+
"content": f"""
|
| 139 |
+
Original Code:
|
| 140 |
+
```
|
| 141 |
+
{code}
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
Previous Review Analysis:
|
| 145 |
+
{groq_review}
|
| 146 |
+
|
| 147 |
+
Please provide additional automated code review insights:
|
| 148 |
+
|
| 149 |
+
1. **ADVANCED PATTERNS & ARCHITECTURE**
|
| 150 |
+
- Design pattern suggestions
|
| 151 |
+
- Architecture improvements
|
| 152 |
+
- SOLID principles compliance
|
| 153 |
+
|
| 154 |
+
2. **FRAMEWORK-SPECIFIC RECOMMENDATIONS**
|
| 155 |
+
- Framework best practices
|
| 156 |
+
- Library usage optimization
|
| 157 |
+
- Integration patterns
|
| 158 |
+
|
| 159 |
+
3. **SCALABILITY & MAINTAINABILITY**
|
| 160 |
+
- Long-term maintainability
|
| 161 |
+
- Scalability considerations
|
| 162 |
+
- Technical debt assessment
|
| 163 |
+
|
| 164 |
+
4. **AUTOMATED TESTING SUGGESTIONS**
|
| 165 |
+
- Unit test recommendations
|
| 166 |
+
- Integration test strategies
|
| 167 |
+
- Mock and stub suggestions
|
| 168 |
+
|
| 169 |
+
5. **DEPLOYMENT & DEVOPS CONSIDERATIONS**
|
| 170 |
+
- CI/CD pipeline compatibility
|
| 171 |
+
- Containerization readiness
|
| 172 |
+
- Configuration management
|
| 173 |
+
|
| 174 |
+
Provide concrete, actionable recommendations with code examples where appropriate.
|
| 175 |
+
"""
|
| 176 |
+
}
|
| 177 |
+
],
|
| 178 |
+
"temperature": 0.2,
|
| 179 |
+
"max_tokens": 1500
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
response = requests.post(BLACKBOX_API_URL, headers=headers, json=payload)
|
| 183 |
+
|
| 184 |
+
if response.status_code == 200:
|
| 185 |
+
return response.json()["choices"][0]["message"]["content"]
|
| 186 |
+
else:
|
| 187 |
+
return f"BLACKBOX.AI enhancement unavailable (Status: {response.status_code})"
|
| 188 |
+
|
| 189 |
+
except Exception as e:
|
| 190 |
+
return f"Error enhancing review with BLACKBOX.AI: {str(e)}"
|
| 191 |
+
|
| 192 |
+
def generate_review_summary(groq_review: str, blackbox_review: str) -> Dict[str, any]:
|
| 193 |
+
"""
|
| 194 |
+
Generate a comprehensive review summary with metrics
|
| 195 |
+
"""
|
| 196 |
+
# Extract key metrics (simplified implementation)
|
| 197 |
+
issues_found = groq_review.count("issue") + groq_review.count("error") + groq_review.count("problem")
|
| 198 |
+
suggestions_made = groq_review.count("suggest") + groq_review.count("recommend") + groq_review.count("improve")
|
| 199 |
+
|
| 200 |
+
# Determine overall rating based on content analysis
|
| 201 |
+
critical_keywords = ["critical", "security", "vulnerability", "bug", "error"]
|
| 202 |
+
critical_issues = sum(1 for keyword in critical_keywords if keyword in groq_review.lower())
|
| 203 |
+
|
| 204 |
+
if critical_issues > 3:
|
| 205 |
+
overall_rating = "Needs Significant Improvement"
|
| 206 |
+
elif critical_issues > 1:
|
| 207 |
+
overall_rating = "Needs Improvement"
|
| 208 |
+
elif issues_found > 5:
|
| 209 |
+
overall_rating = "Good with Minor Issues"
|
| 210 |
+
else:
|
| 211 |
+
overall_rating = "Excellent"
|
| 212 |
+
|
| 213 |
+
return {
|
| 214 |
+
"overall_rating": overall_rating,
|
| 215 |
+
"issues_found": issues_found,
|
| 216 |
+
"suggestions_made": suggestions_made,
|
| 217 |
+
"critical_issues": critical_issues,
|
| 218 |
+
"review_date": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
def unified_code_analysis(code: str, analysis_type: str) -> Tuple[str, str, str, str, Dict]:
|
| 222 |
+
"""
|
| 223 |
+
Unified analysis combining original functionality with automated code review
|
| 224 |
+
"""
|
| 225 |
+
if analysis_type.lower() == "automated_review":
|
| 226 |
+
# Perform comprehensive automated code review
|
| 227 |
+
review_result = comprehensive_code_review(code)
|
| 228 |
+
groq_analysis = review_result["groq_review"]
|
| 229 |
+
|
| 230 |
+
# Enhance with BLACKBOX.AI
|
| 231 |
+
blackbox_enhancement = enhanced_blackbox_review(code, groq_analysis)
|
| 232 |
+
|
| 233 |
+
# Generate summary metrics
|
| 234 |
+
summary_metrics = generate_review_summary(groq_analysis, blackbox_enhancement)
|
| 235 |
+
|
| 236 |
+
# Create combined report
|
| 237 |
+
combined_analysis = f"""
|
| 238 |
+
# π Automated Code Review Report
|
| 239 |
+
|
| 240 |
+
**Review Date:** {summary_metrics['review_date']}
|
| 241 |
+
**Overall Rating:** {summary_metrics['overall_rating']}
|
| 242 |
+
**Issues Found:** {summary_metrics['issues_found']}
|
| 243 |
+
**Suggestions Made:** {summary_metrics['suggestions_made']}
|
| 244 |
+
**Critical Issues:** {summary_metrics['critical_issues']}
|
| 245 |
+
|
| 246 |
+
---
|
| 247 |
+
|
| 248 |
+
## π€ Primary AI Review (Groq + Llama)
|
| 249 |
+
{groq_analysis}
|
| 250 |
+
|
| 251 |
+
---
|
| 252 |
+
|
| 253 |
+
## π Enhanced Review (BLACKBOX.AI)
|
| 254 |
+
{blackbox_enhancement}
|
| 255 |
+
|
| 256 |
+
---
|
| 257 |
+
|
| 258 |
+
## π Review Summary
|
| 259 |
+
This automated code review has identified **{summary_metrics['issues_found']} potential issues** and provided **{summary_metrics['suggestions_made']} improvement suggestions**. The code has been rated as **{summary_metrics['overall_rating']}**.
|
| 260 |
+
"""
|
| 261 |
+
|
| 262 |
+
return groq_analysis, blackbox_enhancement, combined_analysis, f"**Review Rating:** {summary_metrics['overall_rating']}", summary_metrics
|
| 263 |
+
|
| 264 |
+
else:
|
| 265 |
+
return "Invalid analysis type", "", "", "Error", {}
|
| 266 |
+
|
| 267 |
+
def create_gradio_interface():
|
| 268 |
+
"""
|
| 269 |
+
Create Gradio interface with proper markdown rendering
|
| 270 |
+
"""
|
| 271 |
+
|
| 272 |
+
def analyze_code_interface(code_input: str, analysis_type: str) -> Tuple[str, str, str]:
|
| 273 |
+
"""
|
| 274 |
+
Interface function for Gradio - Updated for 3 outputs only
|
| 275 |
+
"""
|
| 276 |
+
if not code_input.strip():
|
| 277 |
+
return "Please enter code to analyze.", "", ""
|
| 278 |
+
|
| 279 |
+
# Check API configuration
|
| 280 |
+
if not GROQ_API_KEY:
|
| 281 |
+
error_msg = "β οΈ GROQ API key not configured. Please set GROQ_API_KEY in environment variables."
|
| 282 |
+
return error_msg, error_msg, error_msg
|
| 283 |
+
|
| 284 |
+
if not BLACKBOX_API_KEY:
|
| 285 |
+
error_msg = "β οΈ BLACKBOX API key not configured. Please set BLACKBOX_API_KEY in environment variables."
|
| 286 |
+
return error_msg, error_msg, error_msg
|
| 287 |
+
|
| 288 |
+
try:
|
| 289 |
+
groq_result, blackbox_result, combined_result, summary, metrics = unified_code_analysis(
|
| 290 |
+
code_input, analysis_type.lower().replace(" ", "_")
|
| 291 |
+
)
|
| 292 |
+
return groq_result, combined_result, summary
|
| 293 |
+
except Exception as e:
|
| 294 |
+
error_msg = f"Analysis failed: {str(e)}"
|
| 295 |
+
return error_msg, error_msg, error_msg
|
| 296 |
+
|
| 297 |
+
# Create Gradio interface
|
| 298 |
+
with gr.Blocks(
|
| 299 |
+
title="π§ AI Code Assistant - Automated Review",
|
| 300 |
+
theme=gr.themes.Soft(),
|
| 301 |
+
css="""
|
| 302 |
+
.gradio-container {
|
| 303 |
+
max-width: 1400px !important;
|
| 304 |
+
}
|
| 305 |
+
.code-input {
|
| 306 |
+
font-family: 'Courier New', monospace;
|
| 307 |
+
font-size: 14px;
|
| 308 |
+
}
|
| 309 |
+
.review-summary {
|
| 310 |
+
background-color: #f0f8ff;
|
| 311 |
+
padding: 10px;
|
| 312 |
+
border-radius: 5px;
|
| 313 |
+
border-left: 4px solid #4CAF50;
|
| 314 |
+
}
|
| 315 |
+
.markdown-output {
|
| 316 |
+
max-height: 600px;
|
| 317 |
+
overflow-y: auto;
|
| 318 |
+
padding: 15px;
|
| 319 |
+
background-color: #2d2d2d;
|
| 320 |
+
border-radius: 8px;
|
| 321 |
+
border: 1px solid #404040;
|
| 322 |
+
}
|
| 323 |
+
.markdown-output h1, .markdown-output h2, .markdown-output h3, .markdown-output h4, .markdown-output h5, .markdown-output h6 {
|
| 324 |
+
color: #ffffff !important;
|
| 325 |
+
font-weight: bold !important;
|
| 326 |
+
}
|
| 327 |
+
.markdown-output p, .markdown-output li {
|
| 328 |
+
color: #e0e0e0 !important;
|
| 329 |
+
line-height: 1.6 !important;
|
| 330 |
+
}
|
| 331 |
+
.markdown-output strong {
|
| 332 |
+
color: #ffeb3b !important;
|
| 333 |
+
font-weight: bold !important;
|
| 334 |
+
}
|
| 335 |
+
.markdown-output code {
|
| 336 |
+
background-color: #1e1e1e !important;
|
| 337 |
+
color: #4fc3f7 !important;
|
| 338 |
+
padding: 2px 6px !important;
|
| 339 |
+
border-radius: 4px !important;
|
| 340 |
+
}
|
| 341 |
+
.markdown-output pre {
|
| 342 |
+
background-color: #1e1e1e !important;
|
| 343 |
+
color: #4fc3f7 !important;
|
| 344 |
+
padding: 10px !important;
|
| 345 |
+
border-radius: 6px !important;
|
| 346 |
+
overflow-x: auto !important;
|
| 347 |
+
}
|
| 348 |
+
"""
|
| 349 |
+
) as demo:
|
| 350 |
+
|
| 351 |
+
gr.Markdown("""
|
| 352 |
+
# π§ AI Code Assistant
|
| 353 |
+
### Powered by BLACKBOX.AI, Groq API, and Llama Models
|
| 354 |
+
|
| 355 |
+
**Features:**
|
| 356 |
+
- π€ **Automated Code Review**: Comprehensive quality assessment and review comments
|
| 357 |
+
- π‘οΈ **Security Analysis**: Vulnerability detection and security recommendations
|
| 358 |
+
- π **Performance Optimization**: Intelligent suggestions for better performance
|
| 359 |
+
- π **Review Comments**: Generate detailed review comments for team collaboration
|
| 360 |
+
""")
|
| 361 |
+
|
| 362 |
+
with gr.Row():
|
| 363 |
+
with gr.Column(scale=1):
|
| 364 |
+
code_input = gr.Textbox(
|
| 365 |
+
label="π Enter Your Code",
|
| 366 |
+
placeholder="Paste your code here for automated review...",
|
| 367 |
+
lines=18,
|
| 368 |
+
elem_classes=["code-input"]
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
analysis_type = gr.Radio(
|
| 372 |
+
label="π Analysis Type",
|
| 373 |
+
choices=["Automated Review"],
|
| 374 |
+
value="Automated Review",
|
| 375 |
+
info="Automated code review with comprehensive analysis"
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
analyze_btn = gr.Button("π Analyze Code", variant="primary", size="lg")
|
| 379 |
+
|
| 380 |
+
# Review summary box
|
| 381 |
+
summary_box = gr.Textbox(
|
| 382 |
+
label="π Quick Summary",
|
| 383 |
+
lines=2,
|
| 384 |
+
interactive=False,
|
| 385 |
+
elem_classes=["review-summary"]
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
with gr.Column(scale=2):
|
| 389 |
+
gr.Markdown("## π Analysis Results")
|
| 390 |
+
|
| 391 |
+
with gr.Tabs():
|
| 392 |
+
with gr.TabItem("π€ Groq + Llama Analysis"):
|
| 393 |
+
groq_output = gr.Markdown(
|
| 394 |
+
value="Analysis results will appear here...",
|
| 395 |
+
elem_classes=["markdown-output"]
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
with gr.TabItem("π Comprehensive Report"):
|
| 399 |
+
combined_output = gr.Markdown(
|
| 400 |
+
value="Comprehensive report will appear here...",
|
| 401 |
+
elem_classes=["markdown-output"]
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
# Event handlers
|
| 405 |
+
analyze_btn.click(
|
| 406 |
+
fn=analyze_code_interface,
|
| 407 |
+
inputs=[code_input, analysis_type],
|
| 408 |
+
outputs=[groq_output, combined_output, summary_box]
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
# Example codes section
|
| 412 |
+
gr.Markdown("## π Example Codes for Testing")
|
| 413 |
+
|
| 414 |
+
enhanced_examples = [
|
| 415 |
+
["Python - Security Vulnerability", """
|
| 416 |
+
import sqlite3
|
| 417 |
+
import os
|
| 418 |
+
|
| 419 |
+
def get_user_data(user_id):
|
| 420 |
+
conn = sqlite3.connect('users.db')
|
| 421 |
+
cursor = conn.cursor()
|
| 422 |
+
|
| 423 |
+
# SQL Injection vulnerability
|
| 424 |
+
query = f"SELECT * FROM users WHERE id = {user_id}"
|
| 425 |
+
cursor.execute(query)
|
| 426 |
+
|
| 427 |
+
result = cursor.fetchone()
|
| 428 |
+
conn.close()
|
| 429 |
+
return result
|
| 430 |
+
|
| 431 |
+
def authenticate_user(username, password):
|
| 432 |
+
# Hardcoded credentials - security issue
|
| 433 |
+
if username == "admin" and password == "password123":
|
| 434 |
+
return True
|
| 435 |
+
return False
|
| 436 |
+
|
| 437 |
+
# No input validation
|
| 438 |
+
user_data = get_user_data(input("Enter user ID: "))
|
| 439 |
+
print(user_data)
|
| 440 |
+
"""],
|
| 441 |
+
|
| 442 |
+
["JavaScript - Performance Issues", """
|
| 443 |
+
// Inefficient DOM manipulation
|
| 444 |
+
function updateUserList(users) {
|
| 445 |
+
const container = document.getElementById('user-list');
|
| 446 |
+
container.innerHTML = ''; // Clearing DOM
|
| 447 |
+
|
| 448 |
+
for (let i = 0; i < users.length; i++) {
|
| 449 |
+
const div = document.createElement('div');
|
| 450 |
+
div.innerHTML = `
|
| 451 |
+
<h3>${users[i].name}</h3>
|
| 452 |
+
<p>${users[i].email}</p>
|
| 453 |
+
<button onclick="deleteUser(${users[i].id})">Delete</button>
|
| 454 |
+
`;
|
| 455 |
+
container.appendChild(div); // Multiple DOM operations
|
| 456 |
+
}
|
| 457 |
+
}
|
| 458 |
+
|
| 459 |
+
// Memory leak potential
|
| 460 |
+
let globalCache = {};
|
| 461 |
+
function cacheUserData(userId, data) {
|
| 462 |
+
globalCache[userId] = data; // Never cleaned up
|
| 463 |
+
}
|
| 464 |
+
|
| 465 |
+
// No error handling
|
| 466 |
+
async function fetchUserData(userId) {
|
| 467 |
+
const response = await fetch(`/api/users/${userId}`);
|
| 468 |
+
const data = response.json(); // Missing await
|
| 469 |
+
return data;
|
| 470 |
+
}
|
| 471 |
+
"""],
|
| 472 |
+
|
| 473 |
+
["Python - Code Quality Issues", """
|
| 474 |
+
# Poor naming conventions and structure
|
| 475 |
+
def func1(x, y, z):
|
| 476 |
+
# No docstring
|
| 477 |
+
a = x + y
|
| 478 |
+
b = a * z
|
| 479 |
+
if b > 100:
|
| 480 |
+
c = b / 2
|
| 481 |
+
else:
|
| 482 |
+
c = b * 2
|
| 483 |
+
|
| 484 |
+
# Magic numbers
|
| 485 |
+
d = c + 42
|
| 486 |
+
e = d - 17
|
| 487 |
+
|
| 488 |
+
# Nested conditions
|
| 489 |
+
if e > 50:
|
| 490 |
+
if e < 200:
|
| 491 |
+
if e % 2 == 0:
|
| 492 |
+
return e
|
| 493 |
+
else:
|
| 494 |
+
return e + 1
|
| 495 |
+
else:
|
| 496 |
+
return 200
|
| 497 |
+
else:
|
| 498 |
+
return 50
|
| 499 |
+
|
| 500 |
+
# Global variables
|
| 501 |
+
counter = 0
|
| 502 |
+
data_list = []
|
| 503 |
+
|
| 504 |
+
def process_data():
|
| 505 |
+
global counter, data_list
|
| 506 |
+
counter += 1
|
| 507 |
+
data_list.append(counter)
|
| 508 |
+
|
| 509 |
+
# Long function with multiple responsibilities
|
| 510 |
+
for item in data_list:
|
| 511 |
+
if item % 2 == 0:
|
| 512 |
+
print(f"Even: {item}")
|
| 513 |
+
else:
|
| 514 |
+
print(f"Odd: {item}")
|
| 515 |
+
|
| 516 |
+
# No error handling
|
| 517 |
+
result = 10 / (counter - 10) # Potential division by zero
|
| 518 |
+
return result
|
| 519 |
+
"""]
|
| 520 |
+
]
|
| 521 |
+
|
| 522 |
+
with gr.Row():
|
| 523 |
+
for title, code in enhanced_examples:
|
| 524 |
+
gr.Button(title, size="sm").click(
|
| 525 |
+
lambda c=code: c,
|
| 526 |
+
outputs=code_input
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
# Usage instructions
|
| 530 |
+
gr.Markdown("""
|
| 531 |
+
## π― How to Use the Automated Code Review
|
| 532 |
+
|
| 533 |
+
### π€ Automated Code Review
|
| 534 |
+
- **Purpose**: Comprehensive code quality assessment and review comments
|
| 535 |
+
- **Features**: Security analysis, performance optimization, style checking, bug detection
|
| 536 |
+
- **Output**: Detailed review report with proper formatting and actionable suggestions
|
| 537 |
+
|
| 538 |
+
### π‘ Pro Tips
|
| 539 |
+
- Use this tool for comprehensive code assessment before team reviews
|
| 540 |
+
- Try the example codes to see different types of analysis
|
| 541 |
+
- Results are properly formatted with bold headings and clear structure
|
| 542 |
+
- Focus on **Critical** and **High** priority issues first
|
| 543 |
+
|
| 544 |
+
### π What You'll Get
|
| 545 |
+
- **Primary AI Analysis**: Detailed code review from Groq + Llama with proper formatting
|
| 546 |
+
- **Comprehensive Report**: Combined analysis with actionable insights
|
| 547 |
+
- **Quick Summary**: Overview of issues found and overall code rating
|
| 548 |
+
""")
|
| 549 |
+
|
| 550 |
+
return demo
|
| 551 |
+
|
| 552 |
+
# Launch the application
|
| 553 |
+
if __name__ == "__main__":
|
| 554 |
+
demo = create_gradio_interface()
|
| 555 |
+
demo.launch()
|