import gradio as gr from transformers import AutoTokenizer, AutoModelForCausalLM from peft import PeftModel import torch import time # Configuration BASE_MODEL_NAME = "unsloth/Meta-Llama-3.1-8B" # Your base model ADAPTER_NAME = "sneha2803/Final_Llama3_18_BfineTune" # Your adapter repo # Load models with caching def load_peft_model(): try: # Load tokenizer from adapter repo tokenizer = AutoTokenizer.from_pretrained(ADAPTER_NAME) # Load base model base_model = AutoModelForCausalLM.from_pretrained( BASE_MODEL_NAME, device_map="auto", torch_dtype="auto", trust_remote_code=True ) # Load LoRA adapter model = PeftModel.from_pretrained( base_model, ADAPTER_NAME, device_map="auto" ) return tokenizer, model except Exception as e: print(f"Error loading model: {e}") return None, None # Generate answer def get_answer(full_query, tokenizer, model): try: inputs = tokenizer(full_query, return_tensors="pt").to(model.device) outputs = model.generate( inputs.input_ids, max_new_tokens=400, temperature=0.7, top_p=0.9, repetition_penalty=1.1 ) return tokenizer.decode(outputs[0], skip_special_tokens=True) except Exception as e: return f"Error generating answer: {str(e)}" # Show loading animation def show_loading(): return """
Analyzing your question...
Please wait while the model processes your question.
This may take a few minutes on first run.
""" # Main function to process input and generate response def analyze_math_question(question, option_a, option_b, option_c, option_d, student_answer): # Check if inputs are provided if not question or not option_a or not option_b or not option_c or not option_d: return show_loading(), """
⚠️ Error: Please fill in all fields before analyzing.
""" # First show the loading animation yield show_loading(), None # Load models if not already loaded global tokenizer, model if 'tokenizer' not in globals() or 'model' not in globals() or tokenizer is None or model is None: tokenizer, model = load_peft_model() if tokenizer is None or model is None: return show_loading(), """
❌ Error: Failed to load the model. Please check the logs.
""" # Format the input prompt full_query = ( f"You are a mathematics expert. Analyze the following:\n\n" f"Question: {question}\n" f"Options:\nA) {option_a}\nB) {option_b}\nC) {option_c}\nD) {option_d}\n\n" f"The student chose option {student_answer}.\n" f"Please identify the student's likely misconception based on their chosen answer. " f"Explain clearly why the student might have thought this was correct, and what misunderstanding they show.\n\n" f"Misconception:" ) # Generate the answer answer = get_answer(full_query, tokenizer, model) # Process the response to extract the explanation if "Explanation:" in answer: explanation = answer.split("Explanation:")[-1].strip() else: explanation = answer # Remove the loading indicator and display the result return "", f"""

Analysis Result

Student selected: Option {student_answer}

{explanation}
""" # Define the Gradio interface with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as demo: gr.Markdown( """ # 📐 Mathematics Question Assistant This tool analyzes student responses to math problems and identifies misconceptions. """ ) with gr.Row(): with gr.Column(scale=3): gr.Markdown("### 📝 Problem Details") question = gr.Textbox( label="Question", placeholder="Enter the math question here...", lines=4 ) with gr.Row(): with gr.Column(): option_a = gr.Textbox(label="Option A", placeholder="Enter option A...") option_b = gr.Textbox(label="Option B", placeholder="Enter option B...") with gr.Column(): option_c = gr.Textbox(label="Option C", placeholder="Enter option C...") option_d = gr.Textbox(label="Option D", placeholder="Enter option D...") student_answer = gr.Radio( ["A", "B", "C", "D"], label="Student's Answer", value="A" ) analyze_btn = gr.Button("✨ Analyze Answer", variant="primary", size="lg") with gr.Column(scale=2): gr.Markdown("### 🔍 Result") # Add two HTML components: one for the loading animation and one for the result loading_indicator = gr.HTML() result = gr.HTML() # Set up the analyze button click event with streaming output analyze_btn.click( fn=analyze_math_question, inputs=[question, option_a, option_b, option_c, option_d, student_answer], outputs=[loading_indicator, result], api_name="analyze" ) # Add example inputs gr.Examples( [ [ "Solve for x: 2x + 5 = 13", "x = 4", "x = 9", "x = 8", "x = 4.5", "A" ], [ "Find the derivative of f(x) = x^2 + 3x", "f'(x) = 2x", "f'(x) = 2x + 3", "f'(x) = x^2 + 3", "f'(x) = 2 + 3x", "B" ] ], inputs=[question, option_a, option_b, option_c, option_d, student_answer] ) gr.Markdown( """ ### 📌 How to use 1. Enter the math question in the text box 2. Fill in the multiple choice options A through D 3. Select the student's chosen answer 4. Click "Analyze Answer" to generate an assessment of their misconception ### ⏱️ Note on loading time When you first click "Analyze Answer", the app needs to load large language models which may take several minutes. The loading indicator will show you that the app is working. """ ) # Load models on startup tokenizer, model = None, None # Launch the app if __name__ == "__main__": demo.launch()