import gradio as gr import torch from transformers import pipeline import re import time # Initialize the model pipeline model_id = "openai/gpt-oss-120b" pipe = None def initialize_model(): global pipe try: pipe = pipeline( "text-generation", model=model_id, torch_dtype="auto", device_map="auto", ) return "✅ Model loaded successfully!" except Exception as e: return f"❌ Error loading model: {str(e)}" def generate_code(prompt, task_type, language, max_tokens, temperature): if pipe is None: return "❌ Model not initialized. Please load the model first.", "" try: # Customize prompt based on task type if task_type == "Generate Code": system_prompt = f"You are an expert {language} programmer. Generate clean, optimized, and well-commented code for the following request:" full_prompt = f"{system_prompt}\n\n{prompt}\n\nCode:" elif task_type == "Fix Bugs": system_prompt = f"You are an expert {language} debugger. Analyze the following code and fix all bugs, then provide the corrected version:" full_prompt = f"{system_prompt}\n\n{prompt}\n\nFixed Code:" elif task_type == "Optimize Code": system_prompt = f"You are an expert {language} optimizer. Analyze and optimize the following code for better performance and readability:" full_prompt = f"{system_prompt}\n\n{prompt}\n\nOptimized Code:" else: # Explain Code system_prompt = f"You are an expert {language} teacher. Explain the following code step by step:" full_prompt = f"{system_prompt}\n\n{prompt}\n\nExplanation:" messages = [ {"role": "user", "content": full_prompt}, ] outputs = pipe( messages, max_new_tokens=int(max_tokens), temperature=temperature, do_sample=True, pad_token_id=pipe.tokenizer.eos_token_id ) generated_text = outputs[0]["generated_text"][-1]["content"] if isinstance(outputs[0]["generated_text"], list) else outputs[0]["generated_text"] # Extract code if it's wrapped in code blocks code_match = re.search(r'```(?:\w+\n)?(.*?)```', generated_text, re.DOTALL) if code_match: code_output = code_match.group(1).strip() else: code_output = generated_text.strip() # Generate explanation based on the output explanation = f"Task completed successfully! Generated {len(code_output)} characters of {language} code." if task_type == "Fix Bugs": explanation = "Bugs have been identified and fixed. Please review the corrected code." elif task_type == "Optimize Code": explanation = "Code has been optimized for better performance and readability." elif task_type == "Explain Code": explanation = "Code explanation provided below." return code_output, explanation except Exception as e: return f"❌ Error generating code: {str(e)}", "Please try again with different parameters." # Custom CSS for modern UI css = """ .gradio-container { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } .header { text-align: center; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 2rem; border-radius: 15px; margin-bottom: 2rem; box-shadow: 0 10px 30px rgba(0,0,0,0.2); } .header h1 { font-size: 2.5rem; font-weight: 700; margin: 0; text-shadow: 2px 2px 4px rgba(0,0,0,0.3); } .header p { font-size: 1.2rem; margin: 0.5rem 0 0 0; opacity: 0.9; } .custom-button { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); border: none; color: white; font-weight: 600; border-radius: 8px; transition: all 0.3s ease; } .custom-button:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(79, 172, 254, 0.4); } .footer { text-align: center; margin-top: 3rem; padding: 2rem; background: linear-gradient(135deg, #2d3436 0%, #636e72 100%); color: white; border-radius: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); } .footer h3 { margin: 0 0 1rem 0; font-size: 1.3rem; } .footer a { color: #74b9ff; text-decoration: none; margin: 0 1rem; font-weight: 500; transition: color 0.3s ease; } .footer a:hover { color: #0984e3; } .status-box { padding: 1rem; border-radius: 8px; margin: 1rem 0; font-weight: 500; } .code-output { background: #1e1e1e; border-radius: 8px; border: 1px solid #333; } .explanation-output { background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%); border-radius: 8px; padding: 1rem; } """ # Create the Gradio interface with gr.Blocks(css=css, title="AI Code Generator & Bug Fixer", theme=gr.themes.Soft()) as demo: # Header gr.HTML("""
Powered by Advanced AI • Generate, Fix, Optimize & Explain Code