Files
game_voice_recorder/worker/tests/conftest.py
EJClaw 7c9146cd2d 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>
2026-10-15 01:17:48 +09:00

96 lines
3.4 KiB
Python

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()