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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
import requests
|
3 |
+
import os
|
4 |
+
import logging
|
5 |
+
import re
|
6 |
+
import random
|
7 |
+
import json
|
8 |
|
9 |
+
# Set up logging
|
10 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
11 |
+
logger = logging.getLogger(__name__)
|
12 |
|
13 |
+
# ======= CODE ANALYSIS CLASS ========
|
14 |
+
class CodeRoaster:
|
15 |
+
def __init__(self):
|
16 |
+
# Roast templates for different levels
|
17 |
+
self.roast_templates = {
|
18 |
+
"Mild": [
|
19 |
+
"I see some opportunities for improvement in this code. It's not bad, but we can make it better!",
|
20 |
+
"This code would benefit from a few tweaks. Let me show you how.",
|
21 |
+
"Your code works, but there are some best practices we could apply here."
|
22 |
+
],
|
23 |
+
"Medium": [
|
24 |
+
"This code looks like it was written the night before a deadline. Time for some tough love!",
|
25 |
+
"I've seen better code written by first-year CS students. Let's clean this up.",
|
26 |
+
"Your code needs a serious makeover. It's like showing up to a wedding in sweatpants."
|
27 |
+
],
|
28 |
+
"Savage": [
|
29 |
+
"This code is what happens when Stack Overflow answers are copied without understanding. Pure chaos!",
|
30 |
+
"Did you write this code during a power outage? While blindfolded? On a keyboard missing half its keys?",
|
31 |
+
"If this code were a restaurant dish, Gordon Ramsay would throw it in the trash and shut down the kitchen."
|
32 |
+
]
|
33 |
+
}
|
34 |
+
|
35 |
+
# Issue templates for different languages
|
36 |
+
self.python_issue_detectors = [
|
37 |
+
{
|
38 |
+
'pattern': r"range\s*\(\s*0\s*,",
|
39 |
+
'issue': "unnecessary zero in range",
|
40 |
+
'suggestion': "range() starts at 0 by default, so range(0, n) can be simplified to range(n)",
|
41 |
+
'fix': lambda code: re.sub(r"range\s*\(\s*0\s*,\s*([^\)]+)\)", r"range(\1)", code)
|
42 |
+
},
|
43 |
+
{
|
44 |
+
'pattern': r"print\s*\(",
|
45 |
+
'issue': "print statements used for output",
|
46 |
+
'suggestion': "Consider using logging for better control in production environments",
|
47 |
+
'fix': lambda code: code # No automatic fix
|
48 |
+
},
|
49 |
+
{
|
50 |
+
'pattern': r"if\s+\*\*name\*\*\s+==",
|
51 |
+
'issue': "incorrect __name__ syntax",
|
52 |
+
'suggestion': 'Use if __name__ == "__main__": instead of if **name** == "__main__":',
|
53 |
+
'fix': lambda code: re.sub(r"if\s+\*\*name\*\*\s+==", r"if __name__ ==", code)
|
54 |
+
},
|
55 |
+
{
|
56 |
+
'pattern': r"def\s+\w+\s*\([^\)]*\)\s*:\s*(?!\n\s*[\"\'])",
|
57 |
+
'issue': "missing docstring",
|
58 |
+
'suggestion': "Add docstrings to functions explaining purpose, parameters and return values",
|
59 |
+
'fix': lambda code: code # No automatic fix, requires understanding function purpose
|
60 |
+
},
|
61 |
+
{
|
62 |
+
'pattern': r" [^\n]+",
|
63 |
+
'issue': "inconsistent indentation",
|
64 |
+
'suggestion': "Use consistent indentation (4 spaces per level is the Python standard)",
|
65 |
+
'fix': lambda code: re.sub(r" (?! {2})", r" ", code)
|
66 |
+
},
|
67 |
+
{
|
68 |
+
'pattern': r"except:",
|
69 |
+
'issue': "bare except clause",
|
70 |
+
'suggestion': "Specify exceptions to catch instead of using a bare except clause",
|
71 |
+
'fix': lambda code: re.sub(r"except:", r"except Exception:", code)
|
72 |
+
},
|
73 |
+
{
|
74 |
+
'pattern': r"from\s+\w+\s+import\s+\*",
|
75 |
+
'issue': "wildcard import",
|
76 |
+
'suggestion': "Import specific modules or functions instead of using wildcard imports",
|
77 |
+
'fix': lambda code: code # No automatic fix, requires knowledge of what's needed
|
78 |
+
},
|
79 |
+
{
|
80 |
+
'pattern': r"i\s*\+=\s*1",
|
81 |
+
'issue': "manual index increment in loop",
|
82 |
+
'suggestion': "Consider using enumerate() for clean iteration with indices",
|
83 |
+
'fix': lambda code: code # No automatic fix, requires restructuring
|
84 |
+
},
|
85 |
+
{
|
86 |
+
'pattern': r"with\s+open\([^,]+\)\s+as",
|
87 |
+
'issue': "missing file mode in open()",
|
88 |
+
'suggestion': "Specify the file mode in open(filename, mode)",
|
89 |
+
'fix': lambda code: re.sub(r"with\s+open\(([^,]+)\)\s+as", r"with open(\1, 'r') as", code)
|
90 |
+
}
|
91 |
+
]
|
92 |
+
|
93 |
+
self.js_issue_detectors = [
|
94 |
+
{
|
95 |
+
'pattern': r"var\s+",
|
96 |
+
'issue': "using var instead of let/const",
|
97 |
+
'suggestion': "Use let for variables that change and const for variables that don't change",
|
98 |
+
'fix': lambda code: re.sub(r"var\s+", r"let ", code) # Simple replacement, not always correct
|
99 |
+
},
|
100 |
+
{
|
101 |
+
'pattern': r"==(?!=)",
|
102 |
+
'issue': "loose equality operators",
|
103 |
+
'suggestion': "Use === instead of == for strict equality checking",
|
104 |
+
'fix': lambda code: re.sub(r"==(?!=)", r"===", code)
|
105 |
+
},
|
106 |
+
{
|
107 |
+
'pattern': r"console\.log\(",
|
108 |
+
'issue': "console.log statements left in code",
|
109 |
+
'suggestion': "Remove console.log statements before production deployment",
|
110 |
+
'fix': lambda code: code # No automatic fix
|
111 |
+
},
|
112 |
+
{
|
113 |
+
'pattern': r"document\.write\(",
|
114 |
+
'issue': "using document.write",
|
115 |
+
'suggestion': "Avoid document.write as it can overwrite the entire document",
|
116 |
+
'fix': lambda code: code # No automatic fix
|
117 |
+
},
|
118 |
+
{
|
119 |
+
'pattern': r"setTimeout\(\s*function\s*\(\)\s*{\s*},\s*0\)",
|
120 |
+
'issue': "setTimeout with 0 delay",
|
121 |
+
'suggestion': "Consider using requestAnimationFrame instead for browser animations",
|
122 |
+
'fix': lambda code: code # No automatic fix
|
123 |
+
}
|
124 |
+
]
|
125 |
+
|
126 |
+
self.generic_issue_detectors = [
|
127 |
+
{
|
128 |
+
'pattern': r"(.{80,})\n",
|
129 |
+
'issue': "lines exceeding 80 characters",
|
130 |
+
'suggestion': "Keep lines under 80 characters for better readability",
|
131 |
+
'fix': lambda code: code # No automatic fix, requires manual line splitting
|
132 |
+
},
|
133 |
+
{
|
134 |
+
'pattern': r"(\/\/|\#)\s*TODO",
|
135 |
+
'issue': "TODO comments in code",
|
136 |
+
'suggestion': "Resolve TODO comments before considering code complete",
|
137 |
+
'fix': lambda code: code # No automatic fix
|
138 |
+
},
|
139 |
+
{
|
140 |
+
'pattern': r"[^\w](\w{1,2})[^\w]",
|
141 |
+
'issue': "short variable names",
|
142 |
+
'suggestion': "Use descriptive variable names that explain their purpose",
|
143 |
+
'fix': lambda code: code # No automatic fix, requires understanding context
|
144 |
+
}
|
145 |
+
]
|
146 |
+
|
147 |
+
def detect_language(self, code):
|
148 |
+
"""Detect what programming language the code is written in"""
|
149 |
+
# Python detection
|
150 |
+
if "def " in code or "import " in code or "class " in code and ":" in code:
|
151 |
+
return "Python"
|
152 |
+
# JavaScript detection
|
153 |
+
elif "function " in code or "var " in code or "let " in code or "const " in code:
|
154 |
+
return "JavaScript"
|
155 |
+
# Unknown language
|
156 |
+
else:
|
157 |
+
return "unknown"
|
158 |
+
|
159 |
+
def analyze_code(self, code, language):
|
160 |
+
"""Analyze code for issues based on detected language"""
|
161 |
+
issues = []
|
162 |
+
suggestions = []
|
163 |
+
fix_functions = []
|
164 |
+
|
165 |
+
# Select appropriate detectors based on language
|
166 |
+
if language == "Python":
|
167 |
+
detectors = self.python_issue_detectors + self.generic_issue_detectors
|
168 |
+
elif language == "JavaScript":
|
169 |
+
detectors = self.js_issue_detectors + self.generic_issue_detectors
|
170 |
+
else:
|
171 |
+
detectors = self.generic_issue_detectors
|
172 |
+
|
173 |
+
# Apply each detector
|
174 |
+
for detector in detectors:
|
175 |
+
if re.search(detector['pattern'], code):
|
176 |
+
issues.append(detector['issue'])
|
177 |
+
suggestions.append(detector['suggestion'])
|
178 |
+
fix_functions.append(detector['fix'])
|
179 |
+
|
180 |
+
# Check for missing newline at end of file
|
181 |
+
if code.count('\n') > 3 and not code.strip().endswith('\n'):
|
182 |
+
issues.append("missing newline at end of file")
|
183 |
+
suggestions.append("Add a newline at the end of the file (standard best practice)")
|
184 |
+
fix_functions.append(lambda code: code + '\n')
|
185 |
+
|
186 |
+
return issues, suggestions, fix_functions
|
187 |
+
|
188 |
+
def generate_roast(self, issues, level):
|
189 |
+
"""Generate a roast message based on the issues found and the roast level"""
|
190 |
+
base_roast = random.choice(self.roast_templates[level])
|
191 |
+
|
192 |
+
if issues:
|
193 |
+
if level == "Mild":
|
194 |
+
roast = f"{base_roast}\n\nI noticed these {len(issues)} issues that could be improved: {', '.join(issues)}."
|
195 |
+
elif level == "Medium":
|
196 |
+
roast = f"{base_roast}\n\nSpecifically, I found {len(issues)} issues that need attention: {', '.join(issues)}."
|
197 |
+
else: # Savage
|
198 |
+
roast = f"{base_roast}\n\nThis masterpiece of chaos has {len(issues)} issues: {', '.join(issues)}."
|
199 |
+
else:
|
200 |
+
if level == "Mild":
|
201 |
+
roast = f"{base_roast}\n\nYour code is actually pretty clean, but there are always ways to improve."
|
202 |
+
elif level == "Medium":
|
203 |
+
roast = f"{base_roast}\n\nSurprisingly, your code doesn't have major issues, but let's not celebrate too early."
|
204 |
+
else: # Savage
|
205 |
+
roast = f"{base_roast}\n\nI was ready to demolish this code, but it's... acceptable. Don't get used to compliments."
|
206 |
+
|
207 |
+
return roast
|
208 |
+
|
209 |
+
def fix_code(self, code, fix_functions):
|
210 |
+
"""Apply all fix functions to the code"""
|
211 |
+
fixed_code = code
|
212 |
+
for fix_func in fix_functions:
|
213 |
+
fixed_code = fix_func(fixed_code)
|
214 |
+
return fixed_code
|
215 |
+
|
216 |
+
def generate_explanation(self, issues, suggestions, language):
|
217 |
+
"""Generate an explanation of the issues and suggestions"""
|
218 |
+
explanation = "Here's what I found and improved:\n\n"
|
219 |
+
|
220 |
+
if issues:
|
221 |
+
for i, (issue, suggestion) in enumerate(zip(issues, suggestions)):
|
222 |
+
explanation += f"{i+1}. **{issue.capitalize()}**: {suggestion}\n"
|
223 |
+
else:
|
224 |
+
explanation += "- Made minor formatting improvements for better readability\n"
|
225 |
+
|
226 |
+
if language != "unknown":
|
227 |
+
explanation += f"\nYour code appears to be written in {language}. "
|
228 |
+
|
229 |
+
explanation += "\nWriting clean, consistent code helps with maintainability and reduces bugs!"
|
230 |
+
|
231 |
+
return explanation
|
232 |
+
|
233 |
+
def roast_code(self, code, roast_level):
|
234 |
+
"""Main function to analyze, roast and fix code"""
|
235 |
+
if not code.strip():
|
236 |
+
return "Please enter some code to roast.", "No code provided.", "Nothing to fix."
|
237 |
+
|
238 |
+
try:
|
239 |
+
# Detect language
|
240 |
+
language = self.detect_language(code)
|
241 |
+
logger.info(f"Detected language: {language}")
|
242 |
+
|
243 |
+
# Analyze code
|
244 |
+
issues, suggestions, fix_functions = self.analyze_code(code, language)
|
245 |
+
logger.info(f"Found {len(issues)} issues")
|
246 |
+
|
247 |
+
# Generate roast
|
248 |
+
roast = self.generate_roast(issues, roast_level)
|
249 |
+
|
250 |
+
# Fix code
|
251 |
+
fixed_code = self.fix_code(code, fix_functions)
|
252 |
+
|
253 |
+
# Generate explanation
|
254 |
+
explanation = self.generate_explanation(issues, suggestions, language)
|
255 |
+
|
256 |
+
return roast, fixed_code, explanation
|
257 |
+
|
258 |
+
except Exception as e:
|
259 |
+
logger.error(f"Error analyzing code: {str(e)}")
|
260 |
+
return (
|
261 |
+
f"Oops! Something went wrong while roasting your code: {str(e)}",
|
262 |
+
code,
|
263 |
+
"Error generating explanation."
|
264 |
+
)
|
265 |
+
|
266 |
+
# ======= HUGGING FACE API INTEGRATION ========
|
267 |
+
def call_huggingface_api(code, roast_level, api_key, model_name):
|
268 |
+
if not code.strip():
|
269 |
+
return "Please enter some code to roast.", "No code provided.", "Nothing to fix."
|
270 |
+
|
271 |
+
if not api_key.strip():
|
272 |
+
return "Please enter a valid Hugging Face API key.", code, "API key is required."
|
273 |
+
|
274 |
+
try:
|
275 |
+
logger.info(f"Calling Hugging Face API with model: {model_name}")
|
276 |
+
|
277 |
+
# Create different prompts based on roast level
|
278 |
+
roast_level_descriptions = {
|
279 |
+
"Mild": "gentle but humorous",
|
280 |
+
"Medium": "moderately sarcastic and pointed",
|
281 |
+
"Savage": "brutally honest and hilariously critical"
|
282 |
+
}
|
283 |
+
|
284 |
+
# Better prompt format with less chance of format confusion
|
285 |
+
prompt = f"""You're a senior software engineer reviewing this code:
|
286 |
+
|
287 |
+
```
|
288 |
+
{code}
|
289 |
+
```
|
290 |
+
|
291 |
+
Respond with THREE separate sections:
|
292 |
+
|
293 |
+
1. ROAST: Give a {roast_level_descriptions[roast_level]} code review. Be humorous but point out real issues.
|
294 |
+
|
295 |
+
2. FIXED_CODE: Provide an improved version of the code.
|
296 |
+
|
297 |
+
3. EXPLANATION: Explain what was improved and why it matters.
|
298 |
+
|
299 |
+
Start each section with the heading exactly as shown above.
|
300 |
+
"""
|
301 |
+
|
302 |
+
# API URL based on selected model
|
303 |
+
API_URL = f"https://api-inference.huggingface.co/models/{model_name}"
|
304 |
+
|
305 |
+
# Set up the headers with API key
|
306 |
+
headers = {
|
307 |
+
"Authorization": f"Bearer {api_key}",
|
308 |
+
"Content-Type": "application/json"
|
309 |
+
}
|
310 |
+
|
311 |
+
# Set up the payload
|
312 |
+
payload = {
|
313 |
+
"inputs": prompt,
|
314 |
+
"parameters": {
|
315 |
+
"max_new_tokens": 2048,
|
316 |
+
"temperature": 0.7,
|
317 |
+
"top_p": 0.9,
|
318 |
+
"top_k": 50,
|
319 |
+
"repetition_penalty": 1.2,
|
320 |
+
"stop": ["<|endoftext|>", "</s>"]
|
321 |
+
}
|
322 |
+
}
|
323 |
+
|
324 |
+
# Make the API call
|
325 |
+
response = requests.post(API_URL, headers=headers, json=payload)
|
326 |
+
|
327 |
+
# Check if the request was successful
|
328 |
+
if response.status_code != 200:
|
329 |
+
logger.error(f"API Error: {response.status_code} - {response.text}")
|
330 |
+
return f"Error: {response.status_code} - {response.text}", code, "API call failed."
|
331 |
+
|
332 |
+
# Extract the response text
|
333 |
+
try:
|
334 |
+
response_text = response.json()[0]["generated_text"]
|
335 |
+
logger.info(f"Raw API response received with length: {len(response_text)}")
|
336 |
+
|
337 |
+
# Remove the original prompt if it's included in the response
|
338 |
+
if prompt in response_text:
|
339 |
+
response_text = response_text.replace(prompt, "")
|
340 |
+
|
341 |
+
# Now extract each section using regex
|
342 |
+
roast_match = re.search(r"ROAST:(.*?)(?=FIXED_CODE:|$)", response_text, re.DOTALL)
|
343 |
+
code_match = re.search(r"FIXED_CODE:(.*?)(?=EXPLANATION:|$)", response_text, re.DOTALL)
|
344 |
+
explanation_match = re.search(r"EXPLANATION:(.*?)$", response_text, re.DOTALL)
|
345 |
+
|
346 |
+
# Extract content from matches
|
347 |
+
roast = roast_match.group(1).strip() if roast_match else "Failed to generate roast."
|
348 |
+
|
349 |
+
# For the code section, also look for code blocks
|
350 |
+
if code_match:
|
351 |
+
code_section = code_match.group(1).strip()
|
352 |
+
# Try to extract code between triple backticks if present
|
353 |
+
code_block_match = re.search(r"```(?:\w+)?\n(.*?)```", code_section, re.DOTALL)
|
354 |
+
if code_block_match:
|
355 |
+
fixed_code = code_block_match.group(1).strip()
|
356 |
+
else:
|
357 |
+
# If no code blocks, use the whole section
|
358 |
+
fixed_code = code_section
|
359 |
+
else:
|
360 |
+
fixed_code = "Failed to generate fixed code."
|
361 |
+
|
362 |
+
explanation = explanation_match.group(1).strip() if explanation_match else "Failed to generate explanation."
|
363 |
+
|
364 |
+
# If sections are still missing or empty, provide default messages
|
365 |
+
if not roast or roast == "":
|
366 |
+
roast = "The model didn't generate a proper roast. Try again or use local mode."
|
367 |
+
|
368 |
+
if not fixed_code or fixed_code == "":
|
369 |
+
fixed_code = code
|
370 |
+
|
371 |
+
if not explanation or explanation == "":
|
372 |
+
explanation = "The model didn't generate a proper explanation. Try again or use local mode."
|
373 |
+
|
374 |
+
logger.info("Successfully parsed response from Hugging Face API")
|
375 |
+
return roast, fixed_code, explanation
|
376 |
+
|
377 |
+
except Exception as e:
|
378 |
+
logger.error(f"Error parsing API response: {e}")
|
379 |
+
logger.error(f"Response content: {response.content[:500]}") # Log first 500 chars
|
380 |
+
return "Error parsing API response", code, f"Error details: {str(e)}"
|
381 |
+
|
382 |
+
except Exception as e:
|
383 |
+
logger.error(f"Error calling Hugging Face API: {str(e)}")
|
384 |
+
return (
|
385 |
+
f"Oops! Something went wrong while roasting your code: {str(e)}",
|
386 |
+
code,
|
387 |
+
"Error generating explanation."
|
388 |
+
)
|
389 |
+
|
390 |
+
# ======= MAIN ROASTING FUNCTION ========
|
391 |
+
def roast_code(code, roast_level, use_api, api_key="", model_choice="Mistral-7B"):
|
392 |
+
# Map model choice to actual model name
|
393 |
+
model_map = {
|
394 |
+
"Mistral-7B": "mistralai/Mistral-7B-Instruct-v0.2",
|
395 |
+
"Falcon-7B": "tiiuae/falcon-7b-instruct",
|
396 |
+
"Llama-2-7B": "meta-llama/Llama-2-7b-chat-hf",
|
397 |
+
"CodeLlama-7B": "codellama/CodeLlama-7b-instruct-hf"
|
398 |
+
}
|
399 |
+
|
400 |
+
model_name = model_map.get(model_choice, model_map["Mistral-7B"])
|
401 |
+
|
402 |
+
if use_api and api_key.strip():
|
403 |
+
# Use the API with specified model
|
404 |
+
logger.info(f"Using API with model: {model_name}")
|
405 |
+
return call_huggingface_api(code, roast_level, api_key, model_name)
|
406 |
+
else:
|
407 |
+
# Use the local analysis
|
408 |
+
logger.info("Using local code analysis")
|
409 |
+
roaster = CodeRoaster()
|
410 |
+
return roaster.roast_code(code, roast_level)
|
411 |
+
|
412 |
+
# ======= GRADIO INTERFACE ========
|
413 |
+
def create_interface():
|
414 |
+
with gr.Blocks(title="AI Roast My Code") as app:
|
415 |
+
gr.Markdown("# π₯ AI Roast My Code π₯")
|
416 |
+
gr.Markdown("Let our AI roast your code, fix it, and teach you - all while making you laugh!")
|
417 |
+
|
418 |
+
with gr.Row():
|
419 |
+
with gr.Column(scale=3):
|
420 |
+
code_input = gr.Textbox(
|
421 |
+
label="Your Code",
|
422 |
+
lines=15
|
423 |
+
)
|
424 |
+
with gr.Column(scale=1):
|
425 |
+
roast_level = gr.Radio(
|
426 |
+
choices=["Mild", "Medium", "Savage"],
|
427 |
+
label="Roast Level",
|
428 |
+
value="Medium"
|
429 |
+
)
|
430 |
+
|
431 |
+
use_api = gr.Checkbox(label="Use Hugging Face API", value=True)
|
432 |
+
|
433 |
+
with gr.Group(visible=True) as api_settings:
|
434 |
+
api_key = gr.Textbox(
|
435 |
+
label="Hugging Face API Key",
|
436 |
+
type="password",
|
437 |
+
value=os.environ.get("HF_API_KEY", "")
|
438 |
+
)
|
439 |
+
|
440 |
+
model_choice = gr.Dropdown(
|
441 |
+
choices=["Mistral-7B", "Falcon-7B", "Llama-2-7B", "CodeLlama-7B"],
|
442 |
+
label="Model",
|
443 |
+
value="Mistral-7B",
|
444 |
+
info="Select which LLM to use for code analysis"
|
445 |
+
)
|
446 |
+
|
447 |
+
submit_btn = gr.Button("π₯ Roast My Code!", variant="primary")
|
448 |
+
|
449 |
+
# Function to toggle API settings visibility
|
450 |
+
def toggle_api_settings(use_api):
|
451 |
+
return gr.Group.update(visible=use_api)
|
452 |
+
|
453 |
+
use_api.change(fn=toggle_api_settings, inputs=use_api, outputs=api_settings)
|
454 |
+
|
455 |
+
# Output Sections
|
456 |
+
with gr.Row():
|
457 |
+
loading_indicator = gr.Textbox(label="Status", value="")
|
458 |
+
|
459 |
+
with gr.Tab("Roast π₯"):
|
460 |
+
roast_output = gr.Textbox(label="Roast", lines=5)
|
461 |
+
|
462 |
+
with gr.Tab("Fixed Code β
"):
|
463 |
+
fixed_code_output = gr.Textbox(label="Fixed Code", lines=10)
|
464 |
+
|
465 |
+
with gr.Tab("Explanation π"):
|
466 |
+
explanation_output = gr.Textbox(label="Explanation", lines=5)
|
467 |
+
|
468 |
+
# Example code
|
469 |
+
example_python_code = '''def calculate_fibonacci(n):
|
470 |
+
# This function calculates the fibonacci sequence
|
471 |
+
result = []
|
472 |
+
a, b = 0, 1
|
473 |
+
for i in range(0, n):
|
474 |
+
result.append(a)
|
475 |
+
a, b = b, a + b
|
476 |
+
|
477 |
+
return result
|
478 |
+
|
479 |
+
if **name** == "__main__":
|
480 |
+
print("Fibonacci Sequence:")
|
481 |
+
print(calculate_fibonacci(10))
|
482 |
+
'''
|
483 |
+
|
484 |
+
# Event handlers
|
485 |
+
def load_example():
|
486 |
+
return example_python_code
|
487 |
+
|
488 |
+
def clear_inputs():
|
489 |
+
return ""
|
490 |
+
|
491 |
+
def show_loading():
|
492 |
+
return "β³ AI is analyzing your code and preparing a roast. This may take a few moments..."
|
493 |
+
|
494 |
+
def hide_loading():
|
495 |
+
return "β
Roast complete! Check the tabs below for results."
|
496 |
+
|
497 |
+
# Set up buttons for examples and clearing
|
498 |
+
with gr.Row():
|
499 |
+
example_btn = gr.Button("Load Example Code")
|
500 |
+
clear_btn = gr.Button("Clear")
|
501 |
+
|
502 |
+
example_btn.click(fn=load_example, outputs=code_input)
|
503 |
+
clear_btn.click(fn=clear_inputs, outputs=code_input)
|
504 |
+
|
505 |
+
# Main submit button with loading state
|
506 |
+
submit_btn.click(
|
507 |
+
fn=show_loading,
|
508 |
+
outputs=loading_indicator
|
509 |
+
).then(
|
510 |
+
fn=roast_code,
|
511 |
+
inputs=[code_input, roast_level, use_api, api_key, model_choice],
|
512 |
+
outputs=[roast_output, fixed_code_output, explanation_output]
|
513 |
+
).then(
|
514 |
+
fn=hide_loading,
|
515 |
+
outputs=loading_indicator
|
516 |
+
)
|
517 |
+
|
518 |
+
# About Section
|
519 |
+
gr.Markdown("""
|
520 |
+
### π€ How It Works
|
521 |
+
|
522 |
+
"AI Roast My Code" can work in two modes:
|
523 |
+
|
524 |
+
1. **API Mode**: Uses the Hugging Face API with various models to provide advanced code analysis
|
525 |
+
- Multiple model options including Mistral, Falcon, Llama-2, and CodeLlama
|
526 |
+
- Requires a Hugging Face API key
|
527 |
+
|
528 |
+
2. **Local Mode**: Uses built-in pattern matching for basic code analysis (no API needed)
|
529 |
+
- Works completely offline
|
530 |
+
- No API key required
|
531 |
+
- Detects common issues in Python and JavaScript
|
532 |
+
|
533 |
+
The app will:
|
534 |
+
1. **Analyze** your code for problems, anti-patterns, and style issues
|
535 |
+
2. **Roast** it with humor that ranges from gentle to savage (you choose!)
|
536 |
+
3. **Fix** the issues and provide an improved version
|
537 |
+
4. **Explain** what was wrong and how it was improved
|
538 |
+
|
539 |
+
### π Note
|
540 |
+
|
541 |
+
- For educational purposes only - always review generated code before using it
|
542 |
+
""")
|
543 |
+
|
544 |
+
return app
|
545 |
+
|
546 |
+
# Main function
|
547 |
+
def main():
|
548 |
+
try:
|
549 |
+
logger.info("Starting AI Roast My Code...")
|
550 |
+
|
551 |
+
# Create the interface
|
552 |
+
app = create_interface()
|
553 |
+
|
554 |
+
# Launch the app
|
555 |
+
logger.info("Launching Gradio interface...")
|
556 |
+
app.launch(share=True)
|
557 |
+
except Exception as e:
|
558 |
+
logger.error(f"Error launching application: {str(e)}")
|
559 |
+
raise
|
560 |
+
|
561 |
+
if __name__ == "__main__":
|
562 |
+
main()
|