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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 4 |
+
from peft import PeftModel, PeftConfig
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
# App metadata
|
| 8 |
+
APP_TITLE = "π STHASI Code Review Assistant"
|
| 9 |
+
APP_DESCRIPTION = """
|
| 10 |
+
An AI-powered code review assistant that analyzes code quality, detects vulnerabilities, and suggests improvements.
|
| 11 |
+
Built with β€οΈ by **[Syed Tahir Hussan](https://www.linkedin.com/in/syedtahirhussan/)**
|
| 12 |
+
|
| 13 |
+
**Features:**
|
| 14 |
+
- π‘οΈ Security vulnerability detection across 13+ languages
|
| 15 |
+
- π Code quality analysis
|
| 16 |
+
- π‘ Improvement suggestions
|
| 17 |
+
- π Bug detection
|
| 18 |
+
|
| 19 |
+
**Supported Languages:** Python, JavaScript, Java, C, C++, C#, Go, PHP, Ruby, Swift, Kotlin, TypeScript, Fortran
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
FOOTER = """
|
| 23 |
+
---
|
| 24 |
+
**STHASI Code Review Assistant** | Built with β€οΈ by [Syed Tahir Hussan](https://www.linkedin.com/in/syedtahirhussan/)
|
| 25 |
+
|
| 26 |
+
π§ [GitHub](https://github.com/SyedTahirHussan) | πΌ [LinkedIn](https://www.linkedin.com/in/syedtahirhussan/)
|
| 27 |
+
|
| 28 |
+
*Powered by CodeAstra-7B & Hugging Face Spaces*
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
# Global variables for model
|
| 32 |
+
model = None
|
| 33 |
+
tokenizer = None
|
| 34 |
+
model_loaded = False
|
| 35 |
+
|
| 36 |
+
def load_model():
|
| 37 |
+
"""Load the CodeAstra-7B model"""
|
| 38 |
+
global model, tokenizer, model_loaded
|
| 39 |
+
|
| 40 |
+
if model_loaded:
|
| 41 |
+
return "Model already loaded!"
|
| 42 |
+
|
| 43 |
+
try:
|
| 44 |
+
peft_model_id = "rootxhacker/CodeAstra-7B"
|
| 45 |
+
config = PeftConfig.from_pretrained(peft_model_id)
|
| 46 |
+
|
| 47 |
+
# Load model in 4-bit for efficiency
|
| 48 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 49 |
+
config.base_model_name_or_path,
|
| 50 |
+
return_dict=True,
|
| 51 |
+
load_in_4bit=True,
|
| 52 |
+
device_map='auto',
|
| 53 |
+
trust_remote_code=True
|
| 54 |
+
)
|
| 55 |
+
tokenizer = AutoTokenizer.from_pretrained(config.base_model_name_or_path)
|
| 56 |
+
|
| 57 |
+
# Load PEFT adapter
|
| 58 |
+
model = PeftModel.from_pretrained(model, peft_model_id)
|
| 59 |
+
|
| 60 |
+
model_loaded = True
|
| 61 |
+
return "β
Model loaded successfully!"
|
| 62 |
+
except Exception as e:
|
| 63 |
+
return f"β Error loading model: {str(e)}"
|
| 64 |
+
|
| 65 |
+
def analyze_code(code_input, analysis_type, language):
|
| 66 |
+
"""
|
| 67 |
+
Analyze code for vulnerabilities and quality issues
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
code_input: The code to analyze
|
| 71 |
+
analysis_type: Type of analysis (vulnerability, quality, both)
|
| 72 |
+
language: Programming language
|
| 73 |
+
"""
|
| 74 |
+
global model, tokenizer, model_loaded
|
| 75 |
+
|
| 76 |
+
if not code_input.strip():
|
| 77 |
+
return "β οΈ Please enter some code to analyze."
|
| 78 |
+
|
| 79 |
+
if not model_loaded:
|
| 80 |
+
return "β οΈ Model not loaded. Please wait for initialization or refresh the page."
|
| 81 |
+
|
| 82 |
+
try:
|
| 83 |
+
# Construct the prompt based on analysis type
|
| 84 |
+
if analysis_type == "Security Vulnerabilities":
|
| 85 |
+
prompt = f"""Analyze the following {language} code for security vulnerabilities.
|
| 86 |
+
Identify any potential security issues, explain their severity, and suggest fixes.
|
| 87 |
+
|
| 88 |
+
Code:
|
| 89 |
+
```{language.lower()}
|
| 90 |
+
{code_input}
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
Analysis:"""
|
| 94 |
+
elif analysis_type == "Code Quality":
|
| 95 |
+
prompt = f"""Review the following {language} code for quality issues.
|
| 96 |
+
Check for: code smell, performance issues, best practices, readability, and maintainability.
|
| 97 |
+
|
| 98 |
+
Code:
|
| 99 |
+
```{language.lower()}
|
| 100 |
+
{code_input}
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
Review:"""
|
| 104 |
+
else: # Both
|
| 105 |
+
prompt = f"""Perform a comprehensive code review of the following {language} code.
|
| 106 |
+
Analyze both security vulnerabilities AND code quality issues.
|
| 107 |
+
|
| 108 |
+
Code:
|
| 109 |
+
```{language.lower()}
|
| 110 |
+
{code_input}
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
Comprehensive Analysis:"""
|
| 114 |
+
|
| 115 |
+
# Generate response
|
| 116 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
| 117 |
+
|
| 118 |
+
with torch.no_grad():
|
| 119 |
+
outputs = model.generate(
|
| 120 |
+
**inputs,
|
| 121 |
+
max_new_tokens=1024,
|
| 122 |
+
do_sample=True,
|
| 123 |
+
temperature=0.3,
|
| 124 |
+
top_p=0.95,
|
| 125 |
+
repetition_penalty=1.15,
|
| 126 |
+
pad_token_id=tokenizer.eos_token_id
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
result = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 130 |
+
|
| 131 |
+
# Extract only the analysis part (remove the prompt)
|
| 132 |
+
if "Analysis:" in result:
|
| 133 |
+
result = result.split("Analysis:")[-1].strip()
|
| 134 |
+
elif "Review:" in result:
|
| 135 |
+
result = result.split("Review:")[-1].strip()
|
| 136 |
+
elif "Comprehensive Analysis:" in result:
|
| 137 |
+
result = result.split("Comprehensive Analysis:")[-1].strip()
|
| 138 |
+
|
| 139 |
+
return f"## π Analysis Results\n\n{result}"
|
| 140 |
+
|
| 141 |
+
except Exception as e:
|
| 142 |
+
return f"β Error during analysis: {str(e)}\n\nPlease try again or contact support."
|
| 143 |
+
|
| 144 |
+
# Example codes for different languages
|
| 145 |
+
EXAMPLES = {
|
| 146 |
+
"Python - SQL Injection": '''def user_login(username, password):
|
| 147 |
+
query = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'"
|
| 148 |
+
cursor.execute(query)
|
| 149 |
+
return cursor.fetchone()''',
|
| 150 |
+
|
| 151 |
+
"JavaScript - XSS": '''function displayUserInput() {
|
| 152 |
+
var userInput = document.getElementById("input").value;
|
| 153 |
+
document.getElementById("output").innerHTML = userInput;
|
| 154 |
+
}''',
|
| 155 |
+
|
| 156 |
+
"Python - Hardcoded Secrets": '''import requests
|
| 157 |
+
|
| 158 |
+
API_KEY = "sk-1234567890abcdef"
|
| 159 |
+
DB_PASSWORD = "admin123"
|
| 160 |
+
|
| 161 |
+
def connect_to_api():
|
| 162 |
+
headers = {"Authorization": f"Bearer {API_KEY}"}
|
| 163 |
+
return requests.get("https://api.example.com", headers=headers)''',
|
| 164 |
+
|
| 165 |
+
"Java - Resource Leak": '''public void readFile(String filename) throws IOException {
|
| 166 |
+
FileInputStream fis = new FileInputStream(filename);
|
| 167 |
+
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
|
| 168 |
+
String line = br.readLine();
|
| 169 |
+
System.out.println(line);
|
| 170 |
+
}''',
|
| 171 |
+
|
| 172 |
+
"C - Buffer Overflow": '''#include <string.h>
|
| 173 |
+
#include <stdio.h>
|
| 174 |
+
|
| 175 |
+
void copy_input(char *input) {
|
| 176 |
+
char buffer[10];
|
| 177 |
+
strcpy(buffer, input);
|
| 178 |
+
printf("Input: %s\\n", buffer);
|
| 179 |
+
}'''
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
# Create Gradio interface
|
| 183 |
+
def create_interface():
|
| 184 |
+
with gr.Blocks(theme=gr.themes.Soft(), css=".footer {text-align: center; margin-top: 20px;}") as app:
|
| 185 |
+
gr.Markdown(f"# {APP_TITLE}")
|
| 186 |
+
gr.Markdown(APP_DESCRIPTION)
|
| 187 |
+
|
| 188 |
+
with gr.Row():
|
| 189 |
+
with gr.Column(scale=2):
|
| 190 |
+
code_input = gr.Code(
|
| 191 |
+
label="π Paste Your Code Here",
|
| 192 |
+
language="python",
|
| 193 |
+
lines=15,
|
| 194 |
+
placeholder="Enter your code here for analysis..."
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
with gr.Row():
|
| 198 |
+
language_select = gr.Dropdown(
|
| 199 |
+
choices=[
|
| 200 |
+
"Python", "JavaScript", "Java", "C", "C++", "C#",
|
| 201 |
+
"Go", "PHP", "Ruby", "Swift", "Kotlin", "TypeScript", "Fortran"
|
| 202 |
+
],
|
| 203 |
+
value="Python",
|
| 204 |
+
label="π€ Programming Language"
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
analysis_type = gr.Radio(
|
| 208 |
+
choices=["Security Vulnerabilities", "Code Quality", "Both"],
|
| 209 |
+
value="Both",
|
| 210 |
+
label="π Analysis Type"
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
analyze_btn = gr.Button("π Analyze Code", variant="primary", size="lg")
|
| 214 |
+
|
| 215 |
+
gr.Markdown("### π Example Vulnerable Code")
|
| 216 |
+
example_dropdown = gr.Dropdown(
|
| 217 |
+
choices=list(EXAMPLES.keys()),
|
| 218 |
+
label="Load Example",
|
| 219 |
+
interactive=True
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
with gr.Column(scale=2):
|
| 223 |
+
output = gr.Markdown(label="Analysis Results")
|
| 224 |
+
|
| 225 |
+
# Event handlers
|
| 226 |
+
analyze_btn.click(
|
| 227 |
+
fn=analyze_code,
|
| 228 |
+
inputs=[code_input, analysis_type, language_select],
|
| 229 |
+
outputs=output
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
def load_example(example_name):
|
| 233 |
+
if example_name:
|
| 234 |
+
return EXAMPLES[example_name]
|
| 235 |
+
return ""
|
| 236 |
+
|
| 237 |
+
example_dropdown.change(
|
| 238 |
+
fn=load_example,
|
| 239 |
+
inputs=example_dropdown,
|
| 240 |
+
outputs=code_input
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
gr.Markdown(FOOTER, elem_classes="footer")
|
| 244 |
+
|
| 245 |
+
# Auto-load model on startup
|
| 246 |
+
app.load(load_model, inputs=None, outputs=None)
|
| 247 |
+
|
| 248 |
+
return app
|
| 249 |
+
|
| 250 |
+
# Launch the app
|
| 251 |
+
if __name__ == "__main__":
|
| 252 |
+
demo = create_interface()
|
| 253 |
+
demo.queue()
|
| 254 |
+
demo.launch(share=True)
|