@yxw007/translate 0.0.20 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,7 +19,7 @@ English | [简体中文](./README_zh-CN.md)
19
19
  ## ✨ Features
20
20
  - 🌐 **Multi-environment support**: Node environment, browser environment
21
21
  - ✨ **Easy to use**: provides a concise API, you can easily help you to translate
22
- - 🌍 **Multi-translation engine support**: Google, Azure Translate, etc. (will expand more in the future)
22
+ - 🌍 **Multi-translation engine support**: Google, Azure Translate, Amazon Translate, Deepl, Baidu, OpenAI, etc. (will expand more in the future)
23
23
  - 🛠️ **typescript**: friendlier code hints and quality assurance
24
24
  - 📦 **Batch translation**: one api request, translate more content, reduce http requests to improve translation efficiency
25
25
  - 🔓 **completely open source**.
@@ -35,6 +35,7 @@ English | [简体中文](./README_zh-CN.md)
35
35
  | amazon translate | √ | Commissioned and ready for use |
36
36
  | baidu | √ | Commissioned and ready for use |
37
37
  | deepl | √ | Commissioned and ready for use |
38
+ | openai | √ | Commissioned and ready for use |
38
39
  | yandex | | I have not tuned in as I do not have a bank account supported by the platform (help from those who are in a position to do so is welcome and appreciated) |
39
40
 
40
41
  ## 🚀 Install
@@ -73,7 +74,7 @@ English | [简体中文](./README_zh-CN.md)
73
74
 
74
75
  - example
75
76
  ```typescript
76
- translator.use(engines.google());
77
+ translator.addEngine(engines.google());
77
78
  const res1 = await translator.translate("hello", { from: "en", to: "zh" });
78
79
  console.log(res1);
79
80
 
@@ -117,7 +118,7 @@ use jsDelivr CDN
117
118
  <script>
118
119
  (async () => {
119
120
  const { engines, translator } = translate;
120
- translator.use(engines.google());
121
+ translator.addEngine(engines.google());
121
122
  const res = await translator.translate("hello", { from: "en", to: "zh" });
122
123
  console.log(res);
123
124
  })();
@@ -139,7 +140,18 @@ class Translator {
139
140
  constructor() {
140
141
  this.engines = new Map<string, Engine>();
141
142
  }
143
+ /**
144
+ * This method is obsolete, please use the addEngine method
145
+ * @param engine {@link Engine} instance
146
+ * @deprecated Use {@link addEngine} instead.
147
+ */
142
148
  use(engine: Engine) {
149
+ this.addEngine(engine);
150
+ }
151
+ addEngine(engine: Engine) {
152
+ ...
153
+ }
154
+ removeEngine(engineName: string) {
143
155
  ...
144
156
  }
145
157
  translate<T extends Engines>(text: string | string[], options: TranslateOptions<T>) {
@@ -252,6 +264,48 @@ export interface DeeplEngineOption {
252
264
 
253
265
  - Related document:https://www.deepl.com/en/your-account/keys
254
266
 
267
+ #### OpenAIEngineOption
268
+
269
+ ```typescript
270
+ export interface OpenAIEngineOption {
271
+ apiKey: string;
272
+ model: OpenAIModel;
273
+ }
274
+
275
+ export const OPEN_AI_MODELS = [
276
+ "o1-preview",
277
+ "o1-preview-2024-09-12",
278
+ "o1-mini-2024-09-12",
279
+ "o1-mini",
280
+ "dall-e-2",
281
+ "gpt-3.5-turbo",
282
+ "gpt-3.5-turbo-0125",
283
+ "babbage-002",
284
+ "davinci-002",
285
+ "dall-e-3",
286
+ "text-embedding-3-large",
287
+ "gpt-3.5-turbo-16k",
288
+ "tts-1-hd-1106",
289
+ "text-embedding-ada-002",
290
+ "text-embedding-3-small",
291
+ "tts-1-hd",
292
+ "whisper-1",
293
+ "gpt-3.5-turbo-1106",
294
+ "gpt-3.5-turbo-instruct",
295
+ "gpt-4o-mini-2024-07-18",
296
+ "gpt-4o-mini",
297
+ "tts-1",
298
+ "tts-1-1106",
299
+ "gpt-3.5-turbo-instruct-0914",
300
+ ] as const;
301
+
302
+ export type OpenAIModel = (typeof OPEN_AI_MODELS)[number];
303
+ ```
304
+
305
+ > Description:option param Please get it from the corresponding platform.
306
+
307
+ - Related document:https://platform.openai.com/settings/organization/api-keys
308
+
255
309
  ## 🤝 Contribute
256
310
 
257
311
  > Special attention: Please create a new branch based on the master, develop on the new branch, and create PR to Master after development.
@@ -303,6 +357,7 @@ export interface DeeplEngineOption {
303
357
  amazon,
304
358
  baidu,
305
359
  deepl,
360
+ openai,
306
361
  xx
307
362
  } as const;
308
363
  ```
package/README_zh-CN.md CHANGED
@@ -21,7 +21,7 @@ Translate 是一个支持多翻译引擎的翻译工具库,它提供了一套
21
21
  ## ✨ 特点
22
22
  - 🌐 **多环境支持**:Node环境、浏览器环境
23
23
  - ✨ **简单易用**:提供了简洁的API,就可以轻松帮你翻译
24
- - 🌍 **支持多翻译引擎**:Google、Azure Translate等(未来将拓展更多)
24
+ - 🌍 **支持多翻译引擎**:Google、Azure Translate、Amazon Translate、Deepl、Baidu、OpenAI等(未来将拓展更多)
25
25
  - 🛠️ **typescript**: 更友好的代码提示和质量保障
26
26
  - 📦 **批量翻译**:一次api请求,翻译更多内容,减少http请求提高翻译效率
27
27
  - 🔓 **完全开源**
@@ -37,6 +37,7 @@ Translate 是一个支持多翻译引擎的翻译工具库,它提供了一套
37
37
  | amazon translate | √ | 已投产,可以正常使用 |
38
38
  | baidu | √ | 已投产,可以正常使用 |
39
39
  | deepl | √ | 已投产,可以正常使用 |
40
+ | openai | √ | 已投产,可以正常使用 |
40
41
  | yandex | | 由于我没有平台支持的银行账号,所以未调通(欢迎有条件的朋友帮忙调通,感谢) |
41
42
 
42
43
 
@@ -76,7 +77,7 @@ Translate 是一个支持多翻译引擎的翻译工具库,它提供了一套
76
77
 
77
78
  - example
78
79
  ```typescript
79
- translator.use(engines.google());
80
+ translator.addEngine(engines.google());
80
81
  const res1 = await translator.translate("hello", { from: "en", to: "zh" });
81
82
  console.log(res1);
82
83
 
@@ -120,7 +121,7 @@ Translate 是一个支持多翻译引擎的翻译工具库,它提供了一套
120
121
  <script>
121
122
  (async () => {
122
123
  const { engines, translator } = translate;
123
- translator.use(engines.google());
124
+ translator.addEngine(engines.google());
124
125
  const res = await translator.translate("hello", { from: "en", to: "zh" });
125
126
  console.log(res);
126
127
  })();
@@ -141,7 +142,18 @@ class Translator {
141
142
  constructor() {
142
143
  this.engines = new Map<string, Engine>();
143
144
  }
145
+ /**
146
+ * This method is obsolete, please use the addEngine method
147
+ * @param engine {@link Engine} instance
148
+ * @deprecated Use {@link addEngine} instead.
149
+ */
144
150
  use(engine: Engine) {
151
+ this.addEngine(engine);
152
+ }
153
+ addEngine(engine: Engine) {
154
+ ...
155
+ }
156
+ removeEngine(engineName: string) {
145
157
  ...
146
158
  }
147
159
  translate<T extends Engines>(text: string | string[], options: TranslateOptions<T>) {
@@ -254,6 +266,48 @@ export interface DeeplEngineOption {
254
266
 
255
267
  - 相关文档:https://www.deepl.com/en/your-account/keys
256
268
 
269
+ #### OpenAIEngineOption
270
+
271
+ ```typescript
272
+ export interface OpenAIEngineOption {
273
+ apiKey: string;
274
+ model: OpenAIModel;
275
+ }
276
+
277
+ export const OPEN_AI_MODELS = [
278
+ "o1-preview",
279
+ "o1-preview-2024-09-12",
280
+ "o1-mini-2024-09-12",
281
+ "o1-mini",
282
+ "dall-e-2",
283
+ "gpt-3.5-turbo",
284
+ "gpt-3.5-turbo-0125",
285
+ "babbage-002",
286
+ "davinci-002",
287
+ "dall-e-3",
288
+ "text-embedding-3-large",
289
+ "gpt-3.5-turbo-16k",
290
+ "tts-1-hd-1106",
291
+ "text-embedding-ada-002",
292
+ "text-embedding-3-small",
293
+ "tts-1-hd",
294
+ "whisper-1",
295
+ "gpt-3.5-turbo-1106",
296
+ "gpt-3.5-turbo-instruct",
297
+ "gpt-4o-mini-2024-07-18",
298
+ "gpt-4o-mini",
299
+ "tts-1",
300
+ "tts-1-1106",
301
+ "gpt-3.5-turbo-instruct-0914",
302
+ ] as const;
303
+
304
+ export type OpenAIModel = (typeof OPEN_AI_MODELS)[number];
305
+ ```
306
+
307
+ > 说明:option param 请从对应平台获取
308
+
309
+ - 相关文档:https://platform.openai.com/settings/organization/api-keys
310
+
257
311
  ## 🤝 贡献
258
312
 
259
313
  > 特别注意:请基于master创建一个新分支,在新分支上开发,开发完后创建PR至master
@@ -305,6 +359,7 @@ export interface DeeplEngineOption {
305
359
  amazon,
306
360
  baidu,
307
361
  deepl,
362
+ openai,
308
363
  xxx
309
364
  } as const;
310
365
  ```
@@ -362,9 +417,8 @@ export interface DeeplEngineOption {
362
417
  ...
363
418
  xxx: ValuesOf<typeof xxx>;
364
419
  };
365
-
366
420
  ```
367
-
421
+
368
422
  - 打包
369
423
  ```bash
370
424
  pnpm build
@@ -1,4 +1,4 @@
1
- // translate v0.0.20 Copyright (c) 2024 Potter<aa4790139@gmail.com> and contributors
1
+ // translate v0.1.1 Copyright (c) 2024 Potter<aa4790139@gmail.com> and contributors
2
2
  'use strict';
3
3
 
4
4
  Object.defineProperty(exports, '__esModule', { value: true });
@@ -13,8 +13,34 @@ class TranslationError extends Error {
13
13
  Error.captureStackTrace(this, this.constructor);
14
14
  }
15
15
  }
16
-
17
- function google$1(options) {
16
+ const OPEN_AI_MODELS = [
17
+ "o1-preview",
18
+ "o1-preview-2024-09-12",
19
+ "o1-mini-2024-09-12",
20
+ "o1-mini",
21
+ "dall-e-2",
22
+ "gpt-3.5-turbo",
23
+ "gpt-3.5-turbo-0125",
24
+ "babbage-002",
25
+ "davinci-002",
26
+ "dall-e-3",
27
+ "text-embedding-3-large",
28
+ "gpt-3.5-turbo-16k",
29
+ "tts-1-hd-1106",
30
+ "text-embedding-ada-002",
31
+ "text-embedding-3-small",
32
+ "tts-1-hd",
33
+ "whisper-1",
34
+ "gpt-3.5-turbo-1106",
35
+ "gpt-3.5-turbo-instruct",
36
+ "gpt-4o-mini-2024-07-18",
37
+ "gpt-4o-mini",
38
+ "tts-1",
39
+ "tts-1-1106",
40
+ "gpt-3.5-turbo-instruct-0914",
41
+ ];
42
+
43
+ function google(options) {
18
44
  const base = "https://translate.googleapis.com/translate_a/single";
19
45
  return {
20
46
  name: "google",
@@ -1349,12 +1375,74 @@ function deepl$2(options) {
1349
1375
  };
1350
1376
  }
1351
1377
 
1378
+ function openai$1(options) {
1379
+ const { apiKey, model } = options;
1380
+ const name = "openai";
1381
+ const checkOptions = () => {
1382
+ if (!apiKey) {
1383
+ throw new TranslationError(name, `${name} apiKey is required`);
1384
+ }
1385
+ if (!OPEN_AI_MODELS.includes(model)) {
1386
+ throw new TranslationError(name, `${name} model=${model} is invalid`);
1387
+ }
1388
+ };
1389
+ checkOptions();
1390
+ const base = "https://api.openai.com/v1/chat/completions";
1391
+ return {
1392
+ name,
1393
+ async translate(text, opts) {
1394
+ checkOptions();
1395
+ const { from, to } = opts;
1396
+ const url = `${base}`;
1397
+ if (!Array.isArray(text)) {
1398
+ text = [text];
1399
+ }
1400
+ const prompt = {
1401
+ role: "user",
1402
+ content: `Translate the following texts from ${from} to ${to}:
1403
+ -$s$-
1404
+ ${text.join("\n")}
1405
+ -$e$-
1406
+ Translated content is between the start marker -$s$- and the end marker -$e$-, do not return the start and end markers, only the translated text is returned.
1407
+ Connect multiple text with newline character, keep the original order when return.
1408
+ `,
1409
+ };
1410
+ const res = await fetch(url, {
1411
+ method: "POST",
1412
+ headers: {
1413
+ "Content-Type": "application/json",
1414
+ Authorization: `Bearer ${apiKey}`,
1415
+ },
1416
+ body: JSON.stringify({
1417
+ model,
1418
+ messages: [{ role: "system", content: "You are a professional IT translator" }, prompt],
1419
+ max_tokens: 2000,
1420
+ }),
1421
+ });
1422
+ const bodyRes = await res.json();
1423
+ if (bodyRes.error) {
1424
+ throw new TranslationError(this.name, `Translate fail! message: ${bodyRes.error.message}`);
1425
+ }
1426
+ if (!bodyRes || !bodyRes.choices || bodyRes.choices.length === 0 || !bodyRes.choices[0]?.message?.content) {
1427
+ throw new TranslationError(this.name, "Translate fail ! translate's result is null or empty");
1428
+ }
1429
+ const content = bodyRes.choices[0].message.content;
1430
+ const translations = content
1431
+ .trim()
1432
+ .split("\n")
1433
+ .map((item) => item.trim());
1434
+ return translations;
1435
+ },
1436
+ };
1437
+ }
1438
+
1352
1439
  const engines = {
1353
- google: google$1,
1440
+ google,
1354
1441
  azure: azure$1,
1355
1442
  amazon: amazon$1,
1356
1443
  baidu: baidu$1,
1357
1444
  deepl: deepl$2,
1445
+ openai: openai$1,
1358
1446
  };
1359
1447
 
1360
1448
  class Cache {
@@ -1582,7 +1670,7 @@ var azure = {
1582
1670
  Zulu: "zu",
1583
1671
  };
1584
1672
 
1585
- var google = {
1673
+ var openai = {
1586
1674
  Abkhazian: "ab",
1587
1675
  Acehnese: "ace",
1588
1676
  "Acholi language": "ach",
@@ -2155,10 +2243,11 @@ var amazon = {
2155
2243
 
2156
2244
  const originLanguages = {
2157
2245
  azure: azure,
2158
- google: google,
2246
+ google: openai,
2159
2247
  baidu: baidu,
2160
2248
  deepl: deepl$1,
2161
2249
  amazon: amazon,
2250
+ openai: openai,
2162
2251
  };
2163
2252
 
2164
2253
  var deepl = {
@@ -2202,10 +2291,11 @@ var deepl = {
2202
2291
 
2203
2292
  const targetLanguages = {
2204
2293
  azure: azure,
2205
- google: google,
2294
+ google: openai,
2206
2295
  baidu: baidu,
2207
2296
  deepl: deepl,
2208
2297
  amazon: amazon,
2298
+ openai: openai,
2209
2299
  };
2210
2300
 
2211
2301
  function normalFromLanguage(from, engine) {
@@ -2259,13 +2349,28 @@ class Translator {
2259
2349
  this.engines = new Map();
2260
2350
  this.cache_time = cache_time;
2261
2351
  }
2352
+ /**
2353
+ * This method is obsolete, please use the addEngine method
2354
+ * @param engine {@link Engine} instance
2355
+ * @deprecated Use {@link addEngine} instead.
2356
+ */
2262
2357
  use(engine) {
2358
+ this.addEngine(engine);
2359
+ }
2360
+ addEngine(engine) {
2263
2361
  if (this.engines.has(engine.name)) {
2264
2362
  logger.warn("Engine already exists");
2265
2363
  return;
2266
2364
  }
2267
2365
  this.engines.set(engine.name, engine);
2268
2366
  }
2367
+ removeEngine(engineName) {
2368
+ if (!engineName || !this.engines.has(engineName)) {
2369
+ logger.warn("Engine name is required or not found");
2370
+ return false;
2371
+ }
2372
+ this.engines.delete(engineName);
2373
+ }
2269
2374
  async translate(text, options) {
2270
2375
  const { engine = "google", cache_time = 60 * 1000 } = options;
2271
2376
  let { from = "auto", to } = options;
@@ -2317,6 +2422,7 @@ var index = {
2317
2422
  };
2318
2423
 
2319
2424
  exports.Cache = Cache;
2425
+ exports.OPEN_AI_MODELS = OPEN_AI_MODELS;
2320
2426
  exports.TranslationError = TranslationError;
2321
2427
  exports.Translator = Translator;
2322
2428
  exports.default = index;