File size: 8,780 Bytes
bcbb772 1a3111b 32abcbb 1a3111b 32abcbb e45239e 32abcbb 1a3111b 32abcbb 1a3111b ec0ecd4 32abcbb ec0ecd4 32abcbb ec0ecd4 32abcbb ec0ecd4 1a3111b ec0ecd4 32abcbb ec0ecd4 32abcbb ec0ecd4 1a3111b ec0ecd4 32abcbb ec0ecd4 32abcbb ec0ecd4 1a3111b ec0ecd4 1a3111b ec0ecd4 1a3111b ec0ecd4 32abcbb ec0ecd4 1a3111b ec0ecd4 32abcbb bcbb772 ec0ecd4 32abcbb ec0ecd4 bcbb772 32abcbb 1a3111b ec0ecd4 1a3111b ec0ecd4 1a3111b bcbb772 1a3111b ec0ecd4 32abcbb ec0ecd4 1a3111b ec0ecd4 bcbb772 ec0ecd4 32abcbb ec0ecd4 1a3111b 32abcbb 1a3111b 32abcbb 1a3111b bcbb772 ec0ecd4 1a3111b 32abcbb bcbb772 1a3111b bcbb772 32abcbb bcbb772 32abcbb bcbb772 1a3111b bcbb772 1a3111b 32abcbb 1a3111b bcbb772 1a3111b 32abcbb 1a3111b bcbb772 1a3111b ec0ecd4 1a3111b ec0ecd4 1a3111b 32abcbb 1a3111b 32abcbb 1a3111b bcbb772 32abcbb 1a3111b bcbb772 1a3111b bcbb772 1a3111b 32abcbb 1a3111b 32abcbb 1a3111b 32abcbb 7aedb7c 32abcbb 1a3111b 32abcbb 1a3111b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 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 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 | import spaces
import torch
import gradio as gr
from transformers import AutoTokenizer, AutoModelForCausalLM
# ============================================================
# Model
# ============================================================
MODEL_NAME = "ma4389/LFM2-DPO"
# ============================================================
# System Prompt
# ============================================================
SYSTEM_PROMPT = """
You are an expert educational AI assistant.
Your task is to generate high-quality educational questions ONLY from the paragraph provided by the user.
Rules:
- Use ONLY the provided paragraph.
- Never use outside knowledge.
- Never hallucinate.
- Never invent facts.
- If the paragraph does not contain enough information, generate only the questions that are supported.
- Follow the user's requested format exactly.
- Do not include explanations unless explicitly requested.
- Return only the generated questions.
"""
# ============================================================
# Prompts
# ============================================================
PROMPTS = {
"MCQ": """
Paragraph:
{context}
Generate EXACTLY {num} multiple-choice questions if the paragraph contains enough information.
Strict Rules:
- Use ONLY the provided paragraph.
- Never use outside knowledge.
- Never hallucinate.
- Never invent facts.
- Never invent examples.
- Every question must assess a DIFFERENT concept.
- Never repeat questions.
- Do not copy entire sentences from the paragraph.
- Questions should test understanding.
- Generate EXACTLY four options.
- There must be EXACTLY one correct answer.
- Distractors must be realistic.
- Vary the correct answer naturally between A, B, C and D.
- Do NOT explain the answers.
- Do NOT stop after generating one question.
Output Format:
1. Question?
A) ...
B) ...
C) ...
D) ...
Answer: B
2. Question?
A) ...
B) ...
C) ...
D) ...
Answer: D
3. Question?
A) ...
B) ...
C) ...
D) ...
Answer: A
...
Continue until EXACTLY {num} questions have been generated.
You have NOT finished until EXACTLY {num} questions are written.
Return ONLY the questions.
""",
"True / False": """
Paragraph:
{context}
Generate EXACTLY {num} True/False questions if the paragraph contains enough information.
Strict Rules:
- Use ONLY the provided paragraph.
- Never use outside knowledge.
- Never hallucinate.
- Never invent facts.
- Every statement must assess a DIFFERENT concept.
- Never repeat ideas.
- Mix True and False naturally.
- False statements should modify ONLY one important fact.
- Avoid obviously false statements.
- End every statement with (T/F).
- Do NOT explain the answers.
- Do NOT stop after generating one question.
Output Format:
1. Statement. (T/F)
Answer: True
2. Statement. (T/F)
Answer: False
3. Statement. (T/F)
Answer: True
...
Continue until EXACTLY {num} questions have been generated.
You have NOT finished until EXACTLY {num} questions are written.
Return ONLY the questions.
""",
"Essay": """
Paragraph:
{context}
Generate EXACTLY {num} essay questions if the paragraph contains enough information.
Strict Rules:
- Use ONLY the provided paragraph.
- Never use outside knowledge.
- Never hallucinate.
- Never invent facts.
- Every question must assess a DIFFERENT concept.
- Never repeat questions.
- Answers must contain ONLY information from the paragraph.
- Never invent information.
- Each answer should contain 3β6 complete sentences.
- Keep answers concise and educational.
- Do NOT stop after generating one question.
Output Format:
1. Question?
Answer:
...
2. Question?
Answer:
...
3. Question?
Answer:
...
Continue until EXACTLY {num} questions have been generated.
You have NOT finished until EXACTLY {num} questions are written.
Return ONLY the questions.
"""
}
# ============================================================
# Lazy Loading
# ============================================================
model = None
tokenizer = None
def load_model():
global model, tokenizer
if model is None:
print("Loading model...")
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForCausalLM.from_pretrained(
MODEL_NAME,
torch_dtype=torch.float16,
device_map="auto",
)
model.eval()
# ============================================================
# Generation
# ============================================================
@spaces.GPU
def ask(prompt):
load_model()
messages = [
{
"role": "system",
"content": SYSTEM_PROMPT,
},
{
"role": "user",
"content": prompt,
},
]
inputs = tokenizer.apply_chat_template(
messages,
tokenize=True,
add_generation_prompt=True,
return_dict=True,
return_tensors="pt",
)
inputs = {
k: v.to(model.device)
for k, v in inputs.items()
}
with torch.no_grad():
outputs = model.generate(
**inputs,
max_new_tokens=1200,
temperature=0.6,
top_p=0.95,
top_k=50,
do_sample=True,
repetition_penalty=1.15,
no_repeat_ngram_size=4,
pad_token_id=tokenizer.eos_token_id,
eos_token_id=tokenizer.eos_token_id,
)
response = tokenizer.decode(
outputs[0][inputs["input_ids"].shape[-1]:],
skip_special_tokens=True,
)
return response.strip()
# ============================================================
# Main Function
# ============================================================
def generate(paragraph, qtype, num):
paragraph = paragraph.strip()
if not paragraph:
return "Please enter a paragraph."
prompt = PROMPTS[qtype].format(
context=paragraph,
num=num,
)
return ask(prompt)
# ============================================================
# Gradio Interface
# ============================================================
with gr.Blocks(
title="π AI Question Generator",
theme=gr.themes.Soft(),
) as demo:
gr.Markdown(
"""
# π AI Question Generator
Generate **Multiple Choice**, **True/False**, and **Essay** questions from any paragraph using a fine-tuned **LFM2-DPO** language model.
### Features
- β
Multiple Choice Questions
- β
True / False Questions
- β
Essay Questions
- β
Grounded only in the provided paragraph
- β
Covers different concepts with minimal repetition
"""
)
with gr.Row():
with gr.Column(scale=1):
paragraph = gr.Textbox(
label="Paragraph",
lines=16,
placeholder="Paste your paragraph here...",
)
question_type = gr.Radio(
choices=[
"MCQ",
"True / False",
"Essay",
],
value="MCQ",
label="Question Type",
)
number = gr.Slider(
minimum=1,
maximum=10,
value=5,
step=1,
label="Number of Questions",
)
generate_btn = gr.Button(
"Generate Questions",
variant="primary",
)
clear_btn = gr.Button("Clear")
with gr.Column(scale=1):
output = gr.Textbox(
label="Generated Questions",
lines=28
)
generate_btn.click(
fn=generate,
inputs=[
paragraph,
question_type,
number,
],
outputs=output,
)
clear_btn.click(
lambda: ("", "MCQ", 5, ""),
outputs=[
paragraph,
question_type,
number,
output,
],
)
gr.Markdown(
"""
---
### Notes
- The model uses **only the supplied paragraph**.
- It does **not** use external knowledge.
- Each generated question is designed to assess a different concept whenever possible.
"""
)
# ============================================================
# Launch
# ============================================================
if __name__ == "__main__":
demo.queue(max_size=20)
demo.launch() |