Datasets:
HVU_QA
Browse files- .gitattributes +1 -0
- HVU_QA/30ktrain.json +3 -0
- HVU_QA/500train_bcp.json +0 -0
- HVU_QA/README.md +285 -0
- HVU_QA/fine_tune_qg.py +109 -0
- HVU_QA/generate_question.py +139 -0
.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:52bbe28e120c309d54ceee13f3176b0e6b04ea88fdad0c4598d8cea7daf904a6
|
3 |
+
size 95443835
|
HVU_QA/500train_bcp.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
HVU_QA/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 |
+
📧 [[email protected]](mailto:[email protected])
|
273 |
+
|
274 |
+
* **Phuc Le-Hong**
|
275 |
+
📧 [[email protected]](mailto:[email protected])
|
276 |
+
|
277 |
+
* **Dang Do-Cao**
|
278 |
+
📧 [[email protected]](mailto:[email protected])
|
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.*
|
HVU_QA/fine_tune_qg.py
ADDED
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
"""
|
13 |
+
Đọc dữ liệu từ file JSON theo cấu trúc đã phân tích và chuẩn bị dữ liệu cho mô hình.
|
14 |
+
"""
|
15 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
16 |
+
squad_data = json.load(f)
|
17 |
+
|
18 |
+
data = []
|
19 |
+
for article in squad_data["data"]:
|
20 |
+
for paragraph in article["paragraphs"]:
|
21 |
+
context = paragraph.get("context", "")
|
22 |
+
for qa in paragraph["qas"]:
|
23 |
+
if not qa.get("is_impossible", False) and qa.get("answers"):
|
24 |
+
answer = qa["answers"][0]["text"]
|
25 |
+
question = qa["question"]
|
26 |
+
input_text = f"answer: {answer} context: {context}"
|
27 |
+
data.append({"input": input_text, "target": question})
|
28 |
+
return data
|
29 |
+
|
30 |
+
def preprocess_function(example, tokenizer, max_input_length=512, max_target_length=64):
|
31 |
+
"""
|
32 |
+
Tiền xử lý dữ liệu, bao gồm token hóa đầu vào và đầu ra.
|
33 |
+
"""
|
34 |
+
model_inputs = tokenizer(
|
35 |
+
example["input"],
|
36 |
+
max_length=max_input_length,
|
37 |
+
padding="max_length",
|
38 |
+
truncation=True,
|
39 |
+
)
|
40 |
+
labels = tokenizer(
|
41 |
+
text_target=example["target"],
|
42 |
+
max_length=max_target_length,
|
43 |
+
padding="max_length",
|
44 |
+
truncation=True,
|
45 |
+
)
|
46 |
+
model_inputs["labels"] = labels["input_ids"]
|
47 |
+
return model_inputs
|
48 |
+
|
49 |
+
def main():
|
50 |
+
data_path = "new_data.json" # Đường dẫn đến file dữ liệu của bạn
|
51 |
+
output_dir = "t5-viet-qg-finetuned"
|
52 |
+
logs_dir = "logs"
|
53 |
+
model_name = "VietAI/vit5-base"
|
54 |
+
|
55 |
+
print("Tải mô hình và tokenizer...")
|
56 |
+
tokenizer = T5Tokenizer.from_pretrained(model_name)
|
57 |
+
model = T5ForConditionalGeneration.from_pretrained(model_name)
|
58 |
+
|
59 |
+
print("Đọc và chia dữ liệu...")
|
60 |
+
raw_data = load_squad_data(data_path) # Tải dữ liệu từ file
|
61 |
+
train_data, val_data = train_test_split(raw_data, test_size=0.2, random_state=42)
|
62 |
+
|
63 |
+
train_dataset = Dataset.from_list(train_data)
|
64 |
+
val_dataset = Dataset.from_list(val_data)
|
65 |
+
|
66 |
+
# Tiền xử lý dữ liệu cho train và validation
|
67 |
+
tokenized_train = train_dataset.map(
|
68 |
+
lambda x: preprocess_function(x, tokenizer),
|
69 |
+
batched=True,
|
70 |
+
remove_columns=["input", "target"]
|
71 |
+
)
|
72 |
+
tokenized_val = val_dataset.map(
|
73 |
+
lambda x: preprocess_function(x, tokenizer),
|
74 |
+
batched=True,
|
75 |
+
remove_columns=["input", "target"]
|
76 |
+
)
|
77 |
+
|
78 |
+
print("Cấu hình huấn luyện...")
|
79 |
+
training_args = TrainingArguments(
|
80 |
+
output_dir=output_dir,
|
81 |
+
overwrite_output_dir=True,
|
82 |
+
per_device_train_batch_size=1,
|
83 |
+
gradient_accumulation_steps=1,
|
84 |
+
num_train_epochs=3,
|
85 |
+
learning_rate=2e-4,
|
86 |
+
weight_decay=0.01,
|
87 |
+
warmup_steps=0,
|
88 |
+
logging_dir=logs_dir,
|
89 |
+
logging_steps=10,
|
90 |
+
fp16=False
|
91 |
+
)
|
92 |
+
|
93 |
+
print("Huấn luyện mô hình...")
|
94 |
+
trainer = Trainer(
|
95 |
+
model=model,
|
96 |
+
args=training_args,
|
97 |
+
train_dataset=tokenized_train,
|
98 |
+
eval_dataset=tokenized_val,
|
99 |
+
tokenizer=tokenizer,
|
100 |
+
)
|
101 |
+
trainer.train()
|
102 |
+
|
103 |
+
print("Lưu mô hình...")
|
104 |
+
model.save_pretrained(output_dir)
|
105 |
+
tokenizer.save_pretrained(output_dir)
|
106 |
+
print("Huấn luyện hoàn tất!")
|
107 |
+
|
108 |
+
if __name__ == "__main__":
|
109 |
+
main()
|
HVU_QA/generate_question.py
ADDED
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 = "new_data.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, # Tăng temperature để sinh câu hỏi sáng tạo hơn
|
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 |
+
# Sử dụng thông tin câu trả lời và bối cảnh rõ ràng hơn
|
63 |
+
input_text = f"answer: {answer} context: {context} Hãy tạo câu hỏi sáng tạo và đúng đắn từ câu trả lời này. Đảm bảo câu hỏi có dấu hỏi chấm và rõ ràng."
|
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, # Cho phép lựa chọn từ ngữ đa dạng
|
80 |
+
top_p=top_p, # Cho phép lựa chọn ngẫu nhiên từ các từ ngữ
|
81 |
+
temperature=temperature, # Tăng temperature để sinh câu hỏi sáng tạo hơn
|
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 |
+
# Đảm bảo rằng câu hỏi có dấu hỏi chấm
|
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 += "?" # Thêm dấu hỏi chấm nếu không có
|
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, # Điều chỉnh top_p để mô hình sáng tạo hơn
|
136 |
+
temperature=0.9, # Tăng temperature đ��� sinh câu hỏi sáng tạo hơn
|
137 |
+
max_input_len=512,
|
138 |
+
max_new_tokens=64
|
139 |
+
)
|