Some checks failed
Windows / verify (push) Has been cancelled
CTranslate2 Windows 패키지는 GPU 계산 때 cublas64_12.dll 을 이름으로 불러오는데 포터블 exe 에는 이 파일(과 cublasLt64_12.dll)이 없다. 리눅스 GPU 점검은 torch 가 깔아 둔 cuBLAS 를 써서 통과했고, torch 를 뺀 exe 에서는 모델은 GPU 에 올라가지만 첫 문장부터 매번 실패했다. 실패는 로그에만 남아 화면은 '듣는 중' 그대로였다. - 처음 GPU 를 쓸 때 NVIDIA 공식 nvidia-cublas-cu12 12.8.4.1(Blackwell 지원)을 PyPI 에서 한 번 받아 모델 폴더에 두고 전체 경로로 미리 불러 둔다. 크기·sha256 을 확인하고 DLL 두 개만 꺼낸다. 시스템에 이미 있으면 받지 않는다. - 받기에 실패하거나 GPU 쪽 오류(cuda/cublas/cudnn)로 문장 처리가 실패하면 이번 실행만 CPU 로 바꿔 같은 구간을 다시 처리한다. 설정 파일 값은 바꾸지 않는다. - 문장 처리 실패와 CPU 전환 사유를 홈 화면 상태 줄에 띄운다. - windows_smoke 에 cuBLAS 받기·불러오기 점검을 넣었다. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
197 lines
6.1 KiB
Python
197 lines
6.1 KiB
Python
"""엔진 파이프라인을 가짜 모델로 끝까지 돌려본다 (GPU/오디오 장치 불필요)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import time
|
|
|
|
import numpy as np
|
|
import pytest
|
|
|
|
from livesub.audio.base import CaptureBackend, to_mono_16k
|
|
from livesub.config import AppConfig
|
|
from livesub.constants import SAMPLE_RATE
|
|
from livesub.core.engine import TranslationEngine
|
|
from livesub.models.asr import Transcript
|
|
|
|
|
|
class FakeCapture(CaptureBackend):
|
|
"""말-침묵-말-침묵 패턴을 즉시 흘려보낸다."""
|
|
|
|
name = "fake"
|
|
per_process = True
|
|
|
|
@staticmethod
|
|
def available() -> bool:
|
|
return True
|
|
|
|
@staticmethod
|
|
def list_sources():
|
|
return []
|
|
|
|
def _run(self) -> None:
|
|
def tone(ms, amp=0.35):
|
|
n = SAMPLE_RATE * ms // 1000
|
|
t = np.arange(n, dtype=np.float32) / SAMPLE_RATE
|
|
return (np.sin(2 * np.pi * 240 * t) * amp).astype(np.float32)
|
|
|
|
pattern = np.concatenate(
|
|
[np.zeros(SAMPLE_RATE // 5, np.float32), tone(900),
|
|
np.zeros(SAMPLE_RATE, np.float32)]
|
|
)
|
|
while not self._stop.is_set():
|
|
for i in range(0, pattern.size, 1600):
|
|
if self._stop.is_set():
|
|
return
|
|
self._emit(pattern[i : i + 1600].copy())
|
|
time.sleep(0.005)
|
|
|
|
|
|
class FakeRecognizer:
|
|
loaded = True
|
|
|
|
def load(self):
|
|
pass
|
|
|
|
def unload(self):
|
|
pass
|
|
|
|
def transcribe(self, audio, language=None, fast=False, prompt="", target_lang=None):
|
|
return Transcript(text="hello world", language="en", confidence=0.99)
|
|
|
|
|
|
class FakeTranslator:
|
|
loaded = True
|
|
|
|
def load(self):
|
|
pass
|
|
|
|
def unload(self):
|
|
pass
|
|
|
|
def translate(self, text, source_lang, target_lang, glossary=None, **kwargs):
|
|
# 실제 Translator 와 같은 키워드(speech_level, source_politeness)를 받는다.
|
|
self.last_kwargs = kwargs
|
|
return f"[{target_lang}] {text}"
|
|
|
|
|
|
@pytest.fixture
|
|
def engine(tmp_path, monkeypatch):
|
|
config = AppConfig()
|
|
config.models.preload_on_start = False
|
|
config.glossary.path = str(tmp_path / "glossary.json")
|
|
config.audio.partial_interval_ms = 0
|
|
config.audio.silence_ms = 300
|
|
config.audio.min_segment_ms = 200
|
|
|
|
lines = []
|
|
eng = TranslationEngine(config, on_line=lines.append)
|
|
monkeypatch.setattr(eng.models, "recognizer", lambda: FakeRecognizer())
|
|
monkeypatch.setattr(eng.models, "translator", lambda: FakeTranslator())
|
|
monkeypatch.setattr("livesub.core.engine.create_capture", lambda cfg: FakeCapture())
|
|
eng.lines = lines
|
|
yield eng
|
|
eng.shutdown()
|
|
|
|
|
|
def test_engine_produces_translated_lines(engine):
|
|
engine.start()
|
|
deadline = time.time() + 12
|
|
while time.time() < deadline and not engine.lines:
|
|
time.sleep(0.05)
|
|
engine.stop()
|
|
|
|
assert engine.lines, "12초 안에 자막이 한 줄도 나오지 않았습니다"
|
|
line = engine.lines[0]
|
|
assert line.source_text == "hello world"
|
|
assert line.translated_text == "[ko] hello world"
|
|
assert line.source_lang == "en"
|
|
assert line.is_final
|
|
assert line.latency_s >= 0
|
|
|
|
|
|
def test_stop_is_idempotent(engine):
|
|
engine.start()
|
|
time.sleep(0.3)
|
|
engine.stop()
|
|
engine.stop()
|
|
assert not engine.running
|
|
|
|
|
|
def test_to_mono_16k_downmixes_and_resamples():
|
|
stereo_48k = np.tile(np.array([1.0, -1.0], dtype=np.float32), 48_000)
|
|
out = to_mono_16k(stereo_48k, channels=2, src_rate=48_000)
|
|
assert out.dtype == np.float32
|
|
assert abs(out.size - 16_000) <= 2 # 1초 분량
|
|
assert np.allclose(out, 0.0, atol=1e-6) # L+R 이 상쇄
|
|
|
|
|
|
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
|