dgith commited on
Commit
41dee66
ยท
verified ยท
1 Parent(s): 3cddcd9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +186 -90
app.py CHANGED
@@ -20,95 +20,174 @@ def load_model():
20
  if model is None:
21
  print("๐Ÿš€ Loading the personalized learning recommendation model...")
22
 
23
- # Use your accessible Gemma model
24
- model_name = "google/gemma-7b-it"
25
 
26
- # Set up quantization configuration
27
- bnb_config = BitsAndBytesConfig(
28
- load_in_4bit=True,
29
- bnb_4bit_quant_type="nf4",
30
- bnb_4bit_compute_dtype=torch.bfloat16,
31
- bnb_4bit_use_double_quant=True,
32
- )
33
-
34
- # Load tokenizer
35
- tokenizer = AutoTokenizer.from_pretrained(model_name)
36
- tokenizer.pad_token = tokenizer.eos_token
37
- tokenizer.padding_side = "left"
38
-
39
- # Load base model with quantization
40
- base_model = AutoModelForCausalLM.from_pretrained(
41
- model_name,
42
- quantization_config=bnb_config,
43
- device_map="auto"
44
- )
45
-
46
- # Load the fine-tuned adapter
47
- # Replace with your actual model path on Hugging Face
48
- adapter_path = "your-username/learning-recommender-rubric" # CHANGE THIS TO YOUR MODEL
49
-
50
- model = PeftModel.from_pretrained(base_model, adapter_path)
51
- model.eval()
52
-
53
- print("โœ… Model loaded successfully!")
54
 
55
  return model, tokenizer
56
 
57
- def generate_recommendation(student_data):
58
  """
59
- Generate a personalized learning recommendation based on student data
 
 
 
 
 
 
 
 
 
 
 
60
 
61
- Args:
62
- student_data (dict): Dictionary containing student information
63
 
64
- Returns:
65
- str: Personalized recommendation
66
- """
67
- # Load model if not already loaded
68
- model, tokenizer = load_model()
69
 
70
- # Create input prompt
71
- input_text = f"""Student ID: {student_data['student_id']}
72
- Learning Style: {student_data['learning_style']}
73
- Current Session:
74
- - Subject: {student_data['subject']}
75
- - Difficulty: {student_data['difficulty']}/5
76
- - Time Spent: {student_data['time_spent']} minutes
77
- - Problems Attempted: {student_data['problems_attempted']}
78
- - Problems Solved: {student_data['problems_solved']}
79
- - Engagement: {student_data['engagement_score']:.2f}
80
- - Session Type: {student_data['session_type']}
81
- - Performance Score: {student_data['performance_score']:.2f}"""
82
 
83
- # Tokenize input
84
- inputs = tokenizer(input_text, return_tensors="pt", max_length=512, truncation=True)
85
- inputs = {k: v.to(model.device) for k, v in inputs.items()}
86
 
87
- # Generate recommendation
88
- with torch.no_grad():
89
- outputs = model.generate(
90
- **inputs,
91
- max_new_tokens=200,
92
- temperature=0.7,
93
- top_p=0.9,
94
- do_sample=True,
95
- pad_token_id=tokenizer.eos_token_id
96
- )
97
 
98
- # Decode and return the recommendation
99
- full_response = tokenizer.decode(outputs[0], skip_special_tokens=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
- # Extract only the recommendation part (after the input text)
102
- recommendation = full_response[len(input_text):].strip()
 
103
 
104
- # Clean up the recommendation (remove any repeated text)
105
- lines = recommendation.split('\n')
106
- unique_lines = []
107
- for line in lines:
108
- if line.strip() and line not in unique_lines:
109
- unique_lines.append(line)
 
 
 
 
 
 
 
110
 
111
- return '\n'.join(unique_lines)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
  def process_student_input(student_id, learning_style, subject, difficulty, time_spent,
114
  problems_attempted, problems_solved, engagement_score,
@@ -126,11 +205,11 @@ def process_student_input(student_id, learning_style, subject, difficulty, time_
126
  if engagement_score < 0 or engagement_score > 1:
127
  return "โŒ Engagement score must be between 0 and 1."
128
 
129
- # Calculate success rate for performance score if not provided
130
  if performance_score is None or performance_score <= 0:
131
  success_rate = problems_solved / problems_attempted
132
- time_efficiency = problems_solved / max(1, time_spent)
133
- performance_score = round((success_rate * 0.6 + time_efficiency * 0.4) * 4, 2)
134
 
135
  # Create student data dictionary
136
  student_data = {
@@ -150,8 +229,23 @@ def process_student_input(student_id, learning_style, subject, difficulty, time_
150
  # Generate recommendation
151
  recommendation = generate_recommendation(student_data)
152
 
153
- # Add some formatting
154
- result = f"### ๐ŸŽฏ Personalized Learning Recommendation\n\n{recommendation}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
 
156
  return result
157
 
@@ -166,8 +260,8 @@ def create_demo():
166
  """
167
  # ๐ŸŽ“ Personalized Learning Recommendation System
168
 
169
- This system uses advanced AI to provide personalized learning recommendations based on student data.
170
- The model was trained using a semi-supervised approach with Reinforcement Learning and Rubric Anchors (RLRA).
171
 
172
  Fill in the student's information below to get a personalized recommendation.
173
  """
@@ -198,7 +292,7 @@ def create_demo():
198
  difficulty = gr.Slider(
199
  minimum=1, maximum=5, step=1,
200
  label="Difficulty Level",
201
- value=4
202
  )
203
 
204
  time_spent = gr.Number(
@@ -252,7 +346,8 @@ def create_demo():
252
  examples=[
253
  ["student_123", "visual", "math", 4, 25, 10, 3, 0.4, "quiz", None],
254
  ["student_456", "auditory", "science", 3, 30, 15, 12, 0.8, "video", None],
255
- ["student_789", "kinesthetic", "coding", 5, 45, 8, 2, 0.3, "interactive", None]
 
256
  ],
257
  inputs=[student_id, learning_style, subject, difficulty, time_spent,
258
  problems_attempted, problems_solved, engagement_score, session_type, performance_score]
@@ -270,13 +365,14 @@ def create_demo():
270
  """
271
  ---
272
  **How it works**:
273
- This system uses a fine-tuned Google Gemma-7b model trained with a semi-supervised approach.
274
- The model was trained using:
275
- - **Automatic pseudo-labeling** with educational rubrics
276
- - **Two-phase learning** to build constraint-handling foundation
277
- - **Reinforcement Learning with Rubric Anchors (RLRA)** for quality control
 
278
 
279
- The recommendations are generated based on patterns learned from thousands of simulated student sessions.
280
  """
281
  )
282
 
 
20
  if model is None:
21
  print("๐Ÿš€ Loading the personalized learning recommendation model...")
22
 
23
+ # Use a smaller, non-gated model that works better in Spaces
24
+ model_name = "microsoft/DialoGPT-medium" # Alternative: "distilgpt2", "gpt2"
25
 
26
+ try:
27
+ # Load tokenizer
28
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
29
+ tokenizer.pad_token = tokenizer.eos_token
30
+ tokenizer.padding_side = "left"
31
+
32
+ # Load base model (no quantization for smaller models)
33
+ model = AutoModelForCausalLM.from_pretrained(
34
+ model_name,
35
+ device_map="auto" if torch.cuda.is_available() else "cpu",
36
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
37
+ )
38
+
39
+ # Note: If you have a trained adapter, uncomment and modify this:
40
+ # adapter_path = "your-username/learning-recommender-rubric" # UPDATE THIS
41
+ # model = PeftModel.from_pretrained(model, adapter_path)
42
+
43
+ model.eval()
44
+ print("โœ… Model loaded successfully!")
45
+
46
+ except Exception as e:
47
+ print(f"โŒ Error loading model: {e}")
48
+ # Fallback to rule-based system
49
+ model = None
50
+ tokenizer = None
 
 
 
51
 
52
  return model, tokenizer
53
 
54
+ def generate_rule_based_recommendation(student_data):
55
  """
56
+ Fallback rule-based recommendation system
57
+ """
58
+ student_id = student_data['student_id']
59
+ learning_style = student_data['learning_style']
60
+ subject = student_data['subject']
61
+ difficulty = student_data['difficulty']
62
+ time_spent = student_data['time_spent']
63
+ problems_attempted = student_data['problems_attempted']
64
+ problems_solved = student_data['problems_solved']
65
+ engagement_score = student_data['engagement_score']
66
+ session_type = student_data['session_type']
67
+ performance_score = student_data['performance_score']
68
 
69
+ success_rate = problems_solved / problems_attempted
 
70
 
71
+ recommendations = []
 
 
 
 
72
 
73
+ # Performance-based recommendations
74
+ if success_rate < 0.3:
75
+ recommendations.append("๐Ÿ“š **Focus on Fundamentals**: Your current success rate suggests reviewing basic concepts would be beneficial.")
76
+ recommendations.append(f"๐Ÿ”„ **Adjust Difficulty**: Consider reducing difficulty from level {difficulty} to level {max(1, difficulty-1)} temporarily.")
77
+ if learning_style == "visual":
78
+ recommendations.append("๐ŸŽจ **Visual Aids**: Use diagrams, charts, and visual representations to understand core concepts.")
79
+ elif learning_style == "auditory":
80
+ recommendations.append("๐ŸŽง **Audio Learning**: Try educational podcasts or recorded lectures for this topic.")
 
 
 
 
81
 
82
+ elif success_rate < 0.6:
83
+ recommendations.append("โšก **Practice More**: You're on the right track! Additional practice problems will help solidify your understanding.")
84
+ recommendations.append("๐ŸŽฏ **Targeted Review**: Focus on the types of problems you're missing most often.")
85
 
86
+ else:
87
+ recommendations.append("๐Ÿš€ **Challenge Yourself**: Great job! Consider increasing difficulty or exploring advanced topics.")
88
+ recommendations.append(f"๐Ÿ“ˆ **Next Level**: Try moving to difficulty level {min(5, difficulty+1)} in your next session.")
89
+
90
+ # Engagement-based recommendations
91
+ if engagement_score < 0.4:
92
+ recommendations.append("๐ŸŽฎ **Interactive Content**: Try more interactive sessions to boost engagement.")
93
+ if session_type != "interactive":
94
+ recommendations.append("๐Ÿ”„ **Change Format**: Consider switching to interactive exercises or gamified content.")
 
95
 
96
+ elif engagement_score < 0.7:
97
+ recommendations.append("โญ **Mix It Up**: Vary your session types to maintain interest.")
98
+
99
+ # Time-based recommendations
100
+ if time_spent > 40:
101
+ recommendations.append("โฑ๏ธ **Take Breaks**: Long sessions detected. Try shorter, more focused 20-30 minute sessions.")
102
+ elif time_spent < 15:
103
+ recommendations.append("๐Ÿ“… **Extend Sessions**: Consider slightly longer sessions for better concept retention.")
104
+
105
+ # Learning style specific recommendations
106
+ if learning_style == "kinesthetic":
107
+ recommendations.append("๐Ÿคน **Hands-on Practice**: Incorporate physical activities or manipulatives when possible.")
108
+ elif learning_style == "reading/writing":
109
+ recommendations.append("๐Ÿ“ **Note-taking**: Make detailed notes and try explaining concepts in writing.")
110
+
111
+ # Subject-specific recommendations
112
+ if subject == "math":
113
+ recommendations.append("๐Ÿงฎ **Step-by-step**: Break down complex problems into smaller, manageable steps.")
114
+ elif subject == "science":
115
+ recommendations.append("๐Ÿ”ฌ **Real-world Connections**: Connect concepts to everyday phenomena and experiments.")
116
+ elif subject == "coding":
117
+ recommendations.append("๐Ÿ’ป **Code Practice**: Build small projects to apply what you're learning.")
118
+
119
+ return "\n\n".join(recommendations)
120
+
121
+ def generate_recommendation(student_data):
122
+ """
123
+ Generate a personalized learning recommendation based on student data
124
+ """
125
+ # Try to load model
126
+ model, tokenizer = load_model()
127
 
128
+ # If model loading failed, use rule-based system
129
+ if model is None or tokenizer is None:
130
+ return generate_rule_based_recommendation(student_data)
131
 
132
+ # Create input prompt for AI model
133
+ input_text = f"""Generate a personalized learning recommendation for this student:
134
+
135
+ Student Profile:
136
+ - ID: {student_data['student_id']}
137
+ - Learning Style: {student_data['learning_style']}
138
+ - Subject: {student_data['subject']}
139
+ - Current Performance: {student_data['problems_solved']}/{student_data['problems_attempted']} problems solved
140
+ - Engagement Level: {student_data['engagement_score']:.1f}/1.0
141
+ - Time Management: {student_data['time_spent']} minutes spent
142
+ - Difficulty Level: {student_data['difficulty']}/5
143
+
144
+ Recommendation:"""
145
 
146
+ try:
147
+ # Tokenize input
148
+ inputs = tokenizer(input_text, return_tensors="pt", max_length=256, truncation=True)
149
+
150
+ # Move to appropriate device
151
+ if torch.cuda.is_available():
152
+ inputs = {k: v.to(model.device) for k, v in inputs.items()}
153
+
154
+ # Generate recommendation
155
+ with torch.no_grad():
156
+ outputs = model.generate(
157
+ **inputs,
158
+ max_new_tokens=150,
159
+ temperature=0.8,
160
+ top_p=0.9,
161
+ do_sample=True,
162
+ pad_token_id=tokenizer.eos_token_id,
163
+ repetition_penalty=1.1
164
+ )
165
+
166
+ # Decode and return the recommendation
167
+ full_response = tokenizer.decode(outputs[0], skip_special_tokens=True)
168
+
169
+ # Extract only the recommendation part
170
+ recommendation = full_response[len(input_text):].strip()
171
+
172
+ # Clean up the recommendation
173
+ lines = recommendation.split('\n')
174
+ unique_lines = []
175
+ for line in lines:
176
+ if line.strip() and line not in unique_lines and len(line) > 10:
177
+ unique_lines.append(line.strip())
178
+
179
+ result = '\n\n'.join(unique_lines)
180
+
181
+ # If AI generation is too short, fall back to rule-based
182
+ if len(result) < 50:
183
+ return generate_rule_based_recommendation(student_data)
184
+
185
+ return result
186
+
187
+ except Exception as e:
188
+ print(f"AI generation failed: {e}")
189
+ # Fallback to rule-based system
190
+ return generate_rule_based_recommendation(student_data)
191
 
192
  def process_student_input(student_id, learning_style, subject, difficulty, time_spent,
193
  problems_attempted, problems_solved, engagement_score,
 
205
  if engagement_score < 0 or engagement_score > 1:
206
  return "โŒ Engagement score must be between 0 and 1."
207
 
208
+ # Calculate performance score if not provided
209
  if performance_score is None or performance_score <= 0:
210
  success_rate = problems_solved / problems_attempted
211
+ time_efficiency = min(1.0, problems_solved / max(1, time_spent/10)) # Normalize time efficiency
212
+ performance_score = round((success_rate * 0.7 + time_efficiency * 0.3) * 4, 2)
213
 
214
  # Create student data dictionary
215
  student_data = {
 
229
  # Generate recommendation
230
  recommendation = generate_recommendation(student_data)
231
 
232
+ # Add some formatting and stats
233
+ success_rate = (problems_solved / problems_attempted) * 100
234
+ efficiency = problems_solved / max(1, time_spent/10)
235
+
236
+ result = f"""### ๐ŸŽฏ Personalized Learning Recommendation
237
+
238
+ **Session Summary:**
239
+ - Success Rate: {success_rate:.1f}%
240
+ - Time Efficiency: {efficiency:.1f} problems/10min
241
+ - Performance Score: {performance_score:.1f}/4.0
242
+
243
+ **Recommendations:**
244
+
245
+ {recommendation}
246
+
247
+ ---
248
+ *Generated using AI-enhanced educational analytics*"""
249
 
250
  return result
251
 
 
260
  """
261
  # ๐ŸŽ“ Personalized Learning Recommendation System
262
 
263
+ This system provides intelligent, personalized learning recommendations based on student performance data.
264
+ Uses both AI models (when available) and expert rule-based systems for reliable recommendations.
265
 
266
  Fill in the student's information below to get a personalized recommendation.
267
  """
 
292
  difficulty = gr.Slider(
293
  minimum=1, maximum=5, step=1,
294
  label="Difficulty Level",
295
+ value=3
296
  )
297
 
298
  time_spent = gr.Number(
 
346
  examples=[
347
  ["student_123", "visual", "math", 4, 25, 10, 3, 0.4, "quiz", None],
348
  ["student_456", "auditory", "science", 3, 30, 15, 12, 0.8, "video", None],
349
+ ["student_789", "kinesthetic", "coding", 5, 45, 8, 2, 0.3, "interactive", None],
350
+ ["student_101", "reading/writing", "language", 2, 20, 12, 10, 0.9, "reading", None]
351
  ],
352
  inputs=[student_id, learning_style, subject, difficulty, time_spent,
353
  problems_attempted, problems_solved, engagement_score, session_type, performance_score]
 
365
  """
366
  ---
367
  **How it works**:
368
+ This system combines AI models with expert educational rules to provide personalized recommendations.
369
+ The system analyzes:
370
+ - **Performance patterns** (success rate, time efficiency)
371
+ - **Learning style preferences** (visual, auditory, kinesthetic, reading/writing)
372
+ - **Engagement levels** and session types
373
+ - **Subject-specific strategies** for optimal learning paths
374
 
375
+ Recommendations adapt to individual learning needs and provide actionable guidance.
376
  """
377
  )
378