Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,170 +1,261 @@
|
|
|
|
1 |
import gradio as gr
|
2 |
-
from model_wrapper import CodeDebuggerWrapper
|
3 |
import logging
|
|
|
4 |
|
5 |
-
# Set up logging
|
6 |
-
logging.basicConfig(level=logging.INFO)
|
7 |
logger = logging.getLogger(__name__)
|
8 |
|
9 |
-
# Global
|
10 |
debugger = None
|
|
|
11 |
|
12 |
def initialize_debugger():
|
13 |
-
"""Initialize the debugger with
|
14 |
-
global debugger
|
|
|
15 |
try:
|
16 |
-
logger.info("π
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
|
25 |
def debug_code(code: str):
|
26 |
-
"""Debug code with
|
27 |
-
global debugger
|
28 |
|
|
|
29 |
if not code or not code.strip():
|
30 |
return "β Please paste some code to debug."
|
31 |
|
32 |
-
# Initialize debugger if
|
33 |
if debugger is None:
|
34 |
-
|
35 |
-
|
36 |
-
|
|
|
37 |
|
|
|
38 |
try:
|
39 |
-
logger.info("π Processing
|
40 |
result = debugger.debug(code)
|
41 |
logger.info("β
Debug request completed")
|
42 |
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
except Exception as e:
|
44 |
-
|
45 |
-
logger.error(error_msg)
|
46 |
-
return error_msg
|
47 |
|
48 |
-
|
49 |
-
|
|
|
|
|
|
|
|
|
50 |
"""Create the Gradio interface."""
|
51 |
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
with gr.Blocks(css=css, title="π AI Code Debugger", theme=gr.themes.Soft()) as demo:
|
70 |
# Header
|
71 |
-
gr.Markdown(
|
72 |
-
|
73 |
-
|
74 |
-
### Fine-tuned AI model for debugging Python code
|
75 |
-
|
76 |
-
**Instructions:**
|
77 |
-
1. Paste your Python code in the input box below
|
78 |
-
2. Click "π§ Debug Code" to get suggestions and fixes
|
79 |
-
3. The AI will analyze your code and provide improvements
|
80 |
-
|
81 |
-
---
|
82 |
-
"""
|
83 |
-
)
|
84 |
|
85 |
-
|
86 |
-
|
87 |
-
|
|
|
|
|
|
|
|
|
|
|
88 |
label="π System Status",
|
|
|
89 |
interactive=False,
|
90 |
-
|
91 |
)
|
92 |
|
93 |
# Main interface
|
94 |
with gr.Row():
|
95 |
with gr.Column(scale=1):
|
96 |
-
code_input = gr.
|
97 |
-
|
98 |
-
|
99 |
-
value="""# Paste your Python code here
|
100 |
-
# Example:
|
101 |
-
def fibonacci(n):
|
102 |
-
if n <= 1
|
103 |
-
return n
|
104 |
-
else:
|
105 |
-
return fibonacci(n-1) + fibonacci(n-2)
|
106 |
-
|
107 |
-
print(fibonacci(10))""",
|
108 |
label="π Input Code",
|
109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
110 |
)
|
111 |
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
|
|
|
|
|
|
|
|
118 |
|
119 |
with gr.Column(scale=1):
|
120 |
-
output = gr.
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
)
|
126 |
|
127 |
# Examples section
|
128 |
-
gr.Markdown("###
|
129 |
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
|
|
136 |
|
137 |
-
|
138 |
-
result = calculate_average([])
|
139 |
-
print(result)"""],
|
140 |
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
return
|
148 |
|
149 |
-
|
150 |
-
print(
|
151 |
|
152 |
-
|
|
|
153 |
result = []
|
154 |
-
for
|
155 |
-
|
156 |
-
result.append(items[i] * 2)
|
157 |
return result
|
158 |
|
159 |
-
#
|
160 |
-
data = [
|
161 |
-
|
|
|
162 |
]
|
163 |
|
164 |
gr.Examples(
|
165 |
-
examples=
|
166 |
inputs=code_input,
|
167 |
-
label="Click any example to load
|
168 |
)
|
169 |
|
170 |
# Event handlers
|
@@ -174,33 +265,36 @@ print(process_list(data))"""]
|
|
174 |
outputs=output
|
175 |
)
|
176 |
|
177 |
-
|
|
|
|
|
|
|
|
|
|
|
178 |
demo.load(
|
179 |
fn=initialize_debugger,
|
180 |
-
outputs=
|
181 |
)
|
182 |
|
183 |
# Footer
|
184 |
-
gr.Markdown(
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
**Model:** `Girinath11/aiml_code_debug_model` | **Framework:** Transformers + Gradio
|
194 |
-
"""
|
195 |
-
)
|
196 |
|
197 |
return demo
|
198 |
|
199 |
-
# Main execution
|
200 |
if __name__ == "__main__":
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
|
|
|
|
|
1 |
+
# app.py - Robust version with fallback
|
2 |
import gradio as gr
|
|
|
3 |
import logging
|
4 |
+
import traceback
|
5 |
|
6 |
+
# Set up logging
|
7 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
8 |
logger = logging.getLogger(__name__)
|
9 |
|
10 |
+
# Global debugger instance
|
11 |
debugger = None
|
12 |
+
debugger_status = "π Initializing..."
|
13 |
|
14 |
def initialize_debugger():
|
15 |
+
"""Initialize the debugger with comprehensive error handling."""
|
16 |
+
global debugger, debugger_status
|
17 |
+
|
18 |
try:
|
19 |
+
logger.info("π Starting debugger initialization...")
|
20 |
+
debugger_status = "π Loading AI model..."
|
21 |
+
|
22 |
+
# First, try the main model wrapper
|
23 |
+
try:
|
24 |
+
from model_wrapper import CodeDebuggerWrapper
|
25 |
+
logger.info("Attempting to load main model wrapper...")
|
26 |
+
debugger = CodeDebuggerWrapper()
|
27 |
+
debugger_status = "β
AI model loaded successfully!"
|
28 |
+
logger.info("β
Main model wrapper loaded successfully")
|
29 |
+
return debugger_status
|
30 |
+
|
31 |
+
except Exception as main_error:
|
32 |
+
logger.warning(f"Main model wrapper failed: {str(main_error)[:200]}...")
|
33 |
+
logger.debug(f"Full error: {traceback.format_exc()}")
|
34 |
+
|
35 |
+
# Try fallback debugger
|
36 |
+
try:
|
37 |
+
from model_wrapper import FallbackDebugger
|
38 |
+
logger.info("Falling back to rule-based debugger...")
|
39 |
+
debugger = FallbackDebugger()
|
40 |
+
debugger_status = "β οΈ Using fallback debugger (AI model unavailable)"
|
41 |
+
logger.info("β
Fallback debugger loaded")
|
42 |
+
return debugger_status
|
43 |
+
|
44 |
+
except Exception as fallback_error:
|
45 |
+
logger.error(f"Fallback debugger also failed: {fallback_error}")
|
46 |
+
debugger_status = "β Both AI and fallback debuggers failed"
|
47 |
+
return debugger_status
|
48 |
+
|
49 |
+
except Exception as critical_error:
|
50 |
+
logger.error(f"Critical initialization error: {critical_error}")
|
51 |
+
logger.error(f"Full traceback: {traceback.format_exc()}")
|
52 |
+
debugger_status = f"β Critical error: {str(critical_error)[:100]}..."
|
53 |
+
return debugger_status
|
54 |
|
55 |
def debug_code(code: str):
|
56 |
+
"""Debug code with comprehensive error handling."""
|
57 |
+
global debugger, debugger_status
|
58 |
|
59 |
+
# Input validation
|
60 |
if not code or not code.strip():
|
61 |
return "β Please paste some code to debug."
|
62 |
|
63 |
+
# Initialize debugger if needed
|
64 |
if debugger is None:
|
65 |
+
logger.info("Debugger not initialized, initializing now...")
|
66 |
+
status = initialize_debugger()
|
67 |
+
if "β" in status:
|
68 |
+
return f"{status}\n\nπ§ **Manual Analysis:**\n{manual_debug_fallback(code)}"
|
69 |
|
70 |
+
# Try to debug with loaded debugger
|
71 |
try:
|
72 |
+
logger.info("π Processing debug request...")
|
73 |
result = debugger.debug(code)
|
74 |
logger.info("β
Debug request completed")
|
75 |
return result
|
76 |
+
|
77 |
+
except Exception as debug_error:
|
78 |
+
logger.error(f"Debug processing failed: {debug_error}")
|
79 |
+
logger.error(f"Full traceback: {traceback.format_exc()}")
|
80 |
+
|
81 |
+
# Ultimate fallback
|
82 |
+
return f"β Debug processing failed: {str(debug_error)[:100]}...\n\nπ§ **Manual Analysis:**\n{manual_debug_fallback(code)}"
|
83 |
+
|
84 |
+
def manual_debug_fallback(code: str) -> str:
|
85 |
+
"""Ultimate fallback - basic syntax checking."""
|
86 |
+
try:
|
87 |
+
issues = []
|
88 |
+
lines = code.split('\n')
|
89 |
+
|
90 |
+
for i, line in enumerate(lines, 1):
|
91 |
+
stripped = line.strip()
|
92 |
+
if not stripped or stripped.startswith('#'):
|
93 |
+
continue
|
94 |
+
|
95 |
+
# Check for missing colons
|
96 |
+
control_keywords = ['if ', 'elif ', 'else:', 'for ', 'while ', 'def ', 'class ', 'try:', 'except', 'finally:']
|
97 |
+
if any(keyword in stripped for keyword in control_keywords):
|
98 |
+
if not stripped.endswith(':') and 'else:' not in stripped and 'try:' not in stripped and 'finally:' not in stripped:
|
99 |
+
issues.append(f"Line {i}: Possible missing colon (:)")
|
100 |
+
|
101 |
+
# Check for unbalanced parentheses
|
102 |
+
if stripped.count('(') != stripped.count(')'):
|
103 |
+
issues.append(f"Line {i}: Unbalanced parentheses")
|
104 |
+
|
105 |
+
# Check for unbalanced quotes
|
106 |
+
single_quotes = stripped.count("'")
|
107 |
+
double_quotes = stripped.count('"')
|
108 |
+
if single_quotes % 2 != 0:
|
109 |
+
issues.append(f"Line {i}: Unbalanced single quotes")
|
110 |
+
if double_quotes % 2 != 0:
|
111 |
+
issues.append(f"Line {i}: Unbalanced double quotes")
|
112 |
+
|
113 |
+
# Generate response
|
114 |
+
result = f"**Your Code:**\n```python\n{code}\n```\n\n"
|
115 |
+
|
116 |
+
if issues:
|
117 |
+
result += "**Potential Issues Found:**\n"
|
118 |
+
for issue in issues:
|
119 |
+
result += f"β’ {issue}\n"
|
120 |
+
else:
|
121 |
+
result += "**No obvious syntax errors detected.**\n"
|
122 |
+
|
123 |
+
result += "\n**Debugging Checklist:**\n"
|
124 |
+
result += "β’ β Check for missing colons after if/for/def statements\n"
|
125 |
+
result += "β’ β Verify proper indentation (4 spaces per level)\n"
|
126 |
+
result += "β’ β Ensure parentheses and quotes are balanced\n"
|
127 |
+
result += "β’ β Check for typos in variable names\n"
|
128 |
+
result += "β’ β Verify all imports are included\n"
|
129 |
+
result += "β’ β Look for logic errors in conditions\n"
|
130 |
+
|
131 |
+
return result
|
132 |
+
|
133 |
except Exception as e:
|
134 |
+
return f"Even manual analysis failed: {e}\n\nOriginal code:\n{code}"
|
|
|
|
|
135 |
|
136 |
+
def get_status():
|
137 |
+
"""Get current system status."""
|
138 |
+
global debugger_status
|
139 |
+
return debugger_status
|
140 |
+
|
141 |
+
def create_app():
|
142 |
"""Create the Gradio interface."""
|
143 |
|
144 |
+
with gr.Blocks(
|
145 |
+
title="π AI Code Debugger",
|
146 |
+
theme=gr.themes.Soft(),
|
147 |
+
css="""
|
148 |
+
.status-box {
|
149 |
+
background: linear-gradient(45deg, #f0f0f0, #e0e0e0);
|
150 |
+
border-radius: 10px;
|
151 |
+
padding: 10px;
|
152 |
+
}
|
153 |
+
.code-box {
|
154 |
+
font-family: 'Consolas', 'Monaco', monospace;
|
155 |
+
font-size: 14px;
|
156 |
+
}
|
157 |
+
"""
|
158 |
+
) as demo:
|
159 |
+
|
|
|
|
|
160 |
# Header
|
161 |
+
gr.Markdown("""
|
162 |
+
# π AI Code Debugger
|
163 |
+
### Fine-tuned AI model for debugging Python code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
164 |
|
165 |
+
**How to use:**
|
166 |
+
1. Paste your Python code in the left box
|
167 |
+
2. Click "π§ Debug Code"
|
168 |
+
3. Get AI-powered suggestions and fixes
|
169 |
+
""")
|
170 |
+
|
171 |
+
# Status display
|
172 |
+
status_display = gr.Textbox(
|
173 |
label="π System Status",
|
174 |
+
value="π Loading...",
|
175 |
interactive=False,
|
176 |
+
elem_classes=["status-box"]
|
177 |
)
|
178 |
|
179 |
# Main interface
|
180 |
with gr.Row():
|
181 |
with gr.Column(scale=1):
|
182 |
+
code_input = gr.Textbox(
|
183 |
+
lines=16,
|
184 |
+
placeholder="Paste your Python code here...",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
185 |
label="π Input Code",
|
186 |
+
elem_classes=["code-box"],
|
187 |
+
value="""# Example: Function with syntax error
|
188 |
+
def calculate_average(numbers):
|
189 |
+
total = 0
|
190 |
+
for num in numbers
|
191 |
+
total += num
|
192 |
+
return total / len(numbers)
|
193 |
+
|
194 |
+
# Test with empty list (will cause error)
|
195 |
+
result = calculate_average([])
|
196 |
+
print(result)"""
|
197 |
)
|
198 |
|
199 |
+
with gr.Row():
|
200 |
+
debug_btn = gr.Button(
|
201 |
+
"π§ Debug Code",
|
202 |
+
variant="primary",
|
203 |
+
size="lg"
|
204 |
+
)
|
205 |
+
clear_btn = gr.Button(
|
206 |
+
"ποΈ Clear",
|
207 |
+
variant="secondary"
|
208 |
+
)
|
209 |
|
210 |
with gr.Column(scale=1):
|
211 |
+
output = gr.Textbox(
|
212 |
+
lines=16,
|
213 |
+
label="β¨ Debug Results",
|
214 |
+
placeholder="Debug results will appear here...",
|
215 |
+
elem_classes=["code-box"]
|
216 |
)
|
217 |
|
218 |
# Examples section
|
219 |
+
gr.Markdown("### π Example Problems:")
|
220 |
|
221 |
+
example_codes = [
|
222 |
+
# Syntax error example
|
223 |
+
["""def greet(name):
|
224 |
+
if name
|
225 |
+
print(f"Hello, {name}!")
|
226 |
+
else:
|
227 |
+
print("Hello, stranger!")
|
228 |
|
229 |
+
greet("Alice")"""],
|
|
|
|
|
230 |
|
231 |
+
# Logic error example
|
232 |
+
["""def find_maximum(numbers):
|
233 |
+
max_num = 0 # Bug: assumes all numbers are positive
|
234 |
+
for num in numbers:
|
235 |
+
if num > max_num:
|
236 |
+
max_num = num
|
237 |
+
return max_num
|
238 |
|
239 |
+
result = find_maximum([-5, -2, -8, -1])
|
240 |
+
print(f"Maximum: {result}")"""],
|
241 |
|
242 |
+
# Runtime error example
|
243 |
+
["""def divide_list(numbers, divisor):
|
244 |
result = []
|
245 |
+
for num in numbers:
|
246 |
+
result.append(num / divisor)
|
|
|
247 |
return result
|
248 |
|
249 |
+
# This will cause division by zero
|
250 |
+
data = [10, 20, 30]
|
251 |
+
divided = divide_list(data, 0)
|
252 |
+
print(divided)"""],
|
253 |
]
|
254 |
|
255 |
gr.Examples(
|
256 |
+
examples=example_codes,
|
257 |
inputs=code_input,
|
258 |
+
label="Click any example to load:"
|
259 |
)
|
260 |
|
261 |
# Event handlers
|
|
|
265 |
outputs=output
|
266 |
)
|
267 |
|
268 |
+
clear_btn.click(
|
269 |
+
lambda: ("", ""),
|
270 |
+
outputs=[code_input, output]
|
271 |
+
)
|
272 |
+
|
273 |
+
# Initialize status on load
|
274 |
demo.load(
|
275 |
fn=initialize_debugger,
|
276 |
+
outputs=status_display
|
277 |
)
|
278 |
|
279 |
# Footer
|
280 |
+
gr.Markdown("""
|
281 |
+
---
|
282 |
+
**Model:** `Girinath11/aiml_code_debug_model` | **Fallback:** Rule-based analysis
|
283 |
+
|
284 |
+
**Tips for better results:**
|
285 |
+
β’ Include complete, runnable code snippets
|
286 |
+
β’ Add comments explaining expected behavior
|
287 |
+
β’ Include any error messages you're seeing
|
288 |
+
""")
|
|
|
|
|
|
|
289 |
|
290 |
return demo
|
291 |
|
|
|
292 |
if __name__ == "__main__":
|
293 |
+
try:
|
294 |
+
logger.info("π Starting Code Debugger application...")
|
295 |
+
demo = create_app()
|
296 |
+
|
297 |
+
# Launch the app
|
298 |
+
demo.launch(
|
299 |
+
share=True
|
300 |
+
)
|