Some checks failed
Windows / verify (push) Has been cancelled
`models/` 처럼 슬래시 없이 쓴 규칙은 깊이에 상관없이 같은 이름의 폴더를 전부 무시한다. 의도는 루트의 모델 캐시였는데 소스 패키지까지 같이 걸렸고, 그래서 asr/translator/manager/tiers/glossary/packs/speech_level 8개 파일이 한 번도 커밋된 적이 없다. 증상: Gitea 에서 clone 하면 `ModuleNotFoundError: No module named 'livesub.models'` 로 앱이 아예 임포트되지 않는다. 로컬 작업 트리에는 파일이 있으니 개발 중에는 절대 안 보인다. 방금 붙인 Windows CI VM 이 첫 검증에서 바로 잡아냈다. /models/, /adapters/, /data/ 로 루트에 고정하고 빠진 파일을 추가한다.
153 lines
5.2 KiB
Python
153 lines
5.2 KiB
Python
"""기본 제공 게임 용어집 팩.
|
|
|
|
`resources/glossaries/*.json` 에 게임별로 묶어둔 용어를 읽어, 사용자가 켠 팩만
|
|
사용자 용어집과 합쳐 하나의 `Glossary` 로 만든다.
|
|
|
|
합칠 때 **사용자가 직접 등록한 항목이 항상 이긴다.** 기본 팩의 역어가 마음에
|
|
안 들면 용어집 화면에서 같은 단어를 등록하면 그쪽이 적용된다.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
from dataclasses import dataclass
|
|
from functools import lru_cache
|
|
from pathlib import Path
|
|
|
|
from .glossary import Glossary, GlossaryEntry
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
PACK_DIR = Path(__file__).resolve().parent.parent / "resources" / "glossaries"
|
|
|
|
|
|
#: 여러 팩을 동시에 켰을 때 같은 단어의 역어가 갈리는 것을 막기 위한 계층.
|
|
#: 숫자가 클수록 나중에 적용되어 이긴다.
|
|
SCOPE_PRIORITY = {"generic": 0, "game": 1}
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class GlossaryPack:
|
|
key: str
|
|
name: str
|
|
description: str
|
|
entries: tuple[GlossaryEntry, ...]
|
|
#: "generic" = 장르 공통, "game" = 특정 게임 전용
|
|
scope: str = "game"
|
|
|
|
def __len__(self) -> int:
|
|
return len(self.entries)
|
|
|
|
@property
|
|
def priority(self) -> int:
|
|
return SCOPE_PRIORITY.get(self.scope, 1)
|
|
|
|
@property
|
|
def is_generic(self) -> bool:
|
|
return self.scope == "generic"
|
|
|
|
|
|
@lru_cache(maxsize=1)
|
|
def available_packs() -> tuple[GlossaryPack, ...]:
|
|
"""번들된 팩 목록. 파일이 깨져 있으면 그 팩만 건너뛴다."""
|
|
if not PACK_DIR.is_dir():
|
|
return ()
|
|
packs: list[GlossaryPack] = []
|
|
for path in sorted(PACK_DIR.glob("*.json")):
|
|
try:
|
|
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
except (OSError, json.JSONDecodeError) as exc:
|
|
log.warning("용어집 팩을 읽지 못했습니다 (%s): %s", path.name, exc)
|
|
continue
|
|
entries = tuple(
|
|
GlossaryEntry(
|
|
source=item["source"],
|
|
targets=dict(item.get("targets", {})),
|
|
note=raw.get("name", path.stem),
|
|
whole_only=bool(item.get("whole_only", False)),
|
|
)
|
|
for item in raw.get("entries", [])
|
|
if item.get("source")
|
|
)
|
|
if not entries:
|
|
continue
|
|
packs.append(
|
|
GlossaryPack(
|
|
key=raw.get("key", path.stem),
|
|
name=raw.get("name", path.stem),
|
|
description=raw.get("description", ""),
|
|
entries=entries,
|
|
scope=raw.get("scope", "game"),
|
|
)
|
|
)
|
|
return tuple(packs)
|
|
|
|
|
|
def get_pack(key: str) -> GlossaryPack | None:
|
|
for pack in available_packs():
|
|
if pack.key == key:
|
|
return pack
|
|
return None
|
|
|
|
|
|
def resolve_packs(enabled_packs: list[str]) -> list[GlossaryPack]:
|
|
"""켜둔 팩을 적용 순서대로 돌려준다 (범용 먼저, 게임 전용 나중).
|
|
|
|
`knocked` 는 FPS 공통에서 "기절", 배그에서 "눕혔다"다. 어느 쪽이 맞는지는
|
|
지금 무슨 게임을 하느냐로 갈리므로, **게임 전용 팩이 항상 범용을 이겨야**
|
|
한다. 그렇지 않으면 체크박스를 누른 순서에 따라 결과가 달라진다.
|
|
"""
|
|
packs: list[GlossaryPack] = []
|
|
for key in enabled_packs:
|
|
pack = get_pack(key)
|
|
if pack is None:
|
|
log.warning("알 수 없는 용어집 팩입니다: %s", key)
|
|
continue
|
|
packs.append(pack)
|
|
# 같은 계층 안에서는 사용자가 켠 순서를 유지한다 (stable sort).
|
|
return sorted(packs, key=lambda p: p.priority)
|
|
|
|
|
|
def find_conflicts(enabled_packs: list[str], lang: str = "ko") -> dict[str, list[tuple[str, str]]]:
|
|
"""켜둔 게임 전용 팩끼리 역어가 갈리는 단어를 찾는다.
|
|
|
|
범용 팩은 게임 팩에 확실히 지므로 충돌로 보지 않는다. 게임 팩 둘 이상이
|
|
같은 단어를 다르게 번역하면 그건 사용자가 판단해야 할 문제라 UI로 알린다.
|
|
"""
|
|
seen: dict[str, list[tuple[str, str]]] = {}
|
|
for pack in resolve_packs(enabled_packs):
|
|
if pack.is_generic:
|
|
continue
|
|
for entry in pack.entries:
|
|
target = entry.target_for(lang)
|
|
if not target:
|
|
continue
|
|
seen.setdefault(entry.source.casefold(), []).append((pack.name, target))
|
|
return {
|
|
source: owners
|
|
for source, owners in seen.items()
|
|
if len({t for _, t in owners}) > 1
|
|
}
|
|
|
|
|
|
def build_glossary(
|
|
user_glossary: Glossary,
|
|
enabled_packs: list[str],
|
|
case_sensitive: bool = False,
|
|
) -> Glossary:
|
|
"""켜둔 팩 + 사용자 용어집을 하나로 합친다.
|
|
|
|
적용 순서: 범용 팩 → 게임 전용 팩 → 사용자 항목.
|
|
뒤에 오는 쪽이 이기므로 사용자가 직접 등록한 것이 항상 최우선이다.
|
|
"""
|
|
merged: list[GlossaryEntry] = []
|
|
for pack in resolve_packs(enabled_packs):
|
|
merged.extend(pack.entries)
|
|
merged.extend(user_glossary.entries)
|
|
|
|
combined = Glossary(case_sensitive=case_sensitive)
|
|
for entry in merged:
|
|
combined.add(entry) # add() 가 같은 원문을 교체해준다
|
|
return combined
|