Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,8 +3,8 @@ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
|
|
| 3 |
from peft import PeftModel
|
| 4 |
import torch
|
| 5 |
import os
|
| 6 |
-
import
|
| 7 |
-
|
| 8 |
|
| 9 |
# ---------------- QUESTION GEN ----------------
|
| 10 |
BASE_MODEL = "Qwen/Qwen2.5-Math-1.5B-Instruct"
|
|
@@ -17,23 +17,21 @@ tokenizer = AutoTokenizer.from_pretrained(
|
|
| 17 |
BASE_MODEL,
|
| 18 |
trust_remote_code=True,
|
| 19 |
device_map="auto",
|
| 20 |
-
|
| 21 |
)
|
| 22 |
|
| 23 |
if tokenizer.pad_token is None:
|
| 24 |
tokenizer.pad_token = tokenizer.eos_token
|
| 25 |
|
| 26 |
# ---------------- LOAD MODEL ----------------
|
| 27 |
-
loaded_bnb
|
| 28 |
loaded_base = AutoModelForCausalLM.from_pretrained(BASE_MODEL, quantization_config=loaded_bnb, device_map='auto')
|
| 29 |
model = PeftModel.from_pretrained(loaded_base, ADAPTER_ID_QUESTION)
|
| 30 |
model.eval()
|
| 31 |
|
| 32 |
|
| 33 |
-
# ---------------- INFERENCE ----------------
|
| 34 |
@torch.no_grad()
|
| 35 |
-
def infer_question_gen(topic, difficulty,grade):
|
| 36 |
-
|
| 37 |
prompt = (
|
| 38 |
"### INSTRUCTION\n"
|
| 39 |
"Generate ONE UNIQUE math MCQ.\n"
|
|
@@ -69,232 +67,278 @@ def infer_question_gen(topic, difficulty,grade):
|
|
| 69 |
return json_text
|
| 70 |
|
| 71 |
|
|
|
|
|
|
|
|
|
|
| 72 |
|
|
|
|
|
|
|
| 73 |
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
f"Grade: {sample['grade']}\n"
|
| 79 |
-
f"Topic: {sample['topic']}\n"
|
| 80 |
-
f"Question: {sample['question']}\n"
|
| 81 |
-
f"Student Answer: {sample['student_answer']}\n\n"
|
| 82 |
-
"Score the answer from 0.0 (completely wrong) to 1.0 (perfectly correct).\n"
|
| 83 |
-
"Return JSON with matching_score and improvements:\n"
|
| 84 |
-
)
|
| 85 |
-
else:
|
| 86 |
-
time_lines = "\n".join(
|
| 87 |
-
f"[{k.upper()}_TIME={v}]" for k, v in sample["time_spent"].items()
|
| 88 |
-
)
|
| 89 |
-
return (
|
| 90 |
-
f"### TASK: IDENTIFY WEAK TEACHING SECTIONS\n"
|
| 91 |
-
f"Grade: {sample['grade']}\n"
|
| 92 |
-
f"Teacher Guide: {sample['teacher_guide']}\n\n"
|
| 93 |
-
f"Student Feedback: {sample['student_feedback']}\n\n"
|
| 94 |
-
f"Time Spent Per Section:\n{time_lines}\n\n"
|
| 95 |
-
f"Based on student feedback, identify which sections were weak.\n"
|
| 96 |
-
f"Return JSON with weak_sections (list) and reason (string):\n"
|
| 97 |
-
)
|
| 98 |
-
|
| 99 |
-
|
| 100 |
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
BCE_THRESHOLD = 0.5
|
| 106 |
-
LM_WEIGHT = 1.0
|
| 107 |
-
SECTION_WEIGHT = 30.0 # upweight classification head
|
| 108 |
-
NUM_SECTIONS = 8
|
| 109 |
-
SECTION_INDEX = {
|
| 110 |
-
"introduction": 0, "concept_explanation": 1,
|
| 111 |
-
"worked_examples": 2, "practice_questions": 3,
|
| 112 |
-
"word_problems": 4, "pacing": 5,
|
| 113 |
-
"clarity": 6, "engagement": 7
|
| 114 |
-
}
|
| 115 |
-
IDX_TO_SECTION = {v:k for k,v in SECTION_INDEX.items()}
|
| 116 |
-
|
| 117 |
-
ADAPTER_ID_TEACHER = "Chamith2000/teachers_guide_and_matching_score"
|
| 118 |
-
NUM_SECTIONS = 8
|
| 119 |
-
|
| 120 |
-
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 121 |
-
|
| 122 |
-
class TeachingAnalyserModel(nn.Module):
|
| 123 |
-
def __init__(self, base_model):
|
| 124 |
-
super().__init__()
|
| 125 |
-
self.base = base_model
|
| 126 |
-
hidden = base_model.config.hidden_size
|
| 127 |
-
self.section_head = nn.Sequential(
|
| 128 |
-
nn.Linear(hidden, hidden // 2),
|
| 129 |
-
nn.ReLU(),
|
| 130 |
-
nn.Dropout(0.1),
|
| 131 |
-
nn.Linear(hidden // 2, NUM_SECTIONS)
|
| 132 |
-
)
|
| 133 |
-
|
| 134 |
-
def forward(self, input_ids, attention_mask, labels=None, section_labels=None):
|
| 135 |
-
out = self.base(
|
| 136 |
-
input_ids=input_ids, attention_mask=attention_mask,
|
| 137 |
-
labels=labels, output_hidden_states=True
|
| 138 |
-
)
|
| 139 |
-
seq_len = attention_mask.sum(dim=1) - 1
|
| 140 |
-
hidden_states = out.hidden_states[-1][
|
| 141 |
-
torch.arange(input_ids.size(0)), seq_len
|
| 142 |
-
].to(torch.bfloat16)
|
| 143 |
-
|
| 144 |
-
section_logits = self.section_head(hidden_states)
|
| 145 |
-
|
| 146 |
-
loss = None
|
| 147 |
-
if labels is not None and out.loss is not None:
|
| 148 |
-
pos_weight = torch.tensor(
|
| 149 |
-
[12.0, 4.8, 6.2, 5.3, 4.3, 3.4, 3.6, 4.1],
|
| 150 |
-
device=DEVICE, dtype=torch.float32
|
| 151 |
-
)
|
| 152 |
-
lm_loss = LM_WEIGHT * out.loss.to(torch.bfloat16)
|
| 153 |
-
section_loss = SECTION_WEIGHT * nn.functional.binary_cross_entropy_with_logits(
|
| 154 |
-
section_logits,
|
| 155 |
-
section_labels.to(torch.bfloat16),
|
| 156 |
-
pos_weight=pos_weight
|
| 157 |
-
) if section_labels is not None else 0.0
|
| 158 |
-
loss = lm_loss + section_loss
|
| 159 |
-
|
| 160 |
-
return {'loss': loss, 'section_logits': section_logits}
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
section_head_path = hf_hub_download(
|
| 164 |
-
repo_id=ADAPTER_ID_TEACHER,
|
| 165 |
-
filename="section_head.pt"
|
| 166 |
)
|
| 167 |
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
loaded_model_teacher = TeachingAnalyserModel(loaded_peft_teacher).to(DEVICE)
|
| 172 |
-
loaded_model_teacher.section_head = loaded_model_teacher.section_head.to(torch.bfloat16)
|
| 173 |
-
ckpt = torch.load(section_head_path, map_location=DEVICE)
|
| 174 |
-
loaded_model_teacher.section_head.load_state_dict(ckpt['section_head'])
|
| 175 |
-
loaded_model_teacher.eval()
|
| 176 |
-
print('Model teacher loaded.')
|
| 177 |
-
|
| 178 |
|
| 179 |
-
|
| 180 |
-
def infer_teacher_guide(sample):
|
| 181 |
-
prompt = build_prompt(sample)
|
| 182 |
-
ids = loaded_tok_teacher(prompt, return_tensors="pt").to(DEVICE)
|
| 183 |
-
|
| 184 |
-
gen = loaded_peft_teacher.generate(
|
| 185 |
-
**ids,
|
| 186 |
-
max_new_tokens=120,
|
| 187 |
-
do_sample=False, # CRITICAL
|
| 188 |
-
eos_token_id=loaded_tok_teacher.eos_token_id,
|
| 189 |
-
pad_token_id=loaded_tok_teacher.eos_token_id
|
| 190 |
-
)
|
| 191 |
|
| 192 |
-
generated = loaded_tok_teacher.decode(
|
| 193 |
-
gen[0][ids['input_ids'].shape[1]:],
|
| 194 |
-
skip_special_tokens=True
|
| 195 |
-
)
|
| 196 |
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
]
|
| 206 |
|
| 207 |
-
|
| 208 |
-
|
| 209 |
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
'section_probs': breakdown,
|
| 213 |
-
'generated_reason': generated.strip()
|
| 214 |
-
}
|
| 215 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
|
| 217 |
-
|
| 218 |
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
|
| 223 |
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
#
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
|
| 242 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 243 |
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
lm_loss = LM_WEIGHT * out.loss.to(torch.bfloat16)
|
| 247 |
-
score_loss = SCORE_WEIGHT * nn.functional.mse_loss(
|
| 248 |
-
score_pred, score.to(torch.bfloat16)
|
| 249 |
-
) if score is not None else 0.0
|
| 250 |
-
loss = lm_loss + score_loss
|
| 251 |
|
| 252 |
-
|
|
|
|
|
|
|
|
|
|
| 253 |
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
|
|
|
| 257 |
)
|
| 258 |
|
|
|
|
|
|
|
|
|
|
| 259 |
|
| 260 |
-
|
| 261 |
-
loaded_tok_analyze = AutoTokenizer.from_pretrained(BASE_MODEL_CLASSIC)
|
| 262 |
-
loaded_tok_analyze.pad_token = loaded_tok_analyze.eos_token
|
| 263 |
-
loaded_peft_analyze = PeftModel.from_pretrained(loaded_base_analyze, ADAPTER_ID_ANALYSE)
|
| 264 |
-
loaded_model_analyze = AnswerEvaluatorModel(loaded_peft_analyze).to(DEVICE)
|
| 265 |
-
loaded_model_analyze.score_head = loaded_model_analyze.score_head.to(torch.bfloat16)
|
| 266 |
-
ckpt = torch.load(score_head_path, map_location=DEVICE)
|
| 267 |
-
loaded_model_analyze.score_head.load_state_dict(ckpt['score_head'])
|
| 268 |
-
loaded_model_analyze.eval()
|
| 269 |
-
print('Model analyze loaded.')
|
| 270 |
|
| 271 |
-
print(score_head_path)
|
| 272 |
|
| 273 |
@torch.no_grad()
|
| 274 |
-
def evaluate_answer(
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
return {
|
| 291 |
'matching_score': round(score, 3),
|
| 292 |
-
'score_label':
|
| 293 |
-
'improvements':
|
| 294 |
}
|
| 295 |
|
| 296 |
|
| 297 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
app = Flask(__name__)
|
| 299 |
|
| 300 |
@app.route("/generate", methods=["POST"])
|
|
@@ -302,8 +346,9 @@ def generate():
|
|
| 302 |
data = request.get_json()
|
| 303 |
|
| 304 |
calling_type = data.get('model_type')
|
|
|
|
| 305 |
if calling_type == 'teacher':
|
| 306 |
-
|
| 307 |
|
| 308 |
elif calling_type == 'question':
|
| 309 |
return question_gen(data)
|
|
@@ -312,9 +357,10 @@ def generate():
|
|
| 312 |
return analyze_gen(data.get('teacher_data'))
|
| 313 |
|
| 314 |
return jsonify({"error": "Invalid model type use 'teacher' or 'question' as the model type"}), 400
|
| 315 |
-
|
| 316 |
|
| 317 |
def question_gen(data):
|
|
|
|
| 318 |
if not data:
|
| 319 |
return jsonify({"error": "Invalid JSON body"}), 400
|
| 320 |
|
|
@@ -325,27 +371,37 @@ def question_gen(data):
|
|
| 325 |
if not topic or not difficulty or not grade:
|
| 326 |
return jsonify({"error": "Missing 'topic' or 'difficulty' or 'grade'"}), 400
|
| 327 |
|
| 328 |
-
result = infer_question_gen(topic, difficulty,grade)
|
| 329 |
return jsonify({"output": result})
|
| 330 |
|
| 331 |
|
| 332 |
def analyze_gen(data):
|
|
|
|
| 333 |
if not data:
|
| 334 |
return jsonify({"error": "Invalid JSON body"}), 400
|
| 335 |
|
| 336 |
result = evaluate_answer(data)
|
| 337 |
-
|
| 338 |
return jsonify({"output": result})
|
| 339 |
|
| 340 |
|
| 341 |
def teacher_guide(data):
|
|
|
|
| 342 |
if not data:
|
| 343 |
return jsonify({"error": "Missing 'prompt'"}), 400
|
| 344 |
|
| 345 |
prompt = infer_teacher_guide(data)
|
| 346 |
-
|
| 347 |
return jsonify({"output": prompt})
|
| 348 |
|
| 349 |
|
| 350 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 351 |
app.run(host="0.0.0.0", port=7860)
|
|
|
|
| 3 |
from peft import PeftModel
|
| 4 |
import torch
|
| 5 |
import os
|
| 6 |
+
import json
|
| 7 |
+
import re
|
| 8 |
|
| 9 |
# ---------------- QUESTION GEN ----------------
|
| 10 |
BASE_MODEL = "Qwen/Qwen2.5-Math-1.5B-Instruct"
|
|
|
|
| 17 |
BASE_MODEL,
|
| 18 |
trust_remote_code=True,
|
| 19 |
device_map="auto",
|
|
|
|
| 20 |
)
|
| 21 |
|
| 22 |
if tokenizer.pad_token is None:
|
| 23 |
tokenizer.pad_token = tokenizer.eos_token
|
| 24 |
|
| 25 |
# ---------------- LOAD MODEL ----------------
|
| 26 |
+
loaded_bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16)
|
| 27 |
loaded_base = AutoModelForCausalLM.from_pretrained(BASE_MODEL, quantization_config=loaded_bnb, device_map='auto')
|
| 28 |
model = PeftModel.from_pretrained(loaded_base, ADAPTER_ID_QUESTION)
|
| 29 |
model.eval()
|
| 30 |
|
| 31 |
|
| 32 |
+
# ---------------- INFERENCE (UNCHANGED) ----------------
|
| 33 |
@torch.no_grad()
|
| 34 |
+
def infer_question_gen(topic, difficulty, grade):
|
|
|
|
| 35 |
prompt = (
|
| 36 |
"### INSTRUCTION\n"
|
| 37 |
"Generate ONE UNIQUE math MCQ.\n"
|
|
|
|
| 67 |
return json_text
|
| 68 |
|
| 69 |
|
| 70 |
+
# ===============================================================================
|
| 71 |
+
# TEACHER FEEDBACK MODEL
|
| 72 |
+
# ===============================================================================
|
| 73 |
|
| 74 |
+
TEACHER_MODEL_PATH = "Qwen/Qwen2.5-3B-Instruct"
|
| 75 |
+
TEACHER_ADAPTER_PATH = "Chamith2000/teachers_guide_and_matching_score"
|
| 76 |
|
| 77 |
+
print("Loading teacher feedback model...")
|
| 78 |
+
teacher_tokenizer = AutoTokenizer.from_pretrained(TEACHER_MODEL_PATH)
|
| 79 |
+
if teacher_tokenizer.pad_token is None:
|
| 80 |
+
teacher_tokenizer.pad_token = teacher_tokenizer.eos_token
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
+
teacher_base = AutoModelForCausalLM.from_pretrained(
|
| 83 |
+
TEACHER_MODEL_PATH,
|
| 84 |
+
quantization_config=loaded_bnb,
|
| 85 |
+
device_map='auto'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
)
|
| 87 |
|
| 88 |
+
# Load your trained LoRA weights
|
| 89 |
+
teacher_model = PeftModel.from_pretrained(teacher_base, TEACHER_ADAPTER_PATH)
|
| 90 |
+
teacher_model.eval()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
+
print("✅ Teacher feedback model loaded!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
+
@torch.no_grad()
|
| 96 |
+
def infer_teacher_guide(data):
|
| 97 |
+
"""Analyze teaching effectiveness using YOUR trained model"""
|
| 98 |
+
|
| 99 |
+
# Extract data
|
| 100 |
+
teacher_guide = data.get('teacher_guide', '')
|
| 101 |
+
student_feedback = data.get('student_feedback', '')
|
| 102 |
+
engagement_time = data.get('student_engagement_time', 0)
|
| 103 |
+
allocated_time = data.get('guide_allocated_time', 0)
|
| 104 |
+
grade = data.get('grade', 4)
|
| 105 |
+
|
| 106 |
+
# Calculate time difference
|
| 107 |
+
time_diff = allocated_time - engagement_time
|
| 108 |
+
|
| 109 |
+
if time_diff > 10:
|
| 110 |
+
time_analysis = f"Student finished {time_diff} minutes early (engaged {engagement_time} min vs {allocated_time} min allocated). This suggests possible disengagement, rushing, or giving up."
|
| 111 |
+
elif time_diff < -10:
|
| 112 |
+
time_analysis = f"Student took {abs(time_diff)} minutes longer than allocated (engaged {engagement_time} min vs {allocated_time} min allocated). This suggests slow pacing or difficulty understanding."
|
| 113 |
+
else:
|
| 114 |
+
time_analysis = f"Student completed in appropriate time (engaged {engagement_time} min, allocated {allocated_time} min)."
|
| 115 |
+
|
| 116 |
+
# Build prompt (same format as training)
|
| 117 |
+
prompt = f"""Analyze teaching effectiveness. Return ONLY JSON.
|
| 118 |
|
| 119 |
+
LESSON INFO:
|
| 120 |
+
Grade Level: {grade}
|
| 121 |
+
Teacher Guide: {teacher_guide}
|
|
|
|
| 122 |
|
| 123 |
+
STUDENT FEEDBACK:
|
| 124 |
+
"{student_feedback}"
|
| 125 |
|
| 126 |
+
TIME ANALYSIS:
|
| 127 |
+
{time_analysis}
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
+
Analyze and return JSON:
|
| 130 |
+
{{
|
| 131 |
+
"weak_sections": ["section1", "section2", ...],
|
| 132 |
+
"reason": "<detailed analysis>"
|
| 133 |
+
}}
|
| 134 |
|
| 135 |
+
OUTPUT:"""
|
| 136 |
|
| 137 |
+
# Tokenize
|
| 138 |
+
inputs = teacher_tokenizer(prompt, return_tensors="pt").to(DEVICE)
|
| 139 |
+
|
| 140 |
+
# Generate
|
| 141 |
+
outputs = teacher_model.generate(
|
| 142 |
+
**inputs,
|
| 143 |
+
max_new_tokens=200,
|
| 144 |
+
temperature=0.05, # Low for consistent JSON
|
| 145 |
+
top_p=0.9,
|
| 146 |
+
do_sample=True,
|
| 147 |
+
repetition_penalty=1.15,
|
| 148 |
+
pad_token_id=teacher_tokenizer.pad_token_id,
|
| 149 |
+
eos_token_id=teacher_tokenizer.eos_token_id,
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
generated = teacher_tokenizer.decode(
|
| 153 |
+
outputs[0][inputs['input_ids'].shape[1]:],
|
| 154 |
+
skip_special_tokens=True
|
| 155 |
+
).strip()
|
| 156 |
+
|
| 157 |
+
# Parse JSON with multiple strategies
|
| 158 |
+
result = parse_json_output(generated)
|
| 159 |
+
|
| 160 |
+
return result
|
| 161 |
|
| 162 |
|
| 163 |
+
def parse_json_output(text):
|
| 164 |
+
"""Robust JSON parsing with fallbacks"""
|
| 165 |
+
|
| 166 |
+
# Strategy 1: Direct JSON parse
|
| 167 |
+
try:
|
| 168 |
+
start = text.find('{')
|
| 169 |
+
end = text.rfind('}') + 1
|
| 170 |
+
if start != -1 and end > start:
|
| 171 |
+
json_str = text[start:end]
|
| 172 |
+
return json.loads(json_str)
|
| 173 |
+
except:
|
| 174 |
+
pass
|
| 175 |
|
| 176 |
+
# Strategy 2: Regex extraction
|
| 177 |
+
try:
|
| 178 |
+
weak_sections = []
|
| 179 |
+
reason = ""
|
| 180 |
+
|
| 181 |
+
# Extract weak_sections array
|
| 182 |
+
sections_match = re.search(r'"weak_sections"\s*:\s*\[(.*?)\]', text, re.DOTALL)
|
| 183 |
+
if sections_match:
|
| 184 |
+
sections_str = sections_match.group(1)
|
| 185 |
+
# Extract quoted strings
|
| 186 |
+
weak_sections = re.findall(r'"([^"]+)"', sections_str)
|
| 187 |
+
|
| 188 |
+
# Extract reason
|
| 189 |
+
reason_match = re.search(r'"reason"\s*:\s*"([^"]*)"', text, re.DOTALL)
|
| 190 |
+
if reason_match:
|
| 191 |
+
reason = reason_match.group(1)
|
| 192 |
+
|
| 193 |
+
if weak_sections or reason:
|
| 194 |
+
return {
|
| 195 |
+
'weak_sections': weak_sections,
|
| 196 |
+
'reason': reason
|
| 197 |
+
}
|
| 198 |
+
except:
|
| 199 |
+
pass
|
| 200 |
|
| 201 |
+
# Fallback
|
| 202 |
+
return {
|
| 203 |
+
'weak_sections': [],
|
| 204 |
+
'reason': 'Failed to parse model output',
|
| 205 |
+
'raw_output': text[:500]
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
# ===============================================================================
|
| 210 |
+
# ANSWER EVALUATION MODEL -
|
| 211 |
+
# ===============================================================================
|
| 212 |
|
| 213 |
+
ANSWER_MODEL_PATH = "Qwen/Qwen2.5-1.5B-Instruct"
|
| 214 |
+
ANSWER_ADAPTER_PATH = "Chamith2000/answer_evaluate"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
|
| 216 |
+
print("Loading answer evaluation model...")
|
| 217 |
+
answer_tokenizer = AutoTokenizer.from_pretrained(ANSWER_MODEL_PATH)
|
| 218 |
+
if answer_tokenizer.pad_token is None:
|
| 219 |
+
answer_tokenizer.pad_token = answer_tokenizer.eos_token
|
| 220 |
|
| 221 |
+
answer_base = AutoModelForCausalLM.from_pretrained(
|
| 222 |
+
ANSWER_MODEL_PATH,
|
| 223 |
+
quantization_config=loaded_bnb,
|
| 224 |
+
device_map='auto'
|
| 225 |
)
|
| 226 |
|
| 227 |
+
# Load your trained LoRA weights
|
| 228 |
+
answer_model = PeftModel.from_pretrained(answer_base, ANSWER_ADAPTER_PATH)l
|
| 229 |
+
answer_model.eval()
|
| 230 |
|
| 231 |
+
print("✅ Answer evaluation model loaded!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
|
|
|
|
| 233 |
|
| 234 |
@torch.no_grad()
|
| 235 |
+
def evaluate_answer(data):
|
| 236 |
+
"""Evaluate student answer using YOUR trained model"""
|
| 237 |
+
|
| 238 |
+
# Extract data
|
| 239 |
+
grade = data.get('grade', 4)
|
| 240 |
+
topic = data.get('topic', '')
|
| 241 |
+
question = data.get('question', '')
|
| 242 |
+
student_answer = data.get('student_answer', '')
|
| 243 |
+
|
| 244 |
+
# Build prompt (same format as training)
|
| 245 |
+
prompt = f"""Grade the student's answer. Return ONLY JSON.
|
| 246 |
+
|
| 247 |
+
Format: {{"score": <number>, "reason": "<text>"}}
|
| 248 |
+
Score must be: 0.0, 0.25, 0.5, 0.75, or 1.0
|
| 249 |
|
| 250 |
+
Question: {question}
|
| 251 |
+
Student Answer: {student_answer}
|
| 252 |
+
Grade Level: {grade}
|
| 253 |
+
Topic: {topic}
|
| 254 |
|
| 255 |
+
Grading:"""
|
| 256 |
+
|
| 257 |
+
# Tokenize
|
| 258 |
+
inputs = answer_tokenizer(prompt, return_tensors="pt").to(DEVICE)
|
| 259 |
+
|
| 260 |
+
# Generate
|
| 261 |
+
outputs = answer_model.generate(
|
| 262 |
+
**inputs,
|
| 263 |
+
max_new_tokens=150,
|
| 264 |
+
temperature=0.01, # Very low for consistent JSON
|
| 265 |
+
top_p=0.9,
|
| 266 |
+
do_sample=True,
|
| 267 |
+
repetition_penalty=1.15,
|
| 268 |
+
pad_token_id=answer_tokenizer.pad_token_id,
|
| 269 |
+
eos_token_id=answer_tokenizer.eos_token_id,
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
generated = answer_tokenizer.decode(
|
| 273 |
+
outputs[0][inputs['input_ids'].shape[1]:],
|
| 274 |
+
skip_special_tokens=True
|
| 275 |
+
).strip()
|
| 276 |
+
|
| 277 |
+
# Parse JSON
|
| 278 |
+
result = parse_answer_json(generated)
|
| 279 |
+
|
| 280 |
+
# Convert to your API format
|
| 281 |
+
score = result.get('score', 0.0)
|
| 282 |
return {
|
| 283 |
'matching_score': round(score, 3),
|
| 284 |
+
'score_label': 'High' if score >= 0.7 else ('Mid' if score >= 0.4 else 'Low'),
|
| 285 |
+
'improvements': result.get('reason', 'No feedback available')
|
| 286 |
}
|
| 287 |
|
| 288 |
|
| 289 |
+
def parse_answer_json(text):
|
| 290 |
+
"""Parse answer evaluation JSON"""
|
| 291 |
+
|
| 292 |
+
# Strategy 1: Direct JSON parse
|
| 293 |
+
try:
|
| 294 |
+
start = text.find('{')
|
| 295 |
+
end = text.rfind('}') + 1
|
| 296 |
+
if start != -1 and end > start:
|
| 297 |
+
json_str = text[start:end]
|
| 298 |
+
parsed = json.loads(json_str)
|
| 299 |
+
# Ensure score is valid
|
| 300 |
+
if 'score' in parsed:
|
| 301 |
+
parsed['score'] = max(0.0, min(1.0, float(parsed['score'])))
|
| 302 |
+
return parsed
|
| 303 |
+
except:
|
| 304 |
+
pass
|
| 305 |
+
|
| 306 |
+
# Strategy 2: Regex extraction
|
| 307 |
+
try:
|
| 308 |
+
score_match = re.search(r'"score"\s*:\s*([\d.]+)', text)
|
| 309 |
+
reason_match = re.search(r'"reason"\s*:\s*"([^"]+)"', text)
|
| 310 |
+
|
| 311 |
+
if score_match:
|
| 312 |
+
score = max(0.0, min(1.0, float(score_match.group(1))))
|
| 313 |
+
reason = reason_match.group(1) if reason_match else "No reason provided"
|
| 314 |
+
return {'score': score, 'reason': reason}
|
| 315 |
+
except:
|
| 316 |
+
pass
|
| 317 |
+
|
| 318 |
+
# Strategy 3: Find valid score
|
| 319 |
+
try:
|
| 320 |
+
valid_scores = ['1.0', '0.75', '0.5', '0.25', '0.0']
|
| 321 |
+
for score_str in valid_scores:
|
| 322 |
+
if score_str in text:
|
| 323 |
+
return {
|
| 324 |
+
'score': float(score_str),
|
| 325 |
+
'reason': text.replace(score_str, '').strip()[:200]
|
| 326 |
+
}
|
| 327 |
+
except:
|
| 328 |
+
pass
|
| 329 |
+
|
| 330 |
+
# Fallback
|
| 331 |
+
return {
|
| 332 |
+
'score': 0.0,
|
| 333 |
+
'reason': 'Failed to parse model output',
|
| 334 |
+
'raw_output': text[:200]
|
| 335 |
+
}
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
# ===============================================================================
|
| 339 |
+
# FLASK APP
|
| 340 |
+
# ===============================================================================
|
| 341 |
+
|
| 342 |
app = Flask(__name__)
|
| 343 |
|
| 344 |
@app.route("/generate", methods=["POST"])
|
|
|
|
| 346 |
data = request.get_json()
|
| 347 |
|
| 348 |
calling_type = data.get('model_type')
|
| 349 |
+
|
| 350 |
if calling_type == 'teacher':
|
| 351 |
+
return teacher_guide(data.get('teacher_data'))
|
| 352 |
|
| 353 |
elif calling_type == 'question':
|
| 354 |
return question_gen(data)
|
|
|
|
| 357 |
return analyze_gen(data.get('teacher_data'))
|
| 358 |
|
| 359 |
return jsonify({"error": "Invalid model type use 'teacher' or 'question' as the model type"}), 400
|
| 360 |
+
|
| 361 |
|
| 362 |
def question_gen(data):
|
| 363 |
+
"""Generate math question (UNCHANGED)"""
|
| 364 |
if not data:
|
| 365 |
return jsonify({"error": "Invalid JSON body"}), 400
|
| 366 |
|
|
|
|
| 371 |
if not topic or not difficulty or not grade:
|
| 372 |
return jsonify({"error": "Missing 'topic' or 'difficulty' or 'grade'"}), 400
|
| 373 |
|
| 374 |
+
result = infer_question_gen(topic, difficulty, grade)
|
| 375 |
return jsonify({"output": result})
|
| 376 |
|
| 377 |
|
| 378 |
def analyze_gen(data):
|
| 379 |
+
"""Analyze student answer (UPDATED)"""
|
| 380 |
if not data:
|
| 381 |
return jsonify({"error": "Invalid JSON body"}), 400
|
| 382 |
|
| 383 |
result = evaluate_answer(data)
|
|
|
|
| 384 |
return jsonify({"output": result})
|
| 385 |
|
| 386 |
|
| 387 |
def teacher_guide(data):
|
| 388 |
+
"""Analyze teacher feedback (UPDATED)"""
|
| 389 |
if not data:
|
| 390 |
return jsonify({"error": "Missing 'prompt'"}), 400
|
| 391 |
|
| 392 |
prompt = infer_teacher_guide(data)
|
|
|
|
| 393 |
return jsonify({"output": prompt})
|
| 394 |
|
| 395 |
|
| 396 |
if __name__ == "__main__":
|
| 397 |
+
print("\n" + "="*70)
|
| 398 |
+
print("SERVER READY!")
|
| 399 |
+
print("="*70)
|
| 400 |
+
print("\nEndpoints:")
|
| 401 |
+
print(" POST /generate")
|
| 402 |
+
print(" - model_type: 'question' (math question generation)")
|
| 403 |
+
print(" - model_type: 'analyze' (answer evaluation)")
|
| 404 |
+
print(" - model_type: 'teacher' (teaching feedback)")
|
| 405 |
+
print("="*70 + "\n")
|
| 406 |
+
|
| 407 |
app.run(host="0.0.0.0", port=7860)
|