fix: 필수 팩 기본 활성화 + 저부하 모드 토글 반영 + 용어 겹침 수정

리뷰 지적 2건과, 그것을 고치다 드러난 용어집 버그 1건을 함께 처리했다.

1) 저부하 모드 토글이 모델에 반영되지 않던 버그
   ModelManager 는 생성 시점의 low_power 로 정밀도를 정하는데 설정에서
   토글해도 갱신되지 않았고, stop() 은 모델을 내리지 않아 이전 정밀도
   모델이 그대로 남았다. TranslationEngine.sync_performance() 를 추가해
   값이 바뀌면 언로드 후 갱신하고, _bootstrap 과 재시작 경로에서 부른다.

2) 필수 게임 팩이 기본으로 꺼져 있던 문제
   새 설치 기본값을 fps-common + 오버워치 + 배그 + R6 + 워독스로 켰다.

3) (1)(2)를 고치며 드러난 것: 팩 여러 개를 켜면 결과가 체크 순서에
   휘둘렸다. knocked 가 FPS공통 "기절" / 배그 "눕혔다" 로 갈리는 식으로
   19개 용어가 충돌하는데, 사용자는 그 순서를 볼 수도 바꿀 수도 없었다.
   팩에 scope(generic/game) 를 두고 범용 -> 게임 전용 -> 사용자 항목
   순으로 적용해 결정적으로 만들었다. 게임 팩끼리 갈리는 것은 사람이
   판단할 문제라 find_conflicts() 로 뽑아 용어집 화면에 표시한다.

4) 용어 겹침 버그: "the blue"(조각)가 "blue zone" 보다 앞 위치라는
   이유로 먼저 잡혀 "자기장 자기장" 이 됐다. 최장일치 정렬은 같은 시작
   위치에서만 통한다. 조각 항목을 제거하고, 모든 팩을 켠 상태로 각
   용어가 정확히 한 번만 치환되는지 검사하는 테스트를 추가했다.

검증: pytest 110개 통과 (저부하 6 + 팩 계층/충돌/겹침 12 신규), ruff clean

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-09-21 18:05:22 +09:00
parent a7eafd03e1
commit e4a048c8d5
19 changed files with 4266 additions and 506 deletions

95
tests/test_low_power.py Normal file
View File

@@ -0,0 +1,95 @@
"""저부하(게임) 모드 토글이 실제로 모델에 반영되는지.
설정 화면에서 모드를 꺼도 이미 올라가 있는 int8 모델이 그대로 남으면
"껐는데 품질이 안 올라간다"가 된다. 반대로 켜도 float16 모델이 남으면
게임 프레임을 지키려던 목적이 통째로 무산된다.
"""
from __future__ import annotations
from livesub.config import AppConfig
from livesub.core.engine import TranslationEngine
from livesub.models import ModelManager
def make_engine(game_mode: bool, tmp_path) -> TranslationEngine:
cfg = AppConfig()
cfg.models.preload_on_start = False
cfg.glossary.path = str(tmp_path / "glossary.json")
cfg.performance.game_mode = game_mode
return TranslationEngine(cfg)
def test_manager_reflects_initial_game_mode(tmp_path):
on = make_engine(True, tmp_path)
off = make_engine(False, tmp_path)
assert on.models.low_power is True
assert off.models.low_power is False
def test_toggling_game_mode_updates_manager(tmp_path):
"""설정에서 모드를 바꾸면 다음 시작 때 모델 사양이 따라와야 한다."""
engine = make_engine(True, tmp_path)
assert "int8" in engine.models.effective_asr_spec().compute_type
engine.config.performance.game_mode = False
engine.sync_performance()
assert engine.models.low_power is False
assert engine.models.effective_asr_spec() == engine.models.tier.asr
def test_toggling_back_on_restores_low_power_specs(tmp_path):
engine = make_engine(False, tmp_path)
engine.config.performance.game_mode = True
engine.sync_performance()
assert engine.models.low_power is True
assert "int8" in engine.models.effective_asr_spec().compute_type
def test_changed_mode_unloads_stale_models(tmp_path):
"""정밀도가 바뀌었으면 이미 올라간 모델을 반드시 내려야 한다."""
engine = make_engine(True, tmp_path)
class FakeModel:
def __init__(self):
self.loaded = True
self.unloaded = False
def unload(self):
self.unloaded = True
self.loaded = False
asr, mt = FakeModel(), FakeModel()
engine.models._asr, engine.models._mt = asr, mt
engine.config.performance.game_mode = False
changed = engine.sync_performance()
assert changed is True
assert asr.unloaded and mt.unloaded
assert engine.models._asr is None and engine.models._mt is None
def test_unchanged_mode_keeps_models_loaded(tmp_path):
"""바뀐 게 없으면 굳이 내려서 재다운로드/재로딩을 유발하면 안 된다."""
engine = make_engine(True, tmp_path)
class FakeModel:
loaded = True
def unload(self):
raise AssertionError("바뀐 게 없는데 언로드하면 안 됩니다")
engine.models._asr = FakeModel()
engine.models._mt = FakeModel()
assert engine.sync_performance() is False
assert engine.models._asr is not None
def test_int4_tier_is_not_downgraded_further(tmp_path):
cfg = AppConfig()
cfg.models.tier = "precision"
manager = ModelManager(cfg.models, low_power=True)
assert manager.effective_mt_spec().compute_type == "int4"

View File

@@ -4,7 +4,13 @@ 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
from livesub.models.packs import (
available_packs,
build_glossary,
find_conflicts,
get_pack,
resolve_packs,
)
#: 사용자가 "필수 게임"으로 지정한 것 — 빠지면 테스트가 잡아낸다.
REQUIRED_GAMES = {"overwatch", "watchdogs", "pubg", "r6siege"}
@@ -102,3 +108,103 @@ def test_no_packs_means_only_user_entries():
user = Glossary([GlossaryEntry("foo", {"ko": "푸"})])
merged = build_glossary(user, [])
assert len(merged) == 1
# --- 팩 계층: 게임 전용이 장르 공통을 이긴다 --------------------------------
def test_generic_packs_are_tagged():
generic = {p.key for p in available_packs() if p.is_generic}
assert generic == {"fps-common", "streaming"}
def test_game_pack_beats_generic_regardless_of_check_order():
"""체크한 순서가 결과를 바꾸면 안 된다.
knocked 는 FPS 공통에서 '기절', 배그에서 '눕혔다'다. 배그를 켰으면
어느 쪽을 먼저 눌렀든 '눕혔다'가 나와야 한다.
"""
for order in (["fps-common", "pubg"], ["pubg", "fps-common"]):
_, repl = build_glossary(Glossary(), order).protect("knocked", "ko")
assert repl == ["눕혔다"], f"{order} 에서 순서에 휘둘림"
def test_resolve_packs_puts_generic_first():
order = [p.key for p in resolve_packs(["pubg", "fps-common", "overwatch", "streaming"])]
assert order.index("fps-common") < order.index("pubg")
assert order.index("streaming") < order.index("overwatch")
def test_user_entry_still_beats_everything():
user = Glossary([GlossaryEntry("knocked", {"ko": "쓰러짐"})])
_, repl = build_glossary(user, ["fps-common", "pubg"]).protect("knocked", "ko")
assert repl == ["쓰러짐"]
# --- 충돌 감지 ---------------------------------------------------------------
def test_conflicts_detected_between_game_packs():
conflicts = find_conflicts(["overwatch", "watchdogs"])
assert "payload" in conflicts
assert {t for _, t in conflicts["payload"]} == {"화물", "페이로드"}
def test_generic_vs_game_is_not_reported_as_conflict():
"""범용은 게임 팩에 확실히 지므로 사용자가 판단할 일이 없다."""
assert "knocked" not in find_conflicts(["fps-common", "pubg"])
def test_single_game_pack_has_no_conflicts():
assert find_conflicts(["pubg", "fps-common", "streaming"]) == {}
def test_default_enabled_packs_cover_required_games():
from livesub.config import AppConfig
enabled = set(AppConfig().glossary.enabled_packs)
assert enabled >= REQUIRED_GAMES, f"기본값에서 빠진 필수 게임: {REQUIRED_GAMES - enabled}"
def test_default_enabled_packs_all_exist():
from livesub.config import AppConfig
keys = {p.key for p in available_packs()}
assert set(AppConfig().glossary.enabled_packs) <= keys
def test_default_enabled_packs_actually_translate():
from livesub.config import AppConfig
cfg = AppConfig()
merged = build_glossary(Glossary(), cfg.glossary.enabled_packs)
_, repl = merged.protect("DedSec hacked the ctOS server", "ko")
assert repl == ["데드섹", "해킹됐다", "ctOS"]
# --- 용어가 조각나서 두 번 치환되지 않는지 -----------------------------------
def test_each_term_protects_as_a_single_unit():
"""등록된 용어를 그대로 넣으면 정확히 한 번만 치환돼야 한다.
조각 용어("the blue")가 더 긴 용어("blue zone")보다 앞 위치에서 먼저
매칭되면 "자기장 자기장" 같은 겹침이 생긴다. 최장일치 정렬은 같은 시작
위치에서만 통하므로, 데이터에 조각이 섞이면 이 테스트가 잡아낸다.
팩을 전부 켠 최악의 조합으로 검사한다.
"""
merged = build_glossary(Glossary(), [p.key for p in available_packs()])
broken = []
for entry in merged.entries:
_, repl = merged.protect(entry.source, "ko")
if len(repl) != 1:
broken.append((entry.source, repl))
assert not broken, f"한 용어가 여러 조각으로 잘립니다: {broken[:5]}"
def test_blue_zone_is_one_replacement():
merged = build_glossary(Glossary(), ["fps-common", "pubg"])
protected, repl = merged.protect("head to the blue zone", "ko")
assert repl == ["자기장"], f"겹침 발생: {protected}"
assert Glossary.restore(protected, repl) == "head to the 자기장"