@joplo-app/server 0.2.17 → 0.3.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/dist/voice.js CHANGED
@@ -1,22 +1,30 @@
1
1
  /**
2
- * 朗读(D74)的服务端:声音供应商 profile、合成请求、项目里的音频缓存、发布时带上音频。
2
+ * 朗读(D74 / D85)的服务端:声音来源、合成请求、项目里的音频缓存、发布时带上音频。
3
+ *
4
+ * 声音来源只有官方的(D85):浏览器朗读(不是 profile)、Joplo Cloud 朗读(cloud,登录即用、不要 Key)、OpenAI 与 ElevenLabs
5
+ * (接口地址固定,自带 Key)。以前的 AiHubMix 预设、可改 Base URL 的 OpenAI 兼容与自定义 HTTP 已去掉;本机已有的这类 profile
6
+ * 列为“不再支持”(unsupported):不能再生成,但声音指纹与以前一样,已生成的音频照常播放、照常随 build / share 带上。
3
7
  *
4
8
  * 数据流:
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)。
9
+ * - Key:看板「声音 → 管理密钥」→ PUT /__joplo/voice/profiles/:id(只有 openai / elevenlabs)→ ProfileStore 写 `<JOPLO_HOME>/voice/profiles.json`
10
+ * (0600,含 Key 与改过的默认音色)→ GET 时 publicOf 去掉 Key(只给是否已保存、末 4 位、可用的环境变量名)→ 看板浮层与对话框。
11
+ * - Cloud 音色表:bridge.voice.status()(`GET /api/v1/voice`)→ VoiceHub 记在内存并写 `<JOPLO_HOME>/voice/cloud-voices.json`
12
+ * (rememberCloudCatalog,不含额度)→ ProfileStore.cloudCatalog()(内存 > 本机文件 > 内置的 6 个英文标签)→ publicOf 的 voices(看板音色列表与样音)
13
+ * 与 autoVoiceFor 的 recommended(按内容语言选音色)。build 时连不上云端也按本机文件选,音色与看板一致。
14
+ * - 选用:config({ voice: { profile } }) 优先;否则看板浮层里选的(PUT /__joplo/p/:id/voice → `<项目>/.joplo/voice/index.json` 的 profileId,chosen: true);
15
+ * 都没有时(selection() 为 undefined)用调用方给的默认来源:已登录为 cloud,否则浏览器朗读(resolveVoices 的 fallback,source: 'default')。
16
+ * resolveVoices 算出旁白与各角色的音色和“声音指纹”(cloud:音色;其他:接口、地址、模型、音色、返回格式;不含 Key)。
10
17
  * - 生成:看板按当前语言算出每一步的朗读文字与角色 → POST /__joplo/p/:id/voice/generate → 每段用 clipKey(指纹, 文字) 作键,
11
- * 已有就跳过,否则 synthesize → 识别音频格式 → 写 `<项目>/.joplo/voice/clips/<sha256>.<ext>`,index.json 记 { 文件, 步骤, 指纹, 文字, 语言 };
12
- * 失败记在 failures(看板显示原因,播放时这一步改用浏览器朗读)。进度用 HMR 自定义事件 joplo:voice 推给看板。
18
+ * 已有就跳过,否则合成(cloud 经 bridge.voice.speech,带 locale 与 project)→ 识别音频格式 → 写 `<项目>/.joplo/voice/clips/<sha256>.<ext>`,
19
+ * index.json 记 { 文件, 步骤, 指纹, 文字, 语言 };失败记在 failures(看板显示原因,播放时这一步改用浏览器朗读)。
20
+ * cloud 额度不够(402)时停止,不记失败(GenerateSummary.quota)。进度用 HMR 自定义事件 joplo:voice 推给看板。
13
21
  * - 播放:GET /__joplo/p/:id/voice → { voices(指纹), clips(键 → 音频地址)} → 网页 narrator 按同一个 clipKey 找音频,没有就用浏览器朗读。
14
22
  * - 发布:bundleVoice(joplo build / share)把发布 IR 里步骤用到的、当前声音的音频拷进站点 `voice/`,写 IR 的 voiceIndex;Key 永远不进产物。
15
23
  */
16
24
  import crypto from 'node:crypto';
17
25
  import fs from 'node:fs';
18
26
  import path from 'node:path';
19
- import { DEFAULT_STYLE, clipKey, localizeProject, speakerRoleAt, spokenLine, voiceFingerprint } from '@joplo-app/core';
27
+ import { DEFAULT_STYLE, automaticCaption, clipKey, localizeProject, speakerRoleAt, spokenChars, spokenLine, voiceFingerprint } from '@joplo-app/core';
20
28
  export { DEFAULT_STYLE };
21
29
  /** OpenAI 的内置音色都能读多种语言;marin / cedar 是官方推荐的高质量音色。 */
22
30
  const OPENAI_VOICES = [
@@ -49,96 +57,112 @@ const ELEVENLABS_VOICES = [
49
57
  { id: 'cjVigY5qzO86Huf0OWal', name: 'Eric', gender: 'male', accent: 'en-US' },
50
58
  { id: 'IKne3meq5aSn9XLyUdCD', name: 'Charlie', gender: 'male', accent: 'en-AU' },
51
59
  ];
60
+ /** Joplo Cloud 的 6 个音色 id(契约固定,都是多语言);云端连不上时用它们和下面的英文标签。 */
61
+ export const CLOUD_VOICE_IDS = ['narrator-warm-f', 'narrator-calm-m', 'bright-f', 'friendly-m', 'clear-f', 'deep-m'];
62
+ export const CLOUD_DEFAULT_VOICE = 'narrator-warm-f';
63
+ const BUILTIN_CLOUD_LABELS = {
64
+ 'narrator-warm-f': 'Narrator · warm (female)',
65
+ 'narrator-calm-m': 'Narrator · calm (male)',
66
+ 'bright-f': 'Bright (female)',
67
+ 'friendly-m': 'Friendly (male)',
68
+ 'clear-f': 'Clear (female)',
69
+ 'deep-m': 'Deep (male)',
70
+ };
71
+ export const BUILTIN_CLOUD_CATALOG = {
72
+ model: '',
73
+ defaultVoice: CLOUD_DEFAULT_VOICE,
74
+ voices: CLOUD_VOICE_IDS.map((id) => ({ id, gender: id.endsWith('-m') ? 'male' : 'female', labels: { en: BUILTIN_CLOUD_LABELS[id] }, samples: {} })),
75
+ recommended: {},
76
+ };
77
+ /** OpenAI / ElevenLabs 的官方地址(D85:固定,不能改)。 */
78
+ export const OFFICIAL_BASE_URL = { openai: 'https://api.openai.com/v1', elevenlabs: 'https://api.elevenlabs.io/v1' };
79
+ /** 预设:Joplo Cloud 朗读排第一(D85)。 */
52
80
  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 },
81
+ { id: 'cloud', preset: 'cloud', name: 'Joplo Cloud', kind: 'cloud', baseUrl: '', model: '', voice: CLOUD_DEFAULT_VOICE, response: 'audio', env: null, voices: [] },
82
+ { id: 'openai', preset: 'openai', name: 'OpenAI', kind: 'openai', baseUrl: OFFICIAL_BASE_URL.openai, model: 'gpt-4o-mini-tts', voice: 'marin', response: 'audio', style: DEFAULT_STYLE, env: 'OPENAI_API_KEY', voices: OPENAI_VOICES },
54
83
  // 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 },
84
+ { id: 'elevenlabs', preset: 'elevenlabs', name: 'ElevenLabs', kind: 'elevenlabs', baseUrl: OFFICIAL_BASE_URL.elevenlabs, model: 'eleven_multilingual_v2', voice: 'JBFqnCBsd6RMkjVDRZzb', response: 'audio', env: 'ELEVENLABS_API_KEY', voices: ELEVENLABS_VOICES },
57
85
  ];
58
86
  const presetOf = (id) => PRESETS.find((p) => p.id === id);
87
+ /**
88
+ * 以前内置的 AiHubMix 预设(D85 去掉):项目里可能还选着它(index.json 或 config 的 voice.profile),甚至从没存进 profiles.json(Key 来自环境变量)。
89
+ * 按原来的字段还原出来,标为不再支持:指纹不变,已生成的音频照常打包。
90
+ */
91
+ const LEGACY_AIHUBMIX = { id: 'aihubmix', name: 'AiHubMix', kind: 'openai', baseUrl: 'https://aihubmix.com/v1', model: 'gpt-4o-mini-tts', voice: 'marin', response: 'audio', style: DEFAULT_STYLE, unsupported: true };
59
92
  export class VoiceError extends Error {
60
93
  code;
61
94
  hint;
62
- constructor(code, message, hint) {
95
+ data;
96
+ constructor(code, message, hint,
97
+ /** cloud 错误的附加数据(例如 402 的 neededChars / remainingChars / usageUrl)。 */
98
+ data) {
63
99
  super(message);
64
100
  this.code = code;
65
101
  this.hint = hint;
102
+ this.data = data;
66
103
  }
67
104
  }
105
+ /** 换用提示(D85):旧 profile 不能再生成时告诉作者换成哪一个。 */
106
+ export const UNSUPPORTED_MESSAGE = (name) => `"${name}" is no longer supported as a voice source. Audio it already generated still plays and is still included in build and share, but it cannot generate new audio. Switch to Joplo Cloud narration (npx joplo login), OpenAI or ElevenLabs in the board (Voice), or change voice.profile in joplo.config.ts.`;
68
107
  const ID_RE = /^[a-z0-9][a-z0-9_-]{0,39}$/;
69
108
  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')。 */
109
+ /**
110
+ * 校验看板提交的改动(只有预设能改):openai / elevenlabs 可以改默认音色、模型(openai 还有说话风格);cloud 只能改默认音色。
111
+ * 接口地址、返回格式、请求头与请求体都不能改(D85)。返回合并后的字段。
112
+ */
80
113
  export function normalizeProfile(input, base) {
81
114
  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)
115
+ const voice = o.voice === undefined ? base.voice : str(o.voice, 200);
116
+ if (!voice)
94
117
  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 } : {}) };
118
+ if (base.kind === 'cloud' && !/^[a-z0-9][a-z0-9-]{0,63}$/.test(voice))
119
+ throw new VoiceError('INVALID', 'Unknown Joplo Cloud voice');
120
+ const model = base.kind === 'cloud' || o.model === undefined ? base.model : (str(o.model, 200) ?? base.model);
121
+ let style = base.style;
122
+ if (base.kind === 'openai' && o.style !== undefined && o.style !== null) {
123
+ if (typeof o.style !== 'string' || o.style.length > 1000)
124
+ throw new VoiceError('INVALID', 'Speaking style is up to 1000 characters');
125
+ style = o.style.trim() || undefined;
126
+ }
127
+ const preset = presetOf(base.preset);
128
+ return { name: preset.name, kind: preset.kind, baseUrl: preset.baseUrl, model, voice, response: 'audio', ...(style ? { style } : {}) };
129
+ }
130
+ /** 本机对 OpenAI / ElevenLabs 预设的覆盖改了地址、请求头或返回格式(旧版允许):不再是官方预设。 */
131
+ function isCustomOverride(p, s) {
132
+ if (p.kind !== 'openai' && p.kind !== 'elevenlabs')
133
+ return false;
134
+ const url = typeof s.baseUrl === 'string' && s.baseUrl.trim() ? s.baseUrl.trim().replace(/\/+$/, '') : p.baseUrl;
135
+ return url !== p.baseUrl || (!!s.headers && Object.keys(s.headers).length > 0) || (!!s.response && s.response !== 'audio') || !!s.path || !!s.body;
129
136
  }
130
- /** `<JOPLO_HOME>/voice/profiles.json`:自建的 profile 与改过的预设(含 Key),权限 0600。 */
137
+ /**
138
+ * `<JOPLO_HOME>/voice/profiles.json`:改过的预设(Key、默认音色)与本机旧的 profile,权限 0600。
139
+ * `<JOPLO_HOME>/voice/cloud-voices.json`:最近一次从云端拿到的 Joplo 音色表(不含额度、没有秘密)。
140
+ */
131
141
  export class ProfileStore {
132
142
  env;
143
+ opts;
133
144
  file;
134
- constructor(home, env = process.env) {
145
+ catalogFile;
146
+ constructor(home, env = process.env, opts = {}) {
135
147
  this.env = env;
148
+ this.opts = opts;
136
149
  this.file = path.join(home, 'voice', 'profiles.json');
150
+ this.catalogFile = path.join(home, 'voice', 'cloud-voices.json');
137
151
  }
138
152
  read() {
139
153
  try {
140
154
  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') : [];
155
+ const list = Array.isArray(raw?.profiles) ? raw.profiles.filter((p) => p && typeof p.id === 'string' && ID_RE.test(p.id) && typeof p.name === 'string') : [];
156
+ // 旧版自建的 profile 恰好叫 cloud(D85 之前没有 Joplo Cloud 预设):改名保留为旧 profile,不当作 Joplo Cloud 的覆盖。
157
+ // 下一次写文件时新名字就存下来了。
158
+ return list.map((p) => {
159
+ if (p.id !== 'cloud' || p.kind === 'cloud')
160
+ return p;
161
+ let id = 'cloud-old';
162
+ for (let i = 2; list.some((x) => x.id === id); i++)
163
+ id = `cloud-old-${i}`;
164
+ return { ...p, id, legacyId: 'cloud' };
165
+ });
142
166
  }
143
167
  catch {
144
168
  return [];
@@ -147,26 +171,76 @@ export class ProfileStore {
147
171
  write(list) {
148
172
  fs.mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 });
149
173
  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 });
174
+ fs.writeFileSync(tmp, JSON.stringify({ version: 1, profiles: list.map(({ unsupported: _u, ...p }) => p) }, null, 2), { mode: 0o600 });
151
175
  fs.chmodSync(tmp, 0o600);
152
176
  fs.renameSync(tmp, this.file);
153
177
  }
154
- /** 预设(合并本机覆盖)在前,自建的在后。 */
178
+ /**
179
+ * 预设(合并本机改过的默认音色、模型、风格与 Key;地址固定)在前;本机旧的 profile(不再支持)在后。
180
+ * 旧版把 OpenAI / ElevenLabs 预设改成别的地址(代理)、请求头或返回格式的,不再当作官方预设:作为不再支持的旧 profile
181
+ * 按原来的字段算指纹(旧音频照常播放与打包),Key 不给出去(原本是给代理的,绝不能发到官方地址);删掉它才恢复官方预设。
182
+ */
155
183
  list() {
156
184
  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))];
185
+ const customized = new Set(PRESETS.filter((p) => { const s = stored.find((x) => x.id === p.id); return !!s && isCustomOverride(p, s); }).map((p) => p.id));
186
+ const presets = PRESETS.filter((p) => !customized.has(p.id)).map(({ env: _e, voices: _v, ...p }) => {
187
+ const s = stored.find((x) => x.id === p.id);
188
+ const out = { ...p };
189
+ if (typeof s?.voice === 'string' && s.voice.trim())
190
+ out.voice = s.voice;
191
+ else if (p.kind === 'cloud')
192
+ out.voice = this.cloudCatalog().defaultVoice || p.voice;
193
+ if (p.kind !== 'cloud' && typeof s?.model === 'string' && s.model.trim())
194
+ out.model = s.model;
195
+ if (p.kind === 'openai' && s && 'style' in s) {
196
+ if (s.style)
197
+ out.style = s.style;
198
+ else
199
+ delete out.style;
200
+ }
201
+ if (s?.key && p.kind !== 'cloud')
202
+ out.key = s.key;
203
+ return out;
204
+ });
205
+ const legacy = stored
206
+ .filter((s) => !presetOf(s.id) || customized.has(s.id))
207
+ .map((s) => {
208
+ if (s.id === LEGACY_AIHUBMIX.id)
209
+ return { ...LEGACY_AIHUBMIX, ...s, id: s.id, unsupported: true };
210
+ // 改过地址的预设:以前的合并方式是“预设 + 本机覆盖”,指纹也按它算
211
+ const base = presetOf(s.id);
212
+ if (base) {
213
+ const { env: _e, voices: _v, ...b } = base;
214
+ return { ...b, ...s, id: s.id, kind: base.kind, unsupported: true };
215
+ }
216
+ return { ...s, unsupported: true };
217
+ });
218
+ return [...presets, ...legacy];
159
219
  }
220
+ /** 按 id 找;项目选着的 aihubmix 即使从没存过也找得到(不再支持)。 */
160
221
  get(id) {
161
- return this.list().find((p) => p.id === id) ?? null;
222
+ return this.list().find((p) => p.id === id) ?? (id === LEGACY_AIHUBMIX.id ? { ...LEGACY_AIHUBMIX } : null);
162
223
  }
163
224
  /** 按 id 或名字(不区分大小写)找,config({ voice: { profile } }) 用。 */
164
225
  find(ref) {
165
226
  const r = ref.trim().toLowerCase();
166
- return this.list().find((p) => p.id === r || p.name.toLowerCase() === r) ?? null;
227
+ const all = [...this.list(), ...(this.list().some((p) => p.id === LEGACY_AIHUBMIX.id) ? [] : [LEGACY_AIHUBMIX])];
228
+ const hit = all.find((p) => p.id === r || p.name.toLowerCase() === r);
229
+ return hit ? { ...hit } : null;
230
+ }
231
+ /** 项目升级前保存的 cloud 引用继续指向旧来源;官方名称始终可显式选用。 */
232
+ projectProfile(ref, officialCloud = false) {
233
+ if (ref.trim().toLowerCase() === 'cloud' && !officialCloud) {
234
+ const legacy = this.list().find((p) => p.legacyId === 'cloud');
235
+ if (legacy)
236
+ return legacy;
237
+ }
238
+ return this.find(ref);
167
239
  }
168
- /** Key:保存的优先,其次是预设对应的环境变量。 */
240
+ /** Key:保存的优先,其次是预设对应的环境变量。cloud 不用 Key(用 CLI 的登录);旧 profile 不再生成,也不给 Key。 */
169
241
  keyOf(p) {
242
+ if (p.unsupported || p.kind === 'cloud')
243
+ return null;
170
244
  if (p.key)
171
245
  return p.key;
172
246
  const env = presetOf(p.preset)?.env;
@@ -174,72 +248,97 @@ export class ProfileStore {
174
248
  return v && v.trim() ? v.trim() : null;
175
249
  }
176
250
  /**
177
- * 新建或修改。id 为 null 时新建(id 由名字生成)。key:undefined = 不改;null 或 '' = 删掉保存的 Key;字符串 = 保存。
251
+ * 改预设:默认音色、模型、风格(见 normalizeProfile)与 Key。key:undefined = 不改;null 或 '' = 删掉保存的 Key;字符串 = 保存。
252
+ * 不能新建(D85:不再提供 OpenAI 兼容与自定义 HTTP),也不能改旧的 profile。
178
253
  */
179
254
  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}`;
255
+ if (!id || !presetOf(id)) {
256
+ if (id && !this.get(id))
257
+ throw new VoiceError('NOT_FOUND', `Unknown voice profile: ${id}`);
258
+ throw new VoiceError('INVALID', 'Custom voice providers are no longer supported. Use Joplo Cloud narration, OpenAI or ElevenLabs');
191
259
  }
260
+ const current = this.get(id);
261
+ if (current.unsupported)
262
+ throw new VoiceError('INVALID', `${current.name} uses an address, headers or response format that is no longer supported. Delete it first to use the official ${current.name}`);
263
+ const fields = normalizeProfile(input, current);
192
264
  if (key !== undefined && key !== null && (typeof key !== 'string' || key.length > 500 || /[\r\n]/.test(key)))
193
265
  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;
266
+ const list = this.read();
267
+ const keep = list.find((p) => p.id === id)?.key;
268
+ const nextKey = id === 'cloud' ? undefined : key === undefined ? keep : key && key.trim() ? key.trim() : undefined;
269
+ const next = { id, ...fields, preset: id, ...(nextKey ? { key: nextKey } : {}) };
270
+ this.write([...list.filter((p) => p.id !== id), next]);
271
+ return this.get(id);
199
272
  }
200
- /** 自建的删除;预设恢复默认(去掉本机覆盖,包括保存的 Key)。 */
273
+ /** 预设恢复默认(去掉本机覆盖,包括保存的 Key);本机旧的 profile 删除。 */
201
274
  remove(id) {
202
275
  const list = this.read();
203
276
  if (!presetOf(id) && !list.some((p) => p.id === id))
204
277
  throw new VoiceError('NOT_FOUND', `Unknown voice profile: ${id}`);
205
278
  this.write(list.filter((p) => p.id !== id));
206
279
  }
280
+ /** Joplo 音色表:云端给的(内存)> 本机记下的上一次 > 内置的 6 个(英文标签,没有推荐与样音)。 */
281
+ cloudCatalog() {
282
+ const live = this.opts.catalog?.();
283
+ if (live)
284
+ return live;
285
+ try {
286
+ const raw = JSON.parse(fs.readFileSync(this.catalogFile, 'utf8'));
287
+ if (raw && Array.isArray(raw.voices) && raw.voices.length && raw.recommended && typeof raw.recommended === 'object')
288
+ return raw;
289
+ }
290
+ catch {
291
+ /* 没有或损坏:用内置的 */
292
+ }
293
+ return BUILTIN_CLOUD_CATALOG;
294
+ }
295
+ /** 记下云端给的音色表(内容变了才写),build 与离线时按它选音色,与看板一致。 */
296
+ rememberCloudCatalog(c) {
297
+ const next = JSON.stringify({ model: c.model, defaultVoice: c.defaultVoice, voices: c.voices, recommended: c.recommended }, null, 2);
298
+ try {
299
+ if (fs.existsSync(this.catalogFile) && fs.readFileSync(this.catalogFile, 'utf8') === next)
300
+ return;
301
+ fs.mkdirSync(path.dirname(this.catalogFile), { recursive: true, mode: 0o700 });
302
+ const tmp = `${this.catalogFile}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
303
+ fs.writeFileSync(tmp, next);
304
+ fs.renameSync(tmp, this.catalogFile);
305
+ }
306
+ catch {
307
+ /* 只影响离线时的音色选择 */
308
+ }
309
+ }
310
+ /** cloud 的音色候选(看板列表与试听)。 */
311
+ cloudVoices() {
312
+ const c = this.cloudCatalog();
313
+ return c.voices.map((v) => ({ id: v.id, name: v.labels.en ?? Object.values(v.labels)[0] ?? v.id, gender: v.gender, labels: v.labels, samples: v.samples, ...(v.id === c.defaultVoice ? { recommended: true } : {}) }));
314
+ }
207
315
  publicOf(p) {
208
- const { key: _k, ...rest } = p;
209
- const preset = presetOf(p.preset);
316
+ const { key: _k, unsupported, ...rest } = p;
317
+ const preset = unsupported ? undefined : presetOf(p.preset);
210
318
  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 };
319
+ const voices = p.kind === 'cloud' ? this.cloudVoices() : (preset?.voices ?? (p.kind === 'openai' ? OPENAI_VOICES : p.kind === 'elevenlabs' ? ELEVENLABS_VOICES : []));
320
+ return { ...rest, key: { saved: !!p.key, hint: p.key ? `…${p.key.slice(-4)}` : null, env, envSet: !!(env && this.env[env]?.trim()) }, voices, removable: !preset, unsupported: !!unsupported };
212
321
  }
213
322
  }
214
323
  // ---------- 合成 ----------
215
324
  const MAX_AUDIO = 20 * 1024 * 1024;
216
325
  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)时才发。 */
326
+ /** 发给模型的说话风格:只有 OpenAI、且不是 tts-1 系列(不支持 instructions)时才发。 */
223
327
  export const styleOf = (p) => (p.kind === 'openai' && p.style?.trim() && !/^tts-1/i.test(p.model) ? p.style.trim() : null);
224
- /** 这次合成的 HTTP 请求(不发出)。 */
328
+ /** 这次合成的 HTTP 请求(不发出):只有官方的 OpenAI 与 ElevenLabs(地址固定)。 */
225
329
  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 ?? '')]));
330
+ if (p.unsupported || (p.kind !== 'openai' && p.kind !== 'elevenlabs'))
331
+ throw new VoiceError('UNSUPPORTED', UNSUPPORTED_MESSAGE(p.name));
332
+ if (!key)
333
+ throw new VoiceError('NO_KEY', 'No API key for this provider');
227
334
  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
- };
335
+ const url = `${OFFICIAL_BASE_URL.elevenlabs}/text-to-speech/${encodeURIComponent(voice)}?output_format=mp3_44100_128`;
336
+ return { url, init: { method: 'POST', headers: { 'content-type': 'application/json', accept: 'audio/mpeg', 'xi-api-key': key }, body: JSON.stringify({ text, ...(p.model ? { model_id: p.model } : {}) }) } };
240
337
  }
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 ?? '' }) } };
338
+ return {
339
+ url: `${OFFICIAL_BASE_URL.openai}/audio/speech`,
340
+ init: { method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` }, body: JSON.stringify({ model: p.model, input: text, voice, response_format: 'mp3', ...(styleOf(p) ? { instructions: styleOf(p) } : {}) }) },
341
+ };
243
342
  }
244
343
  export const AUDIO_TYPES = { mp3: 'audio/mpeg', wav: 'audio/wav', ogg: 'audio/ogg', flac: 'audio/flac', m4a: 'audio/mp4', aac: 'audio/aac' };
245
344
  /** 按文件头识别音频格式;不是音频返回 null。 */
@@ -264,40 +363,6 @@ export function sniffAudio(b) {
264
363
  return t('mp3'); // MPEG 帧同步
265
364
  return null;
266
365
  }
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
366
  const clip = (s, n) => (s.length > n ? `${s.slice(0, n)}…` : s);
302
367
  /** 错误信息里去掉 Key,截断。 */
303
368
  const scrub = (s, key) => clip(key ? s.split(key).join('••••') : s, 300).replace(/\s+/g, ' ').trim();
@@ -310,7 +375,7 @@ async function readLimited(res) {
310
375
  throw new VoiceError('TOO_LARGE', `The response is larger than ${MAX_AUDIO / 1024 / 1024} MB`);
311
376
  return buf;
312
377
  }
313
- /** 合成一段:返回音频字节与格式。失败抛 VoiceError(信息里不含 Key)。 */
378
+ /** 用自带 Key 的官方接口合成一段:返回音频字节与格式。失败抛 VoiceError(信息里不含 Key)。 */
314
379
  export async function synthesize(p, key, text, voice, opts = {}) {
315
380
  const f = opts.fetch ?? ((u, i) => fetch(u, i));
316
381
  const { url, init } = buildRequest(p, key, text, voice);
@@ -329,72 +394,76 @@ export async function synthesize(p, key, text, voice, opts = {}) {
329
394
  const body = scrub(bytes.toString('utf8'), key);
330
395
  throw new VoiceError('HTTP', `HTTP ${res.status}${body ? `: ${body}` : ''}`);
331
396
  }
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;
397
+ const t = sniffAudio(bytes);
398
+ if (t)
399
+ return { bytes, ...t };
400
+ throw new VoiceError('NOT_AUDIO', `The response is not audio (${ct || 'no content type'}): ${scrub(bytes.subarray(0, 200).toString('utf8'), key)}`);
401
+ }
402
+ const CLOUD_CODES = new Set(['TTS_QUOTA_EXCEEDED', 'AUTH_REQUIRED', 'AUTH_EXPIRED', 'EMAIL_UNVERIFIED', 'FORBIDDEN', 'RATE_LIMITED', 'TTS_UNAVAILABLE', 'BAD_REQUEST', 'NETWORK', 'NOT_FOUND']);
403
+ /** 托管朗读合成一段(D85):经 CLI 注入的 bridge,用 CLI 的登录,不要 Key。bridge 抛出的 { code, message, data } 转成 VoiceError。 */
404
+ export async function synthesizeCloud(bridge, req) {
405
+ if (!bridge)
406
+ throw new VoiceError('CLOUD_UNAVAILABLE', 'This board cannot use Joplo Cloud narration. Stop it and run npx joplo dev again');
407
+ let result;
371
408
  try {
372
- dl = await f(v, { signal, redirect: 'follow' });
409
+ result = await bridge.speech({ text: req.text, voice: req.voice, ...(req.locale ? { locale: req.locale } : {}), ...(req.project ? { project: req.project.slice(0, 200) } : {}) });
373
410
  }
374
411
  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);
412
+ const err = (e ?? {});
413
+ const code = typeof err.code === 'string' && CLOUD_CODES.has(err.code) ? err.code : 'CLOUD_UNAVAILABLE';
414
+ const data = err.data && typeof err.data === 'object' ? err.data : undefined;
415
+ throw new VoiceError(code, typeof err.message === 'string' && err.message ? err.message : 'Joplo Cloud narration failed', undefined, data);
416
+ }
417
+ const bytes = Buffer.from(result.audio);
418
+ if (bytes.length > MAX_AUDIO)
419
+ throw new VoiceError('TOO_LARGE', `The audio is larger than ${MAX_AUDIO / 1024 / 1024} MB`);
420
+ const t = sniffAudio(bytes);
381
421
  if (!t)
382
- throw new VoiceError('NOT_AUDIO', `The link in "${p.path}" did not return audio`);
383
- return { bytes: audio, ...t };
422
+ throw new VoiceError('NOT_AUDIO', 'Joplo Cloud did not return audio');
423
+ return { bytes, result, ...t };
384
424
  }
385
425
  // ---------- 声音指纹与选用 ----------
386
- /** 声音指纹:接口、地址、模型、音色、返回格式、请求体模板、说话风格(不含 Key 与请求头)。 */
426
+ /**
427
+ * 声音指纹:cloud 只看音色(换上游模型不让旧音频失效,D85);其他是接口、地址、模型、音色、返回格式、请求体模板、说话风格(不含 Key 与请求头)。
428
+ * 旧 profile 的算法与以前完全一样,已生成的音频的键不变。
429
+ */
387
430
  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);
431
+ const parts = p.kind === 'cloud' ? ['cloud', voice] : [p.kind, p.baseUrl, p.model, voice, p.response, p.path ?? '', p.body ?? '', styleOf(p) ?? ''];
432
+ return crypto.createHash('sha256').update(JSON.stringify(parts)).digest('hex').slice(0, 16);
433
+ }
434
+ /** 磁盘元数据不可信:只保留合法语言、基础音色和固定契约中的目标音色。 */
435
+ function cleanVoicePins(value) {
436
+ const object = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
437
+ const validVoice = (v) => typeof v === 'string' && CLOUD_VOICE_IDS.includes(v);
438
+ if (!object(value))
439
+ return {};
440
+ return Object.fromEntries(Object.entries(value).flatMap(([locale, map]) => {
441
+ if (!/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(locale) || !object(map))
442
+ return [];
443
+ const entries = Object.entries(map).filter((entry) => validVoice(entry[0]) && validVoice(entry[1]));
444
+ return entries.length ? [[locale, Object.fromEntries(entries)]] : [];
445
+ }));
389
446
  }
390
447
  /**
391
- * 某种内容语言用哪个音色(D84):音色有口音(ElevenLabs 预设)且口音不是这种语言、而预设里有这种语言的音色时,
392
- * 换成同语言的(优先同性别、推荐的);多语言音色(OpenAI 预设没有口音)原样用,由说话风格要求母语口音。
448
+ * 某种内容语言用哪个音色(D84):
449
+ * - ElevenLabs 预设:音色有口音且口音不是这种语言、而预设里有这种语言的音色时,换成同语言的(优先同性别、推荐的);
450
+ * - Joplo Cloud:云端给了这种语言的推荐音色(recommended[语言])时,音色在推荐里就不换,否则换成推荐里同性别的第一个,没有同性别的用第一个;
451
+ * - 多语言音色(OpenAI 预设没有口音)原样用,由说话风格要求母语口音。
393
452
  */
394
- export function autoVoiceFor(profile, voice, locale) {
453
+ export function autoVoiceFor(profile, voice, locale, catalog) {
454
+ if (!locale)
455
+ return voice;
456
+ if (profile.preset === 'cloud') {
457
+ const c = catalog ?? BUILTIN_CLOUD_CATALOG;
458
+ const rec = c.recommended[locale] ?? c.recommended[locale.split('-')[0]] ?? [];
459
+ if (!rec.length || rec.includes(voice))
460
+ return voice;
461
+ const gender = c.voices.find((v) => v.id === voice)?.gender;
462
+ return rec.find((id) => gender && c.voices.find((v) => v.id === id)?.gender === gender) ?? rec[0];
463
+ }
395
464
  const choices = presetOf(profile.preset)?.voices;
396
465
  const cur = choices?.find((v) => v.id === voice);
397
- if (!locale || !choices || !cur?.accent)
466
+ if (!choices || !cur?.accent)
398
467
  return voice;
399
468
  const lang = (tag) => tag.toLowerCase().split('-')[0];
400
469
  if (lang(cur.accent) === lang(locale))
@@ -407,38 +476,79 @@ export function autoVoiceFor(profile, voice, locale) {
407
476
  }
408
477
  /** 传给 resolveVoices 的语言:默认语言(源文件的语言)不自动换音色,保留作者原来的选择和已生成的音频。 */
409
478
  export const voiceLocaleOf = (project, locale) => (locale && project?.i18n && locale !== project.i18n.default ? locale : null);
410
- /** locale:内容语言(D84,默认语言传 null,见 voiceLocaleOf)。config.voice.locales[locale] 优先,其次按 autoVoiceFor 自动选;不传时与之前一样。 */
411
- export function resolveVoices(config, selected, store, locale) {
479
+ /**
480
+ * locale:内容语言(D84,默认语言传 null,见 voiceLocaleOf)。config.voice.locales[locale] 优先,其次按 autoVoiceFor 自动选;不传时与之前一样。
481
+ * selected:看板里选的(VoiceCache.selection()):字符串 = 某个来源;null = 选了浏览器朗读;undefined = 没选过,这时用 fallback
482
+ * (调用方给:已登录为 'cloud',否则 null)。
483
+ */
484
+ export function resolveVoices(config, selected, store, locale, fallback, pins, officialCloud = false) {
412
485
  let profile = null;
413
486
  let source = null;
414
487
  let missing = null;
415
488
  if (config?.profile) {
416
- profile = store.find(config.profile);
489
+ profile = store.projectProfile(config.profile);
417
490
  if (profile)
418
491
  source = 'config';
419
492
  else
420
493
  missing = config.profile;
421
494
  }
422
495
  else if (selected) {
423
- profile = store.get(selected);
496
+ profile = store.projectProfile(selected, officialCloud);
424
497
  if (profile)
425
498
  source = 'board';
426
499
  }
500
+ else if (selected === undefined && fallback) {
501
+ profile = store.get(fallback);
502
+ if (profile)
503
+ source = 'default';
504
+ }
427
505
  if (!profile)
428
506
  return { profile: null, source, missing, narrator: null, roles: {}, voices: { narrator: null, roles: {} } };
507
+ const p = profile;
508
+ const catalog = p.kind === 'cloud' ? store.cloudCatalog() : undefined;
429
509
  const own = locale ? config?.locales?.[locale] : undefined;
430
- const narrator = own?.narrator ?? autoVoiceFor(profile, config?.narrator ?? profile.voice, locale);
431
- const roles = { ...Object.fromEntries(Object.entries(config?.roles ?? {}).map(([r, v]) => [r, autoVoiceFor(profile, v, locale)])), ...(own?.roles ?? {}) };
510
+ // cloud:这种语言下已经记下的选择优先(不随推荐列表变),没记过才按推荐挑
511
+ const picks = {};
512
+ const safePins = cleanVoicePins(pins);
513
+ const auto = (v) => {
514
+ if (p.kind !== 'cloud' || !locale)
515
+ return autoVoiceFor(p, v, locale, catalog);
516
+ const chosen = safePins[locale]?.[v] ?? autoVoiceFor(p, v, locale, catalog);
517
+ picks[v] = chosen;
518
+ return chosen;
519
+ };
520
+ const narrator = own?.narrator ?? auto(config?.narrator ?? p.voice);
521
+ const roles = { ...Object.fromEntries(Object.entries(config?.roles ?? {}).filter(([r]) => !own?.roles?.[r]).map(([r, v]) => [r, auto(v)])), ...(own?.roles ?? {}) };
432
522
  return {
433
523
  profile,
434
524
  source,
435
525
  missing,
436
526
  narrator,
437
527
  roles,
438
- voices: { narrator: fingerprint(profile, narrator), roles: Object.fromEntries(Object.entries(roles).map(([r, v]) => [r, fingerprint(profile, v)])) },
528
+ voices: { narrator: fingerprint(p, narrator), roles: Object.fromEntries(Object.entries(roles).map(([r, v]) => [r, fingerprint(p, v)])) },
529
+ ...(Object.keys(picks).length && locale ? { autoPicks: { locale, map: picks } } : {}),
439
530
  };
440
531
  }
441
532
  const FILE_RE = /^[0-9a-f]{64}\.(mp3|wav|ogg|flac|m4a|aac)$/;
533
+ /** 账号层面的错误:继续请求别的段也一样失败,生成在这里停下,也不记成某一步的失败。 */
534
+ const STOP_CODES = new Set(['TTS_QUOTA_EXCEEDED', 'AUTH_REQUIRED', 'AUTH_EXPIRED', 'EMAIL_UNVERIFIED', 'FORBIDDEN', 'CLOUD_UNAVAILABLE', 'UNSUPPORTED', 'NOT_FOUND']);
535
+ const nonNeg = (v) => (Number.isSafeInteger(v) && v >= 0 ? v : null);
536
+ /**
537
+ * 这次要生成的段数与字数(D85):只算缺音频的段,同一段(同一个片段键)只算一次,字数按 spokenChars(Array.from)。
538
+ * 看板按钮“约 X 字”与 `joplo voice --dry-run` 用它;没有选用来源时都是 0。
539
+ */
540
+ export function estimateVoice(segments, resolved, cache) {
541
+ const seen = new Set();
542
+ let chars = 0;
543
+ for (const s of segments) {
544
+ const j = cache.plan(s, resolved);
545
+ if (!j || seen.has(j.key) || cache.clipOf(j.key))
546
+ continue;
547
+ seen.add(j.key);
548
+ chars += spokenChars(j.text);
549
+ }
550
+ return { steps: seen.size, chars };
551
+ }
442
552
  /** `<项目>/.joplo/voice/`:index.json(选用的 profile、片段、失败)与 clips/。 */
443
553
  export class VoiceCache {
444
554
  projectDir;
@@ -453,12 +563,19 @@ export class VoiceCache {
453
563
  read() {
454
564
  try {
455
565
  const raw = JSON.parse(fs.readFileSync(path.join(this.root, 'index.json'), 'utf8'));
456
- 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 : {} };
566
+ const profileId = typeof raw.profileId === 'string' ? raw.profileId : null;
567
+ const pins = cleanVoicePins(raw.pins);
568
+ return { version: 1, profileId, chosen: raw.chosen === true || profileId !== null, ...(raw.cloudSource === 'official' ? { cloudSource: 'official' } : {}), ...(Object.keys(pins).length ? { pins } : {}), clips: raw.clips && typeof raw.clips === 'object' ? raw.clips : {}, failures: raw.failures && typeof raw.failures === 'object' ? raw.failures : {} };
457
569
  }
458
570
  catch {
459
- return { version: 1, profileId: null, clips: {}, failures: {} };
571
+ return { version: 1, profileId: null, chosen: false, clips: {}, failures: {} };
460
572
  }
461
573
  }
574
+ /** 看板里选的来源:字符串 = 某个来源;null = 选了浏览器朗读;undefined = 没选过(用默认来源,见 resolveVoices 的 fallback)。 */
575
+ selection() {
576
+ const idx = this.read();
577
+ return idx.chosen ? idx.profileId : undefined;
578
+ }
462
579
  write(idx) {
463
580
  fs.mkdirSync(this.root, { recursive: true });
464
581
  const file = path.join(this.root, 'index.json');
@@ -467,7 +584,22 @@ export class VoiceCache {
467
584
  fs.renameSync(tmp, file);
468
585
  }
469
586
  select(profileId) {
470
- this.write({ ...this.read(), profileId });
587
+ this.write({ ...this.read(), profileId, chosen: true, cloudSource: profileId === 'cloud' ? 'official' : undefined });
588
+ }
589
+ /** 新版看板明确选过官方 cloud;旧选择没有此标记。 */
590
+ officialCloud() { return this.read().cloudSource === 'official'; }
591
+ /** 记下的 cloud 自动音色(见 ResolvedVoices.autoPicks);build、share、播放、joplo voice 都传给 resolveVoices。 */
592
+ pins() {
593
+ return this.read().pins ?? {};
594
+ }
595
+ /** 记下这种语言自动选的音色:已经记过的不改(只有从没生成过的组合才按推荐挑)。 */
596
+ pin(locale, map) {
597
+ const idx = this.read();
598
+ const cur = idx.pins?.[locale] ?? {};
599
+ const add = Object.entries(cleanVoicePins({ [locale]: map })[locale] ?? {}).filter(([k]) => !Object.hasOwn(cur, k));
600
+ if (!add.length)
601
+ return;
602
+ this.write({ ...idx, pins: { ...(idx.pins ?? {}), [locale]: { ...cur, ...Object.fromEntries(add) } } });
471
603
  }
472
604
  /** 片段文件的绝对路径(文件名不合法或不存在时为 null)。 */
473
605
  fileOf(name) {
@@ -520,6 +652,10 @@ export class VoiceCache {
520
652
  const c = this.read().clips[key];
521
653
  return c && FILE_RE.test(c.file) && fs.existsSync(path.join(this.clipsDir, c.file)) ? c.file : null;
522
654
  }
655
+ /** 分享下载的片段不能被误认成本机新生成,进而覆盖另一语言的旧声音。旧缓存缺省为本机生成。 */
656
+ localClipOf(key) {
657
+ return this.read().clips[key]?.origin === 'shared' ? null : this.clipOf(key);
658
+ }
523
659
  /** 收下一段别处来的音频(D84:从已发布的分享沿用):文件名必须是内容的 sha256,否则不收。 */
524
660
  adopt(key, file, bytes, rec) {
525
661
  if (!FILE_RE.test(file) || crypto.createHash('sha256').update(bytes).digest('hex') !== file.split('.')[0])
@@ -543,13 +679,19 @@ export class VoiceCache {
543
679
  const have = this.clipOf(j.key);
544
680
  if (have)
545
681
  return { key: j.key, file: have, generated: false };
682
+ if (p.unsupported)
683
+ throw new VoiceError('UNSUPPORTED', UNSUPPORTED_MESSAGE(p.name));
546
684
  const running = opts.inflight?.get(j.key);
547
685
  if (running)
548
686
  return { ...(await running), generated: false };
549
687
  const run = this.synthesizeOne(seg, locale, p, j, store, opts);
550
688
  opts.inflight?.set(j.key, run);
551
689
  try {
552
- return await run;
690
+ const r = await run;
691
+ // 第一次在这种语言下用 cloud 生成成功:把自动选的音色记进项目,之后不随推荐列表变
692
+ if (resolved.autoPicks)
693
+ this.pin(resolved.autoPicks.locale, resolved.autoPicks.map);
694
+ return r;
553
695
  }
554
696
  finally {
555
697
  if (opts.inflight?.get(j.key) === run)
@@ -557,11 +699,19 @@ export class VoiceCache {
557
699
  }
558
700
  }
559
701
  async synthesizeOne(seg, locale, p, j, store, opts) {
560
- const key = store.keyOf(p);
561
702
  try {
562
- if (!key && p.kind !== 'http')
563
- throw new VoiceError('NO_KEY', 'No API key for this provider');
564
- const a = await synthesize(p, key, j.text, j.voice, opts);
703
+ let a;
704
+ if (p.kind === 'cloud') {
705
+ const c = await synthesizeCloud(opts.cloud, { text: j.text, voice: j.voice, locale: opts.speechLocale, project: opts.project });
706
+ opts.onCloud?.({ charged: c.result.charged, remaining: c.result.remaining, cache: c.result.cache });
707
+ a = c;
708
+ }
709
+ else {
710
+ const key = store.keyOf(p);
711
+ if (!key)
712
+ throw new VoiceError('NO_KEY', 'No API key for this provider');
713
+ a = await synthesize(p, key, j.text, j.voice, opts);
714
+ }
565
715
  const file = `${crypto.createHash('sha256').update(a.bytes).digest('hex')}.${a.ext}`;
566
716
  fs.mkdirSync(this.clipsDir, { recursive: true });
567
717
  const dest = path.join(this.clipsDir, file);
@@ -571,7 +721,9 @@ export class VoiceCache {
571
721
  return { key: j.key, file, generated: true };
572
722
  }
573
723
  catch (e) {
574
- this.recordFailure(j.key, seg.stepId, e instanceof Error ? e.message : String(e));
724
+ // 账号层面的错误(额度不够、没登录…)不是这一步的问题:不记失败,看板另外说明
725
+ if (!(e instanceof VoiceError && STOP_CODES.has(e.code)))
726
+ this.recordFailure(j.key, seg.stepId, e instanceof Error ? e.message : String(e));
575
727
  throw e;
576
728
  }
577
729
  }
@@ -589,11 +741,15 @@ export class VoiceCache {
589
741
  }
590
742
  const todo = [...jobs.entries()].filter(([k]) => !this.clipOf(k));
591
743
  const summary = { total: jobs.size, generated: 0, skipped: jobs.size - todo.length, failed: [] };
744
+ // 旧 profile(D85):不再生成;已有的音频照常播放与发布
745
+ if (resolved.profile.unsupported)
746
+ return { ...summary, unsupported: true, ...(todo.length ? { error: { code: 'UNSUPPORTED', message: UNSUPPORTED_MESSAGE(resolved.profile.name) } } : {}) };
592
747
  let done = summary.skipped;
593
748
  opts.onProgress?.(done, summary.total, 0);
594
749
  let next = 0;
750
+ let stop = false;
595
751
  const worker = async () => {
596
- while (next < todo.length) {
752
+ while (next < todo.length && !stop) {
597
753
  if (opts.signal?.aborted)
598
754
  return;
599
755
  const [, seg] = todo[next++];
@@ -605,13 +761,24 @@ export class VoiceCache {
605
761
  summary.skipped++;
606
762
  }
607
763
  catch (e) {
608
- summary.failed.push({ stepId: seg.stepId, message: e instanceof Error ? e.message : String(e) });
764
+ if (e instanceof VoiceError && STOP_CODES.has(e.code)) {
765
+ // 额度不够(402)或账号问题:停下,已生成的保留;没生成的步骤由网页用浏览器朗读
766
+ stop = true;
767
+ if (e.code === 'TTS_QUOTA_EXCEEDED')
768
+ summary.quota = { neededChars: nonNeg(e.data?.neededChars), remainingChars: nonNeg(e.data?.remainingChars) };
769
+ else
770
+ summary.error ??= { code: e.code, message: e.message };
771
+ }
772
+ else
773
+ summary.failed.push({ stepId: seg.stepId, message: e instanceof Error ? e.message : String(e) });
609
774
  }
610
775
  done++;
611
776
  opts.onProgress?.(done, summary.total, summary.failed.length);
612
777
  }
613
778
  };
614
779
  await Promise.all([worker(), worker()]);
780
+ if (stop)
781
+ summary.stopped = todo.length - next;
615
782
  return summary;
616
783
  }
617
784
  }
@@ -622,17 +789,20 @@ function voicesPerLocale(project, resolve) {
622
789
  return v ? [{ locale: l, project: l ? localizeProject(project, l) : project, voices: v }] : [];
623
790
  });
624
791
  }
625
- const sharedVoices = (index) => (l) => (l && index.locales?.[l]) || { narrator: index.narrator, roles: index.roles };
792
+ const sharedVoices = (index) => (l) => (l && index.locales?.[l]) || { narrator: index.narrator, roles: index.roles, ...(index.overrides ? { overrides: index.overrides } : {}) };
626
793
  /**
627
794
  * 从上一次发布的分享沿用音频(D84):Cloud 只存分享出去的作品,不另设缓存。按当前文字和声音算片段键,
628
795
  * 本机没有、分享里有的就下载到本机缓存(文件名必须是内容的 sha256),之后照常打包;上传时 Cloud 已有这些内容,不会重传。
629
796
  * 本机没有供应商时按分享里的声音指纹算键。自动字幕的步骤(文字由网页按语言生成)不在这里沿用。
630
797
  */
631
- export async function reuseSharedVoice(projectDir, project, shared, store, devConfig) {
798
+ export async function reuseSharedVoice(projectDir, project, shared, store, devConfig, defaultProfile) {
632
799
  const cache = new VoiceCache(projectDir);
633
- const selected = cache.read().profileId;
634
- const local = resolveVoices(devConfig ?? project.voiceConfig, selected, store);
635
- const per = voicesPerLocale(project, local.profile ? (l) => resolveVoices(devConfig ?? project.voiceConfig, selected, store, voiceLocaleOf(project, l)).voices : sharedVoices(shared.index));
800
+ const selected = cache.selection();
801
+ const pins = cache.pins();
802
+ const local = resolveVoices(devConfig ?? project.voiceConfig, selected, store, null, defaultProfile, pins, cache.officialCloud());
803
+ // 没选过来源(默认来源)时按分享里的指纹沿用:默认来源变了(例如登录后默认 cloud)也不能让已发布的音频丢掉
804
+ const own = local.profile && local.source !== 'default';
805
+ const per = voicesPerLocale(project, own ? (l) => resolveVoices(devConfig ?? project.voiceConfig, selected, store, voiceLocaleOf(project, l), defaultProfile, pins, cache.officialCloud()).voices : sharedVoices(shared.index));
636
806
  let reused = 0;
637
807
  for (const { locale, project: p, voices } of per)
638
808
  for (const sc of Object.values(p.scenarios))
@@ -640,9 +810,16 @@ export async function reuseSharedVoice(projectDir, project, shared, store, devCo
640
810
  if (st.captionAuto && !st.say && !st.narrate)
641
811
  continue;
642
812
  const line = spokenLine(st, st.caption, speakerRoleAt(p, sc.id, i + 1));
643
- const fp = voiceFingerprint(voices, line.role);
813
+ const fp = voiceFingerprint(voices, line.role, line.text);
644
814
  if (!fp || !line.text)
645
815
  continue;
816
+ // 默认来源下已有的新片段优先,不为同一片段额外下载旧声音。
817
+ if (local.source === 'default') {
818
+ const current = resolveVoices(devConfig ?? project.voiceConfig, selected, store, voiceLocaleOf(project, locale), defaultProfile, pins, cache.officialCloud());
819
+ const currentFp = voiceFingerprint(current.voices, line.role);
820
+ if (currentFp && cache.localClipOf(clipKey(currentFp, line.text)))
821
+ continue;
822
+ }
646
823
  const text = line.text.replace(/\s+/g, ' ').trim();
647
824
  const key = clipKey(fp, text);
648
825
  const rel = shared.index.clips[key];
@@ -650,7 +827,7 @@ export async function reuseSharedVoice(projectDir, project, shared, store, devCo
650
827
  continue;
651
828
  const file = rel.replace(/^voice\//, '');
652
829
  const bytes = await shared.fetch(rel).catch(() => null);
653
- if (bytes && cache.adopt(key, file, bytes, { stepId: st.id, fp, text, locale: locale ?? 'en' }))
830
+ if (bytes && cache.adopt(key, file, bytes, { stepId: st.id, fp, text, locale: locale ?? 'en', origin: 'shared' }))
654
831
  reused++;
655
832
  }
656
833
  return reused;
@@ -659,70 +836,111 @@ export async function reuseSharedVoice(projectDir, project, shared, store, devCo
659
836
  * 发布(joplo build / share):把发布 IR 里步骤用到的、当前声音的音频拷进 `<outDir>/voice/`,返回 IR 的 voiceIndex。
660
837
  * 同一步同一声音同一语言只留最新的一段(改过字之后旧的不再带上)。
661
838
  * 内容多语言(D84):每种内容语言按 resolveVoices(…, 语言) 选声音,voiceIndex.locales 记各语言的指纹;missing 按语言分别统计。
662
- * missing:还没有音频的步骤数(自动字幕的步骤只要有这种语言的任意音频就算有)。
839
+ * missing:还没有有效音频的步骤数(自动字幕必须匹配当前参数在片段语言下生成的文字)。
663
840
  * 没有选用 profile 时:给了 fallback(已发布分享的 voiceIndex)就按它的指纹带上本机已有的音频,否则不带(观众端用浏览器朗读)。
841
+ * defaultProfile:项目没选过来源时的默认(D85:已登录为 'cloud',与看板同一规则,见 resolveVoices)。
842
+ * 不再支持的旧 profile 照常按它的指纹打包(D85:已生成的音频照常随分享上传)。
664
843
  */
665
- export function bundleVoice(projectDir, project, outDir, store, devConfig, fallback) {
844
+ export function bundleVoice(projectDir, project, outDir, store, devConfig, fallback, defaultProfile) {
666
845
  const cache = new VoiceCache(projectDir);
667
846
  const idx = cache.read();
847
+ const selected = cache.selection();
668
848
  const cfg = devConfig ?? project.voiceConfig;
669
- const base = resolveVoices(cfg, idx.profileId, store);
670
- const profileName = base.profile?.name ?? (fallback ? 'the published share' : null);
849
+ const pins = cache.pins();
850
+ const base = resolveVoices(cfg, selected, store, null, defaultProfile, pins, cache.officialCloud());
851
+ // 有上一次的分享、而这里只是默认来源(没选过)时,按分享里的指纹打包(P0:默认来源的改变不能让已发布的音频丢失)
852
+ const own = !!base.profile && !(fallback && base.source === 'default');
853
+ const profileName = own ? base.profile.name : fallback ? 'the published share' : null;
671
854
  const empty = { index: null, report: { clips: 0, bytes: 0, missing: 0, profile: profileName } };
672
- if (!base.profile && !fallback)
855
+ if (!own && !fallback)
673
856
  return { ...empty, report: { ...empty.report, profile: null } };
674
- const per = voicesPerLocale(project, base.profile ? (l) => resolveVoices(cfg, idx.profileId, store, voiceLocaleOf(project, l)).voices : sharedVoices(fallback));
675
- const fps = new Set(per.flatMap((x) => [x.voices.narrator, ...Object.values(x.voices.roles)]).filter(Boolean));
676
- const stepIds = new Set(Object.values(project.scenarios).flatMap((s) => s.steps.map((st) => st.id)));
677
- const latest = new Map();
678
- for (const [k, c] of Object.entries(idx.clips)) {
679
- if (!stepIds.has(c.stepId) || !fps.has(c.fp) || !FILE_RE.test(c.file) || !fs.existsSync(path.join(cache.clipsDir, c.file)))
680
- continue;
681
- const g = `${c.stepId}|${c.fp}|${c.locale}`;
682
- const prev = latest.get(g);
683
- if (!prev || prev[1].at < c.at)
684
- latest.set(g, [k, c]);
685
- }
857
+ const per = voicesPerLocale(project, own ? (l) => resolveVoices(cfg, selected, store, voiceLocaleOf(project, l), defaultProfile, pins, cache.officialCloud()).voices : sharedVoices(fallback));
686
858
  const clips = {};
687
- let bytes = 0;
688
- if (latest.size)
689
- fs.mkdirSync(path.join(outDir, 'voice'), { recursive: true });
690
- for (const [k, c] of latest.values()) {
691
- const dest = path.join(outDir, 'voice', c.file);
692
- if (!fs.existsSync(dest)) {
693
- fs.copyFileSync(path.join(cache.clipsDir, c.file), dest);
694
- bytes += c.bytes;
695
- }
696
- clips[k] = `voice/${c.file}`;
697
- }
698
- let missing = 0;
859
+ let bytes = 0, missing = 0;
699
860
  const byLocale = {};
861
+ const output = [];
700
862
  for (const { locale, project: p, voices } of per) {
863
+ const current = base.source === 'default'
864
+ ? resolveVoices(cfg, selected, store, voiceLocaleOf(project, locale), defaultProfile, pins, cache.officialCloud()).voices
865
+ : null;
866
+ const overrides = {};
701
867
  let n = 0;
702
868
  for (const sc of Object.values(p.scenarios))
703
869
  sc.steps.forEach((st, i) => {
704
870
  const line = spokenLine(st, st.caption, speakerRoleAt(p, sc.id, i + 1));
705
- const fp = voiceFingerprint(voices, line.role);
706
- if (!fp || !line.text)
871
+ const primary = voiceFingerprint(voices, line.role);
872
+ if (!primary || !line.text)
707
873
  return;
708
- // 自动字幕在网页里按语言生成:这一步有这种语言(没有 i18n 时任意语言)的音频就算有
874
+ const localFp = current ? voiceFingerprint(current, line.role) : null;
875
+ const previousFp = voiceFingerprint(voices, line.role, line.text);
876
+ const preferredFp = localFp && cache.localClipOf(clipKey(localFp, line.text)) ? localFp : null;
877
+ const candidates = [...new Set([preferredFp, previousFp, primary, localFp].filter((fp) => !!fp))];
709
878
  const localized = !!st.captionAuto && !st.say && !st.narrate && st.action.type !== 'card';
710
- const ok = localized ? [...latest.values()].some(([, c]) => c.stepId === st.id && c.fp === fp && (!locale || c.locale === locale)) : !!clips[clipKey(fp, line.text)];
711
- if (!ok)
879
+ // 自动字幕在网页里生成。按来源优先级找这种语言的最新片段,其他步骤严格匹配当前文字。
880
+ const chosen = [];
881
+ if (localized) {
882
+ const records = Object.entries(idx.clips)
883
+ .filter(([key, c]) => {
884
+ if (c.stepId !== st.id || (locale && c.locale !== locale) || typeof c.text !== 'string')
885
+ return false;
886
+ const expected = automaticCaption(st.captionAuto, c.locale);
887
+ // 先证明文字仍属于当前内容,再考虑来源优先级;未知语言、旧文字或错配缓存键均不能发布。
888
+ return expected !== null && c.text.replace(/\s+/g, ' ').trim() === expected.replace(/\s+/g, ' ').trim()
889
+ && key === clipKey(c.fp, expected) && !!cache.clipOf(key);
890
+ })
891
+ .sort((a, b) => b[1].at.localeCompare(a[1].at));
892
+ // 没有作者内容语言时,仍保留每种看板界面语言的自动字幕音频。
893
+ for (const lang of new Set(records.map(([, c]) => c.locale))) {
894
+ const sameLanguage = records.filter(([, c]) => c.locale === lang);
895
+ const clip = sameLanguage.find(([, c]) => c.fp === localFp && c.origin !== 'shared')
896
+ ?? sameLanguage.find(([, c]) => c.fp === voiceFingerprint(voices, line.role, c.text))
897
+ ?? sameLanguage.find(([, c]) => c.fp === localFp);
898
+ if (clip)
899
+ chosen.push(clip);
900
+ }
901
+ }
902
+ else {
903
+ for (const fp of candidates) {
904
+ const key = clipKey(fp, line.text);
905
+ const c = idx.clips[key];
906
+ if (c && cache.clipOf(key)) {
907
+ chosen.push([key, c]);
908
+ break;
909
+ }
910
+ }
911
+ }
912
+ if (!chosen.length) {
712
913
  n++;
914
+ return;
915
+ }
916
+ for (const [key, c] of chosen) {
917
+ if (!clips[key]) {
918
+ fs.mkdirSync(path.join(outDir, 'voice'), { recursive: true });
919
+ const dest = path.join(outDir, 'voice', c.file);
920
+ if (!fs.existsSync(dest)) {
921
+ fs.copyFileSync(path.join(cache.clipsDir, c.file), dest);
922
+ bytes += c.bytes;
923
+ }
924
+ clips[key] = `voice/${c.file}`;
925
+ }
926
+ // 不伪造缓存指纹:索引单独记下这一语言、角色和文字实际使用的声音。
927
+ if (c.fp !== primary)
928
+ overrides[clipKey(line.role ?? '', c.text)] = c.fp;
929
+ }
713
930
  });
714
931
  missing += n;
715
932
  if (locale)
716
933
  byLocale[locale] = { missing: n };
934
+ output.push({ locale, project: p, voices: { narrator: voices.narrator, roles: voices.roles, ...(Object.keys(overrides).length ? { overrides } : {}) } });
717
935
  }
718
- const head = per[0].voices;
936
+ const head = output[0].voices;
719
937
  const extra = project.i18n ? { locales: byLocale } : {};
720
938
  if (!Object.keys(clips).length)
721
939
  return { index: null, report: { ...empty.report, missing, ...extra } };
722
- const same = (x) => JSON.stringify([x.narrator, x.roles]) === JSON.stringify([head.narrator, head.roles]);
723
- const locales = Object.fromEntries(per.filter((x) => x.locale && x.locale !== project.i18n?.default && !same(x.voices)).map((x) => [x.locale, { narrator: x.voices.narrator, roles: x.voices.roles }]));
940
+ const same = (x) => JSON.stringify(x) === JSON.stringify(head);
941
+ const locales = Object.fromEntries(output.filter((x) => x.locale && x.locale !== project.i18n?.default && !same(x.voices)).map((x) => [x.locale, x.voices]));
724
942
  return {
725
- index: { narrator: head.narrator, roles: head.roles, clips, ...(Object.keys(locales).length ? { locales } : {}) },
943
+ index: { ...head, clips, ...(Object.keys(locales).length ? { locales } : {}) },
726
944
  report: { clips: Object.keys(clips).length, bytes, missing, profile: profileName, ...extra },
727
945
  };
728
946
  }