Datasets:
Upload 6 files
Browse files- .gitattributes +3 -0
- Data_totalQCAtriples30K/30ktrain.json +3 -0
- Datatest1k/testorgin1k.json +3 -0
- Datatrain29k/29kcorpustag.json +3 -0
- README.md +239 -0
- fine_tune_qg.py +102 -0
- generate_question.py +154 -0
.gitattributes
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Data_totalQCAtriples30K/30ktrain.json filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
Datatest1k/testorgin1k.json filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
Datatrain29k/29kcorpustag.json filter=lfs diff=lfs merge=lfs -text
|
Data_totalQCAtriples30K/30ktrain.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a1989e727e0bb58732b6cd569c87fe2e474816d69064d0769f34cd307544d2fa
|
| 3 |
+
size 11786416
|
Datatest1k/testorgin1k.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a1989e727e0bb58732b6cd569c87fe2e474816d69064d0769f34cd307544d2fa
|
| 3 |
+
size 11786416
|
Datatrain29k/29kcorpustag.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a1989e727e0bb58732b6cd569c87fe2e474816d69064d0769f34cd307544d2fa
|
| 3 |
+
size 11786416
|
README.md
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# HVU_QA_NLP
|
| 2 |
+
|
| 3 |
+
**HVU_QA_NLP** 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 |
+
1. Fine-tune the [VietAI/vit5-base](https://huggingface.co/VietAI/vit5-base) model on your own QA dataset.
|
| 12 |
+
2. Generate multiple, diverse questions given a user-provided text passage (context).
|
| 13 |
+
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
## 📁 Dataset Format
|
| 17 |
+
|
| 18 |
+
Your dataset must follow the **SQuAD v2.0** JSON structure:
|
| 19 |
+
|
| 20 |
+
```json
|
| 21 |
+
{
|
| 22 |
+
"version": "v2.0",
|
| 23 |
+
"data": [
|
| 24 |
+
{
|
| 25 |
+
"title": "Đồ uống nào của Việt Nam từng lọt top ngon nhất thế giới?",
|
| 26 |
+
"paragraphs": [
|
| 27 |
+
{
|
| 28 |
+
"qas": [
|
| 29 |
+
{
|
| 30 |
+
"id": "q1_1",
|
| 31 |
+
"question": "Đồ uống nào của Việt Nam từng lọt top ngon nhất thế giới?",
|
| 32 |
+
"answers": [
|
| 33 |
+
{
|
| 34 |
+
"text": "Theo bản đánh giá tháng 2/2023 của Taste Atlas...",
|
| 35 |
+
"answer_start": "Theo bản đánh giá tháng 2/2023 của Taste Atlas..."
|
| 36 |
+
}
|
| 37 |
+
],
|
| 38 |
+
"is_impossible": false
|
| 39 |
+
}
|
| 40 |
+
]
|
| 41 |
+
}
|
| 42 |
+
]
|
| 43 |
+
}
|
| 44 |
+
]
|
| 45 |
+
}
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
**Required fields:**
|
| 49 |
+
- `title` → used as context
|
| 50 |
+
- `question` → target question
|
| 51 |
+
- `answers[0].text` → seed answer for training
|
| 52 |
+
- `is_impossible` → filter for valid QAs
|
| 53 |
+
|
| 54 |
+
**File name:** `30ktrain.json` (UTF-8)
|
| 55 |
+
|
| 56 |
+
---
|
| 57 |
+
|
| 58 |
+
## 📁 Datasets
|
| 59 |
+
|
| 60 |
+
This repository provides datasets for **training** and **evaluating** Vietnamese question generation models.
|
| 61 |
+
|
| 62 |
+
### 🔹 `DataTotalQCAtriples30k/`
|
| 63 |
+
- **`30ktrain.json`** → 30,000 QCA triples for training.
|
| 64 |
+
|
| 65 |
+
### 🔹 `Datatest1k/`
|
| 66 |
+
- **`testorgin1k.json`** → 1,000 examples for manual & automatic evaluation.
|
| 67 |
+
|
| 68 |
+
### 🔹 `Datatrain29k/`
|
| 69 |
+
- **`29kcorpustag.json`** → 29,000 preprocessed QCA triples.
|
| 70 |
+
|
| 71 |
+
> All files are UTF-8 encoded and ready for direct use in NLP pipelines.
|
| 72 |
+
|
| 73 |
+
---
|
| 74 |
+
|
| 75 |
+
## 📊 Evaluation Results
|
| 76 |
+
|
| 77 |
+
We performed **manual evaluation on 500 samples** and **automatic evaluation on 1,000 samples**.
|
| 78 |
+
|
| 79 |
+
| Evaluation Type | Precision | Recall | F1-Score |
|
| 80 |
+
|------------------|-----------|--------|----------|
|
| 81 |
+
| Automatic (1000) | 0.85 | 0.83 | 0.84 |
|
| 82 |
+
| Manual (500) | 0.88 | 0.86 | 0.87 |
|
| 83 |
+
|
| 84 |
+
---
|
| 85 |
+
|
| 86 |
+
## 🔧 Installation
|
| 87 |
+
|
| 88 |
+
Create a virtual environment and install dependencies:
|
| 89 |
+
|
| 90 |
+
### Windows (PowerShell)
|
| 91 |
+
```powershell
|
| 92 |
+
python -m venv .venv
|
| 93 |
+
.venv\Scripts\Activate.ps1
|
| 94 |
+
python -m pip install --upgrade pip
|
| 95 |
+
pip install torch transformers datasets scikit-learn
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
### Linux / macOS
|
| 99 |
+
```bash
|
| 100 |
+
python3 -m venv .venv
|
| 101 |
+
source .venv/bin/activate
|
| 102 |
+
python -m pip install --upgrade pip
|
| 103 |
+
pip install torch transformers datasets scikit-learn
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
---
|
| 107 |
+
|
| 108 |
+
## 🚀 Training (Fine-tuning)
|
| 109 |
+
|
| 110 |
+
Make sure `30ktrain.json` is in the same folder as `fine_tune_qg.py`.
|
| 111 |
+
|
| 112 |
+
Run:
|
| 113 |
+
```bash
|
| 114 |
+
python fine_tune_qg.py
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
**What happens:**
|
| 118 |
+
- Loads `30ktrain.json`
|
| 119 |
+
- Splits into 80% train / 20% validation
|
| 120 |
+
- Tokenizes using `T5Tokenizer`
|
| 121 |
+
- Fine-tunes `VietAI/vit5-base` for 3 epochs
|
| 122 |
+
- Saves model + tokenizer to `t5-viet-qg-finetuned/`
|
| 123 |
+
|
| 124 |
+
**Key training parameters** (edit in `fine_tune_qg.py` if needed):
|
| 125 |
+
- `per_device_train_batch_size`: 1
|
| 126 |
+
- `learning_rate`: 2e-4
|
| 127 |
+
- `num_train_epochs`: 3
|
| 128 |
+
- `max_input_length`: 512
|
| 129 |
+
- `max_target_length`: 64
|
| 130 |
+
|
| 131 |
+
---
|
| 132 |
+
|
| 133 |
+
## 💡 Generating Questions
|
| 134 |
+
|
| 135 |
+
Once training is done, use `generate_question.py` to generate new questions.
|
| 136 |
+
|
| 137 |
+
Ensure:
|
| 138 |
+
- `MODEL_DIR` → `t5-viet-qg-finetuned/`
|
| 139 |
+
- `DATA_PATH` → `30ktrain.json`
|
| 140 |
+
|
| 141 |
+
Run:
|
| 142 |
+
```bash
|
| 143 |
+
python generate_question.py
|
| 144 |
+
```
|
| 145 |
+
|
| 146 |
+
Steps:
|
| 147 |
+
1. Enter a context passage (Vietnamese)
|
| 148 |
+
2. Enter number of questions (default 20, max 200)
|
| 149 |
+
3. Script will:
|
| 150 |
+
- Find best match in dataset by title similarity
|
| 151 |
+
- Use matched answer + your context
|
| 152 |
+
- Generate multiple unique questions with top-k & top-p sampling
|
| 153 |
+
4. Output lists generated questions.
|
| 154 |
+
|
| 155 |
+
---
|
| 156 |
+
|
| 157 |
+
## ⚙️ Generation Settings
|
| 158 |
+
|
| 159 |
+
In `generate_question.py`, tweak:
|
| 160 |
+
- `top_k` (default 60)
|
| 161 |
+
- `top_p` (default 0.95)
|
| 162 |
+
- `temperature` (default 0.9)
|
| 163 |
+
- `no_repeat_ngram_size` (default 3)
|
| 164 |
+
- `repetition_penalty` (default 1.12)
|
| 165 |
+
|
| 166 |
+
---
|
| 167 |
+
|
| 168 |
+
## 📂 Project Structure
|
| 169 |
+
|
| 170 |
+
```
|
| 171 |
+
.
|
| 172 |
+
├── fine_tune_qg.py
|
| 173 |
+
├── generate_question.py
|
| 174 |
+
├── 30ktrain.json
|
| 175 |
+
├── t5-viet-qg-finetuned/
|
| 176 |
+
├── README.md
|
| 177 |
+
└── LICENSE
|
| 178 |
+
```
|
| 179 |
+
|
| 180 |
+
---
|
| 181 |
+
|
| 182 |
+
## 🔍 Example Usage
|
| 183 |
+
|
| 184 |
+
**Training**
|
| 185 |
+
```bash
|
| 186 |
+
python fine_tune_qg.py
|
| 187 |
+
```
|
| 188 |
+
|
| 189 |
+
**Generating**
|
| 190 |
+
```bash
|
| 191 |
+
python generate_question.py
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
Example:
|
| 195 |
+
```
|
| 196 |
+
Nhập đoạn văn bản:
|
| 197 |
+
Cà phê sữa đá là đồ uống nổi tiếng ở Việt Nam.
|
| 198 |
+
|
| 199 |
+
Nhập vào số lượng câu hỏi bạn cần: 5
|
| 200 |
+
|
| 201 |
+
✅ Các câu hỏi mới được sinh ra:
|
| 202 |
+
1. Loại cà phê nào nổi tiếng ở Việt Nam?
|
| 203 |
+
2. Tại sao cà phê sữa đá được yêu thích?
|
| 204 |
+
3. Cà phê sữa đá gồm những nguyên liệu gì?
|
| 205 |
+
4. Nguồn gốc của cà phê sữa đá là từ đâu?
|
| 206 |
+
5. Cà phê sữa đá Việt Nam được pha chế như thế nào?
|
| 207 |
+
```
|
| 208 |
+
|
| 209 |
+
---
|
| 210 |
+
|
| 211 |
+
## 🤝 Contribution
|
| 212 |
+
|
| 213 |
+
You’re welcome to:
|
| 214 |
+
- Open issues
|
| 215 |
+
- Submit pull requests
|
| 216 |
+
- Suggest new datasets
|
| 217 |
+
|
| 218 |
+
---
|
| 219 |
+
|
| 220 |
+
## 📄 License
|
| 221 |
+
|
| 222 |
+
Licensed under the MIT License – see the `LICENSE` file for details.
|
| 223 |
+
|
| 224 |
+
---
|
| 225 |
+
|
| 226 |
+
## 📬 Contact
|
| 227 |
+
|
| 228 |
+
- **Ha Nguyen-Tien** (Corresponding author)
|
| 229 |
+
Email: nguyentienha@hvu.edu.vn
|
| 230 |
+
|
| 231 |
+
- **Phuc Le-Hong**
|
| 232 |
+
Email: Lehongphuc20021408@gmail.com
|
| 233 |
+
|
| 234 |
+
- **DANG DO CAO**
|
| 235 |
+
Email: docaodang532001@gmail.com
|
| 236 |
+
|
| 237 |
+
---
|
| 238 |
+
|
| 239 |
+
*This repository is part of an effort to advance Vietnamese NLP by making question generation more accessible for researchers and developers.*
|
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, # vẫn truyền để bạn có thể eval thủ công sau
|
| 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()
|
generate_question.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 = "30ktrain.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 |
+
)
|