gptrans 1.6.2 → 1.6.6

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
@@ -39,7 +39,7 @@ import GPTrans from 'gptrans';
39
39
  const gptrans = new GPTrans({
40
40
  from: 'en-US',
41
41
  target: 'es-AR',
42
- model: 'claude-3-5-sonnet-20241022'
42
+ model: 'sonnet45'
43
43
  });
44
44
 
45
45
  // Translate text with parameter substitution
@@ -67,7 +67,7 @@ When creating a new instance of GPTrans, you can customize:
67
67
  |--------|-------------|---------|
68
68
  | `from` | Source language locale (BCP 47) | `en-US` |
69
69
  | `target` | Target language locale (BCP 47) | `es` |
70
- | `model` | Translation model key or array of models for fallback | `claude-3-7-sonnet` |
70
+ | `model` | Translation model key or array of models for fallback | `sonnet45` `gpt41` |
71
71
  | `batchThreshold` | Maximum number of characters to accumulate before triggering batch processing | `1500` |
72
72
  | `debounceTimeout` | Time in milliseconds to wait before processing translations | `500` |
73
73
  | `freeze` | Freeze mode to prevent translations from being queued | `false` |
@@ -128,7 +128,7 @@ GPTrans supports a fallback mechanism for translation models. Instead of providi
128
128
 
129
129
  ```javascript
130
130
  const translator = new GPTrans({
131
- model: ['claude-3-7-sonnet-20250219', 'o3-mini-2025-01-31'],
131
+ model: ['claude37', 'gpt41'],
132
132
  // ... other options
133
133
  });
134
134
  ```
package/demo/case_1.js CHANGED
@@ -1,8 +1,6 @@
1
1
  import GPTrans from '../index.js';
2
2
 
3
- const gptrans = new GPTrans({
4
- model: 'claude-3-5-sonnet-20241022',
5
- });
3
+ const gptrans = new GPTrans({ model: 'sonnet45' });
6
4
 
7
5
  console.log(gptrans.t('Hello, {name}!', { name: 'Anya' }));
8
6
 
@@ -18,7 +16,7 @@ console.log(gptrans.t('Card'));
18
16
  const es2ar = new GPTrans({
19
17
  from: 'es-ES',
20
18
  target: 'es-AR',
21
- model: 'claude-3-5-sonnet-20241022',
19
+ model: 'sonnet37'
22
20
  });
23
21
 
24
22
  console.log(es2ar.t('Eres muy bueno'));
@@ -29,7 +27,7 @@ console.log(es2ar.setContext().t('Tienes fuego?'));
29
27
  const ar2es = new GPTrans({
30
28
  from: 'es-AR',
31
29
  target: 'es-ES',
32
- model: 'claude-3-5-sonnet-20241022',
30
+ model: 'gpt41'
33
31
  });
34
32
 
35
33
  console.log(ar2es.t('¿Tenés fuego?'));
package/demo/case_4.js CHANGED
@@ -8,7 +8,7 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
8
8
 
9
9
  // Initialize translator
10
10
  const model = new GPTrans({
11
- model: ['claude-3-7-sonnet-20250219', 'o3-mini-2025-01-31'],
11
+ model: ['sonnet37', 'gpt41'],
12
12
  from: 'es', // Assuming the source file is in Spanish
13
13
  target: 'en',
14
14
  });
package/index.js CHANGED
@@ -1,14 +1,16 @@
1
1
  import DeepBase from 'deepbase';
2
2
  import stringHash from 'string-hash';
3
- import { ModelMix, MixOpenAI, MixAnthropic } from 'modelmix';
3
+ import { ModelMix } from 'modelmix';
4
4
  import { isoAssoc, isLanguageAvailable } from './isoAssoc.js';
5
5
  import dotenv from 'dotenv';
6
6
 
7
7
  class GPTrans {
8
- static #mmixInstance = null;
8
+ static #mmixInstances = new Map();
9
9
 
10
- static get mmix() {
11
- if (!this.#mmixInstance) {
10
+ static mmix(models = 'sonnet45') {
11
+ const key = Array.isArray(models) ? models.join(',') : models;
12
+
13
+ if (!this.#mmixInstances.has(key)) {
12
14
  const mmix = new ModelMix({
13
15
  config: {
14
16
  max_history: 1,
@@ -20,19 +22,30 @@ class GPTrans {
20
22
  }
21
23
  });
22
24
 
23
- mmix.attach(new MixOpenAI());
24
- mmix.attach(new MixAnthropic());
25
+ // Chain models dynamically
26
+ let instance = mmix;
27
+ const modelArray = Array.isArray(models) ? models : [models];
28
+
29
+ for (const model of modelArray) {
30
+ if (typeof instance[model] !== 'function') {
31
+ throw new Error(
32
+ `Model "${model}" is not available. Please check the model name. ` +
33
+ `Available models include: gpt41, gpt4o, sonnet45, sonnet37, opus41, haiku35, etc.`
34
+ );
35
+ }
36
+ instance = instance[model]();
37
+ }
25
38
 
26
- this.#mmixInstance = mmix;
39
+ this.#mmixInstances.set(key, instance);
27
40
  }
28
- return this.#mmixInstance;
41
+ return this.#mmixInstances.get(key);
29
42
  }
30
43
 
31
44
  static isLanguageAvailable(langCode) {
32
45
  return isLanguageAvailable(langCode);
33
46
  }
34
47
 
35
- constructor({ from = 'en-US', target = 'es', model = 'claude-3-7-sonnet-20250219', batchThreshold = 1500, debounceTimeout = 500, promptFile = null, context = '', freeze = false }) {
48
+ constructor({ from = 'en-US', target = 'es', model = 'sonnet45', batchThreshold = 1500, debounceTimeout = 500, promptFile = null, context = '', freeze = false } = {}) {
36
49
 
37
50
  try {
38
51
  dotenv.config();
@@ -98,7 +111,7 @@ class GPTrans {
98
111
  const translation = this.dbTarget.get(contextHash, key);
99
112
 
100
113
  if (!translation) {
101
-
114
+
102
115
  if (!this.freeze && !this.dbFrom.get(this.context, key)) {
103
116
  this.dbFrom.set(this.context, key, text);
104
117
  }
@@ -146,7 +159,7 @@ class GPTrans {
146
159
 
147
160
  this.modelConfig.options.max_tokens = this.pendingCharCount + 1000;
148
161
  const minTime = Math.floor((60000 / (8000 / this.pendingCharCount)) * 1.4);
149
- GPTrans.mmix.limiter.updateSettings({ minTime });
162
+ GPTrans.mmix(this.modelKey).limiter.updateSettings({ minTime });
150
163
 
151
164
  this.pendingCharCount = 0;
152
165
 
@@ -175,7 +188,7 @@ class GPTrans {
175
188
 
176
189
  async _translate(text) {
177
190
 
178
- const model = GPTrans.mmix.create(this.modelKey, this.modelConfig);
191
+ const model = GPTrans.mmix(this.modelKey);
179
192
 
180
193
  model.setSystem("You are an expert translator specialized in literary translation between FROM_LANG and TARGET_DENONYM TARGET_LANG.");
181
194
 
@@ -213,6 +226,11 @@ class GPTrans {
213
226
  }
214
227
 
215
228
  async preload() {
229
+
230
+ if (!this.context && this.replaceFrom.FROM_ISO === this.replaceTarget.TARGET_ISO) {
231
+ return this;
232
+ }
233
+
216
234
  for (const [context, pairs] of this.dbFrom.entries()) {
217
235
  this.setContext(context);
218
236
  for (const [key, text] of Object.entries(pairs)) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "gptrans",
3
3
  "type": "module",
4
- "version": "1.6.2",
4
+ "version": "1.6.6",
5
5
  "description": "🚆 GPTrans - The smarter AI-powered way to translate.",
6
6
  "keywords": [
7
7
  "translate",
@@ -32,9 +32,11 @@
32
32
  },
33
33
  "homepage": "https://github.com/clasen/GPTrans#readme",
34
34
  "dependencies": {
35
+ "axios": "^1.12.2",
35
36
  "deepbase": "^1.4.8",
36
37
  "dotenv": "^16.4.7",
37
- "modelmix": "^2.9.2",
38
+ "form-data": "^4.0.4",
39
+ "modelmix": "^3.9.0",
38
40
  "string-hash": "^1.1.3"
39
41
  }
40
42
  }
@@ -1,10 +0,0 @@
1
- {
2
- "45h": {
3
- "eres_muy_bueno\n_lo_eres_1lkenvc": "You're very good\n---\nYou truly are",
4
- "tienes_fuego_1i2o3ok": "Do you have a light?"
5
- },
6
- "1sfvxng": {
7
- "eres_muy_bueno_26czme": "You are very good",
8
- "_memora_intern_p18x__vrlf96": "| **INTERNAL MEMORANDUM P-18-X** | |\n| ------------------------------- | --------------------- |\n| **From:** | Zentara Group |\n| **Date:** | February 15, 2018 |\n| **Time:** | 06:00 AM GMT |\n| **Confidentiality Level:** | ALPHA-8 |\n\n\n## Incident in South Georgia\n### Advanced MPD Propulsion ZNC-S20 Vessel\n\nAt 03:45 AM GMT on February 15, 2018, an **Advanced MPD Propulsion ZNC-S20 Vessel** experienced a loss of control due to causes still unknown. The vessel performed an emergency landing at coordinates **54°39'44.62\" S 36°11'42.47\" W** in South Georgia, leaving a furrow approximately 1 km long across the snow and surrounding mountains.\n\n![full](/ODF.ZNG/georgia_incident/aereal_view.jpg)\n*Aerial view of the impact.*\n\n### **Immediate Actions:**\n\n1. **Containment Team Deployment:**\n - Send specialized units to the impact site to secure the area and recover the vessel.\n - Establish a 15 km security perimeter and restrict access to all unauthorized personnel.\n\n2. **Information Control:**\n - Apply confidentiality procedures for all personnel involved.\n - Implement disinformation protocols for any eyewitnesses.\n\n3. **Satellite Image Manipulation:**\n - Coordinate with the Satellite Observation Department to, in the short term, **replace images simulating a glacier collapse**.\n - In the long term, **remove high-quality satellite images of the area**.\n\n4. **Communication with Local Population:**\n - Inform residents that security operations are being conducted due to geological risks.\n - Restrict access to nearby areas.\n\n5. **Media Management:**\n - Issue an official statement reporting an avalanche in the area caused by a glacier collapse.\n - Facilitate interviews with experts such as Dr. Richard Waller to support the official version.\n\n6. **Social Media Monitoring and Control:**\n - Monitor digital platforms to identify and neutralize any information leaks.\n - Disseminate content that reinforces the official narrative.\n\n### **Official Scientific Narrative:**\n\nDr. Richard Waller, geologist from Keele University, will indicate that the observed phenomenon was a consequence of a glacier collapse, which has left visible debris in the snow. He will also suggest that the trail in the snow is related to a recent avalanche in the area.\n\n![full](/ODF.ZNG/georgia_incident/maps_view.jpg)\n*Proposal to replace satellite images of the area.*\n\n---\n\n### **Conclusions and Next Steps:**\n\nThe situation must be handled with the highest level of discretion. All departments must work in coordination to ensure that the incident remains confidential. The described actions are expected to be implemented immediately and effectively.\n\n\n![width=200](/ODF.ZNG/sign.png)\n**Michael Camelbot**\n\nZentara Group\n\n---\n\n**This document is confidential and intended only for authorized Zentara Group personnel. Any unauthorized disclosure is strictly prohibited and will be sanctioned according to internal security protocols.**"
9
- }
10
- }
@@ -1,10 +0,0 @@
1
- {
2
- "": {
3
- "eres_muy_bueno\n_lo_eres_1lkenvc": "Eres muy bueno\n---\nVerdaderamente lo eres",
4
- "tienes_fuego_1i2o3ok": "Tienes fuego?"
5
- },
6
- "El mensaje es para una mujer": {
7
- "eres_muy_bueno_26czme": "Eres muy bueno",
8
- "_memora_intern_p18x__vrlf96": "| **MEMORANDO INTERNO P-18-X** | |\n| ------------------------------ | --------------------- |\n| **Emisor:** | Zentara Group |\n| **Fecha:** | 15 de febrero de 2018 |\n| **Hora:** | 06:00 AM GMT |\n| **Nivel de Confidencialidad:** | ALPHA-8 |\n\n\n## Incidente en South Georgia\n### Nave ZNC-S20 de Propulsión MPD Avanzada\n\nA las 03:45 AM GMT del 15 de febrero de 2018, una **Nave ZNC-S20 de Propulsión MPD Avanzada** sufrió una pérdida de control por causas aún desconocidas. La nave realizó un aterrizaje de emergencia en las coordenadas **54°39'44.62\" S 36°11'42.47\" W** en South Georgia, dejando una surco de aproximadamente 1 km a través de la nieve y las montañas circundantes.\n\n![full](/ODF.ZNG/georgia_incident/aereal_view.jpg)\n*Vista aérea del impacto.*\n\n### **Acciones Inmediatas:**\n\n1. **Despliegue de Equipo de Contención:**\n - Enviar unidades especializadas al sitio del impacto para asegurar el área y recuperar la nave.\n - Establecer un perímetro de seguridad de 15 km y restringir el acceso a todo personal no autorizado.\n\n2. **Control de Información:**\n - Aplicar procedimientos de confidencialidad para todo el personal involucrado.\n - Implementar protocolos de desinformación para cualquier testigo presencial.\n\n3. **Manipulación de Imágenes Satelitales:**\n - Coordinar con el Departamento de Observación Satelital para, a corto plazo, **sustituir imágenes simulando un desprendimiento glaciar**.\n - A largo plazo, **eliminar las imágenes satelitales de alta calidad en la zona**.\n\n4. **Comunicación con la Población Local:**\n - Informar a los residentes que se están llevando a cabo operaciones de seguridad por riesgos geológicos.\n - Restringir el acceso a áreas próximas.\n\n5. **Gestión de Medios de Comunicación:**\n - Emitir un comunicado oficial informando sobre una avalancha en la zona ocasionada por el colapso de un glaciar.\n - Facilitar entrevistas con expertos como el Dr. Richard Waller para respaldar la versión oficial.\n\n6. **Monitoreo y Control de Redes Sociales:**\n - Supervisar plataformas digitales para identificar y neutralizar cualquier filtración de información.\n - Difundir contenido que refuerce la narrativa oficial.\n\n### **Narrativa Científica Oficial:**\n\nEl Dr. Richard Waller, geólogo de la Universidad Keele, indicará que el fenómeno observado fue consecuencia del colapso de un glaciar, lo que ha dejado escombros visibles en la nieve. También sugerirá que el rastro en la nieve está relacionado con una avalancha reciente en la zona.\n\n![full](/ODF.ZNG/georgia_incident/maps_view.jpg)\n*Propuesta para reemplazar las imagenes satelitales de la zona.*\n\n---\n\n### **Conclusiones y Pasos a Seguir:**\n\nLa situación debe ser manejada con el máximo nivel de discreción. Todos los departamentos deben trabajar en coordinación para asegurar que el incidente permanezca confidencial. Se espera que las acciones descritas sean implementadas de forma inmediata y efectiva.\n\n\n![width=200](/ODF.ZNG/sign.png)\n**Michael Camelbot**\n\nZentara Group\n\n---\n\n**Este documento es confidencial y está destinado únicamente al personal autorizado de Zentara Group. Cualquier divulgación no autorizada está estrictamente prohibida y será sancionada conforme a protocolos internos de seguridad.**"
9
- }
10
- }