| from __future__ import annotations |
|
|
| import argparse |
| import csv |
| import fnmatch |
| import importlib.metadata |
| import importlib.util |
| import json |
| import logging |
| import os |
| import platform |
| import socket |
| import shutil |
| import subprocess |
| import sys |
| import time |
| import traceback |
| import urllib.error |
| import urllib.request |
| import webbrowser |
| from dataclasses import dataclass |
| from pathlib import Path |
| from typing import Optional |
|
|
| SCRIPT_ROOT = Path(__file__).resolve().parent |
| PLATFORM_SYSTEM = platform.system().lower() |
| IS_WINDOWS = os.name == "nt" |
| IS_MACOS = PLATFORM_SYSTEM == "darwin" |
| IS_LINUX = PLATFORM_SYSTEM == "linux" |
| MIN_PYTHON = (3, 10) |
| TOOL_VENV_DIR = SCRIPT_ROOT / ".hvu_qa_env" |
| TOOL_VENV_PYTHON = TOOL_VENV_DIR / ("Scripts/python.exe" if IS_WINDOWS else "bin/python") |
| CONFIG_FILE = SCRIPT_ROOT / ".hvu_qa_config.json" |
| LOG_DIR = SCRIPT_ROOT / "logs" |
| LOG_FILE = LOG_DIR / "HVU_QA_tool.log" |
|
|
| HF_DATASET_REPO_ID = "DANGDOCAO/GeneratingQuestions" |
| HF_DATASET_REVISION = "main" |
| HF_PROJECT_SUBDIR = "HVU_QA" |
| HF_MODEL_SUBDIR = f"{HF_PROJECT_SUBDIR}/t5-viet-qg-finetuned" |
| HF_BEST_MODEL_SUBDIR = f"{HF_MODEL_SUBDIR}/best-model" |
|
|
| HF_HUB_REQUIREMENT = "huggingface_hub>=0.23.0,<1.0.0" |
| TORCH_REQUIREMENT = "torch>=2.2.0,<3.0.0" |
| RUNTIME_REQUIREMENTS = [ |
| "accelerate>=1.1.0,<2.0.0", |
| "Flask>=3.0.0,<4.0.0", |
| "flask-cors>=4.0.0,<7.0.0", |
| HF_HUB_REQUIREMENT, |
| "numpy>=1.26.0,<2.0.0", |
| "packaging>=23.2,<26.0", |
| "requests>=2.31.0,<3.0.0", |
| "safetensors>=0.4.3,<1.0.0", |
| "sentencepiece>=0.2.0,<1.0.0", |
| TORCH_REQUIREMENT, |
| "tqdm>=4.66.0,<5.0.0", |
| "transformers>=4.41.0,<4.42.0", |
| ] |
| DEPENDENCY_IMPORTS = { |
| "accelerate": "accelerate", |
| "Flask": "flask", |
| "flask-cors": "flask_cors", |
| "huggingface_hub": "huggingface_hub", |
| "numpy": "numpy", |
| "packaging": "packaging", |
| "requests": "requests", |
| "safetensors": "safetensors", |
| "sentencepiece": "sentencepiece", |
| "tqdm": "tqdm", |
| "transformers": "transformers", |
| } |
| LOCAL_PROJECT_MARKERS = [ |
| "main.py", |
| "backend/app.py", |
| "frontend/index.html", |
| "generate_question.py", |
| ] |
| RUNTIME_REQUIRED_FILES = [ |
| "requirements.txt", |
| "main.py", |
| "backend/app.py", |
| "generate_question.py", |
| "frontend/index.html", |
| ] |
| RUNTIME_ALLOW_PATTERNS = [ |
| f"{HF_PROJECT_SUBDIR}/requirements.txt", |
| f"{HF_PROJECT_SUBDIR}/main.py", |
| f"{HF_PROJECT_SUBDIR}/generate_question.py", |
| f"{HF_PROJECT_SUBDIR}/backend/**", |
| f"{HF_PROJECT_SUBDIR}/frontend/**", |
| ] |
| RUNTIME_IGNORE_PATTERNS = [ |
| f"{HF_PROJECT_SUBDIR}/**/__pycache__/**", |
| f"{HF_PROJECT_SUBDIR}/**/*.pyc", |
| ] |
| MODEL_IGNORE_PATTERNS = [ |
| f"{HF_MODEL_SUBDIR}/checkpoint-*/**", |
| f"{HF_MODEL_SUBDIR}/all_results.json", |
| f"{HF_MODEL_SUBDIR}/eval_results.json", |
| f"{HF_MODEL_SUBDIR}/train_results.json", |
| f"{HF_MODEL_SUBDIR}/trainer_state.json", |
| f"{HF_MODEL_SUBDIR}/training_summary.json", |
| f"{HF_MODEL_SUBDIR}/training_args.bin", |
| f"{HF_BEST_MODEL_SUBDIR}/training_args.bin", |
| ] |
| PYTORCH_CPU_INDEX_URL = "https://download.pytorch.org/whl/cpu" |
| VC_REDIST_X64_URL = "https://aka.ms/vc14/vc_redist.x64.exe" |
| VC_REDIST_CACHE = SCRIPT_ROOT / ".hvu_qa_cache" / "vc_redist.x64.exe" |
| VC_REDIST_SUCCESS_CODES = {0, 1638, 3010} |
|
|
|
|
| @dataclass(frozen=True) |
| class RuntimeContext: |
| root: Path |
| main_file: Path |
| requirements_file: Path |
| local_model_dir: Path |
| local_best_model_dir: Path |
| standalone_mode: bool |
|
|
|
|
| @dataclass(frozen=True) |
| class GpuInfo: |
| name: str |
| driver_version: Optional[str] = None |
| compute_capability: Optional[str] = None |
| vendor: str = "NVIDIA" |
|
|
|
|
| @dataclass(frozen=True) |
| class SystemProfile: |
| os_key: str |
| os_label: str |
| platform_name: str |
| release: str |
| machine: str |
| processor: str |
| python_version: str |
| python_bits: int |
| python_executable: str |
|
|
| @property |
| def is_64bit_python(self) -> bool: |
| return self.python_bits == 64 |
|
|
| @property |
| def is_arm64(self) -> bool: |
| return self.machine.lower() in {"arm64", "aarch64"} |
|
|
| @property |
| def is_x64(self) -> bool: |
| return self.machine.lower() in {"amd64", "x86_64", "x64"} |
|
|
|
|
| @dataclass(frozen=True) |
| class PytorchCudaWheel: |
| tag: str |
| index_url: str |
| min_driver_major: int |
| min_driver_minor: int = 0 |
| torch_requirement: str = TORCH_REQUIREMENT |
| companion_requirements: tuple[str, ...] = () |
|
|
|
|
| |
| |
| PYTORCH_CUDA_WHEELS = [ |
| PytorchCudaWheel("cu128", "https://download.pytorch.org/whl/cu128", 572, 0), |
| PytorchCudaWheel("cu126", "https://download.pytorch.org/whl/cu126", 560, 0), |
| PytorchCudaWheel("cu118", "https://download.pytorch.org/whl/cu118", 522, 0), |
| PytorchCudaWheel( |
| "cu117", |
| "https://download.pytorch.org/whl/cu117", |
| 516, |
| 1, |
| "torch==2.0.1+cu117", |
| ("numpy>=1.26.0,<2.0.0", "transformers>=4.41.0,<4.42.0"), |
| ), |
| ] |
|
|
|
|
| def setup_logging() -> None: |
| LOG_DIR.mkdir(parents=True, exist_ok=True) |
| logging.basicConfig( |
| level=logging.INFO, |
| format="%(asctime)s [%(levelname)s] %(message)s", |
| handlers=[ |
| logging.FileHandler(LOG_FILE, encoding="utf-8"), |
| ], |
| ) |
|
|
|
|
| def print_step(message: str) -> None: |
| text = f"[HVU_QA_tool] {message}" |
| logging.info(message) |
| try: |
| print(text) |
| except UnicodeEncodeError: |
| encoding = getattr(sys.stdout, "encoding", None) or "utf-8" |
| safe_text = text.encode(encoding, errors="backslashreplace").decode(encoding, errors="ignore") |
| print(safe_text) |
|
|
|
|
| def load_config() -> dict[str, object]: |
| if not CONFIG_FILE.exists(): |
| return {} |
| try: |
| payload = json.loads(CONFIG_FILE.read_text(encoding="utf-8")) |
| except (OSError, json.JSONDecodeError): |
| return {} |
| return payload if isinstance(payload, dict) else {} |
|
|
|
|
| def save_config(config: dict[str, object]) -> None: |
| CONFIG_FILE.write_text(json.dumps(config, ensure_ascii=False, indent=2), encoding="utf-8") |
|
|
|
|
| def update_config(**values: object) -> None: |
| config = load_config() |
| config.update(values) |
| save_config(config) |
|
|
|
|
| def python_version_label() -> str: |
| return ".".join(str(part) for part in sys.version_info[:3]) |
|
|
|
|
| def collect_system_profile() -> SystemProfile: |
| if IS_WINDOWS: |
| os_key = "windows" |
| os_label = "Windows" |
| elif IS_MACOS: |
| os_key = "macos" |
| os_label = "macOS" |
| elif IS_LINUX: |
| os_key = "linux" |
| os_label = "Linux" |
| else: |
| os_key = PLATFORM_SYSTEM or sys.platform |
| os_label = platform.system() or sys.platform |
|
|
| return SystemProfile( |
| os_key=os_key, |
| os_label=os_label, |
| platform_name=sys.platform, |
| release=platform.release(), |
| machine=platform.machine() or "unknown", |
| processor=platform.processor() or "unknown", |
| python_version=python_version_label(), |
| python_bits=64 if sys.maxsize > 2**32 else 32, |
| python_executable=sys.executable, |
| ) |
|
|
|
|
| def system_profile_config(profile: SystemProfile) -> dict[str, object]: |
| return { |
| "os": profile.os_key, |
| "os_label": profile.os_label, |
| "platform": profile.platform_name, |
| "release": profile.release, |
| "machine": profile.machine, |
| "processor": profile.processor, |
| "python_version": profile.python_version, |
| "python_bits": profile.python_bits, |
| "python_executable": profile.python_executable, |
| } |
|
|
|
|
| def format_system_profile(profile: SystemProfile) -> str: |
| arch_label = "ARM64" if profile.is_arm64 else ("x64" if profile.is_x64 else profile.machine) |
| return ( |
| f"{profile.os_label} {profile.release} ({arch_label}), " |
| f"Python {profile.python_version} {profile.python_bits}-bit" |
| ) |
|
|
|
|
| def validate_system_profile(profile: SystemProfile) -> None: |
| if profile.os_key not in {"windows", "macos", "linux"}: |
| raise RuntimeError( |
| f"Hệ điều hành {profile.os_label} chưa được hỗ trợ tự động. " |
| "Tool hiện hỗ trợ Windows, macOS và Linux." |
| ) |
| if not profile.is_64bit_python: |
| raise RuntimeError( |
| "Python hiện tại là bản 32-bit nên không phù hợp để cài PyTorch/model NLP. " |
| "Vui lòng cài Python 64-bit rồi chạy lại `python HVU_QA_tool.py`." |
| ) |
|
|
|
|
| def check_python_version() -> None: |
| if sys.version_info >= MIN_PYTHON: |
| return |
| required = ".".join(str(part) for part in MIN_PYTHON) |
| raise RuntimeError( |
| f"Python hiện tại là {python_version_label()}, chưa phù hợp. " |
| f"Vui lòng cài Python {required} trở lên rồi chạy lại `python HVU_QA_tool.py`." |
| ) |
|
|
|
|
| def check_python_module(module_name: str, friendly_name: str) -> None: |
| completed = subprocess.run( |
| [sys.executable, "-m", module_name, "--help"], |
| capture_output=True, |
| text=True, |
| encoding="utf-8", |
| errors="replace", |
| check=False, |
| ) |
| if completed.returncode != 0: |
| raise RuntimeError( |
| f"Python hiện tại chưa dùng được module `{module_name}` ({friendly_name}). " |
| "Hãy cài lại Python và bật tùy chọn pip/venv khi cài đặt." |
| ) |
|
|
|
|
| def check_write_access(path: Path) -> None: |
| path.mkdir(parents=True, exist_ok=True) |
| probe = path / ".hvu_write_test" |
| try: |
| probe.write_text("ok", encoding="utf-8") |
| probe.unlink(missing_ok=True) |
| except OSError as exc: |
| raise RuntimeError(f"Không có quyền ghi vào thư mục {path}: {exc}") from exc |
|
|
|
|
| def has_complete_runtime(context: RuntimeContext) -> bool: |
| return all((context.root / relative).exists() for relative in RUNTIME_REQUIRED_FILES) |
|
|
|
|
| def has_complete_model(context: RuntimeContext, best_model_only: bool) -> bool: |
| return all(path.exists() for path in required_model_files(context, best_model_only)) |
|
|
|
|
| def internet_available(url: str = "https://huggingface.co", timeout: int = 8) -> bool: |
| try: |
| with urllib.request.urlopen(url, timeout=timeout): |
| return True |
| except (OSError, urllib.error.URLError): |
| return False |
|
|
|
|
| def check_internet_if_needed(context: RuntimeContext, args: argparse.Namespace) -> None: |
| needs_runtime = args.force_download or args.force_runtime_refresh or not has_complete_runtime(context) |
| needs_model = args.force_download or not has_complete_model(context, args.best_model_only) |
| if not needs_runtime and not needs_model: |
| print_step("Runtime và model đã có sẵn, không cần tải thêm từ Internet.") |
| return |
| print_step("Đang kiểm tra kết nối Internet...") |
| if internet_available(): |
| return |
| raise RuntimeError( |
| "Không kết nối được tới Hugging Face. Hãy kiểm tra Internet/proxy rồi chạy lại." |
| ) |
|
|
|
|
| def check_disk_space(path: Path, min_free_gb: float) -> None: |
| free_bytes = shutil.disk_usage(path).free |
| required_bytes = int(min_free_gb * 1024**3) |
| if free_bytes < required_bytes: |
| raise RuntimeError( |
| f"Dung lượng trống tại {path} chỉ còn {format_bytes(free_bytes)}. " |
| f"Cần tối thiểu khoảng {min_free_gb:g} GB để tải và chạy hệ thống." |
| ) |
| print_step(f"Dung lượng trống khả dụng: {format_bytes(free_bytes)}.") |
|
|
|
|
| def run_base_preflight(args: argparse.Namespace) -> None: |
| print_step("Đang kiểm tra môi trường...") |
| check_python_version() |
| profile = collect_system_profile() |
| print_step(f"Thiết bị phát hiện: {format_system_profile(profile)}.") |
| validate_system_profile(profile) |
| check_python_module("pip", "pip") |
| if not args.no_venv: |
| check_python_module("venv", "môi trường ảo") |
| check_write_access(SCRIPT_ROOT) |
| update_config(system_profile=system_profile_config(profile)) |
|
|
|
|
| def module_exists(module_name: str) -> bool: |
| return importlib.util.find_spec(module_name) is not None |
|
|
|
|
| def subprocess_env(env: Optional[dict[str, str]] = None) -> dict[str, str]: |
| merged = os.environ.copy() |
| merged.setdefault("PYTHONIOENCODING", "utf-8") |
| merged.setdefault("PYTHONUTF8", "1") |
| merged.setdefault("PIP_NO_COLOR", "1") |
| merged.setdefault("PIP_DISABLE_PIP_VERSION_CHECK", "1") |
| if env: |
| merged.update(env) |
| return merged |
|
|
|
|
| def run_command( |
| command: list[str], |
| *, |
| cwd: Optional[Path] = None, |
| env: Optional[dict[str, str]] = None, |
| ) -> None: |
| subprocess.check_call(command, cwd=str(cwd) if cwd else None, env=subprocess_env(env)) |
|
|
|
|
| def try_run_command( |
| command: list[str], |
| *, |
| cwd: Optional[Path] = None, |
| env: Optional[dict[str, str]] = None, |
| ) -> bool: |
| try: |
| run_command(command, cwd=cwd, env=env) |
| except subprocess.CalledProcessError: |
| return False |
| return True |
|
|
|
|
| def run_command_capture(command: list[str], *, cwd: Optional[Path] = None) -> subprocess.CompletedProcess: |
| return subprocess.run( |
| command, |
| cwd=str(cwd) if cwd else None, |
| env=subprocess_env(), |
| capture_output=True, |
| text=True, |
| encoding="utf-8", |
| errors="replace", |
| check=False, |
| ) |
|
|
|
|
| def is_running_in_virtualenv() -> bool: |
| return sys.prefix != getattr(sys, "base_prefix", sys.prefix) or bool(os.getenv("VIRTUAL_ENV")) |
|
|
|
|
| def is_running_in_tool_venv() -> bool: |
| try: |
| return Path(sys.executable).resolve() == TOOL_VENV_PYTHON.resolve() |
| except OSError: |
| return False |
|
|
|
|
| def format_bytes(size: int) -> str: |
| units = ["B", "KB", "MB", "GB", "TB"] |
| value = float(size) |
| for unit in units: |
| if value < 1024 or unit == units[-1]: |
| if unit == "B": |
| return f"{int(value)} {unit}" |
| return f"{value:.1f} {unit}" |
| value /= 1024 |
| return f"{size} B" |
|
|
|
|
| def render_progress_bar(current: int, total: int, width: int = 28) -> str: |
| if total <= 0: |
| return "[----------------------------] 0.0%" |
| ratio = max(0.0, min(1.0, current / total)) |
| filled = int(ratio * width) |
| return f"[{'#' * filled}{'-' * (width - filled)}] {ratio * 100:5.1f}%" |
|
|
|
|
| def matches_any_pattern(path: str, patterns: list[str]) -> bool: |
| normalized = path.replace("\\", "/") |
| return any(fnmatch.fnmatch(normalized, pattern) for pattern in patterns) |
|
|
|
|
| def has_local_project(root: Path) -> bool: |
| return all((root / marker).exists() for marker in LOCAL_PROJECT_MARKERS) |
|
|
|
|
| def resolve_runtime_context(args: argparse.Namespace) -> RuntimeContext: |
| use_local_project = has_local_project(SCRIPT_ROOT) and not args.force_standalone_runtime |
| if use_local_project: |
| runtime_root = SCRIPT_ROOT |
| standalone_mode = False |
| else: |
| requested_runtime_dir = Path(args.runtime_dir).expanduser() |
| if not requested_runtime_dir.is_absolute(): |
| requested_runtime_dir = SCRIPT_ROOT / requested_runtime_dir |
| runtime_root = requested_runtime_dir.resolve() |
| standalone_mode = True |
|
|
| context = RuntimeContext( |
| root=runtime_root, |
| main_file=runtime_root / "main.py", |
| requirements_file=runtime_root / "requirements.txt", |
| local_model_dir=runtime_root / "t5-viet-qg-finetuned", |
| local_best_model_dir=runtime_root / "t5-viet-qg-finetuned" / "best-model", |
| standalone_mode=standalone_mode, |
| ) |
| mode_label = "standalone" if standalone_mode else "full project" |
| print_step(f"Runtime mode: {mode_label}") |
| print_step(f"Runtime root: {context.root}") |
| return context |
|
|
|
|
| def maybe_bootstrap_tool_venv(args: argparse.Namespace) -> Optional[int]: |
| if args.no_venv or is_running_in_tool_venv(): |
| return None |
|
|
| if not TOOL_VENV_PYTHON.exists(): |
| print_step("Không phát hiện virtualenv hiện tại. Đang tạo môi trường riêng cho launcher...") |
| run_command([sys.executable, "-m", "venv", str(TOOL_VENV_DIR)], cwd=SCRIPT_ROOT) |
| run_command( |
| [str(TOOL_VENV_PYTHON), "-m", "pip", "install", "--upgrade", "pip", "setuptools", "wheel"], |
| cwd=SCRIPT_ROOT, |
| ) |
|
|
| relaunch_env = os.environ.copy() |
| relaunch_env["HVU_QA_TOOL_BOOTSTRAPPED"] = "1" |
| relaunch_env = subprocess_env(relaunch_env) |
| relaunch_command = [str(TOOL_VENV_PYTHON), str(Path(__file__).resolve()), *sys.argv[1:]] |
|
|
| print_step("Đang chuyển sang môi trường Python riêng của launcher...") |
| return subprocess.call(relaunch_command, cwd=str(SCRIPT_ROOT), env=relaunch_env) |
|
|
|
|
| def ensure_huggingface_hub() -> None: |
| if module_exists("huggingface_hub"): |
| return |
|
|
| if not internet_available(): |
| raise RuntimeError( |
| "Thiếu huggingface_hub và không có Internet để cài tự động. " |
| f"Vui lòng kết nối mạng rồi chạy lại: {sys.executable} HVU_QA_tool.py" |
| ) |
| print_step("Thiếu huggingface_hub. Đang cài tự động...") |
| run_command([sys.executable, "-m", "pip", "install", HF_HUB_REQUIREMENT], cwd=SCRIPT_ROOT) |
|
|
|
|
| def dependency_install_needs_internet(selected_device: str, context: RuntimeContext) -> bool: |
| if pending_non_torch_requirement_specs(context): |
| return True |
| torch_info = inspect_installed_torch() |
| if not torch_info.get("installed"): |
| return True |
| return selected_device == "cuda" and not torch_info.get("cuda_available") |
|
|
|
|
| def check_dependency_internet_if_needed(selected_device: str, context: RuntimeContext) -> None: |
| if not dependency_install_needs_internet(selected_device, context): |
| return |
| print_step("Đang kiểm tra Internet trước khi cài thư viện...") |
| if internet_available(): |
| return |
| raise RuntimeError( |
| "Cần Internet để cài hoặc cập nhật thư viện Python. " |
| "Hãy kết nối mạng rồi chạy lại." |
| ) |
|
|
|
|
| def requirement_name(spec: str) -> str: |
| cleaned = spec.split("#", 1)[0].strip() |
| chars: list[str] = [] |
| for char in cleaned: |
| if char.isalnum() or char in {"_", "-"}: |
| chars.append(char) |
| continue |
| break |
| return "".join(chars).lower().replace("_", "-") |
|
|
|
|
| def read_requirement_specs(context: RuntimeContext) -> list[str]: |
| specs: list[str] = [] |
| for line in RUNTIME_REQUIREMENTS: |
| stripped = line.strip() |
| if stripped and not stripped.startswith("#"): |
| specs.append(stripped) |
| return specs |
|
|
|
|
| def non_torch_requirement_specs(context: RuntimeContext) -> list[str]: |
| return [ |
| spec |
| for spec in read_requirement_specs(context) |
| if requirement_name(spec) not in {"torch", "torchvision", "torchaudio"} |
| ] |
|
|
|
|
| def pending_non_torch_requirement_specs(context: RuntimeContext) -> list[str]: |
| pending: list[str] = [] |
| for spec in non_torch_requirement_specs(context): |
| package_name = requirement_name(spec) |
| module_name = DEPENDENCY_IMPORTS.get(package_name) |
| if module_name and not module_exists(module_name): |
| pending.append(spec) |
| continue |
| if not requirement_satisfied(spec): |
| pending.append(spec) |
| return pending |
|
|
|
|
| def find_missing_dependencies() -> list[str]: |
| missing: list[str] = [] |
| for package_name, module_name in DEPENDENCY_IMPORTS.items(): |
| if not module_exists(module_name): |
| missing.append(package_name) |
| return missing |
|
|
|
|
| def install_non_torch_dependencies(context: RuntimeContext) -> None: |
| specs = pending_non_torch_requirement_specs(context) |
| if not specs: |
| print_step("Môi trường Python đã có đủ dependency runtime ngoài PyTorch.") |
| return |
|
|
| print_step("Đang cài/cập nhật dependency runtime: " + ", ".join(specs)) |
| run_command([sys.executable, "-m", "pip", "install", "--upgrade", *specs], cwd=context.root) |
|
|
|
|
| def inspect_installed_torch() -> dict[str, object]: |
| probe_code = r""" |
| import json |
| |
| try: |
| import torch |
| except Exception as exc: |
| print(json.dumps({"installed": False, "error": str(exc)})) |
| raise SystemExit(0) |
| |
| cuda_available = False |
| gpu_names = [] |
| try: |
| cuda_available = bool(torch.cuda.is_available()) |
| if cuda_available: |
| gpu_names = [torch.cuda.get_device_name(index) for index in range(torch.cuda.device_count())] |
| except Exception: |
| cuda_available = False |
| |
| print(json.dumps({ |
| "installed": True, |
| "version": getattr(torch, "__version__", ""), |
| "cuda_version": getattr(getattr(torch, "version", None), "cuda", None), |
| "cuda_available": cuda_available, |
| "gpu_names": gpu_names, |
| })) |
| """ |
| completed = subprocess.run( |
| [sys.executable, "-c", probe_code], |
| capture_output=True, |
| text=True, |
| encoding="utf-8", |
| errors="replace", |
| check=False, |
| ) |
| if completed.returncode != 0 or not completed.stdout.strip(): |
| return {"installed": False, "error": completed.stderr.strip()} |
|
|
| try: |
| payload = json.loads(completed.stdout.strip().splitlines()[-1]) |
| except json.JSONDecodeError as exc: |
| return {"installed": False, "error": str(exc)} |
|
|
| return payload if isinstance(payload, dict) else {"installed": False, "error": "Invalid torch probe output"} |
|
|
|
|
| def parse_driver_version(value: Optional[str]) -> Optional[tuple[int, int]]: |
| if not value: |
| return None |
| parts = value.strip().split(".") |
| if not parts or not parts[0].isdigit(): |
| return None |
| major = int(parts[0]) |
| minor = int(parts[1]) if len(parts) > 1 and parts[1].isdigit() else 0 |
| return major, minor |
|
|
|
|
| def detect_nvidia_gpus() -> list[GpuInfo]: |
| command = [ |
| "nvidia-smi", |
| "--query-gpu=name,driver_version,compute_cap", |
| "--format=csv,noheader,nounits", |
| ] |
| try: |
| completed = subprocess.run( |
| command, |
| capture_output=True, |
| text=True, |
| encoding="utf-8", |
| errors="replace", |
| timeout=8, |
| check=False, |
| ) |
| except (FileNotFoundError, subprocess.SubprocessError): |
| return detect_windows_nvidia_gpus() |
|
|
| if completed.returncode != 0 or not completed.stdout.strip(): |
| return detect_windows_nvidia_gpus() |
|
|
| gpus: list[GpuInfo] = [] |
| for row in csv.reader(completed.stdout.splitlines()): |
| if not row: |
| continue |
| name = row[0].strip() |
| driver_version = row[1].strip() if len(row) > 1 and row[1].strip() else None |
| compute_capability = row[2].strip() if len(row) > 2 and row[2].strip() else None |
| gpus.append(GpuInfo(name=name, driver_version=driver_version, compute_capability=compute_capability)) |
| return gpus |
|
|
|
|
| def detect_windows_nvidia_gpus() -> list[GpuInfo]: |
| if not IS_WINDOWS: |
| return [] |
|
|
| command = [ |
| "powershell", |
| "-NoProfile", |
| "-Command", |
| ( |
| "Get-CimInstance Win32_VideoController | " |
| "Where-Object { $_.Name -match 'NVIDIA' } | " |
| "Select-Object Name,DriverVersion | ConvertTo-Json -Compress" |
| ), |
| ] |
| try: |
| completed = subprocess.run( |
| command, |
| capture_output=True, |
| text=True, |
| encoding="utf-8", |
| errors="replace", |
| timeout=8, |
| check=False, |
| ) |
| except (FileNotFoundError, subprocess.SubprocessError): |
| return [] |
|
|
| if completed.returncode != 0: |
| return [] |
|
|
| raw = completed.stdout.strip() |
| if not raw: |
| return [] |
|
|
| try: |
| payload = json.loads(raw) |
| except json.JSONDecodeError: |
| names = [line.strip() for line in completed.stdout.splitlines() if line.strip()] |
| return [GpuInfo(name=name) for name in names if "nvidia" in name.lower()] |
|
|
| items = payload if isinstance(payload, list) else [payload] |
| gpus: list[GpuInfo] = [] |
| for item in items: |
| if not isinstance(item, dict): |
| continue |
| name = str(item.get("Name") or "").strip() |
| if not name or "nvidia" not in name.lower(): |
| continue |
| gpus.append(GpuInfo(name=name, driver_version=normalize_windows_driver_version(item.get("DriverVersion")))) |
| return gpus |
|
|
|
|
| def normalize_windows_driver_version(value: object) -> Optional[str]: |
| text = str(value or "").strip() |
| if not text: |
| return None |
| parts = text.split(".") |
| if len(parts) >= 4 and parts[-1].isdigit(): |
| tail = parts[-1] |
| if len(tail) >= 5: |
| return f"{int(tail[:-2])}.{tail[-2:]}" |
| return text |
|
|
|
|
| def format_gpu_list(gpus: list[GpuInfo]) -> str: |
| labels: list[str] = [] |
| for index, gpu in enumerate(gpus): |
| details: list[str] = [] |
| if gpu.driver_version: |
| details.append(f"driver {gpu.driver_version}") |
| if gpu.compute_capability: |
| details.append(f"compute {gpu.compute_capability}") |
| suffix = f" ({', '.join(details)})" if details else "" |
| labels.append(f"GPU {index}: {gpu.name}{suffix}") |
| return "; ".join(labels) |
|
|
|
|
| def select_runtime_device(args: argparse.Namespace) -> tuple[str, list[GpuInfo]]: |
| requested = (args.device or os.getenv("HVU_DEVICE") or "auto").strip().lower() |
| if requested == "cpu": |
| print_step("Đã chọn CPU theo tham số chạy.") |
| return "cpu", [] |
|
|
| gpus = detect_nvidia_gpus() |
| if requested == "cuda": |
| if gpus: |
| print_step(f"Đang sử dụng GPU: {format_gpu_list(gpus)}") |
| else: |
| print_step("Đã chọn CUDA nhưng chưa phát hiện GPU NVIDIA bằng nvidia-smi/WMI.") |
| return "cuda", gpus |
|
|
| if not gpus: |
| print_step("Không phát hiện GPU NVIDIA CUDA. Chương trình sẽ dùng CPU.") |
| update_config(device="cpu") |
| return "cpu", [] |
|
|
| print_step(f"Phát hiện GPU NVIDIA CUDA, ưu tiên chạy bằng GPU: {format_gpu_list(gpus)}") |
| update_config(device="cuda") |
| return "cuda", gpus |
|
|
|
|
| def cuda_wheel_candidates(gpus: list[GpuInfo]) -> list[PytorchCudaWheel]: |
| override_url = os.getenv("HVU_PYTORCH_CUDA_INDEX_URL") |
| if override_url: |
| override_tag = os.getenv("HVU_PYTORCH_CUDA_TAG", "custom") |
| override_requirement = os.getenv("HVU_PYTORCH_TORCH_REQUIREMENT", TORCH_REQUIREMENT) |
| return [PytorchCudaWheel(override_tag, override_url, 0, 0, override_requirement)] |
|
|
| driver = parse_driver_version(next((gpu.driver_version for gpu in gpus if gpu.driver_version), None)) |
| if driver is None: |
| return PYTORCH_CUDA_WHEELS[:] |
|
|
| return [ |
| wheel |
| for wheel in PYTORCH_CUDA_WHEELS |
| if driver >= (wheel.min_driver_major, wheel.min_driver_minor) |
| ] |
|
|
|
|
| def describe_cuda_selection(gpus: list[GpuInfo], candidates: list[PytorchCudaWheel]) -> None: |
| driver_text = next((gpu.driver_version for gpu in gpus if gpu.driver_version), None) |
| if driver_text: |
| if candidates: |
| print_step( |
| f"Driver NVIDIA {driver_text}; chọn CUDA wheel tương thích cao nhất: " |
| f"{candidates[0].tag}." |
| ) |
| else: |
| print_step(f"Driver NVIDIA {driver_text}; chưa có CUDA wheel PyTorch tương thích trực tiếp.") |
| return |
|
|
| if candidates: |
| print_step( |
| "Không đọc được phiên bản driver NVIDIA. Tool sẽ thử các CUDA wheel từ mới đến cũ." |
| ) |
|
|
|
|
| def winget_available() -> bool: |
| try: |
| completed = subprocess.run( |
| ["winget", "--version"], |
| capture_output=True, |
| text=True, |
| encoding="utf-8", |
| errors="replace", |
| timeout=20, |
| check=False, |
| ) |
| except (FileNotFoundError, subprocess.SubprocessError): |
| return False |
| return completed.returncode == 0 |
|
|
|
|
| def try_install_nvidia_cuda_support() -> bool: |
| if not IS_WINDOWS or not winget_available(): |
| return False |
|
|
| print_step( |
| "Không có CUDA wheel phù hợp với driver hiện tại. " |
| "Đang thử cài NVIDIA CUDA Toolkit chính thức qua winget để bổ sung/cập nhật hỗ trợ CUDA..." |
| ) |
| base_command = [ |
| "winget", |
| "install", |
| "--id", |
| "Nvidia.CUDA", |
| "--source", |
| "winget", |
| "--accept-package-agreements", |
| "--accept-source-agreements", |
| "--silent", |
| "--disable-interactivity", |
| ] |
| if try_run_command(base_command, cwd=SCRIPT_ROOT): |
| return True |
|
|
| 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.") |
| upgrade_command = [ |
| "winget", |
| "upgrade", |
| "--id", |
| "Nvidia.CUDA", |
| "--source", |
| "winget", |
| "--accept-package-agreements", |
| "--accept-source-agreements", |
| "--silent", |
| "--disable-interactivity", |
| ] |
| return try_run_command(upgrade_command, cwd=SCRIPT_ROOT) |
|
|
|
|
| def companion_requirements_for_torch(torch_info: dict[str, object]) -> tuple[str, ...]: |
| version = str(torch_info.get("version") or "") |
| if version.startswith("2.0."): |
| return ("numpy>=1.26.0,<2.0.0", "transformers>=4.41.0,<4.42.0") |
| return () |
|
|
|
|
| def requirement_satisfied(spec: str) -> bool: |
| try: |
| from packaging.requirements import Requirement |
| except Exception: |
| return False |
|
|
| try: |
| requirement = Requirement(spec) |
| installed_version = importlib.metadata.version(requirement.name) |
| except Exception: |
| return False |
|
|
| if not requirement.specifier: |
| return True |
| return installed_version in requirement.specifier |
|
|
|
|
| def ensure_companion_requirements(requirements: tuple[str, ...], context: RuntimeContext) -> None: |
| specs = tuple(dict.fromkeys(spec for spec in requirements if spec)) |
| if not specs: |
| return |
|
|
| pending_specs = tuple(spec for spec in specs if not requirement_satisfied(spec)) |
| if not pending_specs: |
| return |
|
|
| print_step("Dang cai dependency tuong thich voi PyTorch CUDA: " + ", ".join(pending_specs)) |
| run_command([sys.executable, "-m", "pip", "install", "--upgrade", *pending_specs], cwd=context.root) |
|
|
|
|
| def cpu_torch_install_commands(force_reinstall: bool) -> list[list[str]]: |
| base_command = [sys.executable, "-m", "pip", "install", "--upgrade"] |
| if force_reinstall: |
| base_command.append("--force-reinstall") |
|
|
| pypi_command = [*base_command, TORCH_REQUIREMENT] |
| cpu_index_command = [*base_command, TORCH_REQUIREMENT, "--index-url", PYTORCH_CPU_INDEX_URL] |
|
|
| |
| |
| profile = collect_system_profile() |
| if IS_MACOS or profile.is_arm64: |
| return [pypi_command, cpu_index_command] |
| return [cpu_index_command, pypi_command] |
|
|
|
|
| def install_cpu_torch(context: RuntimeContext, force_reinstall: bool = False) -> None: |
| commands = cpu_torch_install_commands(force_reinstall) |
| for index, command in enumerate(commands, start=1): |
| source_label = "PyPI" if "--index-url" not in command else "PyTorch CPU index" |
| if index == 1: |
| print_step(f"Đang cài PyTorch CPU từ {source_label}.") |
| else: |
| print_step(f"Nguồn cài trước chưa thành công, đang thử PyTorch CPU từ {source_label}.") |
| if try_run_command(command, cwd=context.root): |
| return |
|
|
| raise RuntimeError( |
| "Không cài được PyTorch CPU tự động. Hãy kiểm tra Internet, phiên bản Python 64-bit " |
| "và thử chạy lại `python HVU_QA_tool.py`." |
| ) |
|
|
|
|
| def platform_runtime_note(selected_device: str) -> None: |
| profile = collect_system_profile() |
| if profile.os_key == "windows": |
| print_step("Windows: tool sẽ tự xử lý virtualenv, pip, VC++ Redistributable khi cần, PyTorch CPU/CUDA.") |
| elif profile.os_key == "macos": |
| print_step("macOS: tool sẽ tự xử lý virtualenv, pip và PyTorch CPU/MPS wheel qua PyPI; CUDA không áp dụng.") |
| elif profile.os_key == "linux": |
| print_step("Linux: tool sẽ tự xử lý virtualenv, pip và PyTorch; GPU NVIDIA cần driver hệ thống đã sẵn sàng.") |
| if selected_device == "cuda" and profile.os_key != "windows": |
| 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.") |
|
|
|
|
| def is_torch_dll_error(torch_info: dict[str, object]) -> bool: |
| text = str(torch_info.get("error") or "") |
| markers = ("c10.dll", "_load_dll_libraries", "WinError 1114", "DLL initialization routine failed") |
| return any(marker.lower() in text.lower() for marker in markers) |
|
|
|
|
| def windows_is_admin() -> bool: |
| if not IS_WINDOWS: |
| return False |
| try: |
| import ctypes |
|
|
| return bool(ctypes.windll.shell32.IsUserAnAdmin()) |
| except Exception: |
| return False |
|
|
|
|
| def download_vc_redist() -> Path: |
| VC_REDIST_CACHE.parent.mkdir(parents=True, exist_ok=True) |
| if VC_REDIST_CACHE.exists() and VC_REDIST_CACHE.stat().st_size > 1_000_000: |
| return VC_REDIST_CACHE |
|
|
| if not internet_available(): |
| raise RuntimeError( |
| "Cần Internet để tải Microsoft Visual C++ Redistributable tự động." |
| ) |
|
|
| print_step("Đang tải Microsoft Visual C++ Redistributable 2015-2022 x64...") |
| with urllib.request.urlopen(VC_REDIST_X64_URL, timeout=60) as response: |
| VC_REDIST_CACHE.write_bytes(response.read()) |
| return VC_REDIST_CACHE |
|
|
|
|
| def run_vc_redist_installer(installer: Path) -> int: |
| args = "/install /quiet /norestart" |
| if windows_is_admin(): |
| completed = run_command_capture([str(installer), "/install", "/quiet", "/norestart"]) |
| return completed.returncode |
|
|
| 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.") |
| command = [ |
| "powershell", |
| "-NoProfile", |
| "-ExecutionPolicy", |
| "Bypass", |
| "-Command", |
| ( |
| "$p = Start-Process " |
| f"-FilePath {json.dumps(str(installer))} " |
| f"-ArgumentList {json.dumps(args)} " |
| "-Verb RunAs -Wait -PassThru; exit $p.ExitCode" |
| ), |
| ] |
| completed = run_command_capture(command) |
| return completed.returncode |
|
|
|
|
| def ensure_windows_vc_redist() -> bool: |
| if not IS_WINDOWS: |
| return False |
| if os.getenv("HVU_SKIP_VC_REDIST", "").strip().lower() in {"1", "true", "yes", "on"}: |
| return False |
|
|
| installer = download_vc_redist() |
| print_step("Đang cài Microsoft Visual C++ Redistributable 2015-2022 x64...") |
| exit_code = run_vc_redist_installer(installer) |
| if exit_code in VC_REDIST_SUCCESS_CODES: |
| if exit_code == 3010: |
| print_step("VC++ Redistributable đã cài xong và Windows có thể cần khởi động lại.") |
| else: |
| print_step("VC++ Redistributable đã sẵn sàng.") |
| return True |
|
|
| raise RuntimeError( |
| "Không cài được Microsoft Visual C++ Redistributable tự động " |
| 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." |
| ) |
|
|
|
|
| def repair_torch_runtime(context: RuntimeContext, reason: str) -> None: |
| print_step("Đang sửa lỗi PyTorch/DLL trước khi chạy backend...") |
| if IS_WINDOWS: |
| ensure_windows_vc_redist() |
| print_step("Đang cài lại PyTorch CPU ổn định...") |
| install_cpu_torch(context, force_reinstall=True) |
| torch_info = inspect_installed_torch() |
| if not torch_info.get("installed"): |
| raise RuntimeError( |
| "Đã thử sửa PyTorch nhưng vẫn chưa import được. " |
| f"Lỗi ban đầu: {reason}. Lỗi hiện tại: {torch_info.get('error')}" |
| ) |
|
|
|
|
| def ensure_pytorch_for_device( |
| selected_device: str, |
| context: RuntimeContext, |
| gpus: list[GpuInfo], |
| ) -> str: |
| torch_info = inspect_installed_torch() |
| if selected_device == "cuda": |
| if torch_info.get("cuda_available"): |
| ensure_companion_requirements(companion_requirements_for_torch(torch_info), context) |
| print_step(f"PyTorch CUDA đã dùng được ({torch_info.get('version')}).") |
| return "cuda" |
|
|
| candidates = cuda_wheel_candidates(gpus) |
| describe_cuda_selection(gpus, candidates) |
| if not candidates: |
| if try_install_nvidia_cuda_support(): |
| gpus = detect_nvidia_gpus() |
| candidates = cuda_wheel_candidates(gpus) |
| describe_cuda_selection(gpus, candidates) |
| if not candidates: |
| gpu_label = format_gpu_list(gpus) if gpus else "không đọc được thông tin GPU" |
| raise RuntimeError( |
| "Tool chưa tự chuẩn bị được CUDA cho GPU hiện tại. " |
| f"GPU/driver phát hiện: {gpu_label}." |
| ) |
|
|
| if torch_info.get("installed"): |
| print_step( |
| f"PyTorch hiện tại là {torch_info.get('version')} " |
| f"(cuda={torch_info.get('cuda_version')}). Đang cài lại bản CUDA phù hợp." |
| ) |
|
|
| for wheel in candidates: |
| print_step( |
| f"Đang cài PyTorch GPU phù hợp: {wheel.torch_requirement} " |
| f"({wheel.tag}) từ {wheel.index_url}" |
| ) |
| command = [ |
| sys.executable, |
| "-m", |
| "pip", |
| "install", |
| "--upgrade", |
| "--force-reinstall", |
| wheel.torch_requirement, |
| "--index-url", |
| wheel.index_url, |
| ] |
| installed_ok = try_run_command(command, cwd=context.root) |
| if installed_ok: |
| installed_info = inspect_installed_torch() |
| if installed_info.get("cuda_available"): |
| ensure_companion_requirements(wheel.companion_requirements, context) |
| print_step(f"PyTorch CUDA {wheel.tag} đã dùng được.") |
| return "cuda" |
| print_step( |
| f"Đã cài {wheel.tag} nhưng PyTorch vẫn chưa dùng được CUDA " |
| f"(version={installed_info.get('version')}, cuda={installed_info.get('cuda_version')}). " |
| "Tool sẽ thử CUDA wheel thấp hơn nếu có." |
| ) |
| else: |
| print_step(f"Cài PyTorch {wheel.tag} không thành công. Thử CUDA wheel thấp hơn nếu có.") |
|
|
| raise RuntimeError( |
| "Tool không cài được PyTorch CUDA phù hợp sau khi đã thử các phiên bản tương thích." |
| ) |
|
|
| if torch_info.get("installed"): |
| print_step(f"PyTorch đã sẵn sàng ({torch_info.get('version')}).") |
| ensure_companion_requirements(companion_requirements_for_torch(torch_info), context) |
| return "cpu" |
|
|
| error_text = str(torch_info.get("error") or "").strip() |
| if error_text: |
| print_step("PyTorch hiện tại bị lỗi khi import, đang cài lại bản CPU ổn định.") |
| print_step(f"Lỗi PyTorch: {error_text}") |
| if is_torch_dll_error(torch_info): |
| repair_torch_runtime(context, error_text) |
| return "cpu" |
| else: |
| print_step("Đang cài PyTorch CPU.") |
| install_cpu_torch(context, force_reinstall=bool(error_text)) |
| installed_info = inspect_installed_torch() |
| if not installed_info.get("installed"): |
| raise RuntimeError( |
| "Đã cài lại PyTorch CPU nhưng vẫn không import được. " |
| "Hãy cài Microsoft Visual C++ Redistributable 2015-2022 x64, khởi động lại máy rồi chạy lại. " |
| f"Chi tiết PyTorch: {installed_info.get('error')}" |
| ) |
| return "cpu" |
|
|
|
|
| def verify_selected_device(selected_device: str) -> str: |
| if selected_device != "cuda": |
| torch_info = inspect_installed_torch() |
| if not torch_info.get("installed"): |
| raise RuntimeError( |
| "PyTorch chưa import được sau bước cài đặt. " |
| f"Chi tiết: {torch_info.get('error')}" |
| ) |
| return "cpu" |
|
|
| torch_info = inspect_installed_torch() |
| if torch_info.get("cuda_available"): |
| gpu_names = ", ".join(str(name) for name in torch_info.get("gpu_names", [])) |
| suffix = f": {gpu_names}" if gpu_names else "" |
| print_step(f"PyTorch CUDA đã sẵn sàng{suffix}.") |
| return "cuda" |
|
|
| raise RuntimeError( |
| "Bạn đã chọn dùng GPU nhưng PyTorch chưa truy cập được CUDA sau khi cài đặt. " |
| f"Thông tin PyTorch: version={torch_info.get('version')}, cuda={torch_info.get('cuda_version')}, " |
| f"cuda_available={torch_info.get('cuda_available')}." |
| ) |
|
|
|
|
| def ensure_runtime_dependencies( |
| selected_device: str, |
| context: RuntimeContext, |
| gpus: list[GpuInfo], |
| ) -> str: |
| install_non_torch_dependencies(context=context) |
| selected_device = ensure_pytorch_for_device( |
| selected_device=selected_device, |
| context=context, |
| gpus=gpus, |
| ) |
| return verify_selected_device(selected_device) |
|
|
|
|
| def resolve_repo_files( |
| repo_id: str, |
| revision: str, |
| allow_patterns: list[str], |
| ignore_patterns: list[str], |
| ) -> list[dict[str, object]]: |
| from huggingface_hub import HfApi |
|
|
| api = HfApi() |
| repo_files = api.list_repo_tree(repo_id=repo_id, repo_type="dataset", revision=revision, recursive=True) |
|
|
| selected: list[dict[str, object]] = [] |
| for entry in repo_files: |
| path = str(getattr(entry, "path", "")).replace("\\", "/") |
| size = getattr(entry, "size", None) |
| if not path or path.endswith("/") or size is None: |
| continue |
| if not matches_any_pattern(path, allow_patterns): |
| continue |
| if matches_any_pattern(path, ignore_patterns): |
| continue |
| selected.append({"path": path, "size": size}) |
|
|
| return sorted(selected, key=lambda item: str(item["path"])) |
|
|
|
|
| def runtime_relative_path(repo_file: str) -> Optional[Path]: |
| normalized = repo_file.replace("\\", "/") |
| prefix = f"{HF_PROJECT_SUBDIR}/" |
| if matches_any_pattern(normalized, RUNTIME_ALLOW_PATTERNS): |
| return Path(normalized[len(prefix) :]) |
| return None |
|
|
|
|
| def model_destination(context: RuntimeContext, repo_file: str) -> Path: |
| normalized = repo_file.replace("\\", "/") |
| relative_path = Path(normalized).relative_to(HF_MODEL_SUBDIR) |
| return context.local_model_dir / relative_path |
|
|
|
|
| def sync_single_file( |
| source_file: Path, |
| destination_file: Path, |
| force_copy: bool, |
| *, |
| verify_content: bool = False, |
| ) -> tuple[bool, int]: |
| destination_file.parent.mkdir(parents=True, exist_ok=True) |
| size = source_file.stat().st_size |
|
|
| if destination_file.exists() and not force_copy and destination_file.stat().st_size == size: |
| if not verify_content or destination_file.read_bytes() == source_file.read_bytes(): |
| return False, size |
|
|
| shutil.copy2(source_file, destination_file) |
| return True, size |
|
|
|
|
| def download_and_sync_files( |
| context: RuntimeContext, |
| repo_id: str, |
| revision: str, |
| allow_patterns: list[str], |
| ignore_patterns: list[str], |
| force_download: bool, |
| scope_label: str, |
| ) -> tuple[int, int, int, int]: |
| from huggingface_hub import snapshot_download |
|
|
| repo_files = resolve_repo_files( |
| repo_id=repo_id, |
| revision=revision, |
| allow_patterns=allow_patterns, |
| ignore_patterns=ignore_patterns, |
| ) |
| if not repo_files: |
| raise FileNotFoundError( |
| f"Không tìm thấy file {scope_label} hợp lệ trong repo {repo_id}@{revision}. " |
| "Hãy kiểm tra lại cấu trúc dataset trên Hugging Face." |
| ) |
|
|
| total_files = len(repo_files) |
| total_bytes = sum(int(item["size"] or 0) for item in repo_files) |
| copied_files = 0 |
| skipped_files = 0 |
| copied_bytes = 0 |
| skipped_bytes = 0 |
| processed_bytes = 0 |
|
|
| print_step(f"Tìm thấy {total_files} file cần đồng bộ cho {scope_label}.") |
| 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...") |
| snapshot_dir = Path( |
| snapshot_download( |
| repo_id=repo_id, |
| repo_type="dataset", |
| revision=revision, |
| allow_patterns=allow_patterns, |
| ignore_patterns=ignore_patterns, |
| force_download=force_download, |
| local_files_only=False, |
| ) |
| ) |
|
|
| for index, repo_item in enumerate(repo_files, start=1): |
| repo_file = str(repo_item["path"]) |
| runtime_path = runtime_relative_path(repo_file) |
| if runtime_path is not None: |
| destination_path = context.root / runtime_path |
| verify_content = True |
| else: |
| destination_path = model_destination(context, repo_file) |
| verify_content = False |
|
|
| relative_label = destination_path.relative_to(context.root).as_posix() |
| expected_size = int(repo_item["size"] or 0) |
| if ( |
| not force_download |
| and not verify_content |
| and expected_size > 0 |
| and destination_path.exists() |
| and destination_path.stat().st_size == expected_size |
| ): |
| skipped_files += 1 |
| skipped_bytes += expected_size |
| processed_bytes += expected_size |
| if processed_bytes > total_bytes: |
| total_bytes = processed_bytes |
| print_step(f"[{index}/{total_files}] Giữ nguyên {relative_label} ({format_bytes(expected_size)})") |
| print_step( |
| " Tổng tiến độ " |
| f"{render_progress_bar(processed_bytes, total_bytes)} " |
| f"({format_bytes(processed_bytes)}/{format_bytes(total_bytes)})" |
| ) |
| continue |
|
|
| print_step(f"[{index}/{total_files}] Đang đồng bộ {relative_label}") |
| cached_file = snapshot_dir / repo_file |
| if not cached_file.exists(): |
| raise FileNotFoundError(f"snapshot_download thiếu file đã chọn: {repo_file}") |
|
|
| copied, size = sync_single_file( |
| cached_file, |
| destination_path, |
| force_copy=force_download, |
| verify_content=verify_content, |
| ) |
| if copied: |
| copied_files += 1 |
| copied_bytes += size |
| print_step(f" Đã đồng bộ {relative_label} ({format_bytes(size)})") |
| else: |
| skipped_files += 1 |
| skipped_bytes += size |
| print_step(f" Giữ nguyên {relative_label} ({format_bytes(size)})") |
|
|
| processed_bytes += size |
| if processed_bytes > total_bytes: |
| total_bytes = processed_bytes |
| print_step( |
| " Tổng tiến độ " |
| f"{render_progress_bar(processed_bytes, total_bytes)} " |
| f"({format_bytes(processed_bytes)}/{format_bytes(total_bytes)})" |
| ) |
|
|
| return copied_files, skipped_files, copied_bytes, skipped_bytes |
|
|
|
|
| def validate_runtime_files(context: RuntimeContext) -> None: |
| missing_files = [relative for relative in RUNTIME_REQUIRED_FILES if not (context.root / relative).exists()] |
| if missing_files: |
| raise FileNotFoundError( |
| "Runtime chưa đầy đủ sau khi tải về. Thiếu các file: " + ", ".join(missing_files) |
| ) |
|
|
|
|
| def patch_generate_question_runtime(context: RuntimeContext) -> None: |
| if context.requirements_file.exists(): |
| requirements_text = context.requirements_file.read_text(encoding="utf-8") |
| patched_requirements = ( |
| requirements_text.replace("numpy>=1.26.0,<3.0.0", "numpy>=1.26.0,<2.0.0") |
| .replace("transformers>=4.41.0,<5.0.0", "transformers>=4.41.0,<4.42.0") |
| ) |
| if patched_requirements != requirements_text: |
| context.requirements_file.write_text(patched_requirements, encoding="utf-8") |
|
|
| target = context.root / "generate_question.py" |
| if not target.exists(): |
| return |
|
|
| text = target.read_text(encoding="utf-8") |
| original_text = text |
|
|
| import_insertions = { |
| "import argparse\n": "import argparse\nimport hashlib\n", |
| "import re\n": "import re\nimport shutil\n", |
| "import sys\n": "import sys\nimport tempfile\n", |
| } |
| for anchor, replacement in import_insertions.items(): |
| imported_name = replacement.splitlines()[-1] |
| if imported_name not in text and anchor in text: |
| text = text.replace(anchor, replacement, 1) |
|
|
| if "TOKENIZER_FILES = (" not in text and "QUESTION_LIMIT = 100\n" in text: |
| text = text.replace( |
| "QUESTION_LIMIT = 100\n", |
| "QUESTION_LIMIT = 100\n" |
| "TOKENIZER_FILES = (\n" |
| " \"config.json\",\n" |
| " \"special_tokens_map.json\",\n" |
| " \"spiece.model\",\n" |
| " \"tokenizer.json\",\n" |
| " \"tokenizer_config.json\",\n" |
| " \"added_tokens.json\",\n" |
| ")\n", |
| 1, |
| ) |
|
|
| if "def resolve_tokenizer_dir(" not in text and "\ndef parse_dtype(value: str) -> torch.dtype:\n" in text: |
| helper_block = """ |
| def path_needs_ascii_mirror(path: Path) -> bool: |
| try: |
| str(path).encode("ascii") |
| except UnicodeEncodeError: |
| return True |
| return False |
| |
| |
| def resolve_tokenizer_dir(model_dir: Path) -> Path: |
| if not path_needs_ascii_mirror(model_dir): |
| return model_dir |
| |
| digest = hashlib.sha1(str(model_dir).encode("utf-8")).hexdigest()[:16] |
| cache_base = Path(os.getenv("LOCALAPPDATA") or tempfile.gettempdir()) |
| tokenizer_dir = cache_base / "HVU_QA" / "tokenizer_cache" / digest |
| tokenizer_dir.mkdir(parents=True, exist_ok=True) |
| |
| copied = False |
| for filename in TOKENIZER_FILES: |
| source = model_dir / filename |
| if not source.exists(): |
| continue |
| destination = tokenizer_dir / filename |
| if destination.exists() and destination.stat().st_size == source.stat().st_size: |
| continue |
| shutil.copy2(source, destination) |
| copied = True |
| |
| if copied: |
| marker = tokenizer_dir / "source_model_dir.txt" |
| marker.write_text(str(model_dir), encoding="utf-8") |
| |
| return tokenizer_dir |
| |
| """ |
| text = text.replace( |
| "\ndef parse_dtype(value: str) -> torch.dtype:\n", |
| "\n" + helper_block + "def parse_dtype(value: str) -> torch.dtype:\n", |
| 1, |
| ) |
|
|
| method_start = text.find(" def _load_tokenizer(self):") |
| method_end = text.find("\n def load(self)", method_start) |
| if method_start != -1 and method_end != -1: |
| method_block = text[method_start:method_end] |
| if "tokenizer_dir = resolve_tokenizer_dir(self.model_dir)" not in method_block: |
| new_method = """ def _load_tokenizer(self): |
| use_fast = as_bool(os.getenv("HVU_USE_FAST_TOKENIZER"), default=False) |
| tokenizer_dir = resolve_tokenizer_dir(self.model_dir) |
| try: |
| return AutoTokenizer.from_pretrained(str(tokenizer_dir), use_fast=use_fast) |
| except Exception: |
| if use_fast: |
| return AutoTokenizer.from_pretrained(str(tokenizer_dir), use_fast=False) |
| if (tokenizer_dir / "tokenizer.json").exists(): |
| try: |
| return AutoTokenizer.from_pretrained(str(tokenizer_dir), use_fast=True) |
| except Exception: |
| pass |
| return AutoTokenizer.from_pretrained(str(tokenizer_dir), use_fast=False) |
| """ |
| text = text[:method_start] + new_method + text[method_end:] |
|
|
| if text != original_text: |
| target.write_text(text, encoding="utf-8") |
| print_step("Da cap nhat tuong thich tokenizer trong runtime generate_question.py.") |
|
|
|
|
| def prepare_runtime( |
| context: RuntimeContext, |
| repo_id: str, |
| revision: str, |
| force_download: bool, |
| ) -> None: |
| if not force_download and has_complete_runtime(context): |
| patch_generate_question_runtime(context) |
| print_step("Backend/frontend runtime đã có sẵn.") |
| return |
|
|
| copied_files, skipped_files, copied_bytes, skipped_bytes = download_and_sync_files( |
| context=context, |
| repo_id=repo_id, |
| revision=revision, |
| allow_patterns=RUNTIME_ALLOW_PATTERNS, |
| ignore_patterns=RUNTIME_IGNORE_PATTERNS, |
| force_download=force_download, |
| scope_label="backend/frontend runtime", |
| ) |
| validate_runtime_files(context) |
| patch_generate_question_runtime(context) |
| print_step( |
| "Đồng bộ backend/frontend runtime xong. " |
| f"File mới/cập nhật: {copied_files} ({format_bytes(copied_bytes)}), " |
| f"file giữ nguyên: {skipped_files} ({format_bytes(skipped_bytes)})." |
| ) |
|
|
|
|
| def required_model_files(context: RuntimeContext, best_model_only: bool) -> list[Path]: |
| root_files = [ |
| context.local_model_dir / "config.json", |
| context.local_model_dir / "generation_config.json", |
| context.local_model_dir / "model.safetensors", |
| context.local_model_dir / "tokenizer_config.json", |
| context.local_model_dir / "special_tokens_map.json", |
| context.local_model_dir / "spiece.model", |
| ] |
| best_model_files = [ |
| context.local_best_model_dir / "config.json", |
| context.local_best_model_dir / "generation_config.json", |
| context.local_best_model_dir / "model.safetensors", |
| context.local_best_model_dir / "tokenizer_config.json", |
| context.local_best_model_dir / "special_tokens_map.json", |
| context.local_best_model_dir / "spiece.model", |
| ] |
| if best_model_only: |
| return best_model_files |
| return [*root_files, *best_model_files] |
|
|
|
|
| def validate_local_model_dir(context: RuntimeContext, best_model_only: bool) -> None: |
| missing_files = [ |
| str(path.relative_to(context.root)) |
| for path in required_model_files(context, best_model_only) |
| if not path.exists() |
| ] |
| if missing_files: |
| raise FileNotFoundError( |
| "Model chưa đầy đủ sau khi tải về. Thiếu các file: " + ", ".join(missing_files) |
| ) |
|
|
|
|
| def prepare_model( |
| context: RuntimeContext, |
| repo_id: str, |
| revision: str, |
| force_download: bool, |
| best_model_only: bool, |
| ) -> None: |
| if not force_download and has_complete_model(context, best_model_only): |
| scope = "best-model" if best_model_only else "toàn bộ model" |
| print_step(f"{scope} đã có sẵn, không cần tải lại.") |
| return |
|
|
| allow_patterns = [f"{HF_BEST_MODEL_SUBDIR}/**"] if best_model_only else [f"{HF_MODEL_SUBDIR}/**"] |
| copied_files, skipped_files, copied_bytes, skipped_bytes = download_and_sync_files( |
| context=context, |
| repo_id=repo_id, |
| revision=revision, |
| allow_patterns=allow_patterns, |
| ignore_patterns=MODEL_IGNORE_PATTERNS, |
| force_download=force_download, |
| scope_label="best-model" if best_model_only else "toàn bộ model", |
| ) |
| validate_local_model_dir(context, best_model_only=best_model_only) |
|
|
| scope = "best-model" if best_model_only else "toàn bộ model" |
| print_step( |
| f"Đồng bộ {scope} xong. " |
| f"File mới/cập nhật: {copied_files} ({format_bytes(copied_bytes)}), " |
| f"file giữ nguyên: {skipped_files} ({format_bytes(skipped_bytes)})." |
| ) |
|
|
|
|
| def build_runtime_env(context: RuntimeContext, args: argparse.Namespace) -> dict[str, str]: |
| env = subprocess_env() |
| env["HVU_HOST"] = args.host or "127.0.0.1" |
| env["HVU_PORT"] = str(args.port) |
| if args.device: |
| env["HVU_DEVICE"] = args.device |
| if args.debug: |
| env["HVU_DEBUG"] = "1" |
| env["HVU_OPEN_BROWSER"] = "0" |
|
|
| env["HVU_MODEL_DIR"] = str(context.local_model_dir) |
| return env |
|
|
|
|
| def port_available(host: str, port: int) -> bool: |
| try: |
| with socket.create_connection((host, port), timeout=0.4): |
| return False |
| except OSError: |
| return True |
|
|
|
|
| def choose_port(host: str, requested_port: Optional[int]) -> int: |
| if requested_port is not None: |
| if port_available(host, requested_port): |
| return requested_port |
| print_step(f"Port {requested_port} đang bận, đang tìm port khác...") |
|
|
| for port in range(5000, 5101): |
| if port_available(host, port): |
| return port |
|
|
| with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: |
| sock.bind((host, 0)) |
| return int(sock.getsockname()[1]) |
|
|
|
|
| def wait_for_backend(url: str, process: subprocess.Popen, timeout: int = 45) -> None: |
| deadline = time.time() + timeout |
| last_error = "" |
| while time.time() < deadline: |
| if process.poll() is not None: |
| raise RuntimeError(f"Backend dừng sớm với mã lỗi {process.returncode}.") |
| try: |
| with urllib.request.urlopen(url, timeout=2) as response: |
| if 200 <= response.status < 500: |
| return |
| except Exception as exc: |
| last_error = str(exc) |
| time.sleep(0.8) |
| raise RuntimeError(f"Backend chưa sẵn sàng sau {timeout} giây. Lỗi gần nhất: {last_error}") |
|
|
|
|
| def probe_backend_import(context: RuntimeContext, env: dict[str, str]) -> subprocess.CompletedProcess: |
| return subprocess.run( |
| [sys.executable, "-c", "from backend import create_app; app = create_app(); print('backend-ok')"], |
| cwd=str(context.root), |
| env=env, |
| capture_output=True, |
| text=True, |
| encoding="utf-8", |
| errors="replace", |
| timeout=90, |
| check=False, |
| ) |
|
|
|
|
| def validate_backend_import(context: RuntimeContext, env: dict[str, str]) -> None: |
| probe = probe_backend_import(context, env) |
| if probe.returncode == 0: |
| return |
|
|
| details = (probe.stderr or probe.stdout or "").strip() |
| if "c10.dll" in details or "_load_dll_libraries" in details or "WinError 1114" in details: |
| repair_torch_runtime(context, details[-1200:]) |
| retry = probe_backend_import(context, env) |
| if retry.returncode == 0: |
| return |
| retry_details = (retry.stderr or retry.stdout or "").strip() |
| raise RuntimeError( |
| "PyTorch vẫn không load được DLL sau khi đã tự cài VC++ Redistributable và cài lại PyTorch CPU. " |
| "Hãy khởi động lại Windows rồi chạy lại HVU_QA_tool.py. " |
| f"Chi tiết: {retry_details[-1200:]}" |
| ) |
|
|
| raise RuntimeError(f"Backend chưa import được trước khi khởi động. Chi tiết: {details[-1200:]}") |
|
|
|
|
| def launch_app(context: RuntimeContext, args: argparse.Namespace) -> int: |
| if not context.main_file.exists(): |
| raise FileNotFoundError(f"Không tìm thấy file chạy ứng dụng: {context.main_file}") |
|
|
| args.host = args.host or "127.0.0.1" |
| args.port = choose_port(args.host, args.port) |
| update_config(last_host=args.host, last_port=args.port) |
| env = build_runtime_env(context, args) |
| command = [sys.executable, str(context.main_file)] |
| url = f"http://{env['HVU_HOST']}:{env['HVU_PORT']}" |
| print_step("Đang kiểm tra backend trước khi chạy...") |
| validate_backend_import(context, env) |
| print_step("Đang khởi động backend...") |
| process = subprocess.Popen( |
| command, |
| cwd=str(context.root), |
| env=env, |
| stdout=None, |
| stderr=None, |
| ) |
| wait_for_backend(url, process) |
| print_step(f"Backend đã chạy tại {url}") |
| if not args.no_browser: |
| print_step("Đang mở giao diện hệ thống...") |
| webbrowser.open(url) |
| print_step("Hoàn tất, HỆ THỐNG SINH CÂU HỎI đã sẵn sàng.") |
| return process.wait() |
|
|
|
|
| def build_parser() -> argparse.ArgumentParser: |
| parser = argparse.ArgumentParser( |
| description=( |
| "Launcher cho HVU_QA. Chạy không cần tham số để tự tải backend/frontend thật, " |
| "tải model từ dataset Hugging Face, chuẩn bị CPU/GPU và mở giao diện web." |
| ), |
| ) |
| parser.add_argument("--repo-id", default=HF_DATASET_REPO_ID, help="Repo dataset trên Hugging Face.") |
| parser.add_argument("--revision", default=HF_DATASET_REVISION, help="Revision trên Hugging Face.") |
| parser.add_argument("--host", default=None, help="Host chạy Flask. Mặc định dùng HVU_HOST hoặc 127.0.0.1.") |
| parser.add_argument("--port", type=int, default=None, help="Port chạy Flask. Mặc định dùng HVU_PORT hoặc 5000.") |
| parser.add_argument( |
| "--device", |
| choices=["auto", "cpu", "cuda"], |
| default=None, |
| help="Thiết bị chạy model. Mặc định tự ưu tiên GPU NVIDIA/CUDA, nếu không có thì dùng CPU.", |
| ) |
| parser.add_argument("--debug", action="store_true", help="Bật Flask debug.") |
| parser.add_argument("--no-browser", action="store_true", help="Không tự mở trình duyệt.") |
| parser.add_argument("--no-venv", action="store_true", help="Không tự tạo virtualenv riêng cho launcher.") |
| parser.add_argument("--force-download", action="store_true", help="Tải lại runtime/model và ghi đè file local.") |
| 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.") |
| parser.set_defaults(best_model_only=False) |
| parser.add_argument( |
| "--best-model-only", |
| dest="best_model_only", |
| action="store_true", |
| help="Chỉ tải thư mục best-model nếu muốn runtime nhẹ và chỉ hiện 1 model.", |
| ) |
| parser.add_argument( |
| "--full-model", |
| dest="best_model_only", |
| action="store_false", |
| help="Tải đủ model gốc và best-model để giao diện hiện 2 lựa chọn (mặc định).", |
| ) |
| parser.add_argument( |
| "--runtime-dir", |
| default="HVU_QA_runtime", |
| help="Thư mục runtime standalone sẽ được tạo nếu không có full project hoặc khi ép standalone.", |
| ) |
| parser.add_argument( |
| "--force-standalone-runtime", |
| action="store_true", |
| help="Luôn dùng runtime standalone, kể cả khi đang đứng trong full project.", |
| ) |
| parser.add_argument( |
| "--force-runtime-refresh", |
| action="store_true", |
| help="Tải lại backend/frontend từ Hugging Face và ghi đè runtime local.", |
| ) |
| return parser |
|
|
|
|
| def main() -> int: |
| if hasattr(sys.stdout, "reconfigure"): |
| sys.stdout.reconfigure(encoding="utf-8") |
| if hasattr(sys.stderr, "reconfigure"): |
| sys.stderr.reconfigure(encoding="utf-8") |
|
|
| parser = build_parser() |
| args = parser.parse_args() |
|
|
| run_base_preflight(args) |
| bootstrap_exit_code = maybe_bootstrap_tool_venv(args) |
| if bootstrap_exit_code is not None: |
| return bootstrap_exit_code |
|
|
| print_step("Đang chuẩn bị HỆ THỐNG SINH CÂU HỎI...") |
| context = resolve_runtime_context(args) |
| check_write_access(context.root) |
| check_disk_space(context.root, args.min_free_gb) |
| ensure_huggingface_hub() |
| check_internet_if_needed(context, args) |
| prepare_runtime( |
| context=context, |
| repo_id=args.repo_id, |
| revision=args.revision, |
| force_download=args.force_download or args.force_runtime_refresh, |
| ) |
|
|
| selected_device, detected_gpus = select_runtime_device(args) |
| platform_runtime_note(selected_device) |
| check_dependency_internet_if_needed(selected_device, context) |
| try: |
| selected_device = ensure_runtime_dependencies( |
| selected_device=selected_device, |
| context=context, |
| gpus=detected_gpus, |
| ) |
| except RuntimeError as exc: |
| if selected_device != "cuda": |
| raise |
| print_step(f"GPU/CUDA chưa dùng được ({exc}). Hệ thống sẽ chuyển sang CPU.") |
| selected_device = ensure_runtime_dependencies( |
| selected_device="cpu", |
| context=context, |
| gpus=detected_gpus, |
| ) |
| args.device = selected_device |
| update_config( |
| device=selected_device, |
| runtime_root=str(context.root), |
| model_dir=str(context.local_model_dir), |
| last_port=args.port, |
| ) |
|
|
| prepare_model( |
| context=context, |
| repo_id=args.repo_id, |
| revision=args.revision, |
| force_download=args.force_download, |
| best_model_only=args.best_model_only, |
| ) |
|
|
| return launch_app(context, args) |
|
|
|
|
| def pause_on_error() -> None: |
| if not IS_WINDOWS: |
| return |
| if os.getenv("HVU_NO_PAUSE_ON_ERROR", "").strip().lower() in {"1", "true", "yes", "on"}: |
| return |
| try: |
| input("Nhấn Enter để thoát...") |
| except EOFError: |
| os.system("pause") |
|
|
|
|
| def write_error_log(exc: BaseException) -> Path: |
| LOG_DIR.mkdir(parents=True, exist_ok=True) |
| log_file = LOG_DIR / "HVU_QA_tool_error.log" |
| details = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__)) |
| log_file.write_text(details, encoding="utf-8") |
| return log_file |
|
|
|
|
| def run_main() -> int: |
| setup_logging() |
| try: |
| return main() |
| except KeyboardInterrupt: |
| print_step("Đã dừng theo yêu cầu người dùng.") |
| return 130 |
| except Exception as exc: |
| print_step(f"Lỗi: {exc}") |
| logging.exception("Launcher failed") |
| log_file = write_error_log(exc) |
| print_step(f"Đã ghi log lỗi tại: {log_file}") |
| print_step("Chi tiết lỗi:") |
| traceback.print_exc() |
| pause_on_error() |
| return 1 |
|
|
|
|
| if __name__ == "__main__": |
| raise SystemExit(run_main()) |
|
|