import gradio as gr import google.generativeai as genai from functools import lru_cache import time # Initialize Gemini API (replace with your actual API key) genai.configure(api_key="AIzaSyBPQF0g5EfEPzEiGRzA3iNzJZK4jDukMvE") # Initialize the model model = genai.GenerativeModel('gemini-pro') def get_coding_exercise(topic, difficulty): """Generate a coding exercise based on the given topic and difficulty.""" prompt = f"""Create a {difficulty} Python coding exercise about {topic}. Provide ONLY the problem statement and expected output , sample input and sample output. Do NOT include any code or solution. Keep it under 100 words and make it clear and concise.""" try: response = model.generate_content(prompt) return response.text except Exception as e: return f"Error generating exercise: {str(e)}" def evaluate_code(exercise, user_code): """Evaluate the user's code submission.""" prompt = f""" Exercise: {exercise} User's code: {user_code} Perform a concise code review addressing the following points: 1. Correctness: Does the code solve the given problem? If not, what's missing? 2. Efficiency: Is the solution efficient? Suggest any optimizations if applicable. 3. Style and Best Practices: Comment on code style, readability, and adherence to Python best practices. 4. Potential Improvements: Offer 1-2 specific suggestions for improving the code. Format your response as follows: Correctness: [Your evaluation] Efficiency: [Your evaluation] Style: [Your evaluation] Improvements: [Your suggestions] Keep the entire response under 200 words and be specific in your feedback. """ try: response = model.generate_content(prompt) return response.text except Exception as e: return f"Error evaluating code: {str(e)}" def tutor_interface(topic, difficulty): with gr.Row(): gr.Markdown("Generating exercise...") time.sleep(0.1) # Small delay to ensure loading message is shown exercise = get_coding_exercise(topic, difficulty) return exercise def submit_solution(exercise, user_code): with gr.Row(): gr.Markdown("Evaluating solution...") time.sleep(0.1) # Small delay to ensure loading message is shown feedback = evaluate_code(exercise, user_code) return feedback # Create the Gradio interface with gr.Blocks() as demo: gr.Markdown("# Intelligent Code Tutor") with gr.Row(): topic_input = gr.Textbox(label="Topic (e.g., 'loops', 'lists', 'functions')") difficulty_input = gr.Dropdown(["easy", "medium", "hard"], label="Difficulty") generate_btn = gr.Button("Generate Exercise") exercise_output = gr.Textbox(label="Coding Exercise", lines=10) generate_btn.click(tutor_interface, inputs=[topic_input, difficulty_input], outputs=exercise_output) code_input = gr.Code(language="python", label="Your Solution") submit_btn = gr.Button("Submit Solution") feedback_output = gr.Textbox(label="Feedback", lines=10) submit_btn.click(submit_solution, inputs=[exercise_output, code_input], outputs=feedback_output) if __name__ == "__main__": demo.launch()