olumideola commited on
Commit
6e8f34a
·
verified ·
1 Parent(s): ecd7fc5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -14
app.py CHANGED
@@ -70,40 +70,78 @@ def generate(passage: str, language_code: str, n: int):
70
 
71
  model, tok = _load()
72
  lang_name = LANG_NAMES.get(language_code, language_code)
 
73
  slots = ", ".join(['"..."'] * int(n))
74
- user = TEACHER_TEMPLATE.format(n=int(n), language=lang_name, slots=slots, passage=passage)
 
 
 
 
 
 
75
  messages = [
76
  {"role": "system", "content": TEACHER_SYSTEM},
77
  {"role": "user", "content": user},
78
  ]
79
- input_ids = tok.apply_chat_template(
80
- messages, tokenize=True, add_generation_prompt=True, return_tensors="pt"
81
- ).to(model.device)
 
 
 
 
 
 
 
 
82
 
83
  with torch.no_grad():
84
  out = model.generate(
85
- input_ids, max_new_tokens=250, do_sample=False,
86
- pad_token_id=tok.pad_token_id or tok.eos_token_id,
 
 
 
 
87
  )
88
- text = tok.decode(out[0][input_ids.shape[1]:], skip_special_tokens=True)
 
 
 
 
 
 
89
 
90
  try:
91
- obj = json.loads(text[text.index("{"): text.rindex("}") + 1])
92
- questions = [q for q in obj.get("questions", []) if isinstance(q, str) and q.strip()]
 
 
 
 
 
 
93
  except (ValueError, json.JSONDecodeError):
94
  questions = []
95
 
96
  note = ""
97
  if language_code in WEAK_LANGS:
98
- note = (f"\n\n⚠️ {lang_name} is one of this model's lower-confidence languages "
99
- f"(see the [model card](https://huggingface.co/{MODEL_ID}) for benchmark numbers).")
 
 
100
 
101
  if not questions:
102
- return text, f"⚠️ Couldn't parse valid questions from the model's output. Raw output shown alongside.{note}"
 
 
 
103
 
104
- formatted = "\n".join(f"{i+1}. {q}" for i, q in enumerate(questions))
105
- return formatted, (" Generated." + note) if note else "✅ Generated."
 
106
 
 
107
 
108
  with gr.Blocks(title="mist-qg-1.5b — multilingual question generator") as demo:
109
  gr.Markdown(
 
70
 
71
  model, tok = _load()
72
  lang_name = LANG_NAMES.get(language_code, language_code)
73
+
74
  slots = ", ".join(['"..."'] * int(n))
75
+ user = TEACHER_TEMPLATE.format(
76
+ n=int(n),
77
+ language=lang_name,
78
+ slots=slots,
79
+ passage=passage,
80
+ )
81
+
82
  messages = [
83
  {"role": "system", "content": TEACHER_SYSTEM},
84
  {"role": "user", "content": user},
85
  ]
86
+
87
+ # Build model inputs
88
+ inputs = tok.apply_chat_template(
89
+ messages,
90
+ tokenize=True,
91
+ add_generation_prompt=True,
92
+ return_tensors="pt",
93
+ return_dict=True,
94
+ )
95
+
96
+ inputs = {k: v.to(model.device) for k, v in inputs.items()}
97
 
98
  with torch.no_grad():
99
  out = model.generate(
100
+ **inputs,
101
+ max_new_tokens=250,
102
+ do_sample=False,
103
+ pad_token_id=tok.pad_token_id
104
+ if tok.pad_token_id is not None
105
+ else tok.eos_token_id,
106
  )
107
+
108
+ prompt_len = inputs["input_ids"].shape[1]
109
+
110
+ text = tok.decode(
111
+ out[0][prompt_len:],
112
+ skip_special_tokens=True,
113
+ )
114
 
115
  try:
116
+ start = text.index("{")
117
+ end = text.rindex("}") + 1
118
+ obj = json.loads(text[start:end])
119
+ questions = [
120
+ q
121
+ for q in obj.get("questions", [])
122
+ if isinstance(q, str) and q.strip()
123
+ ]
124
  except (ValueError, json.JSONDecodeError):
125
  questions = []
126
 
127
  note = ""
128
  if language_code in WEAK_LANGS:
129
+ note = (
130
+ f"\n\n⚠️ {lang_name} is one of this model's lower-confidence languages "
131
+ f"(see the [model card](https://huggingface.co/{MODEL_ID}) for benchmark numbers)."
132
+ )
133
 
134
  if not questions:
135
+ return (
136
+ text,
137
+ f"⚠️ Couldn't parse valid questions from the model's output. Raw output shown alongside.{note}",
138
+ )
139
 
140
+ formatted = "\n".join(
141
+ f"{i + 1}. {q}" for i, q in enumerate(questions)
142
+ )
143
 
144
+ return formatted, ("✅ Generated." + note) if note else "✅ Generated."
145
 
146
  with gr.Blocks(title="mist-qg-1.5b — multilingual question generator") as demo:
147
  gr.Markdown(