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:
EJClaw
2026-10-15 01:17:48 +09:00
parent 4596989ba7
commit 7c9146cd2d
95 changed files with 18435 additions and 0 deletions

8
worker/.gitignore vendored Normal file
View File

@@ -0,0 +1,8 @@
.venv/
.venv-ft/
__pycache__/
*.pyc
.pytest_cache/
.pytest-tmp/
build/
dist/

94
worker/README.md Normal file
View File

@@ -0,0 +1,94 @@
# gvr-worker (겜녹이 STT 워커)
앱 코어(Electron/Node)가 자식 프로세스로 띄우는 Python 워커. 하는 일:
- 발화 Ogg Opus → 음량 정규화(BS.1770 LUFS + 리미터) → Silero VAD → faster-whisper(한국어 고정, 핫워드, 단어별 시각)
- 잡음 판정 4단계(VAD / no_speech / 환각 문구 / 반복) → `noise`, `noise_reason`
- 교정 사전(정확 일치) + 한글 자모 유사도 교정 (단어 시각 유지)
- GPU 감지(NVML → nvidia-smi)와 VRAM 별 모델 추천, 모델·CUDA 런타임 다운로드(이어받기, 해시 검사, 진행률)
- 롤 채팅 화면 OCR(Windows.Media.Ocr), r3dlog 채팅 확인
- 파인튜닝(별도 환경): TTS 합성 → LoRA → CER 비교 → CTranslate2 내보내기
## 프로토콜
`docs/dev/ARCHITECTURE.md` 1장이 계약이다. stdin/stdout JSON Lines, stdout 은 프로토콜 메시지만, 로그는 stderr.
계약 외 추가 사항:
| op | 설명 |
|---|---|
| `r3dlog_check {logs_dir}` | `{found_chat, file, sample:[...]}` |
| `r3dlog_read {logs_dir, since_ms}` | 최신 `*_r3dlog.txt`(since_ms 이후 수정) 전체 채팅 → `{file, lines:[{game_time, game_time_s, channel, sender, champion, message}]}` |
| `train {python?, args:{...}}` | 파인튜닝 환경의 파이썬(`python` 또는 `GVR_FINETUNE_PYTHON`)으로 `finetune/run.py` 실행. `args` 키는 `--kebab-case` 옵션으로 넘어감. 진행은 `progress` 이벤트(`stage`,`step`,`total`)로 중계 |
- `load` 는 `device` 생략 시 GPU 있으면 cuda/float16, 없으면 cpu/int8. cuda 요청인데 GPU 가 없으면 cpu 로 바꾸고 `"fallback":"no_gpu"`. `cpu_threads` 선택.
- `models` 응답에 `loaded`(슬롯별 적재 상태)와 파인튜닝 모델(`<이름>-ft-<날짜>`, `meta`=gvr-model.json) 이 함께 나온다.
- `ocr_start` 중 창 상태가 바뀌면 `{"event":"ocr_status","state":"window_not_found"|"capturing"|"error"}`.
- `ocr_line.parsed` 에 `game_time_s`(초, 없으면 null) 포함. 시각 없는 줄은 dedupe 키에 시각이 없어 같은 내용 반복이 한 번만 잡힌다 → 게임 옵션에서 채팅 타임스탬프를 켜도록 안내.
- 잡음이면 `text=null`, `words=[]`, `raw_text` 는 모델 출력(① VAD 단계에서 걸리면 Whisper 를 돌리지 않으므로 null).
- 동시성: 같은 슬롯의 load/unload/transcribe 는 순서대로, realtime/precise 는 서로 병렬. download·train·ocr_image·r3dlog_read 는 별도 스레드.
- 주요 오류 코드: `bad_json` `bad_request` `unknown_op` `model_not_loaded` `model_not_installed` `unknown_model` `file_not_found` `decode_failed` `transcribe_failed` `load_failed` `cuda_runtime_missing` `disk_full` `network` `verify_failed` `busy` `ocr_unavailable` `ocr_lang_missing` `finetune_env_missing` `train_failed` `internal`.
환경변수: `GVR_DATA_DIR`, `GVR_MODELS_DIR`(선택), `GVR_FINETUNE_PYTHON`(선택), `GVR_LOG_LEVEL`(기본 INFO).
## 개발 환경 (리눅스)
```bash
cd worker
uv venv --python 3.11 .venv
uv pip install --python .venv/bin/python -r requirements-dev.txt
.venv/bin/python -m gvr_worker # stdin 으로 JSON 한 줄씩
```
## 테스트
```bash
cd worker && .venv/bin/python -m pytest -q
```
- 모델은 tiny(CPU, int8). `~/.cache/huggingface` 에 `Systran/faster-whisper-tiny` 가 있으면 링크하고, 없으면 테스트가 `download` op 로 받는다.
- 픽스처(`tests/fixtures/*.ogg`, 48kHz mono Opus)는 `tests/make_fixtures.py` 로 다시 만들 수 있다 (edge-tts + ffmpeg, 인터넷 필요).
## 패키징 (Windows)
```bat
py -3.11 -m venv .venv && .venv\Scripts\pip install -r requirements-dev.txt
.venv\Scripts\pyinstaller gvr-worker.spec REM → dist\gvr-worker\gvr-worker.exe (onedir)
```
콘솔 앱이며 부모가 `windowsHide` 로 띄운다. faster-whisper VAD onnx, ctranslate2/onnxruntime/av DLL, pywinrt 가 포함되고
`gvr_worker/finetune/*.py` 는 데이터 파일로만 들어간다 (torch 등은 exe 에 넣지 않음).
## Windows CUDA 메모
- ctranslate2 4.8.x Windows 휠은 CUDA 12.8 + cuDNN 9 로 빌드되어 RTX 50(Blackwell, sm_120)을 지원한다. 그래픽 드라이버는 CUDA 12.8 이상을 지원해야 한다(R570+).
- cuBLAS/cuDNN DLL 은 exe 에 넣지 않고 첫 실행 때 `download {target:"cuda_runtime"}` 으로 PyPI 의 `nvidia-cublas-cu12`, `nvidia-cudnn-cu12` win_amd64 휠(약 1.2GB)을 받아 `bin/*.dll` 만 `GVR-Data/cuda/` 에 푼다(sha256 검사). 워커는 시작할 때 이 폴더를 `os.add_dll_directory` + PATH 앞에 넣으므로, 받은 뒤에는 워커를 재시작한다(`restart_required:true`).
- 기본 연산 정밀도는 float16. RTX 50 에서 int8 계열이 cuBLAS 오류를 낸 보고가 있어 int8 은 VRAM 이 빠듯할 때만 추천하고 경고를 붙인다.
- 리눅스에서 `cuda_runtime` 다운로드는 `skipped:true` 로 끝난다.
## 파인튜닝 (M8, 별도 환경)
```bash
uv venv --python 3.11 .venv-ft
uv pip install --python .venv-ft/bin/python torch --index-url https://download.pytorch.org/whl/cu128 # CPU: /whl/cpu
uv pip install --python .venv-ft/bin/python -r gvr_worker/finetune/requirements.txt
.venv-ft/bin/python gvr_worker/finetune/run.py --data-dir GVR-Data \
--dictionary words.txt --sentences sentences.txt --user-corrections corrections.jsonl
```
- 단계: `synth.py`(edge-tts SunHi/InJoon/Hyunsu, 속도·피치 변화, 30% 확률 배경 잡음) → `build_dataset.py`(문장 해시로 고정 검증 세트) →
`evaluate.py`(학습 전 CER) → `train_lora.py`(LoRA r=32, q/k/v/out_proj, CUDA bf16 autocast / CPU fp32, gradient checkpointing) →
`evaluate.py`(학습 후 CER) → `export_ct2.py`(병합 → CTranslate2 float16 → `models/<이름>-ft-<YYYYMMDD>/` + `gvr-model.json`).
- `adopt = cer_after < cer_before` 일 때만 내보낸다(`--export-always` 로 강제). 앱은 `models` 의 `meta` 를 보고 교체/되돌리기.
- 중지 파일(기본 `GVR-Data/finetune.stop`)이 있으면 시작하지 않고, 학습 중 생기면 어댑터를 저장하고 `stopped:true` 로 끝난다.
- 사용자 교정 jsonl: `{"audio":"<training/xxx.ogg>","text":"<고친 문장>"}`.
CPU 스모크 테스트(openai/whisper-tiny, 합성 30개, `--max-steps 3`)는 약 30초에 전체 단계와 CT2 내보내기까지 돈다.
## 알려진 한계
- 화면 OCR 과 Windows OCR 경로는 리눅스에서 실행 검증하지 못했다(파싱·중복 제거만 단위 테스트). 실제 게임 PC 에서 확인 필요.
'전체 화면(독점)' 모드는 캡처가 검게 나올 수 있어 '테두리 없음' 창 모드를 권장한다.
- r3dlog 채팅 형식은 2024년 이전 보고 기준 추정이다. `r3dlog_check` 로 실제 로그를 확인해야 한다.
- 잡음 판정 기준값은 추정치다. 실제 녹음으로 `noise_sensitivity` 와 `noise.py` 임계값을 조정해야 한다.
- 정규화 음량은 16kHz 로 디코딩한 신호에서 잰다(48k 원본과 소폭 차이 가능).
- CUDA 경로(GPU 추론, cuDNN/cuBLAS DLL 다운로드·로딩)는 이 개발 머신에서 실행하지 않았다(M0 에서 게임 PC 로 확인).

50
worker/gvr-worker.spec Normal file
View File

@@ -0,0 +1,50 @@
# -*- mode: python ; coding: utf-8 -*-
# PyInstaller onedir 빌드: pyinstaller gvr-worker.spec → dist/gvr-worker/gvr-worker.exe
# 콘솔 앱이지만 부모(Electron)가 windowsHide 로 띄우므로 창은 보이지 않는다.
import sys
from PyInstaller.utils.hooks import collect_data_files, collect_dynamic_libs, collect_submodules
datas = []
binaries = []
hiddenimports = []
# faster-whisper: Silero VAD onnx (assets/)
datas += collect_data_files("faster_whisper")
# CTranslate2 / onnxruntime / PyAV 네이티브 라이브러리
for pkg in ("ctranslate2", "onnxruntime", "av"):
binaries += collect_dynamic_libs(pkg)
hiddenimports += collect_submodules("av")
hiddenimports += ["pyloudnorm", "scipy.signal", "scipy.ndimage", "pynvml", "mss"]
# Windows OCR (pywinrt) — 윈도우에서만
if sys.platform == "win32":
hiddenimports += collect_submodules("winrt")
binaries += collect_dynamic_libs("winrt")
hiddenimports += ["PIL.Image"]
# 파인튜닝 스크립트는 별도 파이썬 환경에서 돌리므로 모듈로 묶지 않고 파일로만 넣는다
datas += [("gvr_worker/finetune/*.py", "gvr_worker/finetune"),
("gvr_worker/finetune/requirements.txt", "gvr_worker/finetune")]
a = Analysis(
["run_worker.py"],
pathex=["."],
binaries=binaries,
datas=datas,
hiddenimports=hiddenimports,
excludes=["gvr_worker.finetune", "torch", "transformers", "peft", "tkinter", "matplotlib", "IPython",
"pytest"],
noarchive=False,
)
pyz = PYZ(a.pure)
exe = EXE(
pyz,
a.scripts,
[],
exclude_binaries=True,
name="gvr-worker",
console=True,
upx=False,
)
coll = COLLECT(exe, a.binaries, a.datas, strip=False, upx=False, name="gvr-worker")

View File

@@ -0,0 +1,3 @@
"""겜녹이(GVR) STT 워커. 앱 코어와 stdin/stdout JSON Lines 로 통신한다 (docs/dev/ARCHITECTURE.md 1장)."""
__version__ = "1.0.0"

View File

@@ -0,0 +1,4 @@
from gvr_worker.main import main
if __name__ == "__main__":
main()

111
worker/gvr_worker/audio.py Normal file
View File

@@ -0,0 +1,111 @@
"""오디오 디코딩, 라우드니스 정규화(ITU-R BS.1770), 피크 리미터, 선택적 잡음 억제."""
from __future__ import annotations
import logging
from dataclasses import dataclass
import numpy as np
log = logging.getLogger(__name__)
SR = 16000
MIN_GAIN_DB = -12.0
MAX_GAIN_DB = 24.0
CEILING_DBFS = -1.0
SHORT_S = 0.5
SILENCE_LUFS = -70.0
@dataclass
class Prepared:
audio: np.ndarray # STT 입력 (정규화·리미터·선택적 잡음 억제 후), 16k mono float32
duration_s: float
lufs: float | None # 게인 계산에 쓴 음량 (측정값, 짧으면 유저 프로필 값)
gain_db: float # 재생 시 원본에 적용할 게인
def decode(path: str) -> np.ndarray:
from faster_whisper import decode_audio
return decode_audio(path, sampling_rate=SR).astype(np.float32, copy=False)
def measure_lufs(audio: np.ndarray, sr: int = SR) -> float | None:
"""BS.1770 게이팅 적분 음량. 0.4초 미만이거나 무음이면 None."""
if audio.size < int(0.4 * sr) + 1:
return None
import pyloudnorm
try:
lufs = float(pyloudnorm.Meter(sr).integrated_loudness(audio.astype(np.float64)))
except ValueError:
return None
if not np.isfinite(lufs) or lufs < SILENCE_LUFS:
return None
return lufs
def limit(audio: np.ndarray, ceiling_dbfs: float = CEILING_DBFS, sr: int = SR) -> np.ndarray:
"""룩어헤드 피크 리미터. 결과 피크는 항상 ceiling 이하."""
ceiling = 10 ** (ceiling_dbfs / 20)
peak = float(np.max(np.abs(audio))) if audio.size else 0.0
if peak <= ceiling:
return audio
from scipy.ndimage import minimum_filter1d, uniform_filter1d
need = np.minimum(1.0, ceiling / np.maximum(np.abs(audio), 1e-9))
w = max(1, int(0.005 * sr)) # 5ms
# 최소값 필터 창(2w+1)이 평균 창(w)보다 넓으므로 평활 게인 <= 필요 게인이 보장된다
g = uniform_filter1d(minimum_filter1d(need, size=2 * w + 1), size=w)
return np.clip(audio * g, -ceiling, ceiling).astype(np.float32)
def denoise(audio: np.ndarray, sr: int = SR) -> np.ndarray:
"""간단한 스펙트럼 게이팅. 가장 조용한 프레임들로 잡음 스펙트럼을 추정해 그 아래를 감쇠한다."""
from scipy.signal import istft, stft
if audio.size < sr // 4:
return audio
_, _, z = stft(audio, fs=sr, nperseg=512, noverlap=384)
mag = np.abs(z)
energy = mag.mean(axis=0)
quiet = mag[:, energy <= np.quantile(energy, 0.1)]
noise = quiet.mean(axis=1, keepdims=True) if quiet.size else mag.min(axis=1, keepdims=True)
floor = 10 ** (-12 / 20)
mask = np.clip((mag - 1.5 * noise) / np.maximum(mag, 1e-9), floor, 1.0)
# 시간축 평활로 음악성 잡음 줄이기
from scipy.ndimage import uniform_filter1d
mask = uniform_filter1d(mask, size=3, axis=1)
_, out = istft(z * mask, fs=sr, nperseg=512, noverlap=384)
return out[: audio.size].astype(np.float32)
def prepare(
path: str,
target_lufs: float = -18.0,
profile_lufs: float | None = None,
use_denoise: bool = False,
) -> Prepared:
audio = decode(path)
duration = audio.size / SR
measured = measure_lufs(audio) if duration >= SHORT_S else None
lufs = measured if measured is not None else profile_lufs
if lufs is None and audio.size:
# 짧고 프로필도 없음: RMS 로 대충 추정 (완전 무음이면 게인 0)
rms = float(np.sqrt(np.mean(np.square(audio, dtype=np.float64))))
lufs = 20 * np.log10(rms) - 0.691 if rms > 1e-6 else None
if lufs is not None and lufs < SILENCE_LUFS:
lufs = None
gain_db = 0.0 if lufs is None else float(np.clip(target_lufs - lufs, MIN_GAIN_DB, MAX_GAIN_DB))
out = audio * np.float32(10 ** (gain_db / 20)) if gain_db else audio
if use_denoise:
out = denoise(out)
out = limit(out)
return Prepared(
audio=out.astype(np.float32, copy=False),
duration_s=round(duration, 3),
lufs=None if lufs is None else round(float(lufs), 2),
gain_db=round(gain_db, 2),
)

View File

@@ -0,0 +1,228 @@
"""후처리 교정: (a) 교정 사전 정확 일치 치환 → (b) 한글 자모 유사도로 사전 단어에 맞추기.
단어 타임스탬프를 유지하도록 Whisper 단어 목록(words) 단위로 고친다.
"""
from __future__ import annotations
import re
from dataclasses import dataclass, field
from typing import Any, Iterable
# --- 자모 분해 ---------------------------------------------------------------
_L = "ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ"
_V = ["ㅏ", "ㅐ", "ㅑ", "ㅒ", "ㅓ", "ㅔ", "ㅕ", "ㅖ", "ㅗ", "ㅗㅏ", "ㅗㅐ", "ㅗㅣ", "ㅛ", "ㅜ", "ㅜㅓ", "ㅜㅔ", "ㅜㅣ",
"ㅠ", "ㅡ", "ㅡㅣ", "ㅣ"]
_T = ["", "ㄱ", "ㄲ", "ㄱㅅ", "ㄴ", "ㄴㅈ", "ㄴㅎ", "ㄷ", "ㄹ", "ㄹㄱ", "ㄹㅁ", "ㄹㅂ", "ㄹㅅ", "ㄹㅌ", "ㄹㅍ", "ㄹㅎ",
"ㅁ", "ㅂ", "ㅂㅅ", "ㅅ", "ㅆ", "ㅇ", "ㅈ", "ㅊ", "ㅋ", "ㅌ", "ㅍ", "ㅎ"]
def jamo(text: str) -> str:
"""완성형 한글을 자모로 분해 (겹모음·겹받침도 쪼갬). 그 외 문자는 소문자로 그대로."""
out = []
for ch in text:
code = ord(ch) - 0xAC00
if 0 <= code < 11172:
out.append(_L[code // 588])
out.append(_V[(code % 588) // 28])
out.append(_T[code % 28])
else:
out.append(ch.lower())
return "".join(out)
def _is_hangul(ch: str) -> bool:
return 0xAC00 <= ord(ch) <= 0xD7A3
# 발음이 비슷해 자주 헷갈리는 자모쌍은 치환 비용을 낮춘다
_SIMILAR: dict[frozenset[str], float] = {
frozenset(p): c
for p, c in [
(("ㅐ", "ㅔ"), 0.2), (("ㅒ", "ㅖ"), 0.2), (("ㅓ", "ㅗ"), 0.6), (("ㅓ", "ㅡ"), 0.5), (("ㅜ", "ㅡ"), 0.5),
(("ㅗ", "ㅜ"), 0.6), (("ㅕ", "ㅛ"), 0.6), (("ㅑ", "ㅏ"), 0.6), (("ㅣ", "ㅡ"), 0.6),
(("ㄱ", "ㄲ"), 0.4), (("ㄱ", "ㅋ"), 0.4), (("ㄷ", "ㄸ"), 0.4), (("ㄷ", "ㅌ"), 0.4), (("ㅂ", "ㅃ"), 0.4),
(("ㅂ", "ㅍ"), 0.4), (("ㅅ", "ㅆ"), 0.4), (("ㅈ", "ㅉ"), 0.4), (("ㅈ", "ㅊ"), 0.4), (("ㄴ", "ㄹ"), 0.6),
(("ㄴ", "ㅇ"), 0.6), (("ㅁ", "ㅂ"), 0.6),
]
}
def _sub_cost(a: str, b: str) -> float:
if a == b:
return 0.0
return _SIMILAR.get(frozenset((a, b)), 1.0)
def jamo_similarity(a: str, b: str) -> float:
"""가중 레벤슈타인 거리로 계산한 자모 유사도 (0~1)."""
ja, jb = jamo(a), jamo(b)
if not ja or not jb:
return 0.0
prev = [float(j) for j in range(len(jb) + 1)]
for i, ca in enumerate(ja, 1):
cur = [float(i)] + [0.0] * len(jb)
for j, cb in enumerate(jb, 1):
cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + _sub_cost(ca, cb))
prev = cur
return 1.0 - prev[-1] / max(len(ja), len(jb))
# --- 토큰 처리 ---------------------------------------------------------------
PARTICLES = sorted(
["을", "를", "이", "가", "은", "는", "도", "에", "에서", "으로", "로", "한테", "랑", "이랑", "요", "의", "만",
"에게", "까지", "부터", "처럼", "보다", "하고", "이야", "야", "이요"],
key=len, reverse=True,
)
# 자모 교정 대상에서 빼는 아주 흔한 단어 (오교정 방지)
COMMON_WORDS = frozenset(
"""나 너 저 제 내 네 우리 너희 저희 그 이 저거 이거 그거 여기 거기 저기 지금 빨리 천천히 진짜 정말 아니 아니야 그래
그래서 근데 그런데 그리고 하지만 왜 뭐 뭐야 어디 언제 누구 어떻게 이제 아직 다시 같이 먼저 나중 오늘 내일 어제
사람 시간 하나 둘 셋 많이 조금 좀 다 잘 못 안 더 덜 가자 하자 해 해라 해줘 봐 보자 와 와라 가 가라 있어 없어
했어 됐어 된다 했다 좋아 싫어 맞아 알았어 몰라 괜찮아 미안 고마워 감사 대박 레전드 이번 다음 저번 처음 마지막
왼쪽 오른쪽 위 아래 앞 뒤 옆 안쪽 바깥 하나만 진짜로 계속 그냥 일단 이미 혹시 아마 너무 엄청 완전""".split()
)
_PUNCT_RE = re.compile(r"^([\"'“‘(\[{]*)(.*?)([.,!?…~\"'”’)\]}:;]*)$", re.S)
@dataclass
class Token:
text: str # 앞뒤 공백 없는 단어 (문장부호 포함)
lead: str = " " # 원래 앞 공백 (텍스트 재조립용)
s: float | None = None
e: float | None = None
p: float | None = None
locked: bool = False # 교정 사전으로 이미 바뀐 단어
extra: dict[str, Any] = field(default_factory=dict)
def _split_punct(word: str) -> tuple[str, str, str]:
m = _PUNCT_RE.match(word)
return (m.group(1), m.group(2), m.group(3)) if m else ("", word, "")
def _strip_particle(core: str) -> tuple[str, str]:
for p in PARTICLES:
if core.endswith(p) and len(core) - len(p) >= 2:
return core[: -len(p)], p
return core, ""
@dataclass
class Corrector:
corrections: list[tuple[str, str]]
dictionary: list[str]
threshold: float = 0.8
@classmethod
def from_request(
cls, corrections: Iterable[dict[str, Any]] | None, dictionary: Iterable[str] | None, threshold: float = 0.8
) -> "Corrector":
pairs = []
for c in corrections or []:
if isinstance(c, dict) and isinstance(c.get("from"), str) and isinstance(c.get("to"), str):
f = " ".join(c["from"].split())
if f:
pairs.append((f, c["to"].strip()))
pairs.sort(key=lambda x: len(x[0]), reverse=True) # 긴 것 먼저
words = [w.strip() for w in (dictionary or []) if isinstance(w, str) and w.strip()]
return cls(pairs, words, threshold)
def __post_init__(self) -> None:
self._dict_set = {w for w in self.dictionary}
self._targets = {to for _, to in self.corrections}
# 한 단어로 된 한글 사전 단어만 자모 교정 후보 (2음절 이상)
self._candidates = [
w for w in dict.fromkeys(self.dictionary)
if " " not in w and len(w) >= 2 and any(_is_hangul(c) for c in w)
]
# (a) 교정 사전 -----------------------------------------------------------
def _apply_corrections(self, toks: list[Token]) -> list[Token]:
for src, dst in self.corrections:
parts = src.split(" ")
n = len(parts)
i = 0
while i + n <= len(toks):
window = toks[i : i + n]
if any(t.locked for t in window):
i += 1
continue
cores = [_split_punct(t.text) for t in window]
ok = all(cores[k][1] == parts[k] for k in range(n - 1))
last_pre, last_core, last_post = cores[-1]
suffix = ""
if ok and last_core != parts[-1]:
stem, part = _strip_particle(last_core)
if stem == parts[-1]:
suffix = part
else:
ok = False
if not ok:
i += 1
continue
first = window[0]
merged = Token(
text=cores[0][0] + dst + suffix + last_post,
lead=first.lead,
s=first.s,
e=window[-1].e,
p=min((t.p for t in window if t.p is not None), default=None),
locked=True,
)
toks[i : i + n] = [merged]
i += 1
return toks
# (b) 자모 유사도 ---------------------------------------------------------
def _best_match(self, core: str) -> str | None:
if core in self._dict_set or core in self._targets or core in COMMON_WORDS:
return None
if len(core) < 2 or not all(_is_hangul(c) for c in core):
return None
best, best_sim = None, self.threshold
for w in self._candidates:
if abs(len(w) - len(core)) > 1:
continue
sim = jamo_similarity(core, w)
if sim >= best_sim and (best is None or sim > best_sim):
best, best_sim = w, sim
return best
def _apply_jamo(self, toks: list[Token]) -> None:
if not self._candidates:
return
for t in toks:
if t.locked:
continue
pre, core, post = _split_punct(t.text)
if not core:
continue
repl = self._best_match(core)
suffix = ""
if repl is None:
stem, part = _strip_particle(core)
if part and stem not in self._dict_set:
repl = self._best_match(stem)
suffix = part
if repl is not None:
t.text = pre + repl + suffix + post
def correct_tokens(self, toks: list[Token]) -> list[Token]:
toks = self._apply_corrections(toks)
self._apply_jamo(toks)
return toks
# 공개 API ----------------------------------------------------------------
def correct_text(self, text: str) -> str:
toks = [Token(w) for w in text.split()]
return " ".join(t.text for t in self.correct_tokens(toks))
def correct_words(self, words: list[dict[str, Any]]) -> tuple[str, list[dict[str, Any]]]:
"""words: [{"w","s","e","p","lead"}] → (교정된 텍스트, 교정된 words)."""
toks = [Token(w["w"], w.get("lead", " "), w.get("s"), w.get("e"), w.get("p")) for w in words]
toks = self.correct_tokens(toks)
text = "".join(t.lead + t.text for t in toks).strip()
return text, [{"w": t.text, "s": t.s, "e": t.e, "p": t.p} for t in toks]

View File

@@ -0,0 +1,70 @@
"""합성 매니페스트 + 사용자 교정 내보내기 → train/valid 분할.
검증 세트는 고정: 문장(공백 제거) 해시로 정하므로 학습을 다시 해도 같은 문장이 검증에 남고,
같은 문장의 다른 녹음/합성이 학습과 검증에 나뉘어 들어가지 않는다.
실제 목소리(사용자 교정)는 20%, 합성은 10% 를 검증으로 뺀다.
python build_dataset.py --synth work/synth/manifest.jsonl --user corrections.jsonl --out work/data
사용자 교정 jsonl 형식: {"audio": "<ogg 경로>", "text": "<고친 문장>"} (앱이 training/ 에서 내보냄)
"""
from __future__ import annotations
import argparse
import hashlib
from pathlib import Path
from common import log, read_jsonl, write_jsonl
VALID_RATIO = {"user": 0.2, "synth": 0.1}
def _key(text: str) -> str:
return "".join(text.split())
def is_valid(text: str, has_user: bool) -> bool:
"""문장 단위 판정. 사용자 녹음이 있는 문장은 20%, 합성만 있는 문장은 10% 확률(해시 고정)로 검증."""
bucket = int(hashlib.sha1(_key(text).encode("utf-8")).hexdigest()[:8], 16) / 0xFFFFFFFF
return bucket < VALID_RATIO["user" if has_user else "synth"]
def build(synth: str | None, user: str | None) -> tuple[list[dict], list[dict]]:
rows: list[dict] = []
for path, source in ((synth, "synth"), (user, "user")):
if not path or not Path(path).is_file():
continue
for r in read_jsonl(path):
text = str(r.get("text") or "").strip()
audio = r.get("audio")
if not text or not audio or not Path(audio).is_file():
continue
rows.append({"audio": str(audio), "text": text, "source": r.get("source") or source})
user_texts = {_key(r["text"]) for r in rows if r["source"] == "user"}
held = {_key(r["text"]) for r in rows if is_valid(r["text"], _key(r["text"]) in user_texts)}
texts = sorted({_key(r["text"]) for r in rows})
if not held and len(texts) >= 2: # 데이터가 아주 적어도 문장 하나는 검증으로 (정렬 첫 문장: 고정)
held = {texts[0]}
train = [r for r in rows if _key(r["text"]) not in held]
valid = [r for r in rows if _key(r["text"]) in held]
return train, valid
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--synth")
ap.add_argument("--user")
ap.add_argument("--out", required=True)
a = ap.parse_args()
train, valid = build(a.synth, a.user)
if not train or not valid:
raise SystemExit(f"학습 데이터가 부족합니다 (train {len(train)}, valid {len(valid)})")
out = Path(a.out)
out.mkdir(parents=True, exist_ok=True)
write_jsonl(out / "train.jsonl", train)
write_jsonl(out / "valid.jsonl", valid)
log(f"train {len(train)} / valid {len(valid)} → {out}")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,99 @@
"""파인튜닝 스크립트 공용 도구 (가벼운 의존성만: numpy, av)."""
from __future__ import annotations
import json
import re
import sys
import wave
from pathlib import Path
from typing import Any, Iterable, Iterator
import numpy as np
SR = 16000
def emit(obj: dict[str, Any]) -> None:
"""stdout 에 JSON 한 줄 (run.py / 워커가 읽는다). 로그는 stderr 로."""
sys.stdout.write(json.dumps(obj, ensure_ascii=False) + "\n")
sys.stdout.flush()
def progress(stage: str, step: int, total: int, **extra: Any) -> None:
emit({"event": "progress", "stage": stage, "step": step, "total": total, **extra})
def log(msg: str) -> None:
sys.stderr.write(msg + "\n")
sys.stderr.flush()
def read_jsonl(path: str | Path) -> Iterator[dict[str, Any]]:
with open(path, encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
yield json.loads(line)
def write_jsonl(path: str | Path, rows: Iterable[dict[str, Any]]) -> int:
n = 0
with open(path, "w", encoding="utf-8") as f:
for r in rows:
f.write(json.dumps(r, ensure_ascii=False) + "\n")
n += 1
return n
def load_audio(path: str | Path, sr: int = SR) -> np.ndarray:
"""아무 형식(ogg/mp3/wav) → 16k mono float32 (PyAV)."""
import av
with av.open(str(path)) as c:
res = av.AudioResampler(format="fltp", layout="mono", rate=sr)
chunks = []
for frame in c.decode(audio=0):
for f in res.resample(frame):
chunks.append(f.to_ndarray()[0])
for f in res.resample(None):
chunks.append(f.to_ndarray()[0])
return np.concatenate(chunks).astype(np.float32) if chunks else np.zeros(0, np.float32)
def write_wav(path: str | Path, audio: np.ndarray, sr: int = SR) -> None:
pcm = (np.clip(audio, -1.0, 1.0) * 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())
_CER_STRIP = re.compile(r"[\s.,!?…~\"'“”‘’()\[\]-]+")
def edit_distance(a: str, b: str) -> int:
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]
def cer(refs: list[str], hyps: list[str]) -> float:
"""말뭉치 CER: 공백·문장부호를 빼고 글자 편집 거리 합 / 정답 글자 수 합."""
dist = total = 0
for r, h in zip(refs, hyps, strict=True):
r2, h2 = _CER_STRIP.sub("", r).lower(), _CER_STRIP.sub("", h).lower()
dist += edit_distance(r2, h2)
total += len(r2)
return dist / max(total, 1)
def short_name(base: str) -> str:
"""openai/whisper-large-v3-turbo → large-v3-turbo"""
name = base.rstrip("/").split("/")[-1]
return name[len("whisper-"):] if name.startswith("whisper-") else name

View File

@@ -0,0 +1,57 @@
"""검증 세트 CER 계산 (기본 모델 또는 LoRA 어댑터 적용 모델).
python evaluate.py --base openai/whisper-large-v3-turbo --data work/data/valid.jsonl [--adapter work/adapter]
끝: {"result":{"cer":0.123,"n":40,"samples":[...]}}
"""
from __future__ import annotations
import argparse
import numpy as np
from common import cer, emit, load_audio, log, progress, read_jsonl
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--base", required=True)
ap.add_argument("--adapter")
ap.add_argument("--data", required=True)
ap.add_argument("--batch", type=int, default=8)
a = ap.parse_args()
import torch
from transformers import WhisperForConditionalGeneration, WhisperProcessor
cuda = torch.cuda.is_available()
dtype = torch.float16 if cuda else torch.float32
processor = WhisperProcessor.from_pretrained(a.base)
model = WhisperForConditionalGeneration.from_pretrained(a.base, dtype=dtype)
if a.adapter:
from peft import PeftModel
model = PeftModel.from_pretrained(model, a.adapter).merge_and_unload()
model.to("cuda" if cuda else "cpu").eval()
rows = list(read_jsonl(a.data))
refs, hyps = [], []
stage = "evaluate_tuned" if a.adapter else "evaluate_base"
for i in range(0, len(rows), a.batch):
chunk = rows[i : i + a.batch]
audios = [load_audio(r["audio"])[: 30 * 16000] for r in chunk]
feats = processor.feature_extractor(audios, sampling_rate=16000, return_tensors="np").input_features
x = torch.tensor(np.asarray(feats), dtype=dtype, device=model.device)
with torch.inference_mode():
ids = model.generate(input_features=x, language="ko", task="transcribe", max_new_tokens=128)
hyps += [t.strip() for t in processor.batch_decode(ids, skip_special_tokens=True)]
refs += [r["text"] for r in chunk]
progress(stage, min(i + a.batch, len(rows)), len(rows))
score = cer(refs, hyps)
log(f"{stage}: CER {score:.4f} (n={len(rows)})")
emit({"result": {"cer": round(score, 4), "n": len(rows),
"samples": [{"ref": r, "hyp": h} for r, h in list(zip(refs, hyps, strict=True))[:5]]}})
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,72 @@
"""LoRA 를 기본 모델에 합치고 CTranslate2(float16) 로 변환 → models/<name>-ft-<날짜>/
python export_ct2.py --base openai/whisper-large-v3-turbo --adapter work/adapter --models-dir GVR-Data/models \
--cer-before 0.12 --cer-after 0.09
끝: {"result":{"model_dir": "...", "name": "..."}}
"""
from __future__ import annotations
import argparse
import json
import shutil
import time
from datetime import datetime
from pathlib import Path
from common import emit, log, progress, short_name
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--base", required=True)
ap.add_argument("--adapter", required=True)
ap.add_argument("--models-dir", required=True)
ap.add_argument("--name", help="기본: <기본모델 짧은 이름>-ft-<YYYYMMDD>")
ap.add_argument("--cer-before", type=float)
ap.add_argument("--cer-after", type=float)
ap.add_argument("--quantization", default="float16")
a = ap.parse_args()
import ctranslate2
import torch
from peft import PeftModel
from transformers import WhisperForConditionalGeneration, WhisperProcessor
name = a.name or f"{short_name(a.base)}-ft-{datetime.now():%Y%m%d}"
root = Path(a.models_dir)
root.mkdir(parents=True, exist_ok=True)
out = root / name
merged = root / f".merge-{name}"
shutil.rmtree(merged, ignore_errors=True)
try:
progress("export", 0, 2)
model = WhisperForConditionalGeneration.from_pretrained(a.base, dtype=torch.float32)
model = PeftModel.from_pretrained(model, a.adapter).merge_and_unload()
model.save_pretrained(str(merged))
processor = WhisperProcessor.from_pretrained(a.adapter)
processor.save_pretrained(str(merged))
# faster-whisper 는 preprocessor_config.json 의 feature_size(80/128 mel)를 읽는다.
# transformers 5 의 processor 저장은 processor_config.json 만 쓰므로 따로 저장한다.
processor.feature_extractor.save_pretrained(str(merged))
del model
progress("export", 1, 2)
copy = ["tokenizer.json", "preprocessor_config.json"]
missing = [f for f in copy if not (merged / f).exists()]
if missing:
raise SystemExit(f"내보내기에 필요한 파일이 없습니다: {missing}")
ctranslate2.converters.TransformersConverter(str(merged), copy_files=copy).convert(
str(out), quantization=a.quantization, force=True)
finally:
shutil.rmtree(merged, ignore_errors=True)
meta = {"base": a.base, "adapter": str(a.adapter), "cer_before": a.cer_before, "cer_after": a.cer_after,
"quantization": a.quantization, "created": datetime.now().isoformat(timespec="seconds"),
"created_ts": int(time.time())}
(out / "gvr-model.json").write_text(json.dumps(meta, ensure_ascii=False, indent=1), encoding="utf-8")
progress("export", 2, 2)
log(f"내보냄 → {out}")
emit({"result": {"model_dir": str(out), "name": name}})
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,10 @@
# 파인튜닝 전용 환경 (워커와 별도). torch 는 아래 인덱스에서 따로 설치:
# Windows/RTX 50 (CUDA 12.8): pip install torch --index-url https://download.pytorch.org/whl/cu128
# CPU 테스트: pip install torch --index-url https://download.pytorch.org/whl/cpu
transformers==5.19.0
peft==0.21.2
accelerate==1.15.0
ctranslate2==4.8.3
edge-tts==7.3.1
av==18.1.0
numpy==2.4.6

View File

@@ -0,0 +1,133 @@
"""파인튜닝 전체 흐름: 합성 → 데이터셋 → 학습 → 평가(전/후) → CT2 내보내기.
각 단계는 같은 파이썬으로 별도 프로세스에서 돈다 (단계마다 메모리를 비움).
stdout: 진행 {"event":"progress","stage":..,"step":..,"total":..} / 마지막 {"result":{...,"adopt":bool}}
adopt = 학습 후 CER < 학습 전 CER. adopt 일 때만 내보낸다 (--export-always 면 항상).
python run.py --data-dir GVR-Data --dictionary words.txt --sentences s.txt --user-corrections c.jsonl
"""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
from datetime import datetime
from pathlib import Path
from typing import Any
from common import emit, log
HERE = Path(__file__).resolve().parent
class Stopped(Exception):
pass
def stage(script: str, args: list[str]) -> dict[str, Any]:
"""하위 스크립트를 실행하고 진행 줄은 그대로 중계, 마지막 result 를 돌려준다."""
cmd = [sys.executable, str(HERE / script), *args]
log("$ " + " ".join(cmd))
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, text=True, encoding="utf-8", errors="replace")
result: dict[str, Any] = {}
for line in proc.stdout or []:
try:
msg = json.loads(line)
except json.JSONDecodeError:
log(line.rstrip())
continue
if isinstance(msg, dict) and msg.get("event") == "progress":
emit(msg)
elif isinstance(msg, dict) and "result" in msg:
result = msg["result"]
if proc.wait() != 0:
raise SystemExit(f"{script} 실패 (종료 코드 {proc.returncode})")
return result
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--data-dir", required=True)
ap.add_argument("--base", default="openai/whisper-large-v3-turbo")
ap.add_argument("--sentences")
ap.add_argument("--dictionary")
ap.add_argument("--user-corrections")
ap.add_argument("--synth-count", type=int, default=300)
ap.add_argument("--epochs", type=float, default=3)
ap.add_argument("--max-steps", type=int, default=0)
ap.add_argument("--batch", type=int, default=4)
ap.add_argument("--accum", type=int, default=4)
ap.add_argument("--lr", type=float, default=1e-4)
ap.add_argument("--stop-file", help="기본: <data-dir>/finetune.stop (앱이 게임 시작 때 만든다)")
ap.add_argument("--work", help="기본: <data-dir>/finetune/<시각>")
ap.add_argument("--name")
ap.add_argument("--export-always", action="store_true")
a = ap.parse_args()
data_dir = Path(a.data_dir)
stop_file = Path(a.stop_file) if a.stop_file else data_dir / "finetune.stop"
work = Path(a.work) if a.work else data_dir / "finetune" / datetime.now().strftime("%Y%m%d-%H%M%S")
work.mkdir(parents=True, exist_ok=True)
res: dict[str, Any] = {"base": a.base, "work": str(work), "adopt": False, "stopped": False}
def check_stop() -> None:
if stop_file.exists():
raise Stopped()
try:
check_stop()
synth_manifest = None
if a.synth_count > 0 and (a.sentences or a.dictionary):
sargs = ["--out", str(work / "synth"), "--count", str(a.synth_count)]
if a.sentences:
sargs += ["--sentences", a.sentences]
if a.dictionary:
sargs += ["--dictionary", a.dictionary]
stage("synth.py", sargs)
synth_manifest = str(work / "synth" / "manifest.jsonl")
check_stop()
dargs = ["--out", str(work / "data")]
if synth_manifest:
dargs += ["--synth", synth_manifest]
if a.user_corrections:
dargs += ["--user", a.user_corrections]
stage("build_dataset.py", dargs)
valid = str(work / "data" / "valid.jsonl")
check_stop()
before = stage("evaluate.py", ["--base", a.base, "--data", valid])
res["cer_before"] = before["cer"]
check_stop()
tr = stage("train_lora.py", [
"--base", a.base, "--train", str(work / "data" / "train.jsonl"), "--out", str(work / "adapter"),
"--epochs", str(a.epochs), "--max-steps", str(a.max_steps), "--batch", str(a.batch),
"--accum", str(a.accum), "--lr", str(a.lr), "--stop-file", str(stop_file)])
res["train"] = tr
if tr.get("stopped"):
raise Stopped()
after = stage("evaluate.py", ["--base", a.base, "--adapter", str(work / "adapter"), "--data", valid])
res["cer_after"] = after["cer"]
res["adopt"] = res["cer_after"] < res["cer_before"]
res["samples"] = after.get("samples")
if res["adopt"] or a.export_always:
check_stop()
eargs = ["--base", a.base, "--adapter", str(work / "adapter"), "--models-dir", str(data_dir / "models"),
"--cer-before", str(res["cer_before"]), "--cer-after", str(res["cer_after"])]
if a.name:
eargs += ["--name", a.name]
ex = stage("export_ct2.py", eargs)
res["model_dir"], res["model_name"] = ex["model_dir"], ex["name"]
except Stopped:
log("게임 실행 감지(중지 파일) → 파인튜닝 중단")
res["stopped"] = True
res["adopt"] = False
emit({"result": res})
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,132 @@
"""단어사전 문장으로 합성 학습 음성 만들기 (edge-tts, 인터넷 필요).
python synth.py --sentences s.txt --dictionary words.txt --count 200 --out work/synth
출력: out/*.wav (16k mono) + out/manifest.jsonl ({"audio","text","source":"synth","voice"})
"""
from __future__ import annotations
import argparse
import asyncio
import random
import tempfile
from pathlib import Path
import numpy as np
from common import SR, load_audio, log, progress, write_jsonl, write_wav
VOICES = ["ko-KR-SunHiNeural", "ko-KR-InJoonNeural", "ko-KR-HyunsuMultilingualNeural"]
RATES = ["-10%", "+0%", "+10%", "+20%"]
PITCHES = ["-6Hz", "+0Hz", "+6Hz"]
TEMPLATES = [
"{w} 조심해", "{w} 어디 있어", "{w} 봤어", "지금 {w} 간다", "{w} 쪽으로 가자", "{w} 잡았어",
"{w} 각이야", "{w} 써줘", "나 {w} 할게", "{w} 빠졌어",
]
def build_sentences(sentences: list[str], words: list[str], count: int, rng: random.Random) -> list[str]:
pool = list(dict.fromkeys(s.strip() for s in sentences if s.strip()))
for w in words:
pool.append(rng.choice(TEMPLATES).format(w=w))
rng.shuffle(pool)
if not pool:
raise SystemExit("문장이 없습니다 (--sentences 또는 --dictionary 필요)")
return [pool[i % len(pool)] for i in range(count)]
def mix_noise(x: np.ndarray, rng: random.Random, noise_files: list[Path]) -> np.ndarray:
"""SNR 10~30dB 로 배경 잡음 섞기. 잡음 파일이 없으면 합성 잡음(백색+키보드 딸깍)."""
n = x.size
if noise_files:
noise = load_audio(rng.choice(noise_files))
if noise.size == 0:
return x
noise = np.tile(noise, int(np.ceil(n / noise.size)))[:n]
else:
g = np.random.default_rng(rng.randrange(1 << 30))
noise = g.normal(0, 1, n).astype(np.float32) * 0.3
for _ in range(int(n / SR * 4)): # 초당 4번 딸깍
i = g.integers(0, max(1, n - 200))
noise[i : i + 200] += g.normal(0, 3, min(200, n - i)) * np.exp(-np.linspace(0, 8, min(200, n - i)))
snr = rng.uniform(10, 30)
ps = float(np.mean(x**2)) + 1e-12
pn = float(np.mean(noise**2)) + 1e-12
out = x + noise * np.sqrt(ps / (pn * 10 ** (snr / 10)))
peak = float(np.max(np.abs(out)))
return (out / peak * 0.95 if peak > 0.99 else out).astype(np.float32)
async def synth_all(texts: list[str], out: Path, noise_prob: float, noise_files: list[Path], seed: int,
voices: list[str]) -> list[dict]:
import edge_tts
rng = random.Random(seed)
jobs = [(i, t, rng.choice(voices), rng.choice(RATES), rng.choice(PITCHES), rng.random() < noise_prob,
rng.randrange(1 << 30)) for i, t in enumerate(texts)]
sem = asyncio.Semaphore(4)
rows: list[dict | None] = [None] * len(jobs)
done = 0
bad_voices: set[str] = set()
async def one(job: tuple) -> None:
nonlocal done
i, text, voice, rate, pitch, noisy, s = job
async with sem:
for v in [voice] + [x for x in voices if x != voice]:
if v in bad_voices:
continue
with tempfile.NamedTemporaryFile(suffix=".mp3", dir=out, delete=False) as tf:
mp3 = Path(tf.name)
try:
await edge_tts.Communicate(text, v, rate=rate, pitch=pitch).save(str(mp3))
audio = load_audio(mp3)
if audio.size == 0:
raise RuntimeError("빈 음성")
if noisy:
audio = mix_noise(audio, random.Random(s), noise_files)
wav = out / f"synth_{i:05d}.wav"
write_wav(wav, audio)
rows[i] = {"audio": str(wav.resolve()), "text": text, "source": "synth", "voice": v,
"rate": rate, "pitch": pitch, "noise": noisy}
break
except Exception as e: # noqa: BLE001 - 목소리 하나 실패하면 다른 목소리로
log(f"TTS 실패 ({v}): {e}")
if "voice" in str(e).lower() or "No audio" in str(e):
bad_voices.add(v)
finally:
mp3.unlink(missing_ok=True)
done += 1
progress("synth", done, len(jobs))
await asyncio.gather(*(one(j) for j in jobs))
return [r for r in rows if r]
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--sentences", help="문장 파일 (한 줄에 하나)")
ap.add_argument("--dictionary", help="단어 파일 (한 줄에 하나). 템플릿 문장으로 만든다")
ap.add_argument("--count", type=int, default=200)
ap.add_argument("--out", required=True)
ap.add_argument("--noise-prob", type=float, default=0.3)
ap.add_argument("--noise-dir", help="배경 잡음 오디오 폴더 (선택)")
ap.add_argument("--voices", default=",".join(VOICES))
ap.add_argument("--seed", type=int, default=1234)
a = ap.parse_args()
read = lambda p: Path(p).read_text(encoding="utf-8").splitlines() if p else [] # noqa: E731
rng = random.Random(a.seed)
texts = build_sentences(read(a.sentences), [w.strip() for w in read(a.dictionary) if w.strip()], a.count, rng)
out = Path(a.out)
out.mkdir(parents=True, exist_ok=True)
noise_files = sorted(p for p in Path(a.noise_dir).glob("*") if p.is_file()) if a.noise_dir else []
rows = asyncio.run(synth_all(texts, out, a.noise_prob, noise_files, a.seed, a.voices.split(",")))
if not rows:
raise SystemExit("합성 음성을 하나도 만들지 못했습니다 (인터넷 연결 확인)")
n = write_jsonl(out / "manifest.jsonl", rows)
log(f"합성 {n}개 → {out / 'manifest.jsonl'}")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,141 @@
"""Whisper LoRA 학습 (peft). CUDA 면 bf16 autocast, 아니면 CPU fp32.
python train_lora.py --base openai/whisper-large-v3-turbo --train work/data/train.jsonl --out work/adapter
진행: {"event":"progress","stage":"train","step":k,"total":n,"loss":x} / 끝: {"result":{...}}
--stop-file 이 생기면 (게임 시작) 지금까지 학습한 어댑터를 저장하고 멈춘다.
"""
from __future__ import annotations
import argparse
import json
import math
import os
import random
import time
from pathlib import Path
import numpy as np
from common import emit, load_audio, log, progress, read_jsonl
MAX_SAMPLES = 30 * 16000
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--base", default="openai/whisper-large-v3-turbo")
ap.add_argument("--train", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--epochs", type=float, default=3)
ap.add_argument("--max-steps", type=int, default=0, help="0 이면 epochs 로 계산")
ap.add_argument("--batch", type=int, default=4)
ap.add_argument("--accum", type=int, default=4)
ap.add_argument("--lr", type=float, default=1e-4)
ap.add_argument("--rank", type=int, default=32)
ap.add_argument("--no-grad-ckpt", action="store_true")
ap.add_argument("--stop-file")
ap.add_argument("--seed", type=int, default=42)
a = ap.parse_args()
import torch
from peft import LoraConfig, get_peft_model
from transformers import WhisperForConditionalGeneration, WhisperProcessor
random.seed(a.seed)
torch.manual_seed(a.seed)
cuda = torch.cuda.is_available()
device = torch.device("cuda" if cuda else "cpu")
bf16 = cuda and torch.cuda.is_bf16_supported()
log(f"device={device} bf16={bf16} base={a.base}")
processor = WhisperProcessor.from_pretrained(a.base)
processor.tokenizer.set_prefix_tokens(language="korean", task="transcribe")
model = WhisperForConditionalGeneration.from_pretrained(a.base, dtype=torch.float32)
model.config.use_cache = False
model.generation_config.language = "ko"
model.generation_config.task = "transcribe"
model.generation_config.forced_decoder_ids = None
if not a.no_grad_ckpt:
model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
model = get_peft_model(model, LoraConfig(
r=a.rank, lora_alpha=a.rank * 2, lora_dropout=0.05, bias="none",
target_modules=["q_proj", "k_proj", "v_proj", "out_proj"],
))
model.print_trainable_parameters()
model.to(device)
rows = list(read_jsonl(a.train))
if not rows:
raise SystemExit("학습 데이터가 없습니다")
start_id = model.config.decoder_start_token_id
def featurize(row: dict) -> tuple[np.ndarray, list[int]]:
audio = load_audio(row["audio"])[:MAX_SAMPLES]
feats = processor.feature_extractor(audio, sampling_rate=16000, return_tensors="np").input_features[0]
labels = processor.tokenizer(row["text"]).input_ids
if labels and labels[0] == start_id: # 모델이 decoder_start 를 앞에 붙이므로 뺀다
labels = labels[1:]
return feats, labels
def batches():
while True:
order = list(range(len(rows)))
random.shuffle(order)
for i in range(0, len(order), a.batch):
items = [featurize(rows[j]) for j in order[i : i + a.batch]]
feats = torch.tensor(np.stack([f for f, _ in items]))
n = max(len(lab) for _, lab in items)
labels = torch.full((len(items), n), -100, dtype=torch.long)
for k, (_, lab) in enumerate(items):
labels[k, : len(lab)] = torch.tensor(lab)
yield feats, labels
steps_per_epoch = math.ceil(len(rows) / (a.batch * a.accum))
total = a.max_steps or max(1, int(steps_per_epoch * a.epochs))
params = [p for p in model.parameters() if p.requires_grad]
opt = torch.optim.AdamW(params, lr=a.lr, weight_decay=0.01)
warmup = max(1, total // 10)
sched = torch.optim.lr_scheduler.LambdaLR( # 선형 워밍업 → 선형 감소
opt, lambda s: (s + 1) / warmup if s < warmup else max(0.0, (total - s) / max(1, total - warmup)))
stop_file = Path(a.stop_file) if a.stop_file else None
out = Path(a.out)
out.mkdir(parents=True, exist_ok=True)
model.train()
it = batches()
step, stopped, t0, last_loss = 0, False, time.time(), float("nan")
progress("train", 0, total)
while step < total:
if stop_file and stop_file.exists():
log("중지 파일 발견 → 저장 후 종료")
stopped = True
break
opt.zero_grad(set_to_none=True)
acc_loss = 0.0
for _ in range(a.accum):
feats, labels = next(it)
feats, labels = feats.to(device), labels.to(device)
with torch.autocast("cuda", dtype=torch.bfloat16, enabled=bf16):
loss = model(input_features=feats, labels=labels).loss / a.accum
loss.backward()
acc_loss += float(loss.detach())
torch.nn.utils.clip_grad_norm_(params, 1.0)
opt.step()
sched.step()
step += 1
last_loss = acc_loss
progress("train", step, total, loss=round(acc_loss, 4), lr=sched.get_last_lr()[0])
model.save_pretrained(str(out))
processor.save_pretrained(str(out))
meta = {"base": a.base, "steps": step, "total": total, "stopped": stopped, "train_samples": len(rows),
"last_loss": None if math.isnan(last_loss) else last_loss, "seconds": round(time.time() - t0, 1),
"device": str(device), "bf16": bf16}
(out / "train_meta.json").write_text(json.dumps(meta, ensure_ascii=False, indent=1), encoding="utf-8")
emit({"result": {"adapter": str(out), **meta}})
if __name__ == "__main__":
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
main()

174
worker/gvr_worker/gpu.py Normal file
View File

@@ -0,0 +1,174 @@
"""NVIDIA GPU 감지 (NVML → nvidia-smi 순) 와 VRAM 별 모델 추천."""
from __future__ import annotations
import logging
import re
import shutil
import subprocess
from typing import Any
log = logging.getLogger(__name__)
GAME_RESERVE_MB = 3072 # 게임 프로필 기본값 (발로란트·롤 중 큰 값, 추정)
def _as_str(v: Any) -> str:
return v.decode() if isinstance(v, bytes) else str(v)
def _from_nvml() -> list[dict[str, Any]] | None:
try:
import pynvml
except ImportError:
return None
try:
pynvml.nvmlInit()
except Exception as e: # noqa: BLE001 - 드라이버 없음 등
log.info("NVML 초기화 실패: %s", e)
return None
try:
driver = _as_str(pynvml.nvmlSystemGetDriverVersion())
try:
cv = int(pynvml.nvmlSystemGetCudaDriverVersion_v2())
cuda_driver = f"{cv // 1000}.{(cv % 1000) // 10}"
except Exception: # noqa: BLE001
cuda_driver = None
gpus = []
for i in range(pynvml.nvmlDeviceGetCount()):
h = pynvml.nvmlDeviceGetHandleByIndex(i)
mem = pynvml.nvmlDeviceGetMemoryInfo(h)
try:
major, minor = pynvml.nvmlDeviceGetCudaComputeCapability(h)
cc = f"{major}.{minor}"
except Exception: # noqa: BLE001
cc = None
gpus.append(
{
"index": i,
"name": _as_str(pynvml.nvmlDeviceGetName(h)),
"vram_total_mb": int(mem.total // 1048576),
"vram_used_mb": int(mem.used // 1048576),
"driver": driver,
"cuda_driver": cuda_driver,
"compute_capability": cc,
}
)
return gpus
finally:
try:
pynvml.nvmlShutdown()
except Exception: # noqa: BLE001
pass
def _run_smi(args: list[str]) -> str | None:
exe = shutil.which("nvidia-smi")
if not exe:
return None
try:
flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
out = subprocess.run([exe, *args], capture_output=True, text=True, timeout=10, creationflags=flags)
except (OSError, subprocess.TimeoutExpired) as e:
log.info("nvidia-smi 실행 실패: %s", e)
return None
return out.stdout if out.returncode == 0 else None
def parse_smi_csv(csv_text: str, cuda_driver: str | None) -> list[dict[str, Any]]:
gpus = []
for line in csv_text.strip().splitlines():
parts = [p.strip() for p in line.split(",")]
if len(parts) < 6:
continue
try:
gpus.append(
{
"index": int(parts[0]),
"name": parts[1],
"vram_total_mb": int(float(parts[2])),
"vram_used_mb": int(float(parts[3])),
"driver": parts[4],
"cuda_driver": cuda_driver,
"compute_capability": parts[5] if parts[5] not in ("", "[N/A]") else None,
}
)
except ValueError:
continue
return gpus
def _from_smi() -> list[dict[str, Any]]:
csv_text = _run_smi(
[
"--query-gpu=index,name,memory.total,memory.used,driver_version,compute_cap",
"--format=csv,noheader,nounits",
]
)
if not csv_text:
return []
header = _run_smi([]) or ""
m = re.search(r"CUDA Version:\s*([\d.]+)", header)
return parse_smi_csv(csv_text, m.group(1) if m else None)
def gpu_list() -> list[dict[str, Any]]:
gpus = _from_nvml()
if gpus is None:
gpus = _from_smi()
return gpus
def recommend(gpus: list[dict[str, Any]], game_reserve_mb: int = GAME_RESERVE_MB) -> dict[str, Any]:
"""VRAM 표(보고서 5-2)에 따라 실시간/정밀 모델을 고른다. 임계값은 GPU 전체 VRAM 기준."""
if not gpus:
return {
"device": "cpu",
"supported": False,
"realtime": "small",
"precise": "medium",
"compute_type": "int8",
"budget_mb": 0,
"precise_after_match": True,
"reason": "NVIDIA GPU 를 찾지 못했습니다. 겜녹이는 NVIDIA GPU 만 지원하며, CPU 로는 매우 느립니다.",
}
gpu = max(gpus, key=lambda g: g["vram_total_mb"])
total_mb = int(gpu["vram_total_mb"])
total_gb = total_mb / 1024
budget_mb = max(0, (total_mb - game_reserve_mb) // 100 * 100)
shown_gb = round(total_gb)
rec: dict[str, Any] = {"device": "cuda", "supported": True, "gpu_index": gpu["index"], "budget_mb": budget_mb}
if total_gb >= 14:
rec.update(
realtime="large-v3-turbo", precise="large-v3", compute_type="float16", precise_after_match=False,
reason=f"{shown_gb}GB: 게임 3GB 예약 후 실시간(large-v3-turbo)+정밀(large-v3) 동시 적재",
)
elif total_gb >= 10:
rec.update(
realtime="large-v3", precise="large-v3", compute_type="float16", precise_after_match=True,
reason=f"{shown_gb}GB: 게임 3GB 예약 후 large-v3 하나만 여유. 정밀 변환은 경기 종료 뒤에 적재",
)
elif total_gb >= 7:
rec.update(
realtime="large-v3-turbo", precise="large-v3-turbo", compute_type="float16", precise_after_match=True,
reason=f"{shown_gb}GB: 게임 3GB 예약 후 large-v3-turbo(float16) 하나로 실시간·정밀 모두 처리",
)
elif total_gb >= 5:
rec.update(
realtime="large-v3-turbo", precise="large-v3-turbo", compute_type="int8_float16", precise_after_match=True,
reason=f"{shown_gb}GB: VRAM 이 빠듯해 large-v3-turbo 를 int8_float16 으로 적재",
)
else:
rec.update(
realtime="small", precise="medium", compute_type="float16", precise_after_match=True,
reason=f"{shown_gb}GB: VRAM 이 작아 실시간은 small, 정밀(경기 후)은 medium 사용",
)
cc = gpu.get("compute_capability") or ""
if rec["compute_type"].startswith("int8") and cc.startswith("12."):
rec["warning"] = "RTX 50 시리즈(Blackwell)에서 int8 연산이 cuBLAS 오류를 낸 사례가 있습니다. 오류 시 float16 으로 바꾸세요."
return rec
def gpu_info() -> dict[str, Any]:
gpus = gpu_list()
return {"gpus": gpus, "recommend": recommend(gpus)}

198
worker/gvr_worker/main.py Normal file
View File

@@ -0,0 +1,198 @@
"""워커 진입점: 요청 라우팅."""
from __future__ import annotations
import json
import logging
import os
import platform
import subprocess
import sys
import threading
from collections import deque
from pathlib import Path
from typing import Any
from . import __version__
from .paths import data_dir, setup_cuda_dll_path
from .protocol import Context, Server, WorkerError, Writer, require, setup_stdio
log = logging.getLogger("gvr_worker")
def build_server(writer: Writer) -> Server:
from . import gpu, models
from .stt import SttEngine
server = Server(writer)
engine = SttEngine()
ocr_state: dict[str, Any] = {"session": None}
ocr_lock = threading.Lock()
@server.route("hello")
def hello(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
return {"version": __version__, "python": platform.python_version(),
"device": "cuda" if gpu.gpu_list() else "cpu"}
@server.route("gpu_info")
def gpu_info(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
return gpu.gpu_info()
@server.route("models")
def models_op(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
res = models.list_models()
res["loaded"] = engine.status()
return res
@server.route("download", "thread")
def download(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
target = require(req, "target")
if target == "model":
return models.download_model(require(req, "name"), ctx.emit)
if target == "cuda_runtime":
return models.download_cuda_runtime(ctx.emit)
raise WorkerError("bad_request", "target 은 model 또는 cuda_runtime 이어야 합니다")
@server.route("load", "slot")
def load(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
cpu_threads = req.get("cpu_threads")
return engine.load(req["slot"], require(req, "model"), req.get("device"), req.get("compute_type"),
int(cpu_threads) if isinstance(cpu_threads, int) else 0)
@server.route("unload", "slot")
def unload(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
return engine.unload(req["slot"])
@server.route("transcribe", "slot")
def transcribe(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
return engine.transcribe(req)
@server.route("ocr_start")
def ocr_start(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
from .ocr import OcrSession
title = require(req, "window_title")
region = req.get("region") or {"x": 0, "y": 0.62, "w": 0.32, "h": 0.25}
if not all(isinstance(region.get(k), (int, float)) for k in ("x", "y", "w", "h")):
raise WorkerError("bad_request", "region 은 {x,y,w,h} 비율이어야 합니다")
with ocr_lock:
if ocr_state["session"] is not None:
ocr_state["session"].stop()
ocr_state["session"] = None
session = OcrSession(title, region, float(req.get("fps") or 3), str(req.get("lang") or "ko"),
writer.send)
session.start()
ocr_state["session"] = session
return {"started": True}
@server.route("ocr_stop")
def ocr_stop(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
with ocr_lock:
session = ocr_state["session"]
ocr_state["session"] = None
if session is not None:
session.stop()
return {"stopped": session is not None}
@server.route("ocr_image", "thread")
def ocr_image(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
from .ocr import ocr_image as run
path = require(req, "path")
if not os.path.isfile(path):
raise WorkerError("file_not_found", f"이미지 파일이 없습니다: {path}")
return run(path, str(req.get("lang") or "ko"))
@server.route("r3dlog_check")
def r3dlog_check(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
from .r3dlog import check
return check(require(req, "logs_dir"))
@server.route("r3dlog_read", "thread")
def r3dlog_read(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
from .r3dlog import read
since = req.get("since_ms")
if since is not None and not isinstance(since, (int, float)):
raise WorkerError("bad_request", "since_ms 는 숫자(Unix ms) 또는 null 이어야 합니다")
return read(require(req, "logs_dir"), since)
@server.route("train", "thread")
def train(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
return run_finetune(req, ctx)
@server.route("shutdown")
def shutdown(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
with ocr_lock:
if ocr_state["session"] is not None:
ocr_state["session"].stop()
ocr_state["session"] = None
server.stop()
return {"bye": True}
return server
def run_finetune(req: dict[str, Any], ctx: Context) -> dict[str, Any]:
"""별도 파인튜닝 파이썬 환경에서 finetune/run.py 를 돌리고 진행 이벤트를 중계한다."""
py = req.get("python") or os.environ.get("GVR_FINETUNE_PYTHON")
if not py or not os.path.isfile(py):
raise WorkerError("finetune_env_missing", "파인튜닝용 파이썬 환경이 없습니다 (python 필드 또는 GVR_FINETUNE_PYTHON)")
script = Path(__file__).parent / "finetune" / "run.py"
cmd = [py, str(script), "--data-dir", str(data_dir())]
for k, v in (req.get("args") or {}).items():
flag = "--" + str(k).replace("_", "-")
if v is True:
cmd.append(flag)
elif v not in (None, False):
cmd += [flag, str(v)]
flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8",
errors="replace", creationflags=flags, env={**os.environ, "PYTHONIOENCODING": "utf-8"})
err_tail: deque[str] = deque(maxlen=30)
def pump_stderr() -> None:
for x in proc.stderr or []:
err_tail.append(x)
sys.stderr.write(x)
t = threading.Thread(target=pump_stderr, daemon=True)
t.start()
result: dict[str, Any] | None = None
for line in proc.stdout or []:
try:
msg = json.loads(line)
except json.JSONDecodeError:
continue
if isinstance(msg, dict) and msg.get("event") == "progress":
ctx.emit("progress", **{k: v for k, v in msg.items() if k not in ("event", "id")})
elif isinstance(msg, dict) and "result" in msg:
result = msg["result"]
code = proc.wait()
t.join(timeout=2)
if code != 0 or result is None:
raise WorkerError("train_failed", f"파인튜닝 실패 (종료 코드 {code}): {''.join(err_tail)[-800:]}")
return result
def main() -> None:
logging.basicConfig(stream=sys.stderr, level=os.environ.get("GVR_LOG_LEVEL", "INFO"),
format="%(asctime)s %(levelname)s %(name)s: %(message)s")
for noisy in ("httpx", "httpx2", "huggingface_hub", "faster_whisper"):
logging.getLogger(noisy).setLevel(logging.WARNING)
setup_cuda_dll_path() # ctranslate2 import 전에
stdin, stdout = setup_stdio()
writer = Writer(stdout)
server = build_server(writer)
log.info("gvr-worker %s 시작 (python %s, data=%s)", __version__, platform.python_version(), data_dir())
try:
server.serve(stdin)
except KeyboardInterrupt:
pass
finally:
try:
stdout.flush()
finally:
# 진행 중 다운로드 스레드는 기다리지 않는다 (다음 실행에서 이어받기)
os._exit(0)

368
worker/gvr_worker/models.py Normal file
View File

@@ -0,0 +1,368 @@
"""모델 레지스트리, 모델·CUDA 런타임 다운로드 (이어받기·디스크 확인·해시 검사·진행률)."""
from __future__ import annotations
import fnmatch
import hashlib
import json
import logging
import os
import shutil
import threading
import time
import urllib.request
import zipfile
from pathlib import Path
from typing import Any, Callable
from .paths import IS_WINDOWS, cuda_dir, models_dir
from .protocol import WorkerError
log = logging.getLogger(__name__)
MB = 1048576
# 이름 → (HF 저장소, 대략 크기 MiB: 설치 전 표시용)
REGISTRY: dict[str, tuple[str, int]] = {
"large-v3-turbo": ("mobiuslabsgmbh/faster-whisper-large-v3-turbo", 1548),
"large-v3": ("Systran/faster-whisper-large-v3", 2949),
"medium": ("Systran/faster-whisper-medium", 1457),
"small": ("Systran/faster-whisper-small", 464),
"tiny": ("Systran/faster-whisper-tiny", 75),
}
MODEL_FILE_PATTERNS = ["config.json", "preprocessor_config.json", "model.bin", "tokenizer.json", "vocabulary.*"]
REQUIRED_FILES = ["config.json", "model.bin"]
PARTIAL_MARKER = ".gvr-downloading"
DOWNLOAD_META = "gvr-download.json"
CUDA_WHEELS = ["nvidia-cublas-cu12", "nvidia-cudnn-cu12"]
CUDA_META = "gvr-cuda.json"
DISK_MARGIN_MB = 300
ProgressFn = Callable[..., None]
_busy: set[str] = set()
_busy_lock = threading.Lock()
# --- 조회 --------------------------------------------------------------------
def _dir_size(path: Path) -> int:
total = 0
for root, _dirs, files in os.walk(path):
for f in files:
try:
total += os.path.getsize(os.path.join(root, f))
except OSError:
pass
return total
def is_model_dir(path: Path) -> bool:
return all((path / f).is_file() for f in REQUIRED_FILES) and not (path / PARTIAL_MARKER).exists()
def resolve_model_path(name: str) -> Path:
"""모델 이름(레지스트리·파인튜닝 모델 폴더명) 또는 절대 경로를 모델 폴더로 바꾼다."""
cand = models_dir() / name
if is_model_dir(cand):
return cand
p = Path(name)
if p.is_absolute() and is_model_dir(p):
return p
if name in REGISTRY or (models_dir() / name).exists():
raise WorkerError("model_not_installed", f"모델 '{name}' 이(가) 설치되지 않았습니다. 먼저 다운로드하세요.")
raise WorkerError("unknown_model", f"알 수 없는 모델: {name}")
def list_models() -> dict[str, Any]:
root = models_dir()
out: list[dict[str, Any]] = []
for name, (repo, approx_mb) in REGISTRY.items():
d = root / name
installed = is_model_dir(d)
out.append(
{
"name": name,
"repo": repo,
"size_mb": round(_dir_size(d) / MB) if installed else approx_mb,
"installed": installed,
"partial": (d / PARTIAL_MARKER).exists(),
"path": str(d),
}
)
# 파인튜닝 등으로 만든 추가 모델 (gvr-model.json 포함)
if root.is_dir():
for d in sorted(root.iterdir()):
if d.name in REGISTRY or not d.is_dir() or not is_model_dir(d):
continue
meta: dict[str, Any] = {}
try:
meta = json.loads((d / "gvr-model.json").read_text(encoding="utf-8"))
except (OSError, ValueError):
pass
out.append(
{"name": d.name, "repo": None, "size_mb": round(_dir_size(d) / MB), "installed": True,
"partial": False, "path": str(d), "meta": meta or None}
)
cd = cuda_dir()
cuda_installed = (cd / CUDA_META).is_file()
return {
"models": out,
"cuda_runtime": {
"installed": cuda_installed,
"required": IS_WINDOWS,
"path": str(cd),
"size_mb": round(_dir_size(cd) / MB) if cd.is_dir() else 0,
},
}
# --- 공통 -------------------------------------------------------------------
def _check_disk(path: Path, need_bytes: int) -> None:
path.mkdir(parents=True, exist_ok=True)
free = shutil.disk_usage(path).free
if free < need_bytes + DISK_MARGIN_MB * MB:
raise WorkerError(
"disk_full",
f"디스크 공간이 부족합니다. 필요 {need_bytes / MB / 1024:.1f}GB, 남은 공간 {free / MB / 1024:.1f}GB ({path})",
)
def _sha256(path: Path) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(8 * MB), b""):
h.update(chunk)
return h.hexdigest()
class ProgressReporter:
"""완료 바이트를 받아 progress 이벤트를 초당 약 2회로 줄여 보낸다."""
def __init__(self, emit: ProgressFn, total_bytes: int, interval: float = 0.5) -> None:
self.emit = emit
self.total = total_bytes
self.interval = interval
self._start = time.monotonic()
self._last = 0.0
self._base: int | None = None
def update(self, done_bytes: int, force: bool = False, **extra: Any) -> None:
now = time.monotonic()
if not force and now - self._last < self.interval:
return
self._last = now
if self._base is None: # 이어받기: 이미 있던 양은 속도 계산에서 뺀다
self._base = done_bytes
elapsed = max(now - self._start, 1e-3)
speed = max(done_bytes - self._base, 0) / elapsed / MB
remain = max(self.total - done_bytes, 0) / MB
self.emit(
"progress",
done_mb=round(done_bytes / MB, 1),
total_mb=round(self.total / MB, 1),
speed_mbps=round(speed, 2),
eta_s=int(remain / speed) if speed > 0.01 else None,
**extra,
)
def _claim(key: str) -> None:
with _busy_lock:
if key in _busy:
raise WorkerError("busy", f"이미 다운로드 중입니다: {key}")
_busy.add(key)
def _release(key: str) -> None:
with _busy_lock:
_busy.discard(key)
# --- 모델 다운로드 ------------------------------------------------------------
def download_model(name: str, emit: ProgressFn) -> dict[str, Any]:
if name not in REGISTRY:
raise WorkerError("unknown_model", f"알 수 없는 모델: {name}")
repo = REGISTRY[name][0]
target = models_dir() / name
if is_model_dir(target):
return {"path": str(target), "already": True}
_claim(f"model:{name}")
try:
return _download_model(repo, target, emit)
finally:
_release(f"model:{name}")
def _download_model(repo: str, target: Path, emit: ProgressFn) -> dict[str, Any]:
from huggingface_hub import HfApi, hf_hub_download
try:
info = HfApi().model_info(repo, files_metadata=True)
except Exception as e: # noqa: BLE001 - 네트워크 오류 등
raise WorkerError("network", f"모델 정보를 가져오지 못했습니다 ({repo}): {e}") from e
files = [
s for s in (info.siblings or [])
if any(fnmatch.fnmatch(s.rfilename, p) for p in MODEL_FILE_PATTERNS)
]
if not any(s.rfilename == "model.bin" for s in files):
raise WorkerError("bad_repo", f"{repo} 에 model.bin 이 없습니다")
total = sum(int(s.size or 0) for s in files)
target.mkdir(parents=True, exist_ok=True)
(target / PARTIAL_MARKER).write_text(repo, encoding="utf-8")
_check_disk(target, max(total - _dir_size(target), 0))
reporter = ProgressReporter(emit, total)
stop = threading.Event()
def poll() -> None: # 디스크에 쌓인 바이트로 진행률 계산 (.incomplete 포함)
while not stop.wait(0.5):
reporter.update(min(_dir_size(target), total))
poller = threading.Thread(target=poll, daemon=True)
poller.start()
try:
for s in files:
for attempt in range(3):
try:
hf_hub_download(repo, s.rfilename, revision=info.sha, local_dir=str(target))
break
except Exception as e: # noqa: BLE001
if attempt == 2:
raise WorkerError("network", f"다운로드 실패 ({s.rfilename}): {e}") from e
log.warning("다운로드 재시도 %s: %s", s.rfilename, e)
time.sleep(2 * (attempt + 1))
finally:
stop.set()
poller.join(timeout=2)
# 검증: 크기, LFS sha256
reporter.update(total, force=True, stage="verify")
for s in files:
p = target / s.rfilename
if s.size is not None and p.stat().st_size != s.size:
p.unlink(missing_ok=True)
raise WorkerError("verify_failed", f"파일 크기가 맞지 않습니다: {s.rfilename}. 다시 다운로드하세요.")
lfs = getattr(s, "lfs", None)
sha = getattr(lfs, "sha256", None) if lfs is not None else None
if sha and _sha256(p) != sha:
p.unlink(missing_ok=True)
raise WorkerError("verify_failed", f"해시가 맞지 않습니다: {s.rfilename}. 다시 다운로드하세요.")
shutil.rmtree(target / ".cache", ignore_errors=True)
(target / DOWNLOAD_META).write_text(
json.dumps({"repo": repo, "revision": info.sha, "files": [s.rfilename for s in files],
"created": int(time.time())}, ensure_ascii=False),
encoding="utf-8",
)
(target / PARTIAL_MARKER).unlink(missing_ok=True)
return {"path": str(target)}
# --- CUDA 런타임 (Windows) -----------------------------------------------------
def pypi_win_wheel(meta: dict[str, Any]) -> dict[str, Any]:
"""PyPI JSON 에서 win_amd64 휠 정보를 고른다."""
for f in meta.get("urls", []):
if f.get("packagetype") == "bdist_wheel" and f["filename"].endswith("win_amd64.whl"):
return {"version": meta["info"]["version"], "filename": f["filename"], "url": f["url"],
"size": int(f["size"]), "sha256": f["digests"]["sha256"]}
raise WorkerError("no_wheel", f"{meta.get('info', {}).get('name')} 의 Windows 휠을 찾지 못했습니다")
def _fetch_json(url: str) -> dict[str, Any]:
with urllib.request.urlopen(url, timeout=30) as r:
return json.loads(r.read().decode("utf-8"))
def extract_dlls(wheel: Path, dest: Path) -> list[str]:
"""휠(zip) 안의 */bin/*.dll 만 dest 로 푼다."""
names = []
dest.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(wheel) as z:
for m in z.infolist():
parts = m.filename.split("/")
if len(parts) >= 2 and parts[-2] == "bin" and parts[-1].lower().endswith(".dll"):
with z.open(m) as src, open(dest / parts[-1], "wb") as dst:
shutil.copyfileobj(src, dst, 4 * MB)
names.append(parts[-1])
return names
def _stream_download(url: str, part: Path, size: int, on_bytes: Callable[[int], None]) -> None:
"""Range 로 이어받는 스트리밍 다운로드."""
have = part.stat().st_size if part.exists() else 0
if have > size:
part.unlink()
have = 0
if have == size:
return
req = urllib.request.Request(url, headers={"Range": f"bytes={have}-"} if have else {})
with urllib.request.urlopen(req, timeout=60) as r:
if have and r.status != 206: # 서버가 Range 를 무시하면 처음부터
have = 0
with open(part, "ab" if have else "wb") as f:
while True:
chunk = r.read(1 * MB)
if not chunk:
break
f.write(chunk)
on_bytes(len(chunk))
def download_cuda_runtime(emit: ProgressFn) -> dict[str, Any]:
dest = cuda_dir()
if not IS_WINDOWS:
return {"path": str(dest), "skipped": True,
"note": "Windows 전용입니다. 리눅스는 시스템 CUDA 나 pip 의 nvidia-* 패키지를 쓰세요."}
if (dest / CUDA_META).is_file():
return {"path": str(dest), "already": True}
_claim("cuda_runtime")
try:
try:
metas = [_fetch_json(f"https://pypi.org/pypi/{p}/json") for p in CUDA_WHEELS]
except Exception as e: # noqa: BLE001
raise WorkerError("network", f"PyPI 에서 CUDA 런타임 정보를 가져오지 못했습니다: {e}") from e
wheels = [pypi_win_wheel(m) for m in metas]
total = sum(w["size"] for w in wheels)
tmp = dest / ".download"
tmp.mkdir(parents=True, exist_ok=True)
have = sum((tmp / (w["filename"] + ".part")).stat().st_size
for w in wheels if (tmp / (w["filename"] + ".part")).exists())
_check_disk(dest, (total - have) + int(total * 2.5)) # 휠 + 압축 해제된 DLL
reporter = ProgressReporter(emit, total)
done = [have]
def on_bytes(n: int) -> None:
done[0] += n
reporter.update(done[0])
dlls: list[str] = []
for w in wheels:
part = tmp / (w["filename"] + ".part")
for attempt in range(3):
try:
_stream_download(w["url"], part, w["size"], on_bytes)
break
except OSError as e:
if attempt == 2:
raise WorkerError("network", f"다운로드 실패 ({w['filename']}): {e}") from e
done[0] = sum((tmp / (x["filename"] + ".part")).stat().st_size
for x in wheels if (tmp / (x["filename"] + ".part")).exists())
time.sleep(2 * (attempt + 1))
reporter.update(done[0], force=True, stage="verify")
if _sha256(part) != w["sha256"]:
part.unlink(missing_ok=True)
raise WorkerError("verify_failed", f"해시가 맞지 않습니다: {w['filename']}. 다시 다운로드하세요.")
reporter.update(done[0], force=True, stage="extract")
dlls += extract_dlls(part, dest)
part.unlink(missing_ok=True)
shutil.rmtree(tmp, ignore_errors=True)
(dest / CUDA_META).write_text(
json.dumps({"wheels": [{k: w[k] for k in ("filename", "version", "sha256")} for w in wheels],
"dlls": dlls, "created": int(time.time())}, ensure_ascii=False),
encoding="utf-8",
)
return {"path": str(dest), "dlls": dlls, "restart_required": True}
finally:
_release("cuda_runtime")

193
worker/gvr_worker/noise.py Normal file
View File

@@ -0,0 +1,193 @@
"""잡음 판정 4단계 (보고서 4-3): ① VAD → ② no_speech → ③ 환각 문구 → ④ 반복.
noise_sensitivity(0~1) 가 클수록 기준이 엄격해져 잡음으로 쉽게 판정된다.
"""
from __future__ import annotations
import re
import zlib
from collections import Counter
from dataclasses import dataclass
from typing import Iterable
# 한국어 Whisper 가 무음·키보드·숨소리에서 자주 지어내는 문장 (공백·문장부호 제거 후 비교)
HALLUCINATION_PHRASES: list[str] = [
"시청해주셔서감사합니다",
"시청해주셔서고맙습니다",
"시청해주신여러분감사합니다",
"봐주셔서감사합니다",
"영상봐주셔서감사합니다",
"끝까지시청해주셔서감사합니다",
"구독과좋아요",
"구독좋아요",
"구독과좋아요부탁드립니다",
"구독좋아요알림설정",
"좋아요와구독",
"알림설정까지",
"구독버튼",
"채널에가입",
"다음영상에서만나요",
"다음영상에서뵙겠습니다",
"다음시간에만나요",
"다음에또만나요",
"오늘도시청해주셔서",
"mbc뉴스",
"kbs뉴스",
"sbs뉴스",
"jtbc뉴스",
"ytn뉴스",
"mbn뉴스",
"뉴스데스크",
"뉴스는여기까지",
"이덕영입니다",
"기자입니다",
"자막제공",
"자막제공배달의민족",
"자막제공및광고",
"자막제작",
"자막by",
"한글자막",
"번역자막",
"자막은설정에서",
"제작지원",
"후원해주신",
"광고를포함하고",
"유료광고",
"여러분안녕하세요",
"이영상은",
"amaraorg",
"벨소리",
]
# 짧고 신뢰도 낮은 발화에서만 환각으로 보는 문장 (실제로도 자주 말하는 표현이라 조건부)
WEAK_PHRASES: list[str] = [
"감사합니다",
"고맙습니다",
"수고하셨습니다",
"안녕하세요",
"안녕히계세요",
"네감사합니다",
"감사합니다감사합니다",
"잘먹겠습니다",
"잘먹었습니다",
"아멘",
"음악",
"박수",
"웃음",
]
_NORM_RE = re.compile(r"[\s\W_]+", re.UNICODE)
_LAUGH_RE = re.compile(r"^[ㅋㅎㅠㅜㄷ]{3,}$")
_BRACKET_RE = re.compile(r"^[\[((♪].*[\]))♪]$")
def normalize(text: str) -> str:
return _NORM_RE.sub("", text).lower()
@dataclass
class SegInfo:
no_speech_prob: float
avg_logprob: float
compression_ratio: float
@dataclass
class Thresholds:
vad_ratio: float
vad_min_speech_s: float
no_speech_prob: float
logprob: float
weak_conf: float
weak_max_s: float
repeat_runs: int
token_dominance: float
compression: float
def thresholds(sensitivity: float) -> Thresholds:
s = min(max(float(sensitivity), 0.0), 1.0)
return Thresholds(
vad_ratio=0.03 + 0.17 * s, # 0.5 → 0.115
vad_min_speech_s=0.08 + 0.14 * s, # 0.5 → 0.15s
no_speech_prob=0.85 - 0.3 * s, # 0.5 → 0.70
logprob=-1.3 + 0.6 * s, # 0.5 → -1.0
weak_conf=0.3 + 0.4 * s, # 0.5 → 0.5
weak_max_s=1.5 + 1.5 * s, # 0.5 → 2.25s
repeat_runs=max(2, round(6 - 4 * s)), # 0.5 → 4번 반복(=5회 등장)
token_dominance=0.75 - 0.3 * s, # 0.5 → 0.6
compression=2.8 - 0.8 * s, # 0.5 → 2.4
)
def judge_vad(speech_ratio: float, speech_s: float, sensitivity: float) -> bool:
t = thresholds(sensitivity)
return speech_ratio < t.vad_ratio or speech_s < t.vad_min_speech_s
def judge_no_speech(segs: list[SegInfo], text: str, sensitivity: float) -> bool:
if not segs or not normalize(text):
return True
t = thresholds(sensitivity)
return all(s.no_speech_prob > t.no_speech_prob and s.avg_logprob < t.logprob for s in segs)
def _covered(norm: str, phrases: Iterable[str]) -> int:
covered = 0
rest = norm
for p in sorted(phrases, key=len, reverse=True):
if p in rest:
covered += len(p) * rest.count(p)
rest = rest.replace(p, "")
return covered
def judge_hallucination(text: str, confidence: float, duration_s: float, sensitivity: float) -> bool:
raw = text.strip()
norm = normalize(raw)
if not norm:
return False
if _LAUGH_RE.match(norm) or _BRACKET_RE.match(raw):
return True
t = thresholds(sensitivity)
# 강한 문구: 문장 대부분(50% 이상)을 차지하면 환각
if _covered(norm, HALLUCINATION_PHRASES) >= 0.5 * len(norm):
return True
# 약한 문구: 짧고 신뢰도 낮을 때 문장 전체가 그 문구면 환각
if norm in WEAK_PHRASES and duration_s <= t.weak_max_s and confidence < t.weak_conf:
return True
return False
def judge_repetition(text: str, segs: list[SegInfo], sensitivity: float) -> bool:
norm = normalize(text)
if len(norm) < 6:
return False
t = thresholds(sensitivity)
# 같은 1~10자 덩어리가 연속으로 repeat_runs 번 이상 더 반복
if re.search(r"(.{1,10}?)\1{%d,}" % t.repeat_runs, norm):
return True
tokens = [normalize(w) for w in text.split() if normalize(w)]
if len(tokens) >= 5:
_, n = Counter(tokens).most_common(1)[0]
if n / len(tokens) >= t.token_dominance:
return True
if len(norm) >= 20:
b = norm.encode("utf-8")
if len(b) / len(zlib.compress(b)) > t.compression:
return True
return any(s.compression_ratio > t.compression + 0.4 for s in segs) and len(norm) >= 12
def judge_text(
text: str, segs: list[SegInfo], confidence: float, duration_s: float, sensitivity: float
) -> str | None:
"""②~④ 단계. 잡음이면 사유 문자열, 아니면 None."""
if judge_no_speech(segs, text, sensitivity):
return "no_speech"
if judge_hallucination(text, confidence, duration_s, sensitivity):
return "hallucination"
if judge_repetition(text, segs, sensitivity):
return "repetition"
return None

307
worker/gvr_worker/ocr.py Normal file
View File

@@ -0,0 +1,307 @@
"""롤 인게임 채팅 화면 OCR (Windows 전용 캡처/OCR, 줄 파싱은 플랫폼 무관).
- 창 찾기: user32 EnumWindows/GetWindowTextW → GetClientRect/ClientToScreen
- 캡처: mss (테두리 없는 창/창 모드에서 동작. '전체 화면(독점)'은 검은 화면이 잡힐 수 있어
게임 설정에서 '테두리 없음' 을 권장)
- 채팅 영역이 바뀐 프레임에서만 Windows.Media.Ocr(ko) 실행
- 같은 (보낸 사람, 내용, 게임 시각) 줄은 한 번만 보낸다
"""
from __future__ import annotations
import asyncio
import logging
import re
import threading
import time
from collections import deque
from typing import Any, Callable
import numpy as np
from .paths import IS_WINDOWS
from .protocol import WorkerError
log = logging.getLogger(__name__)
LANG_MISSING_MSG = (
"Windows 한국어 OCR 이 설치되어 있지 않습니다. 설정 > 시간 및 언어 > 언어 및 지역 > 한국어 > 언어 옵션 > "
"'광학 문자 인식(OCR)' 을 설치하거나, 관리자 PowerShell 에서 "
"Add-WindowsCapability -Online -Name \"Language.OCR~~~ko-KR~0.0.1.0\" 을 실행하세요."
)
# --- 채팅 줄 파싱 --------------------------------------------------------------
CHANNELS = {
"팀": "team", "team": "team", "아군": "team",
"전체": "all", "all": "all", "모두": "all",
"파티": "party", "party": "party",
}
_TIME = r"\[?\s*(?P<time>\d{1,2}\s*:\s*\d{2}(?:\s*:\s*\d{2})?)\s*\]"
_CHAN = r"\[\s*(?P<chan>팀|전체|파티|아군|모두|[Tt]eam|[Aa]ll|[Pp]arty)\s*\]"
LINE_RE = re.compile(
rf"^\s*(?:{_TIME}\s*)?(?:{_CHAN}\s*)?"
r"(?P<sender>[^\[\]()::]{1,32}?)\s*(?:\(\s*(?P<champ>[^()]{1,24}?)\s*\))?\s*[::](?!\d)\s*(?P<msg>.+?)\s*$"
)
SYSTEM_RE = re.compile(rf"^\s*(?:{_TIME}\s*)?(?P<msg>.+?)\s*$")
def _norm_time(t: str | None) -> str | None:
return re.sub(r"\s+", "", t) if t else None
def time_to_seconds(t: str | None) -> float | None:
""""12:34" → 754.0, "1:02:03" → 3723.0."""
if not t:
return None
try:
parts = [int(x) for x in t.split(":")]
except ValueError:
return None
sec = 0
for x in parts:
sec = sec * 60 + x
return float(sec)
def seconds_to_time(sec: float) -> str:
s = int(sec)
h, m, s = s // 3600, (s % 3600) // 60, s % 60
return f"{h}:{m:02d}:{s:02d}" if h else f"{m:02d}:{s:02d}"
def parse_chat_line(text: str) -> dict[str, Any] | None:
"""롤 채팅 한 줄 → {game_time, game_time_s, channel, sender, champion, message}. 빈 줄은 None."""
line = text.replace("​", "").strip()
if not line:
return None
m = LINE_RE.match(line)
if m and m.group("msg") and m.group("sender").strip():
chan = m.group("chan")
gt = _norm_time(m.group("time"))
return {
"game_time": gt,
"game_time_s": time_to_seconds(gt),
"channel": CHANNELS[chan.lower()] if chan else "team",
"sender": m.group("sender").strip(),
"champion": m.group("champ").strip() if m.group("champ") else None,
"message": m.group("msg"),
}
s = SYSTEM_RE.match(line)
gt = _norm_time(s.group("time")) if s else None
return {
"game_time": gt,
"game_time_s": time_to_seconds(gt),
"channel": "system",
"sender": None,
"champion": None,
"message": s.group("msg") if s else line,
}
class Deduper:
"""최근 본 (보낸 사람, 내용, 게임 시각) 키를 기억해 같은 줄을 한 번만 통과시킨다."""
def __init__(self, size: int = 500) -> None:
self._q: deque[tuple[Any, ...]] = deque()
self._set: set[tuple[Any, ...]] = set()
self._size = size
def first_time(self, parsed: dict[str, Any]) -> bool:
key = (parsed.get("sender"), re.sub(r"\s+", "", parsed.get("message") or ""), parsed.get("game_time"))
if key in self._set:
return False
self._set.add(key)
self._q.append(key)
if len(self._q) > self._size:
self._set.discard(self._q.popleft())
return True
def frame_changed(prev: np.ndarray | None, cur: np.ndarray, threshold: float = 2.0) -> bool:
"""축소한 회색조 프레임의 평균 절대 차이로 변화 판단."""
if prev is None or prev.shape != cur.shape:
return True
return float(np.mean(np.abs(prev.astype(np.int16) - cur.astype(np.int16)))) > threshold
def _thumb(bgra: np.ndarray) -> np.ndarray:
gray = bgra[..., :3].mean(axis=2)
return gray[::4, ::4].astype(np.uint8)
# --- Windows 창 · OCR ---------------------------------------------------------
def find_window_client_rect(title: str) -> tuple[int, int, int, int] | None:
"""창 제목(완전 일치 우선, 없으면 포함)으로 찾아 클라이언트 영역의 화면 좌표 (x, y, w, h)."""
if not IS_WINDOWS:
return None
import ctypes
from ctypes import wintypes
user32 = ctypes.windll.user32 # type: ignore[attr-defined]
found: list[tuple[int, str]] = []
@ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
def cb(hwnd: int, _lp: int) -> bool:
if user32.IsWindowVisible(hwnd) and not user32.IsIconic(hwnd):
n = user32.GetWindowTextLengthW(hwnd)
if n:
buf = ctypes.create_unicode_buffer(n + 1)
user32.GetWindowTextW(hwnd, buf, n + 1)
if title in buf.value:
found.append((hwnd, buf.value))
return True
user32.EnumWindows(cb, 0)
if not found:
return None
hwnd = next((h for h, t in found if t == title), found[0][0])
rect = wintypes.RECT()
if not user32.GetClientRect(hwnd, ctypes.byref(rect)):
return None
pt = wintypes.POINT(0, 0)
user32.ClientToScreen(hwnd, ctypes.byref(pt))
w, h = rect.right - rect.left, rect.bottom - rect.top
return (pt.x, pt.y, w, h) if w > 0 and h > 0 else None
def _set_dpi_aware() -> None:
if not IS_WINDOWS:
return
import ctypes
try:
ctypes.windll.user32.SetProcessDpiAwarenessContext(ctypes.c_void_p(-4)) # type: ignore[attr-defined]
except Exception: # noqa: BLE001
try:
ctypes.windll.shcore.SetProcessDpiAwareness(2) # type: ignore[attr-defined]
except Exception: # noqa: BLE001
pass
class WinOcr:
"""Windows.Media.Ocr 래퍼 (pywinrt)."""
def __init__(self, lang: str = "ko") -> None:
if not IS_WINDOWS:
raise WorkerError("ocr_unavailable", "화면 OCR 은 Windows 에서만 지원합니다")
try:
from winrt.windows.globalization import Language
from winrt.windows.graphics.imaging import BitmapPixelFormat, SoftwareBitmap
from winrt.windows.media.ocr import OcrEngine
from winrt.windows.storage.streams import DataWriter
except ImportError as e:
raise WorkerError("ocr_unavailable", f"Windows OCR 모듈(pywinrt)을 불러오지 못했습니다: {e}") from e
self._SoftwareBitmap = SoftwareBitmap
self._fmt = BitmapPixelFormat.BGRA8
self._DataWriter = DataWriter
language = Language(lang)
if not OcrEngine.is_language_supported(language):
raise WorkerError("ocr_lang_missing", LANG_MISSING_MSG)
engine = OcrEngine.try_create_from_language(language)
if engine is None:
raise WorkerError("ocr_lang_missing", LANG_MISSING_MSG)
self._engine = engine
self._loop = asyncio.new_event_loop()
def recognize(self, bgra: np.ndarray) -> list[str]:
h, w = bgra.shape[:2]
writer = self._DataWriter()
writer.write_bytes(np.ascontiguousarray(bgra, dtype=np.uint8).tobytes())
bitmap = self._SoftwareBitmap.create_copy_from_buffer(writer.detach_buffer(), self._fmt, w, h)
result = self._loop.run_until_complete(self._engine.recognize_async(bitmap))
return [line.text for line in result.lines]
def close(self) -> None:
self._loop.close()
OCR_MAX_DIM = 2600 # Windows.Media.Ocr 의 OcrEngine.MaxImageDimension 기본값
def _upscale(bgra: np.ndarray, factor: int = 2) -> np.ndarray:
"""작은 채팅 글씨 인식률을 높이려고 정수배 확대 (OCR 최대 크기를 넘지 않을 때만)."""
if max(bgra.shape[:2]) * factor > OCR_MAX_DIM:
return bgra
return np.repeat(np.repeat(bgra, factor, axis=0), factor, axis=1)
def load_image_bgra(path: str) -> np.ndarray:
from PIL import Image
with Image.open(path) as im:
rgba = np.asarray(im.convert("RGBA"))
return rgba[..., [2, 1, 0, 3]].copy()
def ocr_image(path: str, lang: str = "ko") -> dict[str, Any]:
eng = WinOcr(lang)
try:
img = load_image_bgra(path)
if img.shape[0] < 400:
img = _upscale(img)
lines = [ln for ln in eng.recognize(img) if ln.strip()]
finally:
eng.close()
return {"lines": [{"text": ln, "parsed": parse_chat_line(ln)} for ln in lines]}
# --- 백그라운드 캡처 루프 ------------------------------------------------------
class OcrSession:
def __init__(self, window_title: str, region: dict[str, float], fps: float, lang: str,
send: Callable[[dict[str, Any]], None]) -> None:
self.window_title = window_title
self.region = region
self.interval = 1.0 / min(max(float(fps), 0.5), 10.0)
self.send = send
self._stop = threading.Event()
_set_dpi_aware()
self.engine = WinOcr(lang) # 언어 미설치 등은 시작 시점에 오류로 돌려준다
self.thread = threading.Thread(target=self._run, name="gvr-ocr", daemon=True)
def start(self) -> None:
self.thread.start()
def stop(self) -> None:
self._stop.set()
self.thread.join(timeout=3)
def _status(self, state: str, last: list[str]) -> None:
if last[0] != state:
last[0] = state
self.send({"event": "ocr_status", "state": state})
def _run(self) -> None:
import mss
dedupe = Deduper()
prev: np.ndarray | None = None
last_state = [""]
try:
with mss.mss() as sct:
while not self._stop.is_set():
t0 = time.monotonic()
try:
rect = find_window_client_rect(self.window_title)
if rect is None:
self._status("window_not_found", last_state)
else:
self._status("capturing", last_state)
x, y, w, h = rect
r = self.region
box = {"left": x + int(r["x"] * w), "top": y + int(r["y"] * h),
"width": max(1, int(r["w"] * w)), "height": max(1, int(r["h"] * h))}
img = np.asarray(sct.grab(box)) # BGRA
thumb = _thumb(img)
if frame_changed(prev, thumb):
prev = thumb
for text in self.engine.recognize(_upscale(img)):
parsed = parse_chat_line(text)
if parsed and dedupe.first_time(parsed):
self.send({"event": "ocr_line", "ts": int(time.time() * 1000),
"text": text, "parsed": parsed})
except Exception as e: # noqa: BLE001 - 한 프레임 실패로 루프를 멈추지 않는다
log.warning("OCR 프레임 실패: %s", e)
self._status("error", last_state)
self._stop.wait(max(0.0, self.interval - (time.monotonic() - t0)))
finally:
self.engine.close()

View File

@@ -0,0 +1,47 @@
"""데이터 폴더 경로와 Windows CUDA DLL 경로 설정."""
from __future__ import annotations
import logging
import os
import sys
from pathlib import Path
log = logging.getLogger(__name__)
IS_WINDOWS = sys.platform == "win32"
def data_dir() -> Path:
"""GVR_DATA_DIR. 없으면 실행 파일(또는 작업 폴더) 옆 GVR-Data."""
env = os.environ.get("GVR_DATA_DIR")
if env:
return Path(env)
base = Path(sys.executable).parent if getattr(sys, "frozen", False) else Path.cwd()
return base / "GVR-Data"
def models_dir() -> Path:
env = os.environ.get("GVR_MODELS_DIR")
return Path(env) if env else data_dir() / "models"
def cuda_dir() -> Path:
return data_dir() / "cuda"
_dll_handles: list[object] = []
def setup_cuda_dll_path() -> None:
"""Windows: 내려받은 cuBLAS/cuDNN DLL 폴더를 ctranslate2 import 전에 검색 경로에 넣는다."""
if not IS_WINDOWS:
return
d = cuda_dir()
if not d.is_dir():
return
try:
_dll_handles.append(os.add_dll_directory(str(d))) # type: ignore[attr-defined]
except OSError as e: # pragma: no cover - Windows 전용
log.warning("add_dll_directory 실패: %s", e)
os.environ["PATH"] = str(d) + os.pathsep + os.environ.get("PATH", "")

View File

@@ -0,0 +1,181 @@
"""JSON Lines 프로토콜: stdin 요청 읽기, stdout 응답/이벤트 쓰기, 요청 디스패치.
- stdout 에는 프로토콜 메시지만 쓴다 (UTF-8, 한 줄 = JSON 하나). 로그는 stderr.
- 요청 처리 방식(mode):
- "inline": 읽기 루프에서 바로 처리 (빠른 요청)
- "slot": 슬롯(realtime/precise)별 단일 스레드 큐. 같은 슬롯의 load/unload/transcribe 는
순서대로, 다른 슬롯끼리는 동시에 돈다.
- "thread": 별도 스레드 (download, train 처럼 오래 걸리고 진행 이벤트를 내는 요청)
- 잘못된 요청은 루프를 죽이지 않고 오류 응답으로 돌려준다.
"""
from __future__ import annotations
import json
import logging
import sys
import threading
import traceback
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from typing import Any, Callable, Literal, TextIO
log = logging.getLogger(__name__)
Mode = Literal["inline", "slot", "thread"]
Handler = Callable[[dict[str, Any], "Context"], Any]
class WorkerError(Exception):
"""요청 단위 오류. {"ok":false,"error":{"code","message"}} 로 응답된다."""
def __init__(self, code: str, message: str) -> None:
super().__init__(message)
self.code = code
self.message = message
class Writer:
"""스레드 안전한 stdout JSON Lines 쓰기."""
def __init__(self, stream: TextIO) -> None:
self._stream = stream
self._lock = threading.Lock()
def send(self, obj: dict[str, Any]) -> None:
line = json.dumps(obj, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
with self._lock:
self._stream.write(line + "\n")
self._stream.flush()
@dataclass
class Context:
"""핸들러에 넘기는 요청 컨텍스트. emit() 으로 진행 이벤트를 보낸다."""
req_id: Any
writer: Writer
def emit(self, event: str, **fields: Any) -> None:
msg: dict[str, Any] = {"event": event}
if self.req_id is not None:
msg["id"] = self.req_id
msg.update(fields)
self.writer.send(msg)
@dataclass
class Route:
handler: Handler
mode: Mode
class Server:
def __init__(self, writer: Writer) -> None:
self.writer = writer
self.routes: dict[str, Route] = {}
self._slot_pools: dict[str, ThreadPoolExecutor] = {}
self._pool = ThreadPoolExecutor(max_workers=4, thread_name_prefix="gvr-job")
self._stopping = threading.Event()
def route(self, op: str, mode: Mode = "inline") -> Callable[[Handler], Handler]:
def deco(fn: Handler) -> Handler:
self.routes[op] = Route(fn, mode)
return fn
return deco
# --- 응답 ---------------------------------------------------------------
def _reply_ok(self, req_id: Any, result: Any) -> None:
self.writer.send({"id": req_id, "ok": True, "result": result if result is not None else {}})
def _reply_err(self, req_id: Any, code: str, message: str) -> None:
self.writer.send({"id": req_id, "ok": False, "error": {"code": code, "message": message}})
def _run(self, route: Route, req: dict[str, Any]) -> None:
req_id = req.get("id")
try:
result = route.handler(req, Context(req_id, self.writer))
self._reply_ok(req_id, result)
except WorkerError as e:
self._reply_err(req_id, e.code, e.message)
except Exception as e: # noqa: BLE001 - 경계에서 모든 예외를 오류 응답으로
log.error("op=%s 처리 중 예외\n%s", req.get("op"), traceback.format_exc())
self._reply_err(req_id, "internal", f"{type(e).__name__}: {e}")
def _slot_pool(self, slot: str) -> ThreadPoolExecutor:
pool = self._slot_pools.get(slot)
if pool is None:
pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix=f"gvr-slot-{slot}")
self._slot_pools[slot] = pool
return pool
# --- 디스패치 -------------------------------------------------------------
def handle_line(self, line: str) -> None:
line = line.strip()
if not line:
return
try:
req = json.loads(line)
except json.JSONDecodeError as e:
self._reply_err(None, "bad_json", f"JSON 파싱 실패: {e}")
return
if not isinstance(req, dict):
self._reply_err(None, "bad_request", "요청은 JSON 객체여야 합니다")
return
req_id = req.get("id")
op = req.get("op")
route = self.routes.get(op) if isinstance(op, str) else None
if route is None:
self._reply_err(req_id, "unknown_op", f"알 수 없는 op: {op!r}")
return
if route.mode == "inline":
self._run(route, req)
elif route.mode == "slot":
slot = req.get("slot")
if slot not in ("realtime", "precise"):
self._reply_err(req_id, "bad_request", "slot 은 realtime 또는 precise 여야 합니다")
return
self._slot_pool(slot).submit(self._run, route, req)
else:
self._pool.submit(self._run, route, req)
def stop(self) -> None:
self._stopping.set()
@property
def stopping(self) -> bool:
return self._stopping.is_set()
def serve(self, stdin: TextIO) -> None:
for line in stdin:
try:
self.handle_line(line)
except Exception: # noqa: BLE001 - 루프는 절대 죽지 않는다
log.error("요청 처리 루프 예외\n%s", traceback.format_exc())
if self._stopping.is_set():
break
self.shutdown_pools()
def shutdown_pools(self) -> None:
for pool in self._slot_pools.values():
pool.shutdown(wait=True, cancel_futures=True)
self._pool.shutdown(wait=False, cancel_futures=True)
def setup_stdio() -> tuple[TextIO, TextIO]:
"""stdin/stdout 을 UTF-8 로 고정한다 (Windows 기본 코드페이지 회피)."""
for s in (sys.stdin, sys.stdout, sys.stderr):
try:
kw = {"newline": "\n"} if s is sys.stdout else {} # Windows 에서도 \r\n 이 아닌 \n
s.reconfigure(encoding="utf-8", errors="replace", line_buffering=True, **kw) # type: ignore[union-attr]
except (AttributeError, ValueError):
pass
return sys.stdin, sys.stdout
def require(req: dict[str, Any], key: str, typ: type | tuple[type, ...] = str) -> Any:
val = req.get(key)
if val is None or not isinstance(val, typ) or (isinstance(val, str) and not val):
raise WorkerError("bad_request", f"'{key}' 필드가 필요합니다")
return val

105
worker/gvr_worker/r3dlog.py Normal file
View File

@@ -0,0 +1,105 @@
"""롤 게임 로그(*_r3dlog.txt)에서 채팅 줄 찾기.
2024년 12월 패치 전에는 `[팀] 이름 (챔피언): 내용` 형태 채팅이 r3dlog 에 남았다. 줄 앞에는
`000754.123| ALWAYS| ` 같은 경과 초 접두어가 붙을 수 있고, 있으면 game_time_s 로 쓴다.
지금 게임 PC 로그에 남는지는 r3dlog_check 로 확인한다.
"""
from __future__ import annotations
import re
import threading
from pathlib import Path
from typing import Any, Iterator
from .ocr import CHANNELS, seconds_to_time, time_to_seconds
CHAT_RE = re.compile(
r"(?:\[\s*(?P<time>\d{1,2}:\d{2}(?::\d{2})?)\s*\]\s*)?"
r"\[\s*(?P<chan>팀|전체|파티|아군|모두|[Tt]eam|[Aa]ll|[Pp]arty)\s*\]\s*"
r"(?P<sender>[^\[\]():|]{1,32}?)\s*(?:\(\s*(?P<champ>[^()]{1,24}?)\s*\))?\s*:\s*(?P<msg>.+?)\s*$"
)
LOG_TIME_RE = re.compile(r"^\s*(?P<t>\d+\.\d+)\s*\|")
def parse_r3d_line(line: str) -> dict[str, Any] | None:
"""r3dlog 한 줄 → {game_time, game_time_s, channel, sender, champion, message} 또는 None."""
m = CHAT_RE.search(line)
if not m:
return None
t = LOG_TIME_RE.match(line)
explicit = m.group("time")
if explicit:
game_time, game_time_s = explicit, time_to_seconds(explicit)
elif t:
game_time_s = float(t.group("t"))
game_time = seconds_to_time(game_time_s)
else:
game_time, game_time_s = None, None
return {
"game_time": game_time,
"game_time_s": game_time_s,
"channel": CHANNELS[m.group("chan").lower()],
"sender": m.group("sender").strip(),
"champion": m.group("champ").strip() if m.group("champ") else None,
"message": m.group("msg"),
}
def latest_log(logs_dir: str | Path, since_ms: float | None = None) -> Path | None:
"""가장 최근 *_r3dlog.txt. since_ms 가 있으면 그 뒤에 수정된 파일만."""
root = Path(logs_dir)
if not root.is_dir():
return None
files = [p for p in root.rglob("*_r3dlog.txt") if p.is_file()]
if since_ms is not None:
files = [p for p in files if p.stat().st_mtime * 1000 > since_ms]
return max(files, key=lambda p: p.stat().st_mtime) if files else None
def scan(path: Path, limit: int | None = None) -> list[dict[str, Any]]:
out: list[dict[str, Any]] = []
with open(path, encoding="utf-8", errors="replace") as f:
for line in f:
p = parse_r3d_line(line)
if p:
out.append(p)
if limit and len(out) >= limit:
break
return out
def follow(path: Path, stop: threading.Event, from_start: bool = False, poll_s: float = 0.5
) -> Iterator[dict[str, Any]]:
"""tail -f 처럼 새로 붙는 줄에서 채팅을 꺼낸다. stop 이 설정되면 끝난다."""
with open(path, encoding="utf-8", errors="replace") as f:
if not from_start:
f.seek(0, 2)
buf = ""
while not stop.is_set():
chunk = f.readline()
if not chunk:
stop.wait(poll_s)
continue
buf += chunk
if not buf.endswith("\n"):
continue # 아직 덜 쓰인 줄
line, buf = buf, ""
p = parse_r3d_line(line)
if p:
yield p
def check(logs_dir: str) -> dict[str, Any]:
path = latest_log(logs_dir)
if path is None:
return {"found_chat": False, "file": None, "sample": []}
sample = scan(path, limit=5)
return {"found_chat": bool(sample), "file": str(path), "sample": sample}
def read(logs_dir: str, since_ms: float | None = None) -> dict[str, Any]:
path = latest_log(logs_dir, since_ms)
if path is None:
return {"file": None, "lines": []}
return {"file": str(path), "lines": scan(path)}

197
worker/gvr_worker/stt.py Normal file
View File

@@ -0,0 +1,197 @@
"""STT 슬롯(realtime/precise) 관리와 변환 파이프라인.
정규화 → VAD 말소리 비율 → faster-whisper → 잡음 판정 → 교정 사전 순서.
"""
from __future__ import annotations
import gc
import logging
import math
import os
import threading
import time
from dataclasses import dataclass
from typing import Any
import numpy as np
from . import audio as audio_mod
from . import noise
from .dictionary import Corrector
from .models import resolve_model_path
from .protocol import WorkerError
log = logging.getLogger(__name__)
SLOTS = ("realtime", "precise")
BEAM = {"realtime": 3, "precise": 5}
VAD_MIN_SILENCE_MS = 500
@dataclass
class LoadedModel:
name: str
path: str
device: str
compute_type: str
model: Any # faster_whisper.WhisperModel
def _vad_speech(audio: np.ndarray) -> tuple[float, float]:
"""(말소리 비율, 말소리 초). faster-whisper 내장 Silero VAD 사용."""
from faster_whisper.vad import VadOptions, get_speech_timestamps
if audio.size == 0:
return 0.0, 0.0
opts = VadOptions(min_silence_duration_ms=VAD_MIN_SILENCE_MS, min_speech_duration_ms=100, speech_pad_ms=30)
stamps = get_speech_timestamps(audio, opts, sampling_rate=audio_mod.SR)
speech = sum(s["end"] - s["start"] for s in stamps) / audio_mod.SR
return min(speech / (audio.size / audio_mod.SR), 1.0), speech
def _is_cuda_dll_error(msg: str) -> bool:
m = msg.lower()
return any(k in m for k in ("cublas", "cudnn", ".dll", "libcuda", "cuda driver", "no cuda", "cudart"))
class SttEngine:
def __init__(self) -> None:
self.slots: dict[str, LoadedModel | None] = {s: None for s in SLOTS}
self._lock = threading.Lock()
# --- 적재 ---------------------------------------------------------------
def load(self, slot: str, model: str, device: str | None, compute_type: str | None,
cpu_threads: int = 0) -> dict[str, Any]:
from faster_whisper import WhisperModel
from .gpu import gpu_list
path = resolve_model_path(model)
fallback = None
if device in (None, "auto"):
device = "cuda" if gpu_list() else "cpu"
elif device == "cuda" and not gpu_list():
device, fallback = "cpu", "no_gpu"
if device not in ("cuda", "cpu"):
raise WorkerError("bad_request", "device 는 cuda 또는 cpu 여야 합니다")
if not compute_type or fallback:
compute_type = "float16" if device == "cuda" else "int8"
self.unload(slot) # VRAM 먼저 비우기
t0 = time.monotonic()
try:
m = WhisperModel(str(path), device=device, compute_type=compute_type, cpu_threads=cpu_threads)
except Exception as e: # noqa: BLE001
msg = str(e)
if device == "cuda" and _is_cuda_dll_error(msg):
raise WorkerError(
"cuda_runtime_missing",
f"CUDA 런타임(cuBLAS/cuDNN)을 불러오지 못했습니다. CUDA 런타임을 다운로드한 뒤 다시 시도하세요. ({msg})",
) from e
raise WorkerError("load_failed", f"모델을 불러오지 못했습니다: {msg}") from e
with self._lock:
self.slots[slot] = LoadedModel(model, str(path), device, compute_type, m)
res: dict[str, Any] = {"slot": slot, "model": model, "device": device, "compute_type": compute_type,
"path": str(path), "elapsed_ms": int((time.monotonic() - t0) * 1000)}
if fallback:
res["fallback"] = fallback
return res
def unload(self, slot: str) -> dict[str, Any]:
with self._lock:
had = self.slots.get(slot)
self.slots[slot] = None
if had is not None:
del had
gc.collect()
return {"slot": slot, "unloaded": True}
def status(self) -> dict[str, Any]:
return {s: (None if m is None else {"model": m.name, "device": m.device, "compute_type": m.compute_type})
for s, m in self.slots.items()}
# --- 변환 ---------------------------------------------------------------
def transcribe(self, req: dict[str, Any]) -> dict[str, Any]:
t0 = time.monotonic()
slot = req["slot"]
lm = self.slots.get(slot)
if lm is None:
raise WorkerError("model_not_loaded", f"'{slot}' 슬롯에 모델이 적재되지 않았습니다")
path = req.get("path")
if not isinstance(path, str) or not path:
raise WorkerError("bad_request", "'path' 필드가 필요합니다")
if not os.path.isfile(path):
raise WorkerError("file_not_found", f"오디오 파일이 없습니다: {path}")
sensitivity = float(req.get("noise_sensitivity") if req.get("noise_sensitivity") is not None else 0.5)
try:
prep = audio_mod.prepare(
path,
target_lufs=float(req.get("target_lufs") if req.get("target_lufs") is not None else -18.0),
profile_lufs=req.get("profile_lufs"),
use_denoise=bool(req.get("denoise")),
)
except Exception as e: # noqa: BLE001 - 손상된 파일 등
raise WorkerError("decode_failed", f"오디오를 읽지 못했습니다: {e}") from e
speech_ratio, speech_s = _vad_speech(prep.audio)
result: dict[str, Any] = {
"text": None, "raw_text": None, "words": [], "noise": False, "noise_reason": None,
"confidence": None, "lufs": prep.lufs, "gain_db": prep.gain_db,
"speech_ratio": round(speech_ratio, 3), "duration_s": prep.duration_s, "model": lm.name,
}
def done(noise_reason: str | None = None) -> dict[str, Any]:
if noise_reason:
result.update(noise=True, noise_reason=noise_reason, text=None, words=[])
result["elapsed_ms"] = int((time.monotonic() - t0) * 1000)
return result
# ① VAD: 말소리가 거의 없으면 Whisper 를 돌리지 않는다 (환각 방지 + GPU 절약)
if noise.judge_vad(speech_ratio, speech_s, sensitivity):
return done("vad")
hotwords = req.get("hotwords") or None
try:
segments, _info = lm.model.transcribe(
prep.audio,
language="ko",
task="transcribe",
beam_size=BEAM.get(slot, 5),
word_timestamps=True,
vad_filter=True,
vad_parameters={"min_silence_duration_ms": VAD_MIN_SILENCE_MS},
hotwords=hotwords if isinstance(hotwords, str) else None,
initial_prompt=req.get("initial_prompt") or None,
condition_on_previous_text=False,
)
segs = list(segments)
except Exception as e: # noqa: BLE001
raise WorkerError("transcribe_failed", f"음성 변환 실패: {e}") from e
words: list[dict[str, Any]] = []
for seg in segs:
for w in seg.words or []:
text = w.word.strip()
if not text:
continue
lead = w.word[: len(w.word) - len(w.word.lstrip())]
words.append({"w": text, "s": round(w.start, 2), "e": round(w.end, 2),
"p": round(w.probability, 3), "lead": lead})
raw_text = "".join(s.text for s in segs).strip()
infos = [noise.SegInfo(s.no_speech_prob, s.avg_logprob, s.compression_ratio) for s in segs]
confidence = float(np.mean([math.exp(s.avg_logprob) for s in segs])) if segs else 0.0
result.update(raw_text=raw_text or None, confidence=round(confidence, 3))
reason = noise.judge_text(raw_text, infos, confidence, prep.duration_s, sensitivity)
if reason:
return done(reason)
corrector = Corrector.from_request(req.get("corrections"), req.get("dictionary"))
if words:
text, out_words = corrector.correct_words(words)
else:
text, out_words = corrector.correct_text(raw_text), []
result.update(text=text, words=out_words)
return done()

3
worker/pytest.ini Normal file
View File

@@ -0,0 +1,3 @@
[pytest]
testpaths = tests
addopts = -p no:cacheprovider --basetemp=.pytest-tmp

View File

@@ -0,0 +1,4 @@
-r requirements.txt
pytest==9.1.1
pyinstaller==6.22.3
edge-tts==7.3.1 # tests/make_fixtures.py 용

19
worker/requirements.txt Normal file
View File

@@ -0,0 +1,19 @@
# 겜녹이 STT 워커 런타임 의존성 (Python 3.11)
faster-whisper==1.2.1
ctranslate2==4.8.3 # Windows 휠은 CUDA 12.8 + cuDNN 9 로 빌드됨 (RTX 50 / sm_120 지원)
av==18.1.0
onnxruntime==1.31.0 # Silero VAD
huggingface_hub==2.2.0
nvidia-ml-py==13.615.71
pyloudnorm==0.2.0
numpy==2.4.6
scipy==1.17.1
mss==10.2.0
pillow==12.3.0; sys_platform == "win32"
winrt-runtime==3.2.1; sys_platform == "win32"
winrt-Windows.Foundation==3.2.1; sys_platform == "win32"
winrt-Windows.Foundation.Collections==3.2.1; sys_platform == "win32"
winrt-Windows.Globalization==3.2.1; sys_platform == "win32"
winrt-Windows.Graphics.Imaging==3.2.1; sys_platform == "win32"
winrt-Windows.Media.Ocr==3.2.1; sys_platform == "win32"
winrt-Windows.Storage.Streams==3.2.1; sys_platform == "win32"

6
worker/run_worker.py Normal file
View File

@@ -0,0 +1,6 @@
"""PyInstaller 진입점 (gvr-worker.exe)."""
from gvr_worker.main import main
if __name__ == "__main__":
main()

95
worker/tests/conftest.py Normal file
View 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()

Binary file not shown.

BIN
worker/tests/fixtures/silence.ogg vendored Normal file

Binary file not shown.

BIN
worker/tests/fixtures/speech_ko.ogg vendored Normal file

Binary file not shown.

Binary file not shown.

BIN
worker/tests/fixtures/white_noise.ogg vendored Normal file

Binary file not shown.

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

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

View 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("레이저") == "레이즈"

View 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
View 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"}]

View 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"

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

View 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"] == "미드 갱"

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