@joplo-app/server 0.2.9 → 0.2.12

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/dist/voice.js ADDED
@@ -0,0 +1,637 @@
1
+ /**
2
+ * 朗读(D74)的服务端:声音供应商 profile、合成请求、项目里的音频缓存、发布时带上音频。
3
+ *
4
+ * 数据流:
5
+ * - profile:看板「声音 → 管理供应商」→ PUT /__joplo/voice/profiles/:id → ProfileStore 写 `<JOPLO_HOME>/voice/profiles.json`(0600,含 Key)
6
+ * → GET 时 publicProfile 去掉 Key(只给是否已保存、末 4 位、可用的环境变量名)→ 看板列表与浮层。
7
+ * 预设(OpenAI / ElevenLabs / AiHubMix)不写文件也存在;改过的预设以覆盖的形式存,删除 = 恢复预设。
8
+ * - 选用:config({ voice: { profile } }) 优先;否则看板浮层里选的(PUT /__joplo/p/:id/voice → `<项目>/.joplo/voice/index.json` 的 profileId)。
9
+ * resolveVoices 算出旁白与各角色的音色和“声音指纹”(profile 的接口、地址、模型、音色、返回格式;不含 Key)。
10
+ * - 生成:看板按当前语言算出每一步的朗读文字与角色 → POST /__joplo/p/:id/voice/generate → 每段用 clipKey(指纹, 文字) 作键,
11
+ * 已有就跳过,否则 synthesize → 识别音频格式 → 写 `<项目>/.joplo/voice/clips/<sha256>.<ext>`,index.json 记 { 文件, 步骤, 指纹, 文字, 语言 };
12
+ * 失败记在 failures(看板显示原因,播放时这一步改用浏览器朗读)。进度用 HMR 自定义事件 joplo:voice 推给看板。
13
+ * - 播放:GET /__joplo/p/:id/voice → { voices(指纹), clips(键 → 音频地址)} → 网页 narrator 按同一个 clipKey 找音频,没有就用浏览器朗读。
14
+ * - 发布:bundleVoice(joplo build / share)把发布 IR 里步骤用到的、当前声音的音频拷进站点 `voice/`,写 IR 的 voiceIndex;Key 永远不进产物。
15
+ */
16
+ import crypto from 'node:crypto';
17
+ import fs from 'node:fs';
18
+ import path from 'node:path';
19
+ import { DEFAULT_STYLE, clipKey, speakerRoleAt, spokenLine, voiceFingerprint } from '@joplo-app/core';
20
+ export { DEFAULT_STYLE };
21
+ /** OpenAI 的内置音色都能读多种语言;marin / cedar 是官方推荐的高质量音色。 */
22
+ const OPENAI_VOICES = [
23
+ { id: 'marin', name: 'Marin', gender: 'female', recommended: true },
24
+ { id: 'cedar', name: 'Cedar', gender: 'male', recommended: true },
25
+ { id: 'coral', name: 'Coral', gender: 'female' },
26
+ { id: 'nova', name: 'Nova', gender: 'female' },
27
+ { id: 'shimmer', name: 'Shimmer', gender: 'female' },
28
+ { id: 'sage', name: 'Sage', gender: 'female' },
29
+ { id: 'alloy', name: 'Alloy', gender: 'neutral' },
30
+ { id: 'ash', name: 'Ash', gender: 'male' },
31
+ { id: 'ballad', name: 'Ballad', gender: 'male' },
32
+ { id: 'echo', name: 'Echo', gender: 'male' },
33
+ { id: 'fable', name: 'Fable', gender: 'male' },
34
+ { id: 'onyx', name: 'Onyx', gender: 'male' },
35
+ { id: 'verse', name: 'Verse', gender: 'male' },
36
+ ];
37
+ /** ElevenLabs 的默认音色(voice_id);配合 eleven_multilingual_v2 能读中文等多种语言,口音是音色本身的。 */
38
+ const ELEVENLABS_VOICES = [
39
+ { id: 'JBFqnCBsd6RMkjVDRZzb', name: 'George', gender: 'male', accent: 'en-GB', recommended: true },
40
+ { id: 'EXAVITQu4vr4xnSDxMaL', name: 'Sarah', gender: 'female', accent: 'en-US', recommended: true },
41
+ { id: 'Xb7hH8MSUJpSbSDYk0k2', name: 'Alice', gender: 'female', accent: 'en-GB' },
42
+ { id: 'XrExE9yKIg1WjnnlVkGX', name: 'Matilda', gender: 'female', accent: 'en-US' },
43
+ { id: 'cgSgspJ2msm6clMCkdW9', name: 'Jessica', gender: 'female', accent: 'en-US' },
44
+ { id: 'pFZP5JQG7iQjIQuC4Bku', name: 'Lily', gender: 'female', accent: 'en-GB' },
45
+ { id: 'XB0fDUnXU5powFXDhCwa', name: 'Charlotte', gender: 'female', accent: 'sv-SE' },
46
+ { id: 'nPczCjzI2devNBz1zQrb', name: 'Brian', gender: 'male', accent: 'en-US' },
47
+ { id: 'onwK4e9ZLuTAKqWW03F9', name: 'Daniel', gender: 'male', accent: 'en-GB' },
48
+ { id: 'TX3LPaxmHKxFdv7VOQHJ', name: 'Liam', gender: 'male', accent: 'en-US' },
49
+ { id: 'cjVigY5qzO86Huf0OWal', name: 'Eric', gender: 'male', accent: 'en-US' },
50
+ { id: 'IKne3meq5aSn9XLyUdCD', name: 'Charlie', gender: 'male', accent: 'en-AU' },
51
+ ];
52
+ export const PRESETS = [
53
+ { id: 'openai', preset: 'openai', name: 'OpenAI', kind: 'openai', baseUrl: 'https://api.openai.com/v1', model: 'gpt-4o-mini-tts', voice: 'marin', response: 'audio', style: DEFAULT_STYLE, env: 'OPENAI_API_KEY', voices: OPENAI_VOICES },
54
+ // voice_id 是 ElevenLabs 文档示例里的 George;多语言模型能读中文
55
+ { id: 'elevenlabs', preset: 'elevenlabs', name: 'ElevenLabs', kind: 'elevenlabs', baseUrl: 'https://api.elevenlabs.io/v1', model: 'eleven_multilingual_v2', voice: 'JBFqnCBsd6RMkjVDRZzb', response: 'audio', env: 'ELEVENLABS_API_KEY', voices: ELEVENLABS_VOICES },
56
+ { id: 'aihubmix', preset: 'aihubmix', name: 'AiHubMix', kind: 'openai', baseUrl: 'https://aihubmix.com/v1', model: 'gpt-4o-mini-tts', voice: 'marin', response: 'audio', style: DEFAULT_STYLE, env: 'AIHUBMIX_API_KEY', voices: OPENAI_VOICES },
57
+ ];
58
+ const presetOf = (id) => PRESETS.find((p) => p.id === id);
59
+ export class VoiceError extends Error {
60
+ code;
61
+ hint;
62
+ constructor(code, message, hint) {
63
+ super(message);
64
+ this.code = code;
65
+ this.hint = hint;
66
+ }
67
+ }
68
+ const ID_RE = /^[a-z0-9][a-z0-9_-]{0,39}$/;
69
+ const str = (v, max) => (typeof v === 'string' && v.trim() && v.length <= max ? v.trim() : null);
70
+ const isHttpUrl = (v) => {
71
+ try {
72
+ const u = new URL(v);
73
+ return u.protocol === 'https:' || u.protocol === 'http:';
74
+ }
75
+ catch {
76
+ return false;
77
+ }
78
+ };
79
+ /** 校验看板提交的 profile(不含 id / key)。返回规整后的字段,或抛 VoiceError('INVALID')。 */
80
+ export function normalizeProfile(input, base) {
81
+ const o = (input && typeof input === 'object' ? input : {});
82
+ const kind = base?.preset ? base.kind : o.kind === 'openai' || o.kind === 'elevenlabs' || o.kind === 'http' ? o.kind : null;
83
+ if (!kind)
84
+ throw new VoiceError('INVALID', 'kind must be openai, elevenlabs or http');
85
+ const name = str(o.name, 60);
86
+ if (!name)
87
+ throw new VoiceError('INVALID', 'Name is required (up to 60 characters)');
88
+ const baseUrl = str(o.baseUrl, 500)?.replace(/\/+$/, '');
89
+ if (!baseUrl || !isHttpUrl(baseUrl))
90
+ throw new VoiceError('INVALID', 'Base URL must start with https:// or http://');
91
+ const model = str(o.model, 200) ?? '';
92
+ const voice = str(o.voice, 200) ?? '';
93
+ if (kind !== 'http' && !voice)
94
+ throw new VoiceError('INVALID', 'Default voice is required');
95
+ const response = o.response === 'json-base64' || o.response === 'json-url' ? o.response : 'audio';
96
+ const p = response === 'audio' ? undefined : str(o.path, 200);
97
+ if (response !== 'audio' && (!p || !/^[\w$-]+(\.[\w$-]+)*$/.test(p)))
98
+ throw new VoiceError('INVALID', 'Audio field path is required for JSON responses, for example data.audio');
99
+ let headers;
100
+ if (o.headers !== undefined && o.headers !== null) {
101
+ if (typeof o.headers !== 'object' || Array.isArray(o.headers))
102
+ throw new VoiceError('INVALID', 'headers must be an object of strings');
103
+ const entries = Object.entries(o.headers);
104
+ if (entries.length > 20)
105
+ throw new VoiceError('INVALID', 'At most 20 headers');
106
+ headers = {};
107
+ for (const [k, v] of entries) {
108
+ if (!/^[A-Za-z0-9-]{1,100}$/.test(k) || typeof v !== 'string' || v.length > 2000 || /[\r\n]/.test(v))
109
+ throw new VoiceError('INVALID', `Invalid header: ${k}`);
110
+ headers[k] = v;
111
+ }
112
+ if (!Object.keys(headers).length)
113
+ headers = undefined;
114
+ }
115
+ let body;
116
+ if (kind === 'http') {
117
+ body = str(o.body, 4000) ?? undefined;
118
+ if (!body || !body.includes('{{text}}'))
119
+ throw new VoiceError('INVALID', 'The request body template must contain {{text}}');
120
+ try {
121
+ JSON.parse(fillTemplate(body, { text: 't', voice: 'v', model: 'm' }));
122
+ }
123
+ catch {
124
+ throw new VoiceError('INVALID', 'The request body template is not valid JSON once {{text}} {{voice}} {{model}} are filled in');
125
+ }
126
+ }
127
+ const style = kind === 'openai' && o.style !== undefined && o.style !== null ? (typeof o.style === 'string' && o.style.length <= 1000 ? o.style.trim() : (() => { throw new VoiceError('INVALID', 'Speaking style is up to 1000 characters'); })()) : undefined;
128
+ return { name, kind, baseUrl, model, voice, response, ...(p ? { path: p } : {}), ...(headers ? { headers } : {}), ...(body ? { body } : {}), ...(style ? { style } : {}) };
129
+ }
130
+ /** `<JOPLO_HOME>/voice/profiles.json`:自建的 profile 与改过的预设(含 Key),权限 0600。 */
131
+ export class ProfileStore {
132
+ env;
133
+ file;
134
+ constructor(home, env = process.env) {
135
+ this.env = env;
136
+ this.file = path.join(home, 'voice', 'profiles.json');
137
+ }
138
+ read() {
139
+ try {
140
+ const raw = JSON.parse(fs.readFileSync(this.file, 'utf8'));
141
+ return Array.isArray(raw?.profiles) ? raw.profiles.filter((p) => p && typeof p.id === 'string' && ID_RE.test(p.id) && typeof p.name === 'string') : [];
142
+ }
143
+ catch {
144
+ return [];
145
+ }
146
+ }
147
+ write(list) {
148
+ fs.mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 });
149
+ const tmp = `${this.file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
150
+ fs.writeFileSync(tmp, JSON.stringify({ version: 1, profiles: list }, null, 2), { mode: 0o600 });
151
+ fs.chmodSync(tmp, 0o600);
152
+ fs.renameSync(tmp, this.file);
153
+ }
154
+ /** 预设(合并本机覆盖)在前,自建的在后。 */
155
+ list() {
156
+ const stored = this.read();
157
+ const presets = PRESETS.map(({ env: _e, voices: _v, ...p }) => ({ ...p, ...(stored.find((s) => s.id === p.id) ?? {}), id: p.id, preset: p.id, kind: p.kind }));
158
+ return [...presets, ...stored.filter((s) => !presetOf(s.id))];
159
+ }
160
+ get(id) {
161
+ return this.list().find((p) => p.id === id) ?? null;
162
+ }
163
+ /** 按 id 或名字(不区分大小写)找,config({ voice: { profile } }) 用。 */
164
+ find(ref) {
165
+ const r = ref.trim().toLowerCase();
166
+ return this.list().find((p) => p.id === r || p.name.toLowerCase() === r) ?? null;
167
+ }
168
+ /** Key:保存的优先,其次是预设对应的环境变量。 */
169
+ keyOf(p) {
170
+ if (p.key)
171
+ return p.key;
172
+ const env = presetOf(p.preset)?.env;
173
+ const v = env ? this.env[env] : undefined;
174
+ return v && v.trim() ? v.trim() : null;
175
+ }
176
+ /**
177
+ * 新建或修改。id 为 null 时新建(id 由名字生成)。key:undefined = 不改;null 或 '' = 删掉保存的 Key;字符串 = 保存。
178
+ */
179
+ upsert(id, input, key) {
180
+ const list = this.read();
181
+ const current = id ? this.get(id) : null;
182
+ if (id && !current)
183
+ throw new VoiceError('NOT_FOUND', `Unknown voice profile: ${id}`);
184
+ const fields = normalizeProfile(input, current ?? undefined);
185
+ let nextId = id;
186
+ if (!nextId) {
187
+ const slug = fields.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 24) || 'voice';
188
+ nextId = slug;
189
+ for (let i = 2; this.get(nextId) || presetOf(nextId); i++)
190
+ nextId = `${slug}-${i}`;
191
+ }
192
+ if (key !== undefined && key !== null && (typeof key !== 'string' || key.length > 500 || /[\r\n]/.test(key)))
193
+ throw new VoiceError('INVALID', 'Invalid API key');
194
+ const keep = list.find((p) => p.id === nextId)?.key;
195
+ const nextKey = key === undefined ? keep : key && key.trim() ? key.trim() : undefined;
196
+ const next = { id: nextId, ...fields, ...(presetOf(nextId) ? { preset: nextId } : {}), ...(nextKey ? { key: nextKey } : {}) };
197
+ this.write([...list.filter((p) => p.id !== nextId), next]);
198
+ return next;
199
+ }
200
+ /** 自建的删除;预设恢复默认(去掉本机覆盖,包括保存的 Key)。 */
201
+ remove(id) {
202
+ const list = this.read();
203
+ if (!presetOf(id) && !list.some((p) => p.id === id))
204
+ throw new VoiceError('NOT_FOUND', `Unknown voice profile: ${id}`);
205
+ this.write(list.filter((p) => p.id !== id));
206
+ }
207
+ publicOf(p) {
208
+ const { key: _k, ...rest } = p;
209
+ const preset = presetOf(p.preset);
210
+ const env = preset?.env ?? null;
211
+ return { ...rest, key: { saved: !!p.key, hint: p.key ? `…${p.key.slice(-4)}` : null, env, envSet: !!(env && this.env[env]?.trim()) }, voices: preset?.voices ?? (p.kind === 'openai' ? OPENAI_VOICES : p.kind === 'elevenlabs' ? ELEVENLABS_VOICES : []), removable: !preset };
212
+ }
213
+ }
214
+ // ---------- 合成 ----------
215
+ const MAX_AUDIO = 20 * 1024 * 1024;
216
+ const TIMEOUT_MS = 60_000;
217
+ /** JSON 字符串转义后替换 {{text}} {{voice}} {{model}}(模板本身是 JSON,值放在引号里)。 */
218
+ export function fillTemplate(tpl, v) {
219
+ const esc = (s) => JSON.stringify(s).slice(1, -1);
220
+ return tpl.replace(/\{\{\s*(text|voice|model|key)\s*\}\}/g, (_m, k) => esc(v[k] ?? ''));
221
+ }
222
+ /** 发给模型的说话风格:只有 OpenAI 兼容接口、且不是 tts-1 系列(不支持 instructions)时才发。 */
223
+ export const styleOf = (p) => (p.kind === 'openai' && p.style?.trim() && !/^tts-1/i.test(p.model) ? p.style.trim() : null);
224
+ /** 这次合成的 HTTP 请求(不发出)。 */
225
+ export function buildRequest(p, key, text, voice) {
226
+ const headerVals = (h) => Object.fromEntries(Object.entries(h).map(([k, v]) => [k, v.replace(/\{\{\s*key\s*\}\}/g, key ?? '')]));
227
+ if (p.kind === 'elevenlabs') {
228
+ if (!key)
229
+ throw new VoiceError('NO_KEY', 'No API key for this provider');
230
+ const url = `${p.baseUrl}/text-to-speech/${encodeURIComponent(voice)}?output_format=mp3_44100_128`;
231
+ return { url, init: { method: 'POST', headers: { 'content-type': 'application/json', accept: 'audio/mpeg', 'xi-api-key': key, ...headerVals(p.headers ?? {}) }, body: JSON.stringify({ text, ...(p.model ? { model_id: p.model } : {}) }) } };
232
+ }
233
+ if (p.kind === 'openai') {
234
+ if (!key)
235
+ throw new VoiceError('NO_KEY', 'No API key for this provider');
236
+ return {
237
+ url: `${p.baseUrl}/audio/speech`,
238
+ init: { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${key}`, ...headerVals(p.headers ?? {}) }, body: JSON.stringify({ model: p.model, input: text, voice, response_format: 'mp3', ...(styleOf(p) ? { instructions: styleOf(p) } : {}) }) },
239
+ };
240
+ }
241
+ const headers = p.headers ? headerVals(p.headers) : key ? { authorization: `Bearer ${key}` } : {};
242
+ return { url: p.baseUrl, init: { method: 'POST', headers: { 'content-type': 'application/json', ...headers }, body: fillTemplate(p.body ?? '{"input":"{{text}}"}', { text, voice, model: p.model, key: key ?? '' }) } };
243
+ }
244
+ export const AUDIO_TYPES = { mp3: 'audio/mpeg', wav: 'audio/wav', ogg: 'audio/ogg', flac: 'audio/flac', m4a: 'audio/mp4', aac: 'audio/aac' };
245
+ /** 按文件头识别音频格式;不是音频返回 null。 */
246
+ export function sniffAudio(b) {
247
+ const at = (i, s) => [...s].every((c, j) => b[i + j] === c.charCodeAt(0));
248
+ const t = (ext) => ({ ext, contentType: AUDIO_TYPES[ext] });
249
+ if (b.length < 12)
250
+ return null;
251
+ if (at(0, 'ID3'))
252
+ return t('mp3');
253
+ if (at(0, 'RIFF') && at(8, 'WAVE'))
254
+ return t('wav');
255
+ if (at(0, 'OggS'))
256
+ return t('ogg');
257
+ if (at(0, 'fLaC'))
258
+ return t('flac');
259
+ if (at(4, 'ftyp'))
260
+ return t('m4a');
261
+ if (b[0] === 0xff && (b[1] & 0xf6) === 0xf0)
262
+ return t('aac'); // ADTS
263
+ if (b[0] === 0xff && (b[1] & 0xe0) === 0xe0)
264
+ return t('mp3'); // MPEG 帧同步
265
+ return null;
266
+ }
267
+ /** 按 a.b.0.c 取值。 */
268
+ export function getPath(v, p) {
269
+ let cur = v;
270
+ for (const seg of p.split('.')) {
271
+ if (cur === null || cur === undefined)
272
+ return undefined;
273
+ cur = Array.isArray(cur) && /^\d+$/.test(seg) ? cur[Number(seg)] : typeof cur === 'object' ? cur[seg] : undefined;
274
+ }
275
+ return cur;
276
+ }
277
+ const B64_RE = /^(data:audio\/[\w.+-]+;base64,)?[A-Za-z0-9+/=\r\n_-]+$/;
278
+ const decodeB64 = (s) => Buffer.from(s.replace(/^data:[^,]*,/, '').replace(/[\r\n]/g, '').replace(/-/g, '+').replace(/_/g, '/'), 'base64');
279
+ /** 返回的是 JSON 时,找出像音频的字段,给出“返回内容 + 字段路径”的建议。 */
280
+ export function suggestFromJson(v) {
281
+ const seen = [];
282
+ const walk = (x, p, depth) => {
283
+ if (depth > 6 || seen.length)
284
+ return;
285
+ if (typeof x === 'string') {
286
+ if (x.length >= 64 && B64_RE.test(x) && sniffAudio(decodeB64(x.slice(0, 4096 - (4096 % 4)))))
287
+ seen.push({ response: 'json-base64', path: p.join('.') });
288
+ else if (/^https?:\/\/\S+$/.test(x) && (/\.(mp3|wav|ogg|m4a|aac|flac|opus)(\?|$)/i.test(x) || /audio/i.test(p.join('.'))))
289
+ seen.push({ response: 'json-url', path: p.join('.') });
290
+ return;
291
+ }
292
+ if (Array.isArray(x))
293
+ x.slice(0, 20).forEach((y, i) => walk(y, [...p, String(i)], depth + 1));
294
+ else if (x && typeof x === 'object')
295
+ for (const [k, y] of Object.entries(x))
296
+ walk(y, [...p, k], depth + 1);
297
+ };
298
+ walk(v, [], 0);
299
+ return seen[0] ?? null;
300
+ }
301
+ const clip = (s, n) => (s.length > n ? `${s.slice(0, n)}…` : s);
302
+ /** 错误信息里去掉 Key,截断。 */
303
+ const scrub = (s, key) => clip(key ? s.split(key).join('••••') : s, 300).replace(/\s+/g, ' ').trim();
304
+ async function readLimited(res) {
305
+ const len = Number(res.headers.get('content-length') ?? 0);
306
+ if (len > MAX_AUDIO)
307
+ throw new VoiceError('TOO_LARGE', `The response is larger than ${MAX_AUDIO / 1024 / 1024} MB`);
308
+ const buf = Buffer.from(await res.arrayBuffer());
309
+ if (buf.length > MAX_AUDIO)
310
+ throw new VoiceError('TOO_LARGE', `The response is larger than ${MAX_AUDIO / 1024 / 1024} MB`);
311
+ return buf;
312
+ }
313
+ /** 合成一段:返回音频字节与格式。失败抛 VoiceError(信息里不含 Key)。 */
314
+ export async function synthesize(p, key, text, voice, opts = {}) {
315
+ const f = opts.fetch ?? ((u, i) => fetch(u, i));
316
+ const { url, init } = buildRequest(p, key, text, voice);
317
+ const signal = opts.signal ? AbortSignal.any([opts.signal, AbortSignal.timeout(TIMEOUT_MS)]) : AbortSignal.timeout(TIMEOUT_MS);
318
+ let res;
319
+ try {
320
+ res = await f(url, { ...init, signal, redirect: 'follow' });
321
+ }
322
+ catch (e) {
323
+ const timeout = e instanceof Error && (e.name === 'TimeoutError' || e.name === 'AbortError');
324
+ throw new VoiceError('NETWORK', timeout ? `No response from ${new URL(url).host} within ${TIMEOUT_MS / 1000} s` : `Could not reach ${new URL(url).host}: ${scrub(e instanceof Error ? e.message : String(e), key)}`);
325
+ }
326
+ const bytes = await readLimited(res);
327
+ const ct = res.headers.get('content-type') ?? '';
328
+ if (!res.ok) {
329
+ const body = scrub(bytes.toString('utf8'), key);
330
+ throw new VoiceError('HTTP', `HTTP ${res.status}${body ? `: ${body}` : ''}`);
331
+ }
332
+ if (p.response === 'audio') {
333
+ const t = sniffAudio(bytes);
334
+ if (t)
335
+ return { bytes, ...t };
336
+ let hint = null;
337
+ if (/json/i.test(ct) || /^\s*[{[]/.test(bytes.subarray(0, 16).toString('utf8'))) {
338
+ try {
339
+ hint = suggestFromJson(JSON.parse(bytes.toString('utf8')));
340
+ }
341
+ catch {
342
+ /* 不是 JSON */
343
+ }
344
+ }
345
+ throw new VoiceError('NOT_AUDIO', `The response is not audio (${ct || 'no content type'}): ${scrub(bytes.subarray(0, 200).toString('utf8'), key)}`, hint ?? undefined);
346
+ }
347
+ let json;
348
+ try {
349
+ json = JSON.parse(bytes.toString('utf8'));
350
+ }
351
+ catch {
352
+ const t = sniffAudio(bytes);
353
+ throw new VoiceError('BAD_RESPONSE', t ? 'The response is an audio file, not JSON' : `The response is not JSON (${ct || 'no content type'})`, t ? { response: 'audio', path: '' } : undefined);
354
+ }
355
+ const v = getPath(json, p.path ?? '');
356
+ if (typeof v !== 'string' || !v) {
357
+ throw new VoiceError('BAD_RESPONSE', `No text at "${p.path}" in the JSON response: ${scrub(JSON.stringify(json), key)}`, suggestFromJson(json) ?? undefined);
358
+ }
359
+ if (p.response === 'json-base64') {
360
+ const audio = decodeB64(v);
361
+ const t = sniffAudio(audio);
362
+ if (!t)
363
+ throw new VoiceError('NOT_AUDIO', `"${p.path}" is not base64 audio`, suggestFromJson(json) ?? undefined);
364
+ if (audio.length > MAX_AUDIO)
365
+ throw new VoiceError('TOO_LARGE', `The audio is larger than ${MAX_AUDIO / 1024 / 1024} MB`);
366
+ return { bytes: audio, ...t };
367
+ }
368
+ if (!isHttpUrl(v))
369
+ throw new VoiceError('BAD_RESPONSE', `"${p.path}" is not an http(s) link`, suggestFromJson(json) ?? undefined);
370
+ let dl;
371
+ try {
372
+ dl = await f(v, { signal, redirect: 'follow' });
373
+ }
374
+ catch (e) {
375
+ throw new VoiceError('NETWORK', `Could not download the audio: ${scrub(e instanceof Error ? e.message : String(e), key)}`);
376
+ }
377
+ const audio = await readLimited(dl);
378
+ if (!dl.ok)
379
+ throw new VoiceError('HTTP', `Downloading the audio failed: HTTP ${dl.status}`);
380
+ const t = sniffAudio(audio);
381
+ if (!t)
382
+ throw new VoiceError('NOT_AUDIO', `The link in "${p.path}" did not return audio`);
383
+ return { bytes: audio, ...t };
384
+ }
385
+ // ---------- 声音指纹与选用 ----------
386
+ /** 声音指纹:接口、地址、模型、音色、返回格式、请求体模板、说话风格(不含 Key 与请求头)。 */
387
+ export function fingerprint(p, voice) {
388
+ return crypto.createHash('sha256').update(JSON.stringify([p.kind, p.baseUrl, p.model, voice, p.response, p.path ?? '', p.body ?? '', styleOf(p) ?? ''])).digest('hex').slice(0, 16);
389
+ }
390
+ export function resolveVoices(config, selected, store) {
391
+ let profile = null;
392
+ let source = null;
393
+ let missing = null;
394
+ if (config?.profile) {
395
+ profile = store.find(config.profile);
396
+ if (profile)
397
+ source = 'config';
398
+ else
399
+ missing = config.profile;
400
+ }
401
+ else if (selected) {
402
+ profile = store.get(selected);
403
+ if (profile)
404
+ source = 'board';
405
+ }
406
+ if (!profile)
407
+ return { profile: null, source, missing, narrator: null, roles: {}, voices: { narrator: null, roles: {} } };
408
+ const narrator = config?.narrator ?? profile.voice;
409
+ const roles = { ...(config?.roles ?? {}) };
410
+ return {
411
+ profile,
412
+ source,
413
+ missing,
414
+ narrator,
415
+ roles,
416
+ voices: { narrator: fingerprint(profile, narrator), roles: Object.fromEntries(Object.entries(roles).map(([r, v]) => [r, fingerprint(profile, v)])) },
417
+ };
418
+ }
419
+ const FILE_RE = /^[0-9a-f]{64}\.(mp3|wav|ogg|flac|m4a|aac)$/;
420
+ /** `<项目>/.joplo/voice/`:index.json(选用的 profile、片段、失败)与 clips/。 */
421
+ export class VoiceCache {
422
+ projectDir;
423
+ root;
424
+ constructor(projectDir) {
425
+ this.projectDir = projectDir;
426
+ this.root = path.join(projectDir, '.joplo', 'voice');
427
+ }
428
+ get clipsDir() {
429
+ return path.join(this.root, 'clips');
430
+ }
431
+ read() {
432
+ try {
433
+ const raw = JSON.parse(fs.readFileSync(path.join(this.root, 'index.json'), 'utf8'));
434
+ return { version: 1, profileId: typeof raw.profileId === 'string' ? raw.profileId : null, clips: raw.clips && typeof raw.clips === 'object' ? raw.clips : {}, failures: raw.failures && typeof raw.failures === 'object' ? raw.failures : {} };
435
+ }
436
+ catch {
437
+ return { version: 1, profileId: null, clips: {}, failures: {} };
438
+ }
439
+ }
440
+ write(idx) {
441
+ fs.mkdirSync(this.root, { recursive: true });
442
+ const file = path.join(this.root, 'index.json');
443
+ const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
444
+ fs.writeFileSync(tmp, JSON.stringify(idx, null, 2));
445
+ fs.renameSync(tmp, file);
446
+ }
447
+ select(profileId) {
448
+ this.write({ ...this.read(), profileId });
449
+ }
450
+ /** 片段文件的绝对路径(文件名不合法或不存在时为 null)。 */
451
+ fileOf(name) {
452
+ if (!FILE_RE.test(name))
453
+ return null;
454
+ const f = path.join(this.clipsDir, name);
455
+ return fs.existsSync(f) ? f : null;
456
+ }
457
+ /** 当前声音下已有的片段:键 → 文件名;以及失败的键 → 原因。 */
458
+ current(voices) {
459
+ const fps = new Set([voices.narrator, ...Object.values(voices.roles)].filter(Boolean));
460
+ const idx = this.read();
461
+ const clips = {};
462
+ for (const [k, c] of Object.entries(idx.clips))
463
+ if (fps.has(c.fp) && FILE_RE.test(c.file) && fs.existsSync(path.join(this.clipsDir, c.file)))
464
+ clips[k] = c.file;
465
+ const failures = Object.fromEntries(Object.entries(idx.failures).filter(([k]) => !clips[k]).map(([k, v]) => [k, { stepId: v.stepId, message: v.message }]));
466
+ return { clips, failures };
467
+ }
468
+ /**
469
+ * 生成缺的片段(已有的跳过),并发 2。每段完成后调 onProgress。失败记进 failures,成功时清掉这个键的失败。
470
+ */
471
+ /** 记一段成功:重新读索引再写(看板的批量生成与边放边生成可能同时进行,不能互相覆盖)。 */
472
+ record(k, rec) {
473
+ const idx = this.read();
474
+ idx.clips[k] = rec;
475
+ delete idx.failures[k];
476
+ this.write(idx);
477
+ }
478
+ /** 记一段失败;这一段已经有音频(别的请求先成功了)时不记。 */
479
+ recordFailure(k, stepId, message) {
480
+ if (this.clipOf(k))
481
+ return;
482
+ const idx = this.read();
483
+ idx.failures[k] = { stepId, message, at: new Date().toISOString() };
484
+ this.write(idx);
485
+ }
486
+ /** 这一段的键与要用的音色;文字为空或没有供应商时为 null。 */
487
+ plan(seg, resolved) {
488
+ const p = resolved.profile;
489
+ const text = seg.text.replace(/\s+/g, ' ').trim();
490
+ if (!p || !text)
491
+ return null;
492
+ const voice = (seg.role ? resolved.roles[seg.role] : undefined) ?? resolved.narrator ?? p.voice;
493
+ const fp = voiceFingerprint(resolved.voices, seg.role);
494
+ return { key: clipKey(fp, text), text, voice, fp };
495
+ }
496
+ /** 已有的片段文件名(文件还在时)。 */
497
+ clipOf(key) {
498
+ const c = this.read().clips[key];
499
+ return c && FILE_RE.test(c.file) && fs.existsSync(path.join(this.clipsDir, c.file)) ? c.file : null;
500
+ }
501
+ /**
502
+ * 生成一段(已有就直接返回):返回文件名;失败记进 failures 并抛 VoiceError。
503
+ * inflight:同一个项目共用的“正在生成”表(片段键 → 结果)。批量生成与边放边生成传同一张表,同一段同时只请求一次,后来的等先来的结果(generated 为 false)。
504
+ */
505
+ async generateOne(seg, locale, resolved, store, opts = {}) {
506
+ const p = resolved.profile;
507
+ const j = this.plan(seg, resolved);
508
+ if (!p || !j)
509
+ throw new VoiceError('INVALID', 'No voice provider is selected for this project, or the text is empty');
510
+ const have = this.clipOf(j.key);
511
+ if (have)
512
+ return { key: j.key, file: have, generated: false };
513
+ const running = opts.inflight?.get(j.key);
514
+ if (running)
515
+ return { ...(await running), generated: false };
516
+ const run = this.synthesizeOne(seg, locale, p, j, store, opts);
517
+ opts.inflight?.set(j.key, run);
518
+ try {
519
+ return await run;
520
+ }
521
+ finally {
522
+ if (opts.inflight?.get(j.key) === run)
523
+ opts.inflight.delete(j.key);
524
+ }
525
+ }
526
+ async synthesizeOne(seg, locale, p, j, store, opts) {
527
+ const key = store.keyOf(p);
528
+ try {
529
+ if (!key && p.kind !== 'http')
530
+ throw new VoiceError('NO_KEY', 'No API key for this provider');
531
+ const a = await synthesize(p, key, j.text, j.voice, opts);
532
+ const file = `${crypto.createHash('sha256').update(a.bytes).digest('hex')}.${a.ext}`;
533
+ fs.mkdirSync(this.clipsDir, { recursive: true });
534
+ const dest = path.join(this.clipsDir, file);
535
+ if (!fs.existsSync(dest))
536
+ fs.writeFileSync(dest, a.bytes);
537
+ this.record(j.key, { file, stepId: seg.stepId, fp: j.fp, text: j.text, locale, bytes: a.bytes.length, at: new Date().toISOString() });
538
+ return { key: j.key, file, generated: true };
539
+ }
540
+ catch (e) {
541
+ this.recordFailure(j.key, seg.stepId, e instanceof Error ? e.message : String(e));
542
+ throw e;
543
+ }
544
+ }
545
+ /**
546
+ * 生成缺的片段(已有的跳过),并发 2。每段完成后调 onProgress。失败记进 failures,成功时清掉这个键的失败。
547
+ */
548
+ async generate(segments, locale, resolved, store, opts = {}) {
549
+ if (!resolved.profile)
550
+ return { total: segments.length, generated: 0, skipped: 0, failed: [], noProfile: true };
551
+ const jobs = new Map();
552
+ for (const s of segments) {
553
+ const j = this.plan(s, resolved);
554
+ if (j)
555
+ jobs.set(j.key, s);
556
+ }
557
+ const todo = [...jobs.entries()].filter(([k]) => !this.clipOf(k));
558
+ const summary = { total: jobs.size, generated: 0, skipped: jobs.size - todo.length, failed: [] };
559
+ let done = summary.skipped;
560
+ opts.onProgress?.(done, summary.total, 0);
561
+ let next = 0;
562
+ const worker = async () => {
563
+ while (next < todo.length) {
564
+ if (opts.signal?.aborted)
565
+ return;
566
+ const [, seg] = todo[next++];
567
+ try {
568
+ const r = await this.generateOne(seg, locale, resolved, store, opts);
569
+ if (r.generated)
570
+ summary.generated++;
571
+ else
572
+ summary.skipped++;
573
+ }
574
+ catch (e) {
575
+ summary.failed.push({ stepId: seg.stepId, message: e instanceof Error ? e.message : String(e) });
576
+ }
577
+ done++;
578
+ opts.onProgress?.(done, summary.total, summary.failed.length);
579
+ }
580
+ };
581
+ await Promise.all([worker(), worker()]);
582
+ return summary;
583
+ }
584
+ }
585
+ /**
586
+ * 发布(joplo build / share):把发布 IR 里步骤用到的、当前声音的音频拷进 `<outDir>/voice/`,返回 IR 的 voiceIndex。
587
+ * 同一步同一声音同一语言只留最新的一段(改过字之后旧的不再带上)。
588
+ * missing:当前声音下还没有音频的步骤数(文字与语言无关的步骤按键判断;自动字幕的步骤只要有任意语言的音频就算有)。
589
+ * 没有选用 profile 时不带任何音频(观众端用浏览器朗读)。
590
+ */
591
+ export function bundleVoice(projectDir, project, outDir, store, devConfig) {
592
+ const cache = new VoiceCache(projectDir);
593
+ const idx = cache.read();
594
+ const resolved = resolveVoices(devConfig ?? project.voiceConfig, idx.profileId, store);
595
+ const empty = { index: null, report: { clips: 0, bytes: 0, missing: 0, profile: resolved.profile?.name ?? null } };
596
+ if (!resolved.profile)
597
+ return empty;
598
+ const fps = new Set([resolved.voices.narrator, ...Object.values(resolved.voices.roles)].filter(Boolean));
599
+ const stepIds = new Set(Object.values(project.scenarios).flatMap((s) => s.steps.map((st) => st.id)));
600
+ const latest = new Map();
601
+ for (const [k, c] of Object.entries(idx.clips)) {
602
+ if (!stepIds.has(c.stepId) || !fps.has(c.fp) || !FILE_RE.test(c.file) || !fs.existsSync(path.join(cache.clipsDir, c.file)))
603
+ continue;
604
+ const g = `${c.stepId}|${c.fp}|${c.locale}`;
605
+ const prev = latest.get(g);
606
+ if (!prev || prev[1].at < c.at)
607
+ latest.set(g, [k, c]);
608
+ }
609
+ const clips = {};
610
+ let bytes = 0;
611
+ if (latest.size)
612
+ fs.mkdirSync(path.join(outDir, 'voice'), { recursive: true });
613
+ for (const [k, c] of latest.values()) {
614
+ const dest = path.join(outDir, 'voice', c.file);
615
+ if (!fs.existsSync(dest)) {
616
+ fs.copyFileSync(path.join(cache.clipsDir, c.file), dest);
617
+ bytes += c.bytes;
618
+ }
619
+ clips[k] = `voice/${c.file}`;
620
+ }
621
+ let missing = 0;
622
+ for (const sc of Object.values(project.scenarios))
623
+ sc.steps.forEach((st, i) => {
624
+ const line = spokenLine(st, st.caption, speakerRoleAt(project, sc.id, i + 1));
625
+ const fp = voiceFingerprint(resolved.voices, line.role);
626
+ if (!fp || !line.text)
627
+ return;
628
+ // 自动字幕在网页里按观众语言生成:这一步有任意语言的音频就算有
629
+ const localized = !!st.captionAuto && !st.say && !st.narrate && st.action.type !== 'card';
630
+ const ok = localized ? [...latest.values()].some(([, c]) => c.stepId === st.id && c.fp === fp) : !!clips[clipKey(fp, line.text)];
631
+ if (!ok)
632
+ missing++;
633
+ });
634
+ if (!Object.keys(clips).length)
635
+ return { index: null, report: { ...empty.report, missing } };
636
+ return { index: { narrator: resolved.voices.narrator, roles: resolved.voices.roles, clips }, report: { clips: Object.keys(clips).length, bytes, missing, profile: resolved.profile.name } };
637
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joplo-app/server",
3
- "version": "0.2.9",
3
+ "version": "0.2.12",
4
4
  "description": "Joplo 本地服务:dev 看板、build 发布站、render 截图",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -15,9 +15,9 @@
15
15
  "dist"
16
16
  ],
17
17
  "dependencies": {
18
- "@joplo-app/core": "0.2.9",
19
- "@joplo-app/kit": "0.2.9",
20
- "@joplo-app/web": "0.2.9",
18
+ "@joplo-app/core": "0.2.12",
19
+ "@joplo-app/kit": "0.2.12",
20
+ "@joplo-app/web": "0.2.12",
21
21
  "@tailwindcss/vite": "4.3.4",
22
22
  "tailwindcss": "4.3.4",
23
23
  "vite": "8.3.5",