import gradio as gr from model_wrapper import CodeDebuggerWrapper import logging # Set up logging for the main app logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Global variable to store the debugger instance debugger = None def initialize_debugger(): """Initialize the debugger with proper error handling.""" global debugger try: logger.info("🚀 Initializing Code Debugger...") debugger = CodeDebuggerWrapper() logger.info("✅ Debugger initialized successfully!") return "✅ Model loaded successfully!" except Exception as e: error_msg = f"❌ Failed to initialize debugger: {str(e)}" logger.error(error_msg) return error_msg def debug_code(code: str): """Debug code with proper error handling.""" global debugger if not code or not code.strip(): return "❌ Please paste some code to debug." # Initialize debugger if not already done if debugger is None: init_result = initialize_debugger() if "❌" in init_result: return init_result try: logger.info("🐞 Processing code debug request...") result = debugger.debug(code) logger.info("✅ Debug request completed") return result except Exception as e: error_msg = f"❌ Error during model inference: {str(e)}" logger.error(error_msg) return error_msg # Create the Gradio interface def create_interface(): """Create the Gradio interface.""" # Custom CSS for better styling css = """ .gradio-container { font-family: 'Arial', sans-serif; } .gr-button { background: linear-gradient(45deg, #FF6B6B, #4ECDC4); border: none; color: white; font-weight: bold; } .gr-button:hover { transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0,0,0,0.2); } """ with gr.Blocks(css=css, title="🐞 AI Code Debugger", theme=gr.themes.Soft()) as demo: # Header gr.Markdown( """ # 🐞 AI Code Debugger ### Fine-tuned AI model for debugging Python code **Instructions:** 1. Paste your Python code in the input box below 2. Click "🔧 Debug Code" to get suggestions and fixes 3. The AI will analyze your code and provide improvements --- """ ) # Status indicator status_box = gr.Textbox( value="🔄 Initializing model...", label="📊 System Status", interactive=False, max_lines=2 ) # Main interface with gr.Row(): with gr.Column(scale=1): code_input = gr.Code( language="python", lines=15, value="""# Paste your Python code here # Example: def fibonacci(n): if n <= 1 return n else: return fibonacci(n-1) + fibonacci(n-2) print(fibonacci(10))""", label="🔍 Input Code", elem_id="code_input" ) debug_btn = gr.Button( "🔧 Debug Code", variant="primary", size="lg", elem_id="debug_button" ) with gr.Column(scale=1): output = gr.Code( language="python", lines=15, label="✨ Debugged Code / Suggestions", elem_id="code_output" ) # Examples section gr.Markdown("### 📝 Example Issues to Try:") examples = [ ["""def calculate_average(numbers): total = 0 for num in numbers: total += num return total / len(numbers) # This will cause division by zero error result = calculate_average([]) print(result)"""], ["""import math def find_roots(a, b, c): discriminant = b**2 - 4*a*c root1 = (-b + math.sqrt(discriminant)) / (2*a) root2 = (-b - math.sqrt(discriminant)) / (2*a) return root1, root2 # This might have issues with negative discriminant print(find_roots(1, 2, 5))"""], ["""def process_list(items): result = [] for i in range(len(items)): if items[i] > 0: result.append(items[i] * 2) return result # Test the function data = [1, -2, 3, -4, 5] print(process_list(data))"""] ] gr.Examples( examples=examples, inputs=code_input, label="Click any example to load it:" ) # Event handlers debug_btn.click( fn=debug_code, inputs=code_input, outputs=output ) # Initialize on startup demo.load( fn=initialize_debugger, outputs=status_box ) # Footer gr.Markdown( """ --- **Tips for better results:** - Include complete, runnable code snippets - Add comments explaining what you expect the code to do - Include any error messages you're seeing **Model:** `Girinath11/aiml_code_debug_model` | **Framework:** Transformers + Gradio """ ) return demo # Main execution if __name__ == "__main__": # Create and launch the interface demo = create_interface() # Launch with appropriate settings for Hugging Face Spaces demo.launch( share=True)