리뷰 지적(포터블에서 transformers 제외 -> NLLB 로드 실패)을 고치려고 실제
NLLB 를 받아 돌려봤고, 그 과정에서 용어집이 사실상 동작하지 않고 있었다는
것을 발견했다. 단위 테스트는 "모델이 자리표시자를 통과시킨다"는 틀린 전제
위에 서 있었다.
1) 포터블 패키징 (리뷰 지적)
transformers 를 제외 목록에서 빼고 hiddenimports 에 넣었다. NLLB
토크나이저가 AutoTokenizer 를 쓰기 때문이다. transformers 는 torch 가
없으면 토크나이저 전용 모드로 뜨며 그게 우리 용도와 정확히 맞는다.
torch 없는 환경에서 ctranslate2/transformers/faster-whisper import 와
앱 기동을 검증하는 test_portable.py 를 추가했다.
2) 자리표시자 형식 (실측으로 발견)
`⟦0⟧` 는 NLLB 가 괄호를 날려 생존률 0/3 이었다. 용어가 자막에서 그냥
사라지고 있었다 ("Third party incoming" -> "0 들어오는"). 후보 8종을
실제 모델로 비교해 `#0#` 로 교체 (3/3, 다중 4/5).
3) 소실 대비
모델이 문장 일부를 누락하면 자리표시자도 사라진다. 그대로 복원하면
용어가 증발하므로, 하나라도 없으면 보호 없이 재번역한다.
4) 서술어는 문장 전체일 때만 (whole_only)
절/서술어를 문장 중간에서 치환하면 문법이 무너진다.
before: "탄 필요해와 구급상자"
after : "탄약과 구급상자가 필요합니다"
해당 56개 항목을 whole_only 로 지정해 단독 발화일 때만 적용한다.
("Cover me!" -> "엄호해줘" 는 그대로 유지)
5) 조사 교정
역어 받침이 달라 "자기장를" 이 남던 것을 fix_particles() 로 고친다.
을/를, 이/가, 은/는, 과/와, (으)로 — 한글 코드에서 받침을 읽어 판정.
검증: pytest 189개 통과, ruff clean
실제 NLLB-600M(torch 없이 CPU)로 번역 품질 직접 확인
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
230 lines
8.7 KiB
Python
230 lines
8.7 KiB
Python
"""기본 제공 게임 용어집 팩."""
|
|
|
|
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,
|
|
find_conflicts,
|
|
get_pack,
|
|
resolve_packs,
|
|
)
|
|
|
|
#: 사용자가 "필수 게임"으로 지정한 것 — 빠지면 테스트가 잡아낸다.
|
|
REQUIRED_GAMES = {"overwatch", "watchdogs", "pubg", "r6siege"}
|
|
EXPECTED_PACKS = REQUIRED_GAMES | {
|
|
"lol", "valorant", "apex", "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_required_games_are_bundled():
|
|
"""사용자가 직접 지정한 게임은 반드시 들어 있어야 한다."""
|
|
keys = {p.key for p in available_packs()}
|
|
assert keys >= REQUIRED_GAMES, f"필수 게임 팩 누락: {REQUIRED_GAMES - 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():
|
|
def sources_of(key: str) -> set[str]:
|
|
return {e.source.casefold() for e in get_pack(key).entries}
|
|
|
|
assert {"baron", "gank", "nexus", "ult"} <= sources_of("lol")
|
|
assert {"spike", "defuse", "eco", "retake"} <= sources_of("valorant")
|
|
assert {"drone", "anchor", "roamer", "defuser", "hard breach"} <= sources_of("r6siege")
|
|
assert {"blue zone", "third party", "chicken dinner", "knocked"} <= sources_of("pubg")
|
|
assert {"dedsec", "ctos", "blume", "backdoor"} <= sources_of("watchdogs")
|
|
assert {"ring", "banner", "respawn beacon"} <= sources_of("apex")
|
|
|
|
|
|
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
|
|
|
|
|
|
# --- 팩 계층: 게임 전용이 장르 공통을 이긴다 --------------------------------
|
|
|
|
|
|
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)
|
|
# 'hacked' 는 서술어라 문장 중간에서는 치환하지 않는다 (whole_only).
|
|
_, repl = merged.protect("DedSec hacked the ctOS server", "ko")
|
|
assert repl == ["데드섹", "ctOS"]
|
|
|
|
|
|
def test_predicate_entries_only_apply_to_whole_utterance():
|
|
"""서술어를 문장 한가운데서 치환하면 번역 문법이 무너진다.
|
|
|
|
"I need ammo and a med kit." 에서 'need ammo' 를 통째로 바꾸면
|
|
"탄 필요해와 구급상자" 가 됐다. 명사만 바꾸면 "탄약과 구급상자가
|
|
필요합니다" 로 제대로 나온다 (실제 NLLB 로 확인).
|
|
"""
|
|
from livesub.config import AppConfig
|
|
|
|
merged = build_glossary(Glossary(), AppConfig().glossary.enabled_packs)
|
|
_, repl = merged.protect("I need ammo and a med kit.", "ko")
|
|
assert repl == ["탄약", "구급상자"]
|
|
|
|
# 반대로 그 말만 단독으로 나오면 통째로 바꾸는 게 자연스럽다.
|
|
_, repl = merged.protect("Cover me!", "ko")
|
|
assert repl == ["엄호해줘"]
|
|
|
|
|
|
# --- 용어가 조각나서 두 번 치환되지 않는지 -----------------------------------
|
|
|
|
|
|
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 자기장"
|