Compare commits
4 Commits
v0.3.0-tes
...
v0.3.0-tes
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2e600fa3d | ||
|
|
176e06c4bd | ||
|
|
bd24063c15 | ||
|
|
1f59ed0679 |
@@ -27,7 +27,7 @@
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from PyInstaller.utils.hooks import collect_dynamic_libs
|
||||
from PyInstaller.utils.hooks import collect_data_files, collect_dynamic_libs
|
||||
|
||||
BLOCK_CIPHER = None
|
||||
ROOT = Path(SPECPATH).parent # noqa: F821 - PyInstaller 가 주입
|
||||
@@ -39,6 +39,11 @@ capture_exe = SRC / "livesub" / "resources" / "bin" / "livesub_capture.exe"
|
||||
if capture_exe.is_file():
|
||||
datas.append((str(capture_exe), "livesub/resources/bin"))
|
||||
|
||||
# faster-whisper 는 문장을 확정할 때 Silero VAD 모델(assets/silero_vad_v6.onnx)을
|
||||
# 패키지 폴더에서 읽는다. .py 가 아닌 파일이라 PyInstaller 가 자동으로 넣지 않고,
|
||||
# 빠지면 확정 문장 인식이 매번 실패해 자막이 하나도 안 나온다 (v0.3.0-test7 까지).
|
||||
datas += collect_data_files("faster_whisper")
|
||||
|
||||
# CTranslate2 는 CUDA/cuDNN DLL 을 곁에 두고 로드한다. 자동 수집에서 빠지기 쉽다.
|
||||
binaries = collect_dynamic_libs("ctranslate2")
|
||||
|
||||
|
||||
@@ -130,6 +130,23 @@ def run_source_checks() -> None:
|
||||
raise RuntimeError(gpu.reason)
|
||||
return f"{gpu.name} · {gpu.total_vram_mb / 1024:.1f}GB"
|
||||
|
||||
# CTranslate2 는 GPU 계산 때 cublas64_12.dll 을 이름으로 불러오는데, 포터블
|
||||
# 빌드에는 이 파일이 없다 (v0.3.0-test8 까지 GPU 에서 자막이 안 나온 원인).
|
||||
# 앱이 처음 GPU 를 쓸 때 받아 두는 경로가 실제로 받고 불러오는지 본다.
|
||||
# GPU 가 없어도 DLL 은 올라간다. 한 번 받으면 다음부터는 캐시를 쓴다.
|
||||
@check("GPU 계산 파일(cuBLAS) 받기·불러오기")
|
||||
def _cublas():
|
||||
import ctypes
|
||||
|
||||
from livesub.models import cuda_runtime
|
||||
|
||||
if not cuda_runtime.ensure(device="cuda"):
|
||||
raise RuntimeError("Windows 인데 준비를 건너뛰었습니다")
|
||||
ctypes.WinDLL("cublas64_12.dll") # CTranslate2 처럼 이름만으로 찾아지는지
|
||||
import ctranslate2 # noqa: F401 - 미리 올린 DLL 과 같이 올라가는지
|
||||
|
||||
return str(cuda_runtime.runtime_dir())
|
||||
|
||||
@check("사용 가능한 모델 티어")
|
||||
def _tiers():
|
||||
from livesub.models.manager import has_torch, tier_availability
|
||||
@@ -526,6 +543,21 @@ def _scratch_appdata():
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
|
||||
#: exe 안에 반드시 있어야 하는 .py 아닌 파일. 빠져도 창은 잘 뜨고 소스 점검도
|
||||
#: 통과하므로, 실제로 말소리가 들어올 때가 돼서야 터진다.
|
||||
EXE_REQUIRED_FILES = (
|
||||
"faster_whisper/assets/silero_vad_v6.onnx", # 확정 문장 인식의 VAD
|
||||
"livesub/resources/glossaries/fps-common.json",
|
||||
)
|
||||
|
||||
|
||||
def missing_bundle_files(exe: Path) -> list[str]:
|
||||
from PyInstaller.archive.readers import CArchiveReader
|
||||
|
||||
names = {name.replace("\\", "/") for name in CArchiveReader(str(exe)).toc}
|
||||
return [f for f in EXE_REQUIRED_FILES if f not in names]
|
||||
|
||||
|
||||
def run_exe_check(exe: Path) -> None:
|
||||
print(f"\n=== 빌드된 exe 점검: {exe} ===")
|
||||
|
||||
@@ -538,6 +570,13 @@ def run_exe_check(exe: Path) -> None:
|
||||
raise RuntimeError(f"{mb:.0f}MB — 너무 큼. torch 가 섞여 들어갔는지 확인")
|
||||
return f"{mb:.1f} MB"
|
||||
|
||||
@check("exe 에 실행 중 읽는 파일이 들어 있는지")
|
||||
def _bundled_files():
|
||||
missing = missing_bundle_files(exe)
|
||||
if missing:
|
||||
raise RuntimeError(f"빠짐: {', '.join(missing)}")
|
||||
return f"{len(EXE_REQUIRED_FILES)}개 확인"
|
||||
|
||||
@check("exe 첫 실행 — 저장 위치 화면")
|
||||
def _first_run():
|
||||
# APPDATA 를 빈 폴더로 돌려 "처음 켜는 사람" 을 그대로 재현한다.
|
||||
|
||||
@@ -9,6 +9,7 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import queue
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
@@ -25,7 +26,8 @@ from ..audio import (
|
||||
)
|
||||
from ..config import AppConfig
|
||||
from ..constants import LANGUAGE_CODES, user_data_dir
|
||||
from ..models import Glossary, ModelManager
|
||||
from ..models import Glossary, ModelManager, cuda_runtime
|
||||
from ..models.cuda_runtime import DownloadCancelled
|
||||
from ..models.manager import apply_vram_limit
|
||||
from ..models.packs import build_glossary
|
||||
from ..models.speech_level import (
|
||||
@@ -38,6 +40,10 @@ from .events import EngineState, EngineStatus, TranslationLine
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
#: GPU 쪽 문제로 보이는 예외 문구. 이런 실패는 CPU 로 바꾸면 자막이 나온다.
|
||||
_GPU_ERROR = re.compile(r"cuda|cublas|cudnn|gpu", re.IGNORECASE)
|
||||
_FAILED_PREFIX = "듣는 중 · 문장 처리 실패: "
|
||||
|
||||
StatusCallback = Callable[[EngineStatus], None]
|
||||
LineCallback = Callable[[TranslationLine], None]
|
||||
|
||||
@@ -67,6 +73,8 @@ class TranslationEngine:
|
||||
#: 마지막으로 실제 발화를 처리한 시각. 유휴 언로드 판단에 쓴다.
|
||||
self._last_activity = time.monotonic()
|
||||
self._models_unloaded = False
|
||||
#: GPU 를 못 써서 CPU 로 돌고 있으면 그 사유. 홈 화면 상태에 보인다.
|
||||
self._cpu_notice = ""
|
||||
|
||||
# --- 수명주기 -------------------------------------------------------
|
||||
@property
|
||||
@@ -89,10 +97,15 @@ class TranslationEngine:
|
||||
def start(self) -> None:
|
||||
if self.running:
|
||||
return
|
||||
self._stop.clear()
|
||||
# clear() 가 아니라 새로 만든다. 정지된 이전 시작 작업(예: cuBLAS 받는 중)이
|
||||
# 아직 끝나지 않았을 수 있는데, 같은 이벤트를 다시 끄면 그 작업이 정지된
|
||||
# 줄 모르고 캡처를 켜 버린다.
|
||||
self._stop = threading.Event()
|
||||
self._emit_status(EngineState.LOADING, "모델을 준비하고 있습니다…", 0.0)
|
||||
|
||||
thread = threading.Thread(target=self._bootstrap, name="engine-boot", daemon=True)
|
||||
thread = threading.Thread(
|
||||
target=self._bootstrap, args=(self._stop,), name="engine-boot", daemon=True
|
||||
)
|
||||
thread.start()
|
||||
self._threads = [thread]
|
||||
|
||||
@@ -144,20 +157,40 @@ class TranslationEngine:
|
||||
return True
|
||||
|
||||
# --- 내부 스레드 ----------------------------------------------------
|
||||
def _bootstrap(self) -> None:
|
||||
def _bootstrap(self, stop: threading.Event) -> None:
|
||||
"""모델·캡처를 준비한다. `stop` 은 이 시작 작업 전용 정지 신호다.
|
||||
|
||||
준비 도중(cuBLAS 받기, 모델 올리기)에 정지를 누를 수 있다. 그때는
|
||||
캡처를 켜지도 상태를 바꾸지도 않고 조용히 끝낸다.
|
||||
"""
|
||||
def report(msg: str, pct: float) -> None:
|
||||
if not stop.is_set():
|
||||
self._emit_status(EngineState.LOADING, msg, pct)
|
||||
|
||||
self._cpu_notice = ""
|
||||
try:
|
||||
# 설정이 바뀐 채로 재시작됐을 수 있으므로 매 시작마다 맞춘다.
|
||||
self.sync_performance()
|
||||
self.models.use_device(self.config.models.device)
|
||||
self._prepare_gpu(report, stop)
|
||||
if stop.is_set():
|
||||
return
|
||||
perf = self.config.performance
|
||||
if perf.game_mode and self.config.models.device == "cuda":
|
||||
if perf.game_mode and self.models.device == "cuda":
|
||||
# 모델을 올리기 *전에* 걸어야 상한이 실제로 먹는다.
|
||||
apply_vram_limit(perf.vram_limit_ratio, self.config.models.device_index)
|
||||
if self.config.models.preload_on_start:
|
||||
self.models.preload(
|
||||
lambda msg, pct: self._emit_status(EngineState.LOADING, msg, pct)
|
||||
)
|
||||
self._capture = create_capture(self.config.audio)
|
||||
self._capture.start()
|
||||
self._preload(report)
|
||||
if stop.is_set():
|
||||
return
|
||||
capture = create_capture(self.config.audio)
|
||||
capture.start()
|
||||
self._capture = capture
|
||||
if stop.is_set():
|
||||
# stop() 이 캡처를 확인한 뒤에 여기 왔을 수 있다. 직접 닫는다.
|
||||
capture.stop()
|
||||
self._capture = None
|
||||
return
|
||||
|
||||
workers = [
|
||||
threading.Thread(target=self._segment_loop, name="engine-segment", daemon=True),
|
||||
@@ -167,11 +200,41 @@ class TranslationEngine:
|
||||
w.start()
|
||||
self._threads.extend(workers)
|
||||
|
||||
kind = "프로그램별 캡처" if self._capture.per_process else "출력 장치 전체"
|
||||
self._emit_status(EngineState.RUNNING, f"듣는 중 · {kind}", 1.0)
|
||||
kind = "프로그램별 캡처" if capture.per_process else "출력 장치 전체"
|
||||
message = self._cpu_notice or f"듣는 중 · {kind}"
|
||||
self._emit_status(EngineState.RUNNING, message, 1.0)
|
||||
except (CaptureError, OSError, RuntimeError, ImportError) as exc:
|
||||
log.exception("엔진 시작 실패")
|
||||
self._emit_status(EngineState.ERROR, str(exc))
|
||||
if not stop.is_set():
|
||||
self._emit_status(EngineState.ERROR, str(exc))
|
||||
|
||||
def _preload(self, report) -> None:
|
||||
"""모델을 미리 올린다. GPU 로 안 올라가면 CPU 로 바꿔 다시 올린다."""
|
||||
try:
|
||||
self.models.preload(report)
|
||||
except Exception as exc:
|
||||
if self.models.device != "cuda" or not _GPU_ERROR.search(str(exc)):
|
||||
raise
|
||||
log.warning("GPU 로 모델을 올리지 못했습니다: %s", exc, exc_info=True)
|
||||
self._fall_back_to_cpu(f"GPU 오류: {_short(exc)}")
|
||||
self.models.preload(report)
|
||||
|
||||
def _prepare_gpu(self, report, stop: threading.Event) -> None:
|
||||
"""GPU 계산에 필요한 파일을 준비한다. 안 되면 CPU 로 돌린다."""
|
||||
if self.models.device != "cuda":
|
||||
return
|
||||
try:
|
||||
cuda_runtime.ensure(report, cancel=stop)
|
||||
except DownloadCancelled:
|
||||
log.info("cuBLAS 받기를 멈췄습니다 (번역 정지)")
|
||||
except Exception as exc: # noqa: BLE001 - 받기 실패여도 자막은 나와야 한다
|
||||
log.warning("GPU 계산 파일을 준비하지 못했습니다: %s", exc, exc_info=True)
|
||||
self._fall_back_to_cpu(f"GPU 계산 파일을 받지 못했습니다 ({_short(exc)})")
|
||||
|
||||
def _fall_back_to_cpu(self, reason: str) -> None:
|
||||
self.models.use_device("cpu")
|
||||
self._cpu_notice = f"CPU로 받아 적는 중 · {reason}"
|
||||
log.warning("CPU 로 전환합니다: %s", reason)
|
||||
|
||||
def _segment_loop(self) -> None:
|
||||
cfg = self.config.audio
|
||||
@@ -240,21 +303,40 @@ class TranslationEngine:
|
||||
if not segment.is_final and not self._segments.empty():
|
||||
continue
|
||||
|
||||
self._process_safely(segment, mcfg)
|
||||
|
||||
# 게임에 GPU를 잠깐 돌려준다. 연속 발화 때 우리가 GPU를 독점하면
|
||||
# 프레임이 눈에 띄게 끊긴다.
|
||||
if perf.game_mode and perf.yield_ms > 0:
|
||||
self._stop.wait(perf.yield_ms / 1000)
|
||||
|
||||
def _process_safely(self, segment: Segment, mcfg) -> None:
|
||||
"""한 구간을 처리한다. 실패해도 엔진은 계속 돌고, 사용자에게 보인다.
|
||||
|
||||
예전에는 실패를 로그에만 남겨서, 매 문장이 실패해도 화면은 '듣는 중'
|
||||
그대로였다. 사용자는 게이지만 움직이고 자막이 안 나오는 이유를 알 수 없었다.
|
||||
"""
|
||||
for attempt in range(2):
|
||||
# 모델 참조를 캐시하지 않는다. 유휴 언로드 뒤에는 새로 올려야 하고,
|
||||
# 캐시된 참조를 쓰면 이미 내려간 모델을 붙잡고 있게 된다.
|
||||
try:
|
||||
self._process(
|
||||
segment, self.models.recognizer(), self.models.translator(), mcfg
|
||||
)
|
||||
self._last_activity = time.monotonic()
|
||||
self._models_unloaded = False
|
||||
except Exception as exc: # noqa: BLE001 - 한 문장 실패로 엔진이 죽으면 안 된다
|
||||
log.warning("구간 처리 실패: %s", exc, exc_info=log.isEnabledFor(logging.DEBUG))
|
||||
|
||||
# 게임에 GPU를 잠깐 돌려준다. 연속 발화 때 우리가 GPU를 독점하면
|
||||
# 프레임이 눈에 띄게 끊긴다.
|
||||
if perf.game_mode and perf.yield_ms > 0:
|
||||
self._stop.wait(perf.yield_ms / 1000)
|
||||
log.warning("구간 처리 실패: %s", exc, exc_info=True)
|
||||
if attempt == 0 and self.models.device == "cuda" and _GPU_ERROR.search(str(exc)):
|
||||
# GPU 로는 안 되는 환경이다. 같은 구간을 CPU 로 다시 받아 적는다.
|
||||
self._fall_back_to_cpu(f"GPU 오류: {_short(exc)}")
|
||||
self._emit_status(EngineState.RUNNING, self._cpu_notice)
|
||||
continue
|
||||
self._emit_status(EngineState.RUNNING, f"{_FAILED_PREFIX}{_short(exc)}")
|
||||
return
|
||||
self._last_activity = time.monotonic()
|
||||
self._models_unloaded = False
|
||||
if self._status.message.startswith(_FAILED_PREFIX):
|
||||
self._emit_status(EngineState.RUNNING, self._cpu_notice or "듣는 중")
|
||||
return
|
||||
|
||||
def _maybe_unload_idle(self) -> None:
|
||||
"""한동안 말소리가 없으면 모델을 내려 VRAM을 통째로 돌려준다.
|
||||
@@ -363,3 +445,9 @@ class TranslationEngine:
|
||||
)
|
||||
if self._on_status:
|
||||
self._on_status(self._status)
|
||||
|
||||
|
||||
def _short(exc: Exception, limit: int = 120) -> str:
|
||||
"""상태 줄에 넣을 만큼 짧은 오류 문구."""
|
||||
text = " ".join(str(exc).split()) or type(exc).__name__
|
||||
return text if len(text) <= limit else text[: limit - 1] + "…"
|
||||
|
||||
@@ -9,7 +9,7 @@ from dataclasses import dataclass, field
|
||||
|
||||
import numpy as np
|
||||
|
||||
from ..constants import LANGUAGE_CODES, models_dir
|
||||
from ..constants import LANGUAGE_CODES, SAMPLE_RATE, models_dir
|
||||
from .tiers import AsrSpec
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -27,6 +27,15 @@ ALT_LANGUAGE_MAX_LOGPROB_DROP = -0.45
|
||||
#: 반복 루프는 확률이 높게 나와서 log 확률만으로는 걸러지지 않는다.
|
||||
MAX_COMPRESSION_RATIO = 2.4
|
||||
|
||||
#: Silero 없이 다시 받은 결과를 믿는 최저 토큰당 평균 log 확률. Whisper 원본의
|
||||
#: logprob_threshold 와 같은 값이다. 게임 잡음에서 나오는 "Oh." "you" 같은 환각은
|
||||
#: -1.1 대로 나오고, 효과 걸린 실제 대사는 -0.3 ~ -0.8 로 나온다 (실측).
|
||||
FALLBACK_MIN_LOGPROB = -1.0
|
||||
|
||||
#: 구간이 실제 오디오보다 이만큼(초) 넘게 끝나면 환각이다. 말소리가 없으면 Whisper 는
|
||||
#: 타임스탬프를 못 찍고 30초 창 끝까지 이어진 "Thank you." 를 내놓는다.
|
||||
FALLBACK_MAX_OVERRUN_S = 1.0
|
||||
|
||||
#: 다시 받은 결과에 이 글자가 섞여 있으면 모델이 언어를 바꾸지 못한 것이다.
|
||||
#: (진짜 한국어를 small 모델로 '영어로' 받으면 한글을 그대로 적는다.)
|
||||
_SCRIPT = {
|
||||
@@ -131,20 +140,15 @@ class SpeechRecognizer:
|
||||
def _run(
|
||||
self, audio: np.ndarray, language: str | None, fast: bool, prompt: str
|
||||
) -> Transcript:
|
||||
assert self._model is not None
|
||||
with self._lock:
|
||||
segments, info = self._model.transcribe(
|
||||
audio.astype(np.float32, copy=False),
|
||||
language=language,
|
||||
beam_size=1 if fast else self.spec.beam_size,
|
||||
temperature=0.0,
|
||||
condition_on_previous_text=False,
|
||||
initial_prompt=prompt or None,
|
||||
vad_filter=not fast,
|
||||
vad_parameters={"min_silence_duration_ms": 300},
|
||||
word_timestamps=False,
|
||||
)
|
||||
segments = list(segments)
|
||||
segments, info = self._decode(audio, language, fast, prompt, vad=not fast)
|
||||
if not fast and not any(s.text.strip() for s in segments):
|
||||
# Silero VAD 가 구간을 통째로 버렸다. 효과가 걸린 게임 목소리("Get up!
|
||||
# Over here!")는 Silero 확률이 0.1 대로 나와서 여기서 사라진다. 이 구간은
|
||||
# 이미 우리 분할기가 말소리로 본 것이므로 VAD 없이 한 번 더 받되, 잡음에서
|
||||
# 나오는 환각("Thank you.")은 `_plausible` 로 거른다.
|
||||
segments, info = self._decode(audio, language, fast, prompt, vad=False)
|
||||
duration = audio.size / SAMPLE_RATE
|
||||
segments = [s for s in segments if _plausible(s, duration)]
|
||||
|
||||
text = " ".join(s.text.strip() for s in segments if s.text.strip()).strip()
|
||||
tokens = sum(len(getattr(s, "tokens", ()) or ()) for s in segments)
|
||||
@@ -167,6 +171,24 @@ class SpeechRecognizer:
|
||||
language_probs={str(k): float(v) for k, v in probs},
|
||||
)
|
||||
|
||||
def _decode(
|
||||
self, audio: np.ndarray, language: str | None, fast: bool, prompt: str, vad: bool
|
||||
) -> tuple[list, object]:
|
||||
assert self._model is not None
|
||||
with self._lock:
|
||||
segments, info = self._model.transcribe(
|
||||
audio.astype(np.float32, copy=False),
|
||||
language=language,
|
||||
beam_size=1 if fast else self.spec.beam_size,
|
||||
temperature=0.0,
|
||||
condition_on_previous_text=False,
|
||||
initial_prompt=prompt or None,
|
||||
vad_filter=vad,
|
||||
vad_parameters={"min_silence_duration_ms": 300} if vad else None,
|
||||
word_timestamps=False,
|
||||
)
|
||||
return list(segments), info
|
||||
|
||||
|
||||
def _alternative_language(
|
||||
probs: dict[str, float], detected: str, supported: bool
|
||||
@@ -191,6 +213,15 @@ def _most_likely(candidates: list[str], probs: dict[str, float]) -> str | None:
|
||||
return max(known, key=lambda c: probs[c]) if known else None
|
||||
|
||||
|
||||
def _plausible(segment, duration_s: float) -> bool:
|
||||
"""Silero 없이 받은 구간이 실제 말소리를 받아 적은 것으로 보이는가."""
|
||||
if float(getattr(segment, "end", 0.0) or 0.0) > duration_s + FALLBACK_MAX_OVERRUN_S:
|
||||
return False
|
||||
if float(getattr(segment, "compression_ratio", 0.0) or 0.0) > MAX_COMPRESSION_RATIO:
|
||||
return False
|
||||
return float(getattr(segment, "avg_logprob", 0.0)) >= FALLBACK_MIN_LOGPROB
|
||||
|
||||
|
||||
def _accept_alternative(first: Transcript, alt: Transcript, avoided: str) -> bool:
|
||||
if not alt.text:
|
||||
return False
|
||||
|
||||
156
src/livesub/models/cuda_runtime.py
Normal file
156
src/livesub/models/cuda_runtime.py
Normal file
@@ -0,0 +1,156 @@
|
||||
"""GPU 로 받아 적고 번역할 때 필요한 cuBLAS DLL 을 준비한다 (Windows).
|
||||
|
||||
CTranslate2 의 Windows 패키지는 GPU 계산 때 `cublas64_12.dll` 을 이름으로 찾아
|
||||
불러온다. 그런데 이 DLL 은 패키지에 들어 있지 않다. 리눅스 개발 환경에서는
|
||||
torch 가 같이 깔아 둔 cuBLAS 를 쓰기 때문에 문제가 드러나지 않았고, torch 를 뺀
|
||||
포터블 exe 에서는 모델은 GPU 에 잘 올라가는데 첫 문장을 받아 적는 순간부터
|
||||
매번 실패했다. 소리 게이지는 움직이는데 자막이 하나도 안 나오던 원인이다.
|
||||
|
||||
두 DLL 이 790MB 라 exe 에 넣으면 실행할 때마다 그만큼 임시폴더에 풀어야 한다.
|
||||
그래서 처음 GPU 를 쓸 때 NVIDIA 가 PyPI 에 올린 공식 패키지를 한 번 받아 모델
|
||||
폴더에 둔다. CUDA Toolkit 이 깔려 있어 이미 불러올 수 있으면 받지 않는다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
|
||||
from ..constants import models_dir
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
#: cuBLAS 12.8 부터 RTX 50 계열(Blackwell)을 지원한다.
|
||||
WHEEL_VERSION = "12.8.4.1"
|
||||
WHEEL_URL = (
|
||||
"https://files.pythonhosted.org/packages/70/61/"
|
||||
"7d7b3c70186fb651d0fbd35b01dbfc8e755f69fd58f817f3d0f642df20c3/"
|
||||
"nvidia_cublas_cu12-12.8.4.1-py3-none-win_amd64.whl"
|
||||
)
|
||||
WHEEL_SHA256 = "47e9b82132fa8d2b4944e708049229601448aaad7e6f296f630f2d1a32de35af"
|
||||
WHEEL_SIZE = 567_544_208
|
||||
|
||||
#: 불러오는 순서대로. cublas64_12 가 cublasLt64_12 를 import 하므로 Lt 가 먼저다.
|
||||
DLLS = ("cublasLt64_12.dll", "cublas64_12.dll")
|
||||
_WHEEL_DIR = "nvidia/cublas/bin/"
|
||||
|
||||
ProgressCallback = Callable[[str, float], None]
|
||||
|
||||
|
||||
class DownloadCancelled(Exception):
|
||||
"""사용자가 받는 도중에 번역을 정지했다."""
|
||||
|
||||
#: os.add_dll_directory 가 돌려준 핸들. 닫히면 검색 경로에서 빠지므로 붙잡아 둔다.
|
||||
_dll_dir_handle = None
|
||||
#: 불러온 DLL 핸들. 참조가 사라지면 내려갈 수 있으므로 들고 있는다.
|
||||
_loaded: list = []
|
||||
_ready = False
|
||||
|
||||
|
||||
def runtime_dir() -> Path:
|
||||
"""모델 폴더 안에 둔다. 저장 위치를 옮길 때 모델과 같이 따라간다."""
|
||||
return models_dir() / f"cuda-runtime-cublas-{WHEEL_VERSION}"
|
||||
|
||||
|
||||
def installed(directory: Path | None = None) -> bool:
|
||||
directory = directory or runtime_dir()
|
||||
return all((directory / name).is_file() for name in DLLS)
|
||||
|
||||
|
||||
def _system_has_cublas() -> bool:
|
||||
"""CUDA Toolkit 등으로 이미 이름만으로 불러올 수 있는가."""
|
||||
try:
|
||||
_loaded.append(ctypes.WinDLL(DLLS[-1])) # type: ignore[attr-defined]
|
||||
except OSError:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def ensure(progress: ProgressCallback | None = None, device: str = "cuda",
|
||||
cancel: threading.Event | None = None) -> bool:
|
||||
"""GPU 를 쓸 수 있게 cuBLAS 를 준비한다. 새로 받았거나 불러왔으면 True.
|
||||
|
||||
Windows 가 아니거나 CPU 로 돌릴 때는 아무것도 하지 않는다. 받기·불러오기에
|
||||
실패하면 예외를 그대로 올린다. 호출한 쪽이 CPU 로 바꿀지 정한다.
|
||||
`cancel` 이 켜지면 받기를 멈추고 `DownloadCancelled` 를 올린다.
|
||||
"""
|
||||
global _ready
|
||||
if sys.platform != "win32" or device != "cuda":
|
||||
return False
|
||||
if _ready:
|
||||
return True
|
||||
directory = runtime_dir()
|
||||
if not installed(directory) and _system_has_cublas():
|
||||
log.info("시스템에 있는 cuBLAS 를 씁니다.")
|
||||
else:
|
||||
if not installed(directory):
|
||||
download(directory, progress, cancel=cancel)
|
||||
activate(directory)
|
||||
_ready = True
|
||||
return True
|
||||
|
||||
|
||||
def download(directory: Path, progress: ProgressCallback | None = None,
|
||||
url: str = WHEEL_URL, sha256: str = WHEEL_SHA256,
|
||||
size: int = WHEEL_SIZE, cancel: threading.Event | None = None) -> None:
|
||||
"""공식 패키지를 받아 DLL 두 개만 꺼낸다. 끝나면 패키지 파일은 지운다."""
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
part = directory / "cublas.whl.part"
|
||||
total_mb = size / 2**20
|
||||
log.info("GPU 계산 파일(cuBLAS %s) 내려받기: %s", WHEEL_VERSION, url)
|
||||
digest = hashlib.sha256()
|
||||
done = 0
|
||||
last_pct = -1
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=30) as resp, part.open("wb") as out:
|
||||
while chunk := resp.read(1 << 20):
|
||||
if cancel is not None and cancel.is_set():
|
||||
raise DownloadCancelled("GPU 계산 파일 받기를 멈췄습니다")
|
||||
out.write(chunk)
|
||||
digest.update(chunk)
|
||||
done += len(chunk)
|
||||
pct = int(done * 100 / size) if size else 0
|
||||
if progress and pct != last_pct:
|
||||
last_pct = pct
|
||||
progress(
|
||||
f"GPU 계산 파일 받는 중 (처음 한 번만) "
|
||||
f"{done / 2**20:.0f}/{total_mb:.0f}MB",
|
||||
min(done / size, 1.0) if size else 0.0,
|
||||
)
|
||||
if done != size or digest.hexdigest() != sha256:
|
||||
raise RuntimeError(
|
||||
f"GPU 계산 파일이 손상됐습니다 ({done}바이트, 다시 시도해 주세요)"
|
||||
)
|
||||
with zipfile.ZipFile(part) as wheel:
|
||||
for name in DLLS:
|
||||
tmp = directory / f"{name}.part"
|
||||
with wheel.open(_WHEEL_DIR + name) as src, tmp.open("wb") as dst:
|
||||
while block := src.read(1 << 20):
|
||||
dst.write(block)
|
||||
tmp.replace(directory / name)
|
||||
finally:
|
||||
part.unlink(missing_ok=True)
|
||||
log.info("GPU 계산 파일 준비 완료: %s", directory)
|
||||
|
||||
|
||||
def activate(directory: Path) -> None:
|
||||
"""DLL 을 전체 경로로 미리 불러 둔다.
|
||||
|
||||
CTranslate2 는 `cublas64_12.dll` 을 이름으로만 찾는다. 같은 이름의 모듈이 이미
|
||||
올라와 있으면 Windows 는 그것을 쓰므로, 검색 경로 규칙에 기대지 않아도 된다.
|
||||
"""
|
||||
global _dll_dir_handle
|
||||
if _dll_dir_handle is None and hasattr(os, "add_dll_directory"):
|
||||
_dll_dir_handle = os.add_dll_directory(str(directory))
|
||||
os.environ["PATH"] = f"{directory}{os.pathsep}{os.environ.get('PATH', '')}"
|
||||
for name in DLLS:
|
||||
_loaded.append(ctypes.WinDLL(str(directory / name))) # type: ignore[attr-defined]
|
||||
log.info("cuBLAS 불러옴: %s", directory)
|
||||
@@ -191,6 +191,9 @@ class ModelManager:
|
||||
self.config = config
|
||||
#: 저부하(게임) 모드. 연산 정밀도를 낮춰 VRAM과 GPU 점유를 줄인다.
|
||||
self.low_power = low_power
|
||||
#: 실제로 돌릴 장치. 설정값에서 시작하지만, GPU 가 안 되면 이번 실행만
|
||||
#: CPU 로 바꾼다. 설정 파일에는 남기지 않는다 — 다음엔 GPU 가 될 수 있다.
|
||||
self.device = config.device
|
||||
self._tier: Tier = get_tier(config.tier)
|
||||
self._asr: SpeechRecognizer | None = None
|
||||
self._mt: Translator | None = None
|
||||
@@ -224,7 +227,7 @@ class ModelManager:
|
||||
with self._lock:
|
||||
if self._asr is None:
|
||||
self._asr = SpeechRecognizer(
|
||||
self.effective_asr_spec(), self.config.device, self.config.device_index
|
||||
self.effective_asr_spec(), self.device, self.config.device_index
|
||||
)
|
||||
return self._asr
|
||||
|
||||
@@ -233,7 +236,7 @@ class ModelManager:
|
||||
if self._mt is None:
|
||||
self._mt = create_translator(
|
||||
self.effective_mt_spec(),
|
||||
self.config.device,
|
||||
self.device,
|
||||
self.config.device_index,
|
||||
self.config.lora_adapter_path,
|
||||
)
|
||||
@@ -251,6 +254,15 @@ class ModelManager:
|
||||
self.translator().load()
|
||||
report("준비 완료", 1.0)
|
||||
|
||||
def use_device(self, device: str) -> bool:
|
||||
"""돌릴 장치를 바꾼다. 바뀌었으면 올라가 있던 모델을 내리고 True."""
|
||||
if device == self.device:
|
||||
return False
|
||||
self.unload()
|
||||
self.device = device
|
||||
log.info("연산 장치 변경: %s", device)
|
||||
return True
|
||||
|
||||
def switch_tier(self, tier_key: str) -> Tier:
|
||||
"""티어 변경. 기존 모델은 내려서 VRAM을 즉시 돌려준다."""
|
||||
if tier_key == self._tier.key:
|
||||
|
||||
21
tests/conftest.py
Normal file
21
tests/conftest.py
Normal file
@@ -0,0 +1,21 @@
|
||||
"""모든 테스트 공통 설정."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_cublas_download(monkeypatch):
|
||||
"""엔진 테스트가 Windows 에서 cuBLAS(541MB)를 실제로 받지 않게 한다.
|
||||
|
||||
기본 설정이 device=cuda 라 엔진을 띄우면 Windows 에서는 시작 때 cuBLAS 를
|
||||
준비한다. 그러면 시작이 느려져 시간 제한이 있는 테스트가 실패한다. 엔진이
|
||||
붙잡은 모듈 참조만 바꾸므로 `test_cuda_runtime` 은 진짜 모듈을 그대로 본다.
|
||||
"""
|
||||
monkeypatch.setattr(
|
||||
"livesub.core.engine.cuda_runtime",
|
||||
SimpleNamespace(ensure=lambda *args, **kwargs: False),
|
||||
)
|
||||
@@ -144,3 +144,61 @@ def test_unsupported_language_falls_back_to_best_supported():
|
||||
)
|
||||
t = recognizer(fake).transcribe(AUDIO, target_lang="ko")
|
||||
assert (t.language, t.text) == ("en", "Nice shot")
|
||||
|
||||
|
||||
class SileroDropsWhisper:
|
||||
"""Silero VAD 를 켜면 아무것도 못 받고, 끄면 정해 둔 구간을 돌려준다."""
|
||||
|
||||
def __init__(self, segments):
|
||||
self.segments = segments
|
||||
self.vad_calls: list[bool] = []
|
||||
|
||||
def transcribe(self, audio, language=None, vad_filter=False, **_):
|
||||
self.vad_calls.append(vad_filter)
|
||||
info = SimpleNamespace(
|
||||
language="en", language_probability=0.9, duration=audio.size / 16_000,
|
||||
all_language_probs=[("en", 0.9)],
|
||||
)
|
||||
return iter([] if vad_filter else self.segments), info
|
||||
|
||||
|
||||
def raw(text: str, end: float, logprob: float, ratio: float = 1.0):
|
||||
s = seg(text, logprob)
|
||||
s.end = end
|
||||
s.compression_ratio = ratio
|
||||
return s
|
||||
|
||||
|
||||
# 실측값 (large-v3-turbo, 사용자 게임 녹음 5.2초 구간). Silero 확률이 0.14 라 통째로 버려졌다.
|
||||
EFFECT_VOICE = [raw(" Get up!", 2.0, -0.73), raw(" Over here!", 4.0, -0.73)]
|
||||
FIVE_SECONDS = np.zeros(5 * 16_000, dtype=np.float32)
|
||||
|
||||
|
||||
def test_voice_dropped_by_silero_is_recovered_without_vad():
|
||||
fake = SileroDropsWhisper(EFFECT_VOICE)
|
||||
t = recognizer(fake).transcribe(FIVE_SECONDS, target_lang="ko")
|
||||
assert t.text == "Get up! Over here!"
|
||||
assert fake.vad_calls == [True, False]
|
||||
|
||||
|
||||
def test_noise_hallucination_running_to_window_end_is_dropped():
|
||||
"""말소리가 없으면 30초 창 끝까지 이어진 'Thank you.' 가 나온다 (turbo 실측)."""
|
||||
fake = SileroDropsWhisper([raw(" Thank you.", 29.98, -0.77)])
|
||||
assert recognizer(fake).transcribe(FIVE_SECONDS, target_lang="ko").text == ""
|
||||
|
||||
|
||||
def test_low_confidence_noise_word_is_dropped():
|
||||
fake = SileroDropsWhisper([raw(" Oh.", 0.5, -1.12)])
|
||||
assert recognizer(fake).transcribe(FIVE_SECONDS, target_lang="ko").text == ""
|
||||
|
||||
|
||||
def test_repetition_without_vad_is_dropped():
|
||||
fake = SileroDropsWhisper([raw(" විවිවිවිවිවිවිවි", 3.8, -0.26, ratio=6.0)])
|
||||
assert recognizer(fake).transcribe(FIVE_SECONDS, target_lang="ko").text == ""
|
||||
|
||||
|
||||
def test_partial_results_never_retry():
|
||||
"""중간 결과는 원래 VAD 없이 한 번만 받는다."""
|
||||
fake = SileroDropsWhisper(EFFECT_VOICE)
|
||||
recognizer(fake).transcribe(FIVE_SECONDS, fast=True, target_lang="ko")
|
||||
assert fake.vad_calls == [False]
|
||||
|
||||
76
tests/test_cuda_runtime.py
Normal file
76
tests/test_cuda_runtime.py
Normal file
@@ -0,0 +1,76 @@
|
||||
"""cuBLAS 내려받기·꺼내기 (Windows exe 에서 GPU 로 받아 적는 데 필요)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import zipfile
|
||||
|
||||
import pytest
|
||||
|
||||
from livesub.models import cuda_runtime
|
||||
|
||||
|
||||
def _fake_wheel(tmp_path):
|
||||
wheel = tmp_path / "fake.whl"
|
||||
with zipfile.ZipFile(wheel, "w") as zf:
|
||||
zf.writestr("nvidia/cublas/bin/cublasLt64_12.dll", b"LT" * 1000)
|
||||
zf.writestr("nvidia/cublas/bin/cublas64_12.dll", b"BLAS" * 1000)
|
||||
zf.writestr("nvidia/cublas/bin/nvblas64_12.dll", b"unused")
|
||||
zf.writestr("nvidia/cublas/include/cublas.h", b"header")
|
||||
data = wheel.read_bytes()
|
||||
return wheel.as_uri(), hashlib.sha256(data).hexdigest(), len(data)
|
||||
|
||||
|
||||
def test_download_extracts_only_the_two_dlls(tmp_path):
|
||||
url, sha, size = _fake_wheel(tmp_path)
|
||||
target = tmp_path / "runtime"
|
||||
seen = []
|
||||
|
||||
cuda_runtime.download(target, lambda msg, pct: seen.append(pct), url, sha, size)
|
||||
|
||||
assert cuda_runtime.installed(target)
|
||||
assert (target / "cublasLt64_12.dll").read_bytes() == b"LT" * 1000
|
||||
assert (target / "cublas64_12.dll").read_bytes() == b"BLAS" * 1000
|
||||
assert sorted(p.name for p in target.iterdir()) == ["cublas64_12.dll", "cublasLt64_12.dll"]
|
||||
assert seen and seen[-1] == 1.0
|
||||
|
||||
|
||||
def test_corrupted_download_leaves_nothing_behind(tmp_path):
|
||||
url, _sha, size = _fake_wheel(tmp_path)
|
||||
target = tmp_path / "runtime"
|
||||
|
||||
with pytest.raises(RuntimeError, match="손상"):
|
||||
cuda_runtime.download(target, None, url, "0" * 64, size)
|
||||
|
||||
assert not cuda_runtime.installed(target)
|
||||
assert list(target.iterdir()) == []
|
||||
|
||||
|
||||
def test_pinned_wheel_is_the_blackwell_capable_cublas():
|
||||
# RTX 50 계열(sm_120)은 cuBLAS 12.8 부터 지원한다.
|
||||
major, minor = (int(x) for x in cuda_runtime.WHEEL_VERSION.split(".")[:2])
|
||||
assert (major, minor) >= (12, 8)
|
||||
assert cuda_runtime.WHEEL_VERSION in cuda_runtime.WHEEL_URL
|
||||
assert cuda_runtime.WHEEL_URL.endswith("win_amd64.whl")
|
||||
|
||||
|
||||
def test_ensure_is_a_no_op_off_windows_or_on_cpu(monkeypatch):
|
||||
monkeypatch.setattr(cuda_runtime.sys, "platform", "linux")
|
||||
assert cuda_runtime.ensure(device="cuda") is False
|
||||
monkeypatch.setattr(cuda_runtime.sys, "platform", "win32")
|
||||
assert cuda_runtime.ensure(device="cpu") is False
|
||||
|
||||
|
||||
def test_download_stops_when_cancelled(tmp_path):
|
||||
import threading
|
||||
|
||||
url, sha, size = _fake_wheel(tmp_path)
|
||||
target = tmp_path / "runtime"
|
||||
cancel = threading.Event()
|
||||
cancel.set()
|
||||
|
||||
with pytest.raises(cuda_runtime.DownloadCancelled):
|
||||
cuda_runtime.download(target, None, url, sha, size, cancel=cancel)
|
||||
|
||||
assert not cuda_runtime.installed(target)
|
||||
assert list(target.iterdir()) == []
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
@@ -129,3 +130,126 @@ def test_to_mono_16k_passthrough_when_already_correct():
|
||||
mono = np.linspace(-1, 1, 16_000, dtype=np.float32)
|
||||
out = to_mono_16k(mono, channels=1, src_rate=16_000)
|
||||
assert np.array_equal(out, mono)
|
||||
|
||||
|
||||
class CublasMissingRecognizer(FakeRecognizer):
|
||||
"""Windows exe 에서 cuBLAS 가 없을 때 CTranslate2 가 내는 오류를 흉내 낸다."""
|
||||
|
||||
def transcribe(self, *args, **kwargs):
|
||||
raise RuntimeError("Library cublas64_12.dll is not found or cannot be loaded")
|
||||
|
||||
|
||||
def _wait_for(predicate, timeout=12.0):
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline and not predicate():
|
||||
time.sleep(0.05)
|
||||
return predicate()
|
||||
|
||||
|
||||
def test_gpu_failure_falls_back_to_cpu_and_still_produces_lines(engine, monkeypatch):
|
||||
statuses = []
|
||||
engine._on_status = statuses.append
|
||||
monkeypatch.setattr(
|
||||
engine.models,
|
||||
"recognizer",
|
||||
lambda: CublasMissingRecognizer() if engine.models.device == "cuda" else FakeRecognizer(),
|
||||
)
|
||||
assert engine.models.device == "cuda"
|
||||
|
||||
engine.start()
|
||||
assert _wait_for(lambda: engine.lines), "CPU 로 바꾼 뒤에도 자막이 나오지 않았습니다"
|
||||
engine.stop()
|
||||
|
||||
assert engine.models.device == "cpu"
|
||||
assert engine.config.models.device == "cuda", "설정 파일 값은 그대로 둬야 한다"
|
||||
assert any("CPU로" in s.message and "cublas" in s.message for s in statuses)
|
||||
|
||||
|
||||
def test_non_gpu_failure_is_shown_on_status(engine, monkeypatch):
|
||||
statuses = []
|
||||
engine._on_status = statuses.append
|
||||
|
||||
class Broken(FakeRecognizer):
|
||||
def transcribe(self, *args, **kwargs):
|
||||
raise ValueError("토크나이저가 깨졌습니다")
|
||||
|
||||
monkeypatch.setattr(engine.models, "recognizer", lambda: Broken())
|
||||
engine.start()
|
||||
assert _wait_for(lambda: any("문장 처리 실패" in s.message for s in statuses))
|
||||
engine.stop()
|
||||
assert engine.models.device == "cuda", "GPU 와 상관없는 오류로 CPU 로 바꾸면 안 된다"
|
||||
assert any("토크나이저가 깨졌습니다" in s.message for s in statuses)
|
||||
|
||||
|
||||
def test_gpu_runtime_download_failure_runs_on_cpu(engine, monkeypatch):
|
||||
statuses = []
|
||||
engine._on_status = statuses.append
|
||||
|
||||
def fail(*args, **kwargs):
|
||||
raise OSError("네트워크 연결 없음")
|
||||
|
||||
monkeypatch.setattr("livesub.core.engine.cuda_runtime.ensure", fail)
|
||||
engine.start()
|
||||
assert _wait_for(lambda: engine.lines)
|
||||
engine.stop()
|
||||
assert engine.models.device == "cpu"
|
||||
running = [s for s in statuses if s.state.value == "running"]
|
||||
assert running and "GPU 계산 파일을 받지 못했습니다" in running[0].message
|
||||
|
||||
|
||||
def test_gpu_failure_while_preloading_falls_back_to_cpu(engine, monkeypatch):
|
||||
"""기본값(preload_on_start=True)에서 GPU 로 모델이 안 올라가도 CPU 로 시작한다."""
|
||||
statuses = []
|
||||
engine._on_status = statuses.append
|
||||
engine.config.models.preload_on_start = True
|
||||
devices = []
|
||||
|
||||
def preload(progress=None):
|
||||
devices.append(engine.models.device)
|
||||
if engine.models.device == "cuda":
|
||||
raise RuntimeError("CUDA failed with error no CUDA-capable device is detected")
|
||||
|
||||
monkeypatch.setattr(engine.models, "preload", preload)
|
||||
engine.start()
|
||||
assert _wait_for(lambda: engine.lines), "CPU 로 바꾼 뒤에도 자막이 나오지 않았습니다"
|
||||
engine.stop()
|
||||
|
||||
assert devices == ["cuda", "cpu"]
|
||||
assert not any(s.state.value == "error" for s in statuses)
|
||||
running = [s for s in statuses if s.state.value == "running"]
|
||||
assert running and "CPU로" in running[0].message
|
||||
|
||||
|
||||
def test_stop_while_downloading_gpu_runtime_never_starts_capture(engine, monkeypatch):
|
||||
"""cuBLAS 를 받는 중에 정지하면 받기를 멈추고, 캡처를 켜지 않는다."""
|
||||
from livesub.models.cuda_runtime import DownloadCancelled
|
||||
|
||||
statuses = []
|
||||
engine._on_status = statuses.append
|
||||
downloading = threading.Event()
|
||||
captures = []
|
||||
|
||||
def slow_download(progress=None, device="cuda", cancel=None):
|
||||
downloading.set()
|
||||
while not cancel.is_set():
|
||||
progress("GPU 계산 파일 받는 중", 0.1)
|
||||
time.sleep(0.05)
|
||||
raise DownloadCancelled("멈춤")
|
||||
|
||||
def make_capture(cfg):
|
||||
captures.append(cfg)
|
||||
return FakeCapture()
|
||||
|
||||
monkeypatch.setattr("livesub.core.engine.cuda_runtime.ensure", slow_download)
|
||||
monkeypatch.setattr("livesub.core.engine.create_capture", make_capture)
|
||||
engine.start()
|
||||
assert downloading.wait(5)
|
||||
engine.stop()
|
||||
boot_done = _wait_for(lambda: not any(t.name == "engine-boot" for t in threading.enumerate()), 5)
|
||||
time.sleep(0.3)
|
||||
|
||||
assert boot_done, "정지했는데 시작 작업이 끝나지 않았습니다"
|
||||
assert captures == [], "정지한 뒤에 캡처가 켜졌습니다"
|
||||
assert engine.status.state.value == "idle"
|
||||
assert statuses[-1].state.value == "idle"
|
||||
assert engine.models.device == "cuda", "정지는 GPU 실패가 아니다"
|
||||
|
||||
Reference in New Issue
Block a user