ma4389 commited on
Commit
bcbb772
·
verified ·
1 Parent(s): dd1a186

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -44
app.py CHANGED
@@ -1,32 +1,21 @@
 
1
  import torch
2
  import gradio as gr
3
  from transformers import AutoTokenizer, AutoModelForCausalLM
4
 
5
  MODEL_NAME = "ma4389/LFM2-DPO"
6
 
7
- print("Loading model...")
8
-
9
- tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
10
-
11
- model = AutoModelForCausalLM.from_pretrained(
12
- MODEL_NAME,
13
- torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
14
- device_map="auto" if torch.cuda.is_available() else None,
15
- )
16
-
17
- model.eval()
18
-
19
  SYSTEM_PROMPT = """
20
  You are an expert educational question generation assistant.
21
 
22
- Generate high-quality questions ONLY from the provided paragraph.
23
 
24
  Rules:
25
- - Use only the given paragraph.
26
- - Do not hallucinate.
27
- - Do not use outside knowledge.
28
- - Cover different concepts.
29
- - Return only the requested format.
30
  """
31
 
32
  PROMPTS = {
@@ -36,10 +25,18 @@ Paragraph:
36
 
37
  Generate exactly {num} multiple-choice questions.
38
 
39
- Requirements:
40
- - Four choices (A, B, C, D)
41
- - One correct answer
42
- - No explanations
 
 
 
 
 
 
 
 
43
 
44
  Format:
45
 
@@ -50,7 +47,7 @@ B) ...
50
  C) ...
51
  D) ...
52
 
53
- Answer: A
54
  """,
55
 
56
  "True / False": """
@@ -59,6 +56,12 @@ Paragraph:
59
 
60
  Generate exactly {num} True/False questions.
61
 
 
 
 
 
 
 
62
  Format:
63
 
64
  1. Statement
@@ -66,26 +69,55 @@ Format:
66
  Answer: True
67
  """,
68
 
69
- "WH Questions": """
70
  Paragraph:
71
  {context}
72
 
73
- Generate exactly {num} short-answer questions.
74
 
75
- Requirements:
76
- - Begin with Who, What, When, Where, Why, or How whenever appropriate.
77
- - Each question must have its answer.
 
 
 
78
 
79
  Format:
80
 
81
  1. Question
82
 
83
- Answer: ...
 
84
  """
85
  }
86
 
 
 
 
 
 
 
 
 
 
 
87
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  def ask(prompt):
 
 
 
89
  messages = [
90
  {"role": "system", "content": SYSTEM_PROMPT},
91
  {"role": "user", "content": prompt},
@@ -95,21 +127,23 @@ def ask(prompt):
95
  messages,
96
  tokenize=True,
97
  add_generation_prompt=True,
98
- return_tensors="pt",
99
  return_dict=True,
 
100
  )
101
 
102
  inputs = {k: v.to(model.device) for k, v in inputs.items()}
103
 
104
  with torch.no_grad():
 
105
  outputs = model.generate(
106
  **inputs,
107
- max_new_tokens=512,
108
- temperature=0.3,
109
  top_p=0.9,
 
110
  do_sample=True,
111
- repetition_penalty=1.15,
112
- no_repeat_ngram_size=3,
113
  pad_token_id=tokenizer.eos_token_id,
114
  eos_token_id=tokenizer.eos_token_id,
115
  )
@@ -120,45 +154,46 @@ def ask(prompt):
120
  )
121
 
122
 
123
- def generate_questions(paragraph, question_type, num_questions):
 
124
  if not paragraph.strip():
125
  return "Please enter a paragraph."
126
 
127
- prompt = PROMPTS[question_type].format(
128
  context=paragraph,
129
- num=num_questions,
130
  )
131
 
132
  return ask(prompt)
133
 
134
 
135
  demo = gr.Interface(
136
- fn=generate_questions,
137
  inputs=[
138
  gr.Textbox(
139
- lines=12,
140
  label="Paragraph",
 
141
  placeholder="Paste any paragraph here..."
142
  ),
143
  gr.Radio(
144
- ["MCQ", "True / False", "WH Questions"],
145
  value="MCQ",
146
- label="Question Type",
147
  ),
148
  gr.Slider(
149
  minimum=1,
150
  maximum=10,
151
  value=5,
152
  step=1,
153
- label="Number of Questions",
154
  ),
155
  ],
156
  outputs=gr.Textbox(
157
- lines=20,
158
  label="Generated Questions",
 
159
  ),
160
  title="📚 AI Question Generator",
161
- description="Generate MCQ, True/False, or WH questions from any paragraph using a fine-tuned LFM2-DPO model.",
162
  )
163
 
164
  if __name__ == "__main__":
 
1
+ import spaces
2
  import torch
3
  import gradio as gr
4
  from transformers import AutoTokenizer, AutoModelForCausalLM
5
 
6
  MODEL_NAME = "ma4389/LFM2-DPO"
7
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  SYSTEM_PROMPT = """
9
  You are an expert educational question generation assistant.
10
 
11
+ Generate questions ONLY from the supplied paragraph.
12
 
13
  Rules:
14
+ - Use ONLY the provided paragraph.
15
+ - Never hallucinate.
16
+ - Never repeat questions.
17
+ - Each question must test a different concept.
18
+ - Return ONLY the requested format.
19
  """
20
 
21
  PROMPTS = {
 
25
 
26
  Generate exactly {num} multiple-choice questions.
27
 
28
+ Rules:
29
+ - Use ONLY the paragraph.
30
+ - Every question must test a different concept.
31
+ - Never repeat questions.
32
+ - Each question must have exactly four choices:
33
+ A)
34
+ B)
35
+ C)
36
+ D)
37
+ - The correct answer should vary naturally between A, B, C and D.
38
+ - Wrong choices should be realistic.
39
+ - Do not explain the answer.
40
 
41
  Format:
42
 
 
47
  C) ...
48
  D) ...
49
 
50
+ Answer: C
51
  """,
52
 
53
  "True / False": """
 
56
 
57
  Generate exactly {num} True/False questions.
58
 
59
+ Rules:
60
+ - Use ONLY the paragraph.
61
+ - Never repeat questions.
62
+ - Mix True and False naturally.
63
+ - Do not explain.
64
+
65
  Format:
66
 
67
  1. Statement
 
69
  Answer: True
70
  """,
71
 
72
+ "Essay": """
73
  Paragraph:
74
  {context}
75
 
76
+ Generate exactly {num} essay questions.
77
 
78
+ Rules:
79
+ - Use ONLY the paragraph.
80
+ - Every question should test a different concept.
81
+ - Never repeat questions.
82
+ - Each answer should contain 3-8 complete sentences.
83
+ - Do not invent information.
84
 
85
  Format:
86
 
87
  1. Question
88
 
89
+ Answer:
90
+ Detailed answer...
91
  """
92
  }
93
 
94
+ # Lazy loading
95
+ model = None
96
+ tokenizer = None
97
+
98
+
99
+ def load_model():
100
+ global model, tokenizer
101
+
102
+ if model is None:
103
+ print("Loading model...")
104
 
105
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
106
+
107
+ model = AutoModelForCausalLM.from_pretrained(
108
+ MODEL_NAME,
109
+ dtype=torch.float16,
110
+ device_map="auto",
111
+ )
112
+
113
+ model.eval()
114
+
115
+
116
+ @spaces.GPU
117
  def ask(prompt):
118
+
119
+ load_model()
120
+
121
  messages = [
122
  {"role": "system", "content": SYSTEM_PROMPT},
123
  {"role": "user", "content": prompt},
 
127
  messages,
128
  tokenize=True,
129
  add_generation_prompt=True,
 
130
  return_dict=True,
131
+ return_tensors="pt",
132
  )
133
 
134
  inputs = {k: v.to(model.device) for k, v in inputs.items()}
135
 
136
  with torch.no_grad():
137
+
138
  outputs = model.generate(
139
  **inputs,
140
+ max_new_tokens=700,
141
+ temperature=0.4,
142
  top_p=0.9,
143
+ top_k=50,
144
  do_sample=True,
145
+ repetition_penalty=1.3,
146
+ no_repeat_ngram_size=5,
147
  pad_token_id=tokenizer.eos_token_id,
148
  eos_token_id=tokenizer.eos_token_id,
149
  )
 
154
  )
155
 
156
 
157
+ def generate(paragraph, qtype, num):
158
+
159
  if not paragraph.strip():
160
  return "Please enter a paragraph."
161
 
162
+ prompt = PROMPTS[qtype].format(
163
  context=paragraph,
164
+ num=num,
165
  )
166
 
167
  return ask(prompt)
168
 
169
 
170
  demo = gr.Interface(
171
+ fn=generate,
172
  inputs=[
173
  gr.Textbox(
 
174
  label="Paragraph",
175
+ lines=15,
176
  placeholder="Paste any paragraph here..."
177
  ),
178
  gr.Radio(
179
+ ["MCQ", "True / False", "Essay"],
180
  value="MCQ",
181
+ label="Question Type"
182
  ),
183
  gr.Slider(
184
  minimum=1,
185
  maximum=10,
186
  value=5,
187
  step=1,
188
+ label="Number of Questions"
189
  ),
190
  ],
191
  outputs=gr.Textbox(
 
192
  label="Generated Questions",
193
+ lines=25,
194
  ),
195
  title="📚 AI Question Generator",
196
+ description="Generate MCQ, True/False and Essay questions from any paragraph using a fine-tuned LFM2-DPO model.",
197
  )
198
 
199
  if __name__ == "__main__":