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