319 lines
8.6 KiB
Markdown
319 lines
8.6 KiB
Markdown
# OpenClaw 国际化 (I18N) 文档
|
||
|
||
## 概述
|
||
|
||
OpenClaw 仪表板支持多语言国际化,当前已实现:
|
||
|
||
- **中文 (zh)** - 默认语言
|
||
- **英文 (en)** - 备选语言
|
||
|
||
## 已汉化文件清单
|
||
|
||
### 后端文件
|
||
|
||
| 文件路径 | 汉化内容 |
|
||
|---------|---------|
|
||
| `src/openclaw/dashboard/app.py` | API 响应消息、警报标题、WebSocket 消息类型 |
|
||
| `src/openclaw/dashboard/models.py` | 字段描述(docstrings) |
|
||
|
||
### 前端文件
|
||
|
||
| 文件路径 | 汉化内容 |
|
||
|---------|---------|
|
||
| `src/openclaw/dashboard/templates/index.html` | 页面标题、导航、指标标签、图表标题、表格列头、状态文本 |
|
||
| `src/openclaw/dashboard/templates/config.html` | 页面标题、导航、配置项标签、按钮文本、状态消息 |
|
||
| `src/openclaw/dashboard/static/config.js` | 加载/保存状态消息、控制台日志、成功/错误提示 |
|
||
|
||
### 国际化工具
|
||
|
||
| 文件路径 | 说明 |
|
||
|---------|------|
|
||
| `src/openclaw/dashboard/i18n.py` | 国际化支持类,提供双语翻译字典 |
|
||
|
||
## 使用国际化工具
|
||
|
||
### 基础用法
|
||
|
||
```python
|
||
from openclaw.dashboard.i18n import I18n, t
|
||
|
||
# 创建实例(默认中文)
|
||
i18n = I18n()
|
||
|
||
# 获取翻译
|
||
title = i18n.t("status.agent_bankrupt") # "代理破产"
|
||
|
||
# 切换语言
|
||
i18n.set_language("en")
|
||
title = i18n.t("status.agent_bankrupt") # "Agent Bankrupt"
|
||
```
|
||
|
||
### 字符串插值
|
||
|
||
```python
|
||
# 支持变量替换
|
||
msg = i18n.t("alert.bankruptcy_msg", agent_id="bull_001")
|
||
# 中文: "代理 bull_001 已破产!"
|
||
# 英文: "Agent bull_001 has gone bankrupt!"
|
||
```
|
||
|
||
### 使用全局快捷函数
|
||
|
||
```python
|
||
from openclaw.dashboard.i18n import t, set_language
|
||
|
||
# 使用默认实例
|
||
text = t("metrics.system_equity") # "系统权益"
|
||
|
||
# 切换全局语言
|
||
set_language("en")
|
||
text = t("metrics.system_equity") # "System Equity"
|
||
```
|
||
|
||
## 翻译键值参考
|
||
|
||
### 状态消息 (`status`)
|
||
|
||
| 键值 | 中文 | 英文 |
|
||
|-----|------|------|
|
||
| `status.agent_bankrupt` | 代理破产 | Agent Bankrupt |
|
||
| `status.large_loss_detected` | 检测到重大损失 | Large Loss Detected |
|
||
| `status.config_saved` | 配置已保存 | Configuration Saved |
|
||
| `status.loading_config` | 正在加载配置... | Loading Configuration... |
|
||
| `status.confirm` | 已确认 | Confirmed |
|
||
| `status.not_found` | 未找到 | Not Found |
|
||
| `status.realtime` | 实时 | Realtime |
|
||
| `status.disconnected` | 已断开 | Disconnected |
|
||
|
||
### 导航 (`nav`)
|
||
|
||
| 键值 | 中文 | 英文 |
|
||
|-----|------|------|
|
||
| `nav.dashboard` | 仪表盘 | Dashboard |
|
||
| `nav.config` | 配置 | Configuration |
|
||
| `nav.overview` | 总览 | Overview |
|
||
|
||
### 指标 (`metrics`)
|
||
|
||
| 键值 | 中文 | 英文 |
|
||
|-----|------|------|
|
||
| `metrics.system_equity` | 系统权益 | System Equity |
|
||
| `metrics.total_pnl` | 总盈亏 | Total P&L |
|
||
| `metrics.active_agents` | 活跃 Agent | Active Agents |
|
||
| `metrics.total_trades` | 总交易数 | Total Trades |
|
||
| `metrics.avg_win_rate` | 平均胜率 | Avg Win Rate |
|
||
|
||
### 代理状态 (`agent`)
|
||
|
||
| 键值 | 中文 | 英文 |
|
||
|-----|------|------|
|
||
| `agent.status` | 状态 | Status |
|
||
| `agent.balance` | 余额 | Balance |
|
||
| `agent.win_rate` | 胜率 | Win Rate |
|
||
| `agent.trades` | 交易数 | Trades |
|
||
| `agent.thriving` | 🚀 繁荣 | 🚀 Thriving |
|
||
| `agent.stable` | 💪 稳定 | 💪 Stable |
|
||
| `agent.struggling` | ⚠️ 困难 | ⚠️ Struggling |
|
||
| `agent.critical` | 🔴 危急 | 🔴 Critical |
|
||
| `agent.bankrupt` | 💀 破产 | 💀 Bankrupt |
|
||
|
||
### 交易 (`trade`)
|
||
|
||
| 键值 | 中文 | 英文 |
|
||
|-----|------|------|
|
||
| `trade.recent_trades` | 最近交易 | Recent Trades |
|
||
| `trade.time` | 时间 | Time |
|
||
| `trade.symbol` | 交易对 | Symbol |
|
||
| `trade.side` | 方向 | Side |
|
||
| `trade.buy` | 买入 | BUY |
|
||
| `trade.sell` | 卖出 | SELL |
|
||
| `trade.pnl` | 盈亏 | P&L |
|
||
|
||
### 警报 (`alert`)
|
||
|
||
| 键值 | 中文 | 英文 |
|
||
|-----|------|------|
|
||
| `alert.title` | 警报 | Alert |
|
||
| `alert.critical` | 严重 | Critical |
|
||
| `alert.error` | 错误 | Error |
|
||
| `alert.warning` | 警告 | Warning |
|
||
| `alert.info` | 信息 | Info |
|
||
| `alert.bankruptcy_title` | 代理破产 | Agent Bankrupt |
|
||
| `alert.bankruptcy_msg` | 代理 {agent_id} 已破产! | Agent {agent_id} has gone bankrupt! |
|
||
| `alert.large_loss_title` | 检测到重大损失 | Large Loss Detected |
|
||
| `alert.large_loss_msg` | 代理 {agent_id} 遭受重大损失: ${pnl:.2f} | Agent {agent_id} suffered large loss: ${pnl:.2f} |
|
||
|
||
### 配置 (`config`)
|
||
|
||
| 键值 | 中文 | 英文 |
|
||
|-----|------|------|
|
||
| `config.title` | 配置管理 | Configuration Management |
|
||
| `config.save` | 保存配置 | Save Configuration |
|
||
| `config.reset` | 重置 | Reset |
|
||
| `config.saving` | 保存中... | Saving... |
|
||
| `config.initial_capital` | 初始资金 | Initial Capital |
|
||
| `config.cost_structure` | 成本结构 | Cost Structure |
|
||
| `config.thresholds` | 生存阈值 | Survival Thresholds |
|
||
| `config.simulation` | 模拟设置 | Simulation Settings |
|
||
| `config.llm_providers` | LLM 提供商 | LLM Providers |
|
||
|
||
### WebSocket 消息 (`ws`)
|
||
|
||
| 键值 | 中文 | 英文 |
|
||
|-----|------|------|
|
||
| `ws.status_update` | 状态更新 | Status Update |
|
||
| `ws.initial_state` | 初始状态 | Initial State |
|
||
| `ws.agent_update` | 代理更新 | Agent Update |
|
||
| `ws.trade_update` | 交易更新 | Trade Update |
|
||
| `ws.alert` | 警报 | Alert |
|
||
|
||
## 添加新语言
|
||
|
||
要添加新语言(如日语),请按以下步骤操作:
|
||
|
||
### 1. 更新 Language 枚举
|
||
|
||
```python
|
||
# 在 i18n.py 中的 Language 类添加
|
||
class Language(str, Enum):
|
||
CHINESE = "zh"
|
||
ENGLISH = "en"
|
||
JAPANESE = "jp" # 新增
|
||
```
|
||
|
||
### 2. 添加翻译字典
|
||
|
||
```python
|
||
# 在 _translations 字典中添加
|
||
"jp": {
|
||
"status": {
|
||
"agent_bankrupt": "エージェント破産",
|
||
"config_saved": "設定を保存しました",
|
||
# ... 更多翻译
|
||
},
|
||
# ... 其他分类
|
||
}
|
||
```
|
||
|
||
### 3. 更新 get_available_languages 方法
|
||
|
||
```python
|
||
def get_available_languages(self) -> Dict[str, str]:
|
||
return {
|
||
"zh": "中文",
|
||
"en": "English",
|
||
"jp": "日本語", # 新增
|
||
}
|
||
```
|
||
|
||
### 4. 添加语言切换功能(前端)
|
||
|
||
如需前端语言切换,可添加 API 端点:
|
||
|
||
```python
|
||
@app.post("/api/language/{lang}")
|
||
async def set_language_endpoint(lang: str) -> Dict[str, str]:
|
||
"""切换仪表板语言。"""
|
||
try:
|
||
i18n.set_language(lang)
|
||
return {"status": "success", "message": f"Language set to {lang}"}
|
||
except ValueError as e:
|
||
return {"status": "error", "message": str(e)}
|
||
```
|
||
|
||
## 扩展现有翻译
|
||
|
||
添加新的翻译键值:
|
||
|
||
```python
|
||
from openclaw.dashboard.i18n import I18n
|
||
|
||
i18n = I18n()
|
||
|
||
# 添加中文翻译
|
||
i18n.add_translation("zh", "new.category.key", "新的值")
|
||
|
||
# 添加英文翻译
|
||
i18n.add_translation("en", "new.category.key", "New Value")
|
||
|
||
# 使用新键值
|
||
text = i18n.t("new.category.key")
|
||
```
|
||
|
||
## 最佳实践
|
||
|
||
1. **键名规范**
|
||
- 使用小写字母和下划线
|
||
- 采用 `分类.子分类.键名` 的层级结构
|
||
- 例如:`status.agent_bankrupt`, `trade.recent_trades`
|
||
|
||
2. **变量插值**
|
||
- 使用 `{variable}` 语法
|
||
- 确保所有语言版本包含相同的变量名
|
||
- 示例:`"agent {agent_id} 已破产"`, `"Agent {agent_id} has gone bankrupt"`
|
||
|
||
3. **语言回退**
|
||
- 如果当前语言缺少翻译,自动回退到中文
|
||
- 确保中文翻译完整作为基准
|
||
|
||
4. **前端集成**
|
||
- 前端可直接通过 API 获取翻译
|
||
- 考虑将语言偏好存储在本地存储或用户配置中
|
||
|
||
## 集成示例
|
||
|
||
### FastAPI 集成
|
||
|
||
```python
|
||
from fastapi import FastAPI
|
||
from openclaw.dashboard.i18n import I18n
|
||
|
||
app = FastAPI()
|
||
i18n = I18n()
|
||
|
||
@app.get("/api/translations")
|
||
async def get_translations(lang: str = "zh"):
|
||
"""获取指定语言的完整翻译字典。"""
|
||
i18n.set_language(lang)
|
||
return i18n.get_all_translations()
|
||
|
||
@app.get("/api/translate/{key}")
|
||
async def translate(key: str, lang: str = "zh"):
|
||
"""翻译单个键值。"""
|
||
i18n.set_language(lang)
|
||
return {"key": key, "translation": i18n.t(key)}
|
||
```
|
||
|
||
### WebSocket 消息汉化
|
||
|
||
```python
|
||
# app.py 中使用示例
|
||
from openclaw.dashboard.i18n import t
|
||
|
||
# 使用国际化消息
|
||
alert = AlertMessage(
|
||
alert_type=AlertType.BANKRUPTCY,
|
||
level=AlertLevel.CRITICAL,
|
||
title=t("alert.bankruptcy_title"),
|
||
message=t("alert.bankruptcy_msg", agent_id=agent.agent_id),
|
||
)
|
||
```
|
||
|
||
---
|
||
|
||
## 更新日志
|
||
|
||
### 2024-02-25
|
||
- ✅ 创建 i18n.py 国际化工具类
|
||
- ✅ 完成 index.html 汉化
|
||
- ✅ 完成 config.html 汉化
|
||
- ✅ 完成 config.js 汉化
|
||
- ✅ 完成 app.py API 消息汉化
|
||
- ✅ 创建本文档
|
||
|
||
### 待办事项
|
||
- [ ] 添加前端语言切换 UI
|
||
- [ ] 添加更多语言支持(日语、韩语等)
|
||
- [ ] 将翻译持久化到配置文件
|
||
- [ ] 支持用户个性化语言设置
|