Spaces:
Sleeping
Sleeping
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') | |
# Cache for exercises | |
def get_coding_exercise(topic, difficulty): | |
"""Generate a coding exercise based on the given topic and difficulty.""" | |
prompt = f"Briefly create a {difficulty} Python coding exercise about {topic}. Include a concise problem statement and expected output. Keep it under 100 words." | |
try: | |
response = model.generate_content(prompt, timeout=30) | |
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} | |
Briefly evaluate the code. Provide concise feedback on correctness, efficiency, and style. | |
If there are errors, explain them. Suggest improvements. Keep the response under 150 words. | |
""" | |
try: | |
response = model.generate_content(prompt, timeout=30) | |
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() |