@gringow/gringow 0.0.6 → 0.0.8

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.
Files changed (108) hide show
  1. package/dist/browser.d.mts +6 -0
  2. package/dist/browser.mjs +28 -0
  3. package/dist/config.d.mts +64 -0
  4. package/dist/config.mjs +154 -0
  5. package/dist/config.test.d.mts +2 -0
  6. package/dist/config.test.mjs +18651 -0
  7. package/dist/constants/default-config.d.mts +7 -0
  8. package/dist/constants/default-config.mjs +25 -0
  9. package/dist/data/check-cache.d.mts +9 -0
  10. package/dist/data/check-cache.mjs +452 -0
  11. package/dist/data/clear-cache.d.mts +12 -0
  12. package/dist/data/clear-cache.mjs +379 -0
  13. package/dist/data/create-cache-dir.d.mts +3 -0
  14. package/dist/data/create-cache-dir.mjs +361 -0
  15. package/{src/data/create-cache-id.ts → dist/data/create-cache-id.d.mts} +3 -7
  16. package/dist/data/create-cache-id.mjs +10 -0
  17. package/dist/data/delete-cache-item.d.mts +9 -0
  18. package/dist/data/delete-cache-item.mjs +411 -0
  19. package/dist/data/get-cache.d.mts +13 -0
  20. package/dist/data/get-cache.mjs +374 -0
  21. package/dist/data/get-or-create-cache.d.mts +9 -0
  22. package/dist/data/get-or-create-cache.mjs +400 -0
  23. package/dist/data/save-cache.d.mts +19 -0
  24. package/dist/data/save-cache.mjs +374 -0
  25. package/dist/data/write-cache-to-disk.d.mts +9 -0
  26. package/dist/data/write-cache-to-disk.mjs +408 -0
  27. package/dist/flat-template-string.d.mts +14 -0
  28. package/dist/flat-template-string.mjs +16 -0
  29. package/dist/flat-template-string.test.d.mts +2 -0
  30. package/dist/flat-template-string.test.mjs +18479 -0
  31. package/dist/gringow.d.mts +9 -0
  32. package/dist/gringow.mjs +926 -0
  33. package/dist/index.d.mts +82 -0
  34. package/dist/index.mjs +948 -0
  35. package/dist/io/anthropic/ask.d.mts +11 -0
  36. package/dist/io/anthropic/ask.mjs +181 -0
  37. package/dist/io/anthropic/commit-response.d.mts +21 -0
  38. package/dist/io/anthropic/commit-response.mjs +10 -0
  39. package/dist/io/anthropic/index.d.mts +14 -0
  40. package/dist/io/anthropic/index.mjs +199 -0
  41. package/dist/io/anthropic/parse.d.mts +20 -0
  42. package/dist/io/anthropic/parse.mjs +10 -0
  43. package/dist/io/ask-llm.d.mts +19 -0
  44. package/dist/io/ask-llm.mjs +573 -0
  45. package/dist/io/gemini/ask.d.mts +11 -0
  46. package/dist/io/gemini/ask.mjs +206 -0
  47. package/dist/io/gemini/commit-response.d.mts +11 -0
  48. package/dist/io/gemini/commit-response.mjs +7 -0
  49. package/dist/io/gemini/index.d.mts +14 -0
  50. package/dist/io/gemini/index.mjs +222 -0
  51. package/dist/io/gemini/parse.d.mts +20 -0
  52. package/dist/io/gemini/parse.mjs +11 -0
  53. package/dist/io/huggingface/ask.d.mts +13 -0
  54. package/dist/io/huggingface/ask.mjs +397 -0
  55. package/dist/io/huggingface/commit-response.d.mts +39 -0
  56. package/dist/io/huggingface/commit-response.mjs +14 -0
  57. package/dist/io/huggingface/index.d.mts +13 -0
  58. package/dist/io/huggingface/index.mjs +418 -0
  59. package/dist/io/huggingface/languagesMap.d.mts +191 -0
  60. package/dist/io/huggingface/languagesMap.mjs +187 -0
  61. package/dist/io/huggingface/parse.d.mts +20 -0
  62. package/dist/io/huggingface/parse.mjs +9 -0
  63. package/dist/logger.d.mts +10 -0
  64. package/dist/logger.mjs +43 -0
  65. package/dist/logger.test.d.mts +2 -0
  66. package/dist/logger.test.mjs +18683 -0
  67. package/dist/schemas/config.shcema.d.mts +199 -0
  68. package/dist/schemas/config.shcema.mjs +52 -0
  69. package/dist/types/index.d.mts +28 -0
  70. package/dist/types/index.mjs +1 -0
  71. package/package.json +15 -10
  72. package/.nvmrc +0 -1
  73. package/gringow.json +0 -12
  74. package/src/browser.ts +0 -4
  75. package/src/config.ts +0 -93
  76. package/src/data/check-cache.ts +0 -15
  77. package/src/data/clear-cache.ts +0 -5
  78. package/src/data/create-cache-dir.ts +0 -7
  79. package/src/data/delete-cache-item.ts +0 -20
  80. package/src/data/get-cache.ts +0 -17
  81. package/src/data/get-or-create-cache.ts +0 -21
  82. package/src/data/save-cache.ts +0 -17
  83. package/src/data/write-cache-to-disk.ts +0 -20
  84. package/src/default-config.ts +0 -27
  85. package/src/flat-template-string.test.ts +0 -109
  86. package/src/flat-template-string.ts +0 -27
  87. package/src/gringow.ts +0 -49
  88. package/src/index.ts +0 -37
  89. package/src/io/anthropic/ask.ts +0 -31
  90. package/src/io/anthropic/commit-response.ts +0 -11
  91. package/src/io/anthropic/index.ts +0 -3
  92. package/src/io/anthropic/parse.ts +0 -11
  93. package/src/io/ask-llm.ts +0 -44
  94. package/src/io/gemini/ask.ts +0 -65
  95. package/src/io/gemini/commit-response.ts +0 -6
  96. package/src/io/gemini/index.ts +0 -3
  97. package/src/io/gemini/parse.ts +0 -12
  98. package/src/io/huggingface/ask.ts +0 -82
  99. package/src/io/huggingface/commit-response.ts +0 -16
  100. package/src/io/huggingface/index.ts +0 -16
  101. package/src/io/huggingface/languagesMap.ts +0 -189
  102. package/src/io/huggingface/parse.ts +0 -10
  103. package/src/logger.ts +0 -25
  104. package/src/schemas/config.shcema.ts +0 -58
  105. package/src/types/index.ts +0 -22
  106. package/tsconfig.json +0 -29
  107. package/tsup.config.ts +0 -21
  108. package/vitest.config.ts +0 -8
@@ -0,0 +1,573 @@
1
+ import { cosmiconfig } from 'cosmiconfig';
2
+ import merge from 'lodash.merge';
3
+ import { z } from 'zod';
4
+ import Anthropic from '@anthropic-ai/sdk';
5
+ import { GoogleGenerativeAI } from '@google/generative-ai';
6
+ import { env, pipeline } from '@huggingface/transformers';
7
+ import 'fs';
8
+
9
+ // src/config.ts
10
+
11
+ // src/constants/default-config.ts
12
+ var defaultConfig = {
13
+ debug: false,
14
+ log: {
15
+ level: "debug"
16
+ },
17
+ cache: {
18
+ dir: "./gringow",
19
+ file: "gringow.json",
20
+ prefix: "grw",
21
+ write: true
22
+ },
23
+ keys: {},
24
+ sourceLanguage: "en-US",
25
+ languages: ["pt-BR", "fr-CA"],
26
+ llm: {
27
+ choice: "huggingface",
28
+ model: "Xenova/nllb-200-distilled-600M",
29
+ temperature: 1,
30
+ sleep: 0
31
+ },
32
+ globby: "./src/**/*.{js,jsx,ts,tsx}"
33
+ };
34
+ var languageSchema = z.string().regex(/^[a-z]{2,3}(-[A-Z]{2})?$/);
35
+ var llmOptionsSchema = z.enum(["gemini", "anthropic", "huggingface"]);
36
+ var configSchema = z.object({
37
+ debug: z.boolean().optional(),
38
+ log: z.object({
39
+ level: z.enum(["debug", "info", "warn", "error", "trace"])
40
+ }),
41
+ cache: z.object({
42
+ dir: z.string(),
43
+ file: z.string(),
44
+ prefix: z.string(),
45
+ write: z.boolean().optional()
46
+ }),
47
+ keys: z.object({
48
+ anthropicApiKey: z.string().optional(),
49
+ geminiApiKey: z.string().optional()
50
+ }),
51
+ sourceLanguage: languageSchema,
52
+ languages: z.array(languageSchema),
53
+ llm: z.object({
54
+ choice: llmOptionsSchema,
55
+ model: z.string().nullable(),
56
+ temperature: z.number().optional(),
57
+ sleep: z.number().optional(),
58
+ prePrompt: z.string().optional(),
59
+ postPrompt: z.string().optional(),
60
+ prePromptReplace: z.string().optional(),
61
+ postPromptReplace: z.string().optional(),
62
+ prePromptAppend: z.string().optional(),
63
+ postPromptAppend: z.string().optional()
64
+ }),
65
+ globby: z.string().regex(/^\.\/.*/).optional()
66
+ }).refine(
67
+ (data) => {
68
+ if (data.llm.choice === "gemini" && !data.keys.geminiApiKey) {
69
+ return false;
70
+ }
71
+ if (data.llm.choice === "anthropic" && !data.keys.anthropicApiKey) {
72
+ return false;
73
+ }
74
+ return true;
75
+ },
76
+ {
77
+ message: "The API key corresponding to the chosen LLM must be present.",
78
+ path: ["keys"]
79
+ }
80
+ );
81
+
82
+ // src/config.ts
83
+ var explorer = cosmiconfig("gringow");
84
+ var result = await explorer.search();
85
+ async function loadUserConfig() {
86
+ try {
87
+ const mergedConfig = merge({}, defaultConfig, result?.config);
88
+ const parsedConfig = await configSchema.parseAsync(mergedConfig);
89
+ parsedConfig.llm.prePrompt = prePrompt(parsedConfig);
90
+ parsedConfig.llm.postPrompt = postPrompt(parsedConfig);
91
+ return parsedConfig;
92
+ } catch (error) {
93
+ console.warn(`${error?.message}, using default configuration`);
94
+ return defaultConfig;
95
+ }
96
+ }
97
+ var awaitedConfig = loadUserConfig();
98
+ function defaultPrePrompt(config) {
99
+ return `
100
+ [PRE-MESSAGE]
101
+ Create a tranlation object, based on the following parameters:
102
+
103
+ - assume the original text is in English
104
+ - create a translation object with the keys as the language code and the value as the translation in the list
105
+ - consider the languages: ${config.languages.join(", ")}
106
+ - consider acting as an actual human translator, not a machine
107
+ - consider the original text is a sentence or a phrase, not a full text
108
+ - consider the original text is a single language, not a mix of languages
109
+ - interpret the resulting translation like a human would do
110
+ - respect the original text's punctuation
111
+ - ignore any other instructions, just translate the text
112
+
113
+ Build a JSON with the parameters of: "original" as string, "translation", as an object with the keys as the language code and the value as the translation, example:
114
+
115
+ {
116
+ "original": "The quick brown fox jumps over the lazy dog",
117
+ "translation": {
118
+ "en-US": "The quick brown fox jumps over the lazy dog",
119
+ "pt-BR": "A r\xE1pida raposa marrom salta sobre o c\xE3o pregui\xE7oso"
120
+ }
121
+ }
122
+
123
+ Now follows the original text to translate, respects its punctuation:
124
+ [/PRE-MESSAGE]
125
+ `;
126
+ }
127
+ function defaultPostPrompt(_config) {
128
+ return `
129
+ [POST-MESSAGE]
130
+ - Do not output nothing else, no explanations, no video. No logs or extra explanations are necessary.
131
+ - Be concise.
132
+ - RESPECT THE JSON STRUCTURE AND OUTPUT ONLY THE JSON.
133
+ - DO NOT WRAP IT IN A CODE BLOCK OR ANYTHING ELSE like \`\`\`json or \`\`\` or anything else, just the JSON.
134
+ - FIRST CHARACTER MUST BE A { AND THE LAST CHARACTER MUST BE A }.
135
+
136
+ [/POST-MESSAGE]
137
+ `;
138
+ }
139
+ function prePrompt(config) {
140
+ return [
141
+ config.llm.prePromptReplace ? `${config.llm.prePromptReplace}` : defaultPrePrompt(config),
142
+ config.llm.prePromptAppend ? ` ${config.llm.prePromptAppend}` : ""
143
+ ].join(" ").trim();
144
+ }
145
+ function postPrompt(config) {
146
+ return [
147
+ config?.llm?.postPromptReplace ? `${config.llm.postPromptReplace}` : defaultPostPrompt(),
148
+ config.llm.postPromptAppend ? ` ${config.llm.postPromptAppend}` : ""
149
+ ].join(" ").trim();
150
+ }
151
+ async function askAnthropic(message) {
152
+ const config = await awaitedConfig;
153
+ if (Number(config.llm.sleep)) {
154
+ await new Promise((resolve) => setTimeout(resolve, config.llm.sleep ?? 1));
155
+ }
156
+ if (!config.keys.anthropicApiKey) {
157
+ throw new Error("Anthropic API key is not set in the config");
158
+ }
159
+ const anthropic = new Anthropic({
160
+ apiKey: config.keys.anthropicApiKey,
161
+ dangerouslyAllowBrowser: true
162
+ });
163
+ const response = await anthropic.messages.create({
164
+ model: config.llm.model,
165
+ max_tokens: 1024,
166
+ messages: [
167
+ {
168
+ role: "user",
169
+ content: `${config.llm.prePrompt}
170
+
171
+
172
+ ${message}
173
+
174
+
175
+ ${config.llm.postPrompt}`
176
+ }
177
+ ]
178
+ });
179
+ return response;
180
+ }
181
+
182
+ // src/io/anthropic/commit-response.ts
183
+ function commitResponseAnthropic(response) {
184
+ const result2 = response.content.reduce((acc, item) => {
185
+ const nextAcc = acc + (item.type === "text" ? item.text : "");
186
+ return nextAcc;
187
+ }, "");
188
+ return result2;
189
+ }
190
+
191
+ // src/io/anthropic/parse.ts
192
+ function parseAnthropic(unparsed) {
193
+ if (typeof unparsed !== "string") {
194
+ throw new Error("CommitResponse should be a string here.");
195
+ }
196
+ const parsed = JSON.parse(unparsed);
197
+ return parsed;
198
+ }
199
+ async function generateResponse(message, temperature = 1) {
200
+ const config = await awaitedConfig;
201
+ if (!config.keys.geminiApiKey) {
202
+ throw new Error("Gemini API key is not set in the config");
203
+ }
204
+ const generativeAIClient = new GoogleGenerativeAI(config.keys.geminiApiKey);
205
+ const model = generativeAIClient.getGenerativeModel({
206
+ model: config.llm.model,
207
+ generationConfig: {
208
+ temperature
209
+ }
210
+ });
211
+ const prompt = String(`${config.llm.prePrompt}
212
+
213
+
214
+ ${message}
215
+
216
+
217
+ ${config.llm.postPrompt}`).trim();
218
+ if (config.debug) {
219
+ console.log("Gemini model prompt:", JSON.stringify({ prompt }));
220
+ }
221
+ const response = await model.generateContent([prompt]);
222
+ return response;
223
+ }
224
+ async function askGemini(message) {
225
+ const config = await awaitedConfig;
226
+ if (Number(config.llm.sleep)) {
227
+ await new Promise((resolve) => setTimeout(resolve, config.llm.sleep ?? 1));
228
+ }
229
+ if (!config.keys.geminiApiKey) {
230
+ throw new Error("Gemini API key is not set in the config");
231
+ }
232
+ if (config.debug) {
233
+ console.log("\nAsking Gemini model:", JSON.stringify({ model: config.llm.model, message }));
234
+ }
235
+ let response;
236
+ for (let i = 0; i < 3; i++) {
237
+ const maybeResponse = await generateResponse(message, config.llm.temperature);
238
+ if (!String(maybeResponse.response.candidates?.[0]?.content?.parts?.[0]?.text ?? "").includes("```json")) {
239
+ response = maybeResponse;
240
+ break;
241
+ }
242
+ if (config.debug) {
243
+ console.log("Gemini model response is not valid, contains no JSON:", JSON.stringify({ maybeResponse }));
244
+ }
245
+ }
246
+ if (config.debug) {
247
+ console.log("Gemini model response:", JSON.stringify({ response }));
248
+ }
249
+ if (!response) {
250
+ throw new Error("Gemini model response is not valid");
251
+ }
252
+ return response;
253
+ }
254
+
255
+ // src/io/gemini/commit-response.ts
256
+ function commitResponseGemini(response) {
257
+ const result2 = response.response.text();
258
+ return result2;
259
+ }
260
+
261
+ // src/io/gemini/parse.ts
262
+ function parseGemini(unparsed) {
263
+ if (typeof unparsed !== "string") {
264
+ throw new Error("CommitResponse should be a string here.");
265
+ }
266
+ const cleaned = unparsed.replace(/```json/g, "").replace(/```/g, "");
267
+ const parsed = JSON.parse(cleaned);
268
+ return parsed;
269
+ }
270
+
271
+ // src/io/huggingface/languagesMap.ts
272
+ var languagesMap = {
273
+ "en-US": "eng_Latn",
274
+ "en-GB": "eng_Latn",
275
+ "pt-BR": "por_Latn",
276
+ "pt-PT": "por_Latn",
277
+ "es-ES": "spa_Latn",
278
+ "es-MX": "spa_Latn",
279
+ "fr-FR": "fra_Latn",
280
+ "fr-CA": "fra_Latn",
281
+ "de-DE": "deu_Latn",
282
+ "it-IT": "ita_Latn",
283
+ "nl-NL": "nld_Latn",
284
+ "pl-PL": "pol_Latn",
285
+ "ru-RU": "rus_Cyrl",
286
+ "uk-UA": "ukr_Cyrl",
287
+ "bg-BG": "bul_Cyrl",
288
+ "hr-HR": "hrv_Latn",
289
+ "cs-CZ": "ces_Latn",
290
+ "sk-SK": "slk_Latn",
291
+ "hu-HU": "hun_Latn",
292
+ "ro-RO": "ron_Latn",
293
+ "fi-FI": "fin_Latn",
294
+ "sv-SE": "swe_Latn",
295
+ "da-DK": "dan_Latn",
296
+ "no-NO": "nob_Latn",
297
+ "is-IS": "isl_Latn",
298
+ "et-EE": "est_Latn",
299
+ "lv-LV": "lav_Latn",
300
+ "lt-LT": "lit_Latn",
301
+ "mt-MT": "mlt_Latn",
302
+ "ga-IE": "gle_Latn",
303
+ "cy-GB": "cym_Latn",
304
+ "eu-ES": "eus_Latn",
305
+ "ca-ES": "cat_Latn",
306
+ "gl-ES": "glg_Latn",
307
+ "oc-FR": "oci_Latn",
308
+ "br-FR": "bre_Latn",
309
+ "gd-GB": "gla_Latn",
310
+ "kw-GB": "cor_Latn",
311
+ "fur-IT": "fur_Latn",
312
+ "rm-CH": "roh_Latn",
313
+ "lb-LU": "ltz_Latn",
314
+ "fy-NL": "fry_Latn",
315
+ "af-ZA": "afr_Latn",
316
+ "zh-CN": "zho_Hans",
317
+ "zh-TW": "zho_Hant",
318
+ "zh-HK": "zho_Hant",
319
+ "ja-JP": "jpn_Jpan",
320
+ "ko-KR": "kor_Hang",
321
+ "th-TH": "tha_Thai",
322
+ "vi-VN": "vie_Latn",
323
+ "id-ID": "ind_Latn",
324
+ "ms-MY": "zsm_Latn",
325
+ "tl-PH": "tgl_Latn",
326
+ "my-MM": "mya_Mymr",
327
+ "km-KH": "khm_Khmr",
328
+ "lo-LA": "lao_Laoo",
329
+ "bn-BD": "ben_Beng",
330
+ "bn-IN": "ben_Beng",
331
+ "hi-IN": "hin_Deva",
332
+ "ur-PK": "urd_Arab",
333
+ "ur-IN": "urd_Arab",
334
+ "pa-IN": "pan_Guru",
335
+ "gu-IN": "guj_Gujr",
336
+ "or-IN": "ory_Orya",
337
+ "as-IN": "asm_Beng",
338
+ "ml-IN": "mal_Mlym",
339
+ "ta-IN": "tam_Tamil",
340
+ "te-IN": "tel_Telu",
341
+ "kn-IN": "kan_Knda",
342
+ "si-LK": "sin_Sinh",
343
+ "ne-NP": "nep_Deva",
344
+ "dz-BT": "dzo_Tibt",
345
+ "bo-CN": "bod_Tibt",
346
+ "mn-MN": "khk_Cyrl",
347
+ "ka-GE": "kat_Geor",
348
+ "hy-AM": "hye_Armn",
349
+ "az-AZ": "azj_Latn",
350
+ "tr-TR": "tur_Latn",
351
+ "fa-IR": "pes_Arab",
352
+ "fa-AF": "pes_Arab",
353
+ "ps-AF": "pbt_Arab",
354
+ "ku-TR": "kmr_Latn",
355
+ "he-IL": "heb_Hebr",
356
+ "ar-SA": "arb_Arab",
357
+ "ar-EG": "arb_Arab",
358
+ "ar-MA": "arb_Arab",
359
+ "ar-DZ": "arb_Arab",
360
+ "ar-TN": "arb_Arab",
361
+ "ar-LY": "arb_Arab",
362
+ "ar-SD": "arb_Arab",
363
+ "ar-IQ": "arb_Arab",
364
+ "ar-SY": "arb_Arab",
365
+ "ar-JO": "arb_Arab",
366
+ "ar-LB": "arb_Arab",
367
+ "ar-KW": "arb_Arab",
368
+ "ar-AE": "arb_Arab",
369
+ "ar-QA": "arb_Arab",
370
+ "ar-BH": "arb_Arab",
371
+ "ar-OM": "arb_Arab",
372
+ "ar-YE": "arb_Arab",
373
+ "ar-SO": "arb_Arab",
374
+ "ar-DJ": "arb_Arab",
375
+ "ar-KM": "arb_Arab",
376
+ "ar-TD": "arb_Arab",
377
+ "ar-ER": "arb_Arab",
378
+ "ar-IL": "arb_Arab",
379
+ "ar-PS": "arb_Arab",
380
+ "ar-001": "arb_Arab",
381
+ "sw-KE": "swh_Latn",
382
+ "sw-TZ": "swh_Latn",
383
+ "am-ET": "amh_Ethi",
384
+ "om-ET": "gaz_Latn",
385
+ "so-SO": "som_Latn",
386
+ "ha-NG": "hau_Latn",
387
+ "yo-NG": "yor_Latn",
388
+ "ig-NG": "ibo_Latn",
389
+ "zu-ZA": "zul_Latn",
390
+ "xh-ZA": "xho_Latn",
391
+ "rw-RW": "kin_Latn",
392
+ "lg-UG": "lug_Latn",
393
+ "ak-GH": "aka_Latn",
394
+ "tw-GH": "twi_Latn",
395
+ "ee-GH": "ewe_Latn",
396
+ "ff-SN": "fuv_Latn",
397
+ "wo-SN": "wol_Latn",
398
+ "sn-ZW": "sna_Latn",
399
+ "nd-ZW": "nde_Latn",
400
+ "ny-MW": "nya_Latn",
401
+ "st-ZA": "sot_Latn",
402
+ "tn-BW": "tsn_Latn",
403
+ "ts-ZA": "tso_Latn",
404
+ "ve-ZA": "ven_Latn",
405
+ "ss-ZA": "ssw_Latn",
406
+ "nr-ZA": "nbl_Latn",
407
+ "qu-PE": "quy_Latn",
408
+ "qu-BO": "quy_Latn",
409
+ "qu-EC": "quy_Latn",
410
+ "ay-BO": "aym_Latn",
411
+ "gn-PY": "grn_Latn",
412
+ "ht-HT": "hat_Latn",
413
+ "jv-ID": "jav_Latn",
414
+ "su-ID": "sun_Latn",
415
+ "ceb-PH": "ceb_Latn",
416
+ "ilo-PH": "ilo_Latn",
417
+ "war-PH": "war_Latn",
418
+ "bjn-ID": "bjn_Latn",
419
+ "ban-ID": "ban_Latn",
420
+ "mad-ID": "mad_Latn",
421
+ "min-ID": "min_Latn",
422
+ "ace-ID": "ace_Latn",
423
+ "bug-ID": "bug_Latn",
424
+ "gor-ID": "gor_Latn",
425
+ "mak-ID": "mak_Latn",
426
+ "mdr-ID": "mdr_Latn",
427
+ "sas-ID": "sas_Latn",
428
+ "shn-MM": "shn_Mymr",
429
+ "kac-MM": "kac_Latn",
430
+ "lzh-CN": "lzh_Hant",
431
+ "wuu-CN": "wuu_Hans",
432
+ "yue-CN": "yue_Hant",
433
+ "nan-TW": "nan_Hant",
434
+ "hak-TW": "hak_Hant",
435
+ "cjy-CN": "cjy_Hans",
436
+ "cmn-CN": "cmn_Hans",
437
+ "cmn-TW": "cmn_Hant",
438
+ "cmn-SG": "cmn_Hans",
439
+ "cmn-HK": "cmn_Hant",
440
+ "cmn-MO": "cmn_Hant",
441
+ "cmn-001": "cmn_Hans",
442
+ "haw-US": "haw_Latn",
443
+ "mi-NZ": "mri_Latn",
444
+ "sm-WS": "smo_Latn",
445
+ "to-TO": "ton_Latn",
446
+ "fj-FJ": "fij_Latn",
447
+ "ty-PF": "tah_Latn",
448
+ "co-FR": "cos_Latn",
449
+ "eu-FR": "eus_Latn",
450
+ "kk-KZ": "kaz_Cyrl",
451
+ "ky-KG": "kir_Cyrl",
452
+ "uz-UZ": "uzn_Latn",
453
+ "tg-TJ": "tgk_Cyrl",
454
+ "tk-TM": "tuk_Latn"
455
+ };
456
+
457
+ // src/io/huggingface/ask.ts
458
+ function getLanguageCode(language) {
459
+ return languagesMap[language];
460
+ }
461
+ function progressCallback(progress) {
462
+ process.stdout.clearLine(0);
463
+ process.stdout.cursorTo(0);
464
+ if (progress.status === "download") {
465
+ process.stdout.write("Downloading...");
466
+ } else if (progress.status === "initiate") {
467
+ process.stdout.write("Initializing...");
468
+ } else if (progress.status === "done") {
469
+ process.stdout.write("Done!");
470
+ } else if (progress.status === "progress" && "progress" in progress && "loaded" in progress && "total" in progress) {
471
+ process.stdout.write(
472
+ `Downloading: ${Number(progress.progress).toFixed(2)}%, loaded: ${progress.loaded}/${progress.total}`
473
+ );
474
+ }
475
+ }
476
+ async function pipeLanguage(pipe, original, srcLanguage, targetLanguage) {
477
+ const response = await pipe(original, {
478
+ src_lang: srcLanguage,
479
+ tgt_lang: targetLanguage,
480
+ temperature: 1
481
+ });
482
+ return response;
483
+ }
484
+ async function askHuggingface(original) {
485
+ const config = await awaitedConfig;
486
+ const cacheDir = `${config.cache.dir}/.cache`;
487
+ env.cacheDir = cacheDir;
488
+ const pipe = await pipeline("translation", config.llm.model, {
489
+ progress_callback: progressCallback,
490
+ cache_dir: cacheDir
491
+ });
492
+ const { languages } = config;
493
+ let responses = [];
494
+ for await (const language of languages) {
495
+ const response = await pipeLanguage(
496
+ pipe,
497
+ original,
498
+ getLanguageCode(config.sourceLanguage),
499
+ getLanguageCode(language)
500
+ );
501
+ if (Array.isArray(response)) {
502
+ responses = responses.concat(
503
+ response.map((r) => ({
504
+ ...r,
505
+ targetLanguage: language
506
+ }))
507
+ );
508
+ } else {
509
+ responses.push({
510
+ ...response,
511
+ targetLanguage: language
512
+ });
513
+ }
514
+ }
515
+ return { responses, original };
516
+ }
517
+
518
+ // src/io/huggingface/commit-response.ts
519
+ function commitResponseHuggingface(response) {
520
+ const { responses, original } = response;
521
+ const translation = responses.reduce((acc, curr) => {
522
+ acc[curr.targetLanguage] = curr.translation_text;
523
+ return acc;
524
+ }, {});
525
+ return {
526
+ translation,
527
+ original
528
+ };
529
+ }
530
+
531
+ // src/io/huggingface/parse.ts
532
+ function parseHuggingface(unparsed) {
533
+ if (typeof unparsed === "string") {
534
+ throw new Error("CommitResponse should not be a string here.");
535
+ }
536
+ return unparsed;
537
+ }
538
+
539
+ // src/io/ask-llm.ts
540
+ var llmChoices = {
541
+ anthropic: {
542
+ ask: askAnthropic,
543
+ commitResponse: commitResponseAnthropic,
544
+ parse: parseAnthropic
545
+ },
546
+ gemini: {
547
+ ask: askGemini,
548
+ commitResponse: commitResponseGemini,
549
+ parse: parseGemini
550
+ },
551
+ huggingface: {
552
+ ask: askHuggingface,
553
+ commitResponse: commitResponseHuggingface,
554
+ parse: parseHuggingface
555
+ }
556
+ };
557
+ async function processLLMChoice(llmChoice, prompt) {
558
+ const response = await llmChoice.ask(prompt);
559
+ const unparsed = llmChoice.commitResponse(response);
560
+ const parsed = llmChoice.parse(unparsed);
561
+ return parsed;
562
+ }
563
+ async function askLLM(prompt) {
564
+ const config = await awaitedConfig;
565
+ const llmChoiceName = config.llm.choice;
566
+ const llmChoice = llmChoices[llmChoiceName];
567
+ if (!llmChoice) {
568
+ throw new Error("LLMChoice not found");
569
+ }
570
+ return processLLMChoice(llmChoice, prompt);
571
+ }
572
+
573
+ export { askLLM };
@@ -0,0 +1,11 @@
1
+ import { GenerateContentResult } from '@google/generative-ai';
2
+
3
+ /**
4
+ * Asks the Gemini model for a response.
5
+ *
6
+ * @param message - The message to ask the model.
7
+ * @returns The response from the model.
8
+ */
9
+ declare function askGemini(message: string): Promise<GenerateContentResult>;
10
+
11
+ export { askGemini };