Girinath11 commited on
Commit
65f9a95
Β·
verified Β·
1 Parent(s): bde5911

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +201 -13
app.py CHANGED
@@ -1,25 +1,213 @@
1
  import gradio as gr
2
  from model_wrapper import CodeDebuggerWrapper
 
3
 
4
- # instantiate once (will download model)
5
- debugger = CodeDebuggerWrapper()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
  def debug_code(code: str):
 
 
 
8
  if not code or not code.strip():
9
  return "❌ Please paste some code to debug."
 
 
 
 
 
 
 
10
  try:
11
- return debugger.debug(code)
 
 
 
12
  except Exception as e:
13
- # friendly error message
14
- return f"Error during model inference:\n{e}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- with gr.Blocks() as demo:
17
- gr.Markdown("## 🐞 AI Code Debugger (Fine-tuned)")
18
- gr.Markdown("Paste Python code below and click **Debug Code**. Uses your fine-tuned HF model.")
19
- code_input = gr.Textbox(lines=14, placeholder="Paste Python code here...", label="Input Code")
20
- output = gr.Textbox(lines=14, label="Debugged Code / Output")
21
- btn = gr.Button("Debug Code")
22
- btn.click(fn=debug_code, inputs=code_input, outputs=output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
 
24
  if __name__ == "__main__":
25
- demo.launch(share=True)
 
 
 
 
 
 
 
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
+ placeholder="""# 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
171
+ def on_debug_click(code):
172
+ # Update status
173
+ status_box.update(value="πŸ”„ Processing your code...")
174
+ result = debug_code(code)
175
+ return result, "βœ… Ready for next debug request"
176
+
177
+ debug_btn.click(
178
+ fn=debug_code,
179
+ inputs=code_input,
180
+ outputs=output
181
+ )
182
+
183
+ # Initialize on startup
184
+ demo.load(
185
+ fn=initialize_debugger,
186
+ outputs=status_box
187
+ )
188
+
189
+ # Footer
190
+ gr.Markdown(
191
+ """
192
+ ---
193
+
194
+ **Tips for better results:**
195
+ - Include complete, runnable code snippets
196
+ - Add comments explaining what you expect the code to do
197
+ - Include any error messages you're seeing
198
+
199
+ **Model:** `Girinath11/aiml_code_debug_model` | **Framework:** Transformers + Gradio
200
+ """
201
+ )
202
+
203
+ return demo
204
 
205
+ # Main execution
206
  if __name__ == "__main__":
207
+ # Create and launch the interface
208
+ demo = create_interface()
209
+
210
+ # Launch with appropriate settings for Hugging Face Spaces
211
+ demo.launch(
212
+ share=True
213
+ )