DANGDOCAO commited on
Commit
5bca8c0
·
verified ·
1 Parent(s): 76b4b05

Upload file train, README and LICENSE

Browse files
Files changed (6) hide show
  1. .gitattributes +1 -0
  2. LICENSE.txt +36 -0
  3. README.md +26 -0
  4. fine_tune_qg.py +102 -0
  5. generate_question.py +154 -0
  6. train-QA-v2.0.json +3 -0
.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ train-QA-v2.0.json filter=lfs diff=lfs merge=lfs -text
LICENSE.txt ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License (for code)
2
+ ======================
3
+
4
+ Copyright (c) 2025 Dang Do Cao
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
23
+
24
+ ---
25
+
26
+ CC BY 4.0 License (for dataset)
27
+ ===============================
28
+
29
+ You are free to:
30
+ - Share — copy and redistribute the material in any medium or format
31
+ - Adapt — remix, transform, and build upon the material for any purpose, even commercially.
32
+
33
+ Under the following terms:
34
+ - Attribution — You must give appropriate credit, provide a link to the license, and indicate if changes were made.
35
+
36
+ License details: https://creativecommons.org/licenses/by/4.0/
README.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: "Vietnamese Question Answering Dataset"
3
+ license: cc-by-4.0
4
+ language:
5
+ - vi
6
+ task_categories:
7
+ - question-answering
8
+ tags:
9
+ - vietnamese
10
+ - nlp
11
+ - dataset
12
+ ---
13
+
14
+ # Vietnamese Question Answering Dataset
15
+
16
+ ## Mô tả
17
+ Bộ dữ liệu này gồm các câu hỏi và câu trả lời tiếng Việt, được thiết kế cho các tác vụ **Question Answering** trong nghiên cứu và ứng dụng NLP.
18
+
19
+ ## Cấu trúc dữ liệu
20
+ - **train.jsonl** (~80%)
21
+ - **validation.jsonl** (~10%)
22
+ - **test.jsonl** (~10%)
23
+
24
+ Mỗi dòng là một đối tượng JSON:
25
+ ```json
26
+ {"question": "Câu hỏi?", "answer": "Câu trả lời", "context": "Đoạn văn bản liên quan"}
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 = "train-QA-v2.0.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 = "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
+ )
train-QA-v2.0.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1989e727e0bb58732b6cd569c87fe2e474816d69064d0769f34cd307544d2fa
3
+ size 11786416