dracosh 0.7.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
+ }