DANGDOCAO commited on
Commit
950de05
·
verified ·
1 Parent(s): 8a2223c
Files changed (1) hide show
  1. HVU_QA/generate_question.py +135 -116
HVU_QA/generate_question.py CHANGED
@@ -1,4 +1,5 @@
1
- import json
 
2
  from difflib import SequenceMatcher
3
  from transformers import T5Tokenizer, T5ForConditionalGeneration
4
  from transformers.utils import logging as hf_logging
@@ -6,134 +7,152 @@ from transformers.utils import logging as hf_logging
6
  hf_logging.set_verbosity_error()
7
 
8
  MODEL_DIR = "t5-viet-qg-finetuned"
9
- DATA_PATH = "39k_train.json"
10
 
11
- tokenizer = T5Tokenizer.from_pretrained(MODEL_DIR)
12
- model = T5ForConditionalGeneration.from_pretrained(MODEL_DIR)
 
 
 
 
 
 
 
 
13
 
14
- def find_best_match_from_context(user_context, squad_data):
15
- best_score, best_entry = 0.0, None
16
- ui = user_context.lower()
17
 
18
- for article in squad_data.get("data", []):
19
- context_title = article.get("title", "")
20
- score_title = SequenceMatcher(None, ui, context_title.lower()).ratio()
21
 
22
- for paragraph in article.get("paragraphs", []):
23
- context = paragraph.get("context", "")
24
- for qa in paragraph.get("qas", []):
25
- answers = qa.get("answers", [])
26
- if not answers:
27
- continue
28
- answer_text = answers[0].get("text", "").strip()
29
- question_text = qa.get("question", "").strip()
30
-
31
- score = score_title
32
- if score > best_score:
33
- best_score = score
34
- best_entry = (context, answer_text, question_text)
35
 
36
- return best_entry
37
-
38
- def _near_duplicate(q, seen, thr=0.90):
39
- for s in seen:
40
- if SequenceMatcher(None, q, s).ratio() >= thr:
41
  return True
42
  return False
43
 
44
- def generate_questions(user_context,
45
- total_questions=20,
46
- batch_size=10,
47
- top_k=60,
48
- top_p=0.95,
49
- temperature=0.9,
50
- max_input_len=512,
51
- max_new_tokens=64):
52
- with open(DATA_PATH, "r", encoding="utf-8") as f:
53
- squad_data = json.load(f)
54
-
55
- best_entry = find_best_match_from_context(user_context, squad_data)
56
- if best_entry is None:
57
- print("Không tìm thấy dữ liệu phù hợp trong file JSON.")
58
- return
59
-
60
- context, answer, _ = best_entry
61
-
62
-
63
- input_text = f"answer: {answer}\ncontext: {context}\nquestion:"
64
- inputs = tokenizer(
65
- input_text,
66
- return_tensors="pt",
67
- truncation=True,
68
- max_length=max_input_len
69
- )
70
 
71
- unique_questions = []
72
- remaining = total_questions
73
-
74
- while remaining > 0:
75
- n = min(batch_size, remaining)
76
- outputs = model.generate(
77
- **inputs,
78
- do_sample=True,
79
- top_k=top_k,
80
- top_p=top_p,
81
- temperature=temperature,
82
- max_new_tokens=max_new_tokens,
83
- num_return_sequences=n,
84
- no_repeat_ngram_size=3,
85
- repetition_penalty=1.12
86
- )
87
-
88
- for out in outputs:
89
- q = tokenizer.decode(out, skip_special_tokens=True).strip()
90
- if len(q) < 5:
91
  continue
92
- if not _near_duplicate(q, unique_questions, thr=0.90):
93
- unique_questions.append(q)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
95
- remaining = total_questions - len(unique_questions)
96
- if remaining <= 0:
97
- break
98
 
99
- unique_questions = unique_questions[:total_questions]
100
 
101
-
102
- print("Các câu hỏi mới được sinh ra:")
103
- for i, q in enumerate(unique_questions, 1):
104
- if not q.endswith("?"):
105
- q += "?"
106
- print(f"{i}. {q}")
107
 
108
- if __name__ == "__main__":
109
- user_context = input("\nNhập đoạn văn bản:\n ").strip()
110
 
111
- raw_n = input("\nNhập vào số lượng câu hỏi bạn cần:").strip()
112
- if raw_n == "":
113
- total_questions = 20
114
- else:
115
- try:
116
- total_questions = int(raw_n)
117
- except ValueError:
118
- print("Giá trị không hợp lệ. Dùng mặc định 20.")
119
- total_questions = 20
120
-
121
- if total_questions < 1:
122
- total_questions = 1
123
- if total_questions > 200:
124
- total_questions = 200
125
-
126
- batch_size = 20 if total_questions >= 30 else min(20, total_questions)
127
-
128
- print("\nĐang phân tích dữ liệu...\n")
129
-
130
- generate_questions(
131
- user_context=user_context,
132
- total_questions=total_questions,
133
- batch_size=batch_size,
134
- top_k=60,
135
- top_p=0.95,
136
- temperature=0.9,
137
- max_input_len=512,
138
- max_new_tokens=64
139
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import torch
3
  from difflib import SequenceMatcher
4
  from transformers import T5Tokenizer, T5ForConditionalGeneration
5
  from transformers.utils import logging as hf_logging
 
7
  hf_logging.set_verbosity_error()
8
 
9
  MODEL_DIR = "t5-viet-qg-finetuned"
 
10
 
11
+ PATTERN = re.compile(
12
+ r"""
13
+ “([^”]{3,120})”
14
+ | "([^"]{3,120})"
15
+ | \b(?:là|gồm|do|theo)\s+([^,.;:\n]{3,120})
16
+ | \b\d{4}\b
17
+ | \b(?:Điều|Khoản)\s+\d+\b
18
+ """,
19
+ re.VERBOSE | re.IGNORECASE,
20
+ )
21
 
 
 
 
22
 
23
+ def norm(s: str) -> str:
24
+ return re.sub(r"\s+", " ", s).strip()
 
25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
+ def is_dup(q: str, qs: list[str], thr: float = 0.85) -> bool:
28
+ ql = q.lower()
29
+ for x in qs:
30
+ if SequenceMatcher(None, ql, x.lower()).ratio() >= thr:
 
31
  return True
32
  return False
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
+ def extract_answers(ctx: str, max_n: int = 60) -> list[str]:
36
+ ctx = norm(ctx)
37
+ answers, seen = [], set()
38
+
39
+ for m in PATTERN.finditer(ctx):
40
+ for g in m.groups():
41
+ if not g:
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  continue
43
+ g = norm(g)
44
+ k = g.lower()
45
+ if 3 <= len(g) <= 120 and k not in seen:
46
+ seen.add(k)
47
+ answers.append(g)
48
+ if len(answers) >= max_n:
49
+ return answers
50
+
51
+ if len(answers) < 8:
52
+ for i in range(0, min(len(ctx), 500), 60):
53
+ ch = norm(ctx[i : i + 60])
54
+ k = ch.lower()
55
+ if len(ch) >= 15 and k not in seen:
56
+ seen.add(k)
57
+ answers.append(ch)
58
+ if len(answers) >= max_n:
59
+ break
60
+
61
+ if not answers and ctx:
62
+ answers = [ctx[:120]]
63
+
64
+ return answers
65
+
66
+
67
+ def load_model():
68
+ tok = T5Tokenizer.from_pretrained(MODEL_DIR)
69
+ mdl = T5ForConditionalGeneration.from_pretrained(MODEL_DIR)
70
+
71
+ dev = "cuda" if torch.cuda.is_available() else "cpu"
72
+ try:
73
+ mdl = mdl.to(dev)
74
+ except RuntimeError:
75
+ dev = "cpu"
76
+ try:
77
+ torch.cuda.empty_cache()
78
+ except Exception:
79
+ pass
80
+ mdl = mdl.to(dev)
81
 
82
+ mdl.eval()
83
+ return tok, mdl, dev
 
84
 
 
85
 
86
+ tokenizer, model, device = load_model()
 
 
 
 
 
87
 
 
 
88
 
89
+ def generate_questions(context: str, n: int = 20) -> list[str]:
90
+ ctx = norm(context)
91
+ answers = extract_answers(ctx, max_n=80)
92
+ questions = []
93
+
94
+ gen_cfg = dict(
95
+ do_sample=True,
96
+ top_k=80,
97
+ top_p=0.98,
98
+ temperature=1.05,
99
+ max_new_tokens=72,
100
+ no_repeat_ngram_size=3,
101
+ repetition_penalty=1.08,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  )
103
+
104
+ num_ret = 8 if n <= 20 else 10
105
+
106
+ def run_prompt(ans: str, rounds: int):
107
+ nonlocal gen_cfg
108
+ prompt = f"answer: {ans}\ncontext: {ctx}\nquestion:"
109
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512).to(device)
110
+
111
+ for _ in range(rounds):
112
+ outs = model.generate(**inputs, num_return_sequences=num_ret, **gen_cfg)
113
+ added = 0
114
+ for o in outs:
115
+ q = norm(tokenizer.decode(o, skip_special_tokens=True))
116
+ if not q:
117
+ continue
118
+ if not q.endswith("?"):
119
+ q += "?"
120
+ if len(q) >= 6 and not is_dup(q, questions, thr=0.85):
121
+ questions.append(q)
122
+ added += 1
123
+ if len(questions) >= n:
124
+ return
125
+ if added == 0:
126
+ gen_cfg["temperature"] = min(1.25, gen_cfg["temperature"] + 0.05)
127
+ gen_cfg["top_p"] = min(0.995, gen_cfg["top_p"] + 0.005)
128
+
129
+ with torch.inference_mode():
130
+ for ans in answers:
131
+ if len(questions) >= n:
132
+ break
133
+ run_prompt(ans, rounds=6)
134
+
135
+ if len(questions) < n:
136
+ run_prompt(ctx[:120], rounds=12)
137
+
138
+ return questions[:n]
139
+
140
+
141
+ if __name__ == "__main__":
142
+ print("\nNhập đoạn văn bản: ")
143
+ lines = []
144
+ while True:
145
+ line = input()
146
+ if line == "":
147
+ break
148
+ lines.append(line)
149
+ ctx = "\n".join(lines)
150
+
151
+ n = int(input("\nNhập số lượng câu hỏi cần sinh: "))
152
+ n = max(1, min(n, 200))
153
+
154
+ qs = generate_questions(ctx, n)
155
+
156
+ print("\nCác câu hỏi sinh ra:")
157
+ for i, q in enumerate(qs, 1):
158
+ print(f"{i}. {q}")