Spaces:
Build error

sneha2803's picture
Update app.py
5493105 verified
Raw History Blame Contribute Delete
8.46 kB
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 """
<div style="display: flex; justify-content: center; margin: 20px 0;">
<div style="background-color: #e9f5fe; padding: 20px; border-radius: 10px; text-align: center; border-left: 5px solid #3498db; width: 90%;">
<div style="margin-bottom: 15px; font-weight: bold; color: #3498db; font-size: 18px;">
Analyzing your question...
</div>
<div class="loading-spinner">
<style>
.loading-spinner {
display: inline-block;
width: 50px;
height: 50px;
border: 5px solid rgba(52, 152, 219, 0.3);
border-radius: 50%;
border-top-color: #3498db;
animation: spin 1s ease-in-out infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
</style>
</div>
<div style="margin-top: 15px; color: #3498db;">
Please wait while the model processes your question.
<br>This may take a few minutes on first run.
</div>
</div>
</div>
"""
# 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(), """
<div style="background-color: #f8d7da; padding: 15px; border-radius: 5px; border-left: 5px solid #dc3545;">
<strong style="color: #dc3545;">⚠️ Error:</strong> Please fill in all fields before analyzing.
</div>
"""
# 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(), """
<div style="background-color: #f8d7da; padding: 15px; border-radius: 5px; border-left: 5px solid #dc3545;">
<strong style="color: #dc3545;">❌ Error:</strong> Failed to load the model. Please check the logs.
</div>
"""
# 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"""
<div style="background-color: #f0f8ff; padding: 20px; border-radius: 10px; border-left: 5px solid #4682b4;">
<h3 style="color: #4682b4; margin-top: 0;">Analysis Result</h3>
<p style="margin-bottom: 20px;"><strong>Student selected:</strong> Option {student_answer}</p>
<div style="line-height: 1.6;">
{explanation}
</div>
</div>
"""
# 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()