@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.
@@ -1,30 +1,40 @@
1
1
  /**
2
- * 朗读(D74)的看板接口。写接口都经 dev.ts 的 guardWrite(Origin + 本机令牌 + JSON)。
2
+ * 朗读(D74 / D85)的看板接口。写接口都经 dev.ts 的 guardWrite(Origin + 本机令牌 + JSON)。
3
3
  *
4
4
  * 全局(本机):
5
5
  * - GET /__joplo/voice/profiles → { profiles: PublicProfile[], file }(不含 Key;file = 本机存储文件,所有项目共用)
6
- * - PUT /__joplo/voice/profiles/:id|new { profile, key? } → { profile, profiles }(key:省略 = 不改,null / '' = 删掉)
7
- * - DELETE /__joplo/voice/profiles/:id → { profiles }(自建的删除,预设恢复默认)
8
- * 保存、删除成功后调 opts.profilesChanged:dev.ts 推 joplo:voice { profilesChanged },打开着的看板重新取自己项目的声音状态
9
- * (Key 是否保存、音色、声音指纹都可能变了)。
10
- * - POST /__joplo/voice/test { id?, profile?, key?, text? } → { ok: true, audio: data URL, bytes, contentType }
11
- * | { ok: false, error: { code, message, hint? } }(hint = 建议的返回内容与字段路径)
6
+ * 预设(cloud、openai、elevenlabs)在前,本机旧的 profile(unsupported: true)在后。
7
+ * - PUT /__joplo/voice/profiles/:id { profile?: { voice?, model?, style? }, key? } → { profile, profiles }
8
+ * 只能改预设(「管理密钥」与浮层里换旁白音色);key:省略 = 不改,null / '' = 删掉。
9
+ * 新建(:id = new)与改旧的 profile 返回 400 INVALID(D85:不再提供自定义接口)。
10
+ * - DELETE /__joplo/voice/profiles/:id → { profiles }(预设恢复默认,旧的 profile 删除)
11
+ * 保存、删除成功后调 opts.profilesChanged:dev.ts 推 joplo:voice { profilesChanged },打开着的看板重新取自己项目的声音状态。
12
+ * - POST /__joplo/voice/test { id, key? } → { ok: true, audio: data URL, bytes, contentType } | { ok: false, error: { code, message } }
13
+ * (OpenAI / ElevenLabs 的 Key 测试;cloud 用样音试听,不走这里)
12
14
  * 项目:
13
- * - GET /__joplo/p/:id/voice → VoiceState
14
- * - PUT /__joplo/p/:id/voice { profileId | null } → VoiceState(看板里选的,记在 .joplo/voice/index.json)
15
- * - POST /__joplo/p/:id/voice/clip { locale, segment: { stepId, text, role } } → { key, url }(边放边生成一段;与批量生成共用 inflight,同一段并发只生成一次)
15
+ * - GET /__joplo/p/:id/voice[?refresh=1] → VoiceState(refresh=1 时重新问一次云端额度)
16
+ * - PUT /__joplo/p/:id/voice { profileId | null } → VoiceState(看板里选的,记在 .joplo/voice/index.json,chosen: true)
17
+ * - POST /__joplo/p/:id/voice/clip { locale, segment: { stepId, text, role } } → { key, url }(边放边生成一段;与批量生成共用 inflight)
18
+ * 只给 OpenAI / ElevenLabs(用户自己的 Key):Joplo Cloud 朗读返回 409 CLOUD_GENERATE_ONLY,不请求云端
16
19
  * - POST /__joplo/p/:id/voice/generate { locale, segments: [{ stepId, text, role }] } → { summary, state };进度推 joplo:voice
17
20
  * - GET /__joplo/p/:id/voice/clips/:file → 音频
21
+ *
22
+ * 托管朗读的状态(D85):opts.cloud(CLI 注入的 bridge.voice)→ status() 记在内存 60 秒(cloudInfo)→ VoiceState.cloud(已登录、额度、用量页)。
23
+ * 已登录且项目没选过来源时默认用 cloud(resolveVoices 的 fallback)。每段 cloud 合成成功后用响应头 X-Joplo-Chars-Remaining 更新内存里的
24
+ * totalRemainingChars 并推送状态;402 时记下 exhausted(需要 / 剩余),直到重新取到的额度大于 0。
25
+ * 云端连不上或旧云端 404 时仍按 cloud 指纹找已有的音频(离线也能播已生成的),但生成直接返回 TTS_UNAVAILABLE,不请求云端。
18
26
  */
19
27
  import fs from 'node:fs';
20
28
  import os from 'node:os';
21
29
  import path from 'node:path';
22
- import { AUDIO_TYPES, ProfileStore, voiceLocaleOf, VoiceCache, VoiceError, normalizeProfile, resolveVoices, synthesize } from "./voice.js";
30
+ import { AUDIO_TYPES, ProfileStore, voiceLocaleOf, VoiceCache, VoiceError, resolveVoices, synthesize } from "./voice.js";
23
31
  /** 请求里的内容语言:必须是项目声明的语言;没有 i18n 或不合法时为 null(按原来的方式处理)。 */
24
32
  function contentLocaleOf(project, v) {
25
33
  return typeof v === 'string' && project?.i18n?.locales.includes(v) ? v : null;
26
34
  }
27
35
  const MAX_SEGMENTS = 2000;
36
+ /** 云端额度与音色表在内存里放多久(看板打开浮层时可以 refresh=1 立刻重取)。 */
37
+ const CLOUD_TTL_MS = 60_000;
28
38
  let lastRev = 0;
29
39
  const nextRev = () => (lastRev = Math.max(lastRev + 1, Date.now() * 1000));
30
40
  /** 用户目录写成 ~(看板显示 profile 存在哪里;不在用户目录下时原样)。 */
@@ -32,6 +42,7 @@ export function tildify(file, home = os.homedir()) {
32
42
  return home && (file === home || file.startsWith(home + path.sep)) ? '~' + file.slice(home.length) : file;
33
43
  }
34
44
  const MAX_TEXT = 2000;
45
+ const num = (v) => (Number.isSafeInteger(v) && v >= 0 ? v : null);
35
46
  export class VoiceHub {
36
47
  opts;
37
48
  store;
@@ -44,21 +55,87 @@ export class VoiceHub {
44
55
  this.inflight.set(projectId, (m = new Map()));
45
56
  return m;
46
57
  }
58
+ /** 托管朗读状态(内存,CLOUD_TTL_MS):status = null 表示问云端时出错(当作连不上)。 */
59
+ cloudCache = null;
60
+ exhausted = null;
47
61
  constructor(home, opts) {
48
62
  this.opts = opts;
49
- this.store = new ProfileStore(home, opts.env ?? process.env);
63
+ this.store = new ProfileStore(home, opts.env ?? process.env, { catalog: () => this.liveInfo() });
64
+ }
65
+ now = () => (this.opts.now ?? Date.now)();
66
+ liveInfo() {
67
+ const s = this.cloudCache?.status;
68
+ return s?.signedIn && s.voice ? s.voice : null;
69
+ }
70
+ /** 托管朗读的状态:内存里有、没过期就直接用;否则问一次 bridge(并发的请求共用一次)。出错不抛,当作连不上。 */
71
+ async cloudStatus(refresh = false) {
72
+ if (!this.opts.cloud)
73
+ return null;
74
+ const c = this.cloudCache;
75
+ if (c?.pending)
76
+ return c.pending;
77
+ if (c && !refresh && this.now() - c.at < CLOUD_TTL_MS)
78
+ return c.status;
79
+ const pending = this.opts.cloud
80
+ .status()
81
+ .then((s) => (s && typeof s === 'object' && typeof s.signedIn === 'boolean' ? s : null))
82
+ .catch(() => null);
83
+ this.cloudCache = { at: c?.at ?? 0, status: c?.status ?? null, pending };
84
+ const status = await pending;
85
+ this.cloudCache = { at: this.now(), status };
86
+ if (status?.signedIn && status.voice) {
87
+ this.store.rememberCloudCatalog(status.voice);
88
+ // 额度刷新后有字了(例如买了加油包):解除“额度不够”
89
+ if (status.voice.quota.totalRemainingChars > 0)
90
+ this.exhausted = null;
91
+ }
92
+ return status;
93
+ }
94
+ cloudView(status) {
95
+ if (!this.opts.cloud)
96
+ return null;
97
+ if (!status)
98
+ return { signedIn: true, server: null, loginCommand: null, available: false, quota: null, usageUrl: null, exhausted: this.exhausted };
99
+ if (!status.signedIn)
100
+ return { signedIn: false, server: status.server, loginCommand: status.loginCommand, available: false, quota: null, usageUrl: `${status.server}/usage`, exhausted: null };
101
+ return { signedIn: true, server: status.server, loginCommand: null, available: !!status.voice, quota: status.voice?.quota ?? null, usageUrl: `${status.server}/usage`, exhausted: this.exhausted };
102
+ }
103
+ /** 没选过来源时的默认(D85):已登录用 cloud,否则浏览器朗读。云端暂时连不上时仍算已登录(音色用本机记下的)。 */
104
+ fallbackOf(status) {
105
+ if (!this.opts.cloud)
106
+ return null;
107
+ return !status || status.signedIn ? 'cloud' : null;
108
+ }
109
+ /** 每段 cloud 合成成功:剩余字数以响应头为准(不在本地估算)。 */
110
+ receipt(r) {
111
+ const s = this.cloudCache?.status;
112
+ if (s?.signedIn && s.voice && r.remaining !== null)
113
+ s.voice.quota = { ...s.voice.quota, totalRemainingChars: r.remaining };
114
+ if (r.remaining === null || r.remaining > 0)
115
+ this.exhausted = null;
116
+ }
117
+ /** 402:记下需要 / 剩余,剩余字数也以 402 里的为准。 */
118
+ quotaHit(data) {
119
+ this.exhausted = data;
120
+ const s = this.cloudCache?.status;
121
+ if (s?.signedIn && s.voice && data.remainingChars !== null)
122
+ s.voice.quota = { ...s.voice.quota, totalRemainingChars: data.remainingChars };
50
123
  }
51
124
  profiles = () => this.store.list().map((p) => this.store.publicOf(p));
52
125
  error(ctx, e) {
53
- if (e instanceof VoiceError)
54
- return ctx.send(e.code === 'NOT_FOUND' ? 404 : e.code === 'BUSY' ? 409 : 400, { error: { code: e.code, message: e.message, ...(e.hint ? { hint: e.hint } : {}) } });
126
+ if (e instanceof VoiceError) {
127
+ const status = e.code === 'NOT_FOUND' ? 404 : e.code === 'BUSY' ? 409 : e.code === 'TTS_QUOTA_EXCEEDED' ? 402 : e.code === 'AUTH_REQUIRED' || e.code === 'AUTH_EXPIRED' ? 401 : e.code === 'RATE_LIMITED' ? 429 : e.code === 'TTS_UNAVAILABLE' || e.code === 'NETWORK' ? 503 : 400;
128
+ return ctx.send(status, { error: { code: e.code, message: e.message, ...(e.data ? { data: e.data } : {}) } });
129
+ }
55
130
  throw e;
56
131
  }
57
132
  /** /__joplo/voice/<rest>;不认识的路径返回 false。 */
58
133
  async handleGlobal(rest, req, ctx) {
59
134
  const method = req.method ?? 'GET';
60
- if (rest === 'profiles' && method === 'GET')
135
+ if (rest === 'profiles' && method === 'GET') {
136
+ await this.cloudStatus();
61
137
  return ctx.send(200, { profiles: this.profiles(), file: tildify(this.store.file) }), true;
138
+ }
62
139
  const pm = /^profiles\/([a-z0-9][a-z0-9_-]{0,39}|new)$/.exec(rest);
63
140
  if (pm && method === 'PUT') {
64
141
  if (!ctx.guardWrite())
@@ -100,40 +177,42 @@ export class VoiceHub {
100
177
  const body = (b.body ?? {});
101
178
  try {
102
179
  const saved = typeof body.id === 'string' ? this.store.get(body.id) : null;
103
- if (typeof body.id === 'string' && !saved)
104
- throw new VoiceError('NOT_FOUND', `Unknown voice profile: ${body.id}`);
105
- // 草稿(还没保存的表单)优先;没传 Key 时用已保存的 / 环境变量里的
106
- const draft = body.profile !== undefined ? { ...(saved ?? { id: 'draft' }), ...normalizeProfile(body.profile, saved ?? undefined), id: saved?.id ?? 'draft', ...(saved?.preset ? { preset: saved.preset } : {}) } : saved;
107
- if (!draft)
108
- throw new VoiceError('INVALID', 'Pass id or profile');
109
- const key = typeof body.key === 'string' && body.key.trim() ? body.key.trim() : this.store.keyOf(saved ? { ...draft, key: saved.key } : draft);
110
- if (!key && draft.kind !== 'http')
180
+ if (!saved)
181
+ throw new VoiceError('NOT_FOUND', `Unknown voice profile: ${String(body.id)}`);
182
+ if (saved.kind !== 'openai' && saved.kind !== 'elevenlabs')
183
+ throw new VoiceError('INVALID', 'Only OpenAI and ElevenLabs keys can be tested here');
184
+ const key = typeof body.key === 'string' && body.key.trim() ? body.key.trim() : this.store.keyOf(saved);
185
+ if (!key)
111
186
  throw new VoiceError('NO_KEY', 'No API key: paste one, or set the environment variable shown next to the key field');
112
187
  const text = typeof body.text === 'string' && body.text.trim() ? body.text.trim().slice(0, 200) : 'Hello, this is the Joplo narrator.';
113
- const a = await synthesize(draft, key, text, draft.voice, { fetch: this.opts.fetch });
188
+ const a = await synthesize(saved, key, text, saved.voice, { fetch: this.opts.fetch });
114
189
  ctx.send(200, { ok: true, contentType: a.contentType, bytes: a.bytes.length, audio: `data:${a.contentType};base64,${a.bytes.toString('base64')}` });
115
190
  }
116
191
  catch (e) {
117
192
  if (e instanceof VoiceError && e.code !== 'NOT_FOUND')
118
- return ctx.send(200, { ok: false, error: { code: e.code, message: e.message, ...(e.hint ? { hint: e.hint } : {}) } }), true;
193
+ return ctx.send(200, { ok: false, error: { code: e.code, message: e.message } }), true;
119
194
  this.error(ctx, e);
120
195
  }
121
196
  return true;
122
197
  }
123
198
  return false;
124
199
  }
125
- state(projectId, dir, project) {
200
+ /** 项目的声音状态(看板浮层、播放时找音频)。refresh:重新问一次云端额度。 */
201
+ async state(projectId, dir, project, refresh = false) {
202
+ const status = await this.cloudStatus(refresh);
203
+ const fallback = this.fallbackOf(status);
126
204
  const cache = new VoiceCache(dir);
127
- const idx = cache.read();
128
- const r = resolveVoices(project?.voiceConfig, idx.profileId, this.store);
129
- const per = Object.fromEntries((project?.i18n?.locales ?? []).map((l) => [l, resolveVoices(project?.voiceConfig, idx.profileId, this.store, voiceLocaleOf(project, l))]));
205
+ const selected = cache.selection();
206
+ const pins = cache.pins();
207
+ const r = resolveVoices(project?.voiceConfig, selected, this.store, null, fallback, pins, cache.officialCloud());
208
+ const per = Object.fromEntries((project?.i18n?.locales ?? []).map((l) => [l, resolveVoices(project?.voiceConfig, selected, this.store, voiceLocaleOf(project, l), fallback, pins, cache.officialCloud())]));
130
209
  const all = Object.values(per);
131
210
  const cur = cache.current({ narrator: r.voices.narrator, roles: r.voices.roles }, all.flatMap((x) => [x.voices.narrator, ...Object.values(x.voices.roles)]).filter((x) => !!x));
132
211
  const job = this.jobs.get(projectId);
133
212
  const enc = encodeURIComponent;
134
213
  return {
135
214
  rev: nextRev(),
136
- selected: idx.profileId,
215
+ selected: selected ?? null,
137
216
  source: r.source,
138
217
  missing: r.missing,
139
218
  profile: r.profile ? this.store.publicOf(r.profile) : null,
@@ -144,13 +223,39 @@ export class VoiceHub {
144
223
  failures: cur.failures,
145
224
  generating: job ? { done: job.done, total: job.total, failed: job.failed } : null,
146
225
  ...(all.length ? { byLocale: Object.fromEntries(Object.entries(per).map(([l, x]) => [l, { narrator: x.narrator, roles: x.roles, voices: x.voices }])) } : {}),
226
+ cloud: this.cloudView(status),
147
227
  };
148
228
  }
229
+ emitState(projectId, dir, project) {
230
+ void this.state(projectId, dir, project).then((s) => this.opts.emit(projectId, s), () => undefined);
231
+ }
232
+ /** 生成用的声音:与 state() 同一套默认来源。 */
233
+ async resolveFor(dir, project, content) {
234
+ const fallback = this.fallbackOf(await this.cloudStatus());
235
+ const cache = new VoiceCache(dir);
236
+ return resolveVoices(project?.voiceConfig, cache.selection(), this.store, voiceLocaleOf(project, content), fallback, cache.pins(), cache.officialCloud());
237
+ }
238
+ /**
239
+ * cloud 现在能不能生成(P1-4):没登录 → AUTH_REQUIRED;云端连不上或旧云端没有朗读(404)→ TTS_UNAVAILABLE。
240
+ * 这时不请求云端(否则每一段都要经 CLI 重试好几秒),已有的音频照常按 cloud 指纹播放与打包。能生成时返回 null。
241
+ */
242
+ cloudBlocked() {
243
+ const s = this.cloudCache?.status;
244
+ if (s && !s.signedIn)
245
+ return { code: 'AUTH_REQUIRED', message: `Joplo Cloud narration needs a Joplo account. Run ${s.loginCommand}` };
246
+ if (!s?.signedIn || !s.voice)
247
+ return { code: 'TTS_UNAVAILABLE', message: 'Joplo Cloud narration is not available right now (the cloud cannot be reached, or it does not offer narration yet). Steps without audio use the browser voice; try again later' };
248
+ return null;
249
+ }
250
+ /** cloud 请求的内容语言(D84):项目写了 locales 时是当前内容语言(没传时是默认语言);没写时不带,由云端按文字判断。 */
251
+ speechLocaleOf(project, content) {
252
+ return project?.i18n ? (content ?? project.i18n.default) : null;
253
+ }
149
254
  /** /__joplo/p/:id/voice[/…];不认识的路径返回 false。 */
150
255
  async handleProject(projectId, dir, project, rest, req, res, ctx) {
151
256
  const method = req.method ?? 'GET';
152
257
  if (rest === '' && method === 'GET')
153
- return ctx.send(200, this.state(projectId, dir, project)), true;
258
+ return ctx.send(200, await this.state(projectId, dir, project, /[?&]refresh=1(&|$)/.test(req.url ?? ''))), true;
154
259
  if (rest === '' && method === 'PUT') {
155
260
  if (!ctx.guardWrite())
156
261
  return true;
@@ -161,7 +266,7 @@ export class VoiceHub {
161
266
  if (id !== null && (typeof id !== 'string' || !this.store.get(id)))
162
267
  return ctx.send(400, { error: { code: 'USAGE', message: `Unknown voice profile: ${String(id)}` } }), true;
163
268
  new VoiceCache(dir).select(id);
164
- const st = this.state(projectId, dir, project);
269
+ const st = await this.state(projectId, dir, project);
165
270
  this.opts.emit(projectId, st);
166
271
  return ctx.send(200, st), true;
167
272
  }
@@ -180,7 +285,12 @@ export class VoiceHub {
180
285
  return ctx.send(409, { error: { code: 'BUSY', message: 'Narration is already being generated for this project' } }), true;
181
286
  const cache = new VoiceCache(dir);
182
287
  const content = contentLocaleOf(project, body.contentLocale);
183
- const resolved = resolveVoices(project?.voiceConfig, cache.read().profileId, this.store, voiceLocaleOf(project, content));
288
+ const resolved = await this.resolveFor(dir, project, content);
289
+ const blocked = resolved.profile?.kind === 'cloud' ? this.cloudBlocked() : null;
290
+ if (blocked) {
291
+ const summary = { total: segs.length, generated: 0, skipped: 0, failed: [], error: blocked };
292
+ return ctx.send(200, { summary, state: await this.state(projectId, dir, project) }), true;
293
+ }
184
294
  const job = { done: 0, total: segs.length, failed: 0, abort: new AbortController() };
185
295
  this.jobs.set(projectId, job);
186
296
  let summary;
@@ -189,16 +299,22 @@ export class VoiceHub {
189
299
  fetch: this.opts.fetch,
190
300
  signal: job.abort.signal,
191
301
  inflight: this.inflightOf(projectId),
302
+ cloud: this.opts.cloud,
303
+ project: project?.name ?? null,
304
+ speechLocale: this.speechLocaleOf(project, content),
305
+ onCloud: (r) => this.receipt(r),
192
306
  onProgress: (done, total, failed) => {
193
307
  Object.assign(job, { done, total, failed });
194
- this.opts.emit(projectId, this.state(projectId, dir, project));
308
+ this.emitState(projectId, dir, project);
195
309
  },
196
310
  });
197
311
  }
198
312
  finally {
199
313
  this.jobs.delete(projectId);
200
314
  }
201
- const st = this.state(projectId, dir, project);
315
+ if (summary.quota)
316
+ this.quotaHit(summary.quota);
317
+ const st = await this.state(projectId, dir, project);
202
318
  this.opts.emit(projectId, st);
203
319
  return ctx.send(200, { summary, state: st }), true;
204
320
  }
@@ -215,19 +331,31 @@ export class VoiceHub {
215
331
  return ctx.send(400, { error: { code: 'USAGE', message: 'segment must be { stepId, text, role }' } }), true;
216
332
  const cache = new VoiceCache(dir);
217
333
  const content = contentLocaleOf(project, body.contentLocale);
218
- const resolved = resolveVoices(project?.voiceConfig, cache.read().profileId, this.store, voiceLocaleOf(project, content));
334
+ const resolved = await this.resolveFor(dir, project, content);
219
335
  const plan = cache.plan(seg, resolved);
220
336
  if (!plan)
221
337
  return ctx.send(400, { error: { code: 'INVALID', message: 'No voice provider is selected for this project' } }), true;
222
- const p = cache.generateOne(seg, content ?? (typeof body.locale === 'string' ? body.locale.slice(0, 20) : 'en'), resolved, this.store, { fetch: this.opts.fetch, inflight: this.inflightOf(projectId) });
338
+ // Joplo Cloud 朗读不在播放时现场生成(会花用户的字数):只有「生成缺少的音频」或 joplo voice 才请求云端;缺音频的步骤用浏览器朗读
339
+ if (resolved.profile?.kind === 'cloud')
340
+ return ctx.send(409, { error: { code: 'CLOUD_GENERATE_ONLY', message: 'Joplo Cloud narration is generated only with Generate missing audio (or npx joplo voice); this step uses the browser voice' } }), true;
341
+ const p = cache.generateOne(seg, content ?? (typeof body.locale === 'string' ? body.locale.slice(0, 20) : 'en'), resolved, this.store, {
342
+ fetch: this.opts.fetch,
343
+ inflight: this.inflightOf(projectId),
344
+ cloud: this.opts.cloud,
345
+ project: project?.name ?? null,
346
+ speechLocale: this.speechLocaleOf(project, content),
347
+ onCloud: (r) => this.receipt(r),
348
+ });
223
349
  try {
224
350
  const r = await p;
225
351
  if (r.generated)
226
- this.opts.emit(projectId, this.state(projectId, dir, project));
352
+ this.emitState(projectId, dir, project);
227
353
  return ctx.send(200, { key: r.key, url: `/__joplo/p/${encodeURIComponent(projectId)}/voice/clips/${r.file}` }), true;
228
354
  }
229
355
  catch (e) {
230
- this.opts.emit(projectId, this.state(projectId, dir, project));
356
+ if (e instanceof VoiceError && e.code === 'TTS_QUOTA_EXCEEDED')
357
+ this.quotaHit({ neededChars: num(e.data?.neededChars), remainingChars: num(e.data?.remainingChars) });
358
+ this.emitState(projectId, dir, project);
231
359
  return this.error(ctx, e), true;
232
360
  }
233
361
  }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * `joplo voice`(D74 / D85):在终端里生成缺少的朗读音频,与看板的「生成缺少的音频」同一套缓存与规则,给 Agent 和脚本用。
3
+ *
4
+ * - 范围:每个功能选定方案(feature.pick)的全部场景;项目写了 locales 时每种内容语言各一遍(D84,按 resolveVoices(…, 语言) 选音色),
5
+ * 可以用 locales 只做其中几种。朗读文字与 build 打包时算片段键的文字相同(字幕用 step.caption;自动字幕在看板里按界面语言生成,
6
+ * 这里用编译出的字幕)。
7
+ * - 声音来源:与看板相同——config.voice.profile > 看板里选的 > 没选过时已登录用 Joplo Cloud 朗读(defaultProfile)。
8
+ * 没有来源、来源不再支持、缺 Key 时抛 VoiceError(NO_SOURCE / UNSUPPORTED / NO_KEY),CLI 给出错误码与换用提示。
9
+ * - dryRun:只算这次要生成几段、约多少字(estimateVoice,Array.from 计字),不请求。
10
+ * - cloud 每段成功后用响应头的剩余字数更新 quota;402 时停止(已生成的保留),结果里的 quota 记需要 / 剩余,CLI 以 TTS_QUOTA_EXCEEDED 结束。
11
+ */
12
+ import type { Project } from '@joplo-app/core';
13
+ import type { CloudVoiceBridge, VoiceQuota } from './cloud.js';
14
+ import { type Segment } from './voice.js';
15
+ export type VoiceRunOptions = {
16
+ projectDir: string;
17
+ /** 编译出的 IR(CLI 用 check 的结果)。 */
18
+ project: Project;
19
+ /** 本机目录(缺省 JOPLO_HOME 或 ~/.joplo)。 */
20
+ home?: string;
21
+ /** 托管朗读(CLI 的 cloud bridge 的 voice)。 */
22
+ cloud?: CloudVoiceBridge;
23
+ dryRun?: boolean;
24
+ /** 只做这几种内容语言(必须是项目声明的);缺省全部。 */
25
+ locales?: string[];
26
+ onProgress?: (line: string) => void;
27
+ /** 测试:OpenAI / ElevenLabs 的 fetch。 */
28
+ fetch?: (url: string, init?: RequestInit) => Promise<Response>;
29
+ };
30
+ export type VoiceRunLocale = {
31
+ locale: string | null;
32
+ segments: number;
33
+ missing: number;
34
+ chars: number;
35
+ generated: number;
36
+ skipped: number;
37
+ failed: {
38
+ stepId: string;
39
+ message: string;
40
+ }[];
41
+ };
42
+ export type VoiceRunResult = {
43
+ profile: {
44
+ id: string;
45
+ name: string;
46
+ kind: string;
47
+ } | null;
48
+ source: 'config' | 'board' | 'default' | null;
49
+ dryRun: boolean;
50
+ locales: VoiceRunLocale[];
51
+ /** 合计:要生成的段数与字数(dryRun 时是估算;否则是这次开始前缺的)、生成了几段、失败几段。 */
52
+ total: {
53
+ segments: number;
54
+ missing: number;
55
+ chars: number;
56
+ generated: number;
57
+ failed: number;
58
+ };
59
+ /** cloud 的额度(已登录、云端给了 /api/v1/voice 时);生成后是响应头里最后一次的剩余。 */
60
+ quota: VoiceQuota | null;
61
+ usageUrl: string | null;
62
+ /** 额度不够(402)时:需要 / 剩余;还有几段没生成。 */
63
+ exhausted: {
64
+ neededChars: number | null;
65
+ remainingChars: number | null;
66
+ remainingSteps: number;
67
+ } | null;
68
+ };
69
+ /** 选定方案的全部场景里,每一步要读的段(文字为空的跳过)。 */
70
+ export declare function projectSegments(project: Project): Segment[];
71
+ export declare function generateProjectVoice(opts: VoiceRunOptions): Promise<VoiceRunResult>;
@@ -0,0 +1,98 @@
1
+ import { localizeProject, speakerRoleAt, spokenLine } from '@joplo-app/core';
2
+ import { joploHome } from "./home.js";
3
+ import { ProfileStore, UNSUPPORTED_MESSAGE, VoiceCache, VoiceError, estimateVoice, resolveVoices, voiceLocaleOf } from "./voice.js";
4
+ /** 选定方案的全部场景里,每一步要读的段(文字为空的跳过)。 */
5
+ export function projectSegments(project) {
6
+ const picked = new Set(Object.values(project.features ?? {}).map((f) => f.pick).filter((x) => !!x));
7
+ const out = [];
8
+ for (const sc of Object.values(project.scenarios)) {
9
+ const fid = project.options[sc.optionId]?.featureId;
10
+ const pick = fid ? project.features?.[fid]?.pick : null;
11
+ // 选定方案的 id 可能是 “功能.方案” 或只有方案名:两种都认
12
+ if (!(picked.has(sc.optionId) || (pick && sc.optionId === `${fid}.${pick}`)))
13
+ continue;
14
+ sc.steps.forEach((st, i) => {
15
+ const line = spokenLine(st, st.caption, speakerRoleAt(project, sc.id, i + 1));
16
+ if (line.text)
17
+ out.push({ stepId: st.id, text: line.text, role: line.role });
18
+ });
19
+ }
20
+ return out;
21
+ }
22
+ export async function generateProjectVoice(opts) {
23
+ const status = opts.cloud ? await opts.cloud.status().catch(() => null) : null;
24
+ const live = status?.signedIn && status.voice ? status.voice : null;
25
+ const store = new ProfileStore(opts.home ?? joploHome(), process.env, { catalog: () => live });
26
+ if (live)
27
+ store.rememberCloudCatalog(live);
28
+ // 没选过来源时:已登录(含云端暂时连不上)用 cloud,与看板一致
29
+ const fallback = opts.cloud && (!status || status.signedIn) ? 'cloud' : null;
30
+ const cache = new VoiceCache(opts.projectDir);
31
+ const selected = cache.selection();
32
+ const pins = cache.pins();
33
+ const project = opts.project;
34
+ const base = resolveVoices(project.voiceConfig, selected, store, null, fallback, pins, cache.officialCloud());
35
+ const usageUrl = status ? `${status.server}/usage` : null;
36
+ if (!base.profile) {
37
+ if (base.missing)
38
+ throw new VoiceError('NOT_FOUND', `joplo.config.ts asks for voice profile "${base.missing}", which is not set up on this computer. Use cloud, openai or elevenlabs`);
39
+ const login = status && !status.signedIn ? ` Sign in for Joplo Cloud narration: ${status.loginCommand}.` : '';
40
+ throw new VoiceError('INVALID', `No voice source is selected for this project, so steps use the browser voice.${login} Or choose OpenAI / ElevenLabs in the board (Voice).`);
41
+ }
42
+ if (base.profile.unsupported)
43
+ throw new VoiceError('UNSUPPORTED', UNSUPPORTED_MESSAGE(base.profile.name));
44
+ if (base.profile.kind !== 'cloud' && !store.keyOf(base.profile))
45
+ throw new VoiceError('NO_KEY', `No API key for ${base.profile.name}. Add one in the board (Voice → Manage keys) or set ${base.profile.kind === 'openai' ? 'OPENAI_API_KEY' : 'ELEVENLABS_API_KEY'}`);
46
+ if (base.profile.kind === 'cloud' && status && !status.signedIn)
47
+ throw new VoiceError('AUTH_REQUIRED', `Joplo Cloud narration needs a Joplo account. Run ${status.loginCommand}`);
48
+ // 云端连不上或旧云端没有朗读(404):不发请求(dry-run 照常估算)
49
+ if (base.profile.kind === 'cloud' && !live && !opts.dryRun)
50
+ throw new VoiceError('TTS_UNAVAILABLE', 'Joplo Cloud narration is not available right now (the cloud cannot be reached, or it does not offer narration yet). Try again later; steps without audio use the browser voice');
51
+ const declared = project.i18n?.locales ?? [];
52
+ const bad = (opts.locales ?? []).filter((l) => !declared.includes(l));
53
+ if (bad.length)
54
+ throw new VoiceError('INVALID', declared.length ? `Unknown content language: ${bad.join(', ')} (this project has ${declared.join(', ')})` : 'This project has no content languages (config locales); run joplo voice without --locale');
55
+ const locales = project.i18n ? (opts.locales?.length ? opts.locales : declared) : [null];
56
+ let quota = live?.quota ? { ...live.quota } : null;
57
+ const result = { profile: { id: base.profile.id, name: base.profile.name, kind: base.profile.kind }, source: base.source, dryRun: !!opts.dryRun, locales: [], total: { segments: 0, missing: 0, chars: 0, generated: 0, failed: 0 }, quota, usageUrl, exhausted: null };
58
+ for (const locale of locales) {
59
+ const p = locale ? localizeProject(project, locale) : project;
60
+ const resolved = resolveVoices(project.voiceConfig, selected, store, voiceLocaleOf(project, locale), fallback, cache.pins(), cache.officialCloud());
61
+ const segments = projectSegments(p);
62
+ const est = estimateVoice(segments, resolved, cache);
63
+ const row = { locale, segments: segments.length, missing: est.steps, chars: est.chars, generated: 0, skipped: 0, failed: [] };
64
+ result.locales.push(row);
65
+ result.total.segments += segments.length;
66
+ result.total.missing += est.steps;
67
+ result.total.chars += est.chars;
68
+ if (opts.dryRun || !est.steps || result.exhausted)
69
+ continue;
70
+ opts.onProgress?.(`Generating ${est.steps} clip(s)${locale ? ` for ${locale}` : ''} with ${base.profile.name} (about ${est.chars} characters)...`);
71
+ const summary = await cache.generate(segments, locale ?? 'en', resolved, store, {
72
+ cloud: opts.cloud,
73
+ fetch: opts.fetch,
74
+ project: project.name,
75
+ speechLocale: project.i18n ? locale : null,
76
+ onCloud: (r) => {
77
+ if (quota && r.remaining !== null)
78
+ quota = { ...quota, totalRemainingChars: r.remaining };
79
+ },
80
+ });
81
+ row.generated = summary.generated;
82
+ row.skipped = summary.skipped;
83
+ row.failed = summary.failed;
84
+ result.total.generated += summary.generated;
85
+ result.total.failed += summary.failed.length;
86
+ if (summary.quota) {
87
+ if (quota && summary.quota.remainingChars !== null)
88
+ quota = { ...quota, totalRemainingChars: summary.quota.remainingChars };
89
+ result.exhausted = { ...summary.quota, remainingSteps: 0 };
90
+ }
91
+ else if (summary.error)
92
+ throw new VoiceError(summary.error.code, summary.error.message);
93
+ }
94
+ if (result.exhausted)
95
+ result.exhausted.remainingSteps = result.total.missing - result.total.generated - result.total.failed;
96
+ result.quota = quota;
97
+ return result;
98
+ }