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

@@ -1,7 +1,7 @@
import json
from hearo.config import AppConfig
from hearo.models.tiers import DEFAULT_TIER
from livesub.config import AppConfig
from livesub.models.tiers import DEFAULT_TIER
def test_defaults_are_sane():

View File

@@ -1,4 +1,4 @@
from hearo.models.glossary import Glossary, GlossaryEntry
from livesub.models.glossary import Glossary, GlossaryEntry
def make() -> Glossary:

92
tests/test_packs.py Normal file
View File

@@ -0,0 +1,92 @@
"""기본 제공 게임 용어집 팩."""
from __future__ import annotations
from livesub.constants import LANGUAGE_CODES
from livesub.models.glossary import Glossary, GlossaryEntry
from livesub.models.packs import available_packs, build_glossary, get_pack
EXPECTED_PACKS = {"lol", "valorant", "overwatch", "fps-common", "minecraft", "streaming"}
def test_bundled_packs_are_loadable():
keys = {p.key for p in available_packs()}
assert keys >= EXPECTED_PACKS, f"빠진 팩: {EXPECTED_PACKS - keys}"
def test_every_pack_has_entries_and_metadata():
for pack in available_packs():
assert pack.name, pack.key
assert pack.description, pack.key
assert len(pack) >= 30, f"{pack.key} 는 용어가 너무 적습니다 ({len(pack)}개)"
def test_every_entry_has_a_korean_target():
"""주 용도가 '외국어 → 한국어' 이므로 한국어 역어는 반드시 있어야 한다."""
for pack in available_packs():
for entry in pack.entries:
assert entry.target_for("ko"), f"{pack.key}: {entry.source} 에 한국어 역어 없음"
def test_targets_only_use_supported_languages():
for pack in available_packs():
for entry in pack.entries:
unknown = set(entry.targets) - set(LANGUAGE_CODES)
assert not unknown, f"{pack.key}: {entry.source} 에 미지원 언어 {unknown}"
def test_no_duplicate_sources_inside_a_pack():
for pack in available_packs():
seen = [e.source.casefold() for e in pack.entries]
dupes = {s for s in seen if seen.count(s) > 1}
assert not dupes, f"{pack.key} 에 중복 용어: {dupes}"
def test_known_terms_are_present():
lol = get_pack("lol")
sources = {e.source.casefold() for e in lol.entries}
assert {"baron", "gank", "nexus", "ult"} <= sources
valorant = get_pack("valorant")
sources = {e.source.casefold() for e in valorant.entries}
assert {"spike", "defuse", "eco", "retake"} <= sources
def test_get_pack_returns_none_for_unknown():
assert get_pack("no-such-game") is None
def test_build_glossary_merges_packs():
merged = build_glossary(Glossary(), ["lol"])
protected, repl = merged.protect("push to the Nexus", "ko")
# 'push' 와 'Nexus' 둘 다 LoL 팩에 있으므로 둘 다 잡힌다.
assert repl == ["푸시", "넥서스"]
assert "Nexus" not in protected
assert Glossary.restore(protected, repl) == "푸시 to the 넥서스"
def test_user_entry_beats_pack_entry():
"""기본 팩 역어가 마음에 안 들면 직접 등록한 것이 이겨야 한다."""
user = Glossary([GlossaryEntry("baron", {"ko": "바론둥이"})])
merged = build_glossary(user, ["lol"])
_, repl = merged.protect("baron", "ko")
assert repl == ["바론둥이"]
def test_unknown_pack_key_is_ignored_not_fatal():
merged = build_glossary(Glossary(), ["lol", "does-not-exist"])
assert len(merged) > 0
def test_multiple_packs_combine():
only_lol = build_glossary(Glossary(), ["lol"])
both = build_glossary(Glossary(), ["lol", "minecraft"])
assert len(both) > len(only_lol)
_, repl = both.protect("creeper", "ko")
assert repl == ["크리퍼"]
def test_no_packs_means_only_user_entries():
user = Glossary([GlossaryEntry("foo", {"ko": "푸"})])
merged = build_glossary(user, [])
assert len(merged) == 1

View File

@@ -7,11 +7,11 @@ import time
import numpy as np
import pytest
from hearo.audio.base import CaptureBackend, to_mono_16k
from hearo.config import AppConfig
from hearo.constants import SAMPLE_RATE
from hearo.core.engine import TranslationEngine
from hearo.models.asr import Transcript
from livesub.audio.base import CaptureBackend, to_mono_16k
from livesub.config import AppConfig
from livesub.constants import SAMPLE_RATE
from livesub.core.engine import TranslationEngine
from livesub.models.asr import Transcript
class FakeCapture(CaptureBackend):
@@ -85,7 +85,7 @@ def engine(tmp_path, monkeypatch):
eng = TranslationEngine(config, on_line=lines.append)
monkeypatch.setattr(eng.models, "recognizer", lambda: FakeRecognizer())
monkeypatch.setattr(eng.models, "translator", lambda: FakeTranslator())
monkeypatch.setattr("hearo.core.engine.create_capture", lambda cfg: FakeCapture())
monkeypatch.setattr("livesub.core.engine.create_capture", lambda cfg: FakeCapture())
eng.lines = lines
yield eng
eng.shutdown()

108
tests/test_placement.py Normal file
View File

@@ -0,0 +1,108 @@
"""자막 창 배치 계산 (모니터 선택 + 디스코드식 9분할)."""
from __future__ import annotations
import pytest
from livesub.ui.placement import (
ANCHOR_LABELS,
ANCHORS,
DEFAULT_ANCHOR,
ScreenInfo,
pick_screen,
resolve_rect,
screen_for_point,
)
MAIN = ScreenInfo(0, "DELL U2720Q", 0, 0, 1920, 1080, is_primary=True)
#: 오른쪽에 붙은 두 번째 모니터 (음수 좌표가 아닌 일반 배치)
SECOND = ScreenInfo(1, "LG 27GP", 1920, 0, 2560, 1440)
#: 왼쪽에 붙어 x 가 음수인 모니터 — 윈도우에서 흔한 구성
LEFT = ScreenInfo(1, "왼쪽", -1600, 0, 1600, 900)
SCREENS = [MAIN, SECOND]
def test_all_nine_anchors_defined_and_labelled():
assert len(ANCHORS) == 9
assert set(ANCHORS) == set(ANCHOR_LABELS)
def test_bottom_center_is_default():
x, y, w, h = resolve_rect(MAIN, DEFAULT_ANCHOR, 1100, 200, margin=60)
assert x == (1920 - 1100) // 2
assert y == 1080 - 200 - 60
def test_each_corner_lands_in_its_corner():
w, h, m = 400, 150, 50
tl = resolve_rect(MAIN, "top-left", w, h, m)
tr = resolve_rect(MAIN, "top-right", w, h, m)
bl = resolve_rect(MAIN, "bottom-left", w, h, m)
br = resolve_rect(MAIN, "bottom-right", w, h, m)
assert tl[0] == m and tl[1] == m
assert tr[0] == 1920 - w - m and tr[1] == m
assert bl[0] == m and bl[1] == 1080 - h - m
assert br[0] == 1920 - w - m and br[1] == 1080 - h - m
def test_middle_center_is_centered():
x, y, w, h = resolve_rect(MAIN, "middle-center", 600, 200, 60)
assert x == (1920 - 600) // 2
assert y == (1080 - 200) // 2
def test_second_monitor_offsets_are_applied():
"""두 번째 모니터는 가상 데스크톱 좌표가 1920부터 시작한다."""
x, y, w, h = resolve_rect(SECOND, "bottom-center", 1100, 200, 60)
assert x == 1920 + (2560 - 1100) // 2
assert y == 1440 - 200 - 60
def test_negative_origin_monitor():
x, y, w, h = resolve_rect(LEFT, "top-left", 400, 150, 50)
assert x == -1600 + 50
assert y == 50
def test_oversized_window_is_clamped_into_the_screen():
"""창이 모니터보다 크면 화면 밖으로 나가면 안 된다."""
x, y, w, h = resolve_rect(LEFT, "bottom-center", 9999, 9999, margin=60)
assert w <= LEFT.width
assert h <= LEFT.height
assert x >= LEFT.x
assert y >= LEFT.y
assert x + w <= LEFT.x + LEFT.width
assert y + h <= LEFT.y + LEFT.height
@pytest.mark.parametrize("anchor", list(ANCHORS))
def test_every_anchor_stays_inside_the_screen(anchor):
x, y, w, h = resolve_rect(SECOND, anchor, 1100, 200, 60)
assert SECOND.x <= x and x + w <= SECOND.x + SECOND.width
assert SECOND.y <= y and y + h <= SECOND.y + SECOND.height
def test_unknown_anchor_falls_back_to_default():
assert resolve_rect(MAIN, "nope", 500, 200, 60) == resolve_rect(
MAIN, DEFAULT_ANCHOR, 500, 200, 60
)
def test_screen_for_point_finds_the_right_monitor():
assert screen_for_point(SCREENS, 100, 100) is MAIN
assert screen_for_point(SCREENS, 2500, 700) is SECOND
assert screen_for_point(SCREENS, 99_999, 0) is None
def test_pick_screen_falls_back_to_primary_when_monitor_disappears():
"""모니터를 뽑았을 때 저장된 인덱스가 사라져도 자막이 실종되면 안 된다."""
assert pick_screen(SCREENS, 1) is SECOND
assert pick_screen(SCREENS, 7) is MAIN # 없는 인덱스 → 주 모니터
assert pick_screen([], 0) is None
def test_pick_screen_uses_first_when_no_primary_flagged():
screens = [ScreenInfo(3, "A", 0, 0, 800, 600), ScreenInfo(4, "B", 800, 0, 800, 600)]
assert pick_screen(screens, 99) is screens[0]

View File

@@ -9,10 +9,10 @@ from __future__ import annotations
import pytest
from hearo.constants import LANGUAGE_CODES, LANGUAGES
from hearo.models.glossary import Glossary, GlossaryEntry
from hearo.models.tiers import TIERS, MTBackend, PromptStyle, get_tier
from hearo.models.translator import build_seedx_prompt
from livesub.constants import LANGUAGE_CODES, LANGUAGES
from livesub.models.glossary import Glossary, GlossaryEntry
from livesub.models.tiers import TIERS, MTBackend, PromptStyle, get_tier
from livesub.models.translator import build_seedx_prompt
def test_seedx_prompt_matches_model_card_exactly():

View File

@@ -1,7 +1,7 @@
import numpy as np
from hearo.audio.segmenter import Segmenter, SegmenterConfig
from hearo.constants import SAMPLE_RATE
from livesub.audio.segmenter import Segmenter, SegmenterConfig
from livesub.constants import SAMPLE_RATE
def tone(ms: int, amplitude: float = 0.3) -> np.ndarray:

View File

@@ -1,4 +1,4 @@
from hearo.models.tiers import (
from livesub.models.tiers import (
DEFAULT_TIER,
TIERS,
MTBackend,

View File

@@ -12,10 +12,12 @@ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6.QtGui import QImage, QPainter # noqa: E402
from PySide6.QtWidgets import QApplication # noqa: E402
from hearo.config import AppConfig # noqa: E402
from hearo.core.events import EngineState, EngineStatus, TranslationLine # noqa: E402
from hearo.ui.main_window import MainWindow # noqa: E402
from hearo.ui.overlay import paint_subtitle # noqa: E402
from livesub.config import AppConfig # noqa: E402
from livesub.core.events import EngineState, EngineStatus, TranslationLine # noqa: E402
from livesub.models import ModelManager # noqa: E402
from livesub.ui.main_window import MainWindow # noqa: E402
from livesub.ui.overlay import paint_subtitle # noqa: E402
from livesub.ui.placement import ANCHOR_CUSTOM, list_screens, resolve_rect # noqa: E402
@pytest.fixture(scope="session")
@@ -26,7 +28,7 @@ def qapp():
@pytest.fixture
def window(qapp, tmp_path, monkeypatch):
monkeypatch.setattr("hearo.constants.user_data_dir", lambda: tmp_path)
monkeypatch.setattr("livesub.constants.user_data_dir", lambda: tmp_path)
config = AppConfig()
config.models.preload_on_start = False
config.glossary.path = str(tmp_path / "glossary.json")
@@ -79,6 +81,82 @@ def test_subtitle_style_edit_propagates(window):
assert window.config.subtitle.font_size == 60
def test_subtitle_toggle_turns_overlay_on_and_off(window):
"""자막 on/off — 단축키와 체크박스가 같은 경로를 탄다."""
window.config.overlay.visible = True
window.overlay.set_subtitle_visible(True)
window.toggle_subtitle()
assert window.config.overlay.visible is False
assert window.overlay.isVisible() is False
# 체크박스가 따라와야 한다 (시그널 연결 확인)
assert window.subtitle_page.overlay_check.isChecked() is False
window.toggle_subtitle()
assert window.config.overlay.visible is True
assert window.subtitle_page.overlay_check.isChecked() is True
def test_turning_subtitle_off_clears_leftover_text(window):
window.config.log_transcripts = False
window.overlay.set_subtitle_visible(True)
window._on_line(TranslationLine("hello", "안녕", "en", "ko", is_final=True))
assert window.overlay._final_text
window.toggle_subtitle()
assert window.overlay._final_text == ""
def test_checkbox_and_hotkey_do_not_fight_each_other(window):
"""체크박스 → 오버레이 → 체크박스 되먹임이 무한루프가 되면 안 된다."""
window.config.overlay.visible = True
window.overlay.set_subtitle_visible(True)
window.subtitle_page.overlay_check.setChecked(False)
assert window.config.overlay.visible is False
assert window.overlay.isVisible() is False
def test_anchor_selection_moves_the_overlay(window):
window.subtitle_page._on_anchor_selected("top-left")
assert window.config.overlay.anchor == "top-left"
screens = list_screens()
if screens: # offscreen 플랫폼에도 가상 화면이 하나 있다
expected = resolve_rect(
screens[0], "top-left",
window.config.overlay.width, window.config.overlay.height,
window.config.overlay.margin,
)
assert (window.config.overlay.x, window.config.overlay.y) == expected[:2]
def test_dragging_switches_to_custom_placement(window):
window.subtitle_page._on_anchor_selected("bottom-center")
assert window.config.overlay.anchor == "bottom-center"
window.overlay.move(123, 456)
window.overlay._drag_from = window.overlay.pos()
window.overlay.mouseReleaseEvent(None)
assert window.config.overlay.anchor == ANCHOR_CUSTOM
def test_glossary_packs_reach_the_engine(window):
window.config.glossary.enabled_packs = ["lol"]
window._on_glossary_changed()
_, repl = window.engine.glossary.protect("the Nexus", "ko")
assert repl == ["넥서스"]
def test_game_mode_lowers_precision(window):
window.config.performance.game_mode = True
manager = ModelManager(window.config.models, low_power=True)
assert "int8" in manager.effective_asr_spec().compute_type
assert manager.effective_asr_spec().beam_size == 1
normal = ModelManager(window.config.models, low_power=False)
assert normal.effective_asr_spec() == normal.tier.asr
def test_paint_subtitle_actually_draws_pixels(qapp):
"""자막 글씨가 투명 이미지 위에 실제로 그려지는지 (빈 화면이면 실패).