dracosh 0.6.0 → 0.8.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/src/voice.js ADDED
@@ -0,0 +1,129 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { mkdir, rename, rm, stat, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { cleanUrl, findKey } from "./ai.js";
5
+ import { t } from "./i18n.js";
6
+ import { HOME } from "./store.js";
7
+
8
+ // Natural voices from ElevenLabs, with the user's own key (/settings → Voice). Optional: without one,
9
+ // words are read by the system's voices. Each word is generated once and kept in ~/.dracosh/audio,
10
+ // so a card costs once, not on every review.
11
+ export const ELEVENLABS = { url: "https://api.elevenlabs.io", keyEnv: "ELEVENLABS_API_KEY", site: "elevenlabs.io/app/settings/api-keys" };
12
+ // Flash v2.5: the cheapest per character, fast, and takes the word's language as a hint
13
+ export const MODEL = "eleven_flash_v2_5";
14
+ const LANGUAGES = new Set(["en", "ja", "zh", "de", "hi", "fr", "ko", "pt", "it", "es", "id", "nl", "tr", "fil", "pl", "sv", "bg", "ro", "ar", "cs", "el", "fi", "hr", "ms", "sk", "da", "ta", "uk", "ru", "hu", "no", "vi"]);
15
+ const CODE = { nb: "no", nn: "no", tl: "fil" };
16
+ const codeOf = (lang) => CODE[lang] ?? lang;
17
+ // a language the voice can read; the others stay with the system's voices
18
+ export const speaksLanguage = (lang) => LANGUAGES.has(codeOf(lang));
19
+
20
+ export const AUDIO_DIR = join(HOME, "audio");
21
+ const TIMEOUT_MS = 20_000;
22
+
23
+ // settings.voice, as saved: { provider: "elevenlabs", id, name, url? } (url: another of its servers, the
24
+ // EU one say), or null for the system's voices. The key goes to the address, so only ElevenLabs' own.
25
+ const isElevenLabs = (text) => typeof text === "string" && /^https:\/\/([a-z0-9-]+\.)*elevenlabs\.io\/?$/i.test(text.trim());
26
+ export function normalizeVoice(raw) {
27
+ if (!raw || typeof raw !== "object" || raw.provider !== "elevenlabs") return null;
28
+ if (typeof raw.id !== "string" || !/^[A-Za-z0-9_-]{1,64}$/.test(raw.id)) return null;
29
+ const name = typeof raw.name === "string" && raw.name.trim() ? raw.name.trim().slice(0, 60) : raw.id;
30
+ return { provider: "elevenlabs", id: raw.id, name, ...(isElevenLabs(raw.url) ? { url: cleanUrl(raw.url) } : {}) };
31
+ }
32
+
33
+ export const voiceLabel = (voice) => (voice ? `ElevenLabs · ${voice.name}` : t("voice.system"));
34
+ const urlOf = (voice) => voice?.url ?? ELEVENLABS.url;
35
+
36
+ // What went wrong, said as what to do: `code` is noKey, badKey, noCredit, noVoice, rateLimit, offline,
37
+ // timeout, server or failed. The key is never part of the message.
38
+ export class VoiceError extends Error {
39
+ constructor(code, vars = {}) {
40
+ super(t(`voice.errors.${code}`, { env: ELEVENLABS.keyEnv, ...vars }));
41
+ this.code = code;
42
+ }
43
+ }
44
+
45
+ export const findVoiceKey = () => findKey("elevenlabs");
46
+
47
+ async function call(voice, key, path, { body, signal, timeoutMs = TIMEOUT_MS } = {}) {
48
+ if (!key) throw new VoiceError("noKey");
49
+ const timeout = AbortSignal.timeout(timeoutMs);
50
+ let response;
51
+ try {
52
+ response = await fetch(`${urlOf(voice)}${path}`, {
53
+ method: body ? "POST" : "GET",
54
+ headers: { "xi-api-key": key, ...(body ? { "content-type": "application/json", accept: "audio/mpeg" } : {}) },
55
+ body: body && JSON.stringify(body),
56
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout
57
+ });
58
+ } catch (err) {
59
+ if (signal?.aborted) throw err;
60
+ throw new VoiceError(timeout.aborted ? "timeout" : "offline");
61
+ }
62
+ if (response.ok) return response;
63
+ let detail = {};
64
+ try {
65
+ const data = JSON.parse(await response.text());
66
+ detail = typeof data?.detail === "object" && data.detail ? data.detail : { message: data?.detail };
67
+ } catch {}
68
+ const code = detail.code ?? detail.status ?? "";
69
+ const said = String(detail.message ?? response.statusText ?? "").split(key).join("…").slice(0, 200);
70
+ if (response.status === 402 || /insufficient_credits|quota_exceeded/.test(code)) throw new VoiceError("noCredit");
71
+ if (response.status === 401 || response.status === 403) throw new VoiceError("badKey");
72
+ if (response.status === 404) throw new VoiceError("noVoice");
73
+ if (response.status === 429) throw new VoiceError("rateLimit");
74
+ if (response.status >= 500) throw new VoiceError("server", { status: response.status });
75
+ throw new VoiceError("failed", { status: response.status, detail: said });
76
+ }
77
+
78
+ // the voices the account can use, premade ones included, by name. → [{ id, name, note }]
79
+ export async function listVoices({ key, url, signal } = {}) {
80
+ const voices = [];
81
+ let token = null;
82
+ for (let page = 0; page < 5; page++) {
83
+ const query = new URLSearchParams({ page_size: "100", ...(token ? { next_page_token: token } : {}) });
84
+ const data = await (await call({ url }, key, `/v2/voices?${query}`, { signal })).json().catch(() => ({}));
85
+ for (const voice of Array.isArray(data.voices) ? data.voices : []) {
86
+ if (typeof voice?.voice_id !== "string" || !voice.voice_id) continue;
87
+ const labels = voice.labels && typeof voice.labels === "object" ? voice.labels : {};
88
+ const note = [labels.gender, labels.accent, labels.age].filter((v) => typeof v === "string" && v).join(", ");
89
+ voices.push({ id: voice.voice_id, name: typeof voice.name === "string" && voice.name.trim() ? voice.name.trim() : voice.voice_id, note });
90
+ }
91
+ if (!data.has_more || !data.next_page_token) break;
92
+ token = data.next_page_token;
93
+ }
94
+ const seen = new Set();
95
+ return voices.filter((voice) => !seen.has(voice.id) && seen.add(voice.id)).sort((a, b) => a.name.localeCompare(b.name));
96
+ }
97
+
98
+ // where a word's audio is kept: one file per voice, model, language and text
99
+ export const audioPath = (voice, text, lang) => join(AUDIO_DIR, `${createHash("sha256").update(JSON.stringify([voice.id, MODEL, codeOf(lang), text])).digest("hex").slice(0, 32)}.mp3`);
100
+
101
+ // The word as an mp3 file: the kept one, or a new one from ElevenLabs. → the file's path. `key`: null
102
+ // for only a kept one; left out, the saved one (or the environment's)
103
+ export async function speech(voice, text, lang, { key, signal, timeoutMs } = {}) {
104
+ const file = audioPath(voice, text, lang);
105
+ try {
106
+ if ((await stat(file)).size > 0) return file;
107
+ } catch {}
108
+ if (key === undefined) key = (await findVoiceKey())?.key ?? null;
109
+ const query = new URLSearchParams({ output_format: "mp3_44100_64" });
110
+ const response = await call(voice, key, `/v1/text-to-speech/${encodeURIComponent(voice.id)}?${query}`, { signal, timeoutMs, body: { text, model_id: MODEL, language_code: codeOf(lang) } });
111
+ let audio;
112
+ try {
113
+ audio = Buffer.from(await response.arrayBuffer());
114
+ } catch (err) {
115
+ if (signal?.aborted) throw err;
116
+ throw new VoiceError("offline");
117
+ }
118
+ if (!audio.length) throw new VoiceError("failed", { status: response.status, detail: t("voice.errors.empty") });
119
+ await mkdir(AUDIO_DIR, { recursive: true });
120
+ const tmp = `${file}.${randomUUID()}.tmp`; // the same word asked twice at once writes two files
121
+ try {
122
+ await writeFile(tmp, audio);
123
+ await rename(tmp, file);
124
+ } catch (err) {
125
+ await rm(tmp, { force: true }).catch(() => {});
126
+ throw err;
127
+ }
128
+ return file;
129
+ }
package/src/words.js CHANGED
@@ -11,15 +11,38 @@ export function missingDeck(library, deckRef) {
11
11
  return new Error(deckRef ? t("errors.noDeck", { deck: deckRef, decks: names || t("errors.noDecksYet") }) : t("errors.emptyLibrary"));
12
12
  }
13
13
 
14
+ // a deck as the quiz needs it: its name, languages, the one you're learning, which way it asks
15
+ function describe(library, deck, cards) {
16
+ // the tour is written in the UI's language on both sides: no pair to show or check by
17
+ const languages = deck.tour ? null : deckLanguages(deck, cards);
18
+ const home = homeLanguages({ others: library.decks.filter((d) => d !== deck && d.languages).map((d) => d.languages) });
19
+ return { name: deck.name, languages, learning: deck.tour ? null : learningSide(languages, deck, home), directions: deck.directions, tour: Boolean(deck.tour) };
20
+ }
21
+
22
+ const DIRECTION_KEYS = { forward: ["en-pl"], backward: ["pl-en"], both: ["en-pl", "pl-en"] };
23
+
24
+ // `deckRef` may also be several decks practised together (a list of names or ids) or "all" of yours:
25
+ // their cards mixed, each card carrying its own deck (`word.deck`) and the way that deck asks. Decks of
26
+ // the list that are gone are left out; with none left, it's your first deck again.
14
27
  export async function loadWords(deckRef) {
15
28
  const library = await loadLibrary();
29
+ if (deckRef === "all" || Array.isArray(deckRef)) {
30
+ const own = library.decks.filter((d) => !d.tour);
31
+ const decks = deckRef === "all" ? own : [...new Set(deckRef.map((ref) => findDeck(library, ref)).filter((d) => d && !d.tour))];
32
+ if (decks.length >= 2 || (deckRef === "all" && decks.length)) {
33
+ const words = decks.flatMap((deck) => {
34
+ const cards = cardsOf(library, deck.id);
35
+ const info = describe(library, deck, cards);
36
+ return toWords(cards).map((word) => ({ ...word, deck: info, directions: word.directions ?? DIRECTION_KEYS[deck.directions] ?? DIRECTION_KEYS.both }));
37
+ });
38
+ return { words, deck: { name: decks.map((d) => d.name).join(" + "), mixed: decks.map((d) => d.name), all: deckRef === "all", languages: null, learning: null, directions: "both", tour: false } };
39
+ }
40
+ return loadWords(decks[0]?.id);
41
+ }
16
42
  const deck = deckRef ? findDeck(library, deckRef) : (library.decks.find((d) => !d.tour) ?? library.decks[0]);
17
43
  if (!deck) throw missingDeck(library, deckRef);
18
44
  const cards = cardsOf(library, deck.id);
19
- // the tour is written in the UI's language on both sides: no pair to show or check by
20
- const languages = deck.tour ? null : deckLanguages(deck, cards);
21
- const home = homeLanguages({ others: library.decks.filter((d) => d !== deck && d.languages).map((d) => d.languages) });
22
- return { words: toWords(cards), deck: { name: deck.name, languages, learning: deck.tour ? null : learningSide(languages, deck, home), directions: deck.directions, tour: Boolean(deck.tour) } };
45
+ return { words: toWords(cards), deck: describe(library, deck, cards) };
23
46
  }
24
47
 
25
48
  // every deck of yours (not the tour), for "is anything still waiting today?"