SyedTahir commited on
Commit
af6fb0c
Β·
verified Β·
1 Parent(s): d627695

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +218 -205
app.py CHANGED
@@ -1,250 +1,263 @@
1
  import gradio as gr
2
- import requests
3
- import json
 
4
  import re
5
 
6
- # Hugging Face API configuration
7
- API_URL_STARCODER = "https://api-inference.huggingface.co/models/bigcode/starcoder"
8
- API_URL_CODET5 = "https://api-inference.huggingface.co/models/Salesforce/codet5-large"
9
-
10
- # You'll need to add your Hugging Face API token here
11
- # Get it from: https://huggingface.co/settings/tokens
12
- HF_TOKEN = "" # Users will need to add their token
13
-
14
- def analyze_code_with_starcoder(code, api_token):
15
- """Analyze code using StarCoder model"""
16
- headers = {"Authorization": f"Bearer {api_token}"}
17
-
18
- prompt = f"""Analyze the following code for:
19
- 1. Code quality issues
20
- 2. Potential bugs
21
- 3. Security vulnerabilities
22
- 4. Performance improvements
23
- 5. Best practices violations
24
-
25
- Code to analyze:
26
- ```
27
- {code}
28
- ```
29
-
30
- Provide a detailed review with specific suggestions:"""
31
-
32
- payload = {
33
- "inputs": prompt,
34
- "parameters": {
35
- "max_new_tokens": 500,
36
- "temperature": 0.3,
37
- "top_p": 0.95,
38
- "do_sample": True
39
- }
40
  }
 
 
 
 
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  try:
43
- response = requests.post(API_URL_STARCODER, headers=headers, json=payload, timeout=60)
44
- if response.status_code == 200:
45
- result = response.json()
46
- if isinstance(result, list) and len(result) > 0:
47
- return result[0].get('generated_text', 'No analysis generated')
48
- return str(result)
49
- else:
50
- return f"Error: {response.status_code} - {response.text}"
51
- except Exception as e:
52
- return f"Error during analysis: {str(e)}"
53
-
54
- def detect_language(code):
55
- """Simple language detection based on code patterns"""
56
- if 'def ' in code or 'import ' in code or 'print(' in code:
57
- return 'Python'
58
- elif 'function' in code or 'const ' in code or 'let ' in code or 'var ' in code:
59
- return 'JavaScript'
60
- elif 'public class' in code or 'public static void main' in code:
61
- return 'Java'
62
- elif '#include' in code or 'int main()' in code:
63
- return 'C/C++'
64
- elif 'func ' in code or 'package main' in code:
65
- return 'Go'
66
- elif '<?php' in code:
67
- return 'PHP'
68
- else:
69
- return 'Unknown'
70
 
71
- def count_lines(code):
72
- """Count lines of code"""
73
- lines = code.strip().split('\n')
74
- return len([line for line in lines if line.strip() and not line.strip().startswith('#') and not line.strip().startswith('//')])
75
 
76
- def analyze_code(code, api_token):
77
- """Main function to analyze code"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  if not code.strip():
79
- return "⚠️ Please enter some code to analyze.", "", ""
80
 
81
- if not api_token.strip():
82
- return "⚠️ Please enter your Hugging Face API token. Get it from: https://huggingface.co/settings/tokens", "", ""
83
 
84
- # Basic analysis
85
- language = detect_language(code)
86
- lines = count_lines(code)
87
 
88
- basic_info = f"""## πŸ“Š Code Statistics
89
- - **Language Detected:** {language}
90
- - **Lines of Code:** {lines}
91
- - **Characters:** {len(code)}
92
- """
93
-
94
- # AI-powered analysis
95
- analysis_result = analyze_code_with_starcoder(code, api_token)
96
 
97
- # Format the result
98
- ai_analysis = f"""## πŸ€– AI-Powered Code Review
99
 
100
- {analysis_result}
 
 
 
 
 
101
  """
102
 
103
- # Quick checks
104
- quick_checks = """## βœ… Quick Security Checks
 
 
 
 
 
 
 
 
 
 
 
105
 
 
 
 
 
 
 
 
106
  """
107
- issues_found = []
108
-
109
- # Basic security checks
110
- if 'eval(' in code:
111
- issues_found.append("⚠️ **Security Risk:** Use of `eval()` detected - can execute arbitrary code")
112
- if 'exec(' in code:
113
- issues_found.append("⚠️ **Security Risk:** Use of `exec()` detected - can execute arbitrary code")
114
- if 'input(' in code and 'int(' not in code and 'float(' not in code:
115
- issues_found.append("⚠️ **Input Validation:** Raw `input()` without validation detected")
116
- if 'password' in code.lower() and ('=' in code or 'pass' in code.lower()):
117
- issues_found.append("⚠️ **Security Risk:** Hardcoded password detected")
118
- if 'api_key' in code.lower() or 'apikey' in code.lower():
119
- issues_found.append("⚠️ **Security Risk:** Hardcoded API key detected")
120
- if 'sql' in code.lower() and ('+' in code or 'format' in code):
121
- issues_found.append("⚠️ **SQL Injection Risk:** String concatenation in SQL query detected")
122
-
123
- if issues_found:
124
- quick_checks += "\n".join(issues_found)
125
- else:
126
- quick_checks += "βœ… No obvious security issues detected in quick scan"
127
 
128
- return basic_info, ai_analysis, quick_checks
129
 
130
  # Custom CSS
131
  custom_css = """
132
- <style>
133
- .gradio-container {
134
- font-family: 'Arial', sans-serif;
135
- max-width: 1200px;
136
- margin: auto;
137
- }
138
- .header {
139
- text-align: center;
140
- padding: 20px;
141
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
142
- color: white;
143
- border-radius: 10px;
144
- margin-bottom: 20px;
145
- }
146
- .footer {
147
- text-align: center;
148
- padding: 20px;
149
- margin-top: 20px;
150
- color: #666;
151
- }
152
- .footer a {
153
- color: #667eea;
154
- text-decoration: none;
155
- font-weight: bold;
156
- }
157
- .footer a:hover {
158
- text-decoration: underline;
159
- }
160
- </style>
 
 
 
 
 
 
 
 
 
 
161
  """
162
 
163
  # Create Gradio interface
164
- with gr.Blocks(css=custom_css, title="STHASI Code Review Assistant") as demo:
 
165
  gr.HTML("""
166
- <div class="header">
167
- <h1>πŸ” STHASI Code Review Assistant</h1>
168
- <p>AI-Powered Code Quality Analysis & Vulnerability Detection</p>
169
- <p style="font-size: 14px; margin-top: 10px;">Built with ❀️ by <a href="https://www.linkedin.com/in/syedtahirhussan/" target="_blank" style="color: white; text-decoration: underline;">Syed Tahir Hussan</a></p>
170
- </div>
171
- """)
172
-
173
- gr.Markdown("""
174
- ## πŸš€ How to Use
175
- 1. **Get your Hugging Face API Token** from [here](https://huggingface.co/settings/tokens) (it's free!)
176
- 2. **Paste your API token** in the field below
177
- 3. **Enter your code** in the code editor
178
- 4. **Click "Analyze Code"** to get instant AI-powered review
179
-
180
- ### 🎯 Features
181
- - Multi-language support (Python, JavaScript, Java, C/C++, Go, PHP, and more)
182
- - Code quality analysis
183
- - Security vulnerability detection
184
- - Performance improvement suggestions
185
- - Best practices recommendations
186
  """)
187
 
188
  with gr.Row():
189
  with gr.Column(scale=1):
190
- api_token_input = gr.Textbox(
191
- label="πŸ”‘ Hugging Face API Token",
192
- placeholder="hf_...",
193
- type="password",
194
- info="Get your free token from https://huggingface.co/settings/tokens"
195
  )
196
-
197
  code_input = gr.Code(
198
- label="πŸ“ Enter Your Code",
199
  language="python",
200
- lines=15,
201
- placeholder="""# Example Python code
202
- def calculate_sum(numbers):
203
- total = 0
204
- for num in numbers:
205
- total += num
206
- return total
207
-
208
- # Test
209
- result = calculate_sum([1, 2, 3, 4, 5])
210
- print(result)"""
211
  )
212
-
213
- analyze_btn = gr.Button("πŸ” Analyze Code", variant="primary", size="lg")
214
 
215
  gr.Markdown("""
216
- ### πŸ’‘ Example Code Snippets
217
- Try analyzing these examples:
218
- - Python function with potential issues
219
- - JavaScript code with security vulnerabilities
220
- - SQL queries with injection risks
221
  """)
222
 
223
  with gr.Row():
224
- with gr.Column(scale=1):
225
- basic_output = gr.Markdown(label="πŸ“Š Basic Analysis")
226
- ai_output = gr.Markdown(label="πŸ€– AI Review")
227
- security_output = gr.Markdown(label="πŸ”’ Security Checks")
228
-
229
- analyze_btn.click(
230
- fn=analyze_code,
231
- inputs=[code_input, api_token_input],
232
- outputs=[basic_output, ai_output, security_output]
233
- )
234
 
 
235
  gr.HTML("""
236
- <div class="footer">
237
- <p><strong>STHASI Code Review Assistant</strong> - Powered by StarCoder & CodeT5+</p>
238
- <p>
239
- Created by <a href="https://www.linkedin.com/in/syedtahirhussan/" target="_blank">Syed Tahir Hussan</a> |
240
- <a href="https://github.com/SyedTahirHussan" target="_blank">GitHub</a>
241
- </p>
242
- <p style="font-size: 12px; color: #999; margin-top: 10px;">
243
- This tool uses AI models from Hugging Face. Results should be reviewed by human developers.
244
- </p>
245
- </div>
246
  """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
 
248
  # Launch the app
249
  if __name__ == "__main__":
250
- demo.launch(share=False)
 
1
  import gradio as gr
2
+ import os
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM
4
+ import torch
5
  import re
6
 
7
+ # Initialize model and tokenizer
8
+ MODEL_NAME = "bigcode/starcoderbase-1b"
9
+ tokenizer = None
10
+ model = None
11
+
12
+ def load_model():
13
+ global tokenizer, model
14
+ if tokenizer is None:
15
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
16
+ model = AutoModelForCausalLM.from_pretrained(
17
+ MODEL_NAME,
18
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
19
+ device_map="auto"
20
+ )
21
+ return tokenizer, model
22
+
23
+ def analyze_code_structure(code, language):
24
+ """Analyze code structure and provide metrics"""
25
+ lines = code.split('\n')
26
+ total_lines = len(lines)
27
+ code_lines = len([l for l in lines if l.strip() and not l.strip().startswith('#') and not l.strip().startswith('//')])
28
+ comment_lines = len([l for l in lines if l.strip().startswith('#') or l.strip().startswith('//')])
29
+ blank_lines = total_lines - code_lines - comment_lines
30
+
31
+ # Calculate complexity (simple heuristic)
32
+ complexity_keywords = ['if', 'else', 'elif', 'for', 'while', 'switch', 'case', 'catch', 'try']
33
+ complexity = sum(code.lower().count(keyword) for keyword in complexity_keywords)
34
+
35
+ return {
36
+ 'total_lines': total_lines,
37
+ 'code_lines': code_lines,
38
+ 'comment_lines': comment_lines,
39
+ 'blank_lines': blank_lines,
40
+ 'complexity': complexity
41
  }
42
+
43
+ def detect_vulnerabilities(code, language):
44
+ """Detect common security vulnerabilities"""
45
+ vulnerabilities = []
46
 
47
+ # Common vulnerability patterns
48
+ patterns = {
49
+ 'SQL Injection': [r'execute\s*\(.*\+.*\)', r'query\s*\(.*\+.*\)', r'SELECT.*\+.*FROM'],
50
+ 'Hardcoded Secrets': [r'password\s*=\s*["\'][^"\']+["\']', r'api_key\s*=\s*["\'][^"\']+["\']', r'secret\s*=\s*["\'][^"\']+["\']'],
51
+ 'Command Injection': [r'os\.system\s*\(', r'subprocess\.call\s*\(', r'eval\s*\(', r'exec\s*\('],
52
+ 'Path Traversal': [r'\.\./', r'open\s*\(.*\+.*\)'],
53
+ 'XSS Vulnerability': [r'innerHTML\s*=', r'document\.write\s*\('],
54
+ }
55
+
56
+ for vuln_type, pattern_list in patterns.items():
57
+ for pattern in pattern_list:
58
+ if re.search(pattern, code, re.IGNORECASE):
59
+ vulnerabilities.append(vuln_type)
60
+ break
61
+
62
+ return list(set(vulnerabilities))
63
+
64
+ def generate_ai_suggestions(code, language):
65
+ """Generate AI-powered code suggestions"""
66
  try:
67
+ tokenizer, model = load_model()
68
+
69
+ prompt = f"""# Code Review for {language}
70
+ # Analyze the following code and provide suggestions for improvement:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
+ {code[:500]} # Limit input for faster processing
 
 
 
73
 
74
+ # Suggestions:
75
+ 1."""
76
+
77
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
78
+
79
+ with torch.no_grad():
80
+ outputs = model.generate(
81
+ **inputs,
82
+ max_new_tokens=200,
83
+ temperature=0.7,
84
+ do_sample=True,
85
+ top_p=0.95,
86
+ pad_token_id=tokenizer.eos_token_id
87
+ )
88
+
89
+ suggestion = tokenizer.decode(outputs[0], skip_special_tokens=True)
90
+ # Extract only the generated part
91
+ suggestion = suggestion.split("# Suggestions:")[-1].strip()
92
+
93
+ return suggestion if suggestion else "Consider adding more comments and following best practices for code readability."
94
+
95
+ except Exception as e:
96
+ return f"AI suggestion generation in progress... Meanwhile, consider: proper error handling, code documentation, and following {language} best practices."
97
+
98
+ def review_code(code, language):
99
+ """Main code review function"""
100
  if not code.strip():
101
+ return "⚠️ Please enter some code to review.", "", ""
102
 
103
+ # Analyze code structure
104
+ metrics = analyze_code_structure(code, language)
105
 
106
+ # Detect vulnerabilities
107
+ vulnerabilities = detect_vulnerabilities(code, language)
 
108
 
109
+ # Generate AI suggestions
110
+ ai_suggestions = generate_ai_suggestions(code, language)
 
 
 
 
 
 
111
 
112
+ # Format metrics output
113
+ metrics_output = f"""## πŸ“Š Code Metrics
114
 
115
+ - **Total Lines:** {metrics['total_lines']}
116
+ - **Code Lines:** {metrics['code_lines']}
117
+ - **Comment Lines:** {metrics['comment_lines']}
118
+ - **Blank Lines:** {metrics['blank_lines']}
119
+ - **Cyclomatic Complexity:** {metrics['complexity']}
120
+ - **Comment Ratio:** {(metrics['comment_lines'] / max(metrics['code_lines'], 1) * 100):.1f}%
121
  """
122
 
123
+ # Format vulnerabilities output
124
+ if vulnerabilities:
125
+ vuln_output = "## πŸ”’ Security Vulnerabilities Detected\n\n"
126
+ for vuln in vulnerabilities:
127
+ vuln_output += f"- ⚠️ **{vuln}**\n"
128
+ vuln_output += "\n**Recommendation:** Review and fix these security issues before deployment."
129
+ else:
130
+ vuln_output = "## βœ… No Common Vulnerabilities Detected\n\nNo obvious security issues found. However, always perform thorough security testing."
131
+
132
+ # Format AI suggestions
133
+ suggestions_output = f"""## πŸ€– AI-Powered Suggestions
134
+
135
+ {ai_suggestions}
136
 
137
+ ### General Best Practices:
138
+ - Ensure proper error handling
139
+ - Add comprehensive documentation
140
+ - Follow {language} coding standards
141
+ - Write unit tests for critical functions
142
+ - Use meaningful variable names
143
+ - Keep functions small and focused
144
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
 
146
+ return metrics_output, vuln_output, suggestions_output
147
 
148
  # Custom CSS
149
  custom_css = """
150
+ #header {
151
+ text-align: center;
152
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
153
+ padding: 30px;
154
+ border-radius: 10px;
155
+ margin-bottom: 20px;
156
+ color: white;
157
+ }
158
+
159
+ #header h1 {
160
+ margin: 0;
161
+ font-size: 2.5em;
162
+ font-weight: bold;
163
+ }
164
+
165
+ #header p {
166
+ margin: 10px 0 0 0;
167
+ font-size: 1.1em;
168
+ opacity: 0.9;
169
+ }
170
+
171
+ .footer {
172
+ text-align: center;
173
+ margin-top: 30px;
174
+ padding: 20px;
175
+ background: #f8f9fa;
176
+ border-radius: 10px;
177
+ }
178
+
179
+ .footer a {
180
+ color: #667eea;
181
+ text-decoration: none;
182
+ font-weight: bold;
183
+ margin: 0 10px;
184
+ }
185
+
186
+ .footer a:hover {
187
+ text-decoration: underline;
188
+ }
189
  """
190
 
191
  # Create Gradio interface
192
+ with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
193
+ # Header
194
  gr.HTML("""
195
+ <div id="header">
196
+ <h1>πŸ” STHASI Code Review Assistant</h1>
197
+ <p>AI-Powered Code Analysis, Quality Metrics & Security Vulnerability Detection</p>
198
+ <p style="font-size: 0.9em; margin-top: 10px;">Built with ❀️ by <a href="https://www.linkedin.com/in/syedtahirhussan/" target="_blank" style="color: white; text-decoration: underline;">Syed Tahir Hussan</a></p>
199
+ </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
  """)
201
 
202
  with gr.Row():
203
  with gr.Column(scale=1):
204
+ gr.Markdown("### πŸ“ Input Code")
205
+ language = gr.Dropdown(
206
+ choices=["Python", "JavaScript", "Java", "C++", "C#", "Go", "Ruby", "PHP", "TypeScript", "Swift"],
207
+ value="Python",
208
+ label="Programming Language"
209
  )
 
210
  code_input = gr.Code(
211
+ label="Paste your code here",
212
  language="python",
213
+ lines=15
 
 
 
 
 
 
 
 
 
 
214
  )
215
+ review_btn = gr.Button("πŸš€ Review Code", variant="primary", size="lg")
 
216
 
217
  gr.Markdown("""
218
+ ### πŸ“Œ Features:
219
+ - Code quality metrics
220
+ - Security vulnerability detection
221
+ - AI-powered suggestions
222
+ - Multi-language support
223
  """)
224
 
225
  with gr.Row():
226
+ with gr.Column():
227
+ metrics_output = gr.Markdown(label="Code Metrics")
228
+
229
+ with gr.Row():
230
+ with gr.Column():
231
+ vuln_output = gr.Markdown(label="Security Analysis")
232
+
233
+ with gr.Row():
234
+ with gr.Column():
235
+ suggestions_output = gr.Markdown(label="AI Suggestions")
236
 
237
+ # Footer
238
  gr.HTML("""
239
+ <div class="footer">
240
+ <p><strong>Connect with me:</strong></p>
241
+ <a href="https://www.linkedin.com/in/syedtahirhussan/" target="_blank">πŸ”— LinkedIn</a>
242
+ <a href="https://github.com/SyedTahirHussan" target="_blank">πŸ’» GitHub</a>
243
+ <p style="margin-top: 15px; color: #666;">Powered by StarCoder AI Model | Gradio 5.49.1</p>
244
+ </div>
 
 
 
 
245
  """)
246
+
247
+ # Event handler
248
+ review_btn.click(
249
+ fn=review_code,
250
+ inputs=[code_input, language],
251
+ outputs=[metrics_output, vuln_output, suggestions_output]
252
+ )
253
+
254
+ # Update code editor language when dropdown changes
255
+ language.change(
256
+ fn=lambda x: gr.Code(language=x.lower()),
257
+ inputs=[language],
258
+ outputs=[code_input]
259
+ )
260
 
261
  # Launch the app
262
  if __name__ == "__main__":
263
+ demo.launch()