feat(i18n): enhance localization with new actions and descriptions

- Added new action translations for "assassinate", "attack", "breakthrough", "cultivate", "escape", and "self-heal" in English, Simplified Chinese, and Traditional Chinese.
- Included detailed descriptions and requirements for each action to improve gameplay clarity.
- Updated the translation extraction and compilation process to utilize the polib library for better handling of PO files.
This commit is contained in:
bridge
2026-02-05 22:41:01 +08:00
parent 7e8a737402
commit 07d1cfbee2
122 changed files with 14518 additions and 5492 deletions

View File

@@ -1,41 +1,117 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""将 PO 文件编译为 MO 文件
"""将 PO 文件编译为 MO 文件,支持模块化 PO 文件合并
使用方法:
python tools/i18n/build_mo.py
功能:
1. 扫描 src/i18n/locales 下的语言目录
2. 如果存在 modules/ 目录,将所有 .po 文件合并
3. 生成/更新 LC_MESSAGES/messages.po (作为合并后的完整文件)
4. 编译生成 LC_MESSAGES/messages.mo
5. 同时处理其他独立的 .po 文件 (如 game_configs.po)
"""
import sys
import shutil
from pathlib import Path
def compile_po_to_mo(po_file: Path) -> bool:
"""使用 Python polib 库编译 PO 文件为 MO 文件"""
def compile_modules(lang_dir: Path) -> bool:
"""
编译该语言目录下的模块
Args:
lang_dir: 语言目录,如 src/i18n/locales/zh_CN
Returns:
bool: 是否成功
"""
try:
import polib
except ImportError:
print("[ERROR] polib 库未安装。请运行 pip install polib 安装。")
return False
mo_file = po_file.with_suffix('.mo')
try:
po = polib.pofile(str(po_file))
po.save_as_mofile(str(mo_file))
print(f"[OK] {po_file.relative_to(Path.cwd())} -> {mo_file.name}")
return True
except Exception as e:
print(f"[ERROR] 编译失败: {po_file}")
print(f" 错误信息: {e}")
return False
lc_messages_dir = lang_dir / "LC_MESSAGES"
lc_messages_dir.mkdir(parents=True, exist_ok=True)
modules_dir = lang_dir / "modules"
# 1. 处理 messages.po (可能来自 modules 拆分,也可能就是单个文件)
if modules_dir.exists() and list(modules_dir.glob("*.po")):
print(f" [合并] 发现模块化文件: {lang_dir.name}/modules/ -> messages.po")
# 创建一个新的 PO 对象
merged_po = polib.POFile()
# 收集所有模块文件
module_files = sorted(list(modules_dir.glob("*.po")))
# 为了保留 metadata尝试先读取 common.po 或 misc.po或者直接从第一个文件读
# 最好是如果你有专门的 header.po这里我们直接用第一个文件的 metadata
if module_files:
try:
first_po = polib.pofile(str(module_files[0]))
merged_po.metadata = first_po.metadata
except:
pass
# 遍历合并
count = 0
for po_file in module_files:
try:
po = polib.pofile(str(po_file))
for entry in po:
# 检查是否重复 (简单去重)
# 注意:如果 key 重复polib 默认可能不会报错,但这里我们 append
# 真实场景可能需要 merge 逻辑,这里假设 modules 之间无交集
merged_po.append(entry)
count += 1
except Exception as e:
print(f" [警告] 读取 {po_file.name} 失败: {e}")
print(f" - 合并了 {count} 个文件,共 {len(merged_po)} 条目")
# 保存合并后的 messages.po (方便查看和作为中间文件)
merged_po_path = lc_messages_dir / "messages.po"
merged_po.save(str(merged_po_path))
# 编译为 MO
merged_mo_path = lc_messages_dir / "messages.mo"
merged_po.save_as_mofile(str(merged_mo_path))
print(f" - 生成: {merged_mo_path.name}")
else:
# 没有 modules尝试直接编译现有的 messages.po
legacy_po = lc_messages_dir / "messages.po"
if legacy_po.exists():
print(f" [编译] {lang_dir.name}/messages.po")
try:
po = polib.pofile(str(legacy_po))
po.save_as_mofile(str(legacy_po.with_suffix('.mo')))
except Exception as e:
print(f" [错误] {e}")
return False
# 2. 处理其他独立的 PO 文件 (如 game_configs.po)
# 只要不是 messages.po (上面已经处理过),都单独编译
for po_file in lc_messages_dir.glob("*.po"):
if po_file.name == "messages.po":
continue
print(f" [编译] {po_file.name}")
try:
po = polib.pofile(str(po_file))
po.save_as_mofile(str(po_file.with_suffix('.mo')))
except Exception as e:
print(f" [错误] {e}")
return True
def main():
"""主函数:查找所有 PO 文件并编译为 MO 文件"""
print("="*60)
print("编译 PO 文件为 MO 文件")
print("构建 i18n 文件 (Module -> PO -> MO)")
print("="*60)
# 查找项目根目录
@@ -47,37 +123,23 @@ def main():
print(f"[ERROR] 找不到 i18n 目录: {i18n_dir}")
sys.exit(1)
# 查找所有 PO 文件
po_files = list(i18n_dir.rglob("*.po"))
if not po_files:
print(f"[WARNING] 未找到 PO 文件")
sys.exit(0)
print(f"\n找到 {len(po_files)} 个 PO 文件:")
for po_file in po_files:
print(f" - {po_file.relative_to(project_root)}")
print("\n开始编译...")
print("-"*60)
success_count = 0
for po_file in po_files:
if compile_po_to_mo(po_file):
success_count += 1
# 输出结果
print("-"*60)
print(f"\n编译完成: {success_count}/{len(po_files)} 成功")
if success_count == len(po_files):
print("\n[OK] 所有 PO 文件已成功编译为 MO 文件")
# 遍历语言目录
success = True
for lang_dir in i18n_dir.iterdir():
if not lang_dir.is_dir() or lang_dir.name == "templates":
continue
print(f"\n处理语言: {lang_dir.name}")
if not compile_modules(lang_dir):
success = False
print("-" * 60)
if success:
print("\n[OK] 所有语言包构建完成")
return 0
else:
print(f"\n[WARNING] {len(po_files) - success_count} 个文件编译失败")
print("\n[FAIL] 构建过程中出现错误")
return 1
if __name__ == "__main__":
sys.exit(main())

169
tools/i18n/split_po.py Normal file
View File

@@ -0,0 +1,169 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Split messages.po into multiple modules based on comments.
"""
import os
import re
import polib
from pathlib import Path
def get_category_from_comment(comment):
"""
Extract category from translator comment like "Battle messages"
Returns lower_case_category_name or None
"""
if not comment:
return None
content = ""
lines = comment.split('\n')
for line in lines:
line = line.strip()
if not line:
continue
# Polib usually strips the '# ' prefix for tcomment
# But we handle both cases just to be safe
if line.startswith('#'):
content = line.lstrip('#').strip()
else:
content = line.strip()
if not content:
continue
# Priority Keyword Matching
# This handles cases like "Battle messages", "Battle - action", "Action: Attack"
# Also handles "Effect 系统" (Effect System) which contains Chinese characters
keywords = {
'Battle': 'battle',
'Fortune': 'fortune',
'Misfortune': 'misfortune',
'MutualAction': 'mutual_action', # Must be before 'Action'
'Action': 'action',
'Effect': 'effect',
'Avatar': 'avatar',
'Gathering': 'gathering',
'Cultivation': 'cultivation',
'Technique': 'technique',
'Weapon': 'weapon',
'Auxiliary': 'auxiliary',
'Elixir': 'elixir',
'Sect': 'sect',
'SingleChoice': 'single_choice',
'Single choice': 'single_choice',
'Frontend': 'ui',
'Simulator': 'simulator',
'Map': 'map',
'Region': 'map',
'Relation': 'relation',
'Root': 'root_element',
'Appearance': 'appearance',
'Hidden Domain': 'hidden_domain',
'Story Styles': 'story_styles',
'Death reasons': 'death_reasons',
'Item exchange': 'item_exchange',
'Alignment': 'alignment',
'Gender': 'gender',
'Essence Type': 'essence_type',
'Realm': 'realm',
'Stage': 'stage',
'Direction names': 'direction_names',
'Feedback labels': 'feedback_labels',
'Labels': 'labels',
'LLM Prompt': 'llm_prompt',
'History': 'history',
}
for key, val in keywords.items():
if key in content:
return val
# If it contains non-ASCII characters and didn't match keywords, dump to misc
if any(ord(c) > 127 for c in content):
return 'misc'
# Fallback: simple snake case for English titles
# Take the first part before ' - ' or ':'
parts = re.split(r' [-:] ', content)
main_part = parts[0].strip()
if len(main_part) < 30 and all(c.isalnum() or c == '_' or c == ' ' for c in main_part):
return main_part.lower().replace(' ', '_')
return None
def split_po_file(po_path: Path):
print(f"Processing {po_path}...")
try:
po = polib.pofile(str(po_path))
except Exception as e:
print(f"Error reading {po_path}: {e}")
return
# Prepare modules directory
modules_dir = po_path.parent.parent / "modules"
# Clean up existing modules if any, to avoid left-over garbage files
if modules_dir.exists():
for f in modules_dir.glob("*.po"):
f.unlink()
else:
modules_dir.mkdir(exist_ok=True)
# Store entries by category
categories = {} # category_name -> list[Entry]
current_category = "common"
for entry in po:
# Try to determine category from translator comment
new_category = get_category_from_comment(entry.tcomment)
if new_category:
current_category = new_category
if current_category not in categories:
categories[current_category] = []
categories[current_category].append(entry)
# Write files
sorted_cats = sorted(categories.keys())
print(f" Split into {len(categories)} categories: {', '.join(sorted_cats)}")
for category in sorted_cats:
entries = categories[category]
# Create new PO file with same metadata
new_po = polib.POFile()
new_po.metadata = po.metadata
# Copy entries
for entry in entries:
new_po.append(entry)
out_path = modules_dir / f"{category}.po"
new_po.save(str(out_path))
# print(f" -> {out_path.name} ({len(entries)} entries)")
def main():
root_dir = Path("src/i18n/locales")
if not root_dir.exists():
print(f"Directory not found: {root_dir}")
return
for lang_dir in root_dir.iterdir():
if not lang_dir.is_dir() or lang_dir.name == "templates":
continue
po_file = lang_dir / "LC_MESSAGES" / "messages.po"
if po_file.exists():
split_po_file(po_file)
else:
print(f"Skipping {lang_dir.name}: messages.po not found")
if __name__ == "__main__":
main()