feat: LiveSub 2차 — 자막 on/off, 모니터·위치 선택, GPU 저부하, 게임 용어집

이름을 Hearo → LiveSub 로 변경. 말장난보다 하는 일이 바로 보이는 쪽이 낫다.

자막 on/off
- 전역 단축키 Ctrl+Alt+S (자막) / Ctrl+Alt+D (번역) — Windows RegisterHotKey +
  네이티브 이벤트 필터라 게임 창이 떠 있어도 동작. 다른 OS 에서는 no-op
- 단축키·체크박스·우클릭 메뉴가 모두 같은 경로를 타도록 통합

모니터 선택 + 디스코드식 배치
- placement.py: Qt 비의존 배치 계산 (모니터 목록 → 9분할 좌표)
- AnchorGrid 위젯으로 3x3 위치 선택, 드래그하면 자유 배치로 전환
- 모니터 구성이 바뀌어도 자막이 화면 밖으로 사라지지 않도록 클램프

GPU 저부하 모드 (기본 켜짐)
- 연산 정밀도 int8 강등, VRAM 상한 35%, 추론 후 60ms 양보,
  300초 무음 시 모델 언로드, 중간 결과 비활성
- 기본 티어를 균형(6GB) → 신속(4GB) 으로 하향
- 8GB GPU 기준 자막 2.8GB / 게임 5.2GB

게임 용어집 번들 (304개)
- 롤 74 · 발로란트 59 · 오버워치2 49 · FPS공통 46 · 마크 38 · 방송 38
- 체크박스로 켜고 끄며, 사용자가 직접 등록한 항목이 항상 우선

검증: pytest 91개 통과 (배치 14 + 팩 12 + UI 6 신규), ruff clean

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-09-21 17:49:26 +09:00
parent 5596f905d1
commit 8b36b244ff
60 changed files with 1939 additions and 300 deletions

View File

@@ -0,0 +1,168 @@
"""프로그램별 오디오 캡처 (Windows WASAPI process loopback).
`native/process_loopback` 에서 빌드한 `livesub_capture.exe` 를 자식 프로세스로 띄우고
stdout 으로 흘러나오는 16kHz mono float32 PCM 을 그대로 읽는다.
보조 프로그램이 없으면 `available()` 이 False 를 돌려주고, 상위 레이어는
장치 루프백으로 자동 폴백한다.
"""
from __future__ import annotations
import logging
import subprocess
import sys
from pathlib import Path
import numpy as np
from ..constants import FRAME_SAMPLES
from .base import AudioSource, CaptureBackend, CaptureError
log = logging.getLogger(__name__)
HELPER_NAME = "livesub_capture.exe"
READ_BYTES = FRAME_SAMPLES * 4 * 5 # 100ms 분량
def helper_path() -> Path | None:
"""보조 프로그램 위치. 패키지 내부 → 저장소 빌드 폴더 순으로 찾는다."""
candidates = [
Path(__file__).resolve().parent.parent / "resources" / "bin" / HELPER_NAME,
Path(__file__).resolve().parents[3]
/ "native"
/ "process_loopback"
/ "build"
/ "Release"
/ HELPER_NAME,
]
for path in candidates:
if path.is_file():
return path
return None
class ProcessLoopbackCapture(CaptureBackend):
name = "process"
per_process = True
def __init__(self, pid: int, exclude: bool = False) -> None:
super().__init__()
self.pid = pid
self.exclude = exclude
self._proc: subprocess.Popen[bytes] | None = None
@staticmethod
def available() -> bool:
return sys.platform == "win32" and helper_path() is not None
@staticmethod
def list_sources() -> list[AudioSource]:
"""현재 소리를 내고 있는(또는 낼 수 있는) 프로세스 목록."""
if sys.platform != "win32":
return []
try:
from pycaw.pycaw import AudioUtilities
except ImportError:
log.debug("pycaw 미설치 — 프로세스 목록을 만들 수 없습니다.")
return []
seen: dict[int, AudioSource] = {}
for session in AudioUtilities.GetAllSessions():
proc = session.Process
if proc is None or proc.pid in seen:
continue
try:
name = proc.name()
except Exception: # noqa: BLE001 - 종료된 프로세스
continue
title = _window_title(proc.pid) or name
seen[proc.pid] = AudioSource(
kind="process",
identifier=str(proc.pid),
label=title,
detail=f"{name} (PID {proc.pid})",
)
return sorted(seen.values(), key=lambda s: s.label.lower())
def _run(self) -> None: # pragma: no cover - Windows 전용
exe = helper_path()
if exe is None:
raise CaptureError(
f"{HELPER_NAME} 를 찾지 못했습니다. "
"native/process_loopback/build.ps1 로 먼저 빌드하세요."
)
cmd = [str(exe), "--pid", str(self.pid)]
if self.exclude:
cmd.append("--exclude")
self._proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
bufsize=0,
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
)
assert self._proc.stdout is not None
try:
while not self._stop.is_set():
raw = self._proc.stdout.read(READ_BYTES)
if not raw:
code = self._proc.poll()
err = b""
if self._proc.stderr is not None:
err = self._proc.stderr.read() or b""
raise CaptureError(
f"캡처 보조 프로그램이 종료되었습니다(코드 {code}): "
f"{err.decode('utf-8', 'replace').strip()}"
)
# 4바이트 정렬이 깨지면 float32 해석이 밀린다.
usable = len(raw) - (len(raw) % 4)
self._emit(np.frombuffer(raw[:usable], dtype=np.float32).copy())
finally:
self._terminate()
def _terminate(self) -> None:
proc, self._proc = self._proc, None
if proc is None:
return
if proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=2)
except subprocess.TimeoutExpired:
proc.kill()
for pipe in (proc.stdout, proc.stderr):
if pipe is not None:
pipe.close()
def _window_title(pid: int) -> str:
"""해당 PID의 최상위 창 제목. 실패하면 빈 문자열."""
if sys.platform != "win32":
return ""
try:
import ctypes
from ctypes import wintypes
user32 = ctypes.windll.user32
result: list[str] = []
@ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
def callback(hwnd, _lparam):
owner = wintypes.DWORD()
user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner))
if owner.value != pid or not user32.IsWindowVisible(hwnd):
return True
length = user32.GetWindowTextLengthW(hwnd)
if length <= 0:
return True
buf = ctypes.create_unicode_buffer(length + 1)
user32.GetWindowTextW(hwnd, buf, length + 1)
result.append(buf.value)
return False
user32.EnumWindows(callback, 0)
return result[0] if result else ""
except Exception: # noqa: BLE001 - 창 제목은 부가 정보일 뿐
return ""