dgith commited on
Commit
c2645e1
Β·
verified Β·
1 Parent(s): edbed2f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +290 -0
app.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import pandas as pd
4
+ import numpy as np
5
+ import json
6
+ import time
7
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
8
+ from peft import PeftModel, PeftConfig
9
+ import warnings
10
+ warnings.filterwarnings("ignore")
11
+
12
+ # Global variables for the model and tokenizer
13
+ model = None
14
+ tokenizer = None
15
+
16
+ def load_model():
17
+ """Load the trained model and tokenizer"""
18
+ global model, tokenizer
19
+
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,
115
+ session_type, performance_score):
116
+ """
117
+ Process the input from the Gradio interface and generate a recommendation
118
+ """
119
+ # Validate inputs
120
+ if not student_id or not subject or problems_attempted <= 0:
121
+ return "❌ Please fill in all required fields. Problems attempted must be greater than 0."
122
+
123
+ if problems_solved > problems_attempted:
124
+ return "❌ Problems solved cannot be greater than problems attempted."
125
+
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 = {
137
+ 'student_id': student_id,
138
+ 'learning_style': learning_style,
139
+ 'subject': subject,
140
+ 'difficulty': difficulty,
141
+ 'time_spent': time_spent,
142
+ 'problems_attempted': problems_attempted,
143
+ 'problems_solved': problems_solved,
144
+ 'engagement_score': engagement_score,
145
+ 'session_type': session_type,
146
+ 'performance_score': performance_score
147
+ }
148
+
149
+ try:
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
+
158
+ except Exception as e:
159
+ return f"❌ An error occurred while generating the recommendation: {str(e)}\n\nPlease try again or check your inputs."
160
+
161
+ def create_demo():
162
+ """Create the Gradio demo interface"""
163
+
164
+ with gr.Blocks(title="Personalized Learning Recommendation System", theme=gr.themes.Soft()) as demo:
165
+ gr.Markdown(
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
+ """
174
+ )
175
+
176
+ with gr.Row():
177
+ with gr.Column(scale=1):
178
+ gr.Markdown("### πŸ“ Student Information")
179
+
180
+ student_id = gr.Textbox(
181
+ label="Student ID",
182
+ placeholder="e.g., student_123",
183
+ value="student_123"
184
+ )
185
+
186
+ learning_style = gr.Dropdown(
187
+ label="Learning Style",
188
+ choices=["visual", "auditory", "kinesthetic", "reading/writing"],
189
+ value="visual"
190
+ )
191
+
192
+ subject = gr.Dropdown(
193
+ label="Subject",
194
+ choices=["math", "science", "language", "coding", "history"],
195
+ value="math"
196
+ )
197
+
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(
205
+ label="Time Spent (minutes)",
206
+ value=25,
207
+ minimum=1,
208
+ maximum=120
209
+ )
210
+
211
+ problems_attempted = gr.Number(
212
+ label="Problems Attempted",
213
+ value=10,
214
+ minimum=1,
215
+ maximum=50
216
+ )
217
+
218
+ problems_solved = gr.Number(
219
+ label="Problems Solved",
220
+ value=3,
221
+ minimum=0
222
+ )
223
+
224
+ engagement_score = gr.Slider(
225
+ minimum=0, maximum=1, step=0.05,
226
+ label="Engagement Score",
227
+ value=0.4
228
+ )
229
+
230
+ session_type = gr.Dropdown(
231
+ label="Session Type",
232
+ choices=["video", "quiz", "reading", "interactive"],
233
+ value="quiz"
234
+ )
235
+
236
+ performance_score = gr.Number(
237
+ label="Performance Score (optional)",
238
+ value=None,
239
+ minimum=0,
240
+ maximum=4,
241
+ info="If not provided, will be calculated automatically"
242
+ )
243
+
244
+ submit_btn = gr.Button("Generate Recommendation πŸš€", variant="primary")
245
+
246
+ with gr.Column(scale=1):
247
+ gr.Markdown("### πŸ’‘ Recommendation")
248
+ output = gr.Markdown(label="Recommendation")
249
+
250
+ # Examples for quick testing
251
+ gr.Examples(
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]
259
+ )
260
+
261
+ # Event handling
262
+ submit_btn.click(
263
+ fn=process_student_input,
264
+ inputs=[student_id, learning_style, subject, difficulty, time_spent,
265
+ problems_attempted, problems_solved, engagement_score, session_type, performance_score],
266
+ outputs=output
267
+ )
268
+
269
+ gr.Markdown(
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
+
283
+ return demo
284
+
285
+ # Create and launch the demo
286
+ demo = create_demo()
287
+
288
+ # Launch the app
289
+ if __name__ == "__main__":
290
+ demo.launch()