DANGDOCAO commited on
Commit
1115ab6
·
verified ·
1 Parent(s): 514f770

Delete generate_question.py

Browse files
Files changed (1) hide show
  1. generate_question.py +0 -154
generate_question.py DELETED
@@ -1,154 +0,0 @@
1
- # generate_question.py
2
- import json
3
- from difflib import SequenceMatcher
4
- from transformers import T5Tokenizer, T5ForConditionalGeneration
5
- from transformers.utils import logging as hf_logging
6
-
7
- # ===== Giảm ồn cảnh báo của transformers =====
8
- hf_logging.set_verbosity_error()
9
-
10
- # ===== Cấu hình đường dẫn =====
11
- MODEL_DIR = "t5-viet-qg-finetuned" # thư mục model đã fine-tune
12
- DATA_PATH = "train-QA-v2.0.json" # file JSON dữ liệu gốc
13
-
14
- # ===== Load model & tokenizer 1 lần =====
15
- tokenizer = T5Tokenizer.from_pretrained(MODEL_DIR)
16
- model = T5ForConditionalGeneration.from_pretrained(MODEL_DIR)
17
-
18
- def find_best_match_from_context(user_context, squad_data):
19
- """
20
- Tìm bản ghi gần nhất dựa trên article.title (giữ đúng logic code gốc).
21
- Trả về tuple (context_title, answer_text, question_text) hoặc None.
22
- """
23
- best_score, best_entry = 0.0, None
24
- ui = user_context.lower()
25
-
26
- for article in squad_data.get("data", []):
27
- context_title = article.get("title", "")
28
- score_title = SequenceMatcher(None, ui, context_title.lower()).ratio()
29
-
30
- for paragraph in article.get("paragraphs", []):
31
- for qa in paragraph.get("qas", []):
32
- answers = qa.get("answers", [])
33
- if not answers:
34
- continue
35
- answer_text = answers[0].get("text", "").strip()
36
- question_text = qa.get("question", "").strip()
37
-
38
- score = score_title
39
- if score > best_score:
40
- best_score = score
41
- best_entry = (context_title, answer_text, question_text)
42
-
43
- return best_entry
44
-
45
- def _near_duplicate(q, seen, thr=0.90):
46
- """Loại câu gần trùng dựa trên tỉ lệ giống nhau."""
47
- for s in seen:
48
- if SequenceMatcher(None, q, s).ratio() >= thr:
49
- return True
50
- return False
51
-
52
- def generate_questions(user_context,
53
- total_questions=20,
54
- batch_size=10,
55
- top_k=60,
56
- top_p=0.95,
57
- temperature=0.9,
58
- max_input_len=512,
59
- max_new_tokens=64):
60
- # Load dữ liệu JSON
61
- with open(DATA_PATH, "r", encoding="utf-8") as f:
62
- squad_data = json.load(f)
63
-
64
- # Tìm bản ghi gần giống nhất (KHÔNG in ra màn hình)
65
- best_entry = find_best_match_from_context(user_context, squad_data)
66
- if best_entry is None:
67
- print("❌ Không tìm thấy dữ liệu phù hợp trong file JSON.")
68
- return
69
-
70
- _, answer, _ = best_entry # chỉ cần answer gốc để bảo toàn tính toàn vẹn
71
-
72
- # Chuẩn bị input cho mô hình (đặt max_length để tránh cảnh báo truncate)
73
- input_text = f"answer: {answer} context: {user_context}"
74
- inputs = tokenizer(
75
- input_text,
76
- return_tensors="pt",
77
- truncation=True,
78
- max_length=max_input_len
79
- )
80
-
81
- # Sinh nhiều câu hỏi theo lô để tiết kiệm RAM
82
- unique_questions = []
83
- remaining = total_questions
84
-
85
- while remaining > 0:
86
- n = min(batch_size, remaining)
87
- outputs = model.generate(
88
- **inputs,
89
- do_sample=True,
90
- top_k=top_k,
91
- top_p=top_p,
92
- temperature=temperature,
93
- max_new_tokens=max_new_tokens, # chiều dài phần sinh
94
- num_return_sequences=n,
95
- no_repeat_ngram_size=3,
96
- repetition_penalty=1.12
97
- )
98
-
99
- for out in outputs:
100
- q = tokenizer.decode(out, skip_special_tokens=True).strip()
101
- if len(q) < 5: # lọc câu quá ngắn
102
- continue
103
- if not _near_duplicate(q, unique_questions, thr=0.90):
104
- unique_questions.append(q)
105
-
106
- remaining = total_questions - len(unique_questions)
107
- if remaining <= 0:
108
- break
109
-
110
- # Cắt đúng số lượng yêu cầu
111
- unique_questions = unique_questions[:total_questions]
112
-
113
- print("✅ Các câu hỏi mới được sinh ra:")
114
- for i, q in enumerate(unique_questions, 1):
115
- print(f"{i}. {q}")
116
-
117
- if __name__ == "__main__":
118
- # Nhập đoạn văn
119
- user_context = input("\nNhập đoạn văn bản:\n ").strip()
120
-
121
- # Nhập số lượng câu hỏi cần sinh (tùy biến)
122
- raw_n = input("\nNhập vào số lượng câu hỏi bạn cần:").strip()
123
- if raw_n == "":
124
- total_questions = 20
125
- else:
126
- try:
127
- total_questions = int(raw_n)
128
- except ValueError:
129
- print("⚠️ Giá trị không hợp lệ. Dùng mặc định 20.")
130
- total_questions = 20
131
-
132
- # Ràng buộc an toàn
133
- if total_questions < 1:
134
- total_questions = 1
135
- if total_questions > 200:
136
- print("⚠️ Giới hạn tối đa 200 câu. Sẽ sinh 200 câu.")
137
- total_questions = 200
138
-
139
- # batch_size tự động theo quy mô
140
- batch_size = 10 if total_questions >= 30 else min(10, total_questions)
141
-
142
- # Thông báo phân tích
143
- print("\n🔍 Đang phân tích dữ liệu...\n")
144
-
145
- generate_questions(
146
- user_context=user_context,
147
- total_questions=total_questions,
148
- batch_size=batch_size,
149
- top_k=60,
150
- top_p=0.95,
151
- temperature=0.9,
152
- max_input_len=512,
153
- max_new_tokens=64
154
- )