@yxw007/translate 0.0.19 → 0.1.0

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,11 +19,13 @@ 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**.
26
26
 
27
+ > **Special reminder: although the library has supported the use of the browser environment, but please only use the google engine translation (google does not need key), the use of other translation engine need to configure the key, the use of the front-end will lead to key leakage, do not do it**
28
+
27
29
  ## 💻Translation engines, integration cases
28
30
 
29
31
  | Name | Support | Description |
@@ -33,6 +35,7 @@ English | [简体中文](./README_zh-CN.md)
33
35
  | amazon translate | √ | Commissioned and ready for use |
34
36
  | baidu | √ | Commissioned and ready for use |
35
37
  | deepl | √ | Commissioned and ready for use |
38
+ | openai | √ | Commissioned and ready for use |
36
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) |
37
40
 
38
41
  ## 🚀 Install
@@ -71,7 +74,7 @@ English | [简体中文](./README_zh-CN.md)
71
74
 
72
75
  - example
73
76
  ```typescript
74
- translator.use(engines.google());
77
+ translator.addEngine(engines.google());
75
78
  const res1 = await translator.translate("hello", { from: "en", to: "zh" });
76
79
  console.log(res1);
77
80
 
@@ -115,7 +118,7 @@ use jsDelivr CDN
115
118
  <script>
116
119
  (async () => {
117
120
  const { engines, translator } = translate;
118
- translator.use(engines.google());
121
+ translator.addEngine(engines.google());
119
122
  const res = await translator.translate("hello", { from: "en", to: "zh" });
120
123
  console.log(res);
121
124
  })();
@@ -137,7 +140,18 @@ class Translator {
137
140
  constructor() {
138
141
  this.engines = new Map<string, Engine>();
139
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
+ */
140
148
  use(engine: Engine) {
149
+ this.addEngine(engine);
150
+ }
151
+ addEngine(engine: Engine) {
152
+ ...
153
+ }
154
+ removeEngine(engineName: string) {
141
155
  ...
142
156
  }
143
157
  translate<T extends Engines>(text: string | string[], options: TranslateOptions<T>) {
@@ -250,6 +264,48 @@ export interface DeeplEngineOption {
250
264
 
251
265
  - Related document:https://www.deepl.com/en/your-account/keys
252
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
+
253
309
  ## 🤝 Contribute
254
310
 
255
311
  > Special attention: Please create a new branch based on the master, develop on the new branch, and create PR to Master after development.
@@ -301,6 +357,7 @@ export interface DeeplEngineOption {
301
357
  amazon,
302
358
  baidu,
303
359
  deepl,
360
+ openai,
304
361
  xx
305
362
  } as const;
306
363
  ```
package/README_zh-CN.md CHANGED
@@ -21,11 +21,13 @@ 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
  - 🔓 **完全开源**
28
28
 
29
+ > **特别提醒:虽然库已支持浏览器环境使用,但是请仅使用google engine翻译(google不需要key),使用其他翻译engine 需要配置key,在前端使用会导致key泄露,千万不要这么做**
30
+
29
31
  ## 💻翻译引擎,集成情况
30
32
 
31
33
  | name | 支持 | 描述 |
@@ -35,6 +37,7 @@ Translate 是一个支持多翻译引擎的翻译工具库,它提供了一套
35
37
  | amazon translate | √ | 已投产,可以正常使用 |
36
38
  | baidu | √ | 已投产,可以正常使用 |
37
39
  | deepl | √ | 已投产,可以正常使用 |
40
+ | openai | √ | 已投产,可以正常使用 |
38
41
  | yandex | | 由于我没有平台支持的银行账号,所以未调通(欢迎有条件的朋友帮忙调通,感谢) |
39
42
 
40
43
 
@@ -74,7 +77,7 @@ Translate 是一个支持多翻译引擎的翻译工具库,它提供了一套
74
77
 
75
78
  - example
76
79
  ```typescript
77
- translator.use(engines.google());
80
+ translator.addEngine(engines.google());
78
81
  const res1 = await translator.translate("hello", { from: "en", to: "zh" });
79
82
  console.log(res1);
80
83
 
@@ -118,7 +121,7 @@ Translate 是一个支持多翻译引擎的翻译工具库,它提供了一套
118
121
  <script>
119
122
  (async () => {
120
123
  const { engines, translator } = translate;
121
- translator.use(engines.google());
124
+ translator.addEngine(engines.google());
122
125
  const res = await translator.translate("hello", { from: "en", to: "zh" });
123
126
  console.log(res);
124
127
  })();
@@ -139,7 +142,18 @@ class Translator {
139
142
  constructor() {
140
143
  this.engines = new Map<string, Engine>();
141
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
+ */
142
150
  use(engine: Engine) {
151
+ this.addEngine(engine);
152
+ }
153
+ addEngine(engine: Engine) {
154
+ ...
155
+ }
156
+ removeEngine(engineName: string) {
143
157
  ...
144
158
  }
145
159
  translate<T extends Engines>(text: string | string[], options: TranslateOptions<T>) {
@@ -252,6 +266,48 @@ export interface DeeplEngineOption {
252
266
 
253
267
  - 相关文档:https://www.deepl.com/en/your-account/keys
254
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
+
255
311
  ## 🤝 贡献
256
312
 
257
313
  > 特别注意:请基于master创建一个新分支,在新分支上开发,开发完后创建PR至master
@@ -303,6 +359,7 @@ export interface DeeplEngineOption {
303
359
  amazon,
304
360
  baidu,
305
361
  deepl,
362
+ openai,
306
363
  xxx
307
364
  } as const;
308
365
  ```
@@ -360,9 +417,8 @@ export interface DeeplEngineOption {
360
417
  ...
361
418
  xxx: ValuesOf<typeof xxx>;
362
419
  };
363
-
364
420
  ```
365
-
421
+
366
422
  - 打包
367
423
  ```bash
368
424
  pnpm build
@@ -1,4 +1,4 @@
1
- // translate v0.0.19 Copyright (c) 2024 Potter<aa4790139@gmail.com> and contributors
1
+ // translate v0.1.0 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,76 @@ 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
+ console.log("prompt:", prompt.content);
1411
+ const res = await fetch(url, {
1412
+ method: "POST",
1413
+ headers: {
1414
+ "Content-Type": "application/json",
1415
+ Authorization: `Bearer ${apiKey}`,
1416
+ },
1417
+ body: JSON.stringify({
1418
+ model,
1419
+ messages: [{ role: "system", content: "You are a professional IT translator" }, prompt],
1420
+ max_tokens: 2000,
1421
+ }),
1422
+ });
1423
+ const bodyRes = await res.json();
1424
+ if (bodyRes.error) {
1425
+ throw new TranslationError(this.name, `Translate fail! message: ${bodyRes.error.message}`);
1426
+ }
1427
+ if (!bodyRes || !bodyRes.choices || bodyRes.choices.length === 0 || !bodyRes.choices[0]?.message?.content) {
1428
+ throw new TranslationError(this.name, "Translate fail ! translate's result is null or empty");
1429
+ }
1430
+ const content = bodyRes.choices[0].message.content;
1431
+ const translations = content
1432
+ .trim()
1433
+ .split("\n")
1434
+ .map((item) => item.trim());
1435
+ console.log("translations:", translations);
1436
+ return translations;
1437
+ },
1438
+ };
1439
+ }
1440
+
1352
1441
  const engines = {
1353
- google: google$1,
1442
+ google,
1354
1443
  azure: azure$1,
1355
1444
  amazon: amazon$1,
1356
1445
  baidu: baidu$1,
1357
1446
  deepl: deepl$2,
1447
+ openai: openai$1,
1358
1448
  };
1359
1449
 
1360
1450
  class Cache {
@@ -1439,7 +1529,7 @@ function getGapLine() {
1439
1529
  }
1440
1530
  function getErrorMessages(e, prefix = "Translate fail ! ") {
1441
1531
  if (e instanceof TypeError) {
1442
- return prefix + (e.cause.message ?? e.message);
1532
+ return prefix + (e.cause?.message ?? e.message);
1443
1533
  }
1444
1534
  return prefix + e.message;
1445
1535
  }
@@ -1582,7 +1672,7 @@ var azure = {
1582
1672
  Zulu: "zu",
1583
1673
  };
1584
1674
 
1585
- var google = {
1675
+ var openai = {
1586
1676
  Abkhazian: "ab",
1587
1677
  Acehnese: "ace",
1588
1678
  "Acholi language": "ach",
@@ -2155,10 +2245,11 @@ var amazon = {
2155
2245
 
2156
2246
  const originLanguages = {
2157
2247
  azure: azure,
2158
- google: google,
2248
+ google: openai,
2159
2249
  baidu: baidu,
2160
2250
  deepl: deepl$1,
2161
2251
  amazon: amazon,
2252
+ openai: openai,
2162
2253
  };
2163
2254
 
2164
2255
  var deepl = {
@@ -2202,10 +2293,11 @@ var deepl = {
2202
2293
 
2203
2294
  const targetLanguages = {
2204
2295
  azure: azure,
2205
- google: google,
2296
+ google: openai,
2206
2297
  baidu: baidu,
2207
2298
  deepl: deepl,
2208
2299
  amazon: amazon,
2300
+ openai: openai,
2209
2301
  };
2210
2302
 
2211
2303
  function normalFromLanguage(from, engine) {
@@ -2259,13 +2351,28 @@ class Translator {
2259
2351
  this.engines = new Map();
2260
2352
  this.cache_time = cache_time;
2261
2353
  }
2354
+ /**
2355
+ * This method is obsolete, please use the addEngine method
2356
+ * @param engine {@link Engine} instance
2357
+ * @deprecated Use {@link addEngine} instead.
2358
+ */
2262
2359
  use(engine) {
2360
+ this.addEngine(engine);
2361
+ }
2362
+ addEngine(engine) {
2263
2363
  if (this.engines.has(engine.name)) {
2264
2364
  logger.warn("Engine already exists");
2265
2365
  return;
2266
2366
  }
2267
2367
  this.engines.set(engine.name, engine);
2268
2368
  }
2369
+ removeEngine(engineName) {
2370
+ if (!engineName || !this.engines.has(engineName)) {
2371
+ logger.warn("Engine name is required or not found");
2372
+ return false;
2373
+ }
2374
+ this.engines.delete(engineName);
2375
+ }
2269
2376
  async translate(text, options) {
2270
2377
  const { engine = "google", cache_time = 60 * 1000 } = options;
2271
2378
  let { from = "auto", to } = options;
@@ -2317,6 +2424,7 @@ var index = {
2317
2424
  };
2318
2425
 
2319
2426
  exports.Cache = Cache;
2427
+ exports.OPEN_AI_MODELS = OPEN_AI_MODELS;
2320
2428
  exports.TranslationError = TranslationError;
2321
2429
  exports.Translator = Translator;
2322
2430
  exports.default = index;