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