diff --git a/src/localizer/adapters/resources/unreal_locres.py b/src/localizer/adapters/resources/unreal_locres.py new file mode 100644 index 0000000..918907b --- /dev/null +++ b/src/localizer/adapters/resources/unreal_locres.py @@ -0,0 +1,404 @@ +from __future__ import annotations + +import io +import json +import struct +from dataclasses import dataclass, replace +from pathlib import Path +from typing import Any, Mapping, Optional, Sequence, Tuple + +from localizer.adapters.resources.options import AdapterOptionsModel, normalize_options +from localizer.adapters.resources.registry import register_adapter +from localizer.domain.translation_unit import TranslationUnit +from localizer.infrastructure.atomic_io import AtomicIO +from localizer.ports.resource import RenderResult, ResourceDescriptor, ValidationResult +from localizer.rules.placeholder import register_placeholder_syntax + + +LOCRES_MAGIC = bytes.fromhex("0e147475674a03fc4a15909dc3377f1b") +LOCRES_VERSION_OPTIMIZED_CITYHASH64_UTF16 = 3 + +# Unreal RichText allows a shorthand close tag (``), which the generic +# `` pattern intentionally does not match. +UNREAL_LOCRES_PLACEHOLDERS: Tuple[str, ...] = ( + r"", +) + +register_placeholder_syntax("unreal_locres", UNREAL_LOCRES_PLACEHOLDERS) + + +@dataclass(frozen=True) +class _LocresEntry: + key_hash: int + key: str + source_string_hash: int + value: str + + +@dataclass(frozen=True) +class _LocresNamespace: + namespace_hash: int + name: str + entries: Tuple[_LocresEntry, ...] + + +@dataclass(frozen=True) +class _LocresV3: + namespaces: Tuple[_LocresNamespace, ...] + + @property + def entry_count(self) -> int: + return sum(len(namespace.entries) for namespace in self.namespaces) + + +class _Reader: + def __init__(self, data: bytes) -> None: + self.data = data + self.pos = 0 + + def seek(self, offset: int) -> None: + if offset < 0 or offset > len(self.data): + raise ValueError(f"locres offset out of bounds: {offset}") + self.pos = offset + + def read(self, size: int) -> bytes: + if size < 0 or self.pos + size > len(self.data): + raise ValueError("truncated locres") + value = self.data[self.pos : self.pos + size] + self.pos += size + return value + + def u8(self) -> int: + return self.read(1)[0] + + def i32(self) -> int: + return struct.unpack(" int: + return struct.unpack(" int: + return struct.unpack(" str: + length = self.i32() + if length == 0: + return "" + if length > 0: + raw = self.read(length) + if not raw.endswith(b"\x00"): + raise ValueError("ANSI FString is missing its terminator") + try: + return raw[:-1].decode("ascii") + except UnicodeDecodeError as exc: + raise ValueError("locres ANSI FString is not ASCII") from exc + + code_units = -length + raw = self.read(code_units * 2) + if not raw.endswith(b"\x00\x00"): + raise ValueError("UTF-16 FString is missing its terminator") + try: + return raw[:-2].decode("utf-16-le") + except UnicodeDecodeError as exc: + raise ValueError("invalid UTF-16 FString") from exc + + +def _write_fstring(stream: io.BytesIO, value: str) -> None: + if "\x00" in value: + raise ValueError("locres strings cannot contain embedded NUL") + if all(ord(char) <= 0x7F for char in value): + payload = value.encode("ascii") + b"\x00" + stream.write(struct.pack(" _LocresV3: + reader = _Reader(data) + if reader.read(len(LOCRES_MAGIC)) != LOCRES_MAGIC: + raise ValueError("unsupported legacy locres: missing magic") + + version = reader.u8() + if version != LOCRES_VERSION_OPTIMIZED_CITYHASH64_UTF16: + raise ValueError( + f"unsupported locres version {version}; unreal_locres v1 supports version 3" + ) + + string_table_offset = reader.i64() + entry_count = reader.i32() + namespace_count = reader.i32() + if entry_count < 0 or namespace_count < 0: + raise ValueError("locres contains negative counts") + + namespace_headers = [] + actual_entries = 0 + for _ in range(namespace_count): + namespace_hash = reader.u32() + namespace = reader.fstring() + key_count = reader.i32() + if key_count < 0: + raise ValueError("locres namespace contains a negative key count") + entries = [] + for _ in range(key_count): + key_hash = reader.u32() + key = reader.fstring() + source_string_hash = reader.u32() + string_index = reader.i32() + entries.append((key_hash, key, source_string_hash, string_index)) + actual_entries += 1 + namespace_headers.append((namespace_hash, namespace, entries)) + + if actual_entries != entry_count: + raise ValueError( + f"locres entry count mismatch: header={entry_count}, parsed={actual_entries}" + ) + if reader.pos != string_table_offset: + raise ValueError( + "locres v3 string-table offset does not match the end of the key table" + ) + + reader.seek(string_table_offset) + string_count = reader.i32() + if string_count < 0: + raise ValueError("locres contains a negative string-table count") + strings = [] + ref_counts = [] + for _ in range(string_count): + strings.append(reader.fstring()) + ref_count = reader.i32() + if ref_count < 0: + raise ValueError("locres contains a negative string reference count") + ref_counts.append(ref_count) + + if reader.pos != len(data): + raise ValueError("locres has unexpected trailing bytes") + + actual_ref_counts = [0] * string_count + namespaces = [] + seen_coordinates = set() + for namespace_hash, namespace, raw_entries in namespace_headers: + entries = [] + for key_hash, key, source_string_hash, string_index in raw_entries: + if string_index < 0 or string_index >= string_count: + raise ValueError(f"locres string index out of range: {string_index}") + coordinate = (namespace, key) + if coordinate in seen_coordinates: + raise ValueError(f"duplicate locres coordinate: {coordinate!r}") + seen_coordinates.add(coordinate) + actual_ref_counts[string_index] += 1 + entries.append( + _LocresEntry( + key_hash=key_hash, + key=key, + source_string_hash=source_string_hash, + value=strings[string_index], + ) + ) + namespaces.append( + _LocresNamespace( + namespace_hash=namespace_hash, + name=namespace, + entries=tuple(entries), + ) + ) + + if actual_ref_counts != ref_counts: + raise ValueError("locres string-table reference counts are inconsistent") + + return _LocresV3(tuple(namespaces)) + + +def _dump_locres_v3(resource: _LocresV3) -> bytes: + stream = io.BytesIO() + stream.write(LOCRES_MAGIC) + stream.write(bytes((LOCRES_VERSION_OPTIMIZED_CITYHASH64_UTF16,))) + string_table_offset_pos = stream.tell() + stream.write(struct.pack(" str: + return json.dumps([namespace, key], ensure_ascii=False, separators=(",", ":")) + + +def _decode_logical_key(value: str) -> Tuple[str, str]: + try: + decoded = json.loads(value) + except json.JSONDecodeError as exc: + raise ValueError(f"invalid unreal_locres logical_key: {value!r}") from exc + if ( + not isinstance(decoded, list) + or len(decoded) != 2 + or not all(isinstance(item, str) for item in decoded) + ): + raise ValueError(f"invalid unreal_locres logical_key: {value!r}") + return decoded[0], decoded[1] + + +@register_adapter +class UnrealLocresAdapter: + adapter_id = "unreal_locres" + options_model = AdapterOptionsModel + + def __init__( + self, + *, + project_id: str, + source_root: Path, + source_locale: str, + target_locale: str, + options: Optional[Mapping[str, Any]] = None, + ) -> None: + self.options = normalize_options(self.options_model, options) + self.project_id = project_id + self.source_root = Path(source_root).resolve() + self.source_locale = source_locale + self.target_locale = target_locale + + def probe(self, path: Path) -> float: + candidate = Path(path) + if candidate.suffix.lower() != ".locres" or not candidate.is_file(): + return 0.0 + try: + _load_locres_v3(AtomicIO.read_bytes(candidate)) + except (OSError, ValueError): + return 0.0 + return 1.0 + + def scan(self, path: Path) -> ResourceDescriptor: + candidate = Path(path).resolve(strict=True) + confidence = self.probe(candidate) + if confidence == 0: + raise ValueError(f"not a supported Unreal locres v3 resource: {candidate}") + return ResourceDescriptor( + self.adapter_id, + candidate, + self._relative(candidate), + candidate.stat().st_size, + confidence, + ) + + def extract(self, path: Path) -> Sequence[TranslationUnit]: + candidate = Path(path).resolve(strict=True) + resource = _load_locres_v3(AtomicIO.read_bytes(candidate)) + relative = self._relative(candidate) + units = [] + for namespace in resource.namespaces: + for entry in namespace.entries: + units.append( + TranslationUnit( + project_id=self.project_id, + adapter_id=self.adapter_id, + relative_path=relative, + logical_file=relative, + logical_key=_logical_key(namespace.name, entry.key), + source_text=entry.value, + translation=None, + context=f"{namespace.name} / {entry.key}" + if namespace.name + else entry.key, + source_locale=self.source_locale, + target_locale=self.target_locale, + metadata={ + "namespace": namespace.name, + "key": entry.key, + "locres_version": LOCRES_VERSION_OPTIMIZED_CITYHASH64_UTF16, + "source_string_hash": entry.source_string_hash, + "namespace_hash": namespace.namespace_hash, + "key_hash": entry.key_hash, + }, + ) + ) + return tuple(units) + + def render( + self, units: Sequence[TranslationUnit], source: Path, destination: Path + ) -> RenderResult: + source_path = Path(source).resolve(strict=True) + resource = _load_locres_v3(AtomicIO.read_bytes(source_path)) + + source_entries = { + (namespace.name, entry.key) + for namespace in resource.namespaces + for entry in namespace.entries + } + translations = {} + for unit in units: + coordinate = _decode_logical_key(unit.logical_key) + if coordinate not in source_entries: + raise ValueError( + f"unreal_locres unit does not exist in source: {coordinate!r}" + ) + if coordinate in translations: + raise ValueError(f"duplicate unreal_locres unit: {coordinate!r}") + if unit.translation is not None: + translations[coordinate] = unit.translation + + namespaces = [] + for namespace in resource.namespaces: + entries = [] + for entry in namespace.entries: + value = translations.get((namespace.name, entry.key), entry.value) + entries.append(replace(entry, value=value)) + namespaces.append(replace(namespace, entries=tuple(entries))) + + destination_path = AtomicIO.write_bytes( + Path(destination), _dump_locres_v3(_LocresV3(tuple(namespaces))) + ) + validation = self.validate(destination_path) + return RenderResult(destination_path, len(units), validation) + + def validate(self, path: Path) -> ValidationResult: + try: + _load_locres_v3(AtomicIO.read_bytes(Path(path))) + except (OSError, ValueError) as exc: + return ValidationResult(False, (str(exc),)) + return ValidationResult(True) + + def _relative(self, path: Path) -> str: + try: + return path.relative_to(self.source_root).as_posix() + except ValueError as exc: + raise ValueError( + f"resource is outside source root {self.source_root}: {path}" + ) from exc diff --git a/tests/test_unreal_locres_adapter.py b/tests/test_unreal_locres_adapter.py new file mode 100644 index 0000000..bc96a68 --- /dev/null +++ b/tests/test_unreal_locres_adapter.py @@ -0,0 +1,186 @@ +from __future__ import annotations + +import tempfile +import unittest +from dataclasses import replace +from pathlib import Path + +from localizer.adapters.resources.registry import available_adapters +from localizer.adapters.resources.unreal_locres import ( + LOCRES_VERSION_OPTIMIZED_CITYHASH64_UTF16, + UnrealLocresAdapter, + _LocresEntry, + _LocresNamespace, + _LocresV3, + _dump_locres_v3, +) +from localizer.rules.placeholder import PlaceholderRule + + +def _fixture() -> _LocresV3: + return _LocresV3( + ( + _LocresNamespace( + namespace_hash=101, + name="ST_A", + entries=( + _LocresEntry( + key_hash=201, + key="Label", + source_string_hash=301, + value="{PlayerName}", + ), + _LocresEntry( + key_hash=202, + key="Plural", + source_string_hash=302, + value="Add {Quantity}|plural(one=Salute,other=Salutes)", + ), + ), + ), + _LocresNamespace( + namespace_hash=102, + name="ST_B", + entries=( + _LocresEntry( + key_hash=203, + key="Label", + source_string_hash=303, + value="Ability", + ), + ), + ), + ) + ) + + +def _semantic(units): + return tuple( + ( + unit.logical_key, + unit.source_text, + unit.metadata["source_string_hash"], + unit.metadata["namespace_hash"], + unit.metadata["key_hash"], + ) + for unit in units + ) + + +class UnrealLocresAdapterTest(unittest.TestCase): + def setUp(self) -> None: + self._temp = tempfile.TemporaryDirectory() + self.root = Path(self._temp.name) + self.adapter = UnrealLocresAdapter( + project_id="tyr", + source_root=self.root, + source_locale="en", + target_locale="zh-Hans", + options={}, + ) + + def tearDown(self) -> None: + self._temp.cleanup() + + def _write_fixture(self, relative: str = "source/Game.locres") -> Path: + source = self.root / relative + source.parent.mkdir(parents=True, exist_ok=True) + source.write_bytes(_dump_locres_v3(_fixture())) + return source + + def test_is_discovered_and_extracts_stable_namespace_key_identity(self) -> None: + self.assertIn("unreal_locres", available_adapters()) + source = self._write_fixture( + "Tyr/Content/Localization/Game/en/Game.locres" + ) + + self.assertEqual(self.adapter.probe(source), 1.0) + self.assertEqual( + self.adapter.scan(source).relative_path, + "Tyr/Content/Localization/Game/en/Game.locres", + ) + + units = self.adapter.extract(source) + self.assertEqual(len(units), 3) + self.assertEqual(units[0].logical_key, '["ST_A","Label"]') + self.assertEqual(units[2].logical_key, '["ST_B","Label"]') + self.assertNotEqual(units[0].stable_identity, units[2].stable_identity) + self.assertIsNone(units[0].translation) + self.assertEqual( + units[0].metadata["locres_version"], + LOCRES_VERSION_OPTIMIZED_CITYHASH64_UTF16, + ) + + def test_noop_render_is_byte_identical_and_semantically_equal(self) -> None: + source = self._write_fixture() + original = source.read_bytes() + + before = self.adapter.extract(source) + destination = self.root / "rendered/Game.locres" + result = self.adapter.render(before, source, destination) + + self.assertTrue(result.validation.valid) + self.assertEqual(destination.read_bytes(), original) + after = self.adapter.extract(destination) + self.assertEqual(_semantic(after), _semantic(before)) + + def test_single_entry_mutation_preserves_unrelated_entries_and_hashes(self) -> None: + source = self._write_fixture() + before = self.adapter.extract(source) + changed = tuple( + replace(unit, translation="{PlayerName},你好") + if unit.logical_key == '["ST_A","Label"]' + else unit + for unit in before + ) + + destination = self.root / "rendered/Game.locres" + result = self.adapter.render(changed, source, destination) + self.assertTrue(result.validation.valid) + + after = self.adapter.extract(destination) + differences = [ + (left, right) + for left, right in zip(before, after) + if left.source_text != right.source_text + ] + self.assertEqual(len(differences), 1) + original, translated = differences[0] + self.assertEqual( + original.logical_key, + translated.logical_key, + ) + self.assertEqual(translated.logical_key, '["ST_A","Label"]') + self.assertEqual(translated.source_text, "{PlayerName},你好") + self.assertEqual(translated.metadata, original.metadata) + + unchanged_before = [ + unit for unit in before if unit.logical_key != '["ST_A","Label"]' + ] + unchanged_after = [ + unit for unit in after if unit.logical_key != '["ST_A","Label"]' + ] + self.assertEqual(_semantic(unchanged_after), _semantic(unchanged_before)) + + def test_placeholder_profile_covers_richtext_shorthand_close(self) -> None: + rule = PlaceholderRule.for_adapter("unreal_locres") + self.assertEqual( + rule.extract("{PlayerName}"), + ("", "{PlayerName}", ""), + ) + self.assertTrue(rule.round_trip("{PlayerName}")) + + def test_v1_fails_closed_on_other_versions(self) -> None: + source = self.root / "Game.locres" + payload = bytearray(_dump_locres_v3(_fixture())) + payload[16] = 2 + source.write_bytes(payload) + + self.assertEqual(self.adapter.probe(source), 0.0) + validation = self.adapter.validate(source) + self.assertFalse(validation.valid) + self.assertIn("supports version 3", validation.errors[0]) + + +if __name__ == "__main__": + unittest.main()