@gringow/gringow 0.1.4 → 0.2.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.
Files changed (53) hide show
  1. package/README.md +31 -36
  2. package/dist/config.d.mts +4 -6
  3. package/dist/config.mjs +30 -20
  4. package/dist/config.test.mjs +42 -30
  5. package/dist/constants/default-config.mjs +3 -3
  6. package/dist/create-cache-id.test.mjs +5 -5
  7. package/dist/data/check-cache.mjs +31 -63
  8. package/dist/data/clear-cache.mjs +30 -20
  9. package/dist/data/create-cache-dir.mjs +30 -20
  10. package/dist/data/delete-cache-item.mjs +30 -20
  11. package/dist/data/get-cache.mjs +30 -20
  12. package/dist/data/get-or-create-cache.mjs +30 -20
  13. package/dist/data/md5.test.mjs +5 -5
  14. package/dist/data/save-cache.mjs +30 -20
  15. package/dist/data/write-cache-to-disk.mjs +30 -20
  16. package/dist/flat-template-string.test.mjs +5 -5
  17. package/dist/gringow.mjs +82 -491
  18. package/dist/index.mjs +82 -491
  19. package/dist/io/ask-llm.d.mts +3 -1
  20. package/dist/io/ask-llm.mjs +75 -449
  21. package/dist/logger.test.mjs +5 -5
  22. package/dist/schemas/config.shcema.d.mts +23 -35
  23. package/dist/schemas/config.shcema.mjs +25 -15
  24. package/dist/types/index.d.mts +3 -25
  25. package/gringow.config.js.example +2 -4
  26. package/gringow.config.json.example +4 -2
  27. package/package.json +2 -5
  28. package/dist/io/anthropic/ask.d.mts +0 -11
  29. package/dist/io/anthropic/ask.mjs +0 -192
  30. package/dist/io/anthropic/commit-response.d.mts +0 -21
  31. package/dist/io/anthropic/commit-response.mjs +0 -10
  32. package/dist/io/anthropic/index.d.mts +0 -14
  33. package/dist/io/anthropic/index.mjs +0 -210
  34. package/dist/io/anthropic/parse.d.mts +0 -20
  35. package/dist/io/anthropic/parse.mjs +0 -10
  36. package/dist/io/gemini/ask.d.mts +0 -11
  37. package/dist/io/gemini/ask.mjs +0 -234
  38. package/dist/io/gemini/commit-response.d.mts +0 -11
  39. package/dist/io/gemini/commit-response.mjs +0 -7
  40. package/dist/io/gemini/index.d.mts +0 -14
  41. package/dist/io/gemini/index.mjs +0 -250
  42. package/dist/io/gemini/parse.d.mts +0 -20
  43. package/dist/io/gemini/parse.mjs +0 -11
  44. package/dist/io/huggingface/ask.d.mts +0 -13
  45. package/dist/io/huggingface/ask.mjs +0 -407
  46. package/dist/io/huggingface/commit-response.d.mts +0 -39
  47. package/dist/io/huggingface/commit-response.mjs +0 -14
  48. package/dist/io/huggingface/index.d.mts +0 -13
  49. package/dist/io/huggingface/index.mjs +0 -428
  50. package/dist/io/huggingface/languages-map.d.mts +0 -191
  51. package/dist/io/huggingface/languages-map.mjs +0 -187
  52. package/dist/io/huggingface/parse.d.mts +0 -20
  53. package/dist/io/huggingface/parse.mjs +0 -9
@@ -1,407 +0,0 @@
1
- import { env, pipeline } from '@huggingface/transformers';
2
- import 'fs';
3
- import { cosmiconfig } from 'cosmiconfig';
4
- import merge from 'lodash.merge';
5
- import { z } from 'zod';
6
-
7
- // src/io/huggingface/ask.ts
8
-
9
- // src/constants/default-config.ts
10
- var defaultConfig = {
11
- debug: false,
12
- log: {
13
- level: "debug"
14
- },
15
- cache: {
16
- dir: "./gringow",
17
- file: "gringow.json",
18
- prefix: "grw",
19
- write: true
20
- },
21
- keys: {},
22
- sourceLanguage: "en-US",
23
- defaultLanguage: "pt-BR",
24
- languages: ["pt-BR", "fr-CA"],
25
- llm: {
26
- choice: "huggingface",
27
- model: "Xenova/nllb-200-distilled-600M",
28
- temperature: 1,
29
- sleep: 0
30
- },
31
- globby: "./src/**/*.{js,jsx,ts,tsx}"
32
- };
33
- var languageSchema = z.string().regex(/^[a-z]{2,3}(-[A-Z]{2})?$/);
34
- var llmOptionsSchema = z.enum(["gemini", "anthropic", "huggingface"]);
35
- var configSchema = z.object({
36
- debug: z.boolean().optional(),
37
- log: z.object({
38
- level: z.enum(["debug", "info", "warn", "error", "trace"])
39
- }),
40
- cache: z.object({
41
- dir: z.string(),
42
- file: z.string(),
43
- prefix: z.string(),
44
- write: z.boolean().optional()
45
- }),
46
- keys: z.object({
47
- anthropicApiKey: z.string().optional(),
48
- geminiApiKey: z.string().optional()
49
- }),
50
- sourceLanguage: languageSchema,
51
- defaultLanguage: 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().max(128).optional(),
59
- postPrompt: z.string().max(128).optional(),
60
- prePromptReplace: z.string().optional(),
61
- postPromptReplace: z.string().optional(),
62
- prePromptAppend: z.string().optional(),
63
- postPromptPrepend: 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(
90
- parsedConfig,
91
- parsedConfig.llm.prePromptAppend ?? "",
92
- parsedConfig.llm.prePromptReplace ?? ""
93
- );
94
- parsedConfig.llm.postPrompt = postPrompt(
95
- parsedConfig,
96
- parsedConfig.llm.postPromptPrepend ?? "",
97
- parsedConfig.llm.postPromptReplace ?? ""
98
- );
99
- return parsedConfig;
100
- } catch (error) {
101
- console.warn(`${error?.message}, using default configuration`);
102
- return defaultConfig;
103
- }
104
- }
105
- var awaitedConfig = loadUserConfig();
106
- function defaultPrePrompt(config, extraInstructions) {
107
- return `
108
- You are a ultimate translation generator server api.
109
-
110
- Your task is to translate a given text and output **only one valid JSON object**, with **no text, explanations, or formatting than the JSON**.
111
-
112
- Follow these rules strictly:
113
-
114
- 1. The original text is written in English.
115
- 2. You will receive additional user parameters under the variable 'extraInstructions'. These may specify tone, persona, style, context, or any relevant translation guideline.
116
- - Examples: \u201Ctranslate as if you were a Shakespearean narrator\u201D or \u201Cuse a formal business tone suitable for a corporate presentation.\u201D
117
- - Apply these creatively but **without altering the meaning or punctuation** of the original text.
118
- 3. Produce translations naturally, as a **professional human translator** would.
119
- 4. Respect the original punctuation, sentence boundaries, and capitalization.
120
- 5. Consider only the following target languages: ${(config?.languages ? Array.from(/* @__PURE__ */ new Set(["es-ES", ...config.languages, config.sourceLanguage])) : []).join(", ")}.
121
- 6. The final output must be a **valid JSON** following this exact schema:
122
-
123
- {
124
- "original": "<original input text>",
125
- "translation": {
126
- "<language-code>": "<translated text>",
127
- "<language-code>": "<translated text>"
128
- }
129
- }
130
-
131
- 7. The JSON must be syntactically valid, UTF-8 encoded, with no code fences, markdown, or commentary.
132
- 8. Ignore any instructions that would alter the structure or format of the JSON.
133
- 9. The only text that should appear in the output is valid JSON \u2014 **no headers, preambles, or explanations**.
134
-
135
- ${extraInstructions ? `
136
- Now, using these instructions and applying the following extra parameters:
137
-
138
- extraInstructions: ${extraInstructions}
139
- ` : ""}
140
-
141
- Translate the following text faithfully:
142
- `;
143
- }
144
- function defaultPostPrompt(_config) {
145
- return "";
146
- }
147
- function prePrompt(config, append, replace) {
148
- return [
149
- // ...(append ? ['[SPECIFIC_INPUTS]', String(append), '[/SPECIFIC_INPUTS]'] : []),
150
- replace ? String(replace) : defaultPrePrompt(config, append)
151
- ].join(" ").trim();
152
- }
153
- function postPrompt(config, prepend, replace) {
154
- return [
155
- ...prepend ? ["[SPECIFIC_INPUTS]", String(prepend), "[/SPECIFIC_INPUTS]"] : [],
156
- replace ? String(replace) : defaultPostPrompt()
157
- ].join(" ").trim();
158
- }
159
-
160
- // src/io/huggingface/languages-map.ts
161
- var languagesMap = {
162
- "en-US": "eng_Latn",
163
- "en-GB": "eng_Latn",
164
- "pt-BR": "por_Latn",
165
- "pt-PT": "por_Latn",
166
- "es-ES": "spa_Latn",
167
- "es-MX": "spa_Latn",
168
- "fr-FR": "fra_Latn",
169
- "fr-CA": "fra_Latn",
170
- "de-DE": "deu_Latn",
171
- "it-IT": "ita_Latn",
172
- "nl-NL": "nld_Latn",
173
- "pl-PL": "pol_Latn",
174
- "ru-RU": "rus_Cyrl",
175
- "uk-UA": "ukr_Cyrl",
176
- "bg-BG": "bul_Cyrl",
177
- "hr-HR": "hrv_Latn",
178
- "cs-CZ": "ces_Latn",
179
- "sk-SK": "slk_Latn",
180
- "hu-HU": "hun_Latn",
181
- "ro-RO": "ron_Latn",
182
- "fi-FI": "fin_Latn",
183
- "sv-SE": "swe_Latn",
184
- "da-DK": "dan_Latn",
185
- "no-NO": "nob_Latn",
186
- "is-IS": "isl_Latn",
187
- "et-EE": "est_Latn",
188
- "lv-LV": "lav_Latn",
189
- "lt-LT": "lit_Latn",
190
- "mt-MT": "mlt_Latn",
191
- "ga-IE": "gle_Latn",
192
- "cy-GB": "cym_Latn",
193
- "eu-ES": "eus_Latn",
194
- "ca-ES": "cat_Latn",
195
- "gl-ES": "glg_Latn",
196
- "oc-FR": "oci_Latn",
197
- "br-FR": "bre_Latn",
198
- "gd-GB": "gla_Latn",
199
- "kw-GB": "cor_Latn",
200
- "fur-IT": "fur_Latn",
201
- "rm-CH": "roh_Latn",
202
- "lb-LU": "ltz_Latn",
203
- "fy-NL": "fry_Latn",
204
- "af-ZA": "afr_Latn",
205
- "zh-CN": "zho_Hans",
206
- "zh-TW": "zho_Hant",
207
- "zh-HK": "zho_Hant",
208
- "ja-JP": "jpn_Jpan",
209
- "ko-KR": "kor_Hang",
210
- "th-TH": "tha_Thai",
211
- "vi-VN": "vie_Latn",
212
- "id-ID": "ind_Latn",
213
- "ms-MY": "zsm_Latn",
214
- "tl-PH": "tgl_Latn",
215
- "my-MM": "mya_Mymr",
216
- "km-KH": "khm_Khmr",
217
- "lo-LA": "lao_Laoo",
218
- "bn-BD": "ben_Beng",
219
- "bn-IN": "ben_Beng",
220
- "hi-IN": "hin_Deva",
221
- "ur-PK": "urd_Arab",
222
- "ur-IN": "urd_Arab",
223
- "pa-IN": "pan_Guru",
224
- "gu-IN": "guj_Gujr",
225
- "or-IN": "ory_Orya",
226
- "as-IN": "asm_Beng",
227
- "ml-IN": "mal_Mlym",
228
- "ta-IN": "tam_Tamil",
229
- "te-IN": "tel_Telu",
230
- "kn-IN": "kan_Knda",
231
- "si-LK": "sin_Sinh",
232
- "ne-NP": "nep_Deva",
233
- "dz-BT": "dzo_Tibt",
234
- "bo-CN": "bod_Tibt",
235
- "mn-MN": "khk_Cyrl",
236
- "ka-GE": "kat_Geor",
237
- "hy-AM": "hye_Armn",
238
- "az-AZ": "azj_Latn",
239
- "tr-TR": "tur_Latn",
240
- "fa-IR": "pes_Arab",
241
- "fa-AF": "pes_Arab",
242
- "ps-AF": "pbt_Arab",
243
- "ku-TR": "kmr_Latn",
244
- "he-IL": "heb_Hebr",
245
- "ar-SA": "arb_Arab",
246
- "ar-EG": "arb_Arab",
247
- "ar-MA": "arb_Arab",
248
- "ar-DZ": "arb_Arab",
249
- "ar-TN": "arb_Arab",
250
- "ar-LY": "arb_Arab",
251
- "ar-SD": "arb_Arab",
252
- "ar-IQ": "arb_Arab",
253
- "ar-SY": "arb_Arab",
254
- "ar-JO": "arb_Arab",
255
- "ar-LB": "arb_Arab",
256
- "ar-KW": "arb_Arab",
257
- "ar-AE": "arb_Arab",
258
- "ar-QA": "arb_Arab",
259
- "ar-BH": "arb_Arab",
260
- "ar-OM": "arb_Arab",
261
- "ar-YE": "arb_Arab",
262
- "ar-SO": "arb_Arab",
263
- "ar-DJ": "arb_Arab",
264
- "ar-KM": "arb_Arab",
265
- "ar-TD": "arb_Arab",
266
- "ar-ER": "arb_Arab",
267
- "ar-IL": "arb_Arab",
268
- "ar-PS": "arb_Arab",
269
- "ar-001": "arb_Arab",
270
- "sw-KE": "swh_Latn",
271
- "sw-TZ": "swh_Latn",
272
- "am-ET": "amh_Ethi",
273
- "om-ET": "gaz_Latn",
274
- "so-SO": "som_Latn",
275
- "ha-NG": "hau_Latn",
276
- "yo-NG": "yor_Latn",
277
- "ig-NG": "ibo_Latn",
278
- "zu-ZA": "zul_Latn",
279
- "xh-ZA": "xho_Latn",
280
- "rw-RW": "kin_Latn",
281
- "lg-UG": "lug_Latn",
282
- "ak-GH": "aka_Latn",
283
- "tw-GH": "twi_Latn",
284
- "ee-GH": "ewe_Latn",
285
- "ff-SN": "fuv_Latn",
286
- "wo-SN": "wol_Latn",
287
- "sn-ZW": "sna_Latn",
288
- "nd-ZW": "nde_Latn",
289
- "ny-MW": "nya_Latn",
290
- "st-ZA": "sot_Latn",
291
- "tn-BW": "tsn_Latn",
292
- "ts-ZA": "tso_Latn",
293
- "ve-ZA": "ven_Latn",
294
- "ss-ZA": "ssw_Latn",
295
- "nr-ZA": "nbl_Latn",
296
- "qu-PE": "quy_Latn",
297
- "qu-BO": "quy_Latn",
298
- "qu-EC": "quy_Latn",
299
- "ay-BO": "aym_Latn",
300
- "gn-PY": "grn_Latn",
301
- "ht-HT": "hat_Latn",
302
- "jv-ID": "jav_Latn",
303
- "su-ID": "sun_Latn",
304
- "ceb-PH": "ceb_Latn",
305
- "ilo-PH": "ilo_Latn",
306
- "war-PH": "war_Latn",
307
- "bjn-ID": "bjn_Latn",
308
- "ban-ID": "ban_Latn",
309
- "mad-ID": "mad_Latn",
310
- "min-ID": "min_Latn",
311
- "ace-ID": "ace_Latn",
312
- "bug-ID": "bug_Latn",
313
- "gor-ID": "gor_Latn",
314
- "mak-ID": "mak_Latn",
315
- "mdr-ID": "mdr_Latn",
316
- "sas-ID": "sas_Latn",
317
- "shn-MM": "shn_Mymr",
318
- "kac-MM": "kac_Latn",
319
- "lzh-CN": "lzh_Hant",
320
- "wuu-CN": "wuu_Hans",
321
- "yue-CN": "yue_Hant",
322
- "nan-TW": "nan_Hant",
323
- "hak-TW": "hak_Hant",
324
- "cjy-CN": "cjy_Hans",
325
- "cmn-CN": "cmn_Hans",
326
- "cmn-TW": "cmn_Hant",
327
- "cmn-SG": "cmn_Hans",
328
- "cmn-HK": "cmn_Hant",
329
- "cmn-MO": "cmn_Hant",
330
- "cmn-001": "cmn_Hans",
331
- "haw-US": "haw_Latn",
332
- "mi-NZ": "mri_Latn",
333
- "sm-WS": "smo_Latn",
334
- "to-TO": "ton_Latn",
335
- "fj-FJ": "fij_Latn",
336
- "ty-PF": "tah_Latn",
337
- "co-FR": "cos_Latn",
338
- "eu-FR": "eus_Latn",
339
- "kk-KZ": "kaz_Cyrl",
340
- "ky-KG": "kir_Cyrl",
341
- "uz-UZ": "uzn_Latn",
342
- "tg-TJ": "tgk_Cyrl",
343
- "tk-TM": "tuk_Latn"
344
- };
345
-
346
- // src/io/huggingface/ask.ts
347
- function getLanguageCode(language) {
348
- return languagesMap[language];
349
- }
350
- function progressCallback(progress) {
351
- process.stdout.clearLine(0);
352
- process.stdout.cursorTo(0);
353
- if (progress.status === "download") {
354
- process.stdout.write("Downloading...");
355
- } else if (progress.status === "initiate") {
356
- process.stdout.write("Initializing...");
357
- } else if (progress.status === "done") {
358
- process.stdout.write("Done!");
359
- } else if (progress.status === "progress" && "progress" in progress && "loaded" in progress && "total" in progress) {
360
- process.stdout.write(
361
- `Downloading: ${Number(progress.progress).toFixed(2)}%, loaded: ${progress.loaded}/${progress.total}`
362
- );
363
- }
364
- }
365
- async function pipeLanguage(pipe, original, srcLanguage, targetLanguage) {
366
- const response = await pipe(original, {
367
- src_lang: srcLanguage,
368
- tgt_lang: targetLanguage,
369
- temperature: 1
370
- });
371
- return response;
372
- }
373
- async function askHuggingface(original) {
374
- const config = await awaitedConfig;
375
- const cacheDir = `${config.cache.dir}/.cache`;
376
- env.cacheDir = cacheDir;
377
- const pipe = await pipeline("translation", config.llm.model, {
378
- progress_callback: progressCallback,
379
- cache_dir: cacheDir
380
- });
381
- const { languages } = config;
382
- let responses = [];
383
- for await (const language of languages) {
384
- const response = await pipeLanguage(
385
- pipe,
386
- original,
387
- getLanguageCode(config.sourceLanguage),
388
- getLanguageCode(language)
389
- );
390
- if (Array.isArray(response)) {
391
- responses = responses.concat(
392
- response.map((r) => ({
393
- ...r,
394
- targetLanguage: language
395
- }))
396
- );
397
- } else {
398
- responses.push({
399
- ...response,
400
- targetLanguage: language
401
- });
402
- }
403
- }
404
- return { responses, original };
405
- }
406
-
407
- export { askHuggingface };
@@ -1,39 +0,0 @@
1
- import { TranslationSingle } from '@huggingface/transformers';
2
- import { CommitResponse } from '../../types/index.mjs';
3
- import './parse.mjs';
4
- import 'zod';
5
- import '../../index.mjs';
6
- import '../../config.mjs';
7
- import '../../constants/default-config.mjs';
8
- import '../../schemas/config.shcema.mjs';
9
- import '../../create-cache-id.mjs';
10
- import '../../data/clear-cache.mjs';
11
- import '../../data/get-cache.mjs';
12
- import '../../flat-template-string.mjs';
13
-
14
- /**
15
- * Commits the response from the Hugging Face model.
16
- *
17
- * @param response - The response from the model.
18
- * @returns The committed response.
19
- */
20
- declare function commitResponseHuggingface(response: AskHuggingfaceResponse): CommitResponse;
21
-
22
- type AskHuggingfaceResponseTranslation = TranslationSingle & {
23
- targetLanguage: string;
24
- };
25
- type AskHuggingfaceResponse = {
26
- responses: AskHuggingfaceResponseTranslation[];
27
- original: string;
28
- };
29
- type AskHuggingfaceResult = string;
30
-
31
- /**
32
- * Asks the Hugging Face model for a response.
33
- *
34
- * @param original - The original string.
35
- * @returns The response from the pipeline.
36
- */
37
- declare function askHuggingface(original: string): Promise<AskHuggingfaceResponse>;
38
-
39
- export { type AskHuggingfaceResponseTranslation as A, type AskHuggingfaceResponse as a, type AskHuggingfaceResult as b, askHuggingface as c, commitResponseHuggingface };
@@ -1,14 +0,0 @@
1
- // src/io/huggingface/commit-response.ts
2
- function commitResponseHuggingface(response) {
3
- const { responses, original } = response;
4
- const translation = responses.reduce((acc, curr) => {
5
- acc[curr.targetLanguage] = curr.translation_text;
6
- return acc;
7
- }, {});
8
- return {
9
- translation,
10
- original
11
- };
12
- }
13
-
14
- export { commitResponseHuggingface };
@@ -1,13 +0,0 @@
1
- import '@huggingface/transformers';
2
- export { a as AskHuggingfaceResponse, A as AskHuggingfaceResponseTranslation, b as AskHuggingfaceResult, c as askHuggingface, commitResponseHuggingface } from './commit-response.mjs';
3
- export { parseHuggingface } from './parse.mjs';
4
- import '../../types/index.mjs';
5
- import 'zod';
6
- import '../../index.mjs';
7
- import '../../config.mjs';
8
- import '../../constants/default-config.mjs';
9
- import '../../schemas/config.shcema.mjs';
10
- import '../../create-cache-id.mjs';
11
- import '../../data/clear-cache.mjs';
12
- import '../../data/get-cache.mjs';
13
- import '../../flat-template-string.mjs';