Girinath11 commited on
Commit
3d5faef
Β·
verified Β·
1 Parent(s): 4707188

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +228 -134
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 for the main app
6
- logging.basicConfig(level=logging.INFO)
7
  logger = logging.getLogger(__name__)
8
 
9
- # Global variable to store the debugger instance
10
  debugger = None
 
11
 
12
  def initialize_debugger():
13
- """Initialize the debugger with proper error handling."""
14
- global debugger
 
15
  try:
16
- logger.info("πŸš€ Initializing Code Debugger...")
17
- debugger = CodeDebuggerWrapper()
18
- logger.info("βœ… Debugger initialized successfully!")
19
- return "βœ… Model loaded successfully!"
20
- except Exception as e:
21
- error_msg = f"❌ Failed to initialize debugger: {str(e)}"
22
- logger.error(error_msg)
23
- return error_msg
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
  def debug_code(code: str):
26
- """Debug code with proper error handling."""
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 not already done
33
  if debugger is None:
34
- init_result = initialize_debugger()
35
- if "❌" in init_result:
36
- return init_result
 
37
 
 
38
  try:
39
- logger.info("🐞 Processing code debug request...")
40
  result = debugger.debug(code)
41
  logger.info("βœ… Debug request completed")
42
  return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  except Exception as e:
44
- error_msg = f"❌ Error during model inference: {str(e)}"
45
- logger.error(error_msg)
46
- return error_msg
47
 
48
- # Create the Gradio interface
49
- def create_interface():
 
 
 
 
50
  """Create the Gradio interface."""
51
 
52
- # Custom CSS for better styling
53
- css = """
54
- .gradio-container {
55
- font-family: 'Arial', sans-serif;
56
- }
57
- .gr-button {
58
- background: linear-gradient(45deg, #FF6B6B, #4ECDC4);
59
- border: none;
60
- color: white;
61
- font-weight: bold;
62
- }
63
- .gr-button:hover {
64
- transform: translateY(-2px);
65
- box-shadow: 0 4px 8px rgba(0,0,0,0.2);
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
- # 🐞 AI Code Debugger
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
- # Status indicator
86
- status_box = gr.Textbox(
87
- value="πŸ”„ Initializing model...",
 
 
 
 
 
88
  label="πŸ“Š System Status",
 
89
  interactive=False,
90
- max_lines=2
91
  )
92
 
93
  # Main interface
94
  with gr.Row():
95
  with gr.Column(scale=1):
96
- code_input = gr.Code(
97
- language="python",
98
- lines=15,
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
- elem_id="code_input"
 
 
 
 
 
 
 
 
 
 
110
  )
111
 
112
- debug_btn = gr.Button(
113
- "πŸ”§ Debug Code",
114
- variant="primary",
115
- size="lg",
116
- elem_id="debug_button"
117
- )
 
 
 
 
118
 
119
  with gr.Column(scale=1):
120
- output = gr.Code(
121
- language="python",
122
- lines=15,
123
- label="✨ Debugged Code / Suggestions",
124
- elem_id="code_output"
125
  )
126
 
127
  # Examples section
128
- gr.Markdown("### πŸ“ Example Issues to Try:")
129
 
130
- examples = [
131
- ["""def calculate_average(numbers):
132
- total = 0
133
- for num in numbers:
134
- total += num
135
- return total / len(numbers)
 
136
 
137
- # This will cause division by zero error
138
- result = calculate_average([])
139
- print(result)"""],
140
 
141
- ["""import math
142
-
143
- def find_roots(a, b, c):
144
- discriminant = b**2 - 4*a*c
145
- root1 = (-b + math.sqrt(discriminant)) / (2*a)
146
- root2 = (-b - math.sqrt(discriminant)) / (2*a)
147
- return root1, root2
148
 
149
- # This might have issues with negative discriminant
150
- print(find_roots(1, 2, 5))"""],
151
 
152
- ["""def process_list(items):
 
153
  result = []
154
- for i in range(len(items)):
155
- if items[i] > 0:
156
- result.append(items[i] * 2)
157
  return result
158
 
159
- # Test the function
160
- data = [1, -2, 3, -4, 5]
161
- print(process_list(data))"""]
 
162
  ]
163
 
164
  gr.Examples(
165
- examples=examples,
166
  inputs=code_input,
167
- label="Click any example to load it:"
168
  )
169
 
170
  # Event handlers
@@ -174,33 +265,36 @@ print(process_list(data))"""]
174
  outputs=output
175
  )
176
 
177
- # Initialize on startup
 
 
 
 
 
178
  demo.load(
179
  fn=initialize_debugger,
180
- outputs=status_box
181
  )
182
 
183
  # Footer
184
- gr.Markdown(
185
- """
186
- ---
187
-
188
- **Tips for better results:**
189
- - Include complete, runnable code snippets
190
- - Add comments explaining what you expect the code to do
191
- - Include any error messages you're seeing
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
- # Create and launch the interface
202
- demo = create_interface()
203
-
204
- # Launch with appropriate settings for Hugging Face Spaces
205
- demo.launch(
206
- share=True)
 
 
 
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
+ )