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