generaltranslation 1.2.10 → 1.2.12

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
@@ -54,18 +54,7 @@ const codes = getLanguageCodes(['French', 'Spanish'])
54
54
  console.log(codes) // ['fr', 'es']
55
55
  ```
56
56
 
57
- ## Get a user's language
58
-
59
- ### getUserLanguage()
60
-
61
- Returns a user's default browser language. Meant for use in a web browser (i.e. on the client side).
62
-
63
- ```
64
- const userLanguage = getUserLanguage();
65
- console.log(userLanguage) // 'en'
66
- ```
67
-
68
- ## Prompt Internationalization API
57
+ ## Translation API
69
58
 
70
59
  For this function, you need to sign up for an API key at <a href='https://generaltranslation.com' target='_blank'>generaltranslation.com</a>.
71
60
 
@@ -81,23 +70,21 @@ const gt = new GT({
81
70
  });
82
71
  ```
83
72
 
84
- ### async translatePrompt(prompt, language)
73
+ ### async translate(content, language)
85
74
 
86
- Translates prompt into the language represented by an ISO-639 language code. Designed for translating prompts into other languages, to internationalize responses from AI models.
87
-
88
- Just wrap `translatePrompt` around your prompt and go.
75
+ Translates content into the language represented by an ISO-639 language code. Caches by default. Just wrap `translate` around your content and go.
89
76
 
90
77
  All of the following are valid:
91
78
 
92
79
  ```
93
- const translatedPrompt = await gt.translatePrompt('Tell me a story', 'es');
80
+ const translation = await gt.translate('Tell me a story', 'es'); // returns a string
94
81
  ```
95
82
 
96
83
  ```
97
- const first = 'Tell me a story ';
98
- const second = 'about a cat'
84
+ const first = 'Tell me a story';
85
+ const second = ' about a cat'
99
86
 
100
- const translatedPrompt = await gt.translatePrompt([
87
+ const translated = await gt.translate([
101
88
  first, second
102
89
  ], 'es');
103
90
  ```
@@ -108,18 +95,18 @@ To mark text that shouldn't be translated, wrap it in `{ text: "", translate: fa
108
95
  const prompt = 'Tell me a story about ';
109
96
  const input = 'gatos con espadas'
110
97
 
111
- const translatedPrompt = await gt.translatePrompt([
98
+ const translatedPrompt = await gt.translate([
112
99
  prompt, { text: input, translate: false }
113
100
  ], 'es');
114
101
  ```
115
102
 
116
- For type consistency, you can also make everything in the prompt parameter an object:
103
+ For type consistency, you can also make everything in the content parameter an object:
117
104
 
118
105
  ```
119
106
  const prompt = 'Tell me a story about ';
120
107
  const input = 'gatos con espadas'
121
108
 
122
- const translatedPrompt = await gt.translatePrompt([
109
+ const translatedPrompt = await gt.translate([
123
110
  { text: prompt },
124
111
  { text: input, translate: false }
125
112
  ], 'es');
@@ -128,5 +115,23 @@ const translatedPrompt = await gt.translatePrompt([
128
115
  This also works:
129
116
 
130
117
  ```
131
- const translatedPrompt = await gt.translatePrompt({ text: 'Tell me a story' }, 'es');
118
+ const translatedPrompt = await gt.translate({ text: 'Tell me a story' }, 'es');
119
+ ```
120
+
121
+ ### async translateMany(contentArray, language)
122
+
123
+ Translates multiple items of content into the language represented by an ISO-639 language code. Caches by default. Just wrap `translateMany` around an array of what you want to translate and specify a language. For example:
124
+
125
+ ```
126
+ const requests = [
127
+ {
128
+ content: "You say goodbye",
129
+ language: "es"
130
+ },
131
+ {
132
+ content: "And I say hello.",
133
+ language: "de"
134
+ }
135
+ ];
136
+ const translationArray = await gt.translateMany(requests) // returns an array
132
137
  ```
package/index.js CHANGED
@@ -4,40 +4,63 @@
4
4
  // ----- IMPORTS ----- //
5
5
 
6
6
  const { _getLanguageCode, _getLanguageName } = require('./codes/codes.js');
7
- const _translatePrompt = require('./translate/prompts.js');
7
+ const { _translate, _translateMany } = require('./translate/translate.js');
8
8
  const _translateHTML = require('./translate/html.js');
9
9
 
10
+ // TO DO
11
+ // - Times/dates?
12
+ // - Currency conversion?
13
+ // - Regions (e.g. en-GB)
14
+
10
15
  // ----- CORE CLASS ----- //
11
16
 
17
+ const getDefaultFromEnv = (VARIABLE) => {
18
+ if (typeof process !== 'undefined') {
19
+ if (process?.env?.[VARIABLE]) {
20
+ return process.env[VARIABLE];
21
+ }
22
+ }
23
+ return '';
24
+ }
25
+
12
26
  class GT {
13
27
 
14
28
  constructor({
15
29
  apiKey = '',
16
30
  defaultLanguage = 'en',
31
+ projectID = '',
17
32
  baseURL = 'https://translate.gtx.dev'
18
33
  } = {}) {
19
- this.apiKey = apiKey || (typeof process !== 'undefined' ? process.env.GT_API_KEY : '');
34
+ this.apiKey = apiKey || getDefaultFromEnv('GT_API_KEY');
35
+ this.projectID = projectID || getDefaultFromEnv('GT_PROJECT_ID');
20
36
  this.defaultLanguage = defaultLanguage?.toLowerCase();
21
37
  this.baseURL = baseURL;
22
38
  }
23
39
 
24
- // Prompt I18N
25
- async translatePrompt(prompt, language) {
26
- return await _translatePrompt({
27
- content: prompt, language: language, config: this
40
+ // Site I18N
41
+ async translateHTML({ page, userLanguage, defaultLanguage, content, ...metadata }) {
42
+ return await _translateHTML({
43
+ page: page,
44
+ userLanguage: userLanguage,
45
+ defaultLanguage: defaultLanguage,
46
+ content: content,
47
+ config: this,
48
+ ...metadata
28
49
  });
29
50
  }
30
51
 
31
- // Site I18N
32
- async translateHTML({ projectID, page, userLanguage, defaultLanguage, content, ...metadata }) {
33
- return await _translateHTML({
34
- projectID: projectID,
35
- page: page,
36
- userLanguage: userLanguage,
37
- defaultLanguage: defaultLanguage,
38
- content: content,
39
- config: this,
40
- ...metadata
52
+ // String translation
53
+ async translate(content, language, { ... options }) {
54
+ return await _translate({
55
+ content: content, language: language, config: this, ...options,
56
+ });
57
+ }
58
+
59
+ // String translation, of an array of strings
60
+ // requestArray looks like { content: '', language: '' }
61
+ async translateMany(requestArray) {
62
+ return await _translateMany({
63
+ requestArray, config: this
41
64
  });
42
65
  }
43
66
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "generaltranslation",
3
- "version": "1.2.10",
3
+ "version": "1.2.12",
4
4
  "description": "A language toolkit for AI developers",
5
5
  "main": "index.js",
6
6
  "scripts": {
package/translate/html.js CHANGED
@@ -1,5 +1,4 @@
1
1
  const _translateHTML = async ({
2
- projectID,
3
2
  page,
4
3
  userLanguage,
5
4
  defaultLanguage,
@@ -13,8 +12,9 @@ const _translateHTML = async ({
13
12
  throw new Error('Missing API Key!')
14
13
  };
15
14
 
15
+ const projectID = config?.projectID;
16
16
  if (!projectID) {
17
- throw new Error('Missing project ID!')
17
+ throw new Error('Missing Project ID!')
18
18
  };
19
19
 
20
20
  try {
@@ -5,7 +5,7 @@ const _shouldTranslate = item => typeof item?.translate === 'boolean' ? item.tra
5
5
 
6
6
  // Pre-processes content to send to the API
7
7
  // Separates out text that shouldn't be translated.
8
- const _processPrompt = ({ content }) => {
8
+ const _processContent = ({ content }) => {
9
9
  const processed = [];
10
10
  const untranslated = [];
11
11
  if (Array.isArray(content)) {
@@ -40,7 +40,7 @@ const _processPrompt = ({ content }) => {
40
40
  }
41
41
 
42
42
  // Build content string from array or single item
43
- const _constructPrompt = ({ content, untranslated = null}) => {
43
+ const _constructContent = ({ content, untranslated = null}) => {
44
44
  if (Array.isArray(content)) {
45
45
  let final = '';
46
46
  for (const item of content) {
@@ -64,8 +64,8 @@ const _constructPrompt = ({ content, untranslated = null}) => {
64
64
 
65
65
  // Get a translation via General Translation API
66
66
  // Returns string
67
- const _translatePrompt = async ({
68
- content, language, config
67
+ const _translate = async ({
68
+ content, language, config, ...options
69
69
  }) => {
70
70
 
71
71
  const apiKey = config?.apiKey;
@@ -75,13 +75,13 @@ const _translatePrompt = async ({
75
75
 
76
76
  const defaultLanguage = config?.defaultLanguage;
77
77
  if (language === defaultLanguage) {
78
- return _constructPrompt({ content: content });
78
+ return _constructContent({ content: content });
79
79
  };
80
80
 
81
- const { processed, untranslated } = _processPrompt({ content });
81
+ const { processed, untranslated } = _processContent({ content });
82
82
 
83
83
  try {
84
- const response = await fetch(`${config?.baseURL}/prompts`, {
84
+ const response = await fetch(`${config?.baseURL}`, {
85
85
  method: 'POST',
86
86
  headers: {
87
87
  'Content-Type': 'application/json',
@@ -90,7 +90,8 @@ const _translatePrompt = async ({
90
90
  body: JSON.stringify({
91
91
  content: processed,
92
92
  targetLanguage: language,
93
- defaultLanguage: defaultLanguage
93
+ defaultLanguage: defaultLanguage,
94
+ options: { ...options }
94
95
  })
95
96
  })
96
97
  if (!response.ok) {
@@ -98,13 +99,76 @@ const _translatePrompt = async ({
98
99
  throw new Error(`${result || response.status}`);
99
100
  } else {
100
101
  const result = await response.json();
101
- return _constructPrompt({content: result, untranslated: untranslated });
102
+ return _constructContent({content: result, untranslated: untranslated });
102
103
  }
103
104
  } catch (error) {
104
105
  console.error(error)
105
- return _constructPrompt({ content: content })
106
+ return _constructContent({ content: content })
106
107
  }
107
108
 
108
109
  }
109
110
 
110
- module.exports = _translatePrompt;
111
+ const constructAll = (contentArray) => {
112
+ const returnArray = [];
113
+ for (const item of contentArray) {
114
+ returnArray.push(_constructContent({ content: item }))
115
+ }
116
+ return returnArray;
117
+ }
118
+
119
+ // Get a translation of multiple strings via General Translation API
120
+ // Returns array of strings
121
+ const _translateMany = async ({
122
+ requestArray, config
123
+ }) => {
124
+
125
+ const apiKey = config?.apiKey;
126
+ if (!apiKey) {
127
+ throw new Error('Missing API Key!')
128
+ };
129
+
130
+ const processedRequests = [];
131
+ const untranslatedArray = [];
132
+
133
+ for (const item of requestArray) {
134
+ const { processed, untranslated } = _processContent({ content: item?.content });
135
+ processedRequests.push({ content: processed, language: item.language, options: { ...item.options } });
136
+ untranslatedArray.push(untranslated);
137
+ };
138
+
139
+ try {
140
+ const response = await fetch(`${config?.baseURL}/many`, {
141
+ method: 'POST',
142
+ headers: {
143
+ 'Content-Type': 'application/json',
144
+ 'gtx-api-key': apiKey,
145
+ },
146
+ body: JSON.stringify({
147
+ processedRequests: processedRequests,
148
+ targetLanguage: language,
149
+ defaultLanguage: defaultLanguage,
150
+ options: { ...options }
151
+ })
152
+ })
153
+ if (!response.ok) {
154
+ const result = await response.text();
155
+ throw new Error(`${result || response.status}`);
156
+ } else {
157
+ const result = await response.json();
158
+ if (!Array.isArray(result)) {
159
+ throw new Error(`${result || response.status}`);
160
+ }
161
+ const returnArray = []
162
+ for (const [index, item] of result.entries()) {
163
+ returnArray.push(_constructContent({content: item, untranslated: untranslatedArray[index] }));
164
+ }
165
+ return returnArray;
166
+ }
167
+ } catch (error) {
168
+ console.error(error)
169
+ return constructAll(requestArray.map(item => item.content));
170
+ }
171
+
172
+ }
173
+
174
+ module.exports = { _translate, _translateMany };