M0: 기술 검증 - 구조 설계, STT 워커, 앱 코어, 게임 PC 진단
- docs/dev/ARCHITECTURE.md: 코어-워커-사이트 인터페이스 계약 - worker/: faster-whisper 한국어 STT, 음량 정규화, 4단계 잡음 판정, 사전 교정, GPU 감지·모델/CUDA 다운로드, 롤 채팅 OCR·r3dlog, 파인튜닝 파이프라인 (39 tests) - app/src/core: 디스코드 DAVE 음성 녹음(Ogg Opus), STT 대기열, 발로란트/롤 로컬 API 어댑터, 타임라인·기록 API, 사이트 중계, 7일 음성 삭제, 진단 - tools/gen-dictionary.mjs: 공식 게임 데이터 기반 기본 단어사전 (1993단어) - M0 결과: DAVE 연결 1.06s Ready, CPU tiny STT 3.6s→0.31s, 가짜 Riot 서버 통합 테스트 통과 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
95
worker/tests/conftest.py
Normal file
95
worker/tests/conftest.py
Normal file
@@ -0,0 +1,95 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import queue
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
WORKER_DIR = Path(__file__).resolve().parent.parent
|
||||
FIXTURES = Path(__file__).resolve().parent / "fixtures"
|
||||
HF_TINY = Path.home() / ".cache/huggingface/hub/models--Systran--faster-whisper-tiny/snapshots"
|
||||
|
||||
sys.path.insert(0, str(WORKER_DIR))
|
||||
|
||||
|
||||
class WorkerProc:
|
||||
"""python -m gvr_worker 를 자식 프로세스로 띄워 JSON Lines 로 대화한다."""
|
||||
|
||||
def __init__(self, env: dict[str, str]) -> None:
|
||||
self.proc = subprocess.Popen(
|
||||
[sys.executable, "-m", "gvr_worker"], cwd=WORKER_DIR, env=env,
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
text=True, encoding="utf-8",
|
||||
)
|
||||
self.lines: queue.Queue[dict[str, Any]] = queue.Queue()
|
||||
self.raw: list[str] = []
|
||||
self.stderr: list[str] = []
|
||||
threading.Thread(target=self._read, daemon=True).start()
|
||||
threading.Thread(target=self._drain_stderr, daemon=True).start()
|
||||
|
||||
def _drain_stderr(self) -> None:
|
||||
for line in self.proc.stderr: # type: ignore[union-attr]
|
||||
self.stderr.append(line)
|
||||
|
||||
def _read(self) -> None:
|
||||
for line in self.proc.stdout: # type: ignore[union-attr]
|
||||
self.raw.append(line)
|
||||
self.lines.put(json.loads(line)) # stdout 은 항상 유효한 JSON 이어야 한다
|
||||
|
||||
def send(self, obj: dict[str, Any] | str) -> None:
|
||||
text = obj if isinstance(obj, str) else json.dumps(obj, ensure_ascii=False)
|
||||
self.proc.stdin.write(text + "\n") # type: ignore[union-attr]
|
||||
self.proc.stdin.flush() # type: ignore[union-attr]
|
||||
|
||||
def recv(self, timeout: float = 60) -> dict[str, Any]:
|
||||
return self.lines.get(timeout=timeout)
|
||||
|
||||
def request(self, obj: dict[str, Any], timeout: float = 120) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
||||
"""응답과 그 사이에 온 같은 id 의 이벤트들을 돌려준다."""
|
||||
self.send(obj)
|
||||
events = []
|
||||
while True:
|
||||
msg = self.recv(timeout)
|
||||
if msg.get("id") != obj.get("id"):
|
||||
continue
|
||||
if "event" in msg:
|
||||
events.append(msg)
|
||||
continue
|
||||
return msg, events
|
||||
|
||||
def close(self) -> int:
|
||||
if self.proc.poll() is None:
|
||||
try:
|
||||
self.send({"id": "bye", "op": "shutdown"})
|
||||
except (BrokenPipeError, OSError):
|
||||
pass
|
||||
try:
|
||||
return self.proc.wait(timeout=30)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.proc.kill()
|
||||
return self.proc.wait()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def models_dir(tmp_path_factory: pytest.TempPathFactory) -> Path:
|
||||
"""tiny 모델을 HF 캐시에서 링크하거나 (없으면 테스트 중 download 로 받음)."""
|
||||
d = tmp_path_factory.mktemp("models")
|
||||
snaps = sorted(HF_TINY.glob("*/model.bin")) if HF_TINY.is_dir() else []
|
||||
if snaps:
|
||||
(d / "tiny").symlink_to(snaps[0].parent, target_is_directory=True)
|
||||
return d
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def worker(models_dir: Path, tmp_path_factory: pytest.TempPathFactory):
|
||||
env = {**os.environ, "GVR_DATA_DIR": str(tmp_path_factory.mktemp("data")),
|
||||
"GVR_MODELS_DIR": str(models_dir), "PYTHONIOENCODING": "utf-8"}
|
||||
w = WorkerProc(env)
|
||||
yield w
|
||||
w.close()
|
||||
BIN
worker/tests/fixtures/keyboard_clicks.ogg
vendored
Normal file
BIN
worker/tests/fixtures/keyboard_clicks.ogg
vendored
Normal file
Binary file not shown.
BIN
worker/tests/fixtures/silence.ogg
vendored
Normal file
BIN
worker/tests/fixtures/silence.ogg
vendored
Normal file
Binary file not shown.
BIN
worker/tests/fixtures/speech_ko.ogg
vendored
Normal file
BIN
worker/tests/fixtures/speech_ko.ogg
vendored
Normal file
Binary file not shown.
BIN
worker/tests/fixtures/speech_ko_quiet.ogg
vendored
Normal file
BIN
worker/tests/fixtures/speech_ko_quiet.ogg
vendored
Normal file
Binary file not shown.
BIN
worker/tests/fixtures/white_noise.ogg
vendored
Normal file
BIN
worker/tests/fixtures/white_noise.ogg
vendored
Normal file
Binary file not shown.
71
worker/tests/make_fixtures.py
Normal file
71
worker/tests/make_fixtures.py
Normal file
@@ -0,0 +1,71 @@
|
||||
"""테스트 오디오 픽스처 생성 (edge-tts + ffmpeg 필요, 인터넷 필요). 결과는 저장소에 커밋되어 있다.
|
||||
|
||||
.venv/bin/python tests/make_fixtures.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import subprocess
|
||||
import tempfile
|
||||
import wave
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
FIX = Path(__file__).parent / "fixtures"
|
||||
SENTENCE = "레이즈 궁 빠졌어 B 사이트 로테 하자"
|
||||
OPUS = ["-ac", "1", "-ar", "48000", "-c:a", "libopus", "-b:a", "32k"]
|
||||
|
||||
|
||||
def ffmpeg(*args: str) -> None:
|
||||
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", *args], check=True)
|
||||
|
||||
|
||||
def write_wav(path: Path, x: np.ndarray, sr: int = 48000) -> None:
|
||||
pcm = (np.clip(x, -1, 1) * 32767).astype(np.int16)
|
||||
with wave.open(str(path), "wb") as w:
|
||||
w.setnchannels(1)
|
||||
w.setsampwidth(2)
|
||||
w.setframerate(sr)
|
||||
w.writeframes(pcm.tobytes())
|
||||
|
||||
|
||||
async def tts(text: str, out: Path) -> None:
|
||||
import edge_tts
|
||||
|
||||
await edge_tts.Communicate(text, "ko-KR-SunHiNeural").save(str(out))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
FIX.mkdir(exist_ok=True)
|
||||
rng = np.random.default_rng(0)
|
||||
with tempfile.TemporaryDirectory(dir=Path.home() / ".tmp") as td:
|
||||
tmp = Path(td)
|
||||
mp3 = tmp / "s.mp3"
|
||||
asyncio.run(tts(SENTENCE, mp3))
|
||||
ffmpeg("-i", str(mp3), *OPUS, str(FIX / "speech_ko.ogg"))
|
||||
ffmpeg("-i", str(mp3), "-af", "volume=-30dB", *OPUS, str(FIX / "speech_ko_quiet.ogg"))
|
||||
|
||||
sr = 48000
|
||||
# 무음 + 키보드 딸깍 소리 (짧은 감쇠 잡음 버스트)
|
||||
x = rng.normal(0, 0.0005, int(2.5 * sr))
|
||||
for t in np.arange(0.2, 2.3, 0.17) + rng.uniform(-0.03, 0.03, 13):
|
||||
i = int(t * sr)
|
||||
n = int(0.012 * sr)
|
||||
x[i : i + n] += rng.normal(0, 0.25, n) * np.exp(-np.linspace(0, 8, n))
|
||||
wav = tmp / "c.wav"
|
||||
write_wav(wav, x)
|
||||
ffmpeg("-i", str(wav), *OPUS, str(FIX / "keyboard_clicks.ogg"))
|
||||
# 백색 잡음
|
||||
write_wav(wav, rng.normal(0, 0.08, int(2.0 * sr)))
|
||||
ffmpeg("-i", str(wav), *OPUS, str(FIX / "white_noise.ogg"))
|
||||
# 완전 무음에 가까운 소리
|
||||
write_wav(wav, rng.normal(0, 0.0002, int(1.5 * sr)))
|
||||
ffmpeg("-i", str(wav), *OPUS, str(FIX / "silence.ogg"))
|
||||
for p in sorted(FIX.glob("*.ogg")):
|
||||
print(p.name, p.stat().st_size)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
41
worker/tests/test_audio.py
Normal file
41
worker/tests/test_audio.py
Normal file
@@ -0,0 +1,41 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
|
||||
from conftest import FIXTURES
|
||||
from gvr_worker import audio
|
||||
|
||||
|
||||
def test_limiter_never_exceeds_ceiling() -> None:
|
||||
rng = np.random.default_rng(1)
|
||||
x = (rng.normal(0, 0.6, 16000)).astype(np.float32)
|
||||
y = audio.limit(x)
|
||||
assert np.max(np.abs(y)) <= 10 ** (-1 / 20) + 1e-6
|
||||
quiet = x * 0.1
|
||||
assert np.array_equal(audio.limit(quiet), quiet) # 피크가 낮으면 손대지 않음
|
||||
|
||||
|
||||
def test_prepare_normalizes_quiet_speech() -> None:
|
||||
loud = audio.prepare(str(FIXTURES / "speech_ko.ogg"))
|
||||
quiet = audio.prepare(str(FIXTURES / "speech_ko_quiet.ogg"))
|
||||
assert loud.lufs is not None and quiet.lufs is not None
|
||||
assert abs(loud.lufs - quiet.lufs - 30) < 2
|
||||
assert quiet.gain_db == 24.0 # 클램프 상한
|
||||
assert np.max(np.abs(quiet.audio)) <= 10 ** (-1 / 20) + 1e-6
|
||||
assert abs(loud.duration_s - quiet.duration_s) < 0.05
|
||||
|
||||
|
||||
def test_short_utterance_uses_profile(tmp_path) -> None:
|
||||
import subprocess
|
||||
|
||||
src = tmp_path / "short.ogg"
|
||||
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", str(FIXTURES / "speech_ko.ogg"), "-t", "0.3",
|
||||
"-c:a", "libopus", str(src)], check=True)
|
||||
p = audio.prepare(str(src), target_lufs=-18, profile_lufs=-30)
|
||||
assert p.lufs == -30 and p.gain_db == 12
|
||||
|
||||
|
||||
def test_denoise_keeps_length() -> None:
|
||||
a = audio.decode(str(FIXTURES / "white_noise.ogg"))
|
||||
d = audio.denoise(a)
|
||||
assert d.shape == a.shape and np.sqrt(np.mean(d**2)) < np.sqrt(np.mean(a**2))
|
||||
58
worker/tests/test_dictionary.py
Normal file
58
worker/tests/test_dictionary.py
Normal file
@@ -0,0 +1,58 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from gvr_worker.dictionary import Corrector, jamo, jamo_similarity
|
||||
|
||||
DICT = ["레이즈", "로테", "오퍼레이터", "제트", "세이지", "소바", "오멘", "킬조이", "사이퍼", "스파이크", "사이트",
|
||||
"어센트", "바인드", "헤이븐", "팬텀", "밴달", "에코", "세이브", "하버", "게코", "네온", "페이드"]
|
||||
|
||||
|
||||
def make() -> Corrector:
|
||||
return Corrector.from_request([{"from": "비 싸이트", "to": "B 사이트"}], DICT)
|
||||
|
||||
|
||||
def test_report_example() -> None:
|
||||
assert (make().correct_text("레이저 궁 빠졌어 비 싸이트 로태 하자 나 오퍼래이터 삼")
|
||||
== "레이즈 궁 빠졌어 B 사이트 로테 하자 나 오퍼레이터 삼")
|
||||
|
||||
|
||||
def test_jamo() -> None:
|
||||
assert jamo("각") == "ㄱㅏㄱ"
|
||||
assert jamo("왔") == "ㅇㅗㅏㅆ" # 겹모음 분해
|
||||
assert jamo("값A") == "ㄱㅏㅂㅅa"
|
||||
assert jamo_similarity("로태", "로테") > 0.9
|
||||
assert jamo_similarity("빠졌어", "바인드") < 0.5
|
||||
|
||||
|
||||
def test_particles_and_punctuation() -> None:
|
||||
c = make()
|
||||
assert c.correct_text("레이저가 스파이크를 설치했어.") == "레이즈가 스파이크를 설치했어."
|
||||
assert c.correct_text("오맨이랑 같이 가자!") == "오멘이랑 같이 가자!"
|
||||
assert c.correct_text("비 싸이트로 가자") == "B 사이트로 가자"
|
||||
|
||||
|
||||
def test_no_overcorrection() -> None:
|
||||
c = make()
|
||||
text = "지금 빨리 가자 나 진짜 배고파 하자"
|
||||
assert c.correct_text(text) == text
|
||||
assert c.correct_text("세이브 하자") == "세이브 하자" # 사전 단어는 그대로
|
||||
|
||||
|
||||
def test_words_keep_timestamps() -> None:
|
||||
words = [
|
||||
{"w": "레이저", "s": 0.1, "e": 0.5, "p": 0.9, "lead": " "},
|
||||
{"w": "비", "s": 0.6, "e": 0.7, "p": 0.4, "lead": " "},
|
||||
{"w": "싸이트", "s": 0.7, "e": 1.1, "p": 0.8, "lead": " "},
|
||||
{"w": "가자.", "s": 1.2, "e": 1.5, "p": 0.95, "lead": " "},
|
||||
]
|
||||
text, out = make().correct_words(words)
|
||||
assert text == "레이즈 B 사이트 가자."
|
||||
assert out == [
|
||||
{"w": "레이즈", "s": 0.1, "e": 0.5, "p": 0.9},
|
||||
{"w": "B 사이트", "s": 0.6, "e": 1.1, "p": 0.4},
|
||||
{"w": "가자.", "s": 1.2, "e": 1.5, "p": 0.95},
|
||||
]
|
||||
|
||||
|
||||
def test_bad_input_is_ignored() -> None:
|
||||
c = Corrector.from_request([{"from": 1}, "x", {"from": "", "to": "a"}], [None, "", "레이즈"]) # type: ignore[list-item]
|
||||
assert c.correct_text("레이저") == "레이즈"
|
||||
48
worker/tests/test_finetune_utils.py
Normal file
48
worker/tests/test_finetune_utils.py
Normal file
@@ -0,0 +1,48 @@
|
||||
"""파인튜닝 스크립트의 가벼운 부분 (torch 없이 도는 것만)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
FT = Path(__file__).resolve().parent.parent / "gvr_worker" / "finetune"
|
||||
sys.path.insert(0, str(FT))
|
||||
|
||||
import build_dataset # noqa: E402
|
||||
from common import cer, short_name # noqa: E402
|
||||
|
||||
|
||||
def test_cer() -> None:
|
||||
assert cer(["레이즈 궁 빠졌어"], ["레이즈궁 빠졌어."]) == 0.0
|
||||
assert abs(cer(["레이즈 궁"], ["레이저 궁"]) - 1 / 4) < 1e-9
|
||||
assert cer(["가나", "다라"], ["가나", "다마"]) == 0.25
|
||||
|
||||
|
||||
def test_short_name() -> None:
|
||||
assert short_name("openai/whisper-large-v3-turbo") == "large-v3-turbo"
|
||||
assert short_name("openai/whisper-tiny") == "tiny"
|
||||
|
||||
|
||||
def test_split_by_text_is_fixed(tmp_path: Path) -> None:
|
||||
rows = []
|
||||
for i in range(60):
|
||||
wav = tmp_path / f"s{i}.wav"
|
||||
wav.write_bytes(b"x")
|
||||
rows.append({"audio": str(wav), "text": f"문장 {i % 20}", "source": "synth"})
|
||||
man = tmp_path / "m.jsonl"
|
||||
man.write_text("\n".join(json.dumps(r, ensure_ascii=False) for r in rows), encoding="utf-8")
|
||||
train, valid = build_dataset.build(str(man), None)
|
||||
assert valid and train and len(train) + len(valid) == 60
|
||||
assert not ({r["text"] for r in train} & {r["text"] for r in valid}) # 같은 문장이 양쪽에 없음
|
||||
assert build_dataset.build(str(man), None) == (train, valid) # 매번 같은 분할
|
||||
|
||||
|
||||
def test_run_respects_stop_file(tmp_path: Path) -> None:
|
||||
(tmp_path / "finetune.stop").write_text("game")
|
||||
out = subprocess.run([sys.executable, str(FT / "run.py"), "--data-dir", str(tmp_path)],
|
||||
capture_output=True, text=True, encoding="utf-8", timeout=60)
|
||||
assert out.returncode == 0
|
||||
res = json.loads(out.stdout.strip().splitlines()[-1])["result"]
|
||||
assert res["stopped"] is True and res["adopt"] is False
|
||||
30
worker/tests/test_gpu.py
Normal file
30
worker/tests/test_gpu.py
Normal file
@@ -0,0 +1,30 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from gvr_worker.gpu import parse_smi_csv, recommend
|
||||
|
||||
|
||||
def g(mb: int, cc: str = "12.0") -> list[dict]:
|
||||
return [{"index": 0, "name": "GPU", "vram_total_mb": mb, "vram_used_mb": 0, "compute_capability": cc}]
|
||||
|
||||
|
||||
def test_vram_table() -> None:
|
||||
r = recommend(g(16303))
|
||||
assert (r["realtime"], r["precise"], r["compute_type"]) == ("large-v3-turbo", "large-v3", "float16")
|
||||
assert r["budget_mb"] == 13200 and "16GB" in r["reason"] and r["precise_after_match"] is False
|
||||
r = recommend(g(12282))
|
||||
assert (r["realtime"], r["precise"], r["precise_after_match"]) == ("large-v3", "large-v3", True)
|
||||
r = recommend(g(8188))
|
||||
assert (r["realtime"], r["compute_type"]) == ("large-v3-turbo", "float16")
|
||||
r = recommend(g(6144))
|
||||
assert r["compute_type"] == "int8_float16" and "warning" in r
|
||||
assert "warning" not in recommend(g(6144, "8.6"))
|
||||
r = recommend(g(4096))
|
||||
assert (r["realtime"], r["precise"]) == ("small", "medium")
|
||||
r = recommend([])
|
||||
assert r["device"] == "cpu" and r["supported"] is False
|
||||
|
||||
|
||||
def test_parse_smi() -> None:
|
||||
out = parse_smi_csv("0, NVIDIA GeForce RTX 5070 Ti, 16303, 1200, 581.15, 12.0\n", "13.0")
|
||||
assert out == [{"index": 0, "name": "NVIDIA GeForce RTX 5070 Ti", "vram_total_mb": 16303, "vram_used_mb": 1200,
|
||||
"driver": "581.15", "cuda_driver": "13.0", "compute_capability": "12.0"}]
|
||||
70
worker/tests/test_models.py
Normal file
70
worker/tests/test_models.py
Normal file
@@ -0,0 +1,70 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import zipfile
|
||||
|
||||
import pytest
|
||||
|
||||
from gvr_worker import models
|
||||
from gvr_worker.protocol import WorkerError
|
||||
|
||||
|
||||
def test_pypi_win_wheel() -> None:
|
||||
meta = {"info": {"name": "nvidia-cublas-cu12", "version": "12.9.2.10"}, "urls": [
|
||||
{"packagetype": "bdist_wheel", "filename": "x-manylinux_2_27_x86_64.whl", "url": "u1", "size": 1,
|
||||
"digests": {"sha256": "a"}},
|
||||
{"packagetype": "bdist_wheel", "filename": "x-py3-none-win_amd64.whl", "url": "u2", "size": 2,
|
||||
"digests": {"sha256": "b"}},
|
||||
]}
|
||||
assert models.pypi_win_wheel(meta) == {"version": "12.9.2.10", "filename": "x-py3-none-win_amd64.whl",
|
||||
"url": "u2", "size": 2, "sha256": "b"}
|
||||
with pytest.raises(WorkerError):
|
||||
models.pypi_win_wheel({"info": {"name": "x", "version": "1"}, "urls": meta["urls"][:1]})
|
||||
|
||||
|
||||
def test_extract_dlls(tmp_path) -> None:
|
||||
whl = tmp_path / "w.whl"
|
||||
with zipfile.ZipFile(whl, "w") as z:
|
||||
z.writestr("nvidia/cublas/bin/cublas64_12.dll", b"dll")
|
||||
z.writestr("nvidia/cublas/bin/cublasLt64_12.dll", b"dll2")
|
||||
z.writestr("nvidia/cublas/lib/cublas.lib", b"lib")
|
||||
z.writestr("nvidia/cublas/include/cublas.h", b"h")
|
||||
out = tmp_path / "cuda"
|
||||
assert sorted(models.extract_dlls(whl, out)) == ["cublas64_12.dll", "cublasLt64_12.dll"]
|
||||
assert sorted(p.name for p in out.iterdir()) == ["cublas64_12.dll", "cublasLt64_12.dll"]
|
||||
|
||||
|
||||
def test_resolve_and_list(tmp_path, monkeypatch) -> None:
|
||||
monkeypatch.setenv("GVR_MODELS_DIR", str(tmp_path))
|
||||
monkeypatch.setenv("GVR_DATA_DIR", str(tmp_path / "data"))
|
||||
with pytest.raises(WorkerError) as e:
|
||||
models.resolve_model_path("large-v3")
|
||||
assert e.value.code == "model_not_installed"
|
||||
ft = tmp_path / "tiny-ft-20261015"
|
||||
ft.mkdir()
|
||||
(ft / "config.json").write_text("{}")
|
||||
(ft / "model.bin").write_bytes(b"0")
|
||||
(ft / "gvr-model.json").write_text('{"base":"openai/whisper-tiny","cer_before":0.3,"cer_after":0.2}')
|
||||
assert models.resolve_model_path("tiny-ft-20261015") == ft
|
||||
listed = {m["name"]: m for m in models.list_models()["models"]}
|
||||
assert listed["tiny-ft-20261015"]["meta"]["cer_after"] == 0.2
|
||||
(ft / models.PARTIAL_MARKER).write_text("x")
|
||||
assert not models.is_model_dir(ft)
|
||||
|
||||
|
||||
def test_progress_throttle() -> None:
|
||||
events: list[dict] = []
|
||||
rep = models.ProgressReporter(lambda ev, **kw: events.append(kw), total_bytes=100 * models.MB, interval=0.2)
|
||||
for i in range(50):
|
||||
rep.update(i * models.MB)
|
||||
assert len(events) == 1
|
||||
time.sleep(0.25)
|
||||
rep.update(60 * models.MB)
|
||||
assert len(events) == 2 and events[-1]["done_mb"] == 60.0 and events[-1]["total_mb"] == 100.0
|
||||
assert set(events[-1]) == {"done_mb", "total_mb", "speed_mbps", "eta_s"}
|
||||
|
||||
|
||||
def test_disk_check(tmp_path) -> None:
|
||||
with pytest.raises(WorkerError) as e:
|
||||
models._check_disk(tmp_path, 10**18)
|
||||
assert e.value.code == "disk_full"
|
||||
40
worker/tests/test_noise.py
Normal file
40
worker/tests/test_noise.py
Normal file
@@ -0,0 +1,40 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from gvr_worker.noise import HALLUCINATION_PHRASES, SegInfo, judge_text, judge_vad, thresholds
|
||||
|
||||
GOOD = [SegInfo(0.05, -0.3, 1.2)]
|
||||
|
||||
|
||||
def test_phrase_list_size() -> None:
|
||||
assert len(HALLUCINATION_PHRASES) >= 30
|
||||
|
||||
|
||||
def test_clean_text_passes() -> None:
|
||||
assert judge_text("레이즈 궁 빠졌어 B 사이트 로테 하자", GOOD, 0.8, 2.4, 0.5) is None
|
||||
assert judge_text("감사합니다", GOOD, 0.9, 1.0, 0.5) is None # 신뢰도 높으면 실제 발화
|
||||
|
||||
|
||||
def test_no_speech() -> None:
|
||||
assert judge_text("음", [SegInfo(0.9, -1.5, 1.0)], 0.2, 1.0, 0.5) == "no_speech"
|
||||
assert judge_text("", [], 0.0, 1.0, 0.5) == "no_speech"
|
||||
|
||||
|
||||
def test_hallucination() -> None:
|
||||
for t in ["시청해 주셔서 감사합니다.", "구독과 좋아요 부탁드립니다", "MBC 뉴스 이덕영입니다.", "자막 제공 배달의민족",
|
||||
"다음 영상에서 만나요!", "ㅋㅋㅋㅋㅋㅋ", "(음악)"]:
|
||||
assert judge_text(t, GOOD, 0.7, 2.0, 0.5) == "hallucination", t
|
||||
assert judge_text("감사합니다.", GOOD, 0.3, 0.8, 0.5) == "hallucination"
|
||||
|
||||
|
||||
def test_repetition() -> None:
|
||||
assert judge_text("아 아 아 아 아 아 아 아", GOOD, 0.6, 3.0, 0.5) == "repetition"
|
||||
assert judge_text("가자가자가자가자가자가자가자", GOOD, 0.6, 3.0, 0.5) == "repetition"
|
||||
assert judge_text("가자 가자", GOOD, 0.6, 1.0, 0.5) is None
|
||||
|
||||
|
||||
def test_vad_and_sensitivity() -> None:
|
||||
assert judge_vad(0.0, 0.0, 0.5)
|
||||
assert not judge_vad(0.7, 2.0, 0.5)
|
||||
lo, hi = thresholds(0.0), thresholds(1.0)
|
||||
assert lo.vad_ratio < hi.vad_ratio and lo.no_speech_prob > hi.no_speech_prob
|
||||
assert judge_vad(0.15, 0.4, 1.0) and not judge_vad(0.15, 0.4, 0.0)
|
||||
91
worker/tests/test_ocr_r3dlog.py
Normal file
91
worker/tests/test_ocr_r3dlog.py
Normal file
@@ -0,0 +1,91 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
|
||||
from gvr_worker.ocr import Deduper, frame_changed, parse_chat_line
|
||||
from gvr_worker.r3dlog import follow, latest_log, parse_r3d_line, read
|
||||
|
||||
|
||||
def test_parse_team_with_time_and_champion() -> None:
|
||||
assert parse_chat_line("[12:34] [팀] 민수 (아리): 드래곤 가자") == {
|
||||
"game_time": "12:34", "game_time_s": 754.0, "channel": "team", "sender": "민수", "champion": "아리",
|
||||
"message": "드래곤 가자"}
|
||||
|
||||
|
||||
def test_parse_variants() -> None:
|
||||
p = parse_chat_line("[All] Faker (Ahri): gg wp")
|
||||
assert (p["channel"], p["sender"], p["champion"], p["message"], p["game_time"]) == ("all", "Faker", "Ahri", "gg wp", None)
|
||||
p = parse_chat_line("[1:02:03] [파티] 지우: 바론 치자 3:00 에")
|
||||
assert (p["game_time_s"], p["channel"], p["message"]) == (3723.0, "party", "바론 치자 3:00 에")
|
||||
p = parse_chat_line("[05:10] [전체] 승한 (리 신): ㅋㅋ") # 전각 콜론
|
||||
assert (p["channel"], p["champion"], p["message"]) == ("all", "리 신", "ㅋㅋ")
|
||||
p = parse_chat_line("민수: 갱 와줘")
|
||||
assert (p["channel"], p["sender"]) == ("team", "민수")
|
||||
p = parse_chat_line("[12:40] 민수 님이 드래곤을 처치했습니다")
|
||||
assert (p["channel"], p["sender"], p["game_time"]) == ("system", None, "12:40")
|
||||
p = parse_chat_line("드래곤 등장까지 1:00")
|
||||
assert p["channel"] == "system"
|
||||
assert parse_chat_line(" ") is None
|
||||
|
||||
|
||||
def test_dedupe() -> None:
|
||||
d = Deduper(size=3)
|
||||
a = parse_chat_line("[12:34] [팀] 민수 (아리): 드래곤 가자")
|
||||
assert d.first_time(a) and not d.first_time(dict(a))
|
||||
assert d.first_time(parse_chat_line("[12:35] [팀] 민수 (아리): 드래곤 가자"))
|
||||
for i in range(4):
|
||||
d.first_time(parse_chat_line(f"[13:0{i}] 지우: x"))
|
||||
assert d.first_time(a) # 오래된 키는 밀려남
|
||||
|
||||
|
||||
def test_frame_changed() -> None:
|
||||
a = np.zeros((10, 10), np.uint8)
|
||||
assert frame_changed(None, a)
|
||||
assert not frame_changed(a, a.copy())
|
||||
b = a.copy()
|
||||
b[:5] = 200
|
||||
assert frame_changed(a, b)
|
||||
|
||||
|
||||
def test_r3dlog_parse() -> None:
|
||||
assert parse_r3d_line("000754.123| ALWAYS| [팀] 민수 (아리): 드래곤 가자\n") == {
|
||||
"game_time": "12:34", "game_time_s": 754.123, "channel": "team", "sender": "민수", "champion": "아리",
|
||||
"message": "드래곤 가자"}
|
||||
p = parse_r3d_line("[All] Faker (Ahri): gg")
|
||||
assert p["channel"] == "all" and p["game_time_s"] is None
|
||||
assert parse_r3d_line("000012.000| ALWAYS| r3dRenderLayer::Init") is None
|
||||
|
||||
|
||||
def test_r3dlog_latest_read_and_follow(tmp_path) -> None:
|
||||
old = tmp_path / "a" / "old_r3dlog.txt"
|
||||
new = tmp_path / "b" / "new_r3dlog.txt"
|
||||
old.parent.mkdir()
|
||||
new.parent.mkdir()
|
||||
old.write_text("[팀] 옛날 (티모): 하이\n", encoding="utf-8")
|
||||
time.sleep(0.05)
|
||||
new.write_text("000001.000| x\n000065.500| [전체] 지우 (럭스): 안녕\n", encoding="utf-8")
|
||||
assert latest_log(tmp_path) == new
|
||||
r = read(str(tmp_path), since_ms=None)
|
||||
assert r["file"] == str(new) and r["lines"][0]["game_time"] == "01:05"
|
||||
|
||||
stop = threading.Event()
|
||||
got: list[dict] = []
|
||||
|
||||
def run() -> None:
|
||||
for p in follow(new, stop, poll_s=0.05):
|
||||
got.append(p)
|
||||
stop.set()
|
||||
|
||||
t = threading.Thread(target=run)
|
||||
t.start()
|
||||
time.sleep(0.2)
|
||||
with open(new, "a", encoding="utf-8") as f:
|
||||
f.write("000070.000| [팀] 민수 (아리): 미드 ")
|
||||
f.flush()
|
||||
time.sleep(0.15)
|
||||
f.write("갱\n")
|
||||
t.join(timeout=3)
|
||||
assert got and got[0]["message"] == "미드 갱"
|
||||
177
worker/tests/test_protocol.py
Normal file
177
worker/tests/test_protocol.py
Normal file
@@ -0,0 +1,177 @@
|
||||
"""워커 프로세스와 JSON Lines 왕복 (실제 tiny 모델, CPU int8)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from conftest import FIXTURES
|
||||
|
||||
KO_EXPECTED = "레이즈 궁 빠졌어 B 사이트 로테 하자"
|
||||
|
||||
COMMON = {
|
||||
"hotwords": "레이즈 로테 사이트 오퍼레이터",
|
||||
"initial_prompt": None,
|
||||
"corrections": [{"from": "비 싸이트", "to": "B 사이트"}, {"from": "비 사이트", "to": "B 사이트"}],
|
||||
"dictionary": ["레이즈", "로테", "오퍼레이터", "사이트"],
|
||||
"profile_lufs": None,
|
||||
"target_lufs": -18,
|
||||
"noise_sensitivity": 0.5,
|
||||
"denoise": False,
|
||||
}
|
||||
|
||||
|
||||
def cer(ref: str, hyp: str) -> float:
|
||||
a, b = ref.replace(" ", ""), hyp.replace(" ", "")
|
||||
prev = list(range(len(b) + 1))
|
||||
for i, ca in enumerate(a, 1):
|
||||
cur = [i] + [0] * len(b)
|
||||
for j, cb in enumerate(b, 1):
|
||||
cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb))
|
||||
prev = cur
|
||||
return prev[-1] / len(a)
|
||||
|
||||
|
||||
def test_hello_and_errors(worker) -> None:
|
||||
res, _ = worker.request({"id": "1", "op": "hello"})
|
||||
assert res["ok"] is True
|
||||
assert res["result"]["version"] == "1.0.0"
|
||||
assert res["result"]["device"] in ("cuda", "cpu")
|
||||
assert res["result"]["python"].startswith("3.")
|
||||
|
||||
worker.send("this is not json")
|
||||
msg = worker.recv()
|
||||
assert msg == {"id": None, "ok": False, "error": {"code": "bad_json", "message": msg["error"]["message"]}}
|
||||
|
||||
res, _ = worker.request({"id": "2", "op": "does_not_exist"})
|
||||
assert res["ok"] is False and res["error"]["code"] == "unknown_op"
|
||||
|
||||
res, _ = worker.request({"id": "3", "op": "transcribe", "slot": "nope", "path": "x"})
|
||||
assert res["error"]["code"] == "bad_request"
|
||||
|
||||
res, _ = worker.request({"id": "4", "op": "transcribe", "slot": "precise", "path": "x"})
|
||||
assert res["error"]["code"] == "model_not_loaded"
|
||||
|
||||
res, _ = worker.request({"id": "5", "op": "load", "slot": "precise", "model": "no-such-model"})
|
||||
assert res["error"]["code"] == "unknown_model"
|
||||
|
||||
|
||||
def test_gpu_info_and_models(worker) -> None:
|
||||
res, _ = worker.request({"id": "g", "op": "gpu_info"})
|
||||
r = res["result"]
|
||||
assert isinstance(r["gpus"], list)
|
||||
for g in r["gpus"]:
|
||||
assert {"index", "name", "vram_total_mb", "vram_used_mb", "driver", "cuda_driver", "compute_capability"} <= set(g)
|
||||
assert {"realtime", "precise", "compute_type", "budget_mb", "reason"} <= set(r["recommend"])
|
||||
|
||||
res, _ = worker.request({"id": "m", "op": "models"})
|
||||
names = {m["name"]: m for m in res["result"]["models"]}
|
||||
assert set(names) >= {"large-v3-turbo", "large-v3", "medium", "small", "tiny"}
|
||||
assert names["large-v3-turbo"]["repo"] == "mobiuslabsgmbh/faster-whisper-large-v3-turbo"
|
||||
assert {"installed", "path", "size_mb"} <= set(res["result"]["cuda_runtime"])
|
||||
|
||||
|
||||
def test_load_and_transcribe(worker, models_dir: Path) -> None:
|
||||
if not (models_dir / "tiny" / "model.bin").exists():
|
||||
res, events = worker.request({"id": "dl", "op": "download", "target": "model", "name": "tiny"}, timeout=600)
|
||||
assert res["ok"], res
|
||||
assert all(e["event"] == "progress" for e in events)
|
||||
|
||||
res, _ = worker.request({"id": "L", "op": "load", "slot": "realtime", "model": "tiny",
|
||||
"device": "cpu", "compute_type": "int8"})
|
||||
assert res["ok"], res
|
||||
assert res["result"]["device"] == "cpu"
|
||||
|
||||
res, _ = worker.request({"id": "T1", "op": "transcribe", "slot": "realtime",
|
||||
"path": str(FIXTURES / "speech_ko.ogg"), **COMMON})
|
||||
assert res["ok"], res
|
||||
r = res["result"]
|
||||
assert set(r) >= {"text", "raw_text", "words", "noise", "noise_reason", "confidence", "lufs", "gain_db",
|
||||
"speech_ratio", "duration_s", "model", "elapsed_ms"}
|
||||
assert r["noise"] is False and r["noise_reason"] is None
|
||||
assert r["model"] == "tiny"
|
||||
assert "레이즈" in r["text"]
|
||||
assert cer(KO_EXPECTED, r["text"]) < 0.4, r["text"]
|
||||
assert r["words"] and all(set(w) == {"w", "s", "e", "p"} for w in r["words"])
|
||||
assert all(not w["w"].startswith(" ") for w in r["words"])
|
||||
starts = [w["s"] for w in r["words"]]
|
||||
assert starts == sorted(starts) and r["words"][-1]["e"] <= r["duration_s"] + 0.1
|
||||
assert 0 < r["confidence"] <= 1 and r["speech_ratio"] > 0.4
|
||||
print("\nCPU tiny:", r["text"], f"{r['elapsed_ms']}ms")
|
||||
|
||||
# 작은 목소리: 정규화가 게인을 크게 올리고 같은 문장으로 인식
|
||||
res, _ = worker.request({"id": "T2", "op": "transcribe", "slot": "realtime",
|
||||
"path": str(FIXTURES / "speech_ko_quiet.ogg"), **COMMON})
|
||||
q = res["result"]
|
||||
assert q["gain_db"] >= r["gain_db"] + 20
|
||||
assert q["lufs"] < r["lufs"] - 25
|
||||
assert q["noise"] is False and "레이즈" in q["text"]
|
||||
|
||||
|
||||
def test_noise_samples(worker) -> None:
|
||||
worker.request({"id": "L2", "op": "load", "slot": "precise", "model": "tiny", "device": "cpu",
|
||||
"compute_type": "int8"})
|
||||
for name in ("keyboard_clicks", "white_noise", "silence"):
|
||||
res, _ = worker.request({"id": name, "op": "transcribe", "slot": "precise",
|
||||
"path": str(FIXTURES / f"{name}.ogg"), **COMMON})
|
||||
r = res["result"]
|
||||
assert r["noise"] is True, (name, r)
|
||||
assert r["noise_reason"] in ("vad", "no_speech", "hallucination", "repetition")
|
||||
assert r["text"] is None and r["words"] == []
|
||||
|
||||
res, _ = worker.request({"id": "nf", "op": "transcribe", "slot": "precise", "path": "/no/such.ogg"})
|
||||
assert res["error"]["code"] == "file_not_found"
|
||||
res, _ = worker.request({"id": "U", "op": "unload", "slot": "precise"})
|
||||
assert res["ok"]
|
||||
|
||||
|
||||
def test_misc_ops(worker, tmp_path: Path) -> None:
|
||||
logs = tmp_path / "GameLogs" / "2024-05-01T20-00-00"
|
||||
logs.mkdir(parents=True)
|
||||
(logs / "2024-05-01T20-00-00_r3dlog.txt").write_text(
|
||||
"000010.000| ALWAYS| Game started\n"
|
||||
"000754.123| ALWAYS| [팀] 민수 (아리): 드래곤 가자\n", encoding="utf-8")
|
||||
res, _ = worker.request({"id": "r", "op": "r3dlog_check", "logs_dir": str(tmp_path / "GameLogs")})
|
||||
assert res["result"]["found_chat"] is True
|
||||
res, _ = worker.request({"id": "r2", "op": "r3dlog_read", "logs_dir": str(tmp_path / "GameLogs"),
|
||||
"since_ms": None})
|
||||
line = res["result"]["lines"][0]
|
||||
assert line == {"game_time": "12:34", "game_time_s": 754.123, "channel": "team", "sender": "민수",
|
||||
"champion": "아리", "message": "드래곤 가자"}
|
||||
res, _ = worker.request({"id": "r3", "op": "r3dlog_read", "logs_dir": str(tmp_path / "GameLogs"),
|
||||
"since_ms": 4102444800000})
|
||||
assert res["result"] == {"file": None, "lines": []}
|
||||
|
||||
img = tmp_path / "x.png"
|
||||
img.write_bytes(b"\x89PNG")
|
||||
res, _ = worker.request({"id": "o", "op": "ocr_image", "path": str(img)})
|
||||
if sys.platform != "win32":
|
||||
assert res["error"]["code"] == "ocr_unavailable"
|
||||
res, _ = worker.request({"id": "o2", "op": "ocr_start", "window_title": "League of Legends (TM) Client"})
|
||||
assert res["error"]["code"] == "ocr_unavailable"
|
||||
res, _ = worker.request({"id": "c", "op": "download", "target": "cuda_runtime"})
|
||||
assert res["ok"] and res["result"]["skipped"] is True
|
||||
res, _ = worker.request({"id": "s", "op": "ocr_stop"})
|
||||
assert res["ok"] and res["result"]["stopped"] is False
|
||||
|
||||
# train: 별도 파이썬으로 finetune/run.py 실행 → 중지 파일이 있으면 바로 stopped
|
||||
stop = tmp_path / "finetune.stop"
|
||||
stop.write_text("game")
|
||||
res, _ = worker.request({"id": "t", "op": "train", "python": sys.executable,
|
||||
"args": {"stop_file": str(stop), "base": "openai/whisper-tiny"}})
|
||||
assert res["ok"], res
|
||||
assert res["result"]["stopped"] is True and res["result"]["adopt"] is False
|
||||
res, _ = worker.request({"id": "t2", "op": "train", "python": "/no/python"})
|
||||
assert res["error"]["code"] == "finetune_env_missing"
|
||||
|
||||
|
||||
def test_shutdown_exits_cleanly(models_dir: Path, tmp_path: Path) -> None:
|
||||
import os
|
||||
|
||||
from conftest import WorkerProc
|
||||
|
||||
w = WorkerProc({**os.environ, "GVR_DATA_DIR": str(tmp_path), "GVR_MODELS_DIR": str(models_dir)})
|
||||
res, _ = w.request({"id": "x", "op": "shutdown"})
|
||||
assert res == {"id": "x", "ok": True, "result": {"bye": True}}
|
||||
assert w.proc.wait(timeout=20) == 0
|
||||
assert all(line.endswith("\n") for line in w.raw)
|
||||
Reference in New Issue
Block a user