Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b71f76c8b3 | |||
| ceed482444 | |||
| b752779d18 | |||
| 6807371c5e | |||
| 1bce2d9c7a | |||
| 24ba405d55 | |||
| e18fbad839 | |||
| cd305a62ef | |||
| 7c8a924984 |
120
AGENTS.md
120
AGENTS.md
@@ -3,6 +3,17 @@
|
||||
## 项目概述
|
||||
YOYO是一个命令行翻译工具,使用Go语言编写,采用面向对象设计模式。它通过调用在线大模型API,结合不同的Prompt配置,实现多样化的翻译特色。
|
||||
|
||||
## 开发流程
|
||||
1. AI接手项目后,先阅读 `AGENTS.md` `changelog.md` `taolun.md` `memory.md`,无需读整个项目的所有文件;
|
||||
2. 每次开始执行操作前,先更新 `taolun.md`;
|
||||
3. 执行完开发后,更新 `changelog.md` `memory.md` `AGENTS.md`;
|
||||
4. 最后,执行 git 操作,发布本地的 版本号,而先不提交远程;
|
||||
|
||||
## 文档规范
|
||||
- 讨论的内容:只应该保存在 `taolun.md` 或 `changelod.md`中,根据 文档该写什么该链接什么,分门别类的放置
|
||||
- 不应该再创建其他任何 md 类说明文件。
|
||||
|
||||
|
||||
## OOP设计模式
|
||||
|
||||
### 核心类设计
|
||||
@@ -24,6 +35,32 @@ YOYO是一个命令行翻译工具,使用Go语言编写,采用面向对象
|
||||
### 1. 全局配置类 (Config)
|
||||
负责读取YAML配置文件,提供默认值。
|
||||
|
||||
### 2. 缓存类 (Cache)
|
||||
负责本地缓存管理,减少API调用。
|
||||
|
||||
```go
|
||||
// internal/cache/cache.go
|
||||
package cache
|
||||
|
||||
// Cache 缓存接口
|
||||
type Cache interface {
|
||||
Get(ctx context.Context, key string) (*CacheEntry, error)
|
||||
Set(ctx context.Context, entry *CacheEntry) error
|
||||
Delete(ctx context.Context, key string) error
|
||||
Clear(ctx context.Context) error
|
||||
Stats(ctx context.Context) (*CacheStats, error)
|
||||
Cleanup(ctx context.Context) error
|
||||
Close() error
|
||||
}
|
||||
```
|
||||
|
||||
**缓存功能特点**:
|
||||
- **存储层**: 使用SQLite数据库
|
||||
- **缓存键**: 基于原文+语言对的SHA256哈希
|
||||
- **清理策略**: 组合策略(数量限制+时间过期)
|
||||
- **异步保存**: 不阻塞翻译结果返回
|
||||
- **自动清理**: 定时清理过期缓存
|
||||
|
||||
```go
|
||||
// internal/config/config.go
|
||||
package config
|
||||
@@ -405,6 +442,12 @@ yoyo/
|
||||
│ ├── translator/ # 核心翻译
|
||||
│ │ ├── translator.go
|
||||
│ │ └── prompt.go
|
||||
│ ├── cache/ # 本地缓存
|
||||
│ │ ├── cache.go # 缓存接口
|
||||
│ │ ├── sqlite.go # SQLite实现
|
||||
│ │ ├── key.go # 缓存键生成
|
||||
│ │ ├── cleanup.go # 缓存清理
|
||||
│ │ └── cache_test.go # 单元测试
|
||||
│ └── prompt/ # Prompt管理
|
||||
├── pkg/ # 公共工具
|
||||
├── configs/ # 配置文件目录
|
||||
@@ -456,6 +499,13 @@ prompts:
|
||||
creative: "你是一位富有创造力的翻译家,请用优美流畅的语言翻译以下内容。"
|
||||
academic: "你是一位学术翻译专家,请用严谨的学术语言翻译以下内容。"
|
||||
simple: "请用简单易懂的语言翻译以下内容。"
|
||||
|
||||
# 缓存配置
|
||||
cache:
|
||||
enabled: true # 是否启用缓存
|
||||
max_records: 10000 # 最大缓存记录数
|
||||
expire_days: 30 # 缓存过期天数
|
||||
db_path: "~/.config/yoyo/cache.db" # 缓存数据库文件路径
|
||||
```
|
||||
|
||||
## 开发顺序建议
|
||||
@@ -611,6 +661,17 @@ go run ./cmd/yoyo "This is translation content..."
|
||||
|
||||
# 指定翻译模式
|
||||
./yoyo --mode=technical "API documentation text"
|
||||
|
||||
# 管道功能(与其他命令行工具联合使用)
|
||||
cat file.txt | ./yoyo # 翻译文件内容
|
||||
echo "Hello" | ./yoyo --lang=cn # 翻译命令输出
|
||||
./yoyo "Hello" | grep "你好" # 与其他命令组合
|
||||
cat file.txt | ./yoyo -q # 静默模式,只输出翻译结果
|
||||
|
||||
# 缓存管理命令
|
||||
./yoyo cache clear # 清空翻译缓存
|
||||
./yoyo cache stats # 查看缓存统计信息
|
||||
./yoyo cache cleanup # 清理过期缓存
|
||||
```
|
||||
|
||||
## 代码风格指南
|
||||
@@ -761,7 +822,64 @@ A: 使用指数退避重试,并在`internal/api/`中实现限流器。
|
||||
### Q: 如何支持更多语言?
|
||||
A: 在配置文件中添加语言映射,并更新翻译逻辑。
|
||||
|
||||
## 语言代码处理
|
||||
|
||||
### 支持的语言代码格式
|
||||
项目支持多种语言代码格式,通过 `internal/lang` 模块处理:
|
||||
|
||||
1. **标准BCP47格式**: `zh-CN`, `zh-TW`, `en-US`, `en-GB`, `ja`, `ko` 等
|
||||
2. **简短别名**: `cn`(中文), `en`(英文), `jp`(日文), `kr`(韩文) 等
|
||||
3. **中文名称**: `chinese`(中文), `english`(英文), `japanese`(日文) 等
|
||||
|
||||
### 语言解析函数
|
||||
```go
|
||||
// 解析语言代码
|
||||
lang.ParseLanguageCode("cn") // 返回 "zh-CN"
|
||||
lang.ParseLanguageCode("en") // 返回 "en-US"
|
||||
lang.ParseLanguageCode("zh-TW") // 返回 "zh-TW"
|
||||
|
||||
// 获取语言名称(用于显示)
|
||||
lang.GetLanguageName("zh-CN") // 返回 "中文(简体)"
|
||||
lang.GetLanguageName("en-US") // 返回 "English (US)"
|
||||
```
|
||||
|
||||
## Onboard配置向导
|
||||
|
||||
### 配置流程
|
||||
1. 选择主要翻译厂商
|
||||
2. 配置厂商API密钥、HOST、模型
|
||||
3. 设置全局配置(默认语言、超时)
|
||||
4. 保存配置到 `configs/config.yaml`
|
||||
|
||||
### 使用方法
|
||||
```bash
|
||||
yoyo onboard # 启动配置向导
|
||||
yoyo onboard --force # 强制重新配置
|
||||
```
|
||||
|
||||
### 配置向导实现
|
||||
- 使用 `github.com/AlecAivazis/survey/v2` 实现交互式界面
|
||||
- 支持厂商选择、API配置、语言设置
|
||||
- 生成标准YAML配置文件
|
||||
|
||||
## 分阶段迁移策略
|
||||
|
||||
### 第一阶段:开发阶段(当前)
|
||||
- API密钥存储在 `.env` 文件
|
||||
- 复杂配置存储在 `configs/config.yaml`
|
||||
- 支持环境变量替换
|
||||
|
||||
### 第二阶段:上线前
|
||||
- 实现配置文件路径查找机制
|
||||
- 支持用户配置目录 `~/.config/yoo/yoo.yml`
|
||||
- 提供配置迁移工具
|
||||
|
||||
### 第三阶段:最终优化
|
||||
- 移除对 `.env` 文件依赖
|
||||
- 完全使用配置文件
|
||||
|
||||
## 参考资源
|
||||
- [Effective Go](https://go.dev/doc/effective_go)
|
||||
- [Go Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments)
|
||||
- [Go Style Guide](https://google.github.io/styleguide/go/)
|
||||
- [Go Style Guide](https://google.github.io/styleguide/go/)
|
||||
- [Survey库文档](https://github.com/AlecAivazis/survey)
|
||||
|
||||
228
changelog.md
228
changelog.md
@@ -9,7 +9,7 @@
|
||||
|
||||
## 未来架构想法
|
||||
- [ ] 支持流式翻译输出
|
||||
- [ ] 添加本地缓存减少API调用
|
||||
- [x] 添加本地缓存减少API调用 ✅ 已完成
|
||||
- [ ] 实现插件系统支持自定义厂商
|
||||
- [ ] 支持批量翻译文件
|
||||
- [ ] 添加Web界面(可选)
|
||||
@@ -32,6 +32,232 @@
|
||||
|
||||
## 版本历史
|
||||
|
||||
### 0.5.0 (2026-03-29) - 本地缓存功能
|
||||
**类型**: 功能版本
|
||||
**状态**: 已发布
|
||||
|
||||
**变更内容**:
|
||||
- ✅ 添加本地缓存模块 (internal/cache/)
|
||||
- ✅ 实现SQLite缓存存储层,支持高效查询和存储
|
||||
- ✅ 实现缓存键生成策略(基于原文+语言对的SHA256哈希)
|
||||
- ✅ 修改Translator类集成缓存功能,先查缓存再调用API
|
||||
- ✅ 添加缓存配置到Config结构,支持自定义缓存参数
|
||||
- ✅ 实现缓存管理命令:cache clear, cache stats, cache cleanup
|
||||
- ✅ 添加组合缓存清理策略(数量限制+时间过期)
|
||||
- ✅ 更新配置文件模板,添加缓存配置示例
|
||||
- ✅ 更新帮助文档,添加缓存相关命令说明
|
||||
|
||||
**技术实现**:
|
||||
- 使用 `github.com/mattn/go-sqlite3` 作为SQLite驱动
|
||||
- 实现缓存接口 (Cache interface),支持多种存储后端
|
||||
- 缓存表包含完整字段:原文、译文、语言对、模型、Prompt、用量统计
|
||||
- 自动清理过期缓存和超出数量限制的缓存
|
||||
- 异步保存缓存,不阻塞翻译结果返回
|
||||
|
||||
**使用示例**:
|
||||
```bash
|
||||
# 基本翻译(自动使用缓存)
|
||||
yoyo "Hello world"
|
||||
yoyo "Hello world" # 第二次调用将从缓存返回
|
||||
|
||||
# 缓存管理命令
|
||||
yoyo cache clear # 清空翻译缓存
|
||||
yoyo cache stats # 查看缓存统计信息
|
||||
yoyo cache cleanup # 清理过期缓存
|
||||
```
|
||||
|
||||
**配置示例**:
|
||||
```yaml
|
||||
cache:
|
||||
enabled: true # 是否启用缓存
|
||||
max_records: 10000 # 最大缓存记录数
|
||||
expire_days: 30 # 缓存过期天数
|
||||
db_path: "~/.config/yoyo/cache.db" # 缓存数据库文件路径
|
||||
```
|
||||
|
||||
**讨论记录**:
|
||||
- [本地缓存功能设计](taolun.md#2026-03-29-1500-版本-050-本地缓存功能设计)
|
||||
|
||||
**下一步**:
|
||||
- 完善缓存功能测试
|
||||
- 添加缓存命中率统计
|
||||
- 实现按语言清理缓存功能
|
||||
- 优化缓存性能
|
||||
|
||||
---
|
||||
|
||||
### 0.5.1 (2026-03-29) - 缓存功能修复
|
||||
**类型**: 修复版本
|
||||
**状态**: 已发布
|
||||
|
||||
**变更内容**:
|
||||
- ✅ 修复缓存清空命令中的VACUUM事务错误
|
||||
- ✅ 修复缓存统计中的NULL值处理错误
|
||||
- ✅ 修复缓存过期清理策略,支持expire_days=0时清理所有记录
|
||||
- ✅ 添加缓存模块单元测试
|
||||
- ✅ 更新版本号到v0.5.1
|
||||
|
||||
**修复问题**:
|
||||
- 缓存清空命令执行时出现"cannot VACUUM from within a transaction"错误
|
||||
- 缓存统计查询在空表时出现NULL值转换错误
|
||||
- 缓存过期清理策略在expire_days=0时不工作
|
||||
|
||||
**测试结果**:
|
||||
- 所有缓存模块测试通过
|
||||
- 缓存命令功能正常
|
||||
- 缓存集成功能正常
|
||||
|
||||
**下一步**:
|
||||
- 完善缓存功能测试
|
||||
- 添加缓存命中率统计
|
||||
- 实现按语言清理缓存功能
|
||||
- 优化缓存性能
|
||||
|
||||
---
|
||||
|
||||
### 0.4.0 (2026-03-29) - 管道符功能
|
||||
**类型**: 功能版本
|
||||
**状态**: 已发布
|
||||
|
||||
**变更内容**:
|
||||
- ✅ 添加管道符支持,允许与其他命令行工具联合使用
|
||||
- ✅ 实现管道输入检测 (isPipeInput函数)
|
||||
- ✅ 实现从标准输入读取 (readFromStdin函数)
|
||||
- ✅ 添加 --quiet 和 -q 参数控制统计信息输出
|
||||
- ✅ 更新帮助文档,添加管道使用示例
|
||||
- ✅ 修复 content/filter.go 中的正则表达式错误
|
||||
- ✅ 更新版本号到 v0.3.0
|
||||
|
||||
**使用示例**:
|
||||
```bash
|
||||
# 管道翻译文件
|
||||
cat file.txt | yoyo
|
||||
cat file.txt | yoyo --lang=en
|
||||
|
||||
# 管道翻译命令输出
|
||||
echo "Hello world" | yoyo --lang=cn
|
||||
|
||||
# 静默模式,只输出翻译结果
|
||||
echo "Hello world" | yoyo -q
|
||||
|
||||
# 与其他命令组合使用
|
||||
cat file.txt | yoyo | grep "关键词"
|
||||
yoyo "Hello" | wc -l
|
||||
```
|
||||
|
||||
**讨论记录**:
|
||||
- [管道符功能设计](taolun.md#管道符功能设计)
|
||||
|
||||
**下一步**:
|
||||
- 实现更多厂商(火山引擎、国家超算、Qwen、OpenAI兼容)
|
||||
- 添加配置文件路径查找机制
|
||||
- 实现配置文件迁移工具
|
||||
- 完善错误处理和用户体验
|
||||
|
||||
### 0.3.0 (2026-03-29) - 内容过滤与代码处理
|
||||
**类型**: 功能版本
|
||||
**状态**: 已发布
|
||||
|
||||
**变更内容**:
|
||||
- ✅ 添加内容过滤模块 (internal/content/)
|
||||
- ✅ 实现基础字符过滤(移除控制字符、规范化换行符、截断超长符号)
|
||||
- ✅ 实现代码块和行内代码识别
|
||||
- ✅ 实现代码注释智能识别(支持 JS/TS/Java/Python/Go/HTML 等 30+ 语言)
|
||||
- ✅ 添加 go-enry 依赖实现编程语言智能检测
|
||||
- ✅ 添加 SkipKeywords 配置项,默认保留 TODO/FIXME/HACK 等关键词不翻译
|
||||
- ✅ 集成内容处理到 Translator 模块
|
||||
|
||||
**新增文件**:
|
||||
- `internal/content/content.go` - 模块入口
|
||||
- `internal/content/filter.go` - 基础字符过滤
|
||||
- `internal/content/parser.go` - 内容解析器和语言检测
|
||||
|
||||
**配置更新**:
|
||||
- `configs/config.yaml` 新增 `skip_keywords` 配置项
|
||||
- 支持用户自定义不翻译的关键词列表
|
||||
|
||||
**使用示例**:
|
||||
```bash
|
||||
# 翻译包含代码的文档,自动识别代码和注释
|
||||
yoyo "这是一个文档 ```js // TODO: fix this ```"
|
||||
# 代码块保持不变,只翻译注释中的词汇
|
||||
# TODO: 修复这个
|
||||
```
|
||||
|
||||
**讨论记录**:
|
||||
- [内容过滤与代码处理设计](taolun.md#内容过滤与代码处理设计)
|
||||
|
||||
**下一步**:
|
||||
- 实现更多厂商(火山引擎、国家超算、Qwen、OpenAI兼容)
|
||||
- 添加配置文件路径查找机制
|
||||
- 实现配置文件迁移工具
|
||||
- 完善错误处理和用户体验
|
||||
|
||||
### 0.2.0 (2026-03-29) - 语言支持和配置向导
|
||||
**类型**: 功能版本
|
||||
**状态**: 开发中
|
||||
|
||||
**变更内容**:
|
||||
- ✅ 添加语言代码智能解析模块 (internal/lang)
|
||||
- ✅ 支持 `--lang` 参数指定目标语言
|
||||
- ✅ 支持多种语言代码格式(标准BCP47、别名、中文名称)
|
||||
- ✅ 实现 onboard 交互式配置向导
|
||||
- ✅ 更新配置结构添加语言字段
|
||||
- ✅ 添加 survey 库依赖用于交互式界面
|
||||
- ✅ 改进CLI命令行接口
|
||||
- ✅ 添加语言模块单元测试
|
||||
|
||||
**新增文件**:
|
||||
- `internal/lang/lang.go` - 语言代码解析模块
|
||||
- `internal/lang/lang_test.go` - 语言模块测试
|
||||
- `internal/onboard/onboard.go` - 配置向导实现
|
||||
|
||||
**支持的语言代码**:
|
||||
- 标准格式: zh-CN, zh-TW, en-US, en-GB, ja, ko, es, fr, de 等
|
||||
- 简短别名: cn(中文), en(英文), jp(日文), kr(韩文) 等
|
||||
- 中文名称: chinese(中文), english(英文), japanese(日文) 等
|
||||
|
||||
**使用示例**:
|
||||
```bash
|
||||
# 基本翻译
|
||||
yoyo "Hello world"
|
||||
yoyo --lang=cn "Hello world"
|
||||
yoyo --lang=en "你好世界"
|
||||
yoyo --lang=zh-TW "Hello world"
|
||||
|
||||
# 配置向导
|
||||
yoyo onboard
|
||||
yoyo onboard --force
|
||||
```
|
||||
|
||||
**讨论记录**:
|
||||
- [语言代码解析设计](taolun.md#语言代码解析设计)
|
||||
- [onboard配置向导](taolun.md#onboard配置向导)
|
||||
|
||||
**下一步**:
|
||||
- 实现更多厂商(火山引擎、国家超算、Qwen、OpenAI兼容)
|
||||
- 添加配置文件路径查找机制
|
||||
- 实现配置文件迁移工具
|
||||
- 完善错误处理和用户体验
|
||||
|
||||
### 0.0.3 (2026-03-29) - 环境变量加载修复
|
||||
**类型**: 修复版本
|
||||
**状态**: 开发中
|
||||
|
||||
**变更内容**:
|
||||
- ✅ 修复环境变量加载问题
|
||||
- ✅ 添加godotenv依赖
|
||||
- ✅ 更新memory.md记录踩坑经验
|
||||
- ✅ 测试CLI基本功能
|
||||
|
||||
**讨论记录**:
|
||||
- [环境变量加载修复](taolun.md#2026-03-29-0000-版本-003-环境变量加载修复)
|
||||
|
||||
**下一步**:
|
||||
- 实现更多厂商
|
||||
- 添加更多测试
|
||||
- 完善错误处理
|
||||
|
||||
### 0.0.2 (2026-03-28) - 核心架构实现
|
||||
**类型**: 功能版本
|
||||
**状态**: 开发中
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
default_provider: "siliconflow"
|
||||
default_model: "gpt-3.5-turbo"
|
||||
timeout: 30
|
||||
default_source_lang: "auto" # 默认源语言(auto为自动检测)
|
||||
default_target_lang: "zh-CN" # 默认目标语言(简体中文)
|
||||
|
||||
providers:
|
||||
siliconflow:
|
||||
@@ -40,4 +42,11 @@ prompts:
|
||||
technical: "你是一位专业的技术翻译,请准确翻译以下技术文档,保持专业术语的准确性。"
|
||||
creative: "你是一位富有创造力的翻译家,请用优美流畅的语言翻译以下内容。"
|
||||
academic: "你是一位学术翻译专家,请用严谨的学术语言翻译以下内容。"
|
||||
simple: "请用简单易懂的语言翻译以下内容。"
|
||||
simple: "请用简单易懂的语言翻译以下内容。"
|
||||
|
||||
# 缓存配置
|
||||
cache:
|
||||
enabled: true # 是否启用缓存
|
||||
max_records: 10000 # 最大缓存记录数
|
||||
expire_days: 30 # 缓存过期天数
|
||||
db_path: "~/.config/yoyo/cache.db" # 缓存数据库文件路径
|
||||
16
go.mod
16
go.mod
@@ -2,4 +2,18 @@ module github.com/titor/fanyi
|
||||
|
||||
go 1.26.1
|
||||
|
||||
require gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
require (
|
||||
github.com/AlecAivazis/survey/v2 v2.3.7 // indirect
|
||||
github.com/go-enry/go-enry/v2 v2.9.5 // indirect
|
||||
github.com/go-enry/go-oniguruma v1.2.1 // indirect
|
||||
github.com/joho/godotenv v1.5.1 // indirect
|
||||
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
|
||||
github.com/mattn/go-colorable v0.1.2 // indirect
|
||||
github.com/mattn/go-isatty v0.0.8 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.37 // indirect
|
||||
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b // indirect
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f // indirect
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 // indirect
|
||||
golang.org/x/text v0.4.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
61
go.sum
61
go.sum
@@ -1,3 +1,64 @@
|
||||
github.com/AlecAivazis/survey/v2 v2.3.7 h1:6I/u8FvytdGsgonrYsVn2t8t4QiRnh6QSTqkkhIiSjQ=
|
||||
github.com/AlecAivazis/survey/v2 v2.3.7/go.mod h1:xUTIdE4KCOIjsBAE1JYsUPoCqYdZ1reCfTwbto0Fduo=
|
||||
github.com/Netflix/go-expect v0.0.0-20220104043353-73e0943537d2/go.mod h1:HBCaDeC1lPdgDeDbhX8XFpy1jqjK0IBG8W5K+xYqA0w=
|
||||
github.com/creack/pty v1.1.17/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/go-enry/go-enry/v2 v2.9.5 h1:HPhAQQHYwJgihL2PxBZiUMFWiROsGwOBdB6/D8zCUhY=
|
||||
github.com/go-enry/go-enry/v2 v2.9.5/go.mod h1:9yrj4ES1YrbNb1Wb7/PWYr2bpaCXUGRt0uafN0ISyG8=
|
||||
github.com/go-enry/go-oniguruma v1.2.1 h1:k8aAMuJfMrqm/56SG2lV9Cfti6tC4x8673aHCcBk+eo=
|
||||
github.com/go-enry/go-oniguruma v1.2.1/go.mod h1:bWDhYP+S6xZQgiRL7wlTScFYBe023B6ilRZbCAD5Hf4=
|
||||
github.com/hinshun/vt10x v0.0.0-20220119200601-820417d04eec/go.mod h1:Q48J4R4DvxnHolD5P8pOtXigYlRuPLGl6moFx3ulM68=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs=
|
||||
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8=
|
||||
github.com/mattn/go-colorable v0.1.2 h1:/bC9yWikZXAL9uJdulbSfyVNIR3n3trXl+v8+1sx8mU=
|
||||
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
|
||||
github.com/mattn/go-isatty v0.0.8 h1:HLtExJ+uU2HOZ+wI0Tt5DtUDrx8yhUqDcp7fYERX4CE=
|
||||
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
|
||||
github.com/mattn/go-sqlite3 v1.14.37 h1:3DOZp4cXis1cUIpCfXLtmlGolNLp2VEqhiB/PARNBIg=
|
||||
github.com/mattn/go-sqlite3 v1.14.37/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b h1:j7+1HpAFS1zy5+Q4qx1fWh90gTKwiN4QCGoY9TWyyO4=
|
||||
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f h1:v4INt8xihDGvnrfjMDVXGxw9wrfxYyCjk0KbXjhR55s=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211 h1:JGgROgKl9N8DuW20oFS5gxc+lE67/N3FcwmBPMe7ArY=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.4.0 h1:BrVqGRd7+k1DiOgtnFvAkoQEWQvBc25ouMJM6429SFg=
|
||||
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
||||
75
internal/cache/cache.go
vendored
Normal file
75
internal/cache/cache.go
vendored
Normal file
@@ -0,0 +1,75 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Cache 缓存接口
|
||||
type Cache interface {
|
||||
// Get 获取缓存
|
||||
Get(ctx context.Context, key string) (*CacheEntry, error)
|
||||
|
||||
// Set 设置缓存
|
||||
Set(ctx context.Context, entry *CacheEntry) error
|
||||
|
||||
// Delete 删除缓存
|
||||
Delete(ctx context.Context, key string) error
|
||||
|
||||
// Clear 清空缓存
|
||||
Clear(ctx context.Context) error
|
||||
|
||||
// Stats 获取缓存统计信息
|
||||
Stats(ctx context.Context) (*CacheStats, error)
|
||||
|
||||
// Cleanup 清理过期缓存
|
||||
Cleanup(ctx context.Context) error
|
||||
|
||||
// Close 关闭缓存
|
||||
Close() error
|
||||
}
|
||||
|
||||
// CacheEntry 缓存条目
|
||||
type CacheEntry struct {
|
||||
ID int64 `json:"id"`
|
||||
CacheKey string `json:"cache_key"`
|
||||
OriginalText string `json:"original_text"`
|
||||
TranslatedText string `json:"translated_text"`
|
||||
FromLang string `json:"from_lang"`
|
||||
ToLang string `json:"to_lang"`
|
||||
Model string `json:"model"`
|
||||
PromptName string `json:"prompt_name,omitempty"`
|
||||
PromptContent string `json:"prompt_content,omitempty"`
|
||||
PromptTokens int `json:"prompt_tokens"`
|
||||
CompletionTokens int `json:"completion_tokens"`
|
||||
TotalTokens int `json:"total_tokens"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
LastUsedAt time.Time `json:"last_used_at"`
|
||||
}
|
||||
|
||||
// CacheStats 缓存统计信息
|
||||
type CacheStats struct {
|
||||
TotalRecords int `json:"total_records"`
|
||||
TotalSizeBytes int64 `json:"total_size_bytes"`
|
||||
OldestRecord time.Time `json:"oldest_record"`
|
||||
NewestRecord time.Time `json:"newest_record"`
|
||||
AvgTokensPerRecord float64 `json:"avg_tokens_per_record"`
|
||||
}
|
||||
|
||||
// CacheConfig 缓存配置
|
||||
type CacheConfig struct {
|
||||
Enabled bool `yaml:"enabled"`
|
||||
MaxRecords int `yaml:"max_records"`
|
||||
ExpireDays int `yaml:"expire_days"`
|
||||
DBPath string `yaml:"db_path"`
|
||||
}
|
||||
|
||||
// NewCacheConfig 创建默认缓存配置
|
||||
func NewCacheConfig() *CacheConfig {
|
||||
return &CacheConfig{
|
||||
Enabled: true,
|
||||
MaxRecords: 10000,
|
||||
ExpireDays: 30,
|
||||
DBPath: "~/.config/yoyo/cache.db",
|
||||
}
|
||||
}
|
||||
325
internal/cache/cache_test.go
vendored
Normal file
325
internal/cache/cache_test.go
vendored
Normal file
@@ -0,0 +1,325 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGenerateCacheKey(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
text string
|
||||
fromLang string
|
||||
toLang string
|
||||
wantSame bool
|
||||
}{
|
||||
{
|
||||
name: "相同输入应生成相同键",
|
||||
text: "Hello world",
|
||||
fromLang: "en",
|
||||
toLang: "zh-CN",
|
||||
wantSame: true,
|
||||
},
|
||||
{
|
||||
name: "不同文本应生成不同键",
|
||||
text: "Hello universe",
|
||||
fromLang: "en",
|
||||
toLang: "zh-CN",
|
||||
wantSame: false,
|
||||
},
|
||||
{
|
||||
name: "不同语言对应生成不同键",
|
||||
text: "Hello world",
|
||||
fromLang: "en",
|
||||
toLang: "zh-TW",
|
||||
wantSame: false,
|
||||
},
|
||||
{
|
||||
name: "大小写不敏感的语言代码",
|
||||
text: "Hello world",
|
||||
fromLang: "EN",
|
||||
toLang: "zh-cn",
|
||||
wantSame: true,
|
||||
},
|
||||
{
|
||||
name: "多余空白字符应规范化",
|
||||
text: " Hello world ",
|
||||
fromLang: "en",
|
||||
toLang: "zh-CN",
|
||||
wantSame: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
key1 := GenerateCacheKey(tt.text, tt.fromLang, tt.toLang)
|
||||
key2 := GenerateCacheKey(tt.text, tt.fromLang, tt.toLang)
|
||||
|
||||
if key1 != key2 {
|
||||
t.Errorf("相同输入生成了不同的键: %s != %s", key1, key2)
|
||||
}
|
||||
|
||||
// 检查键的长度(SHA256哈希应为64个字符)
|
||||
if len(key1) != 64 {
|
||||
t.Errorf("缓存键长度不正确: got %d, want 64", len(key1))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSQLiteCache(t *testing.T) {
|
||||
// 创建临时目录
|
||||
tmpDir, err := os.MkdirTemp("", "cache_test")
|
||||
if err != nil {
|
||||
t.Fatalf("创建临时目录失败: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
dbPath := filepath.Join(tmpDir, "test_cache.db")
|
||||
|
||||
// 创建缓存配置
|
||||
config := &CacheConfig{
|
||||
Enabled: true,
|
||||
MaxRecords: 100,
|
||||
ExpireDays: 1,
|
||||
DBPath: dbPath,
|
||||
}
|
||||
|
||||
// 创建缓存实例
|
||||
cache, err := NewSQLiteCache(config)
|
||||
if err != nil {
|
||||
t.Fatalf("创建缓存实例失败: %v", err)
|
||||
}
|
||||
defer cache.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// 测试设置缓存
|
||||
entry := &CacheEntry{
|
||||
CacheKey: "test_key_1",
|
||||
OriginalText: "Hello world",
|
||||
TranslatedText: "你好世界",
|
||||
FromLang: "en",
|
||||
ToLang: "zh-CN",
|
||||
Model: "gpt-3.5-turbo",
|
||||
PromptName: "simple",
|
||||
PromptContent: "请用简单易懂的语言翻译以下内容。",
|
||||
PromptTokens: 10,
|
||||
CompletionTokens: 5,
|
||||
TotalTokens: 15,
|
||||
}
|
||||
|
||||
err = cache.Set(ctx, entry)
|
||||
if err != nil {
|
||||
t.Fatalf("设置缓存失败: %v", err)
|
||||
}
|
||||
|
||||
// 测试获取缓存
|
||||
cachedEntry, err := cache.Get(ctx, "test_key_1")
|
||||
if err != nil {
|
||||
t.Fatalf("获取缓存失败: %v", err)
|
||||
}
|
||||
if cachedEntry == nil {
|
||||
t.Fatal("缓存未命中")
|
||||
}
|
||||
|
||||
if cachedEntry.TranslatedText != "你好世界" {
|
||||
t.Errorf("缓存翻译结果不正确: got %s, want 你好世界", cachedEntry.TranslatedText)
|
||||
}
|
||||
|
||||
// 测试缓存未命中
|
||||
missingEntry, err := cache.Get(ctx, "non_existent_key")
|
||||
if err != nil {
|
||||
t.Fatalf("查询不存在的缓存失败: %v", err)
|
||||
}
|
||||
if missingEntry != nil {
|
||||
t.Error("不存在的缓存应该返回nil")
|
||||
}
|
||||
|
||||
// 测试统计信息
|
||||
stats, err := cache.Stats(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("获取统计信息失败: %v", err)
|
||||
}
|
||||
if stats.TotalRecords != 1 {
|
||||
t.Errorf("统计记录数不正确: got %d, want 1", stats.TotalRecords)
|
||||
}
|
||||
|
||||
// 测试删除缓存
|
||||
err = cache.Delete(ctx, "test_key_1")
|
||||
if err != nil {
|
||||
t.Fatalf("删除缓存失败: %v", err)
|
||||
}
|
||||
|
||||
// 验证删除
|
||||
deletedEntry, err := cache.Get(ctx, "test_key_1")
|
||||
if err != nil {
|
||||
t.Fatalf("查询已删除的缓存失败: %v", err)
|
||||
}
|
||||
if deletedEntry != nil {
|
||||
t.Error("已删除的缓存应该返回nil")
|
||||
}
|
||||
|
||||
// 测试清空缓存
|
||||
err = cache.Set(ctx, entry)
|
||||
if err != nil {
|
||||
t.Fatalf("设置缓存失败: %v", err)
|
||||
}
|
||||
|
||||
err = cache.Clear(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("清空缓存失败: %v", err)
|
||||
}
|
||||
|
||||
stats, err = cache.Stats(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("获取统计信息失败: %v", err)
|
||||
}
|
||||
if stats.TotalRecords != 0 {
|
||||
t.Errorf("清空后记录数不正确: got %d, want 0", stats.TotalRecords)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCacheExpiration(t *testing.T) {
|
||||
// 创建临时目录
|
||||
tmpDir, err := os.MkdirTemp("", "cache_test")
|
||||
if err != nil {
|
||||
t.Fatalf("创建临时目录失败: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpDir)
|
||||
|
||||
dbPath := filepath.Join(tmpDir, "test_cache.db")
|
||||
|
||||
// 创建缓存配置,设置很短的过期时间
|
||||
config := &CacheConfig{
|
||||
Enabled: true,
|
||||
MaxRecords: 100,
|
||||
ExpireDays: 0, // 0天表示立即过期
|
||||
DBPath: dbPath,
|
||||
}
|
||||
|
||||
// 创建缓存实例
|
||||
cache, err := NewSQLiteCache(config)
|
||||
if err != nil {
|
||||
t.Fatalf("创建缓存实例失败: %v", err)
|
||||
}
|
||||
defer cache.Close()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
// 设置缓存
|
||||
entry := &CacheEntry{
|
||||
CacheKey: "test_key_1",
|
||||
OriginalText: "Hello world",
|
||||
TranslatedText: "你好世界",
|
||||
FromLang: "en",
|
||||
ToLang: "zh-CN",
|
||||
Model: "gpt-3.5-turbo",
|
||||
PromptTokens: 10,
|
||||
CompletionTokens: 5,
|
||||
TotalTokens: 15,
|
||||
}
|
||||
|
||||
err = cache.Set(ctx, entry)
|
||||
if err != nil {
|
||||
t.Fatalf("设置缓存失败: %v", err)
|
||||
}
|
||||
|
||||
// 立即清理(应该删除所有记录,因为过期时间为0)
|
||||
err = cache.Cleanup(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("清理缓存失败: %v", err)
|
||||
}
|
||||
|
||||
// 检查统计信息
|
||||
stats, err := cache.Stats(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("获取统计信息失败: %v", err)
|
||||
}
|
||||
if stats.TotalRecords != 0 {
|
||||
t.Errorf("清理后记录数不正确: got %d, want 0", stats.TotalRecords)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeText(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "正常文本",
|
||||
input: "Hello world",
|
||||
expected: "Hello world",
|
||||
},
|
||||
{
|
||||
name: "多余空白字符",
|
||||
input: " Hello world ",
|
||||
expected: "Hello world",
|
||||
},
|
||||
{
|
||||
name: "制表符和换行符",
|
||||
input: "Hello\tworld\n",
|
||||
expected: "Hello world",
|
||||
},
|
||||
{
|
||||
name: "空字符串",
|
||||
input: "",
|
||||
expected: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result := normalizeText(tt.input)
|
||||
if result != tt.expected {
|
||||
t.Errorf("normalizeText(%q) = %q, want %q", tt.input, result, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeLanguageCode(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "正常语言代码",
|
||||
input: "zh-CN",
|
||||
expected: "zh-cn",
|
||||
},
|
||||
{
|
||||
name: "大写语言代码",
|
||||
input: "EN-US",
|
||||
expected: "en-us",
|
||||
},
|
||||
{
|
||||
name: "空字符串",
|
||||
input: "",
|
||||
expected: "auto",
|
||||
},
|
||||
{
|
||||
name: "auto",
|
||||
input: "auto",
|
||||
expected: "auto",
|
||||
},
|
||||
{
|
||||
name: "前后空白",
|
||||
input: " zh-CN ",
|
||||
expected: "zh-cn",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result := normalizeLanguageCode(tt.input)
|
||||
if result != tt.expected {
|
||||
t.Errorf("normalizeLanguageCode(%q) = %q, want %q", tt.input, result, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
53
internal/cache/cleanup.go
vendored
Normal file
53
internal/cache/cleanup.go
vendored
Normal file
@@ -0,0 +1,53 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
)
|
||||
|
||||
// CleanupManager 缓存清理管理器
|
||||
type CleanupManager struct {
|
||||
cache Cache
|
||||
}
|
||||
|
||||
// NewCleanupManager 创建清理管理器
|
||||
func NewCleanupManager(cache Cache) *CleanupManager {
|
||||
return &CleanupManager{
|
||||
cache: cache,
|
||||
}
|
||||
}
|
||||
|
||||
// ClearAll 清空所有缓存
|
||||
func (m *CleanupManager) ClearAll(ctx context.Context) error {
|
||||
if err := m.cache.Clear(ctx); err != nil {
|
||||
return fmt.Errorf("清空缓存失败: %w", err)
|
||||
}
|
||||
log.Println("缓存已清空")
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClearByLanguage 清空指定语言对的缓存
|
||||
func (m *CleanupManager) ClearByLanguage(ctx context.Context, fromLang, toLang string) error {
|
||||
// 这个功能需要在SQLite实现中添加查询功能
|
||||
// 目前先返回一个提示信息
|
||||
return fmt.Errorf("按语言清理功能尚未实现")
|
||||
}
|
||||
|
||||
// GetStats 获取缓存统计信息
|
||||
func (m *CleanupManager) GetStats(ctx context.Context) (*CacheStats, error) {
|
||||
stats, err := m.cache.Stats(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("获取缓存统计失败: %w", err)
|
||||
}
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
// CleanupManual 手动清理
|
||||
func (m *CleanupManager) CleanupManual(ctx context.Context) error {
|
||||
if err := m.cache.Cleanup(ctx); err != nil {
|
||||
return fmt.Errorf("手动清理失败: %w", err)
|
||||
}
|
||||
log.Println("缓存清理完成")
|
||||
return nil
|
||||
}
|
||||
63
internal/cache/key.go
vendored
Normal file
63
internal/cache/key.go
vendored
Normal file
@@ -0,0 +1,63 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// GenerateCacheKey 生成缓存键
|
||||
// 使用原文+语言对进行SHA256哈希
|
||||
func GenerateCacheKey(originalText, fromLang, toLang string) string {
|
||||
// 规范化语言代码
|
||||
fromLang = normalizeLanguageCode(fromLang)
|
||||
toLang = normalizeLanguageCode(toLang)
|
||||
|
||||
// 规范化原文
|
||||
normalizedText := normalizeText(originalText)
|
||||
|
||||
// 生成缓存键
|
||||
data := fmt.Sprintf("%s|%s|%s", normalizedText, fromLang, toLang)
|
||||
hash := sha256.Sum256([]byte(data))
|
||||
return hex.EncodeToString(hash[:])
|
||||
}
|
||||
|
||||
// normalizeLanguageCode 规范化语言代码
|
||||
func normalizeLanguageCode(lang string) string {
|
||||
if lang == "" || lang == "auto" {
|
||||
return "auto"
|
||||
}
|
||||
return strings.ToLower(strings.TrimSpace(lang))
|
||||
}
|
||||
|
||||
// normalizeText 规范化文本
|
||||
// 移除多余的空白字符,确保相同的文本生成相同的哈希
|
||||
func normalizeText(text string) string {
|
||||
// 移除首尾空白
|
||||
text = strings.TrimSpace(text)
|
||||
|
||||
// 将多个连续空白字符替换为单个空格
|
||||
text = strings.Join(strings.Fields(text), " ")
|
||||
|
||||
return text
|
||||
}
|
||||
|
||||
// GenerateCacheKeyWithModel 生成包含模型信息的缓存键
|
||||
// 如果需要更精确的缓存,可以使用这个函数
|
||||
func GenerateCacheKeyWithModel(originalText, fromLang, toLang, model string) string {
|
||||
// 规范化语言代码
|
||||
fromLang = normalizeLanguageCode(fromLang)
|
||||
toLang = normalizeLanguageCode(toLang)
|
||||
|
||||
// 规范化原文
|
||||
normalizedText := normalizeText(originalText)
|
||||
|
||||
// 规范化模型名称
|
||||
model = strings.ToLower(strings.TrimSpace(model))
|
||||
|
||||
// 生成缓存键
|
||||
data := fmt.Sprintf("%s|%s|%s|%s", normalizedText, fromLang, toLang, model)
|
||||
hash := sha256.Sum256([]byte(data))
|
||||
return hex.EncodeToString(hash[:])
|
||||
}
|
||||
337
internal/cache/sqlite.go
vendored
Normal file
337
internal/cache/sqlite.go
vendored
Normal file
@@ -0,0 +1,337 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
// SQLiteCache SQLite缓存实现
|
||||
type SQLiteCache struct {
|
||||
db *sql.DB
|
||||
config *CacheConfig
|
||||
cleanupTTL time.Duration
|
||||
}
|
||||
|
||||
// NewSQLiteCache 创建SQLite缓存实例
|
||||
func NewSQLiteCache(config *CacheConfig) (*SQLiteCache, error) {
|
||||
if config == nil {
|
||||
config = NewCacheConfig()
|
||||
}
|
||||
|
||||
// 展开路径中的~符号
|
||||
dbPath, err := expandPath(config.DBPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("无效的数据库路径: %w", err)
|
||||
}
|
||||
|
||||
// 确保目录存在
|
||||
dir := filepath.Dir(dbPath)
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
return nil, fmt.Errorf("创建缓存目录失败: %w", err)
|
||||
}
|
||||
|
||||
// 打开数据库连接
|
||||
db, err := sql.Open("sqlite3", dbPath+"?_journal_mode=WAL&_synchronous=NORMAL")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("打开数据库失败: %w", err)
|
||||
}
|
||||
|
||||
// 设置连接池参数
|
||||
db.SetMaxOpenConns(1) // SQLite只支持单个写入连接
|
||||
db.SetMaxIdleConns(1)
|
||||
|
||||
cache := &SQLiteCache{
|
||||
db: db,
|
||||
config: config,
|
||||
cleanupTTL: time.Duration(config.ExpireDays) * 24 * time.Hour,
|
||||
}
|
||||
|
||||
// 初始化数据库表
|
||||
if err := cache.initTable(); err != nil {
|
||||
db.Close()
|
||||
return nil, fmt.Errorf("初始化缓存表失败: %w", err)
|
||||
}
|
||||
|
||||
// 设置清理定时器
|
||||
go cache.startCleanupTimer()
|
||||
|
||||
return cache, nil
|
||||
}
|
||||
|
||||
// initTable 初始化缓存表
|
||||
func (c *SQLiteCache) initTable() error {
|
||||
query := `
|
||||
CREATE TABLE IF NOT EXISTS translation_cache (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
cache_key TEXT NOT NULL UNIQUE,
|
||||
original_text TEXT NOT NULL,
|
||||
translated_text TEXT NOT NULL,
|
||||
from_lang TEXT NOT NULL,
|
||||
to_lang TEXT NOT NULL,
|
||||
model TEXT NOT NULL,
|
||||
prompt_name TEXT,
|
||||
prompt_content TEXT,
|
||||
prompt_tokens INTEGER DEFAULT 0,
|
||||
completion_tokens INTEGER DEFAULT 0,
|
||||
total_tokens INTEGER DEFAULT 0,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
last_used_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_cache_key ON translation_cache(cache_key);
|
||||
CREATE INDEX IF NOT EXISTS idx_original_text ON translation_cache(original_text);
|
||||
CREATE INDEX IF NOT EXISTS idx_created_at ON translation_cache(created_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_last_used_at ON translation_cache(last_used_at);
|
||||
`
|
||||
|
||||
_, err := c.db.Exec(query)
|
||||
return err
|
||||
}
|
||||
|
||||
// Get 获取缓存
|
||||
func (c *SQLiteCache) Get(ctx context.Context, key string) (*CacheEntry, error) {
|
||||
query := `
|
||||
SELECT
|
||||
id, cache_key, original_text, translated_text, from_lang, to_lang,
|
||||
model, prompt_name, prompt_content, prompt_tokens, completion_tokens,
|
||||
total_tokens, created_at, last_used_at
|
||||
FROM translation_cache
|
||||
WHERE cache_key = ?
|
||||
`
|
||||
|
||||
entry := &CacheEntry{}
|
||||
var promptName, promptContent sql.NullString
|
||||
var createdAt, lastUsedAt string
|
||||
|
||||
err := c.db.QueryRowContext(ctx, query, key).Scan(
|
||||
&entry.ID, &entry.CacheKey, &entry.OriginalText, &entry.TranslatedText,
|
||||
&entry.FromLang, &entry.ToLang, &entry.Model, &promptName, &promptContent,
|
||||
&entry.PromptTokens, &entry.CompletionTokens, &entry.TotalTokens,
|
||||
&createdAt, &lastUsedAt,
|
||||
)
|
||||
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil // 缓存未命中
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("查询缓存失败: %w", err)
|
||||
}
|
||||
|
||||
// 处理可空字段
|
||||
if promptName.Valid {
|
||||
entry.PromptName = promptName.String
|
||||
}
|
||||
if promptContent.Valid {
|
||||
entry.PromptContent = promptContent.String
|
||||
}
|
||||
|
||||
// 解析时间
|
||||
entry.CreatedAt, _ = time.Parse("2006-01-02 15:04:05", createdAt)
|
||||
entry.LastUsedAt, _ = time.Parse("2006-01-02 15:04:05", lastUsedAt)
|
||||
|
||||
// 更新最后使用时间
|
||||
go c.updateLastUsed(context.Background(), key)
|
||||
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
// Set 设置缓存
|
||||
func (c *SQLiteCache) Set(ctx context.Context, entry *CacheEntry) error {
|
||||
// 开始事务
|
||||
tx, err := c.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("开始事务失败: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
// 插入或替换缓存
|
||||
query := `
|
||||
INSERT OR REPLACE INTO translation_cache
|
||||
(cache_key, original_text, translated_text, from_lang, to_lang,
|
||||
model, prompt_name, prompt_content, prompt_tokens, completion_tokens,
|
||||
total_tokens, created_at, last_used_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`
|
||||
|
||||
now := time.Now().Format("2006-01-02 15:04:05")
|
||||
_, err = tx.ExecContext(ctx, query,
|
||||
entry.CacheKey, entry.OriginalText, entry.TranslatedText,
|
||||
entry.FromLang, entry.ToLang, entry.Model, entry.PromptName,
|
||||
entry.PromptContent, entry.PromptTokens, entry.CompletionTokens,
|
||||
entry.TotalTokens, now, now,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("插入缓存失败: %w", err)
|
||||
}
|
||||
|
||||
// 提交事务
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("提交事务失败: %w", err)
|
||||
}
|
||||
|
||||
// 触发清理(异步)
|
||||
go c.Cleanup(context.Background())
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Delete 删除缓存
|
||||
func (c *SQLiteCache) Delete(ctx context.Context, key string) error {
|
||||
query := `DELETE FROM translation_cache WHERE cache_key = ?`
|
||||
_, err := c.db.ExecContext(ctx, query, key)
|
||||
if err != nil {
|
||||
return fmt.Errorf("删除缓存失败: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Clear 清空缓存
|
||||
func (c *SQLiteCache) Clear(ctx context.Context) error {
|
||||
// 先删除所有记录
|
||||
_, err := c.db.ExecContext(ctx, `DELETE FROM translation_cache`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("清空缓存失败: %w", err)
|
||||
}
|
||||
|
||||
// 然后执行VACUUM(不能在事务中执行)
|
||||
_, err = c.db.ExecContext(ctx, `VACUUM`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("清理数据库失败: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stats 获取缓存统计信息
|
||||
func (c *SQLiteCache) Stats(ctx context.Context) (*CacheStats, error) {
|
||||
stats := &CacheStats{}
|
||||
|
||||
// 获取总记录数
|
||||
err := c.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM translation_cache`).Scan(&stats.TotalRecords)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("查询缓存统计失败: %w", err)
|
||||
}
|
||||
|
||||
// 如果没有记录,直接返回
|
||||
if stats.TotalRecords == 0 {
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
// 获取时间范围和平均tokens
|
||||
var oldestStr, newestStr sql.NullString
|
||||
var avgTokens sql.NullFloat64
|
||||
err = c.db.QueryRowContext(ctx, `
|
||||
SELECT
|
||||
MIN(created_at),
|
||||
MAX(created_at),
|
||||
AVG(total_tokens)
|
||||
FROM translation_cache
|
||||
`).Scan(&oldestStr, &newestStr, &avgTokens)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("查询缓存时间范围失败: %w", err)
|
||||
}
|
||||
|
||||
// 解析时间字符串
|
||||
if oldestStr.Valid {
|
||||
stats.OldestRecord, _ = time.Parse("2006-01-02 15:04:05", oldestStr.String)
|
||||
}
|
||||
if newestStr.Valid {
|
||||
stats.NewestRecord, _ = time.Parse("2006-01-02 15:04:05", newestStr.String)
|
||||
}
|
||||
if avgTokens.Valid {
|
||||
stats.AvgTokensPerRecord = avgTokens.Float64
|
||||
}
|
||||
|
||||
// 计算数据库文件大小
|
||||
dbPath, _ := expandPath(c.config.DBPath)
|
||||
if info, err := os.Stat(dbPath); err == nil {
|
||||
stats.TotalSizeBytes = info.Size()
|
||||
}
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
// Cleanup 清理过期缓存
|
||||
func (c *SQLiteCache) Cleanup(ctx context.Context) error {
|
||||
tx, err := c.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("开始事务失败: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
// 清理过期缓存
|
||||
if c.cleanupTTL > 0 {
|
||||
expiredTime := time.Now().Add(-c.cleanupTTL).Format("2006-01-02 15:04:05")
|
||||
_, err = tx.ExecContext(ctx, `DELETE FROM translation_cache WHERE last_used_at < ?`, expiredTime)
|
||||
if err != nil {
|
||||
return fmt.Errorf("清理过期缓存失败: %w", err)
|
||||
}
|
||||
} else if c.cleanupTTL == 0 {
|
||||
// 如果过期时间为0,清理所有记录
|
||||
_, err = tx.ExecContext(ctx, `DELETE FROM translation_cache`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("清理所有缓存失败: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 清理超出数量限制的缓存
|
||||
if c.config.MaxRecords > 0 {
|
||||
_, err = tx.ExecContext(ctx, `
|
||||
DELETE FROM translation_cache
|
||||
WHERE id NOT IN (
|
||||
SELECT id FROM translation_cache
|
||||
ORDER BY last_used_at DESC
|
||||
LIMIT ?
|
||||
)
|
||||
`, c.config.MaxRecords)
|
||||
if err != nil {
|
||||
return fmt.Errorf("清理超出数量限制的缓存失败: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// Close 关闭缓存
|
||||
func (c *SQLiteCache) Close() error {
|
||||
if c.db != nil {
|
||||
return c.db.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// updateLastUsed 更新最后使用时间
|
||||
func (c *SQLiteCache) updateLastUsed(ctx context.Context, key string) {
|
||||
query := `UPDATE translation_cache SET last_used_at = ? WHERE cache_key = ?`
|
||||
now := time.Now().Format("2006-01-02 15:04:05")
|
||||
c.db.ExecContext(ctx, query, now, key)
|
||||
}
|
||||
|
||||
// startCleanupTimer 启动清理定时器
|
||||
func (c *SQLiteCache) startCleanupTimer() {
|
||||
ticker := time.NewTicker(1 * time.Hour) // 每小时清理一次
|
||||
defer ticker.Stop()
|
||||
|
||||
for range ticker.C {
|
||||
c.Cleanup(context.Background())
|
||||
}
|
||||
}
|
||||
|
||||
// expandPath 展开路径中的~符号
|
||||
func expandPath(path string) (string, error) {
|
||||
if strings.HasPrefix(path, "~") {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
path = filepath.Join(home, path[1:])
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
@@ -12,15 +12,23 @@ import (
|
||||
// Config 全局配置结构
|
||||
type Config struct {
|
||||
// 全局设置
|
||||
DefaultProvider string `yaml:"default_provider"`
|
||||
DefaultModel string `yaml:"default_model"`
|
||||
Timeout int `yaml:"timeout"` // 秒
|
||||
DefaultProvider string `yaml:"default_provider"`
|
||||
DefaultModel string `yaml:"default_model"`
|
||||
Timeout int `yaml:"timeout"` // 秒
|
||||
DefaultSourceLang string `yaml:"default_source_lang"` // 默认源语言(auto为自动检测)
|
||||
DefaultTargetLang string `yaml:"default_target_lang"` // 默认目标语言
|
||||
|
||||
// 厂商配置
|
||||
Providers map[string]ProviderConfig `yaml:"providers"`
|
||||
|
||||
// Prompt配置
|
||||
Prompts map[string]string `yaml:"prompts"`
|
||||
|
||||
// 内容过滤配置
|
||||
SkipKeywords []string `yaml:"skip_keywords"` // 不翻译的关键词
|
||||
|
||||
// 缓存配置
|
||||
Cache CacheConfig `yaml:"cache"`
|
||||
}
|
||||
|
||||
// ProviderConfig 厂商配置
|
||||
@@ -31,6 +39,14 @@ type ProviderConfig struct {
|
||||
Enabled bool `yaml:"enabled"`
|
||||
}
|
||||
|
||||
// CacheConfig 缓存配置
|
||||
type CacheConfig struct {
|
||||
Enabled bool `yaml:"enabled"`
|
||||
MaxRecords int `yaml:"max_records"`
|
||||
ExpireDays int `yaml:"expire_days"`
|
||||
DBPath string `yaml:"db_path"`
|
||||
}
|
||||
|
||||
// ConfigLoader 配置加载器接口
|
||||
type ConfigLoader interface {
|
||||
Load(path string) (*Config, error)
|
||||
@@ -97,6 +113,12 @@ func (c *Config) setDefaults() {
|
||||
if c.DefaultModel == "" {
|
||||
c.DefaultModel = "gpt-3.5-turbo"
|
||||
}
|
||||
if c.DefaultSourceLang == "" {
|
||||
c.DefaultSourceLang = "auto" // 自动检测
|
||||
}
|
||||
if c.DefaultTargetLang == "" {
|
||||
c.DefaultTargetLang = "zh-CN" // 默认翻译为简体中文
|
||||
}
|
||||
|
||||
// 为每个厂商设置默认值
|
||||
for name, provider := range c.Providers {
|
||||
@@ -113,6 +135,27 @@ func (c *Config) setDefaults() {
|
||||
if c.Prompts == nil {
|
||||
c.Prompts = make(map[string]string)
|
||||
}
|
||||
|
||||
// 设置默认关键词
|
||||
if c.SkipKeywords == nil {
|
||||
c.SkipKeywords = []string{
|
||||
"TODO", "FIXME", "HACK", "XXX", "NOTE",
|
||||
"BUG", "WARN", "IMPORTANT", "TODO:",
|
||||
"FIXME:", "HACK:", "XXX:", "NOTE:",
|
||||
"BUG:", "WARN:", "IMPORTANT:",
|
||||
}
|
||||
}
|
||||
|
||||
// 设置缓存配置默认值
|
||||
if c.Cache.MaxRecords <= 0 {
|
||||
c.Cache.MaxRecords = 10000
|
||||
}
|
||||
if c.Cache.ExpireDays <= 0 {
|
||||
c.Cache.ExpireDays = 30
|
||||
}
|
||||
if c.Cache.DBPath == "" {
|
||||
c.Cache.DBPath = "~/.config/yoyo/cache.db"
|
||||
}
|
||||
}
|
||||
|
||||
// GetProviderConfig 获取指定厂商的配置
|
||||
@@ -190,6 +233,8 @@ func (c *Config) String() string {
|
||||
builder.WriteString(fmt.Sprintf("DefaultProvider: %s\n", c.DefaultProvider))
|
||||
builder.WriteString(fmt.Sprintf("DefaultModel: %s\n", c.DefaultModel))
|
||||
builder.WriteString(fmt.Sprintf("Timeout: %d seconds\n", c.Timeout))
|
||||
builder.WriteString(fmt.Sprintf("DefaultSourceLang: %s\n", c.DefaultSourceLang))
|
||||
builder.WriteString(fmt.Sprintf("DefaultTargetLang: %s\n", c.DefaultTargetLang))
|
||||
builder.WriteString("Providers:\n")
|
||||
for name, provider := range c.Providers {
|
||||
builder.WriteString(fmt.Sprintf(" %s: enabled=%v, model=%s\n", name, provider.Enabled, provider.Model))
|
||||
@@ -198,5 +243,10 @@ func (c *Config) String() string {
|
||||
for name := range c.Prompts {
|
||||
builder.WriteString(fmt.Sprintf(" %s\n", name))
|
||||
}
|
||||
builder.WriteString("Cache:\n")
|
||||
builder.WriteString(fmt.Sprintf(" enabled: %v\n", c.Cache.Enabled))
|
||||
builder.WriteString(fmt.Sprintf(" max_records: %d\n", c.Cache.MaxRecords))
|
||||
builder.WriteString(fmt.Sprintf(" expire_days: %d\n", c.Cache.ExpireDays))
|
||||
builder.WriteString(fmt.Sprintf(" db_path: %s\n", c.Cache.DBPath))
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
17
internal/content/content.go
Normal file
17
internal/content/content.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package content
|
||||
|
||||
import (
|
||||
"github.com/go-enry/go-enry/v2"
|
||||
)
|
||||
|
||||
const (
|
||||
Version = "1.0.0"
|
||||
)
|
||||
|
||||
func DetectLanguage(text string) string {
|
||||
return enry.GetLanguage("", []byte(text))
|
||||
}
|
||||
|
||||
func Filter(text string) string {
|
||||
return FilterBasic(text, nil)
|
||||
}
|
||||
56
internal/content/filter.go
Normal file
56
internal/content/filter.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package content
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type FilterOptions struct {
|
||||
RemoveControlChars bool
|
||||
NormalizeLineBreaks bool
|
||||
MaxConsecutiveSymbols int
|
||||
}
|
||||
|
||||
var defaultFilterOptions = &FilterOptions{
|
||||
RemoveControlChars: true,
|
||||
NormalizeLineBreaks: true,
|
||||
MaxConsecutiveSymbols: 20,
|
||||
}
|
||||
|
||||
var controlCharsRegex = regexp.MustCompile(`[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]`)
|
||||
|
||||
func FilterBasic(text string, opts *FilterOptions) string {
|
||||
if opts == nil {
|
||||
opts = defaultFilterOptions
|
||||
}
|
||||
|
||||
result := text
|
||||
|
||||
if opts.RemoveControlChars {
|
||||
result = controlCharsRegex.ReplaceAllString(result, "")
|
||||
}
|
||||
|
||||
if opts.NormalizeLineBreaks {
|
||||
result = strings.ReplaceAll(result, "\r\n", "\n")
|
||||
result = strings.ReplaceAll(result, "\r", "\n")
|
||||
}
|
||||
|
||||
if opts.MaxConsecutiveSymbols > 0 {
|
||||
result = truncateConsecutiveSymbols(result, opts.MaxConsecutiveSymbols)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func truncateConsecutiveSymbols(text string, maxCount int) string {
|
||||
symbols := []string{"=", "-", "_", "*", "#", "~", "`", "."}
|
||||
|
||||
for _, symbol := range symbols {
|
||||
pattern := regexp.MustCompile(regexp.QuoteMeta(symbol) + `{` + fmt.Sprintf("%d", maxCount+1) + `,}`)
|
||||
replacement := strings.Repeat(symbol, maxCount)
|
||||
text = pattern.ReplaceAllString(text, replacement)
|
||||
}
|
||||
|
||||
return text
|
||||
}
|
||||
453
internal/content/parser.go
Normal file
453
internal/content/parser.go
Normal file
@@ -0,0 +1,453 @@
|
||||
package content
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/go-enry/go-enry/v2"
|
||||
)
|
||||
|
||||
type SegmentType int
|
||||
|
||||
const (
|
||||
SegmentTypeText SegmentType = iota
|
||||
SegmentTypeCodeBlock
|
||||
SegmentTypeInlineCode
|
||||
SegmentTypeComment
|
||||
)
|
||||
|
||||
func (t SegmentType) String() string {
|
||||
switch t {
|
||||
case SegmentTypeText:
|
||||
return "text"
|
||||
case SegmentTypeCodeBlock:
|
||||
return "code_block"
|
||||
case SegmentTypeInlineCode:
|
||||
return "inline_code"
|
||||
case SegmentTypeComment:
|
||||
return "comment"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
|
||||
type ContentSegment struct {
|
||||
Type SegmentType
|
||||
Content string
|
||||
Translated string
|
||||
Language string
|
||||
IsComment bool
|
||||
StartPos int
|
||||
EndPos int
|
||||
}
|
||||
|
||||
type ParseResult struct {
|
||||
Segments []ContentSegment
|
||||
SourceLang string
|
||||
HasCode bool
|
||||
}
|
||||
|
||||
type languageCommentPatterns struct {
|
||||
LineComment string
|
||||
BlockComment []string
|
||||
}
|
||||
|
||||
var languagePatterns = map[string]languageCommentPatterns{
|
||||
"javascript": {LineComment: `//`, BlockComment: []string{`/*`, `*/`}},
|
||||
"typescript": {LineComment: `//`, BlockComment: []string{`/*`, `*/`}},
|
||||
"java": {LineComment: `//`, BlockComment: []string{`/*`, `*/`}},
|
||||
"kotlin": {LineComment: `//`, BlockComment: []string{`/*`, `*/`}},
|
||||
"scala": {LineComment: `//`, BlockComment: []string{`/*`, `*/`}},
|
||||
"c": {LineComment: `//`, BlockComment: []string{`/*`, `*/`}},
|
||||
"cpp": {LineComment: `//`, BlockComment: []string{`/*`, `*/`}},
|
||||
"c#": {LineComment: `//`, BlockComment: []string{`/*`, `*/`}},
|
||||
"go": {LineComment: `//`, BlockComment: []string{`/*`, `*/`}},
|
||||
"rust": {LineComment: `//`, BlockComment: []string{`/*`, `*/`}},
|
||||
"php": {LineComment: `//`, BlockComment: []string{`/*`, `*/`}},
|
||||
"swift": {LineComment: `//`, BlockComment: []string{`/*`, `*/`}},
|
||||
"objective-c": {LineComment: `//`, BlockComment: []string{`/*`, `*/`}},
|
||||
"scss": {LineComment: `//`, BlockComment: []string{`/*`, `*/`}},
|
||||
"css": {LineComment: ``, BlockComment: []string{`/*`, `*/`}},
|
||||
"less": {LineComment: ``, BlockComment: []string{`/*`, `*/`}},
|
||||
"html": {LineComment: ``, BlockComment: []string{`<!--`, `-->`}},
|
||||
"xml": {LineComment: ``, BlockComment: []string{`<!--`, `-->`}},
|
||||
"sql": {LineComment: `--`, BlockComment: []string{`/*`, `*/`}},
|
||||
"python": {LineComment: `#`, BlockComment: []string{`"""`, `"""`}},
|
||||
"ruby": {LineComment: `#`, BlockComment: []string{`=begin`, `=end`}},
|
||||
"shell": {LineComment: `#`, BlockComment: []string{}},
|
||||
"bash": {LineComment: `#`, BlockComment: []string{}},
|
||||
"powershell": {LineComment: `#`, BlockComment: []string{`<#`, `#>`}},
|
||||
"yaml": {LineComment: `#()`, BlockComment: []string{}},
|
||||
"json": {LineComment: ``, BlockComment: []string{}},
|
||||
"markdown": {LineComment: ``, BlockComment: []string{}},
|
||||
"vue": {LineComment: `//()`, BlockComment: []string{`/*`, `*/`, `<!--`, `-->`}},
|
||||
"svelte": {LineComment: `//()`, BlockComment: []string{`/*`, `*/`}},
|
||||
"jsx": {LineComment: `//()`, BlockComment: []string{`/*`, `*/`}},
|
||||
"tsx": {LineComment: `//()`, BlockComment: []string{`/*`, `*/`}},
|
||||
}
|
||||
|
||||
var defaultPatterns = languageCommentPatterns{
|
||||
LineComment: `//`,
|
||||
BlockComment: []string{`/*`, `*/`},
|
||||
}
|
||||
|
||||
type Parser struct {
|
||||
skipKeywords []string
|
||||
fallbackLang string
|
||||
}
|
||||
|
||||
func NewParser(skipKeywords []string) *Parser {
|
||||
if skipKeywords == nil {
|
||||
skipKeywords = []string{
|
||||
"TODO", "FIXME", "HACK", "XXX", "NOTE",
|
||||
"BUG", "WARN", "IMPORTANT", "TODO:",
|
||||
"FIXME:", "HACK:", "XXX:", "NOTE:",
|
||||
"BUG:", "WARN:", "IMPORTANT:",
|
||||
}
|
||||
}
|
||||
return &Parser{
|
||||
skipKeywords: skipKeywords,
|
||||
fallbackLang: "javascript",
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Parser) Parse(text string) (*ParseResult, error) {
|
||||
result := &ParseResult{
|
||||
Segments: []ContentSegment{},
|
||||
}
|
||||
|
||||
detectedLang := p.detectLanguage(text)
|
||||
result.SourceLang = detectedLang
|
||||
|
||||
segments := p.splitIntoSegments(text, result.SourceLang)
|
||||
|
||||
for _, seg := range segments {
|
||||
if seg.Type == SegmentTypeCodeBlock || seg.Type == SegmentTypeInlineCode {
|
||||
result.HasCode = true
|
||||
}
|
||||
result.Segments = append(result.Segments, seg)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (p *Parser) detectLanguage(text string) string {
|
||||
lines := strings.Split(text, "\n")
|
||||
var codeLines []string
|
||||
inCodeBlock := false
|
||||
|
||||
for _, line := range lines {
|
||||
trimmed := strings.TrimSpace(line)
|
||||
if strings.HasPrefix(trimmed, "```") {
|
||||
inCodeBlock = !inCodeBlock
|
||||
continue
|
||||
}
|
||||
if inCodeBlock && trimmed != "" {
|
||||
codeLines = append(codeLines, trimmed)
|
||||
}
|
||||
}
|
||||
|
||||
if len(codeLines) == 0 {
|
||||
for _, line := range lines {
|
||||
if strings.TrimSpace(line) != "" {
|
||||
codeLines = append(codeLines, line)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(codeLines) == 0 {
|
||||
return p.fallbackLang
|
||||
}
|
||||
|
||||
sample := strings.Join(codeLines[:min(len(codeLines), 10)], "\n")
|
||||
lang := enry.GetLanguage("", []byte(sample))
|
||||
|
||||
if lang == "" {
|
||||
return p.fallbackLang
|
||||
}
|
||||
|
||||
return strings.ToLower(lang)
|
||||
}
|
||||
|
||||
func (p *Parser) splitIntoSegments(text string, lang string) []ContentSegment {
|
||||
segments := []ContentSegment{}
|
||||
|
||||
codeBlockPattern := regexp.MustCompile("(?s)```[\\s\\S]*?^```|`[^`]+`")
|
||||
matches := codeBlockPattern.FindAllStringIndex(text, -1)
|
||||
|
||||
if len(matches) == 0 {
|
||||
segments = append(segments, ContentSegment{
|
||||
Type: SegmentTypeText,
|
||||
Content: text,
|
||||
StartPos: 0,
|
||||
EndPos: len(text),
|
||||
})
|
||||
return segments
|
||||
}
|
||||
|
||||
lastEnd := 0
|
||||
for _, match := range matches {
|
||||
start, end := match[0], match[1]
|
||||
|
||||
if start > lastEnd {
|
||||
textPart := text[lastEnd:start]
|
||||
textSegments := p.parseTextContent(textPart, lang)
|
||||
segments = append(segments, textSegments...)
|
||||
}
|
||||
|
||||
content := text[start:end]
|
||||
isInline := len(content) > 0 && content[0] == '`' && (len(content) == 1 || content[len(content)-1] == '`')
|
||||
|
||||
if strings.HasPrefix(content, "```") {
|
||||
segments = append(segments, ContentSegment{
|
||||
Type: SegmentTypeCodeBlock,
|
||||
Content: content,
|
||||
Language: p.detectCodeBlockLang(content),
|
||||
StartPos: start,
|
||||
EndPos: end,
|
||||
})
|
||||
} else if isInline {
|
||||
segments = append(segments, ContentSegment{
|
||||
Type: SegmentTypeInlineCode,
|
||||
Content: content,
|
||||
Language: lang,
|
||||
StartPos: start,
|
||||
EndPos: end,
|
||||
})
|
||||
}
|
||||
|
||||
lastEnd = end
|
||||
}
|
||||
|
||||
if lastEnd < len(text) {
|
||||
textPart := text[lastEnd:]
|
||||
textSegments := p.parseTextContent(textPart, lang)
|
||||
segments = append(segments, textSegments...)
|
||||
}
|
||||
|
||||
return segments
|
||||
}
|
||||
|
||||
func (p *Parser) parseTextContent(text string, lang string) []ContentSegment {
|
||||
segments := []ContentSegment{}
|
||||
langPatterns := getLanguagePatterns(lang)
|
||||
|
||||
if langPatterns.SingleLine == "" && len(langPatterns.MultiLine) == 0 {
|
||||
segments = append(segments, ContentSegment{
|
||||
Type: SegmentTypeText,
|
||||
Content: text,
|
||||
Language: lang,
|
||||
StartPos: 0,
|
||||
EndPos: len(text),
|
||||
})
|
||||
return segments
|
||||
}
|
||||
|
||||
commentPatterns := p.buildCommentRegex(langPatterns)
|
||||
if commentPatterns == nil {
|
||||
segments = append(segments, ContentSegment{
|
||||
Type: SegmentTypeText,
|
||||
Content: text,
|
||||
Language: lang,
|
||||
StartPos: 0,
|
||||
EndPos: len(text),
|
||||
})
|
||||
return segments
|
||||
}
|
||||
|
||||
matches := commentPatterns.FindAllStringIndex(text, -1)
|
||||
if len(matches) == 0 {
|
||||
segments = append(segments, ContentSegment{
|
||||
Type: SegmentTypeText,
|
||||
Content: text,
|
||||
Language: lang,
|
||||
StartPos: 0,
|
||||
EndPos: len(text),
|
||||
})
|
||||
return segments
|
||||
}
|
||||
|
||||
lastEnd := 0
|
||||
for _, match := range matches {
|
||||
start, end := match[0], match[1]
|
||||
|
||||
if start > lastEnd {
|
||||
segments = append(segments, ContentSegment{
|
||||
Type: SegmentTypeText,
|
||||
Content: text[lastEnd:start],
|
||||
Language: lang,
|
||||
StartPos: lastEnd,
|
||||
EndPos: start,
|
||||
})
|
||||
}
|
||||
|
||||
segments = append(segments, ContentSegment{
|
||||
Type: SegmentTypeComment,
|
||||
Content: text[start:end],
|
||||
IsComment: true,
|
||||
Language: lang,
|
||||
StartPos: start,
|
||||
EndPos: end,
|
||||
})
|
||||
|
||||
lastEnd = end
|
||||
}
|
||||
|
||||
if lastEnd < len(text) {
|
||||
segments = append(segments, ContentSegment{
|
||||
Type: SegmentTypeText,
|
||||
Content: text[lastEnd:],
|
||||
Language: lang,
|
||||
StartPos: lastEnd,
|
||||
EndPos: len(text),
|
||||
})
|
||||
}
|
||||
|
||||
return segments
|
||||
}
|
||||
|
||||
type languageCommentRegex struct {
|
||||
SingleLine string
|
||||
MultiLine []struct {
|
||||
Start string
|
||||
End string
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Parser) buildCommentRegex(patterns languageCommentRegex) *regexp.Regexp {
|
||||
var parts []string
|
||||
|
||||
if patterns.SingleLine != "" {
|
||||
parts = append(parts, patterns.SingleLine+`.*$`)
|
||||
}
|
||||
|
||||
for _, multi := range patterns.MultiLine {
|
||||
if multi.Start != "" && multi.End != "" {
|
||||
escapedStart := regexp.QuoteMeta(multi.Start)
|
||||
escapedEnd := regexp.QuoteMeta(multi.End)
|
||||
parts = append(parts, escapedStart+`[\s\S]*?`+escapedEnd)
|
||||
}
|
||||
}
|
||||
|
||||
if len(parts) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
pattern := `(?m)` + strings.Join(parts, "|")
|
||||
return regexp.MustCompile(pattern)
|
||||
}
|
||||
|
||||
func getLanguagePatterns(lang string) languageCommentRegex {
|
||||
patterns, ok := languagePatterns[lang]
|
||||
if !ok {
|
||||
patterns = defaultPatterns
|
||||
}
|
||||
|
||||
result := languageCommentRegex{
|
||||
SingleLine: patterns.LineComment,
|
||||
}
|
||||
|
||||
for _, bc := range patterns.BlockComment {
|
||||
if len(bc) >= 2 {
|
||||
result.MultiLine = append(result.MultiLine, struct {
|
||||
Start string
|
||||
End string
|
||||
}{Start: bc[:len(bc)/2], End: bc[len(bc)/2:]})
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func (p *Parser) detectCodeBlockLang(codeBlock string) string {
|
||||
lines := strings.Split(codeBlock, "\n")
|
||||
if len(lines) < 2 {
|
||||
return ""
|
||||
}
|
||||
|
||||
firstLine := strings.TrimSpace(lines[0])
|
||||
firstLine = strings.TrimPrefix(firstLine, "```")
|
||||
firstLine = strings.TrimSpace(firstLine)
|
||||
|
||||
if firstLine != "" {
|
||||
lang := strings.ToLower(firstLine)
|
||||
if _, ok := languagePatterns[lang]; ok {
|
||||
return lang
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func (p *Parser) BuildPrompt(result *ParseResult) string {
|
||||
var prompt strings.Builder
|
||||
|
||||
prompt.WriteString("你是一位专业的技术翻译。请翻译以下内容,遵守以下规则:\n\n")
|
||||
|
||||
prompt.WriteString("需要翻译的部分:\n")
|
||||
prompt.WriteString("- 普通文本:翻译成目标语言\n")
|
||||
prompt.WriteString("- 代码注释:只翻译注释中有意义的词汇,技术术语保留原语言\n\n")
|
||||
|
||||
prompt.WriteString("需要保持不变的部分:\n")
|
||||
prompt.WriteString("- 代码块(如 ```javascript ... ```)保持原样\n")
|
||||
prompt.WriteString("- 行内代码(如 `const count = 10`)保持原样\n")
|
||||
|
||||
if len(p.skipKeywords) > 0 {
|
||||
prompt.WriteString(fmt.Sprintf("- 以下关键词不翻译:%s\n", strings.Join(p.skipKeywords, "、")))
|
||||
}
|
||||
|
||||
prompt.WriteString("\n请将需要翻译的部分翻译成中文,其他部分保持不变。\n\n")
|
||||
prompt.WriteString("原文:\n---\n")
|
||||
|
||||
textToTranslate := p.extractTextForTranslation(result)
|
||||
prompt.WriteString(textToTranslate)
|
||||
|
||||
prompt.WriteString("\n---")
|
||||
|
||||
return prompt.String()
|
||||
}
|
||||
|
||||
func (p *Parser) extractTextForTranslation(result *ParseResult) string {
|
||||
var text strings.Builder
|
||||
|
||||
for _, seg := range result.Segments {
|
||||
switch seg.Type {
|
||||
case SegmentTypeText:
|
||||
text.WriteString(seg.Content)
|
||||
case SegmentTypeComment:
|
||||
text.WriteString(seg.Content)
|
||||
case SegmentTypeCodeBlock, SegmentTypeInlineCode:
|
||||
}
|
||||
}
|
||||
|
||||
return text.String()
|
||||
}
|
||||
|
||||
func (p *Parser) Reconstruct(result *ParseResult, translatedText string) string {
|
||||
translatedLines := strings.Split(translatedText, "\n")
|
||||
var output strings.Builder
|
||||
|
||||
textIndex := 0
|
||||
|
||||
for _, seg := range result.Segments {
|
||||
switch seg.Type {
|
||||
case SegmentTypeText, SegmentTypeComment:
|
||||
if textIndex < len(translatedLines) {
|
||||
output.WriteString(translatedLines[textIndex])
|
||||
textIndex++
|
||||
}
|
||||
case SegmentTypeCodeBlock, SegmentTypeInlineCode:
|
||||
output.WriteString(seg.Content)
|
||||
}
|
||||
}
|
||||
|
||||
return output.String()
|
||||
}
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
317
internal/lang/lang.go
Normal file
317
internal/lang/lang.go
Normal file
@@ -0,0 +1,317 @@
|
||||
package lang
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// 语言代码映射表
|
||||
var languageMap = map[string]string{
|
||||
// 中文变体
|
||||
"cn": "zh-CN",
|
||||
"zh": "zh-CN", // 默认简体中文
|
||||
"zhcn": "zh-CN",
|
||||
"zhtw": "zh-TW",
|
||||
"zhhk": "zh-HK",
|
||||
"zh-hans": "zh-CN",
|
||||
"zh-hant": "zh-TW",
|
||||
"chinese": "zh-CN",
|
||||
"简体中文": "zh-CN",
|
||||
"繁体中文": "zh-TW",
|
||||
|
||||
// 英语变体
|
||||
"en": "en-US", // 默认美式英语
|
||||
"us": "en-US",
|
||||
"uk": "en-GB",
|
||||
"gb": "en-GB",
|
||||
"english": "en-US",
|
||||
"美式英语": "en-US",
|
||||
"英式英语": "en-GB",
|
||||
|
||||
// 日语
|
||||
"jp": "ja",
|
||||
"ja": "ja",
|
||||
"japanese": "ja",
|
||||
"日语": "ja",
|
||||
|
||||
// 韩语
|
||||
"kr": "ko",
|
||||
"ko": "ko",
|
||||
"korean": "ko",
|
||||
"韩语": "ko",
|
||||
|
||||
// 西班牙语
|
||||
"es": "es-ES",
|
||||
"spanish": "es-ES",
|
||||
"西班牙语": "es-ES",
|
||||
|
||||
// 法语
|
||||
"fr": "fr-FR",
|
||||
"french": "fr-FR",
|
||||
"法语": "fr-FR",
|
||||
|
||||
// 德语
|
||||
"de": "de-DE",
|
||||
"german": "de-DE",
|
||||
"德语": "de-DE",
|
||||
|
||||
// 俄语
|
||||
"ru": "ru-RU",
|
||||
"russian": "ru-RU",
|
||||
"俄语": "ru-RU",
|
||||
|
||||
// 葡萄牙语
|
||||
"pt": "pt-PT",
|
||||
"portuguese": "pt-PT",
|
||||
"葡萄牙语": "pt-PT",
|
||||
"br": "pt-BR", // 巴西葡萄牙语
|
||||
|
||||
// 意大利语
|
||||
"it": "it-IT",
|
||||
"italian": "it-IT",
|
||||
"意大利语": "it-IT",
|
||||
|
||||
// 阿拉伯语
|
||||
"ar": "ar-SA",
|
||||
"arabic": "ar-SA",
|
||||
"阿拉伯语": "ar-SA",
|
||||
|
||||
// 印地语
|
||||
"hi": "hi-IN",
|
||||
"hindi": "hi-IN",
|
||||
"印地语": "hi-IN",
|
||||
|
||||
// 其他语言
|
||||
"nl": "nl-NL", // 荷兰语
|
||||
"dutch": "nl-NL",
|
||||
"sv": "sv-SE", // 瑞典语
|
||||
"swedish": "sv-SE",
|
||||
"no": "nb-NO", // 挪威语
|
||||
"norwegian": "nb-NO",
|
||||
"da": "da-DK", // 丹麦语
|
||||
"danish": "da-DK",
|
||||
"fi": "fi-FI", // 芬兰语
|
||||
"finnish": "fi-FI",
|
||||
"pl": "pl-PL", // 波兰语
|
||||
"polish": "pl-PL",
|
||||
"tr": "tr-TR", // 土耳其语
|
||||
"turkish": "tr-TR",
|
||||
"th": "th-TH", // 泰语
|
||||
"thai": "th-TH",
|
||||
"vi": "vi-VN", // 越南语
|
||||
"vietnamese": "vi-VN",
|
||||
"id": "id-ID", // 印尼语
|
||||
"indonesian": "id-ID",
|
||||
"ms": "ms-MY", // 马来语
|
||||
"malay": "ms-MY",
|
||||
}
|
||||
|
||||
// 语言名称到代码的映射(用于显示)
|
||||
var languageNames = map[string]string{
|
||||
"zh-CN": "中文(简体)",
|
||||
"zh-TW": "中文(繁体)",
|
||||
"zh-HK": "中文(香港)",
|
||||
"en-US": "English (US)",
|
||||
"en-GB": "English (UK)",
|
||||
"ja": "日本語",
|
||||
"ko": "한국어",
|
||||
"es-ES": "Español",
|
||||
"fr-FR": "Français",
|
||||
"de-DE": "Deutsch",
|
||||
"ru-RU": "Русский",
|
||||
"pt-PT": "Português",
|
||||
"pt-BR": "Português (Brasil)",
|
||||
"it-IT": "Italiano",
|
||||
"ar-SA": "العربية",
|
||||
"hi-IN": "हिन्दी",
|
||||
"nl-NL": "Nederlands",
|
||||
"sv-SE": "Svenska",
|
||||
"nb-NO": "Norsk",
|
||||
"da-DK": "Dansk",
|
||||
"fi-FI": "Suomi",
|
||||
"pl-PL": "Polski",
|
||||
"tr-TR": "Türkçe",
|
||||
"th-TH": "ไทย",
|
||||
"vi-VN": "Tiếng Việt",
|
||||
"id-ID": "Bahasa Indonesia",
|
||||
"ms-MY": "Bahasa Melayu",
|
||||
}
|
||||
|
||||
// ParseLanguageCode 解析语言代码
|
||||
// 支持多种格式:标准BCP47格式、别名、中文名称等
|
||||
func ParseLanguageCode(input string) string {
|
||||
if input == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
// 转换为小写进行匹配
|
||||
lower := strings.ToLower(strings.TrimSpace(input))
|
||||
|
||||
// 直接匹配
|
||||
if code, exists := languageMap[lower]; exists {
|
||||
return code
|
||||
}
|
||||
|
||||
// 尝试解析BCP47格式(如 zh-CN, en-US)
|
||||
if isValidLanguageTag(input) {
|
||||
return normalizeLanguageTag(input)
|
||||
}
|
||||
|
||||
// 如果无法解析,返回原始输入
|
||||
return input
|
||||
}
|
||||
|
||||
// isValidLanguageTag 检查是否是有效的语言标签格式
|
||||
func isValidLanguageTag(tag string) bool {
|
||||
// 简单的格式检查:语言代码-地区代码
|
||||
parts := strings.Split(tag, "-")
|
||||
if len(parts) == 1 {
|
||||
// 只有语言代码,如 "zh", "en"
|
||||
return len(parts[0]) >= 2 && len(parts[0]) <= 3
|
||||
}
|
||||
if len(parts) == 2 {
|
||||
// 语言代码-地区代码,如 "zh-CN", "en-US"
|
||||
return len(parts[0]) >= 2 && len(parts[0]) <= 3 && len(parts[1]) == 2
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// normalizeLanguageTag 标准化语言标签
|
||||
func normalizeLanguageTag(tag string) string {
|
||||
parts := strings.Split(tag, "-")
|
||||
if len(parts) == 1 {
|
||||
// 只有语言代码,使用默认地区
|
||||
defaultRegions := map[string]string{
|
||||
"zh": "CN",
|
||||
"en": "US",
|
||||
"ja": "JP",
|
||||
"ko": "KR",
|
||||
"es": "ES",
|
||||
"fr": "FR",
|
||||
"de": "DE",
|
||||
"ru": "RU",
|
||||
"pt": "PT",
|
||||
"it": "IT",
|
||||
"ar": "SA",
|
||||
"hi": "IN",
|
||||
"nl": "NL",
|
||||
"sv": "SE",
|
||||
"no": "NO",
|
||||
"da": "DK",
|
||||
"fi": "FI",
|
||||
"pl": "PL",
|
||||
"tr": "TR",
|
||||
"th": "TH",
|
||||
"vi": "VN",
|
||||
"id": "ID",
|
||||
"ms": "MY",
|
||||
}
|
||||
if region, exists := defaultRegions[parts[0]]; exists {
|
||||
return fmt.Sprintf("%s-%s", strings.ToLower(parts[0]), strings.ToUpper(region))
|
||||
}
|
||||
return tag
|
||||
}
|
||||
if len(parts) == 2 {
|
||||
// 标准化格式:语言小写,地区大写
|
||||
return fmt.Sprintf("%s-%s", strings.ToLower(parts[0]), strings.ToUpper(parts[1]))
|
||||
}
|
||||
return tag
|
||||
}
|
||||
|
||||
// GetLanguageName 获取语言名称(用于显示)
|
||||
func GetLanguageName(code string) string {
|
||||
if name, exists := languageNames[code]; exists {
|
||||
return name
|
||||
}
|
||||
return code
|
||||
}
|
||||
|
||||
// GetLanguageNameOrDefault 获取语言名称,如果不存在则返回代码
|
||||
func GetLanguageNameOrDefault(code string, defaultName string) string {
|
||||
if name, exists := languageNames[code]; exists {
|
||||
return name
|
||||
}
|
||||
return defaultName
|
||||
}
|
||||
|
||||
// SupportedLanguages 获取支持的语言列表
|
||||
func SupportedLanguages() []string {
|
||||
codes := make([]string, 0, len(languageNames))
|
||||
for code := range languageNames {
|
||||
codes = append(codes, code)
|
||||
}
|
||||
sort.Strings(codes)
|
||||
return codes
|
||||
}
|
||||
|
||||
// GetLanguageSuggestions 获取语言建议(用于模糊匹配)
|
||||
func GetLanguageSuggestions(input string, limit int) []string {
|
||||
if input == "" {
|
||||
return []string{}
|
||||
}
|
||||
|
||||
lower := strings.ToLower(input)
|
||||
suggestions := make([]string, 0)
|
||||
|
||||
for alias, code := range languageMap {
|
||||
if strings.Contains(alias, lower) || strings.Contains(strings.ToLower(code), lower) {
|
||||
// 避免重复
|
||||
found := false
|
||||
for _, s := range suggestions {
|
||||
if s == code {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
suggestions = append(suggestions, code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 限制数量
|
||||
if len(suggestions) > limit {
|
||||
suggestions = suggestions[:limit]
|
||||
}
|
||||
|
||||
return suggestions
|
||||
}
|
||||
|
||||
// IsLanguageSupported 检查语言是否支持
|
||||
func IsLanguageSupported(code string) bool {
|
||||
normalized := ParseLanguageCode(code)
|
||||
_, exists := languageNames[normalized]
|
||||
return exists
|
||||
}
|
||||
|
||||
// GetCommonLanguages 获取常用语言列表
|
||||
func GetCommonLanguages() []string {
|
||||
return []string{
|
||||
"zh-CN", // 中文(简体)
|
||||
"en-US", // 英语(美国)
|
||||
"ja", // 日语
|
||||
"ko", // 韩语
|
||||
"es-ES", // 西班牙语
|
||||
"fr-FR", // 法语
|
||||
"de-DE", // 德语
|
||||
"ru-RU", // 俄语
|
||||
"pt-PT", // 葡萄牙语
|
||||
"it-IT", // 意大利语
|
||||
}
|
||||
}
|
||||
|
||||
// GetLanguageDirection 获取语言方向(从左到右或从右到左)
|
||||
func GetLanguageDirection(code string) string {
|
||||
rtlLanguages := map[string]bool{
|
||||
"ar-SA": true, // 阿拉伯语
|
||||
"he-IL": true, // 希伯来语
|
||||
"fa-IR": true, // 波斯语
|
||||
"ur-PK": true, // 乌尔都语
|
||||
}
|
||||
|
||||
if rtlLanguages[code] {
|
||||
return "rtl"
|
||||
}
|
||||
return "ltr"
|
||||
}
|
||||
224
internal/lang/lang_test.go
Normal file
224
internal/lang/lang_test.go
Normal file
@@ -0,0 +1,224 @@
|
||||
package lang
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseLanguageCode(t *testing.T) {
|
||||
tests := []struct {
|
||||
input string
|
||||
expected string
|
||||
}{
|
||||
// 中文变体
|
||||
{"cn", "zh-CN"},
|
||||
{"zh", "zh-CN"},
|
||||
{"zh-CN", "zh-CN"},
|
||||
{"zh-TW", "zh-TW"},
|
||||
{"zh-HK", "zh-HK"},
|
||||
{"chinese", "zh-CN"},
|
||||
{"简体中文", "zh-CN"},
|
||||
|
||||
// 英语变体
|
||||
{"en", "en-US"},
|
||||
{"en-US", "en-US"},
|
||||
{"en-GB", "en-GB"},
|
||||
{"us", "en-US"},
|
||||
{"uk", "en-GB"},
|
||||
{"english", "en-US"},
|
||||
|
||||
// 其他语言
|
||||
{"jp", "ja"},
|
||||
{"ja", "ja"},
|
||||
{"japanese", "ja"},
|
||||
{"kr", "ko"},
|
||||
{"ko", "ko"},
|
||||
{"korean", "ko"},
|
||||
{"es", "es-ES"},
|
||||
{"spanish", "es-ES"},
|
||||
{"fr", "fr-FR"},
|
||||
{"french", "fr-FR"},
|
||||
{"de", "de-DE"},
|
||||
{"german", "de-DE"},
|
||||
|
||||
// 空值
|
||||
{"", ""},
|
||||
|
||||
// 未知语言(应返回原始输入)
|
||||
{"unknown", "unknown"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.input, func(t *testing.T) {
|
||||
result := ParseLanguageCode(tt.input)
|
||||
if result != tt.expected {
|
||||
t.Errorf("ParseLanguageCode(%q) = %q, 期望 %q", tt.input, result, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetLanguageName(t *testing.T) {
|
||||
tests := []struct {
|
||||
code string
|
||||
expected string
|
||||
}{
|
||||
{"zh-CN", "中文(简体)"},
|
||||
{"zh-TW", "中文(繁体)"},
|
||||
{"en-US", "English (US)"},
|
||||
{"en-GB", "English (UK)"},
|
||||
{"ja", "日本語"},
|
||||
{"ko", "한국어"},
|
||||
{"es-ES", "Español"},
|
||||
{"fr-FR", "Français"},
|
||||
{"de-DE", "Deutsch"},
|
||||
{"unknown", "unknown"}, // 未知代码返回原值
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.code, func(t *testing.T) {
|
||||
result := GetLanguageName(tt.code)
|
||||
if result != tt.expected {
|
||||
t.Errorf("GetLanguageName(%q) = %q, 期望 %q", tt.code, result, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportedLanguages(t *testing.T) {
|
||||
languages := SupportedLanguages()
|
||||
if len(languages) == 0 {
|
||||
t.Error("SupportedLanguages() 不应返回空列表")
|
||||
}
|
||||
|
||||
// 检查一些关键语言是否在列表中
|
||||
expectedLanguages := []string{"zh-CN", "en-US", "ja", "ko"}
|
||||
for _, expected := range expectedLanguages {
|
||||
found := false
|
||||
for _, lang := range languages {
|
||||
if lang == expected {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("Expected language %q not found in supported languages", expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetLanguageSuggestions(t *testing.T) {
|
||||
tests := []struct {
|
||||
input string
|
||||
limit int
|
||||
minCount int
|
||||
}{
|
||||
{"zh", 5, 1},
|
||||
{"en", 5, 1},
|
||||
{"chinese", 5, 1},
|
||||
{"", 5, 0},
|
||||
{"unknown", 5, 0},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.input, func(t *testing.T) {
|
||||
suggestions := GetLanguageSuggestions(tt.input, tt.limit)
|
||||
if len(suggestions) < tt.minCount {
|
||||
t.Errorf("GetLanguageSuggestions(%q, %d) 返回 %d 个建议,至少需要 %d 个",
|
||||
tt.input, tt.limit, len(suggestions), tt.minCount)
|
||||
}
|
||||
if len(suggestions) > tt.limit {
|
||||
t.Errorf("GetLanguageSuggestions(%q, %d) 返回 %d 个建议,超过限制 %d 个",
|
||||
tt.input, tt.limit, len(suggestions), tt.limit)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsLanguageSupported(t *testing.T) {
|
||||
tests := []struct {
|
||||
code string
|
||||
expected bool
|
||||
}{
|
||||
{"zh-CN", true},
|
||||
{"en-US", true},
|
||||
{"ja", true},
|
||||
{"unknown", false},
|
||||
{"", false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.code, func(t *testing.T) {
|
||||
result := IsLanguageSupported(tt.code)
|
||||
if result != tt.expected {
|
||||
t.Errorf("IsLanguageSupported(%q) = %v, 期望 %v", tt.code, result, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetCommonLanguages(t *testing.T) {
|
||||
languages := GetCommonLanguages()
|
||||
if len(languages) == 0 {
|
||||
t.Error("GetCommonLanguages() 不应返回空列表")
|
||||
}
|
||||
|
||||
// 检查一些关键语言是否在列表中
|
||||
expectedLanguages := []string{"zh-CN", "en-US", "ja"}
|
||||
for _, expected := range expectedLanguages {
|
||||
found := false
|
||||
for _, lang := range languages {
|
||||
if lang == expected {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("Expected language %q not found in common languages", expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetLanguageDirection(t *testing.T) {
|
||||
tests := []struct {
|
||||
code string
|
||||
expected string
|
||||
}{
|
||||
{"zh-CN", "ltr"},
|
||||
{"en-US", "ltr"},
|
||||
{"ja", "ltr"},
|
||||
{"ar-SA", "rtl"},
|
||||
{"he-IL", "rtl"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.code, func(t *testing.T) {
|
||||
result := GetLanguageDirection(tt.code)
|
||||
if result != tt.expected {
|
||||
t.Errorf("GetLanguageDirection(%q) = %q, 期望 %q", tt.code, result, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeLanguageTag(t *testing.T) {
|
||||
tests := []struct {
|
||||
input string
|
||||
expected string
|
||||
}{
|
||||
{"zh", "zh-CN"},
|
||||
{"en", "en-US"},
|
||||
{"ja", "ja-JP"},
|
||||
{"zh-CN", "zh-CN"},
|
||||
{"zh-tw", "zh-TW"},
|
||||
{"EN-us", "en-US"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.input, func(t *testing.T) {
|
||||
result := normalizeLanguageTag(tt.input)
|
||||
if result != tt.expected {
|
||||
t.Errorf("normalizeLanguageTag(%q) = %q, 期望 %q", tt.input, result, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
305
internal/onboard/onboard.go
Normal file
305
internal/onboard/onboard.go
Normal file
@@ -0,0 +1,305 @@
|
||||
package onboard
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/AlecAivazis/survey/v2"
|
||||
"github.com/titor/fanyi/internal/config"
|
||||
"github.com/titor/fanyi/internal/lang"
|
||||
)
|
||||
|
||||
// RunOnboard 启动配置向导
|
||||
func RunOnboard(force bool) error {
|
||||
fmt.Println("欢迎使用YOYO翻译工具配置向导!")
|
||||
fmt.Println("这个向导将帮助您配置翻译工具。")
|
||||
fmt.Println()
|
||||
|
||||
// 检查配置文件是否存在
|
||||
configPath := "configs/config.yaml"
|
||||
if _, err := os.Stat(configPath); err == nil && !force {
|
||||
overwrite := false
|
||||
prompt := &survey.Confirm{
|
||||
Message: "检测到配置文件已存在,是否要重新配置?",
|
||||
Default: false,
|
||||
}
|
||||
if err := survey.AskOne(prompt, &overwrite); err != nil {
|
||||
return fmt.Errorf("用户输入错误: %w", err)
|
||||
}
|
||||
if !overwrite {
|
||||
fmt.Println("配置已取消。")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// 步骤1: 选择主要厂商
|
||||
fmt.Println("步骤1: 选择主要翻译服务提供商")
|
||||
providerName, err := SelectProvider()
|
||||
if err != nil {
|
||||
return fmt.Errorf("选择厂商失败: %w", err)
|
||||
}
|
||||
|
||||
// 步骤2: 配置主要厂商
|
||||
fmt.Println("\n步骤2: 配置主要厂商")
|
||||
providerConfig, err := ConfigureProvider(providerName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("配置厂商失败: %w", err)
|
||||
}
|
||||
|
||||
// 步骤3: 全局设置
|
||||
fmt.Println("\n步骤3: 全局设置")
|
||||
globalConfig, err := GlobalSettings()
|
||||
if err != nil {
|
||||
return fmt.Errorf("全局设置失败: %w", err)
|
||||
}
|
||||
|
||||
// 步骤4: 确认并保存配置
|
||||
fmt.Println("\n步骤4: 保存配置")
|
||||
configData := BuildConfig(providerName, providerConfig, globalConfig)
|
||||
|
||||
if err := SaveConfig(configData, configPath); err != nil {
|
||||
return fmt.Errorf("保存配置失败: %w", err)
|
||||
}
|
||||
|
||||
fmt.Printf("\n配置完成! 配置文件已保存到: %s\n", configPath)
|
||||
fmt.Println("\n您现在可以使用以下命令进行翻译:")
|
||||
fmt.Println(" yoyo \"Hello world\"")
|
||||
fmt.Println(" yoyo --lang=cn \"Hello world\"")
|
||||
fmt.Println("\n更多帮助请运行: yoyo --help")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SelectProvider 选择主要厂商
|
||||
func SelectProvider() (string, error) {
|
||||
providers := []string{
|
||||
"siliconflow",
|
||||
"volcano",
|
||||
"national",
|
||||
"qwen",
|
||||
"openai",
|
||||
}
|
||||
|
||||
providerNames := map[string]string{
|
||||
"siliconflow": "硅基流动 (推荐,免费额度)",
|
||||
"volcano": "火山引擎",
|
||||
"national": "国家超算",
|
||||
"qwen": "Qwen (通义千问)",
|
||||
"openai": "OpenAI兼容格式",
|
||||
}
|
||||
|
||||
var selected string
|
||||
prompt := &survey.Select{
|
||||
Message: "请选择要使用的翻译服务提供商:",
|
||||
Options: func() []string {
|
||||
var opts []string
|
||||
for _, p := range providers {
|
||||
opts = append(opts, providerNames[p])
|
||||
}
|
||||
return opts
|
||||
}(),
|
||||
Default: providerNames["siliconflow"],
|
||||
}
|
||||
|
||||
if err := survey.AskOne(prompt, &selected); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 返回对应的厂商名称
|
||||
for name, displayName := range providerNames {
|
||||
if displayName == selected {
|
||||
return name, nil
|
||||
}
|
||||
}
|
||||
|
||||
return "siliconflow", nil
|
||||
}
|
||||
|
||||
// ConfigureProvider 配置厂商
|
||||
func ConfigureProvider(providerName string) (config.ProviderConfig, error) {
|
||||
// 厂商默认配置
|
||||
defaults := map[string]config.ProviderConfig{
|
||||
"siliconflow": {
|
||||
APIHost: "https://api.siliconflow.cn/v1",
|
||||
Model: "siliconflow-base",
|
||||
Enabled: true,
|
||||
},
|
||||
"volcano": {
|
||||
APIHost: "https://api.volcengine.com/v1",
|
||||
Model: "volcano-chat",
|
||||
Enabled: true,
|
||||
},
|
||||
"national": {
|
||||
APIHost: "https://api.nsc.gov.cn/v1",
|
||||
Model: "nsc-base",
|
||||
Enabled: true,
|
||||
},
|
||||
"qwen": {
|
||||
APIHost: "https://dashscope.aliyuncs.com/compatible-mode/v1",
|
||||
Model: "qwen-turbo",
|
||||
Enabled: true,
|
||||
},
|
||||
"openai": {
|
||||
APIHost: "https://api.openai.com/v1",
|
||||
Model: "gpt-3.5-turbo",
|
||||
Enabled: true,
|
||||
},
|
||||
}
|
||||
|
||||
defaultConfig := defaults[providerName]
|
||||
cfg := config.ProviderConfig{
|
||||
APIHost: defaultConfig.APIHost,
|
||||
Model: defaultConfig.Model,
|
||||
Enabled: defaultConfig.Enabled,
|
||||
}
|
||||
|
||||
// 输入API密钥
|
||||
apiKeyPrompt := &survey.Input{
|
||||
Message: fmt.Sprintf("请输入 %s 的API密钥:", providerName),
|
||||
Help: "API密钥用于身份验证,将存储在配置文件中",
|
||||
}
|
||||
if err := survey.AskOne(apiKeyPrompt, &cfg.APIKey, survey.WithValidator(survey.Required)); err != nil {
|
||||
return config.ProviderConfig{}, err
|
||||
}
|
||||
|
||||
// 确认API HOST
|
||||
apiHostPrompt := &survey.Input{
|
||||
Message: "API HOST (直接回车使用默认值):",
|
||||
Default: cfg.APIHost,
|
||||
}
|
||||
if err := survey.AskOne(apiHostPrompt, &cfg.APIHost); err != nil {
|
||||
return config.ProviderConfig{}, err
|
||||
}
|
||||
|
||||
// 确认默认模型
|
||||
modelPrompt := &survey.Input{
|
||||
Message: "默认模型 (直接回车使用默认值):",
|
||||
Default: cfg.Model,
|
||||
}
|
||||
if err := survey.AskOne(modelPrompt, &cfg.Model); err != nil {
|
||||
return config.ProviderConfig{}, err
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// GlobalSettings 全局设置
|
||||
type GlobalConfig struct {
|
||||
DefaultProvider string
|
||||
DefaultModel string
|
||||
Timeout int
|
||||
DefaultSourceLang string
|
||||
DefaultTargetLang string
|
||||
}
|
||||
|
||||
// GlobalSettings 全局设置
|
||||
func GlobalSettings() (*GlobalConfig, error) {
|
||||
cfg := &GlobalConfig{
|
||||
DefaultProvider: "siliconflow",
|
||||
DefaultModel: "siliconflow-base",
|
||||
Timeout: 30,
|
||||
DefaultSourceLang: "auto",
|
||||
DefaultTargetLang: "zh-CN",
|
||||
}
|
||||
|
||||
// 选择默认语言
|
||||
targetLangOptions := lang.GetCommonLanguages()
|
||||
var targetLangDisplay []string
|
||||
for _, code := range targetLangOptions {
|
||||
targetLangDisplay = append(targetLangDisplay, fmt.Sprintf("%s (%s)", code, lang.GetLanguageName(code)))
|
||||
}
|
||||
|
||||
targetLangPrompt := &survey.Select{
|
||||
Message: "请选择默认目标语言:",
|
||||
Options: targetLangDisplay,
|
||||
Default: fmt.Sprintf("%s (%s)", "zh-CN", lang.GetLanguageName("zh-CN")),
|
||||
}
|
||||
|
||||
var selectedTarget string
|
||||
if err := survey.AskOne(targetLangPrompt, &selectedTarget); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 从选择中提取语言代码
|
||||
for i, display := range targetLangDisplay {
|
||||
if display == selectedTarget {
|
||||
cfg.DefaultTargetLang = targetLangOptions[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// 设置超时时间
|
||||
timeoutPrompt := &survey.Input{
|
||||
Message: "API超时时间(秒):",
|
||||
Default: fmt.Sprintf("%d", cfg.Timeout),
|
||||
}
|
||||
var timeoutStr string
|
||||
if err := survey.AskOne(timeoutPrompt, &timeoutStr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 解析超时时间
|
||||
if timeout := parseIntOrDefault(timeoutStr, 30); timeout > 0 {
|
||||
cfg.Timeout = timeout
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// BuildConfig 构建配置对象
|
||||
func BuildConfig(providerName string, providerConfig config.ProviderConfig, globalConfig *GlobalConfig) *config.Config {
|
||||
// 创建厂商配置
|
||||
providers := map[string]config.ProviderConfig{
|
||||
providerName: providerConfig,
|
||||
}
|
||||
|
||||
// 创建Prompt配置
|
||||
prompts := map[string]string{
|
||||
"technical": "你是一位专业的技术翻译,请准确翻译以下技术文档,保持专业术语的准确性。",
|
||||
"creative": "你是一位富有创造力的翻译家,请用优美流畅的语言翻译以下内容。",
|
||||
"academic": "你是一位学术翻译专家,请用严谨的学术语言翻译以下内容。",
|
||||
"simple": "请用简单易懂的语言翻译以下内容。",
|
||||
}
|
||||
|
||||
return &config.Config{
|
||||
DefaultProvider: providerName,
|
||||
DefaultModel: providerConfig.Model,
|
||||
Timeout: globalConfig.Timeout,
|
||||
DefaultSourceLang: globalConfig.DefaultSourceLang,
|
||||
DefaultTargetLang: globalConfig.DefaultTargetLang,
|
||||
Providers: providers,
|
||||
Prompts: prompts,
|
||||
}
|
||||
}
|
||||
|
||||
// SaveConfig 保存配置文件
|
||||
func SaveConfig(cfg *config.Config, path string) error {
|
||||
// 确保目录存在
|
||||
dir := filepath.Dir(path)
|
||||
if err := os.MkdirAll(dir, 0755); err != nil {
|
||||
return fmt.Errorf("创建配置目录失败: %w", err)
|
||||
}
|
||||
|
||||
// 使用config包的Save方法
|
||||
loader := &config.YAMLConfigLoader{}
|
||||
return loader.Save(cfg, path)
|
||||
}
|
||||
|
||||
// parseIntOrDefault 解析整数,失败时返回默认值
|
||||
func parseIntOrDefault(s string, defaultValue int) int {
|
||||
if s == "" {
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
var result int
|
||||
if _, err := fmt.Sscanf(s, "%d", &result); err != nil {
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
if result <= 0 {
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
@@ -5,24 +5,44 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/titor/fanyi/internal/cache"
|
||||
"github.com/titor/fanyi/internal/config"
|
||||
"github.com/titor/fanyi/internal/content"
|
||||
"github.com/titor/fanyi/internal/provider"
|
||||
)
|
||||
|
||||
// Translator 核心翻译类
|
||||
type Translator struct {
|
||||
config *config.Config
|
||||
provider provider.Provider
|
||||
prompt *PromptManager
|
||||
config *config.Config
|
||||
provider provider.Provider
|
||||
prompt *PromptManager
|
||||
contentParser *content.Parser
|
||||
cache cache.Cache
|
||||
}
|
||||
|
||||
// NewTranslator 创建翻译器实例
|
||||
func NewTranslator(config *config.Config, provider provider.Provider) *Translator {
|
||||
return &Translator{
|
||||
config: config,
|
||||
provider: provider,
|
||||
prompt: NewPromptManager(config.Prompts),
|
||||
translator := &Translator{
|
||||
config: config,
|
||||
provider: provider,
|
||||
prompt: NewPromptManager(config.Prompts),
|
||||
contentParser: content.NewParser(config.SkipKeywords),
|
||||
}
|
||||
|
||||
// 初始化缓存(如果启用)
|
||||
if config.Cache.Enabled {
|
||||
cacheConfig := &cache.CacheConfig{
|
||||
Enabled: config.Cache.Enabled,
|
||||
MaxRecords: config.Cache.MaxRecords,
|
||||
ExpireDays: config.Cache.ExpireDays,
|
||||
DBPath: config.Cache.DBPath,
|
||||
}
|
||||
if cacheInstance, err := cache.NewSQLiteCache(cacheConfig); err == nil {
|
||||
translator.cache = cacheInstance
|
||||
}
|
||||
}
|
||||
|
||||
return translator
|
||||
}
|
||||
|
||||
// Translate 执行翻译
|
||||
@@ -31,15 +51,33 @@ func (t *Translator) Translate(ctx context.Context, text string, options *Transl
|
||||
timeoutCtx, cancel := context.WithTimeout(ctx, time.Duration(t.config.Timeout)*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// 基础字符过滤
|
||||
filteredText := content.FilterBasic(text, nil)
|
||||
|
||||
// 内容解析(包含代码检测)
|
||||
parseResult, parseErr := t.contentParser.Parse(filteredText)
|
||||
|
||||
// 选择Prompt
|
||||
prompt := ""
|
||||
if options.PromptName != "" {
|
||||
prompt = t.prompt.GetPrompt(options.PromptName)
|
||||
}
|
||||
|
||||
// 如果包含代码且解析成功,使用增强的Prompt
|
||||
if parseErr == nil && parseResult.HasCode {
|
||||
enhancedPrompt := t.contentParser.BuildPrompt(parseResult)
|
||||
if enhancedPrompt != "" {
|
||||
if prompt != "" {
|
||||
prompt = prompt + "\n\n" + enhancedPrompt
|
||||
} else {
|
||||
prompt = enhancedPrompt
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 构建请求
|
||||
req := &provider.TranslateRequest{
|
||||
Text: text,
|
||||
Text: filteredText,
|
||||
FromLang: options.FromLang,
|
||||
ToLang: options.ToLang,
|
||||
Prompt: prompt,
|
||||
@@ -47,16 +85,63 @@ func (t *Translator) Translate(ctx context.Context, text string, options *Transl
|
||||
Options: options.ExtraOptions,
|
||||
}
|
||||
|
||||
// 检查缓存
|
||||
if t.cache != nil {
|
||||
cacheKey := cache.GenerateCacheKey(filteredText, options.FromLang, options.ToLang)
|
||||
if cachedEntry, err := t.cache.Get(ctx, cacheKey); err == nil && cachedEntry != nil {
|
||||
// 缓存命中
|
||||
return &TranslateResult{
|
||||
Original: text,
|
||||
Translated: cachedEntry.TranslatedText,
|
||||
FromLang: cachedEntry.FromLang,
|
||||
ToLang: cachedEntry.ToLang,
|
||||
Model: cachedEntry.Model,
|
||||
Usage: &provider.Usage{
|
||||
PromptTokens: cachedEntry.PromptTokens,
|
||||
CompletionTokens: cachedEntry.CompletionTokens,
|
||||
TotalTokens: cachedEntry.TotalTokens,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// 调用厂商API
|
||||
resp, err := t.provider.Translate(timeoutCtx, req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("翻译失败: %w", err)
|
||||
}
|
||||
|
||||
translatedText := resp.Text
|
||||
|
||||
// 如果包含代码且解析成功,重构结果
|
||||
if parseErr == nil && parseResult.HasCode {
|
||||
translatedText = t.contentParser.Reconstruct(parseResult, resp.Text)
|
||||
}
|
||||
|
||||
// 保存到缓存
|
||||
if t.cache != nil {
|
||||
cacheKey := cache.GenerateCacheKey(filteredText, options.FromLang, options.ToLang)
|
||||
cacheEntry := &cache.CacheEntry{
|
||||
CacheKey: cacheKey,
|
||||
OriginalText: filteredText,
|
||||
TranslatedText: translatedText,
|
||||
FromLang: resp.FromLang,
|
||||
ToLang: resp.ToLang,
|
||||
Model: resp.Model,
|
||||
PromptName: options.PromptName,
|
||||
PromptContent: prompt,
|
||||
PromptTokens: resp.Usage.PromptTokens,
|
||||
CompletionTokens: resp.Usage.CompletionTokens,
|
||||
TotalTokens: resp.Usage.TotalTokens,
|
||||
}
|
||||
// 异步保存缓存,不阻塞翻译结果返回
|
||||
go t.cache.Set(context.Background(), cacheEntry)
|
||||
}
|
||||
|
||||
// 构建结果
|
||||
return &TranslateResult{
|
||||
Original: text,
|
||||
Translated: resp.Text,
|
||||
Translated: translatedText,
|
||||
FromLang: resp.FromLang,
|
||||
ToLang: resp.ToLang,
|
||||
Model: resp.Model,
|
||||
|
||||
344
memory.md
344
memory.md
@@ -92,6 +92,31 @@
|
||||
|
||||
---
|
||||
|
||||
### 环境变量加载问题
|
||||
**问题**: 配置文件中的环境变量没有正确加载
|
||||
**原因**: Go程序不会自动加载.env文件,需要使用第三方库
|
||||
**解决方案**:
|
||||
1. 使用`github.com/joho/godotenv`包
|
||||
2. 在程序启动时调用`godotenv.Load()`
|
||||
3. 将.env文件添加到.gitignore
|
||||
|
||||
**代码示例**:
|
||||
```go
|
||||
import "github.com/joho/godotenv"
|
||||
|
||||
func main() {
|
||||
_ = godotenv.Load() // 加载.env文件
|
||||
// 然后加载配置文件
|
||||
}
|
||||
```
|
||||
|
||||
**注意事项**:
|
||||
- 不要提交真实的.env文件到版本控制
|
||||
- 提供.env.example模板
|
||||
- 在文档中说明环境变量配置方法
|
||||
|
||||
---
|
||||
|
||||
## 配置最佳实践
|
||||
|
||||
### 安全配置
|
||||
@@ -163,4 +188,321 @@
|
||||
1. 用户编辑why.md记录初衷
|
||||
2. AI编辑taolun.md记录讨论
|
||||
3. AI更新changelog.md记录版本
|
||||
4. AI更新memory.md记录经验
|
||||
4. AI更新memory.md记录经验
|
||||
|
||||
---
|
||||
|
||||
## 语言代码处理经验
|
||||
|
||||
### 语言代码标准化
|
||||
**问题**: 需要支持多种语言代码格式,但内部应使用标准格式
|
||||
**解决方案**:
|
||||
1. 使用BCP 47语言标签作为标准格式(如 `zh-CN`、`en-US`)
|
||||
2. 实现智能解析函数 `ParseLanguageCode()`
|
||||
3. 支持别名映射(如 `cn` → `zh-CN`、`en` → `en-US`)
|
||||
|
||||
**最佳实践**:
|
||||
- 语言代码小写,地区代码大写(如 `zh-CN`,不是 `zh-cn`)
|
||||
- 提供语言名称映射用于显示(如 `zh-CN` → "中文(简体)")
|
||||
- 支持模糊匹配和建议功能
|
||||
|
||||
### 交互式配置经验
|
||||
**问题**: 命令行工具需要友好的配置界面
|
||||
**解决方案**:
|
||||
1. 使用 `github.com/AlecAivazis/survey/v2` 库
|
||||
2. 实现分步配置流程
|
||||
3. 提供默认值和确认选项
|
||||
|
||||
**注意事项**:
|
||||
- 交互式库需要终端支持
|
||||
- 提供非交互式模式(如配置文件模板)
|
||||
- 错误处理要友好,避免程序崩溃
|
||||
|
||||
### 命令行参数解析经验
|
||||
**问题**: Go标准库 `flag` 包功能有限,需要支持子命令
|
||||
**解决方案**:
|
||||
1. 使用 `flag` 包解析选项参数
|
||||
2. 手动处理子命令(如 `onboard`)
|
||||
3. 提供清晰的帮助信息
|
||||
|
||||
**命名冲突处理**:
|
||||
- 避免变量名与包名冲突(如 `onboard` 变量与 `onboard` 包)
|
||||
- 使用后缀区分(如 `onboardFlag`)
|
||||
|
||||
## 配置文件管理经验
|
||||
|
||||
### 开发阶段配置策略
|
||||
**决策**: 开发阶段使用 `.env` + `configs/config.yaml`
|
||||
**原因**:
|
||||
1. 简化开发环境配置
|
||||
2. 符合12-factor应用原则
|
||||
3. 避免过早优化
|
||||
|
||||
**实施**:
|
||||
- `.env` 文件存储API密钥等敏感信息
|
||||
- `configs/config.yaml` 存储复杂配置结构
|
||||
- 使用环境变量替换 `${VAR}`
|
||||
|
||||
### 配置文件格式选择
|
||||
**决策**: 使用YAML格式
|
||||
**原因**:
|
||||
1. 人类可读性好
|
||||
2. 支持复杂数据结构
|
||||
3. Go生态支持良好
|
||||
|
||||
**注意事项**:
|
||||
- 使用 `gopkg.in/yaml.v3` 库
|
||||
- 注意缩进和格式
|
||||
- 提供配置验证
|
||||
|
||||
---
|
||||
|
||||
## 管道功能实现经验
|
||||
|
||||
### 管道输入检测
|
||||
**问题**: 如何检测是否有管道输入?
|
||||
**解决方案**:
|
||||
1. 使用 `os.Stdin.Stat()` 获取标准输入的状态
|
||||
2. 检查 `fileInfo.Mode() & os.ModeCharDevice` 是否为0
|
||||
3. 如果为0,表示是管道或文件重定向
|
||||
|
||||
**代码示例**:
|
||||
```go
|
||||
func isPipeInput() bool {
|
||||
fileInfo, err := os.Stdin.Stat()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return (fileInfo.Mode()&os.ModeCharDevice) == 0
|
||||
}
|
||||
```
|
||||
|
||||
**注意事项**:
|
||||
- 在管道模式下,即使没有命令行参数也应继续执行
|
||||
- 管道输入可能为空,需要处理空输入情况
|
||||
- 错误信息应输出到stderr,避免污染管道输出
|
||||
|
||||
### 管道输入读取
|
||||
**问题**: 如何从标准输入读取所有内容?
|
||||
**解决方案**:
|
||||
1. 使用 `bufio.Scanner` 逐行读取
|
||||
2. 使用 `strings.Join()` 合并多行
|
||||
3. 处理读取错误
|
||||
|
||||
**代码示例**:
|
||||
```go
|
||||
func readFromStdin() (string, error) {
|
||||
scanner := bufio.NewScanner(os.Stdin)
|
||||
var lines []string
|
||||
for scanner.Scan() {
|
||||
lines = append(lines, scanner.Text())
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return "", fmt.Errorf("读取标准输入失败: %w", err)
|
||||
}
|
||||
return strings.Join(lines, "\n"), nil
|
||||
}
|
||||
```
|
||||
|
||||
### 静默模式设计
|
||||
**问题**: 管道使用时,统计信息会污染输出
|
||||
**解决方案**:
|
||||
1. 添加 `--quiet` 和 `-q` 参数
|
||||
2. 将统计信息输出到stderr
|
||||
3. 静默模式下只输出翻译结果
|
||||
|
||||
**设计原则**:
|
||||
- 翻译结果始终输出到stdout
|
||||
- 统计信息输出到stderr
|
||||
- 静默模式下抑制统计信息输出
|
||||
- 错误信息始终输出到stderr
|
||||
|
||||
### 正则表达式转义
|
||||
**问题**: 特殊字符在正则表达式中需要转义
|
||||
**解决方案**:
|
||||
1. 使用 `regexp.QuoteMeta()` 转义特殊字符
|
||||
2. 避免手动拼接正则表达式
|
||||
|
||||
**代码示例**:
|
||||
```go
|
||||
// 错误的方式
|
||||
pattern := regexp.MustCompile(symbol + `{21,}`) // 如果symbol是*会出错
|
||||
|
||||
// 正确的方式
|
||||
pattern := regexp.MustCompile(regexp.QuoteMeta(symbol) + `{21,}`)
|
||||
```
|
||||
|
||||
**特殊字符列表**:
|
||||
- `*`, `+`, `?`, `.`, `^`, `$`, `|`, `(`, `)`, `[`, `]`, `{`, `}`
|
||||
|
||||
### 输出重定向
|
||||
**问题**: 如何确保管道输出不被其他信息污染?
|
||||
**解决方案**:
|
||||
1. 翻译结果使用 `fmt.Println()` 输出到stdout
|
||||
2. 统计信息使用 `fmt.Fprintf(os.Stderr, ...)` 输出到stderr
|
||||
3. 错误信息也输出到stderr
|
||||
|
||||
**最佳实践**:
|
||||
- 始终区分stdout和stderr的使用场景
|
||||
- 为管道功能提供静默模式选项
|
||||
- 确保错误信息不影响管道输出
|
||||
|
||||
---
|
||||
|
||||
## 本地缓存实现经验
|
||||
|
||||
### SQLite数据库设计
|
||||
**问题**: 如何设计缓存表结构以支持高效的查询和存储?
|
||||
**解决方案**:
|
||||
1. 使用缓存键(cache_key)作为唯一索引
|
||||
2. 包含完整字段:原文、译文、语言对、模型、Prompt、用量统计
|
||||
3. 添加created_at和last_used_at时间戳字段
|
||||
4. 创建适当的索引提高查询性能
|
||||
|
||||
**表结构**:
|
||||
```sql
|
||||
CREATE TABLE translation_cache (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
cache_key TEXT NOT NULL UNIQUE,
|
||||
original_text TEXT NOT NULL,
|
||||
translated_text TEXT NOT NULL,
|
||||
from_lang TEXT NOT NULL,
|
||||
to_lang TEXT NOT NULL,
|
||||
model TEXT NOT NULL,
|
||||
prompt_name TEXT,
|
||||
prompt_content TEXT,
|
||||
prompt_tokens INTEGER DEFAULT 0,
|
||||
completion_tokens INTEGER DEFAULT 0,
|
||||
total_tokens INTEGER DEFAULT 0,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
last_used_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
```
|
||||
|
||||
**索引设计**:
|
||||
```sql
|
||||
CREATE INDEX idx_cache_key ON translation_cache(cache_key);
|
||||
CREATE INDEX idx_original_text ON translation_cache(original_text);
|
||||
CREATE INDEX idx_created_at ON translation_cache(created_at);
|
||||
CREATE INDEX idx_last_used_at ON translation_cache(last_used_at);
|
||||
```
|
||||
|
||||
### 缓存键生成策略
|
||||
**问题**: 如何生成唯一的缓存键,确保相同内容返回相同结果?
|
||||
**解决方案**:
|
||||
1. 使用SHA256哈希算法
|
||||
2. 哈希输入:原文+语言对(from_lang+to_lang)
|
||||
3. 规范化输入:移除多余空白字符,统一语言代码格式
|
||||
|
||||
**代码示例**:
|
||||
```go
|
||||
func GenerateCacheKey(originalText, fromLang, toLang string) string {
|
||||
// 规范化语言代码
|
||||
fromLang = normalizeLanguageCode(fromLang)
|
||||
toLang = normalizeLanguageCode(toLang)
|
||||
|
||||
// 规范化原文
|
||||
normalizedText := normalizeText(originalText)
|
||||
|
||||
// 生成缓存键
|
||||
data := fmt.Sprintf("%s|%s|%s", normalizedText, fromLang, toLang)
|
||||
hash := sha256.Sum256([]byte(data))
|
||||
return hex.EncodeToString(hash[:])
|
||||
}
|
||||
```
|
||||
|
||||
### SQLite NULL值处理
|
||||
**问题**: 当缓存表为空时,MIN(created_at)返回NULL,导致时间转换错误
|
||||
**解决方案**:
|
||||
1. 使用sql.NullString和sql.NullFloat64类型
|
||||
2. 检查Valid字段判断是否为NULL
|
||||
3. 只在有记录时才查询时间范围
|
||||
|
||||
**代码示例**:
|
||||
```go
|
||||
var oldestStr, newestStr sql.NullString
|
||||
var avgTokens sql.NullFloat64
|
||||
err = c.db.QueryRowContext(ctx, `
|
||||
SELECT MIN(created_at), MAX(created_at), AVG(total_tokens)
|
||||
FROM translation_cache
|
||||
`).Scan(&oldestStr, &newestStr, &avgTokens)
|
||||
|
||||
if oldestStr.Valid {
|
||||
stats.OldestRecord, _ = time.Parse("2006-01-02 15:04:05", oldestStr.String)
|
||||
}
|
||||
```
|
||||
|
||||
### 缓存集成策略
|
||||
**问题**: 如何将缓存功能集成到现有的翻译流程中?
|
||||
**解决方案**:
|
||||
1. 在Translator结构中添加缓存字段
|
||||
2. 修改NewTranslator函数,初始化缓存实例
|
||||
3. 在Translate方法中实现"先查缓存再调用API"策略
|
||||
4. 翻译成功后异步保存到缓存
|
||||
|
||||
**集成流程**:
|
||||
```
|
||||
翻译请求 → 生成缓存键 → 查询缓存 → 缓存命中? → 直接返回
|
||||
↓ 否
|
||||
调用API翻译 → 保存到缓存 → 返回结果
|
||||
```
|
||||
|
||||
### 异步缓存保存
|
||||
**问题**: 如何避免缓存保存阻塞翻译结果返回?
|
||||
**解决方案**:
|
||||
1. 使用goroutine异步保存缓存
|
||||
2. 使用context.Background()创建新的上下文
|
||||
3. 错误日志记录到标准错误输出
|
||||
|
||||
**代码示例**:
|
||||
```go
|
||||
// 异步保存缓存,不阻塞翻译结果返回
|
||||
go t.cache.Set(context.Background(), cacheEntry)
|
||||
```
|
||||
|
||||
### 组合清理策略
|
||||
**问题**: 如何平衡缓存大小和缓存时效性?
|
||||
**解决方案**:
|
||||
1. 数量限制:限制最大记录数
|
||||
2. 时间过期:设置缓存过期时间
|
||||
3. 组合策略:同时应用两种限制
|
||||
|
||||
**清理逻辑**:
|
||||
1. 清理过期记录:`DELETE FROM cache WHERE last_used_at < ?`
|
||||
2. 清理超出数量限制:保留最近使用的N条记录
|
||||
3. 定时清理:每小时自动清理一次
|
||||
|
||||
### 性能优化
|
||||
**SQLite性能优化**:
|
||||
1. 使用WAL模式(Write-Ahead Logging)
|
||||
2. 设置适当的连接池参数
|
||||
3. 使用索引提高查询性能
|
||||
4. 批量操作使用事务
|
||||
|
||||
**Go SQLite配置**:
|
||||
```go
|
||||
db, err := sql.Open("sqlite3", dbPath+"?_journal_mode=WAL&_synchronous=NORMAL")
|
||||
db.SetMaxOpenConns(1) // SQLite只支持单个写入连接
|
||||
db.SetMaxIdleConns(1)
|
||||
```
|
||||
|
||||
### 错误处理经验
|
||||
**常见错误及解决方案**:
|
||||
1. **NULL值转换错误**: 使用sql.NullString类型
|
||||
2. **时间解析错误**: 使用正确的时间格式字符串
|
||||
3. **数据库锁定错误**: 设置适当的连接池参数
|
||||
4. **权限错误**: 确保目录存在且有写入权限
|
||||
|
||||
### 测试策略
|
||||
**单元测试要点**:
|
||||
1. 测试缓存键生成的一致性
|
||||
2. 测试缓存命中和未命中情况
|
||||
3. 测试清理策略的正确性
|
||||
4. 测试NULL值处理
|
||||
5. 测试并发访问安全性
|
||||
|
||||
**集成测试要点**:
|
||||
1. 测试缓存与Translator的集成
|
||||
2. 测试配置文件的正确加载
|
||||
3. 测试缓存命令的正确执行
|
||||
4. 测试错误情况的正确处理
|
||||
256
taolun.md
256
taolun.md
@@ -125,4 +125,258 @@
|
||||
|
||||
**关联文档**:
|
||||
- [AGENTS.md#OOP设计模式](AGENTS.md#oop设计模式)
|
||||
- [changelog.md#0.0.2](changelog.md#002)
|
||||
- [changelog.md#0.0.2](changelog.md#002)
|
||||
|
||||
---
|
||||
|
||||
### [2026-03-29 00:00] 版本 0.0.3 - 环境变量加载修复
|
||||
**原因**: 测试CLI时发现环境变量没有正确加载
|
||||
**分析**:
|
||||
- 配置文件中使用`${ENV_VAR}`语法
|
||||
- Go的`os.ExpandEnv`只在加载时替换
|
||||
- 需要先加载.env文件到环境变量
|
||||
|
||||
**解决方案**:
|
||||
1. 添加`github.com/joho/godotenv`依赖
|
||||
2. 在main函数开始时调用`godotenv.Load()`
|
||||
3. 更新memory.md记录踩坑经验
|
||||
|
||||
**技术细节**:
|
||||
- godotenv会自动查找当前目录的.env文件
|
||||
- 如果文件不存在会返回错误,可以忽略
|
||||
- 不影响已有的环境变量
|
||||
|
||||
**关联文档**:
|
||||
- [memory.md#环境变量加载问题](memory.md#环境变量加载问题)
|
||||
- [changelog.md#0.0.3](changelog.md#003)
|
||||
|
||||
---
|
||||
|
||||
### [2026-03-29 10:00] 版本 0.2.0 - 语言代码解析设计
|
||||
**原因**: 用户需要通过 `--lang` 参数指定目标语言,支持多种语言代码格式
|
||||
**分析**:
|
||||
- 需要支持标准BCP47格式(如 `zh-CN`、`en-US`)
|
||||
- 需要支持简短别名(如 `cn`、`en`)
|
||||
- 需要支持中文名称(如 `chinese`、`english`)
|
||||
- 需要智能解析和错误提示
|
||||
|
||||
**解决方案**:
|
||||
1. 创建 `internal/lang/lang.go` 模块
|
||||
2. 实现语言代码映射表和解析函数
|
||||
3. 支持大小写不敏感和模糊匹配
|
||||
4. 提供语言名称获取和建议功能
|
||||
|
||||
**技术细节**:
|
||||
- 使用 `map[string]string` 存储语言代码映射
|
||||
- 实现 `ParseLanguageCode()` 函数进行智能解析
|
||||
- 支持30+种语言和变体
|
||||
- 添加完整的单元测试
|
||||
|
||||
**关联文档**:
|
||||
- [AGENTS.md#语言代码处理](AGENTS.md#语言代码处理)
|
||||
- [changelog.md#0.2.0](changelog.md#020)
|
||||
|
||||
---
|
||||
|
||||
### [2026-03-29 10:30] 版本 0.2.0 - onboard配置向导
|
||||
**原因**: 用户需要友好的配置界面,特别是第一次使用时
|
||||
**分析**:
|
||||
- 需要交互式配置向导
|
||||
- 需要支持选择厂商、输入API密钥、设置默认值
|
||||
- 需要生成标准的YAML配置文件
|
||||
- 需要支持强制重新配置
|
||||
|
||||
**解决方案**:
|
||||
1. 使用 `github.com/AlecAivazis/survey/v2` 库
|
||||
2. 实现分步配置流程:选择厂商 → 配置厂商 → 全局设置 → 保存
|
||||
3. 提供友好的错误处理和用户提示
|
||||
4. 支持 `--force` 参数强制重新配置
|
||||
|
||||
**技术细节**:
|
||||
- 使用 `survey.Select`、`survey.Input`、`survey.Confirm` 组件
|
||||
- 实现厂商默认配置和自定义选项
|
||||
- 生成完整的配置文件包含所有必要字段
|
||||
- 支持配置文件存在性检查
|
||||
|
||||
**关联文档**:
|
||||
- [AGENTS.md#Onboard配置向导](AGENTS.md#onboard配置向导)
|
||||
- [changelog.md#0.2.0](changelog.md#020)
|
||||
|
||||
---
|
||||
|
||||
### [2026-03-29 11:00] 版本 0.2.0 - 分阶段迁移策略
|
||||
**原因**: 需要平衡开发便利性和最终上线需求
|
||||
**分析**:
|
||||
- 开发阶段需要简单配置方式(`.env` + `configs/config.yaml`)
|
||||
- 上线前需要迁移到用户配置目录(`~/.config/yoo/yoo.yml`)
|
||||
- 需要平滑的迁移路径和向后兼容性
|
||||
|
||||
**解决方案**:
|
||||
1. **第一阶段(当前)**: 继续使用 `.env` + `configs/config.yaml`
|
||||
2. **第二阶段(上线前)**: 实现配置文件路径查找和迁移工具
|
||||
3. **第三阶段(最终)**: 移除 `.env` 依赖,完全使用配置文件
|
||||
|
||||
**技术细节**:
|
||||
- 配置文件路径优先级:命令行 > 环境变量 > 用户目录 > 当前目录
|
||||
- 保持向后兼容性,支持旧配置格式
|
||||
- 提供配置验证和错误提示
|
||||
- 实现配置迁移工具(计划)
|
||||
|
||||
**关联文档**:
|
||||
- [AGENTS.md#分阶段迁移策略](AGENTS.md#分阶段迁移策略)
|
||||
- [changelog.md#0.2.0](changelog.md#020)
|
||||
|
||||
---
|
||||
|
||||
### [2026-03-29 12:00] 版本 0.4.0 - 管道符功能
|
||||
**原因**: 用户需要与其他命令行工具联合使用
|
||||
**分析**:
|
||||
- 用户希望支持管道符功能,如 `cat a.txt | yoyo | grep "who are you"`
|
||||
- 需要检测管道输入并从stdin读取内容
|
||||
- 需要控制统计信息输出,避免污染管道输出
|
||||
- 需要保持向后兼容性
|
||||
|
||||
**解决方案**:
|
||||
1. **管道输入检测**: 实现 `isPipeInput()` 函数,使用 `os.Stdin.Stat()` 检测管道
|
||||
2. **stdin读取**: 实现 `readFromStdin()` 函数,使用 `bufio.Scanner` 读取所有输入
|
||||
3. **静默模式**: 添加 `--quiet` 和 `-q` 参数,控制统计信息输出
|
||||
4. **输出重定向**: 将统计信息输出到stderr,避免污染管道输出
|
||||
|
||||
**技术细节**:
|
||||
- 使用 `os.ModeCharDevice` 检测是否为管道设备
|
||||
- 使用 `strings.Join()` 合并多行输入为单个字符串
|
||||
- 统计信息输出到 `os.Stderr` 而不是 `os.Stdout`
|
||||
- 修复 content/filter.go 中的正则表达式转义问题
|
||||
|
||||
**使用示例**:
|
||||
```bash
|
||||
# 基本管道功能
|
||||
echo "Hello world" | yoyo
|
||||
cat file.txt | yoyo --lang=en
|
||||
|
||||
# 静默模式
|
||||
echo "Hello world" | yoyo -q
|
||||
echo "Hello world" | yoyo --quiet
|
||||
|
||||
# 与其他命令组合
|
||||
cat file.txt | yoyo | grep "你好"
|
||||
yoyo "Hello" | wc -l
|
||||
```
|
||||
|
||||
**关联文档**:
|
||||
- [AGENTS.md#管道符功能](AGENTS.md#管道符功能)
|
||||
- [changelog.md#0.4.0](changelog.md#040)
|
||||
|
||||
---
|
||||
|
||||
### [2026-03-29 15:00] 版本 0.5.0 - 本地缓存功能设计
|
||||
**原因**: 用户希望减少API调用,添加本地缓存功能
|
||||
**分析**:
|
||||
- 需要存储翻译结果,避免重复调用API
|
||||
- 需要设计缓存键策略,确保缓存准确性
|
||||
- 需要考虑数据库选择、事务处理、性能优化
|
||||
- 需要设计缓存管理策略
|
||||
|
||||
**解决方案**:
|
||||
1. **数据库选择**: 使用SQLite
|
||||
- 轻量级,无需服务器
|
||||
- 支持ACID事务
|
||||
- Go生态支持良好 (`github.com/mattn/go-sqlite3`)
|
||||
- 适合嵌入式应用
|
||||
|
||||
2. **缓存键设计**:
|
||||
- 使用文本内容 + 源语言 + 目标语言
|
||||
- 生成SHA256哈希作为缓存键
|
||||
- 规范化输入:移除多余空白字符,统一语言代码格式
|
||||
|
||||
3. **事务处理**:
|
||||
- 使用事务保证数据一致性
|
||||
- 插入操作在事务中执行
|
||||
- 查询操作不需要显式事务
|
||||
|
||||
4. **保存时机**:
|
||||
- 在输出结果之前保存到数据库
|
||||
- 确保数据持久化
|
||||
- 异步保存,不阻塞翻译结果返回
|
||||
|
||||
5. **性能优化**:
|
||||
- 为缓存键创建索引
|
||||
- 使用哈希键减少存储空间
|
||||
- 限制缓存表大小(可配置)
|
||||
- 使用WAL模式提高并发性能
|
||||
|
||||
6. **缓存策略**:
|
||||
- 采用组合策略:数量限制+时间过期
|
||||
- 默认启用缓存功能
|
||||
- 提供手动清理命令
|
||||
|
||||
7. **存储位置**:
|
||||
- 数据库文件存储在用户配置目录 `~/.config/yoyo/cache.db`
|
||||
- 符合XDG规范
|
||||
- 支持自定义路径配置
|
||||
|
||||
**技术细节**:
|
||||
- 使用 `github.com/mattn/go-sqlite3` 驱动
|
||||
- 实现 `internal/cache/cache.go` 模块
|
||||
- 缓存表结构:`id`, `cache_key`, `original_text`, `translated_text`, `from_lang`, `to_lang`, `model`, `prompt`, `created_at`
|
||||
- 缓存键生成:`sha256(text + "|" + fromLang + "|" + toLang)`
|
||||
- 查询缓存时使用 `SELECT translated_text FROM cache WHERE cache_key = ?`
|
||||
- 插入缓存时使用 `INSERT OR IGNORE INTO cache (...) VALUES (...)`
|
||||
|
||||
**关联文档**:
|
||||
- [AGENTS.md#本地缓存功能设计](AGENTS.md#本地缓存功能设计)
|
||||
- [changelog.md#0.5.0](changelog.md#050)
|
||||
|
||||
---
|
||||
|
||||
### [2026-03-29 20:00] 版本 0.5.1 - 缓存功能修复
|
||||
**原因**: 缓存功能测试中发现的问题
|
||||
**分析**:
|
||||
1. **VACUUM事务错误**: 缓存清空命令中,VACUUM不能在事务中执行
|
||||
2. **NULL值转换错误**: 缓存统计查询在空表时,MIN(created_at)返回NULL导致转换错误
|
||||
3. **过期清理策略**: 当expire_days=0时,清理逻辑不工作
|
||||
|
||||
**解决方案**:
|
||||
1. **修复VACUUM事务错误**:
|
||||
- 将VACUUM移到事务之外执行
|
||||
- 先删除记录,再执行VACUUM
|
||||
|
||||
2. **修复NULL值转换错误**:
|
||||
- 使用 `sql.NullString` 和 `sql.NullFloat64` 类型
|
||||
- 检查 `Valid` 字段判断是否为NULL
|
||||
- 只在有记录时才查询时间范围
|
||||
|
||||
3. **修复过期清理策略**:
|
||||
- 当cleanupTTL为0时,清理所有记录
|
||||
- 添加条件判断:`if c.cleanupTTL == 0 { ... }`
|
||||
|
||||
**技术细节**:
|
||||
```go
|
||||
// 修复VACUUM事务错误
|
||||
func (c *SQLiteCache) Clear(ctx context.Context) error {
|
||||
// 先删除所有记录
|
||||
_, err := c.db.ExecContext(ctx, `DELETE FROM translation_cache`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("清空缓存失败: %w", err)
|
||||
}
|
||||
// 然后执行VACUUM(不能在事务中执行)
|
||||
_, err = c.db.ExecContext(ctx, `VACUUM`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("清理数据库失败: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 修复NULL值转换错误
|
||||
var oldestStr, newestStr sql.NullString
|
||||
var avgTokens sql.NullFloat64
|
||||
err = c.db.QueryRowContext(ctx, `SELECT MIN(created_at), MAX(created_at), AVG(total_tokens) FROM translation_cache`).Scan(&oldestStr, &newestStr, &avgTokens)
|
||||
|
||||
if oldestStr.Valid {
|
||||
stats.OldestRecord, _ = time.Parse("2006-01-02 15:04:05", oldestStr.String)
|
||||
}
|
||||
```
|
||||
|
||||
**关联文档**:
|
||||
- [changelog.md#0.5.1](changelog.md#051)
|
||||
- [memory.md#本地缓存实现经验](memory.md#本地缓存实现经验)
|
||||
Reference in New Issue
Block a user