import gradio as gr import torch import pandas as pd import numpy as np import json import time from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig from peft import PeftModel, PeftConfig import warnings warnings.filterwarnings("ignore") # Global variables for the model and tokenizer model = None tokenizer = None def load_model(): """Load the trained model and tokenizer""" global model, tokenizer if model is None: print("๐Ÿš€ Loading the personalized learning recommendation model...") # Use a smaller, non-gated model that works better in Spaces model_name = "microsoft/DialoGPT-medium" # Alternative: "distilgpt2", "gpt2" try: # Load tokenizer tokenizer = AutoTokenizer.from_pretrained(model_name) tokenizer.pad_token = tokenizer.eos_token tokenizer.padding_side = "left" # Load base model (no quantization for smaller models) model = AutoModelForCausalLM.from_pretrained( model_name, device_map="auto" if torch.cuda.is_available() else "cpu", torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32 ) # Note: If you have a trained adapter, uncomment and modify this: # adapter_path = "your-username/learning-recommender-rubric" # UPDATE THIS # model = PeftModel.from_pretrained(model, adapter_path) model.eval() print("โœ… Model loaded successfully!") except Exception as e: print(f"โŒ Error loading model: {e}") # Fallback to rule-based system model = None tokenizer = None return model, tokenizer def generate_rule_based_recommendation(student_data): """ Fallback rule-based recommendation system """ student_id = student_data['student_id'] learning_style = student_data['learning_style'] subject = student_data['subject'] difficulty = student_data['difficulty'] time_spent = student_data['time_spent'] problems_attempted = student_data['problems_attempted'] problems_solved = student_data['problems_solved'] engagement_score = student_data['engagement_score'] session_type = student_data['session_type'] performance_score = student_data['performance_score'] success_rate = problems_solved / problems_attempted recommendations = [] # Performance-based recommendations if success_rate < 0.3: recommendations.append("๐Ÿ“š **Focus on Fundamentals**: Your current success rate suggests reviewing basic concepts would be beneficial.") recommendations.append(f"๐Ÿ”„ **Adjust Difficulty**: Consider reducing difficulty from level {difficulty} to level {max(1, difficulty-1)} temporarily.") if learning_style == "visual": recommendations.append("๐ŸŽจ **Visual Aids**: Use diagrams, charts, and visual representations to understand core concepts.") elif learning_style == "auditory": recommendations.append("๐ŸŽง **Audio Learning**: Try educational podcasts or recorded lectures for this topic.") elif success_rate < 0.6: recommendations.append("โšก **Practice More**: You're on the right track! Additional practice problems will help solidify your understanding.") recommendations.append("๐ŸŽฏ **Targeted Review**: Focus on the types of problems you're missing most often.") else: recommendations.append("๐Ÿš€ **Challenge Yourself**: Great job! Consider increasing difficulty or exploring advanced topics.") recommendations.append(f"๐Ÿ“ˆ **Next Level**: Try moving to difficulty level {min(5, difficulty+1)} in your next session.") # Engagement-based recommendations if engagement_score < 0.4: recommendations.append("๐ŸŽฎ **Interactive Content**: Try more interactive sessions to boost engagement.") if session_type != "interactive": recommendations.append("๐Ÿ”„ **Change Format**: Consider switching to interactive exercises or gamified content.") elif engagement_score < 0.7: recommendations.append("โญ **Mix It Up**: Vary your session types to maintain interest.") # Time-based recommendations if time_spent > 40: recommendations.append("โฑ๏ธ **Take Breaks**: Long sessions detected. Try shorter, more focused 20-30 minute sessions.") elif time_spent < 15: recommendations.append("๐Ÿ“… **Extend Sessions**: Consider slightly longer sessions for better concept retention.") # Learning style specific recommendations if learning_style == "kinesthetic": recommendations.append("๐Ÿคน **Hands-on Practice**: Incorporate physical activities or manipulatives when possible.") elif learning_style == "reading/writing": recommendations.append("๐Ÿ“ **Note-taking**: Make detailed notes and try explaining concepts in writing.") # Subject-specific recommendations if subject == "math": recommendations.append("๐Ÿงฎ **Step-by-step**: Break down complex problems into smaller, manageable steps.") elif subject == "science": recommendations.append("๐Ÿ”ฌ **Real-world Connections**: Connect concepts to everyday phenomena and experiments.") elif subject == "coding": recommendations.append("๐Ÿ’ป **Code Practice**: Build small projects to apply what you're learning.") return "\n\n".join(recommendations) def generate_recommendation(student_data): """ Generate a personalized learning recommendation based on student data """ # Try to load model model, tokenizer = load_model() # If model loading failed, use rule-based system if model is None or tokenizer is None: return generate_rule_based_recommendation(student_data) # Create input prompt for AI model input_text = f"""Generate a personalized learning recommendation for this student: Student Profile: - ID: {student_data['student_id']} - Learning Style: {student_data['learning_style']} - Subject: {student_data['subject']} - Current Performance: {student_data['problems_solved']}/{student_data['problems_attempted']} problems solved - Engagement Level: {student_data['engagement_score']:.1f}/1.0 - Time Management: {student_data['time_spent']} minutes spent - Difficulty Level: {student_data['difficulty']}/5 Recommendation:""" try: # Tokenize input inputs = tokenizer(input_text, return_tensors="pt", max_length=256, truncation=True) # Move to appropriate device if torch.cuda.is_available(): inputs = {k: v.to(model.device) for k, v in inputs.items()} # Generate recommendation with torch.no_grad(): outputs = model.generate( **inputs, max_new_tokens=150, temperature=0.8, top_p=0.9, do_sample=True, pad_token_id=tokenizer.eos_token_id, repetition_penalty=1.1 ) # Decode and return the recommendation full_response = tokenizer.decode(outputs[0], skip_special_tokens=True) # Extract only the recommendation part recommendation = full_response[len(input_text):].strip() # Clean up the recommendation lines = recommendation.split('\n') unique_lines = [] for line in lines: if line.strip() and line not in unique_lines and len(line) > 10: unique_lines.append(line.strip()) result = '\n\n'.join(unique_lines) # If AI generation is too short, fall back to rule-based if len(result) < 50: return generate_rule_based_recommendation(student_data) return result except Exception as e: print(f"AI generation failed: {e}") # Fallback to rule-based system return generate_rule_based_recommendation(student_data) def process_student_input(student_id, learning_style, subject, difficulty, time_spent, problems_attempted, problems_solved, engagement_score, session_type, performance_score): """ Process the input from the Gradio interface and generate a recommendation """ # Validate inputs if not student_id or not subject or problems_attempted <= 0: return "โŒ Please fill in all required fields. Problems attempted must be greater than 0." if problems_solved > problems_attempted: return "โŒ Problems solved cannot be greater than problems attempted." if engagement_score < 0 or engagement_score > 1: return "โŒ Engagement score must be between 0 and 1." # Calculate performance score if not provided if performance_score is None or performance_score <= 0: success_rate = problems_solved / problems_attempted time_efficiency = min(1.0, problems_solved / max(1, time_spent/10)) # Normalize time efficiency performance_score = round((success_rate * 0.7 + time_efficiency * 0.3) * 4, 2) # Create student data dictionary student_data = { 'student_id': student_id, 'learning_style': learning_style, 'subject': subject, 'difficulty': difficulty, 'time_spent': time_spent, 'problems_attempted': problems_attempted, 'problems_solved': problems_solved, 'engagement_score': engagement_score, 'session_type': session_type, 'performance_score': performance_score } try: # Generate recommendation recommendation = generate_recommendation(student_data) # Add some formatting and stats success_rate = (problems_solved / problems_attempted) * 100 efficiency = problems_solved / max(1, time_spent/10) result = f"""### ๐ŸŽฏ Personalized Learning Recommendation **Session Summary:** - Success Rate: {success_rate:.1f}% - Time Efficiency: {efficiency:.1f} problems/10min - Performance Score: {performance_score:.1f}/4.0 **Recommendations:** {recommendation} --- *Generated using AI-enhanced educational analytics*""" return result except Exception as e: return f"โŒ An error occurred while generating the recommendation: {str(e)}\n\nPlease try again or check your inputs." def create_demo(): """Create the Gradio demo interface""" with gr.Blocks(title="Personalized Learning Recommendation System", theme=gr.themes.Soft()) as demo: gr.Markdown( """ # ๐ŸŽ“ Personalized Learning Recommendation System This system provides intelligent, personalized learning recommendations based on student performance data. Uses both AI models (when available) and expert rule-based systems for reliable recommendations. Fill in the student's information below to get a personalized recommendation. """ ) with gr.Row(): with gr.Column(scale=1): gr.Markdown("### ๐Ÿ“ Student Information") student_id = gr.Textbox( label="Student ID", placeholder="e.g., student_123", value="student_123" ) learning_style = gr.Dropdown( label="Learning Style", choices=["visual", "auditory", "kinesthetic", "reading/writing"], value="visual" ) subject = gr.Dropdown( label="Subject", choices=["math", "science", "language", "coding", "history"], value="math" ) difficulty = gr.Slider( minimum=1, maximum=5, step=1, label="Difficulty Level", value=3 ) time_spent = gr.Number( label="Time Spent (minutes)", value=25, minimum=1, maximum=120 ) problems_attempted = gr.Number( label="Problems Attempted", value=10, minimum=1, maximum=50 ) problems_solved = gr.Number( label="Problems Solved", value=3, minimum=0 ) engagement_score = gr.Slider( minimum=0, maximum=1, step=0.05, label="Engagement Score", value=0.4 ) session_type = gr.Dropdown( label="Session Type", choices=["video", "quiz", "reading", "interactive"], value="quiz" ) performance_score = gr.Number( label="Performance Score (optional)", value=None, minimum=0, maximum=4, info="If not provided, will be calculated automatically" ) submit_btn = gr.Button("Generate Recommendation ๐Ÿš€", variant="primary") with gr.Column(scale=1): gr.Markdown("### ๐Ÿ’ก Recommendation") output = gr.Markdown(label="Recommendation") # Examples for quick testing gr.Examples( examples=[ ["student_123", "visual", "math", 4, 25, 10, 3, 0.4, "quiz", None], ["student_456", "auditory", "science", 3, 30, 15, 12, 0.8, "video", None], ["student_789", "kinesthetic", "coding", 5, 45, 8, 2, 0.3, "interactive", None], ["student_101", "reading/writing", "language", 2, 20, 12, 10, 0.9, "reading", None] ], inputs=[student_id, learning_style, subject, difficulty, time_spent, problems_attempted, problems_solved, engagement_score, session_type, performance_score] ) # Event handling submit_btn.click( fn=process_student_input, inputs=[student_id, learning_style, subject, difficulty, time_spent, problems_attempted, problems_solved, engagement_score, session_type, performance_score], outputs=output ) gr.Markdown( """ --- **How it works**: This system combines AI models with expert educational rules to provide personalized recommendations. The system analyzes: - **Performance patterns** (success rate, time efficiency) - **Learning style preferences** (visual, auditory, kinesthetic, reading/writing) - **Engagement levels** and session types - **Subject-specific strategies** for optimal learning paths Recommendations adapt to individual learning needs and provide actionable guidance. """ ) return demo # Create and launch the demo demo = create_demo() # Launch the app if __name__ == "__main__": demo.launch()