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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import hashlib
5
+ import json
6
+ import os
7
+ import re
8
+ import shutil
9
+ import sys
10
+ import tempfile
11
+ import threading
12
+ import warnings
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
17
+ if os.environ.get("PYTORCH_CUDA_ALLOC_CONF") == "expandable_segments:True":
18
+ os.environ.pop("PYTORCH_CUDA_ALLOC_CONF", None)
19
+ os.environ.setdefault("TRANSFORMERS_NO_ADVISORY_WARNINGS", "1")
20
+ warnings.filterwarnings("ignore", message=r"You are using the default legacy behaviour.*")
21
+ warnings.filterwarnings("ignore", message=r"Special tokens have been added.*")
22
+
23
+
24
+ def raise_missing_dependency_error(exc: ModuleNotFoundError) -> None:
25
+ raise SystemExit(f"Thiếu thư viện Python: {exc.name}") from exc
26
+
27
+
28
+ try:
29
+ import torch
30
+ from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
31
+ from transformers import logging as transformers_logging
32
+ from transformers.utils import is_torch_available
33
+ except ModuleNotFoundError as exc:
34
+ raise_missing_dependency_error(exc)
35
+
36
+ transformers_logging.set_verbosity_error()
37
+
38
+ if not is_torch_available():
39
+ raise SystemExit("Transformers không nhận PyTorch trong môi trường hiện tại.")
40
+
41
+
42
+ APP_TITLE = "Hệ thống sinh câu hỏi"
43
+ TASK_PREFIX = "sinh câu hỏi"
44
+ QUESTION_LIMIT = 100
45
+ TOKENIZER_FILES = (
46
+ "config.json",
47
+ "special_tokens_map.json",
48
+ "spiece.model",
49
+ "tokenizer.json",
50
+ "tokenizer_config.json",
51
+ "added_tokens.json",
52
+ )
53
+ GENERATION_PASSES = (
54
+ (0.9, 0.95, None, 1, 4),
55
+ (1.0, 0.97, 16, 1, 5),
56
+ (1.08, 0.99, 8, 2, 6),
57
+ )
58
+
59
+
60
+ def normalize_text(text: Any) -> str:
61
+ return " ".join(str(text or "").split())
62
+
63
+
64
+ def unique_text(items: list[str]) -> list[str]:
65
+ seen: set[str] = set()
66
+ output: list[str] = []
67
+ for item in items:
68
+ value = normalize_text(item)
69
+ key = value.lower()
70
+ if key and key not in seen:
71
+ seen.add(key)
72
+ output.append(value)
73
+ return output
74
+
75
+
76
+ def parse_question_count(value: Any, default: int = 5) -> int:
77
+ try:
78
+ parsed = int(value)
79
+ except (TypeError, ValueError):
80
+ parsed = default
81
+ return max(1, min(parsed, QUESTION_LIMIT))
82
+
83
+
84
+ def format_questions(items: list[str]) -> str:
85
+ if not items:
86
+ return "Không sinh được câu hỏi phù hợp."
87
+ return "\n".join(f"{index}. {item}" for index, item in enumerate(items, 1))
88
+
89
+
90
+ def as_bool(value: str | None, default: bool = False) -> bool:
91
+ if value is None:
92
+ return default
93
+ return value.strip().lower() in {"1", "true", "yes", "y", "on"}
94
+
95
+
96
+ def resolve_model_dir(model_dir: str | Path, prefer_nested_model: bool = True) -> Path:
97
+ model_root = Path(model_dir).expanduser().resolve()
98
+ nested_candidates = [model_root / "best-model", model_root / "final-model"]
99
+ candidates = [*nested_candidates, model_root] if prefer_nested_model else [model_root, *nested_candidates]
100
+ for candidate in candidates:
101
+ if candidate.is_dir() and (candidate / "config.json").exists():
102
+ return candidate
103
+ raise FileNotFoundError(f"Không tìm thấy thư mục mô hình hợp lệ: {model_root}")
104
+
105
+
106
+ def path_needs_ascii_mirror(path: Path) -> bool:
107
+ try:
108
+ str(path).encode("ascii")
109
+ except UnicodeEncodeError:
110
+ return True
111
+ return False
112
+
113
+
114
+ def resolve_tokenizer_dir(model_dir: Path) -> Path:
115
+ if not path_needs_ascii_mirror(model_dir):
116
+ return model_dir
117
+
118
+ digest = hashlib.sha1(str(model_dir).encode("utf-8")).hexdigest()[:16]
119
+ cache_base = Path(os.getenv("LOCALAPPDATA") or tempfile.gettempdir())
120
+ tokenizer_dir = cache_base / "HVU_QA" / "tokenizer_cache" / digest
121
+ tokenizer_dir.mkdir(parents=True, exist_ok=True)
122
+
123
+ copied = False
124
+ for filename in TOKENIZER_FILES:
125
+ source = model_dir / filename
126
+ if not source.exists():
127
+ continue
128
+ destination = tokenizer_dir / filename
129
+ if destination.exists() and destination.stat().st_size == source.stat().st_size:
130
+ continue
131
+ shutil.copy2(source, destination)
132
+ copied = True
133
+
134
+ if copied:
135
+ marker = tokenizer_dir / "source_model_dir.txt"
136
+ marker.write_text(str(model_dir), encoding="utf-8")
137
+
138
+ return tokenizer_dir
139
+
140
+
141
+ def parse_dtype(value: str) -> torch.dtype:
142
+ normalized = value.strip().lower()
143
+ mapping = {
144
+ "float16": torch.float16,
145
+ "fp16": torch.float16,
146
+ "float32": torch.float32,
147
+ "fp32": torch.float32,
148
+ "bfloat16": torch.bfloat16,
149
+ "bf16": torch.bfloat16,
150
+ }
151
+ if normalized not in mapping:
152
+ raise ValueError(f"Không hỗ trợ gpu_dtype={value}")
153
+ return mapping[normalized]
154
+
155
+
156
+ class QuestionGenerator:
157
+ def __init__(
158
+ self,
159
+ model_dir: str | Path = "t5-viet-qg-finetuned",
160
+ task_prefix: str = TASK_PREFIX,
161
+ max_source_length: int = 512,
162
+ max_new_tokens: int = 64,
163
+ device: str = "auto",
164
+ cpu_threads: int | None = None,
165
+ gpu_dtype: str = "auto",
166
+ prefer_nested_model: bool = True,
167
+ ) -> None:
168
+ self.model_root = Path(model_dir).expanduser().resolve()
169
+ self.model_dir = resolve_model_dir(model_dir, prefer_nested_model=prefer_nested_model)
170
+ self.task_prefix = task_prefix
171
+ self.max_source_length = max_source_length
172
+ self.max_new_tokens = max_new_tokens
173
+ self.requested_device = device
174
+ self.cpu_threads = cpu_threads
175
+ self.gpu_dtype = gpu_dtype
176
+ self.prefer_nested_model = prefer_nested_model
177
+ self.device: torch.device | None = None
178
+ self.dtype: torch.dtype | None = None
179
+ self.tokenizer = None
180
+ self.model = None
181
+ self._load_lock = threading.Lock()
182
+
183
+ def _resolve_device(self) -> torch.device:
184
+ requested = self.requested_device.lower()
185
+ if requested == "cpu":
186
+ return torch.device("cpu")
187
+ if requested == "cuda":
188
+ if not torch.cuda.is_available():
189
+ raise RuntimeError("Bạn đã chọn device=cuda nhưng máy hiện tại không có CUDA.")
190
+ return torch.device("cuda")
191
+ return torch.device("cuda" if torch.cuda.is_available() else "cpu")
192
+
193
+ def _resolve_dtype(self) -> torch.dtype:
194
+ if self.device is None or self.device.type != "cuda":
195
+ return torch.float32
196
+ if self.gpu_dtype == "auto":
197
+ if hasattr(torch.cuda, "is_bf16_supported") and torch.cuda.is_bf16_supported():
198
+ return torch.bfloat16
199
+ return torch.float16
200
+ return parse_dtype(self.gpu_dtype)
201
+
202
+ def _configure_runtime(self) -> None:
203
+ if self.device is None:
204
+ return
205
+ if self.device.type == "cpu":
206
+ if self.cpu_threads:
207
+ torch.set_num_threads(max(1, int(self.cpu_threads)))
208
+ if hasattr(torch, "set_num_interop_threads"):
209
+ torch.set_num_interop_threads(max(1, min(int(self.cpu_threads), 4)))
210
+ return
211
+
212
+ if hasattr(torch.backends, "cuda") and hasattr(torch.backends.cuda, "matmul"):
213
+ torch.backends.cuda.matmul.allow_tf32 = True
214
+ if hasattr(torch.backends, "cudnn"):
215
+ torch.backends.cudnn.allow_tf32 = True
216
+ torch.backends.cudnn.benchmark = True
217
+
218
+ def _load_tokenizer(self):
219
+ use_fast = as_bool(os.getenv("HVU_USE_FAST_TOKENIZER"), default=False)
220
+ tokenizer_dir = resolve_tokenizer_dir(self.model_dir)
221
+ try:
222
+ return AutoTokenizer.from_pretrained(str(tokenizer_dir), use_fast=use_fast)
223
+ except Exception:
224
+ if use_fast:
225
+ return AutoTokenizer.from_pretrained(str(tokenizer_dir), use_fast=False)
226
+ if (tokenizer_dir / "tokenizer.json").exists():
227
+ try:
228
+ return AutoTokenizer.from_pretrained(str(tokenizer_dir), use_fast=True)
229
+ except Exception:
230
+ pass
231
+ return AutoTokenizer.from_pretrained(str(tokenizer_dir), use_fast=False)
232
+
233
+ def load(self) -> None:
234
+ if self.model is not None and self.tokenizer is not None:
235
+ return
236
+
237
+ with self._load_lock:
238
+ if self.model is not None and self.tokenizer is not None:
239
+ return
240
+
241
+ self.device = self._resolve_device()
242
+ self.dtype = self._resolve_dtype()
243
+ self._configure_runtime()
244
+
245
+ model_kwargs: dict[str, Any] = {}
246
+ if self.device.type == "cuda":
247
+ model_kwargs["torch_dtype"] = self.dtype
248
+ model_kwargs["low_cpu_mem_usage"] = True
249
+
250
+ self.tokenizer = self._load_tokenizer()
251
+ self.model = AutoModelForSeq2SeqLM.from_pretrained(str(self.model_dir), **model_kwargs)
252
+ self.model.to(self.device)
253
+ self.model.eval()
254
+
255
+ def metadata(self) -> dict[str, Any]:
256
+ active_device = self.device.type if self.device is not None else None
257
+ predicted_device = "cuda" if torch.cuda.is_available() and self.requested_device != "cpu" else "cpu"
258
+ return {
259
+ "title": APP_TITLE,
260
+ "model_root": str(self.model_root),
261
+ "model_dir": str(self.model_dir),
262
+ "requested_device": self.requested_device,
263
+ "active_device": active_device,
264
+ "predicted_device": predicted_device,
265
+ "loaded": self.model is not None,
266
+ "gpu_available": torch.cuda.is_available(),
267
+ "gpu_dtype": None if self.dtype is None else str(self.dtype).replace("torch.", ""),
268
+ "cpu_threads": torch.get_num_threads(),
269
+ }
270
+
271
+ def _candidate_answers(self, text: str, limit: int) -> list[str]:
272
+ text = normalize_text(text)
273
+ if not text:
274
+ return []
275
+
276
+ candidates: list[str] = []
277
+ split_pattern = r"(?<=[.!?])\s+|\n+"
278
+ for sentence in [normalize_text(part) for part in re.split(split_pattern, text) if normalize_text(part)]:
279
+ if 3 <= len(sentence.split()) <= 30:
280
+ candidates.append(sentence)
281
+ for clause in (normalize_text(part) for part in re.split(r"\s*[,;:]\s*", sentence)):
282
+ if 3 <= len(clause.split()) <= 20:
283
+ candidates.append(clause)
284
+
285
+ if not candidates:
286
+ words = text.split()
287
+ candidates = [" ".join(words[: min(12, len(words))])] if words else [text]
288
+
289
+ ranked = sorted(unique_text(candidates), key=lambda item: (abs(len(item.split()) - 10), len(item)))
290
+ return ranked[:limit]
291
+
292
+ def _build_prompt(self, context: str, answer: str) -> str:
293
+ return f"{self.task_prefix}:\nngữ cảnh: {context}\nđáp án: {answer}"
294
+
295
+ @torch.inference_mode()
296
+ def _sample(self, context: str, answer: str, count: int, temperature: float, top_p: float) -> list[str]:
297
+ if self.tokenizer is None or self.model is None or self.device is None:
298
+ raise RuntimeError("Model chưa được load.")
299
+
300
+ inputs = self.tokenizer(
301
+ self._build_prompt(context, answer),
302
+ return_tensors="pt",
303
+ truncation=True,
304
+ max_length=self.max_source_length,
305
+ ).to(self.device)
306
+ outputs = self.model.generate(
307
+ **inputs,
308
+ max_new_tokens=self.max_new_tokens,
309
+ do_sample=True,
310
+ temperature=temperature,
311
+ top_p=top_p,
312
+ num_return_sequences=count,
313
+ no_repeat_ngram_size=3,
314
+ repetition_penalty=1.1,
315
+ )
316
+ questions: list[str] = []
317
+ for token_ids in outputs:
318
+ question = normalize_text(self.tokenizer.decode(token_ids, skip_special_tokens=True))
319
+ if question:
320
+ questions.append(question if question.endswith("?") else f"{question}?")
321
+ return [question for question in unique_text(questions) if len(question.split()) >= 3]
322
+
323
+ @torch.inference_mode()
324
+ def _beam_search(self, context: str, answer: str, count: int) -> list[str]:
325
+ if self.tokenizer is None or self.model is None or self.device is None:
326
+ raise RuntimeError("Model chưa được load.")
327
+
328
+ inputs = self.tokenizer(
329
+ self._build_prompt(context, answer),
330
+ return_tensors="pt",
331
+ truncation=True,
332
+ max_length=self.max_source_length,
333
+ ).to(self.device)
334
+ outputs = self.model.generate(
335
+ **inputs,
336
+ max_new_tokens=self.max_new_tokens,
337
+ num_beams=max(4, count),
338
+ num_return_sequences=min(count, 4),
339
+ early_stopping=True,
340
+ no_repeat_ngram_size=3,
341
+ repetition_penalty=1.1,
342
+ )
343
+ questions: list[str] = []
344
+ for token_ids in outputs:
345
+ question = normalize_text(self.tokenizer.decode(token_ids, skip_special_tokens=True))
346
+ if question:
347
+ questions.append(question if question.endswith("?") else f"{question}?")
348
+ return [question for question in unique_text(questions) if len(question.split()) >= 3]
349
+
350
+ def generate(self, text: str, count: int = 5) -> list[str]:
351
+ self.load()
352
+ context = normalize_text(text)
353
+ if not context:
354
+ raise ValueError("Vui lòng nhập đoạn văn.")
355
+
356
+ count = parse_question_count(count)
357
+ pool = unique_text(
358
+ self._candidate_answers(context, max(32, count * 5)) + [context[:180], context[:280], context]
359
+ )
360
+ output: list[str] = []
361
+ seen: set[str] = set()
362
+
363
+ for temperature, top_p, limit, rounds, floor in GENERATION_PASSES:
364
+ answers = pool[:limit] if limit else pool
365
+ for _ in range(rounds):
366
+ for answer in answers:
367
+ remaining = count - len(output)
368
+ if remaining <= 0:
369
+ return output[:count]
370
+ sample_count = min(8, max(floor, remaining * 2))
371
+ for question in self._sample(context, answer, sample_count, temperature, top_p):
372
+ key = question.lower()
373
+ if key not in seen:
374
+ seen.add(key)
375
+ output.append(question)
376
+ if len(output) >= count:
377
+ return output[:count]
378
+
379
+ for answer in pool[: min(8, len(pool))]:
380
+ remaining = count - len(output)
381
+ if remaining <= 0:
382
+ break
383
+ for question in self._beam_search(context, answer, remaining):
384
+ key = question.lower()
385
+ if key not in seen:
386
+ seen.add(key)
387
+ output.append(question)
388
+ if len(output) >= count:
389
+ break
390
+
391
+ return output[:count]
392
+
393
+
394
+ def read_input_text(args: argparse.Namespace) -> str:
395
+ if args.text:
396
+ return args.text
397
+ if args.input_file:
398
+ return Path(args.input_file).read_text(encoding="utf-8")
399
+ if sys.stdin.isatty():
400
+ return input("Nhập đoạn văn cần sinh câu hỏi:\n").strip()
401
+ return sys.stdin.read().strip()
402
+
403
+
404
+ def read_question_count(args: argparse.Namespace) -> int:
405
+ if args.num_questions is not None:
406
+ return parse_question_count(args.num_questions)
407
+ if args.text or args.input_file or not sys.stdin.isatty():
408
+ return parse_question_count(None)
409
+
410
+ while True:
411
+ raw_value = input(f"Nhập số lượng câu hỏi cần sinh (1-{QUESTION_LIMIT}): ").strip()
412
+ if not raw_value:
413
+ print("Vui lòng nhập số lượng câu hỏi cần sinh.")
414
+ continue
415
+ try:
416
+ parsed = int(raw_value)
417
+ except ValueError:
418
+ print("Vui lòng nhập một số nguyên.")
419
+ continue
420
+ if 1 <= parsed <= QUESTION_LIMIT:
421
+ return parsed
422
+ print(f"Số lượng câu hỏi phải nằm trong khoảng 1 đến {QUESTION_LIMIT}.")
423
+
424
+
425
+ def build_parser() -> argparse.ArgumentParser:
426
+ parser = argparse.ArgumentParser()
427
+ parser.add_argument("--model_dir", default="t5-viet-qg-finetuned")
428
+ parser.add_argument("--task_prefix", default=TASK_PREFIX)
429
+ parser.add_argument("--max_source_length", type=int, default=512)
430
+ parser.add_argument("--max_new_tokens", type=int, default=64)
431
+ parser.add_argument("--num_questions", type=int, default=None)
432
+ parser.add_argument("--device", choices=["auto", "cpu", "cuda"], default="auto")
433
+ parser.add_argument("--cpu_threads", type=int, default=None)
434
+ parser.add_argument("--gpu_dtype", default="auto")
435
+ parser.add_argument("--text", default=None)
436
+ parser.add_argument("--input_file", default=None)
437
+ parser.add_argument("--output_format", choices=["text", "json"], default="text")
438
+ return parser
439
+
440
+
441
+ def main() -> None:
442
+ if hasattr(sys.stdout, "reconfigure"):
443
+ sys.stdout.reconfigure(encoding="utf-8")
444
+ if hasattr(sys.stderr, "reconfigure"):
445
+ sys.stderr.reconfigure(encoding="utf-8")
446
+ args = build_parser().parse_args()
447
+ generator = QuestionGenerator(
448
+ model_dir=args.model_dir,
449
+ task_prefix=args.task_prefix,
450
+ max_source_length=args.max_source_length,
451
+ max_new_tokens=args.max_new_tokens,
452
+ device=args.device,
453
+ cpu_threads=args.cpu_threads,
454
+ gpu_dtype=args.gpu_dtype,
455
+ prefer_nested_model=True,
456
+ )
457
+ text = read_input_text(args)
458
+ question_count = read_question_count(args)
459
+ questions = generator.generate(text, question_count)
460
+ payload = {
461
+ "text": normalize_text(text),
462
+ "questions": questions,
463
+ "formatted": format_questions(questions),
464
+ "meta": generator.metadata(),
465
+ }
466
+ if args.output_format == "json":
467
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
468
+ return
469
+ print(payload["formatted"])
470
+
471
+
472
+ if __name__ == "__main__":
473
+ main()