DANGDOCAO commited on
Commit
5cd5764
·
verified ·
1 Parent(s): 5568861
Files changed (1) hide show
  1. HVU_QA/HVU_QA_tool.py +1851 -0
HVU_QA/HVU_QA_tool.py ADDED
@@ -0,0 +1,1851 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import csv
5
+ import fnmatch
6
+ import importlib.metadata
7
+ import importlib.util
8
+ import json
9
+ import logging
10
+ import os
11
+ import platform
12
+ import socket
13
+ import shutil
14
+ import subprocess
15
+ import sys
16
+ import time
17
+ import traceback
18
+ import urllib.error
19
+ import urllib.request
20
+ import webbrowser
21
+ from dataclasses import dataclass
22
+ from pathlib import Path
23
+ from typing import Optional
24
+
25
+ SCRIPT_ROOT = Path(__file__).resolve().parent
26
+ PLATFORM_SYSTEM = platform.system().lower()
27
+ IS_WINDOWS = os.name == "nt"
28
+ IS_MACOS = PLATFORM_SYSTEM == "darwin"
29
+ IS_LINUX = PLATFORM_SYSTEM == "linux"
30
+ MIN_PYTHON = (3, 10)
31
+ TOOL_VENV_DIR = SCRIPT_ROOT / ".hvu_qa_env"
32
+ TOOL_VENV_PYTHON = TOOL_VENV_DIR / ("Scripts/python.exe" if IS_WINDOWS else "bin/python")
33
+ CONFIG_FILE = SCRIPT_ROOT / ".hvu_qa_config.json"
34
+ LOG_DIR = SCRIPT_ROOT / "logs"
35
+ LOG_FILE = LOG_DIR / "HVU_QA_tool.log"
36
+
37
+ HF_DATASET_REPO_ID = "DANGDOCAO/GeneratingQuestions"
38
+ HF_DATASET_REVISION = "main"
39
+ HF_PROJECT_SUBDIR = "HVU_QA"
40
+ HF_MODEL_SUBDIR = f"{HF_PROJECT_SUBDIR}/t5-viet-qg-finetuned"
41
+ HF_BEST_MODEL_SUBDIR = f"{HF_MODEL_SUBDIR}/best-model"
42
+
43
+ HF_HUB_REQUIREMENT = "huggingface_hub>=0.23.0,<1.0.0"
44
+ TORCH_REQUIREMENT = "torch>=2.2.0,<3.0.0"
45
+ RUNTIME_REQUIREMENTS = [
46
+ "accelerate>=1.1.0,<2.0.0",
47
+ "Flask>=3.0.0,<4.0.0",
48
+ "flask-cors>=4.0.0,<7.0.0",
49
+ HF_HUB_REQUIREMENT,
50
+ "numpy>=1.26.0,<2.0.0",
51
+ "packaging>=23.2,<26.0",
52
+ "requests>=2.31.0,<3.0.0",
53
+ "safetensors>=0.4.3,<1.0.0",
54
+ "sentencepiece>=0.2.0,<1.0.0",
55
+ TORCH_REQUIREMENT,
56
+ "tqdm>=4.66.0,<5.0.0",
57
+ "transformers>=4.41.0,<4.42.0",
58
+ ]
59
+ DEPENDENCY_IMPORTS = {
60
+ "accelerate": "accelerate",
61
+ "Flask": "flask",
62
+ "flask-cors": "flask_cors",
63
+ "huggingface_hub": "huggingface_hub",
64
+ "numpy": "numpy",
65
+ "packaging": "packaging",
66
+ "requests": "requests",
67
+ "safetensors": "safetensors",
68
+ "sentencepiece": "sentencepiece",
69
+ "tqdm": "tqdm",
70
+ "transformers": "transformers",
71
+ }
72
+ LOCAL_PROJECT_MARKERS = [
73
+ "main.py",
74
+ "backend/app.py",
75
+ "frontend/index.html",
76
+ "generate_question.py",
77
+ ]
78
+ RUNTIME_REQUIRED_FILES = [
79
+ "requirements.txt",
80
+ "main.py",
81
+ "backend/app.py",
82
+ "generate_question.py",
83
+ "frontend/index.html",
84
+ ]
85
+ RUNTIME_ALLOW_PATTERNS = [
86
+ f"{HF_PROJECT_SUBDIR}/requirements.txt",
87
+ f"{HF_PROJECT_SUBDIR}/main.py",
88
+ f"{HF_PROJECT_SUBDIR}/generate_question.py",
89
+ f"{HF_PROJECT_SUBDIR}/backend/**",
90
+ f"{HF_PROJECT_SUBDIR}/frontend/**",
91
+ ]
92
+ RUNTIME_IGNORE_PATTERNS = [
93
+ f"{HF_PROJECT_SUBDIR}/**/__pycache__/**",
94
+ f"{HF_PROJECT_SUBDIR}/**/*.pyc",
95
+ ]
96
+ MODEL_IGNORE_PATTERNS = [
97
+ f"{HF_MODEL_SUBDIR}/checkpoint-*/**",
98
+ f"{HF_MODEL_SUBDIR}/all_results.json",
99
+ f"{HF_MODEL_SUBDIR}/eval_results.json",
100
+ f"{HF_MODEL_SUBDIR}/train_results.json",
101
+ f"{HF_MODEL_SUBDIR}/trainer_state.json",
102
+ f"{HF_MODEL_SUBDIR}/training_summary.json",
103
+ f"{HF_MODEL_SUBDIR}/training_args.bin",
104
+ f"{HF_BEST_MODEL_SUBDIR}/training_args.bin",
105
+ ]
106
+ PYTORCH_CPU_INDEX_URL = "https://download.pytorch.org/whl/cpu"
107
+ VC_REDIST_X64_URL = "https://aka.ms/vc14/vc_redist.x64.exe"
108
+ VC_REDIST_CACHE = SCRIPT_ROOT / ".hvu_qa_cache" / "vc_redist.x64.exe"
109
+ VC_REDIST_SUCCESS_CODES = {0, 1638, 3010}
110
+
111
+
112
+ @dataclass(frozen=True)
113
+ class RuntimeContext:
114
+ root: Path
115
+ main_file: Path
116
+ requirements_file: Path
117
+ local_model_dir: Path
118
+ local_best_model_dir: Path
119
+ standalone_mode: bool
120
+
121
+
122
+ @dataclass(frozen=True)
123
+ class GpuInfo:
124
+ name: str
125
+ driver_version: Optional[str] = None
126
+ compute_capability: Optional[str] = None
127
+ vendor: str = "NVIDIA"
128
+
129
+
130
+ @dataclass(frozen=True)
131
+ class SystemProfile:
132
+ os_key: str
133
+ os_label: str
134
+ platform_name: str
135
+ release: str
136
+ machine: str
137
+ processor: str
138
+ python_version: str
139
+ python_bits: int
140
+ python_executable: str
141
+
142
+ @property
143
+ def is_64bit_python(self) -> bool:
144
+ return self.python_bits == 64
145
+
146
+ @property
147
+ def is_arm64(self) -> bool:
148
+ return self.machine.lower() in {"arm64", "aarch64"}
149
+
150
+ @property
151
+ def is_x64(self) -> bool:
152
+ return self.machine.lower() in {"amd64", "x86_64", "x64"}
153
+
154
+
155
+ @dataclass(frozen=True)
156
+ class PytorchCudaWheel:
157
+ tag: str
158
+ index_url: str
159
+ min_driver_major: int
160
+ min_driver_minor: int = 0
161
+ torch_requirement: str = TORCH_REQUIREMENT
162
+ companion_requirements: tuple[str, ...] = ()
163
+
164
+
165
+ # Ordered from newest to oldest. The launcher chooses the newest CUDA wheel
166
+ # that the detected NVIDIA driver can run.
167
+ PYTORCH_CUDA_WHEELS = [
168
+ PytorchCudaWheel("cu128", "https://download.pytorch.org/whl/cu128", 572, 0),
169
+ PytorchCudaWheel("cu126", "https://download.pytorch.org/whl/cu126", 560, 0),
170
+ PytorchCudaWheel("cu118", "https://download.pytorch.org/whl/cu118", 522, 0),
171
+ PytorchCudaWheel(
172
+ "cu117",
173
+ "https://download.pytorch.org/whl/cu117",
174
+ 516,
175
+ 1,
176
+ "torch==2.0.1+cu117",
177
+ ("numpy>=1.26.0,<2.0.0", "transformers>=4.41.0,<4.42.0"),
178
+ ),
179
+ ]
180
+
181
+
182
+ def setup_logging() -> None:
183
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
184
+ logging.basicConfig(
185
+ level=logging.INFO,
186
+ format="%(asctime)s [%(levelname)s] %(message)s",
187
+ handlers=[
188
+ logging.FileHandler(LOG_FILE, encoding="utf-8"),
189
+ ],
190
+ )
191
+
192
+
193
+ def print_step(message: str) -> None:
194
+ text = f"[HVU_QA_tool] {message}"
195
+ logging.info(message)
196
+ try:
197
+ print(text)
198
+ except UnicodeEncodeError:
199
+ encoding = getattr(sys.stdout, "encoding", None) or "utf-8"
200
+ safe_text = text.encode(encoding, errors="backslashreplace").decode(encoding, errors="ignore")
201
+ print(safe_text)
202
+
203
+
204
+ def load_config() -> dict[str, object]:
205
+ if not CONFIG_FILE.exists():
206
+ return {}
207
+ try:
208
+ payload = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
209
+ except (OSError, json.JSONDecodeError):
210
+ return {}
211
+ return payload if isinstance(payload, dict) else {}
212
+
213
+
214
+ def save_config(config: dict[str, object]) -> None:
215
+ CONFIG_FILE.write_text(json.dumps(config, ensure_ascii=False, indent=2), encoding="utf-8")
216
+
217
+
218
+ def update_config(**values: object) -> None:
219
+ config = load_config()
220
+ config.update(values)
221
+ save_config(config)
222
+
223
+
224
+ def python_version_label() -> str:
225
+ return ".".join(str(part) for part in sys.version_info[:3])
226
+
227
+
228
+ def collect_system_profile() -> SystemProfile:
229
+ if IS_WINDOWS:
230
+ os_key = "windows"
231
+ os_label = "Windows"
232
+ elif IS_MACOS:
233
+ os_key = "macos"
234
+ os_label = "macOS"
235
+ elif IS_LINUX:
236
+ os_key = "linux"
237
+ os_label = "Linux"
238
+ else:
239
+ os_key = PLATFORM_SYSTEM or sys.platform
240
+ os_label = platform.system() or sys.platform
241
+
242
+ return SystemProfile(
243
+ os_key=os_key,
244
+ os_label=os_label,
245
+ platform_name=sys.platform,
246
+ release=platform.release(),
247
+ machine=platform.machine() or "unknown",
248
+ processor=platform.processor() or "unknown",
249
+ python_version=python_version_label(),
250
+ python_bits=64 if sys.maxsize > 2**32 else 32,
251
+ python_executable=sys.executable,
252
+ )
253
+
254
+
255
+ def system_profile_config(profile: SystemProfile) -> dict[str, object]:
256
+ return {
257
+ "os": profile.os_key,
258
+ "os_label": profile.os_label,
259
+ "platform": profile.platform_name,
260
+ "release": profile.release,
261
+ "machine": profile.machine,
262
+ "processor": profile.processor,
263
+ "python_version": profile.python_version,
264
+ "python_bits": profile.python_bits,
265
+ "python_executable": profile.python_executable,
266
+ }
267
+
268
+
269
+ def format_system_profile(profile: SystemProfile) -> str:
270
+ arch_label = "ARM64" if profile.is_arm64 else ("x64" if profile.is_x64 else profile.machine)
271
+ return (
272
+ f"{profile.os_label} {profile.release} ({arch_label}), "
273
+ f"Python {profile.python_version} {profile.python_bits}-bit"
274
+ )
275
+
276
+
277
+ def validate_system_profile(profile: SystemProfile) -> None:
278
+ if profile.os_key not in {"windows", "macos", "linux"}:
279
+ raise RuntimeError(
280
+ f"Hệ điều hành {profile.os_label} chưa được hỗ trợ tự động. "
281
+ "Tool hiện hỗ trợ Windows, macOS và Linux."
282
+ )
283
+ if not profile.is_64bit_python:
284
+ raise RuntimeError(
285
+ "Python hiện tại là bản 32-bit nên không phù hợp để cài PyTorch/model NLP. "
286
+ "Vui lòng cài Python 64-bit rồi chạy lại `python HVU_QA_tool.py`."
287
+ )
288
+
289
+
290
+ def check_python_version() -> None:
291
+ if sys.version_info >= MIN_PYTHON:
292
+ return
293
+ required = ".".join(str(part) for part in MIN_PYTHON)
294
+ raise RuntimeError(
295
+ f"Python hiện tại là {python_version_label()}, chưa phù hợp. "
296
+ f"Vui lòng cài Python {required} trở lên rồi chạy lại `python HVU_QA_tool.py`."
297
+ )
298
+
299
+
300
+ def check_python_module(module_name: str, friendly_name: str) -> None:
301
+ completed = subprocess.run(
302
+ [sys.executable, "-m", module_name, "--help"],
303
+ capture_output=True,
304
+ text=True,
305
+ encoding="utf-8",
306
+ errors="replace",
307
+ check=False,
308
+ )
309
+ if completed.returncode != 0:
310
+ raise RuntimeError(
311
+ f"Python hiện tại chưa dùng được module `{module_name}` ({friendly_name}). "
312
+ "Hãy cài lại Python và bật tùy chọn pip/venv khi cài đặt."
313
+ )
314
+
315
+
316
+ def check_write_access(path: Path) -> None:
317
+ path.mkdir(parents=True, exist_ok=True)
318
+ probe = path / ".hvu_write_test"
319
+ try:
320
+ probe.write_text("ok", encoding="utf-8")
321
+ probe.unlink(missing_ok=True)
322
+ except OSError as exc:
323
+ raise RuntimeError(f"Không có quyền ghi vào thư mục {path}: {exc}") from exc
324
+
325
+
326
+ def has_complete_runtime(context: RuntimeContext) -> bool:
327
+ return all((context.root / relative).exists() for relative in RUNTIME_REQUIRED_FILES)
328
+
329
+
330
+ def has_complete_model(context: RuntimeContext, best_model_only: bool) -> bool:
331
+ return all(path.exists() for path in required_model_files(context, best_model_only))
332
+
333
+
334
+ def internet_available(url: str = "https://huggingface.co", timeout: int = 8) -> bool:
335
+ try:
336
+ with urllib.request.urlopen(url, timeout=timeout):
337
+ return True
338
+ except (OSError, urllib.error.URLError):
339
+ return False
340
+
341
+
342
+ def check_internet_if_needed(context: RuntimeContext, args: argparse.Namespace) -> None:
343
+ needs_runtime = args.force_download or args.force_runtime_refresh or not has_complete_runtime(context)
344
+ needs_model = args.force_download or not has_complete_model(context, args.best_model_only)
345
+ if not needs_runtime and not needs_model:
346
+ print_step("Runtime và model đã có sẵn, không cần tải thêm từ Internet.")
347
+ return
348
+ print_step("Đang kiểm tra kết nối Internet...")
349
+ if internet_available():
350
+ return
351
+ raise RuntimeError(
352
+ "Không kết nối được tới Hugging Face. Hãy kiểm tra Internet/proxy rồi chạy lại."
353
+ )
354
+
355
+
356
+ def check_disk_space(path: Path, min_free_gb: float) -> None:
357
+ free_bytes = shutil.disk_usage(path).free
358
+ required_bytes = int(min_free_gb * 1024**3)
359
+ if free_bytes < required_bytes:
360
+ raise RuntimeError(
361
+ f"Dung lượng trống tại {path} chỉ còn {format_bytes(free_bytes)}. "
362
+ f"Cần tối thiểu khoảng {min_free_gb:g} GB để tải và chạy hệ thống."
363
+ )
364
+ print_step(f"Dung lượng trống khả dụng: {format_bytes(free_bytes)}.")
365
+
366
+
367
+ def run_base_preflight(args: argparse.Namespace) -> None:
368
+ print_step("Đang kiểm tra môi trường...")
369
+ check_python_version()
370
+ profile = collect_system_profile()
371
+ print_step(f"Thiết bị phát hiện: {format_system_profile(profile)}.")
372
+ validate_system_profile(profile)
373
+ check_python_module("pip", "pip")
374
+ if not args.no_venv:
375
+ check_python_module("venv", "môi trường ảo")
376
+ check_write_access(SCRIPT_ROOT)
377
+ update_config(system_profile=system_profile_config(profile))
378
+
379
+
380
+ def module_exists(module_name: str) -> bool:
381
+ return importlib.util.find_spec(module_name) is not None
382
+
383
+
384
+ def subprocess_env(env: Optional[dict[str, str]] = None) -> dict[str, str]:
385
+ merged = os.environ.copy()
386
+ merged.setdefault("PYTHONIOENCODING", "utf-8")
387
+ merged.setdefault("PYTHONUTF8", "1")
388
+ merged.setdefault("PIP_NO_COLOR", "1")
389
+ merged.setdefault("PIP_DISABLE_PIP_VERSION_CHECK", "1")
390
+ if env:
391
+ merged.update(env)
392
+ return merged
393
+
394
+
395
+ def run_command(
396
+ command: list[str],
397
+ *,
398
+ cwd: Optional[Path] = None,
399
+ env: Optional[dict[str, str]] = None,
400
+ ) -> None:
401
+ subprocess.check_call(command, cwd=str(cwd) if cwd else None, env=subprocess_env(env))
402
+
403
+
404
+ def try_run_command(
405
+ command: list[str],
406
+ *,
407
+ cwd: Optional[Path] = None,
408
+ env: Optional[dict[str, str]] = None,
409
+ ) -> bool:
410
+ try:
411
+ run_command(command, cwd=cwd, env=env)
412
+ except subprocess.CalledProcessError:
413
+ return False
414
+ return True
415
+
416
+
417
+ def run_command_capture(command: list[str], *, cwd: Optional[Path] = None) -> subprocess.CompletedProcess:
418
+ return subprocess.run(
419
+ command,
420
+ cwd=str(cwd) if cwd else None,
421
+ env=subprocess_env(),
422
+ capture_output=True,
423
+ text=True,
424
+ encoding="utf-8",
425
+ errors="replace",
426
+ check=False,
427
+ )
428
+
429
+
430
+ def is_running_in_virtualenv() -> bool:
431
+ return sys.prefix != getattr(sys, "base_prefix", sys.prefix) or bool(os.getenv("VIRTUAL_ENV"))
432
+
433
+
434
+ def is_running_in_tool_venv() -> bool:
435
+ try:
436
+ return Path(sys.executable).resolve() == TOOL_VENV_PYTHON.resolve()
437
+ except OSError:
438
+ return False
439
+
440
+
441
+ def format_bytes(size: int) -> str:
442
+ units = ["B", "KB", "MB", "GB", "TB"]
443
+ value = float(size)
444
+ for unit in units:
445
+ if value < 1024 or unit == units[-1]:
446
+ if unit == "B":
447
+ return f"{int(value)} {unit}"
448
+ return f"{value:.1f} {unit}"
449
+ value /= 1024
450
+ return f"{size} B"
451
+
452
+
453
+ def render_progress_bar(current: int, total: int, width: int = 28) -> str:
454
+ if total <= 0:
455
+ return "[----------------------------] 0.0%"
456
+ ratio = max(0.0, min(1.0, current / total))
457
+ filled = int(ratio * width)
458
+ return f"[{'#' * filled}{'-' * (width - filled)}] {ratio * 100:5.1f}%"
459
+
460
+
461
+ def matches_any_pattern(path: str, patterns: list[str]) -> bool:
462
+ normalized = path.replace("\\", "/")
463
+ return any(fnmatch.fnmatch(normalized, pattern) for pattern in patterns)
464
+
465
+
466
+ def has_local_project(root: Path) -> bool:
467
+ return all((root / marker).exists() for marker in LOCAL_PROJECT_MARKERS)
468
+
469
+
470
+ def resolve_runtime_context(args: argparse.Namespace) -> RuntimeContext:
471
+ use_local_project = has_local_project(SCRIPT_ROOT) and not args.force_standalone_runtime
472
+ if use_local_project:
473
+ runtime_root = SCRIPT_ROOT
474
+ standalone_mode = False
475
+ else:
476
+ requested_runtime_dir = Path(args.runtime_dir).expanduser()
477
+ if not requested_runtime_dir.is_absolute():
478
+ requested_runtime_dir = SCRIPT_ROOT / requested_runtime_dir
479
+ runtime_root = requested_runtime_dir.resolve()
480
+ standalone_mode = True
481
+
482
+ context = RuntimeContext(
483
+ root=runtime_root,
484
+ main_file=runtime_root / "main.py",
485
+ requirements_file=runtime_root / "requirements.txt",
486
+ local_model_dir=runtime_root / "t5-viet-qg-finetuned",
487
+ local_best_model_dir=runtime_root / "t5-viet-qg-finetuned" / "best-model",
488
+ standalone_mode=standalone_mode,
489
+ )
490
+ mode_label = "standalone" if standalone_mode else "full project"
491
+ print_step(f"Runtime mode: {mode_label}")
492
+ print_step(f"Runtime root: {context.root}")
493
+ return context
494
+
495
+
496
+ def maybe_bootstrap_tool_venv(args: argparse.Namespace) -> Optional[int]:
497
+ if args.no_venv or is_running_in_tool_venv():
498
+ return None
499
+
500
+ if not TOOL_VENV_PYTHON.exists():
501
+ print_step("Không phát hiện virtualenv hiện tại. Đang tạo môi trường riêng cho launcher...")
502
+ run_command([sys.executable, "-m", "venv", str(TOOL_VENV_DIR)], cwd=SCRIPT_ROOT)
503
+ run_command(
504
+ [str(TOOL_VENV_PYTHON), "-m", "pip", "install", "--upgrade", "pip", "setuptools", "wheel"],
505
+ cwd=SCRIPT_ROOT,
506
+ )
507
+
508
+ relaunch_env = os.environ.copy()
509
+ relaunch_env["HVU_QA_TOOL_BOOTSTRAPPED"] = "1"
510
+ relaunch_env = subprocess_env(relaunch_env)
511
+ relaunch_command = [str(TOOL_VENV_PYTHON), str(Path(__file__).resolve()), *sys.argv[1:]]
512
+
513
+ print_step("Đang chuyển sang môi trường Python riêng của launcher...")
514
+ return subprocess.call(relaunch_command, cwd=str(SCRIPT_ROOT), env=relaunch_env)
515
+
516
+
517
+ def ensure_huggingface_hub() -> None:
518
+ if module_exists("huggingface_hub"):
519
+ return
520
+
521
+ if not internet_available():
522
+ raise RuntimeError(
523
+ "Thiếu huggingface_hub và không có Internet để cài tự động. "
524
+ f"Vui lòng kết nối mạng rồi chạy lại: {sys.executable} HVU_QA_tool.py"
525
+ )
526
+ print_step("Thiếu huggingface_hub. Đang cài tự động...")
527
+ run_command([sys.executable, "-m", "pip", "install", HF_HUB_REQUIREMENT], cwd=SCRIPT_ROOT)
528
+
529
+
530
+ def dependency_install_needs_internet(selected_device: str, context: RuntimeContext) -> bool:
531
+ if pending_non_torch_requirement_specs(context):
532
+ return True
533
+ torch_info = inspect_installed_torch()
534
+ if not torch_info.get("installed"):
535
+ return True
536
+ return selected_device == "cuda" and not torch_info.get("cuda_available")
537
+
538
+
539
+ def check_dependency_internet_if_needed(selected_device: str, context: RuntimeContext) -> None:
540
+ if not dependency_install_needs_internet(selected_device, context):
541
+ return
542
+ print_step("Đang kiểm tra Internet trước khi cài thư viện...")
543
+ if internet_available():
544
+ return
545
+ raise RuntimeError(
546
+ "Cần Internet để cài hoặc cập nhật thư viện Python. "
547
+ "Hãy kết nối mạng rồi chạy lại."
548
+ )
549
+
550
+
551
+ def requirement_name(spec: str) -> str:
552
+ cleaned = spec.split("#", 1)[0].strip()
553
+ chars: list[str] = []
554
+ for char in cleaned:
555
+ if char.isalnum() or char in {"_", "-"}:
556
+ chars.append(char)
557
+ continue
558
+ break
559
+ return "".join(chars).lower().replace("_", "-")
560
+
561
+
562
+ def read_requirement_specs(context: RuntimeContext) -> list[str]:
563
+ specs: list[str] = []
564
+ for line in RUNTIME_REQUIREMENTS:
565
+ stripped = line.strip()
566
+ if stripped and not stripped.startswith("#"):
567
+ specs.append(stripped)
568
+ return specs
569
+
570
+
571
+ def non_torch_requirement_specs(context: RuntimeContext) -> list[str]:
572
+ return [
573
+ spec
574
+ for spec in read_requirement_specs(context)
575
+ if requirement_name(spec) not in {"torch", "torchvision", "torchaudio"}
576
+ ]
577
+
578
+
579
+ def pending_non_torch_requirement_specs(context: RuntimeContext) -> list[str]:
580
+ pending: list[str] = []
581
+ for spec in non_torch_requirement_specs(context):
582
+ package_name = requirement_name(spec)
583
+ module_name = DEPENDENCY_IMPORTS.get(package_name)
584
+ if module_name and not module_exists(module_name):
585
+ pending.append(spec)
586
+ continue
587
+ if not requirement_satisfied(spec):
588
+ pending.append(spec)
589
+ return pending
590
+
591
+
592
+ def find_missing_dependencies() -> list[str]:
593
+ missing: list[str] = []
594
+ for package_name, module_name in DEPENDENCY_IMPORTS.items():
595
+ if not module_exists(module_name):
596
+ missing.append(package_name)
597
+ return missing
598
+
599
+
600
+ def install_non_torch_dependencies(context: RuntimeContext) -> None:
601
+ specs = pending_non_torch_requirement_specs(context)
602
+ if not specs:
603
+ print_step("Môi trường Python đã có đủ dependency runtime ngoài PyTorch.")
604
+ return
605
+
606
+ print_step("Đang cài/cập nhật dependency runtime: " + ", ".join(specs))
607
+ run_command([sys.executable, "-m", "pip", "install", "--upgrade", *specs], cwd=context.root)
608
+
609
+
610
+ def inspect_installed_torch() -> dict[str, object]:
611
+ probe_code = r"""
612
+ import json
613
+
614
+ try:
615
+ import torch
616
+ except Exception as exc:
617
+ print(json.dumps({"installed": False, "error": str(exc)}))
618
+ raise SystemExit(0)
619
+
620
+ cuda_available = False
621
+ gpu_names = []
622
+ try:
623
+ cuda_available = bool(torch.cuda.is_available())
624
+ if cuda_available:
625
+ gpu_names = [torch.cuda.get_device_name(index) for index in range(torch.cuda.device_count())]
626
+ except Exception:
627
+ cuda_available = False
628
+
629
+ print(json.dumps({
630
+ "installed": True,
631
+ "version": getattr(torch, "__version__", ""),
632
+ "cuda_version": getattr(getattr(torch, "version", None), "cuda", None),
633
+ "cuda_available": cuda_available,
634
+ "gpu_names": gpu_names,
635
+ }))
636
+ """
637
+ completed = subprocess.run(
638
+ [sys.executable, "-c", probe_code],
639
+ capture_output=True,
640
+ text=True,
641
+ encoding="utf-8",
642
+ errors="replace",
643
+ check=False,
644
+ )
645
+ if completed.returncode != 0 or not completed.stdout.strip():
646
+ return {"installed": False, "error": completed.stderr.strip()}
647
+
648
+ try:
649
+ payload = json.loads(completed.stdout.strip().splitlines()[-1])
650
+ except json.JSONDecodeError as exc:
651
+ return {"installed": False, "error": str(exc)}
652
+
653
+ return payload if isinstance(payload, dict) else {"installed": False, "error": "Invalid torch probe output"}
654
+
655
+
656
+ def parse_driver_version(value: Optional[str]) -> Optional[tuple[int, int]]:
657
+ if not value:
658
+ return None
659
+ parts = value.strip().split(".")
660
+ if not parts or not parts[0].isdigit():
661
+ return None
662
+ major = int(parts[0])
663
+ minor = int(parts[1]) if len(parts) > 1 and parts[1].isdigit() else 0
664
+ return major, minor
665
+
666
+
667
+ def detect_nvidia_gpus() -> list[GpuInfo]:
668
+ command = [
669
+ "nvidia-smi",
670
+ "--query-gpu=name,driver_version,compute_cap",
671
+ "--format=csv,noheader,nounits",
672
+ ]
673
+ try:
674
+ completed = subprocess.run(
675
+ command,
676
+ capture_output=True,
677
+ text=True,
678
+ encoding="utf-8",
679
+ errors="replace",
680
+ timeout=8,
681
+ check=False,
682
+ )
683
+ except (FileNotFoundError, subprocess.SubprocessError):
684
+ return detect_windows_nvidia_gpus()
685
+
686
+ if completed.returncode != 0 or not completed.stdout.strip():
687
+ return detect_windows_nvidia_gpus()
688
+
689
+ gpus: list[GpuInfo] = []
690
+ for row in csv.reader(completed.stdout.splitlines()):
691
+ if not row:
692
+ continue
693
+ name = row[0].strip()
694
+ driver_version = row[1].strip() if len(row) > 1 and row[1].strip() else None
695
+ compute_capability = row[2].strip() if len(row) > 2 and row[2].strip() else None
696
+ gpus.append(GpuInfo(name=name, driver_version=driver_version, compute_capability=compute_capability))
697
+ return gpus
698
+
699
+
700
+ def detect_windows_nvidia_gpus() -> list[GpuInfo]:
701
+ if not IS_WINDOWS:
702
+ return []
703
+
704
+ command = [
705
+ "powershell",
706
+ "-NoProfile",
707
+ "-Command",
708
+ (
709
+ "Get-CimInstance Win32_VideoController | "
710
+ "Where-Object { $_.Name -match 'NVIDIA' } | "
711
+ "Select-Object Name,DriverVersion | ConvertTo-Json -Compress"
712
+ ),
713
+ ]
714
+ try:
715
+ completed = subprocess.run(
716
+ command,
717
+ capture_output=True,
718
+ text=True,
719
+ encoding="utf-8",
720
+ errors="replace",
721
+ timeout=8,
722
+ check=False,
723
+ )
724
+ except (FileNotFoundError, subprocess.SubprocessError):
725
+ return []
726
+
727
+ if completed.returncode != 0:
728
+ return []
729
+
730
+ raw = completed.stdout.strip()
731
+ if not raw:
732
+ return []
733
+
734
+ try:
735
+ payload = json.loads(raw)
736
+ except json.JSONDecodeError:
737
+ names = [line.strip() for line in completed.stdout.splitlines() if line.strip()]
738
+ return [GpuInfo(name=name) for name in names if "nvidia" in name.lower()]
739
+
740
+ items = payload if isinstance(payload, list) else [payload]
741
+ gpus: list[GpuInfo] = []
742
+ for item in items:
743
+ if not isinstance(item, dict):
744
+ continue
745
+ name = str(item.get("Name") or "").strip()
746
+ if not name or "nvidia" not in name.lower():
747
+ continue
748
+ gpus.append(GpuInfo(name=name, driver_version=normalize_windows_driver_version(item.get("DriverVersion"))))
749
+ return gpus
750
+
751
+
752
+ def normalize_windows_driver_version(value: object) -> Optional[str]:
753
+ text = str(value or "").strip()
754
+ if not text:
755
+ return None
756
+ parts = text.split(".")
757
+ if len(parts) >= 4 and parts[-1].isdigit():
758
+ tail = parts[-1]
759
+ if len(tail) >= 5:
760
+ return f"{int(tail[:-2])}.{tail[-2:]}"
761
+ return text
762
+
763
+
764
+ def format_gpu_list(gpus: list[GpuInfo]) -> str:
765
+ labels: list[str] = []
766
+ for index, gpu in enumerate(gpus):
767
+ details: list[str] = []
768
+ if gpu.driver_version:
769
+ details.append(f"driver {gpu.driver_version}")
770
+ if gpu.compute_capability:
771
+ details.append(f"compute {gpu.compute_capability}")
772
+ suffix = f" ({', '.join(details)})" if details else ""
773
+ labels.append(f"GPU {index}: {gpu.name}{suffix}")
774
+ return "; ".join(labels)
775
+
776
+
777
+ def select_runtime_device(args: argparse.Namespace) -> tuple[str, list[GpuInfo]]:
778
+ requested = (args.device or os.getenv("HVU_DEVICE") or "auto").strip().lower()
779
+ if requested == "cpu":
780
+ print_step("Đã chọn CPU theo tham số chạy.")
781
+ return "cpu", []
782
+
783
+ gpus = detect_nvidia_gpus()
784
+ if requested == "cuda":
785
+ if gpus:
786
+ print_step(f"Đang sử dụng GPU: {format_gpu_list(gpus)}")
787
+ else:
788
+ print_step("Đã chọn CUDA nhưng chưa phát hiện GPU NVIDIA bằng nvidia-smi/WMI.")
789
+ return "cuda", gpus
790
+
791
+ if not gpus:
792
+ print_step("Không phát hiện GPU NVIDIA CUDA. Chương trình sẽ dùng CPU.")
793
+ update_config(device="cpu")
794
+ return "cpu", []
795
+
796
+ print_step(f"Phát hiện GPU NVIDIA CUDA, ưu tiên chạy bằng GPU: {format_gpu_list(gpus)}")
797
+ update_config(device="cuda")
798
+ return "cuda", gpus
799
+
800
+
801
+ def cuda_wheel_candidates(gpus: list[GpuInfo]) -> list[PytorchCudaWheel]:
802
+ override_url = os.getenv("HVU_PYTORCH_CUDA_INDEX_URL")
803
+ if override_url:
804
+ override_tag = os.getenv("HVU_PYTORCH_CUDA_TAG", "custom")
805
+ override_requirement = os.getenv("HVU_PYTORCH_TORCH_REQUIREMENT", TORCH_REQUIREMENT)
806
+ return [PytorchCudaWheel(override_tag, override_url, 0, 0, override_requirement)]
807
+
808
+ driver = parse_driver_version(next((gpu.driver_version for gpu in gpus if gpu.driver_version), None))
809
+ if driver is None:
810
+ return PYTORCH_CUDA_WHEELS[:]
811
+
812
+ return [
813
+ wheel
814
+ for wheel in PYTORCH_CUDA_WHEELS
815
+ if driver >= (wheel.min_driver_major, wheel.min_driver_minor)
816
+ ]
817
+
818
+
819
+ def describe_cuda_selection(gpus: list[GpuInfo], candidates: list[PytorchCudaWheel]) -> None:
820
+ driver_text = next((gpu.driver_version for gpu in gpus if gpu.driver_version), None)
821
+ if driver_text:
822
+ if candidates:
823
+ print_step(
824
+ f"Driver NVIDIA {driver_text}; chọn CUDA wheel tương thích cao nhất: "
825
+ f"{candidates[0].tag}."
826
+ )
827
+ else:
828
+ print_step(f"Driver NVIDIA {driver_text}; chưa có CUDA wheel PyTorch tương thích trực tiếp.")
829
+ return
830
+
831
+ if candidates:
832
+ print_step(
833
+ "Không đọc được phiên bản driver NVIDIA. Tool sẽ thử các CUDA wheel từ mới đến cũ."
834
+ )
835
+
836
+
837
+ def winget_available() -> bool:
838
+ try:
839
+ completed = subprocess.run(
840
+ ["winget", "--version"],
841
+ capture_output=True,
842
+ text=True,
843
+ encoding="utf-8",
844
+ errors="replace",
845
+ timeout=20,
846
+ check=False,
847
+ )
848
+ except (FileNotFoundError, subprocess.SubprocessError):
849
+ return False
850
+ return completed.returncode == 0
851
+
852
+
853
+ def try_install_nvidia_cuda_support() -> bool:
854
+ if not IS_WINDOWS or not winget_available():
855
+ return False
856
+
857
+ print_step(
858
+ "Không có CUDA wheel phù hợp với driver hiện tại. "
859
+ "Đang thử cài NVIDIA CUDA Toolkit chính thức qua winget để bổ sung/cập nhật hỗ trợ CUDA..."
860
+ )
861
+ base_command = [
862
+ "winget",
863
+ "install",
864
+ "--id",
865
+ "Nvidia.CUDA",
866
+ "--source",
867
+ "winget",
868
+ "--accept-package-agreements",
869
+ "--accept-source-agreements",
870
+ "--silent",
871
+ "--disable-interactivity",
872
+ ]
873
+ if try_run_command(base_command, cwd=SCRIPT_ROOT):
874
+ return True
875
+
876
+ print_step("Cài NVIDIA CUDA Toolkit qua winget chưa thành công. Thử lệnh upgrade nếu gói đã tồn tại.")
877
+ upgrade_command = [
878
+ "winget",
879
+ "upgrade",
880
+ "--id",
881
+ "Nvidia.CUDA",
882
+ "--source",
883
+ "winget",
884
+ "--accept-package-agreements",
885
+ "--accept-source-agreements",
886
+ "--silent",
887
+ "--disable-interactivity",
888
+ ]
889
+ return try_run_command(upgrade_command, cwd=SCRIPT_ROOT)
890
+
891
+
892
+ def companion_requirements_for_torch(torch_info: dict[str, object]) -> tuple[str, ...]:
893
+ version = str(torch_info.get("version") or "")
894
+ if version.startswith("2.0."):
895
+ return ("numpy>=1.26.0,<2.0.0", "transformers>=4.41.0,<4.42.0")
896
+ return ()
897
+
898
+
899
+ def requirement_satisfied(spec: str) -> bool:
900
+ try:
901
+ from packaging.requirements import Requirement
902
+ except Exception:
903
+ return False
904
+
905
+ try:
906
+ requirement = Requirement(spec)
907
+ installed_version = importlib.metadata.version(requirement.name)
908
+ except Exception:
909
+ return False
910
+
911
+ if not requirement.specifier:
912
+ return True
913
+ return installed_version in requirement.specifier
914
+
915
+
916
+ def ensure_companion_requirements(requirements: tuple[str, ...], context: RuntimeContext) -> None:
917
+ specs = tuple(dict.fromkeys(spec for spec in requirements if spec))
918
+ if not specs:
919
+ return
920
+
921
+ pending_specs = tuple(spec for spec in specs if not requirement_satisfied(spec))
922
+ if not pending_specs:
923
+ return
924
+
925
+ print_step("Dang cai dependency tuong thich voi PyTorch CUDA: " + ", ".join(pending_specs))
926
+ run_command([sys.executable, "-m", "pip", "install", "--upgrade", *pending_specs], cwd=context.root)
927
+
928
+
929
+ def cpu_torch_install_commands(force_reinstall: bool) -> list[list[str]]:
930
+ base_command = [sys.executable, "-m", "pip", "install", "--upgrade"]
931
+ if force_reinstall:
932
+ base_command.append("--force-reinstall")
933
+
934
+ pypi_command = [*base_command, TORCH_REQUIREMENT]
935
+ cpu_index_command = [*base_command, TORCH_REQUIREMENT, "--index-url", PYTORCH_CPU_INDEX_URL]
936
+
937
+ # macOS and ARM Linux usually receive the correct CPU/MPS wheels from PyPI.
938
+ # Windows/Linux x64 prefer the PyTorch CPU index to avoid pulling CUDA wheels.
939
+ profile = collect_system_profile()
940
+ if IS_MACOS or profile.is_arm64:
941
+ return [pypi_command, cpu_index_command]
942
+ return [cpu_index_command, pypi_command]
943
+
944
+
945
+ def install_cpu_torch(context: RuntimeContext, force_reinstall: bool = False) -> None:
946
+ commands = cpu_torch_install_commands(force_reinstall)
947
+ for index, command in enumerate(commands, start=1):
948
+ source_label = "PyPI" if "--index-url" not in command else "PyTorch CPU index"
949
+ if index == 1:
950
+ print_step(f"Đang cài PyTorch CPU từ {source_label}.")
951
+ else:
952
+ print_step(f"Nguồn cài trước chưa thành công, đang thử PyTorch CPU từ {source_label}.")
953
+ if try_run_command(command, cwd=context.root):
954
+ return
955
+
956
+ raise RuntimeError(
957
+ "Không cài được PyTorch CPU tự động. Hãy kiểm tra Internet, phiên bản Python 64-bit "
958
+ "và thử chạy lại `python HVU_QA_tool.py`."
959
+ )
960
+
961
+
962
+ def platform_runtime_note(selected_device: str) -> None:
963
+ profile = collect_system_profile()
964
+ if profile.os_key == "windows":
965
+ print_step("Windows: tool sẽ tự xử lý virtualenv, pip, VC++ Redistributable khi cần, PyTorch CPU/CUDA.")
966
+ elif profile.os_key == "macos":
967
+ print_step("macOS: tool sẽ tự xử lý virtualenv, pip và PyTorch CPU/MPS wheel qua PyPI; CUDA không áp dụng.")
968
+ elif profile.os_key == "linux":
969
+ print_step("Linux: tool sẽ tự xử lý virtualenv, pip và PyTorch; GPU NVIDIA cần driver hệ thống đã sẵn sàng.")
970
+ if selected_device == "cuda" and profile.os_key != "windows":
971
+ print_step("Trên Linux, tool có thể cài PyTorch CUDA wheel nhưng không tự cài driver NVIDIA cấp hệ điều hành.")
972
+
973
+
974
+ def is_torch_dll_error(torch_info: dict[str, object]) -> bool:
975
+ text = str(torch_info.get("error") or "")
976
+ markers = ("c10.dll", "_load_dll_libraries", "WinError 1114", "DLL initialization routine failed")
977
+ return any(marker.lower() in text.lower() for marker in markers)
978
+
979
+
980
+ def windows_is_admin() -> bool:
981
+ if not IS_WINDOWS:
982
+ return False
983
+ try:
984
+ import ctypes
985
+
986
+ return bool(ctypes.windll.shell32.IsUserAnAdmin())
987
+ except Exception:
988
+ return False
989
+
990
+
991
+ def download_vc_redist() -> Path:
992
+ VC_REDIST_CACHE.parent.mkdir(parents=True, exist_ok=True)
993
+ if VC_REDIST_CACHE.exists() and VC_REDIST_CACHE.stat().st_size > 1_000_000:
994
+ return VC_REDIST_CACHE
995
+
996
+ if not internet_available():
997
+ raise RuntimeError(
998
+ "Cần Internet để tải Microsoft Visual C++ Redistributable tự động."
999
+ )
1000
+
1001
+ print_step("Đang tải Microsoft Visual C++ Redistributable 2015-2022 x64...")
1002
+ with urllib.request.urlopen(VC_REDIST_X64_URL, timeout=60) as response:
1003
+ VC_REDIST_CACHE.write_bytes(response.read())
1004
+ return VC_REDIST_CACHE
1005
+
1006
+
1007
+ def run_vc_redist_installer(installer: Path) -> int:
1008
+ args = "/install /quiet /norestart"
1009
+ if windows_is_admin():
1010
+ completed = run_command_capture([str(installer), "/install", "/quiet", "/norestart"])
1011
+ return completed.returncode
1012
+
1013
+ print_step("Trình cài VC++ có thể yêu cầu quyền quản trị. Nếu Windows hỏi UAC, hãy chọn Yes.")
1014
+ command = [
1015
+ "powershell",
1016
+ "-NoProfile",
1017
+ "-ExecutionPolicy",
1018
+ "Bypass",
1019
+ "-Command",
1020
+ (
1021
+ "$p = Start-Process "
1022
+ f"-FilePath {json.dumps(str(installer))} "
1023
+ f"-ArgumentList {json.dumps(args)} "
1024
+ "-Verb RunAs -Wait -PassThru; exit $p.ExitCode"
1025
+ ),
1026
+ ]
1027
+ completed = run_command_capture(command)
1028
+ return completed.returncode
1029
+
1030
+
1031
+ def ensure_windows_vc_redist() -> bool:
1032
+ if not IS_WINDOWS:
1033
+ return False
1034
+ if os.getenv("HVU_SKIP_VC_REDIST", "").strip().lower() in {"1", "true", "yes", "on"}:
1035
+ return False
1036
+
1037
+ installer = download_vc_redist()
1038
+ print_step("Đang cài Microsoft Visual C++ Redistributable 2015-2022 x64...")
1039
+ exit_code = run_vc_redist_installer(installer)
1040
+ if exit_code in VC_REDIST_SUCCESS_CODES:
1041
+ if exit_code == 3010:
1042
+ print_step("VC++ Redistributable đã cài xong và Windows có thể cần khởi động lại.")
1043
+ else:
1044
+ print_step("VC++ Redistributable đã sẵn sàng.")
1045
+ return True
1046
+
1047
+ raise RuntimeError(
1048
+ "Không cài được Microsoft Visual C++ Redistributable tự động "
1049
+ f"(mã lỗi {exit_code}). Hãy chạy lại bằng quyền Administrator hoặc cài thủ công rồi chạy lại."
1050
+ )
1051
+
1052
+
1053
+ def repair_torch_runtime(context: RuntimeContext, reason: str) -> None:
1054
+ print_step("Đang sửa lỗi PyTorch/DLL trước khi chạy backend...")
1055
+ if IS_WINDOWS:
1056
+ ensure_windows_vc_redist()
1057
+ print_step("Đang cài lại PyTorch CPU ổn định...")
1058
+ install_cpu_torch(context, force_reinstall=True)
1059
+ torch_info = inspect_installed_torch()
1060
+ if not torch_info.get("installed"):
1061
+ raise RuntimeError(
1062
+ "Đã thử sửa PyTorch nhưng vẫn chưa import được. "
1063
+ f"Lỗi ban đầu: {reason}. Lỗi hiện tại: {torch_info.get('error')}"
1064
+ )
1065
+
1066
+
1067
+ def ensure_pytorch_for_device(
1068
+ selected_device: str,
1069
+ context: RuntimeContext,
1070
+ gpus: list[GpuInfo],
1071
+ ) -> str:
1072
+ torch_info = inspect_installed_torch()
1073
+ if selected_device == "cuda":
1074
+ if torch_info.get("cuda_available"):
1075
+ ensure_companion_requirements(companion_requirements_for_torch(torch_info), context)
1076
+ print_step(f"PyTorch CUDA đã dùng được ({torch_info.get('version')}).")
1077
+ return "cuda"
1078
+
1079
+ candidates = cuda_wheel_candidates(gpus)
1080
+ describe_cuda_selection(gpus, candidates)
1081
+ if not candidates:
1082
+ if try_install_nvidia_cuda_support():
1083
+ gpus = detect_nvidia_gpus()
1084
+ candidates = cuda_wheel_candidates(gpus)
1085
+ describe_cuda_selection(gpus, candidates)
1086
+ if not candidates:
1087
+ gpu_label = format_gpu_list(gpus) if gpus else "không đọc được thông tin GPU"
1088
+ raise RuntimeError(
1089
+ "Tool chưa tự chuẩn bị được CUDA cho GPU hiện tại. "
1090
+ f"GPU/driver phát hiện: {gpu_label}."
1091
+ )
1092
+
1093
+ if torch_info.get("installed"):
1094
+ print_step(
1095
+ f"PyTorch hiện tại là {torch_info.get('version')} "
1096
+ f"(cuda={torch_info.get('cuda_version')}). Đang cài lại bản CUDA phù hợp."
1097
+ )
1098
+
1099
+ for wheel in candidates:
1100
+ print_step(
1101
+ f"Đang cài PyTorch GPU phù hợp: {wheel.torch_requirement} "
1102
+ f"({wheel.tag}) từ {wheel.index_url}"
1103
+ )
1104
+ command = [
1105
+ sys.executable,
1106
+ "-m",
1107
+ "pip",
1108
+ "install",
1109
+ "--upgrade",
1110
+ "--force-reinstall",
1111
+ wheel.torch_requirement,
1112
+ "--index-url",
1113
+ wheel.index_url,
1114
+ ]
1115
+ installed_ok = try_run_command(command, cwd=context.root)
1116
+ if installed_ok:
1117
+ installed_info = inspect_installed_torch()
1118
+ if installed_info.get("cuda_available"):
1119
+ ensure_companion_requirements(wheel.companion_requirements, context)
1120
+ print_step(f"PyTorch CUDA {wheel.tag} đã dùng được.")
1121
+ return "cuda"
1122
+ print_step(
1123
+ f"Đã cài {wheel.tag} nhưng PyTorch vẫn chưa dùng được CUDA "
1124
+ f"(version={installed_info.get('version')}, cuda={installed_info.get('cuda_version')}). "
1125
+ "Tool sẽ thử CUDA wheel thấp hơn nếu có."
1126
+ )
1127
+ else:
1128
+ print_step(f"Cài PyTorch {wheel.tag} không thành công. Thử CUDA wheel thấp hơn nếu có.")
1129
+
1130
+ raise RuntimeError(
1131
+ "Tool không cài được PyTorch CUDA phù hợp sau khi đã thử các phiên bản tương thích."
1132
+ )
1133
+
1134
+ if torch_info.get("installed"):
1135
+ print_step(f"PyTorch đã sẵn sàng ({torch_info.get('version')}).")
1136
+ ensure_companion_requirements(companion_requirements_for_torch(torch_info), context)
1137
+ return "cpu"
1138
+
1139
+ error_text = str(torch_info.get("error") or "").strip()
1140
+ if error_text:
1141
+ print_step("PyTorch hiện tại bị lỗi khi import, đang cài lại bản CPU ổn định.")
1142
+ print_step(f"Lỗi PyTorch: {error_text}")
1143
+ if is_torch_dll_error(torch_info):
1144
+ repair_torch_runtime(context, error_text)
1145
+ return "cpu"
1146
+ else:
1147
+ print_step("Đang cài PyTorch CPU.")
1148
+ install_cpu_torch(context, force_reinstall=bool(error_text))
1149
+ installed_info = inspect_installed_torch()
1150
+ if not installed_info.get("installed"):
1151
+ raise RuntimeError(
1152
+ "Đã cài lại PyTorch CPU nhưng vẫn không import được. "
1153
+ "Hãy cài Microsoft Visual C++ Redistributable 2015-2022 x64, khởi động lại máy rồi chạy lại. "
1154
+ f"Chi tiết PyTorch: {installed_info.get('error')}"
1155
+ )
1156
+ return "cpu"
1157
+
1158
+
1159
+ def verify_selected_device(selected_device: str) -> str:
1160
+ if selected_device != "cuda":
1161
+ torch_info = inspect_installed_torch()
1162
+ if not torch_info.get("installed"):
1163
+ raise RuntimeError(
1164
+ "PyTorch chưa import được sau bước cài đặt. "
1165
+ f"Chi tiết: {torch_info.get('error')}"
1166
+ )
1167
+ return "cpu"
1168
+
1169
+ torch_info = inspect_installed_torch()
1170
+ if torch_info.get("cuda_available"):
1171
+ gpu_names = ", ".join(str(name) for name in torch_info.get("gpu_names", []))
1172
+ suffix = f": {gpu_names}" if gpu_names else ""
1173
+ print_step(f"PyTorch CUDA đã sẵn sàng{suffix}.")
1174
+ return "cuda"
1175
+
1176
+ raise RuntimeError(
1177
+ "Bạn đã chọn dùng GPU nhưng PyTorch chưa truy cập được CUDA sau khi cài đặt. "
1178
+ f"Thông tin PyTorch: version={torch_info.get('version')}, cuda={torch_info.get('cuda_version')}, "
1179
+ f"cuda_available={torch_info.get('cuda_available')}."
1180
+ )
1181
+
1182
+
1183
+ def ensure_runtime_dependencies(
1184
+ selected_device: str,
1185
+ context: RuntimeContext,
1186
+ gpus: list[GpuInfo],
1187
+ ) -> str:
1188
+ install_non_torch_dependencies(context=context)
1189
+ selected_device = ensure_pytorch_for_device(
1190
+ selected_device=selected_device,
1191
+ context=context,
1192
+ gpus=gpus,
1193
+ )
1194
+ return verify_selected_device(selected_device)
1195
+
1196
+
1197
+ def resolve_repo_files(
1198
+ repo_id: str,
1199
+ revision: str,
1200
+ allow_patterns: list[str],
1201
+ ignore_patterns: list[str],
1202
+ ) -> list[dict[str, object]]:
1203
+ from huggingface_hub import HfApi
1204
+
1205
+ api = HfApi()
1206
+ repo_files = api.list_repo_tree(repo_id=repo_id, repo_type="dataset", revision=revision, recursive=True)
1207
+
1208
+ selected: list[dict[str, object]] = []
1209
+ for entry in repo_files:
1210
+ path = str(getattr(entry, "path", "")).replace("\\", "/")
1211
+ size = getattr(entry, "size", None)
1212
+ if not path or path.endswith("/") or size is None:
1213
+ continue
1214
+ if not matches_any_pattern(path, allow_patterns):
1215
+ continue
1216
+ if matches_any_pattern(path, ignore_patterns):
1217
+ continue
1218
+ selected.append({"path": path, "size": size})
1219
+
1220
+ return sorted(selected, key=lambda item: str(item["path"]))
1221
+
1222
+
1223
+ def runtime_relative_path(repo_file: str) -> Optional[Path]:
1224
+ normalized = repo_file.replace("\\", "/")
1225
+ prefix = f"{HF_PROJECT_SUBDIR}/"
1226
+ if matches_any_pattern(normalized, RUNTIME_ALLOW_PATTERNS):
1227
+ return Path(normalized[len(prefix) :])
1228
+ return None
1229
+
1230
+
1231
+ def model_destination(context: RuntimeContext, repo_file: str) -> Path:
1232
+ normalized = repo_file.replace("\\", "/")
1233
+ relative_path = Path(normalized).relative_to(HF_MODEL_SUBDIR)
1234
+ return context.local_model_dir / relative_path
1235
+
1236
+
1237
+ def sync_single_file(
1238
+ source_file: Path,
1239
+ destination_file: Path,
1240
+ force_copy: bool,
1241
+ *,
1242
+ verify_content: bool = False,
1243
+ ) -> tuple[bool, int]:
1244
+ destination_file.parent.mkdir(parents=True, exist_ok=True)
1245
+ size = source_file.stat().st_size
1246
+
1247
+ if destination_file.exists() and not force_copy and destination_file.stat().st_size == size:
1248
+ if not verify_content or destination_file.read_bytes() == source_file.read_bytes():
1249
+ return False, size
1250
+
1251
+ shutil.copy2(source_file, destination_file)
1252
+ return True, size
1253
+
1254
+
1255
+ def download_and_sync_files(
1256
+ context: RuntimeContext,
1257
+ repo_id: str,
1258
+ revision: str,
1259
+ allow_patterns: list[str],
1260
+ ignore_patterns: list[str],
1261
+ force_download: bool,
1262
+ scope_label: str,
1263
+ ) -> tuple[int, int, int, int]:
1264
+ from huggingface_hub import snapshot_download
1265
+
1266
+ repo_files = resolve_repo_files(
1267
+ repo_id=repo_id,
1268
+ revision=revision,
1269
+ allow_patterns=allow_patterns,
1270
+ ignore_patterns=ignore_patterns,
1271
+ )
1272
+ if not repo_files:
1273
+ raise FileNotFoundError(
1274
+ f"Không tìm thấy file {scope_label} hợp lệ trong repo {repo_id}@{revision}. "
1275
+ "Hãy kiểm tra lại cấu trúc dataset trên Hugging Face."
1276
+ )
1277
+
1278
+ total_files = len(repo_files)
1279
+ total_bytes = sum(int(item["size"] or 0) for item in repo_files)
1280
+ copied_files = 0
1281
+ skipped_files = 0
1282
+ copied_bytes = 0
1283
+ skipped_bytes = 0
1284
+ processed_bytes = 0
1285
+
1286
+ print_step(f"Tìm thấy {total_files} file cần đồng bộ cho {scope_label}.")
1287
+ print_step(f"Đang tải {scope_label} bằng snapshot_download, bỏ qua file huấn luyện/log không cần thiết...")
1288
+ snapshot_dir = Path(
1289
+ snapshot_download(
1290
+ repo_id=repo_id,
1291
+ repo_type="dataset",
1292
+ revision=revision,
1293
+ allow_patterns=allow_patterns,
1294
+ ignore_patterns=ignore_patterns,
1295
+ force_download=force_download,
1296
+ local_files_only=False,
1297
+ )
1298
+ )
1299
+
1300
+ for index, repo_item in enumerate(repo_files, start=1):
1301
+ repo_file = str(repo_item["path"])
1302
+ runtime_path = runtime_relative_path(repo_file)
1303
+ if runtime_path is not None:
1304
+ destination_path = context.root / runtime_path
1305
+ verify_content = True
1306
+ else:
1307
+ destination_path = model_destination(context, repo_file)
1308
+ verify_content = False
1309
+
1310
+ relative_label = destination_path.relative_to(context.root).as_posix()
1311
+ expected_size = int(repo_item["size"] or 0)
1312
+ if (
1313
+ not force_download
1314
+ and not verify_content
1315
+ and expected_size > 0
1316
+ and destination_path.exists()
1317
+ and destination_path.stat().st_size == expected_size
1318
+ ):
1319
+ skipped_files += 1
1320
+ skipped_bytes += expected_size
1321
+ processed_bytes += expected_size
1322
+ if processed_bytes > total_bytes:
1323
+ total_bytes = processed_bytes
1324
+ print_step(f"[{index}/{total_files}] Giữ nguyên {relative_label} ({format_bytes(expected_size)})")
1325
+ print_step(
1326
+ " Tổng tiến độ "
1327
+ f"{render_progress_bar(processed_bytes, total_bytes)} "
1328
+ f"({format_bytes(processed_bytes)}/{format_bytes(total_bytes)})"
1329
+ )
1330
+ continue
1331
+
1332
+ print_step(f"[{index}/{total_files}] Đang đồng bộ {relative_label}")
1333
+ cached_file = snapshot_dir / repo_file
1334
+ if not cached_file.exists():
1335
+ raise FileNotFoundError(f"snapshot_download thiếu file đã chọn: {repo_file}")
1336
+
1337
+ copied, size = sync_single_file(
1338
+ cached_file,
1339
+ destination_path,
1340
+ force_copy=force_download,
1341
+ verify_content=verify_content,
1342
+ )
1343
+ if copied:
1344
+ copied_files += 1
1345
+ copied_bytes += size
1346
+ print_step(f" Đã đồng bộ {relative_label} ({format_bytes(size)})")
1347
+ else:
1348
+ skipped_files += 1
1349
+ skipped_bytes += size
1350
+ print_step(f" Giữ nguyên {relative_label} ({format_bytes(size)})")
1351
+
1352
+ processed_bytes += size
1353
+ if processed_bytes > total_bytes:
1354
+ total_bytes = processed_bytes
1355
+ print_step(
1356
+ " Tổng tiến độ "
1357
+ f"{render_progress_bar(processed_bytes, total_bytes)} "
1358
+ f"({format_bytes(processed_bytes)}/{format_bytes(total_bytes)})"
1359
+ )
1360
+
1361
+ return copied_files, skipped_files, copied_bytes, skipped_bytes
1362
+
1363
+
1364
+ def validate_runtime_files(context: RuntimeContext) -> None:
1365
+ missing_files = [relative for relative in RUNTIME_REQUIRED_FILES if not (context.root / relative).exists()]
1366
+ if missing_files:
1367
+ raise FileNotFoundError(
1368
+ "Runtime chưa đầy đủ sau khi tải về. Thiếu các file: " + ", ".join(missing_files)
1369
+ )
1370
+
1371
+
1372
+ def patch_generate_question_runtime(context: RuntimeContext) -> None:
1373
+ if context.requirements_file.exists():
1374
+ requirements_text = context.requirements_file.read_text(encoding="utf-8")
1375
+ patched_requirements = (
1376
+ requirements_text.replace("numpy>=1.26.0,<3.0.0", "numpy>=1.26.0,<2.0.0")
1377
+ .replace("transformers>=4.41.0,<5.0.0", "transformers>=4.41.0,<4.42.0")
1378
+ )
1379
+ if patched_requirements != requirements_text:
1380
+ context.requirements_file.write_text(patched_requirements, encoding="utf-8")
1381
+
1382
+ target = context.root / "generate_question.py"
1383
+ if not target.exists():
1384
+ return
1385
+
1386
+ text = target.read_text(encoding="utf-8")
1387
+ original_text = text
1388
+
1389
+ import_insertions = {
1390
+ "import argparse\n": "import argparse\nimport hashlib\n",
1391
+ "import re\n": "import re\nimport shutil\n",
1392
+ "import sys\n": "import sys\nimport tempfile\n",
1393
+ }
1394
+ for anchor, replacement in import_insertions.items():
1395
+ imported_name = replacement.splitlines()[-1]
1396
+ if imported_name not in text and anchor in text:
1397
+ text = text.replace(anchor, replacement, 1)
1398
+
1399
+ if "TOKENIZER_FILES = (" not in text and "QUESTION_LIMIT = 100\n" in text:
1400
+ text = text.replace(
1401
+ "QUESTION_LIMIT = 100\n",
1402
+ "QUESTION_LIMIT = 100\n"
1403
+ "TOKENIZER_FILES = (\n"
1404
+ " \"config.json\",\n"
1405
+ " \"special_tokens_map.json\",\n"
1406
+ " \"spiece.model\",\n"
1407
+ " \"tokenizer.json\",\n"
1408
+ " \"tokenizer_config.json\",\n"
1409
+ " \"added_tokens.json\",\n"
1410
+ ")\n",
1411
+ 1,
1412
+ )
1413
+
1414
+ if "def resolve_tokenizer_dir(" not in text and "\ndef parse_dtype(value: str) -> torch.dtype:\n" in text:
1415
+ helper_block = """
1416
+ def path_needs_ascii_mirror(path: Path) -> bool:
1417
+ try:
1418
+ str(path).encode("ascii")
1419
+ except UnicodeEncodeError:
1420
+ return True
1421
+ return False
1422
+
1423
+
1424
+ def resolve_tokenizer_dir(model_dir: Path) -> Path:
1425
+ if not path_needs_ascii_mirror(model_dir):
1426
+ return model_dir
1427
+
1428
+ digest = hashlib.sha1(str(model_dir).encode("utf-8")).hexdigest()[:16]
1429
+ cache_base = Path(os.getenv("LOCALAPPDATA") or tempfile.gettempdir())
1430
+ tokenizer_dir = cache_base / "HVU_QA" / "tokenizer_cache" / digest
1431
+ tokenizer_dir.mkdir(parents=True, exist_ok=True)
1432
+
1433
+ copied = False
1434
+ for filename in TOKENIZER_FILES:
1435
+ source = model_dir / filename
1436
+ if not source.exists():
1437
+ continue
1438
+ destination = tokenizer_dir / filename
1439
+ if destination.exists() and destination.stat().st_size == source.stat().st_size:
1440
+ continue
1441
+ shutil.copy2(source, destination)
1442
+ copied = True
1443
+
1444
+ if copied:
1445
+ marker = tokenizer_dir / "source_model_dir.txt"
1446
+ marker.write_text(str(model_dir), encoding="utf-8")
1447
+
1448
+ return tokenizer_dir
1449
+
1450
+ """
1451
+ text = text.replace(
1452
+ "\ndef parse_dtype(value: str) -> torch.dtype:\n",
1453
+ "\n" + helper_block + "def parse_dtype(value: str) -> torch.dtype:\n",
1454
+ 1,
1455
+ )
1456
+
1457
+ method_start = text.find(" def _load_tokenizer(self):")
1458
+ method_end = text.find("\n def load(self)", method_start)
1459
+ if method_start != -1 and method_end != -1:
1460
+ method_block = text[method_start:method_end]
1461
+ if "tokenizer_dir = resolve_tokenizer_dir(self.model_dir)" not in method_block:
1462
+ new_method = """ def _load_tokenizer(self):
1463
+ use_fast = as_bool(os.getenv("HVU_USE_FAST_TOKENIZER"), default=False)
1464
+ tokenizer_dir = resolve_tokenizer_dir(self.model_dir)
1465
+ try:
1466
+ return AutoTokenizer.from_pretrained(str(tokenizer_dir), use_fast=use_fast)
1467
+ except Exception:
1468
+ if use_fast:
1469
+ return AutoTokenizer.from_pretrained(str(tokenizer_dir), use_fast=False)
1470
+ if (tokenizer_dir / "tokenizer.json").exists():
1471
+ try:
1472
+ return AutoTokenizer.from_pretrained(str(tokenizer_dir), use_fast=True)
1473
+ except Exception:
1474
+ pass
1475
+ return AutoTokenizer.from_pretrained(str(tokenizer_dir), use_fast=False)
1476
+ """
1477
+ text = text[:method_start] + new_method + text[method_end:]
1478
+
1479
+ if text != original_text:
1480
+ target.write_text(text, encoding="utf-8")
1481
+ print_step("Da cap nhat tuong thich tokenizer trong runtime generate_question.py.")
1482
+
1483
+
1484
+ def prepare_runtime(
1485
+ context: RuntimeContext,
1486
+ repo_id: str,
1487
+ revision: str,
1488
+ force_download: bool,
1489
+ ) -> None:
1490
+ if not force_download and has_complete_runtime(context):
1491
+ patch_generate_question_runtime(context)
1492
+ print_step("Backend/frontend runtime đã có sẵn.")
1493
+ return
1494
+
1495
+ copied_files, skipped_files, copied_bytes, skipped_bytes = download_and_sync_files(
1496
+ context=context,
1497
+ repo_id=repo_id,
1498
+ revision=revision,
1499
+ allow_patterns=RUNTIME_ALLOW_PATTERNS,
1500
+ ignore_patterns=RUNTIME_IGNORE_PATTERNS,
1501
+ force_download=force_download,
1502
+ scope_label="backend/frontend runtime",
1503
+ )
1504
+ validate_runtime_files(context)
1505
+ patch_generate_question_runtime(context)
1506
+ print_step(
1507
+ "Đồng bộ backend/frontend runtime xong. "
1508
+ f"File mới/cập nhật: {copied_files} ({format_bytes(copied_bytes)}), "
1509
+ f"file giữ nguyên: {skipped_files} ({format_bytes(skipped_bytes)})."
1510
+ )
1511
+
1512
+
1513
+ def required_model_files(context: RuntimeContext, best_model_only: bool) -> list[Path]:
1514
+ root_files = [
1515
+ context.local_model_dir / "config.json",
1516
+ context.local_model_dir / "generation_config.json",
1517
+ context.local_model_dir / "model.safetensors",
1518
+ context.local_model_dir / "tokenizer_config.json",
1519
+ context.local_model_dir / "special_tokens_map.json",
1520
+ context.local_model_dir / "spiece.model",
1521
+ ]
1522
+ best_model_files = [
1523
+ context.local_best_model_dir / "config.json",
1524
+ context.local_best_model_dir / "generation_config.json",
1525
+ context.local_best_model_dir / "model.safetensors",
1526
+ context.local_best_model_dir / "tokenizer_config.json",
1527
+ context.local_best_model_dir / "special_tokens_map.json",
1528
+ context.local_best_model_dir / "spiece.model",
1529
+ ]
1530
+ if best_model_only:
1531
+ return best_model_files
1532
+ return [*root_files, *best_model_files]
1533
+
1534
+
1535
+ def validate_local_model_dir(context: RuntimeContext, best_model_only: bool) -> None:
1536
+ missing_files = [
1537
+ str(path.relative_to(context.root))
1538
+ for path in required_model_files(context, best_model_only)
1539
+ if not path.exists()
1540
+ ]
1541
+ if missing_files:
1542
+ raise FileNotFoundError(
1543
+ "Model chưa đầy đủ sau khi tải về. Thiếu các file: " + ", ".join(missing_files)
1544
+ )
1545
+
1546
+
1547
+ def prepare_model(
1548
+ context: RuntimeContext,
1549
+ repo_id: str,
1550
+ revision: str,
1551
+ force_download: bool,
1552
+ best_model_only: bool,
1553
+ ) -> None:
1554
+ if not force_download and has_complete_model(context, best_model_only):
1555
+ scope = "best-model" if best_model_only else "toàn bộ model"
1556
+ print_step(f"{scope} đã có sẵn, không cần tải lại.")
1557
+ return
1558
+
1559
+ allow_patterns = [f"{HF_BEST_MODEL_SUBDIR}/**"] if best_model_only else [f"{HF_MODEL_SUBDIR}/**"]
1560
+ copied_files, skipped_files, copied_bytes, skipped_bytes = download_and_sync_files(
1561
+ context=context,
1562
+ repo_id=repo_id,
1563
+ revision=revision,
1564
+ allow_patterns=allow_patterns,
1565
+ ignore_patterns=MODEL_IGNORE_PATTERNS,
1566
+ force_download=force_download,
1567
+ scope_label="best-model" if best_model_only else "toàn bộ model",
1568
+ )
1569
+ validate_local_model_dir(context, best_model_only=best_model_only)
1570
+
1571
+ scope = "best-model" if best_model_only else "toàn bộ model"
1572
+ print_step(
1573
+ f"Đồng bộ {scope} xong. "
1574
+ f"File mới/cập nhật: {copied_files} ({format_bytes(copied_bytes)}), "
1575
+ f"file giữ nguyên: {skipped_files} ({format_bytes(skipped_bytes)})."
1576
+ )
1577
+
1578
+
1579
+ def build_runtime_env(context: RuntimeContext, args: argparse.Namespace) -> dict[str, str]:
1580
+ env = subprocess_env()
1581
+ env["HVU_HOST"] = args.host or "127.0.0.1"
1582
+ env["HVU_PORT"] = str(args.port)
1583
+ if args.device:
1584
+ env["HVU_DEVICE"] = args.device
1585
+ if args.debug:
1586
+ env["HVU_DEBUG"] = "1"
1587
+ env["HVU_OPEN_BROWSER"] = "0"
1588
+
1589
+ env["HVU_MODEL_DIR"] = str(context.local_model_dir)
1590
+ return env
1591
+
1592
+
1593
+ def port_available(host: str, port: int) -> bool:
1594
+ try:
1595
+ with socket.create_connection((host, port), timeout=0.4):
1596
+ return False
1597
+ except OSError:
1598
+ return True
1599
+
1600
+
1601
+ def choose_port(host: str, requested_port: Optional[int]) -> int:
1602
+ if requested_port is not None:
1603
+ if port_available(host, requested_port):
1604
+ return requested_port
1605
+ print_step(f"Port {requested_port} đang bận, đang tìm port khác...")
1606
+
1607
+ for port in range(5000, 5101):
1608
+ if port_available(host, port):
1609
+ return port
1610
+
1611
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
1612
+ sock.bind((host, 0))
1613
+ return int(sock.getsockname()[1])
1614
+
1615
+
1616
+ def wait_for_backend(url: str, process: subprocess.Popen, timeout: int = 45) -> None:
1617
+ deadline = time.time() + timeout
1618
+ last_error = ""
1619
+ while time.time() < deadline:
1620
+ if process.poll() is not None:
1621
+ raise RuntimeError(f"Backend dừng sớm với mã lỗi {process.returncode}.")
1622
+ try:
1623
+ with urllib.request.urlopen(url, timeout=2) as response:
1624
+ if 200 <= response.status < 500:
1625
+ return
1626
+ except Exception as exc: # noqa: BLE001
1627
+ last_error = str(exc)
1628
+ time.sleep(0.8)
1629
+ raise RuntimeError(f"Backend chưa sẵn sàng sau {timeout} giây. Lỗi gần nhất: {last_error}")
1630
+
1631
+
1632
+ def probe_backend_import(context: RuntimeContext, env: dict[str, str]) -> subprocess.CompletedProcess:
1633
+ return subprocess.run(
1634
+ [sys.executable, "-c", "from backend import create_app; app = create_app(); print('backend-ok')"],
1635
+ cwd=str(context.root),
1636
+ env=env,
1637
+ capture_output=True,
1638
+ text=True,
1639
+ encoding="utf-8",
1640
+ errors="replace",
1641
+ timeout=90,
1642
+ check=False,
1643
+ )
1644
+
1645
+
1646
+ def validate_backend_import(context: RuntimeContext, env: dict[str, str]) -> None:
1647
+ probe = probe_backend_import(context, env)
1648
+ if probe.returncode == 0:
1649
+ return
1650
+
1651
+ details = (probe.stderr or probe.stdout or "").strip()
1652
+ if "c10.dll" in details or "_load_dll_libraries" in details or "WinError 1114" in details:
1653
+ repair_torch_runtime(context, details[-1200:])
1654
+ retry = probe_backend_import(context, env)
1655
+ if retry.returncode == 0:
1656
+ return
1657
+ retry_details = (retry.stderr or retry.stdout or "").strip()
1658
+ raise RuntimeError(
1659
+ "PyTorch vẫn không load được DLL sau khi đã tự cài VC++ Redistributable và cài lại PyTorch CPU. "
1660
+ "Hãy khởi động lại Windows rồi chạy lại HVU_QA_tool.py. "
1661
+ f"Chi tiết: {retry_details[-1200:]}"
1662
+ )
1663
+
1664
+ raise RuntimeError(f"Backend chưa import được trước khi khởi động. Chi tiết: {details[-1200:]}")
1665
+
1666
+
1667
+ def launch_app(context: RuntimeContext, args: argparse.Namespace) -> int:
1668
+ if not context.main_file.exists():
1669
+ raise FileNotFoundError(f"Không tìm thấy file chạy ứng dụng: {context.main_file}")
1670
+
1671
+ args.host = args.host or "127.0.0.1"
1672
+ args.port = choose_port(args.host, args.port)
1673
+ update_config(last_host=args.host, last_port=args.port)
1674
+ env = build_runtime_env(context, args)
1675
+ command = [sys.executable, str(context.main_file)]
1676
+ url = f"http://{env['HVU_HOST']}:{env['HVU_PORT']}"
1677
+ print_step("Đang kiểm tra backend trước khi chạy...")
1678
+ validate_backend_import(context, env)
1679
+ print_step("Đang khởi động backend...")
1680
+ process = subprocess.Popen(
1681
+ command,
1682
+ cwd=str(context.root),
1683
+ env=env,
1684
+ stdout=None,
1685
+ stderr=None,
1686
+ )
1687
+ wait_for_backend(url, process)
1688
+ print_step(f"Backend đã chạy tại {url}")
1689
+ if not args.no_browser:
1690
+ print_step("Đang mở giao diện hệ thống...")
1691
+ webbrowser.open(url)
1692
+ print_step("Hoàn tất, HỆ THỐNG SINH CÂU HỎI đã sẵn sàng.")
1693
+ return process.wait()
1694
+
1695
+
1696
+ def build_parser() -> argparse.ArgumentParser:
1697
+ parser = argparse.ArgumentParser(
1698
+ description=(
1699
+ "Launcher cho HVU_QA. Chạy không cần tham số để tự tải backend/frontend thật, "
1700
+ "tải model từ dataset Hugging Face, chuẩn bị CPU/GPU và mở giao diện web."
1701
+ ),
1702
+ )
1703
+ parser.add_argument("--repo-id", default=HF_DATASET_REPO_ID, help="Repo dataset trên Hugging Face.")
1704
+ parser.add_argument("--revision", default=HF_DATASET_REVISION, help="Revision trên Hugging Face.")
1705
+ parser.add_argument("--host", default=None, help="Host chạy Flask. Mặc định dùng HVU_HOST hoặc 127.0.0.1.")
1706
+ parser.add_argument("--port", type=int, default=None, help="Port chạy Flask. Mặc định dùng HVU_PORT hoặc 5000.")
1707
+ parser.add_argument(
1708
+ "--device",
1709
+ choices=["auto", "cpu", "cuda"],
1710
+ default=None,
1711
+ help="Thiết bị chạy model. Mặc định tự ưu tiên GPU NVIDIA/CUDA, nếu không có thì dùng CPU.",
1712
+ )
1713
+ parser.add_argument("--debug", action="store_true", help="Bật Flask debug.")
1714
+ parser.add_argument("--no-browser", action="store_true", help="Không tự mở trình duyệt.")
1715
+ parser.add_argument("--no-venv", action="store_true", help="Không tự tạo virtualenv riêng cho launcher.")
1716
+ parser.add_argument("--force-download", action="store_true", help="Tải lại runtime/model và ghi đè file local.")
1717
+ parser.add_argument("--min-free-gb", type=float, default=6.0, help="Dung lượng trống tối thiểu cần kiểm tra.")
1718
+ parser.set_defaults(best_model_only=False)
1719
+ parser.add_argument(
1720
+ "--best-model-only",
1721
+ dest="best_model_only",
1722
+ action="store_true",
1723
+ help="Chỉ tải thư mục best-model nếu muốn runtime nhẹ và chỉ hiện 1 model.",
1724
+ )
1725
+ parser.add_argument(
1726
+ "--full-model",
1727
+ dest="best_model_only",
1728
+ action="store_false",
1729
+ help="Tải đủ model gốc và best-model để giao diện hiện 2 lựa chọn (mặc định).",
1730
+ )
1731
+ parser.add_argument(
1732
+ "--runtime-dir",
1733
+ default="HVU_QA_runtime",
1734
+ help="Thư mục runtime standalone sẽ được tạo nếu không có full project hoặc khi ép standalone.",
1735
+ )
1736
+ parser.add_argument(
1737
+ "--force-standalone-runtime",
1738
+ action="store_true",
1739
+ help="Luôn dùng runtime standalone, kể cả khi đang đứng trong full project.",
1740
+ )
1741
+ parser.add_argument(
1742
+ "--force-runtime-refresh",
1743
+ action="store_true",
1744
+ help="Tải lại backend/frontend từ Hugging Face và ghi đè runtime local.",
1745
+ )
1746
+ return parser
1747
+
1748
+
1749
+ def main() -> int:
1750
+ if hasattr(sys.stdout, "reconfigure"):
1751
+ sys.stdout.reconfigure(encoding="utf-8")
1752
+ if hasattr(sys.stderr, "reconfigure"):
1753
+ sys.stderr.reconfigure(encoding="utf-8")
1754
+
1755
+ parser = build_parser()
1756
+ args = parser.parse_args()
1757
+
1758
+ run_base_preflight(args)
1759
+ bootstrap_exit_code = maybe_bootstrap_tool_venv(args)
1760
+ if bootstrap_exit_code is not None:
1761
+ return bootstrap_exit_code
1762
+
1763
+ print_step("Đang chuẩn bị HỆ THỐNG SINH CÂU HỎI...")
1764
+ context = resolve_runtime_context(args)
1765
+ check_write_access(context.root)
1766
+ check_disk_space(context.root, args.min_free_gb)
1767
+ ensure_huggingface_hub()
1768
+ check_internet_if_needed(context, args)
1769
+ prepare_runtime(
1770
+ context=context,
1771
+ repo_id=args.repo_id,
1772
+ revision=args.revision,
1773
+ force_download=args.force_download or args.force_runtime_refresh,
1774
+ )
1775
+
1776
+ selected_device, detected_gpus = select_runtime_device(args)
1777
+ platform_runtime_note(selected_device)
1778
+ check_dependency_internet_if_needed(selected_device, context)
1779
+ try:
1780
+ selected_device = ensure_runtime_dependencies(
1781
+ selected_device=selected_device,
1782
+ context=context,
1783
+ gpus=detected_gpus,
1784
+ )
1785
+ except RuntimeError as exc:
1786
+ if selected_device != "cuda":
1787
+ raise
1788
+ print_step(f"GPU/CUDA chưa dùng được ({exc}). Hệ thống sẽ chuyển sang CPU.")
1789
+ selected_device = ensure_runtime_dependencies(
1790
+ selected_device="cpu",
1791
+ context=context,
1792
+ gpus=detected_gpus,
1793
+ )
1794
+ args.device = selected_device
1795
+ update_config(
1796
+ device=selected_device,
1797
+ runtime_root=str(context.root),
1798
+ model_dir=str(context.local_model_dir),
1799
+ last_port=args.port,
1800
+ )
1801
+
1802
+ prepare_model(
1803
+ context=context,
1804
+ repo_id=args.repo_id,
1805
+ revision=args.revision,
1806
+ force_download=args.force_download,
1807
+ best_model_only=args.best_model_only,
1808
+ )
1809
+
1810
+ return launch_app(context, args)
1811
+
1812
+
1813
+ def pause_on_error() -> None:
1814
+ if not IS_WINDOWS:
1815
+ return
1816
+ if os.getenv("HVU_NO_PAUSE_ON_ERROR", "").strip().lower() in {"1", "true", "yes", "on"}:
1817
+ return
1818
+ try:
1819
+ input("Nhấn Enter để thoát...")
1820
+ except EOFError:
1821
+ os.system("pause")
1822
+
1823
+
1824
+ def write_error_log(exc: BaseException) -> Path:
1825
+ LOG_DIR.mkdir(parents=True, exist_ok=True)
1826
+ log_file = LOG_DIR / "HVU_QA_tool_error.log"
1827
+ details = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
1828
+ log_file.write_text(details, encoding="utf-8")
1829
+ return log_file
1830
+
1831
+
1832
+ def run_main() -> int:
1833
+ setup_logging()
1834
+ try:
1835
+ return main()
1836
+ except KeyboardInterrupt:
1837
+ print_step("Đã dừng theo yêu cầu người dùng.")
1838
+ return 130
1839
+ except Exception as exc: # noqa: BLE001
1840
+ print_step(f"Lỗi: {exc}")
1841
+ logging.exception("Launcher failed")
1842
+ log_file = write_error_log(exc)
1843
+ print_step(f"Đã ghi log lỗi tại: {log_file}")
1844
+ print_step("Chi tiết lỗi:")
1845
+ traceback.print_exc()
1846
+ pause_on_error()
1847
+ return 1
1848
+
1849
+
1850
+ if __name__ == "__main__":
1851
+ raise SystemExit(run_main())