DANGDOCAO commited on
Commit
602f496
·
verified ·
1 Parent(s): 5428f85
.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ HVU_QA/30ktrain.json filter=lfs diff=lfs merge=lfs -text
HVU_QA/30ktrain.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:87143be92ee93e76f4e4b6ccfee58da6970b70a80bbc3606fbecdec518b01921
3
+ size 218169057
HVU_QA/fine_tune_qg.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from datasets import Dataset
3
+ from sklearn.model_selection import train_test_split
4
+ from transformers import (
5
+ T5Tokenizer,
6
+ T5ForConditionalGeneration,
7
+ TrainingArguments,
8
+ Trainer
9
+ )
10
+
11
+ def load_squad_data(file_path):
12
+ with open(file_path, "r", encoding="utf-8") as f:
13
+ squad_data = json.load(f)
14
+
15
+ data = []
16
+ for article in squad_data["data"]:
17
+ context = article.get("title", "")
18
+ for paragraph in article["paragraphs"]:
19
+ for qa in paragraph["qas"]:
20
+ if not qa.get("is_impossible", False) and qa.get("answers"):
21
+ answer = qa["answers"][0]["text"]
22
+ question = qa["question"]
23
+ input_text = f"answer: {answer} context: {context}"
24
+ data.append({"input": input_text, "target": question})
25
+ return data
26
+
27
+ def preprocess_function(example, tokenizer, max_input_length=512, max_target_length=64):
28
+ model_inputs = tokenizer(
29
+ example["input"],
30
+ max_length=max_input_length,
31
+ padding="max_length",
32
+ truncation=True,
33
+ )
34
+ labels = tokenizer(
35
+ text_target=example["target"],
36
+ max_length=max_target_length,
37
+ padding="max_length",
38
+ truncation=True,
39
+ )
40
+ model_inputs["labels"] = labels["input_ids"]
41
+ return model_inputs
42
+
43
+ def main():
44
+ data_path = "30ktrain.json"
45
+ output_dir = "t5-viet-qg-finetuned"
46
+ logs_dir = "logs"
47
+ model_name = "VietAI/vit5-base"
48
+
49
+ print("Tải mô hình và tokenizer...")
50
+ tokenizer = T5Tokenizer.from_pretrained(model_name)
51
+ model = T5ForConditionalGeneration.from_pretrained(model_name)
52
+
53
+ print("Đọc và chia dữ liệu...")
54
+ raw_data = load_squad_data(data_path)
55
+ train_data, val_data = train_test_split(raw_data, test_size=0.2, random_state=42)
56
+
57
+ train_dataset = Dataset.from_list(train_data)
58
+ val_dataset = Dataset.from_list(val_data)
59
+
60
+ tokenized_train = train_dataset.map(
61
+ lambda x: preprocess_function(x, tokenizer),
62
+ batched=True,
63
+ remove_columns=["input", "target"]
64
+ )
65
+ tokenized_val = val_dataset.map(
66
+ lambda x: preprocess_function(x, tokenizer),
67
+ batched=True,
68
+ remove_columns=["input", "target"]
69
+ )
70
+
71
+ print("Cấu hình huấn luyện...")
72
+ training_args = TrainingArguments(
73
+ output_dir=output_dir,
74
+ overwrite_output_dir=True,
75
+ per_device_train_batch_size=1,
76
+ gradient_accumulation_steps=1,
77
+ num_train_epochs=3,
78
+ learning_rate=2e-4,
79
+ weight_decay=0.01,
80
+ warmup_steps=0,
81
+ logging_dir=logs_dir,
82
+ logging_steps=10,
83
+ fp16=False
84
+ )
85
+
86
+ print("Huấn luyện mô hình...")
87
+ trainer = Trainer(
88
+ model=model,
89
+ args=training_args,
90
+ train_dataset=tokenized_train,
91
+ eval_dataset=tokenized_val,
92
+ tokenizer=tokenizer,
93
+ )
94
+ trainer.train()
95
+
96
+ print("Lưu mô hình...")
97
+ model.save_pretrained(output_dir)
98
+ tokenizer.save_pretrained(output_dir)
99
+ print("Huấn luyện hoàn tất!")
100
+
101
+ if __name__ == "__main__":
102
+ main()
HVU_QA/generate_question.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from difflib import SequenceMatcher
3
+ from transformers import T5Tokenizer, T5ForConditionalGeneration
4
+ from transformers.utils import logging as hf_logging
5
+
6
+ hf_logging.set_verbosity_error()
7
+
8
+ MODEL_DIR = "t5-viet-qg-finetuned"
9
+ DATA_PATH = "30ktrain.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
+ for qa in paragraph.get("qas", []):
24
+ answers = qa.get("answers", [])
25
+ if not answers:
26
+ continue
27
+ answer_text = answers[0].get("text", "").strip()
28
+ question_text = qa.get("question", "").strip()
29
+
30
+ score = score_title
31
+ if score > best_score:
32
+ best_score = score
33
+ best_entry = (context_title, answer_text, question_text)
34
+
35
+ return best_entry
36
+
37
+ def _near_duplicate(q, seen, thr=0.90):
38
+ for s in seen:
39
+ if SequenceMatcher(None, q, s).ratio() >= thr:
40
+ return True
41
+ return False
42
+
43
+ def generate_questions(user_context,
44
+ total_questions=20,
45
+ batch_size=10,
46
+ top_k=60,
47
+ top_p=0.95,
48
+ temperature=0.9,
49
+ max_input_len=512,
50
+ max_new_tokens=64):
51
+ with open(DATA_PATH, "r", encoding="utf-8") as f:
52
+ squad_data = json.load(f)
53
+
54
+ best_entry = find_best_match_from_context(user_context, squad_data)
55
+ if best_entry is None:
56
+ print("Không tìm thấy dữ liệu phù hợp trong file JSON.")
57
+ return
58
+
59
+ _, answer, _ = best_entry
60
+
61
+ input_text = f"answer: {answer} context: {user_context}"
62
+ inputs = tokenizer(
63
+ input_text,
64
+ return_tensors="pt",
65
+ truncation=True,
66
+ max_length=max_input_len
67
+ )
68
+
69
+ unique_questions = []
70
+ remaining = total_questions
71
+
72
+ while remaining > 0:
73
+ n = min(batch_size, remaining)
74
+ outputs = model.generate(
75
+ **inputs,
76
+ do_sample=True,
77
+ top_k=top_k,
78
+ top_p=top_p,
79
+ temperature=temperature,
80
+ max_new_tokens=max_new_tokens,
81
+ num_return_sequences=n,
82
+ no_repeat_ngram_size=3,
83
+ repetition_penalty=1.12
84
+ )
85
+
86
+ for out in outputs:
87
+ q = tokenizer.decode(out, skip_special_tokens=True).strip()
88
+ if len(q) < 5:
89
+ continue
90
+ if not _near_duplicate(q, unique_questions, thr=0.90):
91
+ unique_questions.append(q)
92
+
93
+ remaining = total_questions - len(unique_questions)
94
+ if remaining <= 0:
95
+ break
96
+
97
+ unique_questions = unique_questions[:total_questions]
98
+
99
+ print("Các câu hỏi mới được sinh ra:")
100
+ for i, q in enumerate(unique_questions, 1):
101
+ print(f"{i}. {q}")
102
+
103
+ if __name__ == "__main__":
104
+ user_context = input("\nNhập đoạn văn bản:\n ").strip()
105
+
106
+ raw_n = input("\nNhập vào số lượng câu hỏi bạn cần:").strip()
107
+ if raw_n == "":
108
+ total_questions = 20
109
+ else:
110
+ try:
111
+ total_questions = int(raw_n)
112
+ except ValueError:
113
+ print("Giá trị không hợp lệ. Dùng mặc định 20.")
114
+ total_questions = 20
115
+
116
+ if total_questions < 1:
117
+ total_questions = 1
118
+ if total_questions > 200:
119
+ total_questions = 200
120
+
121
+ batch_size = 20 if total_questions >= 30 else min(20, total_questions)
122
+
123
+ print("\nĐang phân tích dữ liệu...\n")
124
+
125
+ generate_questions(
126
+ user_context=user_context,
127
+ total_questions=total_questions,
128
+ batch_size=batch_size,
129
+ top_k=60,
130
+ top_p=0.95,
131
+ temperature=0.9,
132
+ max_input_len=512,
133
+ max_new_tokens=64
134
+ )
README.md ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HVU_QA
2
+
3
+ **HVU_QA** is a project dedicated to sharing datasets and tools for **Question Generation Processing (NLP)**, developed and maintained by the research team at **Hung Vuong University (HVU), Phu Tho, Vietnam**.
4
+ This project is supported by **Hung Vuong University, Phu Tho, Vietnam**, with the aim of advancing research and applications in low-resource language processing, particularly for the Vietnamese language.
5
+
6
+ ---
7
+
8
+ ## 📚 Overview
9
+
10
+ This repository enables you to:
11
+
12
+ 1. Fine-tune the [VietAI/vit5-base](https://huggingface.co/datasets/DANGDOCAO/GeneratingQuestions) model on your own GQ dataset.
13
+ 2. Generate multiple, diverse questions given a user-provided text passage (context).
14
+
15
+ ---
16
+
17
+ ## 📁 Datasets
18
+
19
+ * Built following the **SQuAD v2.0 standard**, ensuring compatibility with NLP pipelines.
20
+ * Includes tens of thousands of high-quality **Question–Context–Answer triples (QCA)**.
21
+ * Suitable for both **training** and **evaluation**.
22
+
23
+ ---
24
+
25
+ ## 📁 Vietnamese Question Generation Tool
26
+
27
+ A **command-line tool** for:
28
+
29
+ * **Fine-tuning** a question generation model.
30
+ * **Automatically generating questions** from Vietnamese text.
31
+
32
+ Built on **Hugging Face Transformers (VietAI/vit5-base)** and **PyTorch**.
33
+
34
+ ---
35
+
36
+ ## Features
37
+
38
+ * Fine-tune a question generation model with SQuAD v2.0 format data.
39
+ * Generate diverse and creative questions from text passages.
40
+ * Flexible generation parameters (`top-k`, `top-p`, `temperature`, etc.).
41
+ * Simple command-line usage.
42
+ * GPU support if available.
43
+
44
+ ---
45
+
46
+ ## 📊 Evaluation Results
47
+
48
+ We conducted both **manual evaluation** (500 samples) and **automatic evaluation** (1,000 samples).
49
+
50
+ | Evaluation Type | Precision | Recall | F1-Score |
51
+ |------------------|-----------|--------|----------|
52
+ | Automatic (1000) | 0.85 | 0.83 | 0.84 |
53
+ | Manual (500) | 0.88 | 0.86 | 0.87 |
54
+
55
+ ➡️ The model generates diverse, grammatically correct, and contextually appropriate questions.
56
+
57
+ ---
58
+
59
+ ## Creation Process
60
+
61
+ The dataset was built using a **4-stage automated pipeline**:
62
+
63
+ 1. Select relevant QA websites from trusted sources.
64
+ 2. Automatic crawling to collect raw QA pages.
65
+ 3. Semantic tag extraction to obtain clean Question–Context–Answer triples.
66
+ 4. AI-assisted filtering to remove noisy or inconsistent samples.
67
+
68
+ ---
69
+
70
+ ## 📝 Quality Evaluation
71
+
72
+ A fine-tuned model trained on **HVU_QA (VietAI/vit5-base)** achieved:
73
+
74
+ * **BLEU Score**: 90.61
75
+ * **Semantic similarity**: 97.0% (cosine ≥ 0.8)
76
+ * **Human evaluation**:
77
+ * Grammar: **4.58 / 5**
78
+ * Usefulness: **4.29 / 5**
79
+
80
+ ➡️ These results confirm that **HVU_QA is a high-quality resource** for developing robust FAQ-style question generation models.
81
+
82
+ ---
83
+
84
+ ## 📂 Project Structure
85
+
86
+ ```
87
+ .HVU_QA
88
+ ├── t5-viet-qg-finetuned/
89
+ ├── fine_tune_qg.py
90
+ ├── generate_question.py
91
+ ├── 30ktrain.json
92
+ └── README.md
93
+ ```
94
+ > All data files are UTF-8 encoded and ready for use in NLP pipelines.
95
+
96
+ ---
97
+
98
+ ## 🛠️ Requirements
99
+
100
+ * Python 3.8+
101
+ * PyTorch >= 1.9
102
+ * Transformers >= 4.30
103
+ * scikit-learn
104
+ * Fine-tuned model (download at: [link](https://huggingface.co/datasets/DANGDOCAO/GeneratingQuestions/tree/main))
105
+
106
+ ---
107
+
108
+ ## ⚙️ Setup
109
+
110
+ ### 🛠️ Step 1: Download and Extract
111
+
112
+ 1. Download `HVU_QA.zip`
113
+ 2. Extract into a folder, e.g.:
114
+
115
+ ```
116
+ D:\your\HVU_QA
117
+ ```
118
+
119
+ ### 🛠️ Step 2: Add to Environment Path (if needed)
120
+
121
+ 1. Open **System Properties → Environment Variables**
122
+ 2. Select `Path` → **Edit** → **New**
123
+ 3. Add the path, e.g.:
124
+
125
+ ```
126
+ D:\your\HVU_QA
127
+ ```
128
+
129
+ ### 🛠️ Step 3: Open in Visual Studio Code
130
+
131
+ ```
132
+ File > Open Folder > D:\HVU_QA
133
+ ```
134
+
135
+ ### 🛠️ Step 4: Install Required Libraries
136
+
137
+ Open **Terminal** and run:
138
+
139
+ #### Windows (PowerShell)
140
+
141
+ **Required only**
142
+
143
+ ```powershell
144
+ python -m pip install --upgrade pip
145
+ pip install torch transformers datasets scikit-learn sentencepiece safetensors
146
+ ```
147
+
148
+ **Required + Optional**
149
+
150
+ ```powershell
151
+ python -m pip install --upgrade pip
152
+ pip install torch transformers datasets scikit-learn sentencepiece safetensors accelerate tensorboard evaluate sacrebleu rouge-score nltk
153
+ ```
154
+
155
+ #### Linux / macOS (bash/zsh)
156
+
157
+ **Required only**
158
+
159
+ ```bash
160
+ python3 -m pip install --upgrade pip
161
+ pip install torch transformers datasets scikit-learn sentencepiece safetensors
162
+ ```
163
+
164
+ **Required + Optional**
165
+
166
+ ```bash
167
+ python3 -m pip install --upgrade pip
168
+ pip install torch transformers datasets scikit-learn sentencepiece safetensors accelerate tensorboard evaluate sacrebleu rouge-score nltk
169
+ ```
170
+
171
+ ✅ Verify installation:
172
+
173
+ * Windows (PowerShell)
174
+
175
+ ```powershell
176
+ python -c "import torch, transformers, datasets, sklearn, sentencepiece, safetensors, accelerate, tensorboard, evaluate, sacrebleu, rouge_score, nltk; print('✅ All dependencies installed correctly!')"
177
+ ```
178
+
179
+ * Linux/macOS
180
+
181
+ ```bash
182
+ python3 -c "import torch, transformers, datasets, sklearn, sentencepiece, safetensors, accelerate, tensorboard, evaluate, sacrebleu, rouge_score, nltk; print('✅ All dependencies installed correctly!')"
183
+ ```
184
+
185
+ ---
186
+
187
+ ## Usage
188
+
189
+ * Train and evaluate a question generation model.
190
+ * Develop Vietnamese NLP tools.
191
+ * Conduct linguistic research.
192
+
193
+ ### Training (Fine-tuning)
194
+
195
+ When you run `fine_tune_qg.py`, the script will:
196
+
197
+ 1. Load the dataset from **`30ktrain.json`**
198
+ 2. Fine-tune the `VietAI/vit5-base` model
199
+ 3. Save the trained model into a new folder named **`t5-viet-qg-finetuned/`**
200
+
201
+ Run:
202
+
203
+ ```bash
204
+ python fine_tune_qg.py
205
+ ```
206
+
207
+ ### Generating Questions
208
+
209
+ ```bash
210
+ python generate_question.py
211
+ ```
212
+
213
+ **Example:**
214
+
215
+ ```
216
+ Input passage:
217
+ Iced milk coffee (Cà phê sữa đá) is a famous drink in Vietnam.
218
+
219
+ Number of questions: 5
220
+ ```
221
+
222
+ ✅ Output:
223
+
224
+ 1. What type of coffee is famous in Vietnam?
225
+ 2. Why is iced milk coffee popular?
226
+ 3. What ingredients are included in iced milk coffee?
227
+ 4. Where does iced milk coffee originate from?
228
+ 5. How is Vietnamese iced milk coffee prepared?
229
+
230
+ ---
231
+
232
+ ## ⚙️ Generation Settings
233
+
234
+ In `generate_question.py`, you can adjust:
235
+
236
+ * `top_k`, `top_p`, `temperature`, `no_repeat_ngram_size`, `repetition_penalty`
237
+
238
+ ---
239
+
240
+ ## 🤝 Contribution
241
+
242
+ We welcome contributions:
243
+
244
+ * Open issues
245
+ * Submit pull requests
246
+ * Suggest improvements or add datasets
247
+
248
+ ---
249
+
250
+ ## 📄 Citation
251
+
252
+ If you use this repository or datasets in research, please cite:
253
+
254
+ **Ha Nguyen-Tien, Phuc Le-Hong, Dang Do-Cao, Cuong Nguyen-Hung, Chung Mai-Van. 2025. A Method to Build QA Corpora for Low-Resource Languages. Proceedings of KSE 2025. ACM TALLIP.**
255
+
256
+ ### 📚 BibTeX
257
+
258
+ ```bibtex
259
+ @inproceedings{nguyen2025hvuqa,
260
+ title={A Method to Build QA Corpora for Low-Resource Languages},
261
+ author={Ha Nguyen-Tien and Phuc Le-Hong and Dang Do-Cao and Cuong Nguyen-Hung and Chung Mai-Van},
262
+ booktitle={Proceedings of KSE 2025},
263
+ year={2025}
264
+ }
265
+ ```
266
+
267
+ ---
268
+
269
+ ## 📬 Contact
270
+
271
+ * **Ha Nguyen-Tien** (Corresponding author)
272
273
+
274
+ * **Phuc Le-Hong**
275
276
+
277
+ * **Dang Do-Cao**
278
279
+
280
+ 📍 Faculty of Engineering and Technology, Hung Vuong University, Phu Tho, Vietnam
281
+ 🌐 [https://hvu.edu.vn](https://hvu.edu.vn)
282
+
283
+ ---
284
+
285
+ *This repository is part of our ongoing effort to support Vietnamese NLP and make language technology more accessible for low-resource and underrepresented languages.*