Skip to content

rossroma/wdc-translator

Repository files navigation

WDC Translator

License: MIT TypeScript Node.js

一个基于词汇难度和上下文的智能翻译工具,能够自动识别文本中的高难度词汇并提供准确的中文翻译。

🌟 功能特性

  • 智能词汇识别:基于CEFR词汇难度等级自动识别高难度词汇
  • 上下文感知:提取词汇的上下文信息,提供更准确的翻译
  • 双模式词形还原:⚡ 提供轻量级(8x速度提升)和Compromise两种词形还原方法
  • 高性能优化:轻量级词形还原实现,显著提升处理速度
  • 多模型支持:支持OpenAI GPT、Moonshot、Chrome内置Gemini Nano等多种AI模型
  • 本地AI翻译:支持Chrome内置Gemini Nano模型,无需API密钥,保护隐私
  • 灵活配置:可自定义难度阈值、最小词汇长度、词形还原方法等参数
  • TypeScript支持:完整的类型定义和类型安全

📦 安装

npm install wdc-translator

🚀 快速开始

基本使用

const { main } = require('wdc-translator');

const text = `Books are not just a source of entertainment; they are a profound medium for intellectual and emotional exploration. They challenge our preconceptions and invite us to engage in critical thinking.`;

const options = {
  difficulty: 4,        // 难度等级 (1-10)
  minLength: 3,         // 最小词汇长度
  model: 'moonshot-v1-8k',
  apiKey: 'your-api-key',
  apiUrl: 'https://api.moonshot.cn/v1/chat/completions',
  isTranslate: true     // 启用翻译功能
};

main(text, options).then(result => {
  console.log('翻译结果:', result);
}).catch(error => {
  console.error('错误:', error);
});

使用Chrome内置Gemini Nano翻译(推荐)

// 浏览器环境中使用
import { extractWordsWithTranslation } from './dist/wdc-translator.js';

const text = `Books are not just a source of entertainment; they are a profound medium for intellectual and emotional exploration.`;

const options = {
  difficulty: 5,        // 难度等级
  minLength: 4,         // 最小词汇长度
  model: 'gemini-nano', // 使用Chrome内置AI
  isTranslate: true     // 启用翻译
};

extractWordsWithTranslation(text, options).then(result => {
  console.log('翻译结果:', result);
  // 输出格式:
  // [
  //   {
  //     word: "profound",
  //     context: "they are a profound medium for...",
  //     translation: "深刻的"
  //   },
  //   ...
  // ]
}).catch(error => {
  console.error('错误:', error);
});

Gemini Nano环境要求:

  • Chrome 126+ 版本
  • 启用 chrome://flags/#prompt-api-for-gemini-nano
  • 启用 chrome://flags/#optimization-guide-on-device(设置为"Enabled BypassPerfRequirement")
  • 确保 chrome://components/ 中的"Optimization Guide On Device Model"已下载

仅提取高难度词汇

const options = {
  difficulty: 4,
  minLength: 3,
  isTranslate: false  // 不进行翻译,仅提取词汇
};

main(text, options).then(words => {
  console.log('高难度词汇:', words);
});

📖 API 文档

main(content: string, options: MainConfig): Promise<any>

主函数,用于处理文本并提取/翻译高难度词汇。

参数

  • content (string): 要处理的文本内容
  • options (MainConfig): 配置选项

返回值

  • isTranslate: false 时:返回高难度词汇数组
  • isTranslate: true 时:返回翻译结果数组

extractWordsWithTranslation(content: string, options: MainConfig): Promise<WordWithTranslation[]>

专门用于Chrome内置Gemini Nano翻译的函数,返回包含翻译结果的完整数据结构。

参数

  • content (string): 要处理的文本内容
  • options (MainConfig): 配置选项

返回值

返回 WordWithTranslation[] 数组,每个元素包含:

  • word (string): 原始单词
  • context (string): 单词所在的句子上下文
  • translation (string | undefined): 中文翻译结果(可能为undefined如果翻译失败)

MainConfig 接口

interface MainConfig {
  difficulty: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;  // 难度等级 (1-10)
  minLength: 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;           // 最小词汇长度
  model: string;                                        // AI模型名称
  apiKey: string;                                       // API密钥
  apiUrl?: string;                                      // 自定义API地址
  temperature?: number;                                 // 温度参数 (0-1)
  maxTokens?: number;                                   // 最大令牌数
  isTranslate?: boolean;                                // 是否启用翻译
  lemmatizer?: 'lightweight' | 'compromise';            // 词形还原方法(默认: 'lightweight')
}

comparePerformance(content: string, options: MainConfig)

性能对比函数,比较两种词形还原方法的效率和准确性。

返回值

{
  lightweight: PerformanceMetrics,  // 轻量级方法的性能数据
  compromise: PerformanceMetrics,    // Compromise方法的性能数据
  speedup: number                    // 速度提升倍数
}

🔧 配置说明

难度等级 (difficulty)

  • 1-3: 基础词汇 (A1-A2)
  • 4-6: 中级词汇 (B1-B2)
  • 7-9: 高级词汇 (C1-C2)
  • 10: 专业词汇

支持的AI模型

  • gpt-3.5-turbo
  • gpt-4
  • moonshot-v1-8k
  • 其他兼容OpenAI API的模型

API配置

// OpenAI
{
  apiUrl: 'https://api.openai.com/v1/chat/completions',
  model: 'gpt-3.5-turbo'
}

// Moonshot
{
  apiUrl: 'https://api.moonshot.cn/v1/chat/completions',
  model: 'moonshot-v1-8k'
}

⚡ 词形还原方法选择

本项目提供两种词形还原方法,可根据需求选择:

轻量级方法(推荐)

const { extractWords } = require('wdc-translator');

// 使用轻量级方法(默认)
const words = extractWords(text, {
  difficulty: 5,
  minLength: 4,
  lemmatizer: 'lightweight'  // 或者不指定,默认就是 lightweight
});

// 性能特点:
// ✓ 速度快8倍以上
// ✓ 零额外依赖
// ✓ 适合大规模文本处理

Compromise方法

// 使用Compromise方法
const words = extractWords(text, {
  difficulty: 5,
  minLength: 4,
  lemmatizer: 'compromise'
});

// 性能特点:
// ✓ 更全面的NLP功能
// ✓ 适合复杂语法分析

性能对比

const { comparePerformance } = require('wdc-translator');

const text = "Your text here...";
const results = comparePerformance(text, {
  difficulty: 5,
  minLength: 4
});

console.log(`速度提升: ${results.speedup}x`);
// 输出示例:
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ✅ 轻量级方法完成
//    总耗时: 38.06ms
//    词形还原耗时: 0.94ms
// 
// ✅ Compromise方法完成
//    总耗时: 312.50ms
//    词形还原耗时: 84.32ms
// 
// 📊 性能对比总结:
//    加速比: 8.21x
//    轻量级方法快 721.0%

详细文档请查看 LEMMATIZER_GUIDE.md

📝 使用示例

示例1:学术文本处理

const academicText = `The philosophical implications of quantum mechanics challenge our fundamental preconceptions about reality. The profound complexity of these theories requires intellectual rigor and confronts us with questions about the nature of existence.`;

const result = await main(academicText, {
  difficulty: 5,
  minLength: 4,
  model: 'moonshot-v1-8k',
  apiKey: 'your-api-key',
  apiUrl: 'https://api.moonshot.cn/v1/chat/completions',
  isTranslate: true
});

console.log(result);
// 输出: [
//   { "word": "philosophical", "translation": "哲学的" },
//   { "word": "implications", "translation": "含义,暗示" },
//   { "word": "preconceptions", "translation": "先入为主的观念" },
//   ...
// ]

示例2:文学文本分析

const literaryText = `The protagonist's worldview underwent a profound transformation as she confronted the harsh realities of injustice and inequality.`;

const words = await main(literaryText, {
  difficulty: 4,
  minLength: 3,
  isTranslate: false
});

console.log(words);
// 输出: [
//   { word: "protagonist", context: "the protagonist worldview underwent" },
//   { word: "worldview", context: "protagonist worldview underwent profound" },
//   { word: "profound", context: "worldview underwent profound transformation" },
//   ...
// ]

🛠️ 开发

安装依赖

npm install

构建项目

npm run build

代码检查

npm run lint

代码格式化

npm run format

运行测试

node local_test/index.js

📁 项目结构

wdc-translator/
├── src/
│   ├── dictionary/          # 词汇难度字典
│   │   ├── cefr.ts         # CEFR词汇难度数据
│   │   └── subtlexus.ts    # SUBTLEXus频率数据
│   ├── gpt-api/            # AI API集成
│   │   └── translate.ts    # 翻译功能
│   ├── index.ts            # 主入口文件
│   └── types.ts            # 类型定义
├── local_test/             # 本地测试文件
├── dist/                   # 构建输出
├── package.json
├── tsconfig.json
├── rollup.config.mjs
└── README.md

🔍 工作原理

  1. 文本预处理:使用compromise库进行文本标准化和分词
  2. 词汇提取:过滤出符合长度要求的纯字母词汇
  3. 难度评估:基于CEFR词汇难度等级评估每个词汇的难度
  4. 上下文提取:为高难度词汇提取前后文语境
  5. AI翻译:使用大语言模型进行上下文感知的翻译

🤝 贡献

欢迎提交Issue和Pull Request!

  1. Fork 项目
  2. 创建特性分支 (git checkout -b feature/AmazingFeature)
  3. 提交更改 (git commit -m 'Add some AmazingFeature')
  4. 推送到分支 (git push origin feature/AmazingFeature)
  5. 打开Pull Request

📄 许可证

本项目采用 MIT 许可证 - 查看 LICENSE 文件了解详情。

👨‍💻 作者

rossroma - GitHub

🙏 致谢

  • compromise - 自然语言处理库
  • CEFR - 欧洲语言共同参考标准
  • SUBTLEXus - 美式英语词汇频率数据

⭐ 如果这个项目对你有帮助,请给它一个星标!

About

A translator based on word difficulty and context

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published