@joplo-app/server 0.2.16 → 0.2.17

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/build.js CHANGED
@@ -19,12 +19,12 @@ import os from 'node:os';
19
19
  import path from 'node:path';
20
20
  import tailwindcss from '@tailwindcss/vite';
21
21
  import { build as viteBuild, createServer } from 'vite';
22
- import { stepIdentity, hasScope, JoploError, orderedFeatures, resolveScope, scopeProject } from '@joplo-app/core';
22
+ import { stepIdentity, hasScope, JoploError, orderedFeatures, pruneMessages, resolveScope, scopeProject } from '@joplo-app/core';
23
23
  import { compileProject } from "./project.js";
24
24
  import { joploProjectPlugin, kitAliases, locateWebAssets, realProjectDir } from "./vite-shared.js";
25
25
  import { subsetSiteFonts } from "./site-fonts.js";
26
26
  import { joploHome } from "./home.js";
27
- import { ProfileStore, bundleVoice } from "./voice.js";
27
+ import { ProfileStore, bundleVoice, reuseSharedVoice } from "./voice.js";
28
28
  /** 发布站只需要的 IR:去掉创作侧字段(publish 模式下它们本来就为空)。层级、镜头、角色(说话人、过渡卡、层级的 role)与 featureIds 顺序属于演示,保留(D43 / D56 / D61)。 */
29
29
  export function publishPayload(project, home) {
30
30
  // voiceConfig(D74):profile 名与音色属于作者本机的设置,发布站只需要 build 写进的 voiceIndex
@@ -35,7 +35,9 @@ export function publishPayload(project, home) {
35
35
  const { caseIds: _ci, ...sr } = s;
36
36
  return [id, { ...sr, caseIds: [], steps: s.steps.map(({ ruleIds: _ri, key: _key, ...st }) => ({ ...st, ruleIds: [] })) }];
37
37
  }));
38
- return { project: { ...rest, features, options, scenarios }, home: home && project.routes[home] ? home : null };
38
+ const out = { ...rest, features, options, scenarios };
39
+ // 译文(D84)在去掉创作侧字段之后再裁剪一次:约束等只给作者看的原文不能作为译文的键留在站点里
40
+ return { project: rest.i18n ? pruneMessages(out) : out, home: home && project.routes[home] ? home : null };
39
41
  }
40
42
  /** 把 JSON 安全地放进 <script type="application/json">。 */
41
43
  export const jsonForHtml = (v) => JSON.stringify(v).replace(/</g, '\\u003c').replace(/>/g, '\\u003e').replace(/&/g, '\\u0026').replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
@@ -144,7 +146,12 @@ export async function buildSite(opts) {
144
146
  else
145
147
  await buildSourceSite(web, projectDir, staging);
146
148
  // 朗读(D74):当前声音已生成的音频拷进 voice/,IR 带上 voiceIndex;Key 不进产物
147
- const voice = bundleVoice(projectDir, project, staging, new ProfileStore(opts.home ?? joploHome()));
149
+ const store = new ProfileStore(opts.home ?? joploHome());
150
+ // 重新发布(D84):先从上一次的分享沿用本机没有的音频(同样的文字与声音),不重新生成
151
+ const reused = opts.sharedVoice ? await reuseSharedVoice(projectDir, project, opts.sharedVoice, store) : 0;
152
+ const voice = bundleVoice(projectDir, project, staging, store, undefined, opts.sharedVoice?.index);
153
+ if (reused)
154
+ voice.report.reused = reused;
148
155
  // 朗读角色只留范围内功能的(scopeProject 对 voiceIndex 的同一规则;bundleVoice 按声音配置生成全部角色)
149
156
  if (voice.index)
150
157
  inline.project.voiceIndex = scope ? scopeProject({ ...project, voiceIndex: voice.index }, scope.scenarios).project.voiceIndex : voice.index;
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * v2 接口(ADR-0002):CLI 只依赖这里导出的三个函数。由 T-board 实现,届时 index.ts 改为导出它们。
3
3
  */
4
- import type { AppearanceFont, AppearanceStroke, Diagnostic, ScopeInfo, ScopeRequest } from '@joplo-app/core';
4
+ import type { AppearanceFont, AppearanceStroke, Diagnostic, ScopeInfo, ScopeRequest, VoiceIndex } from '@joplo-app/core';
5
5
  import type { CloudBridge } from './cloud.js';
6
6
  export type { CloudAccount, CloudBridge, CloudJob, CloudJobError, CloudPublishRequest, CloudPublishResult } from './cloud.js';
7
7
  export type DevOptions = {
@@ -44,6 +44,14 @@ export type BuildOptions = {
44
44
  * 缺省(或两个数组都为空)时与原来完全一致。写错场景 / 功能时报错,不写任何文件。
45
45
  */
46
46
  scope?: ScopeRequest;
47
+ /**
48
+ * 上一次发布的分享(D84,`joplo share` 重新发布时传):它的 voiceIndex 与取文件的方法。本机没有、分享里有的音频
49
+ * (同样的文字和声音)下载进本机缓存后照常打包,不重新生成;本机没有声音供应商时按分享里的声音指纹带上。
50
+ */
51
+ sharedVoice?: {
52
+ index: VoiceIndex;
53
+ fetch: (file: string) => Promise<Uint8Array | null>;
54
+ };
47
55
  };
48
56
  /** 静态发布站:只含选定方案(compile 的 publish 模式),离线可打开,可直接 `wrangler deploy`。 */
49
57
  /**
@@ -61,6 +69,10 @@ export type BuildResult = {
61
69
  bytes: number;
62
70
  missing: number;
63
71
  profile: string | null;
72
+ reused?: number;
73
+ locales?: Record<string, {
74
+ missing: number;
75
+ }>;
64
76
  }; /** 有 scope 时:范围与借用了哪些别的功能的内容(D75)。 */
65
77
  scope?: ScopeInfo;
66
78
  };
@@ -74,6 +86,8 @@ export type RenderOptions = {
74
86
  theme?: string;
75
87
  /** UI language for the standalone render route. Unsupported values are ignored. */
76
88
  locale?: string;
89
+ /** Author content language (D84): one of config locales; the screenshot shows that translation. */
90
+ content?: string;
77
91
  /** 字体(D55):hand / sans / serif / kai / mono;缺省跟随主题。 */
78
92
  font?: AppearanceFont | null;
79
93
  /** 线条(D55):rough / clean;缺省跟随主题。 */
package/dist/export.js CHANGED
@@ -58,7 +58,7 @@ function parseRequest(project, body, needPosition) {
58
58
  const device = project.scenes[sceneId]?.viewport === 'mobile' ? 'mobile' : 'desktop';
59
59
  // 主题(D51):请求里的主题名,没有或不合法时用项目配置的主题
60
60
  const theme = typeof b.theme === 'string' && THEME_NAME.test(b.theme) ? b.theme : project.theme;
61
- return { sc, position, device, look: { theme, ...exportAppearance(body), locale: exportLocale(b.locale) } };
61
+ return { sc, position, device, look: { theme, ...exportAppearance(body), locale: exportLocale(b.locale), ...(exportLocale(b.contentLocale) ? { content: exportLocale(b.contentLocale) } : {}) } };
62
62
  }
63
63
  const fileSafe = (s) => s.replace(/[^\w.-]+/g, '_').slice(0, 80) || 'scenario';
64
64
  const stamp = (d = new Date()) => `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}-${String(d.getHours()).padStart(2, '0')}${String(d.getMinutes()).padStart(2, '0')}${String(d.getSeconds()).padStart(2, '0')}`;
@@ -204,7 +204,7 @@ export class ExportHub {
204
204
  const browser = await launch(pw);
205
205
  try {
206
206
  const page = await browser.newPage({ viewport: EXPORT_SIZE[device], deviceScaleFactor: 2, reducedMotion: 'reduce' });
207
- await page.goto(this.renderUrl(projectId, { scenario: scenarioId, position: String(position), theme: look.theme, ...appearanceParams(look), ...(look.locale ? { locale: look.locale } : {}), frame: '1' }), { waitUntil: 'domcontentloaded' });
207
+ await page.goto(this.renderUrl(projectId, { scenario: scenarioId, position: String(position), theme: look.theme, ...appearanceParams(look), ...(look.locale ? { locale: look.locale } : {}), ...(look.content ? { content: look.content } : {}), frame: '1' }), { waitUntil: 'domcontentloaded' });
208
208
  await waitReady(page);
209
209
  return await page.locator('[data-jexport]').screenshot({ type: 'png', animations: 'disabled' });
210
210
  }
@@ -225,7 +225,7 @@ export class ExportHub {
225
225
  this.update(job, { phase: 'starting', percent: 2 });
226
226
  await this.deps.recordVideo({
227
227
  projectDir: dir,
228
- url: this.renderUrl(projectId, { scenario: scenarioId, position: '0', theme: look.theme, ...appearanceParams(look), ...(look.locale ? { locale: look.locale } : {}), frame: '1', record: '1' }),
228
+ url: this.renderUrl(projectId, { scenario: scenarioId, position: '0', theme: look.theme, ...appearanceParams(look), ...(look.locale ? { locale: look.locale } : {}), ...(look.content ? { content: look.content } : {}), frame: '1', record: '1' }),
229
229
  size: EXPORT_SIZE[device],
230
230
  out,
231
231
  total,
package/dist/render.d.ts CHANGED
@@ -16,6 +16,7 @@ export declare function renderQuery(q: {
16
16
  position: number;
17
17
  theme: string;
18
18
  locale?: string;
19
+ content?: string;
19
20
  font?: AppearanceFont | null;
20
21
  stroke?: AppearanceStroke | null;
21
22
  viewport?: {
package/dist/render.js CHANGED
@@ -75,6 +75,7 @@ export function renderQuery(q) {
75
75
  position: String(q.position),
76
76
  theme: q.theme,
77
77
  ...(exportLocale(q.locale) ? { locale: exportLocale(q.locale) } : {}),
78
+ ...(exportLocale(q.content) ? { content: exportLocale(q.content) } : {}),
78
79
  ...(isAppearanceFont(q.font) ? { font: q.font } : {}),
79
80
  ...(isAppearanceStroke(q.stroke) ? { stroke: q.stroke } : {}),
80
81
  ...(q.viewport ? { w: String(q.viewport.width), h: String(q.viewport.height) } : {}),
@@ -103,6 +104,9 @@ export async function renderStep(opts) {
103
104
  const sc = project.scenarios[opts.scenarioId];
104
105
  if (!sc)
105
106
  throw new JoploError('NOT_FOUND', `Scenario does not exist: ${opts.scenarioId} (available: ${Object.keys(project.scenarios).join(', ') || 'none'})`);
107
+ // 内容语言(D84)写错时报错,不静默按源语言截图
108
+ if (opts.content !== undefined && !project.i18n?.locales.includes(opts.content))
109
+ throw new JoploError('USAGE', project.i18n ? `--content ${opts.content} is not in config locales (${project.i18n.locales.join(', ')})` : `--content needs config({ locales }); this project has a single language`);
106
110
  const position = opts.stepId ? positionAfterStep(project, sc.id, opts.stepId) : 0;
107
111
  const state = stateAt(project, sc.id, position); // 回放失败会抛出 PLAYBACK_FAILED
108
112
  // 有层级的方案:截图与元素索引用这一步导演层的画面(每层一个独立画面)
@@ -116,7 +120,7 @@ export async function renderStep(opts) {
116
120
  browser = await launch(playwright);
117
121
  const page = await browser.newPage({ viewport, deviceScaleFactor: opts.scale ?? 1, reducedMotion: 'reduce' });
118
122
  // D44:舞台宽度固定为页面自己的 viewport;指定 viewport 时它只是截图尺寸(舞台按比例放进去)
119
- const q = renderQuery({ projectId: server.projectId, scenarioId: sc.id, position, theme, locale: opts.locale, font: opts.font, stroke: opts.stroke, ...(opts.viewport ? { viewport: opts.viewport } : {}) });
123
+ const q = renderQuery({ projectId: server.projectId, scenarioId: sc.id, position, theme, locale: opts.locale, content: opts.content, font: opts.font, stroke: opts.stroke, ...(opts.viewport ? { viewport: opts.viewport } : {}) });
120
124
  await page.goto(`${server.url}?${q}`, { waitUntil: 'domcontentloaded' });
121
125
  await page.waitForFunction(() => window.__JOPLO_READY__ === true, null, { timeout: 60000 });
122
126
  const err = await page.evaluate(() => window.__JOPLO_ERROR__ ?? null);
@@ -32,6 +32,15 @@ export type VoiceState = {
32
32
  total: number;
33
33
  failed: number;
34
34
  } | null;
35
+ /** 内容语言(D84)→ 这种语言的旁白、角色音色与指纹;只有项目写了 locales 才有。看板按当前内容语言取指纹算片段键。 */
36
+ byLocale?: Record<string, {
37
+ narrator: string | null;
38
+ roles: Record<string, string>;
39
+ voices: {
40
+ narrator: string | null;
41
+ roles: Record<string, string>;
42
+ };
43
+ }>;
35
44
  };
36
45
  type Ctx = {
37
46
  guardWrite: (needJson?: boolean) => boolean;
@@ -19,7 +19,11 @@
19
19
  import fs from 'node:fs';
20
20
  import os from 'node:os';
21
21
  import path from 'node:path';
22
- import { AUDIO_TYPES, ProfileStore, VoiceCache, VoiceError, normalizeProfile, resolveVoices, synthesize } from "./voice.js";
22
+ import { AUDIO_TYPES, ProfileStore, voiceLocaleOf, VoiceCache, VoiceError, normalizeProfile, resolveVoices, synthesize } from "./voice.js";
23
+ /** 请求里的内容语言:必须是项目声明的语言;没有 i18n 或不合法时为 null(按原来的方式处理)。 */
24
+ function contentLocaleOf(project, v) {
25
+ return typeof v === 'string' && project?.i18n?.locales.includes(v) ? v : null;
26
+ }
23
27
  const MAX_SEGMENTS = 2000;
24
28
  let lastRev = 0;
25
29
  const nextRev = () => (lastRev = Math.max(lastRev + 1, Date.now() * 1000));
@@ -122,7 +126,9 @@ export class VoiceHub {
122
126
  const cache = new VoiceCache(dir);
123
127
  const idx = cache.read();
124
128
  const r = resolveVoices(project?.voiceConfig, idx.profileId, this.store);
125
- const cur = cache.current(r.voices);
129
+ const per = Object.fromEntries((project?.i18n?.locales ?? []).map((l) => [l, resolveVoices(project?.voiceConfig, idx.profileId, this.store, voiceLocaleOf(project, l))]));
130
+ const all = Object.values(per);
131
+ 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));
126
132
  const job = this.jobs.get(projectId);
127
133
  const enc = encodeURIComponent;
128
134
  return {
@@ -137,6 +143,7 @@ export class VoiceHub {
137
143
  clips: Object.fromEntries(Object.entries(cur.clips).map(([k, f]) => [k, `/__joplo/p/${enc(projectId)}/voice/clips/${f}`])),
138
144
  failures: cur.failures,
139
145
  generating: job ? { done: job.done, total: job.total, failed: job.failed } : null,
146
+ ...(all.length ? { byLocale: Object.fromEntries(Object.entries(per).map(([l, x]) => [l, { narrator: x.narrator, roles: x.roles, voices: x.voices }])) } : {}),
140
147
  };
141
148
  }
142
149
  /** /__joplo/p/:id/voice[/…];不认识的路径返回 false。 */
@@ -172,12 +179,13 @@ export class VoiceHub {
172
179
  if (this.jobs.has(projectId))
173
180
  return ctx.send(409, { error: { code: 'BUSY', message: 'Narration is already being generated for this project' } }), true;
174
181
  const cache = new VoiceCache(dir);
175
- const resolved = resolveVoices(project?.voiceConfig, cache.read().profileId, this.store);
182
+ const content = contentLocaleOf(project, body.contentLocale);
183
+ const resolved = resolveVoices(project?.voiceConfig, cache.read().profileId, this.store, voiceLocaleOf(project, content));
176
184
  const job = { done: 0, total: segs.length, failed: 0, abort: new AbortController() };
177
185
  this.jobs.set(projectId, job);
178
186
  let summary;
179
187
  try {
180
- summary = await cache.generate(segs, typeof body.locale === 'string' ? body.locale.slice(0, 20) : 'en', resolved, this.store, {
188
+ summary = await cache.generate(segs, content ?? (typeof body.locale === 'string' ? body.locale.slice(0, 20) : 'en'), resolved, this.store, {
181
189
  fetch: this.opts.fetch,
182
190
  signal: job.abort.signal,
183
191
  inflight: this.inflightOf(projectId),
@@ -206,11 +214,12 @@ export class VoiceHub {
206
214
  if (!seg || typeof seg.stepId !== 'string' || typeof seg.text !== 'string' || seg.text.length > MAX_TEXT || (seg.role !== null && typeof seg.role !== 'string'))
207
215
  return ctx.send(400, { error: { code: 'USAGE', message: 'segment must be { stepId, text, role }' } }), true;
208
216
  const cache = new VoiceCache(dir);
209
- const resolved = resolveVoices(project?.voiceConfig, cache.read().profileId, this.store);
217
+ const content = contentLocaleOf(project, body.contentLocale);
218
+ const resolved = resolveVoices(project?.voiceConfig, cache.read().profileId, this.store, voiceLocaleOf(project, content));
210
219
  const plan = cache.plan(seg, resolved);
211
220
  if (!plan)
212
221
  return ctx.send(400, { error: { code: 'INVALID', message: 'No voice provider is selected for this project' } }), true;
213
- const p = cache.generateOne(seg, typeof body.locale === 'string' ? body.locale.slice(0, 20) : 'en', resolved, this.store, { fetch: this.opts.fetch, inflight: this.inflightOf(projectId) });
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) });
214
223
  try {
215
224
  const r = await p;
216
225
  if (r.generated)
package/dist/voice.d.ts CHANGED
@@ -138,7 +138,15 @@ export type ResolvedVoices = {
138
138
  roles: Record<string, string>;
139
139
  };
140
140
  };
141
- export declare function resolveVoices(config: VoiceConfig | undefined, selected: string | null, store: ProfileStore): ResolvedVoices;
141
+ /**
142
+ * 某种内容语言用哪个音色(D84):音色有口音(ElevenLabs 预设)且口音不是这种语言、而预设里有这种语言的音色时,
143
+ * 换成同语言的(优先同性别、推荐的);多语言音色(OpenAI 预设没有口音)原样用,由说话风格要求母语口音。
144
+ */
145
+ export declare function autoVoiceFor(profile: Pick<VoiceProfile, 'preset'>, voice: string, locale: string | null | undefined): string;
146
+ /** 传给 resolveVoices 的语言:默认语言(源文件的语言)不自动换音色,保留作者原来的选择和已生成的音频。 */
147
+ export declare const voiceLocaleOf: (project: Pick<Project, "i18n"> | null | undefined, locale: string | null | undefined) => string | null;
148
+ /** locale:内容语言(D84,默认语言传 null,见 voiceLocaleOf)。config.voice.locales[locale] 优先,其次按 autoVoiceFor 自动选;不传时与之前一样。 */
149
+ export declare function resolveVoices(config: VoiceConfig | undefined, selected: string | null, store: ProfileStore, locale?: string | null): ResolvedVoices;
142
150
  export type ClipRecord = {
143
151
  file: string;
144
152
  stepId: string;
@@ -192,7 +200,7 @@ export declare class VoiceCache {
192
200
  /** 片段文件的绝对路径(文件名不合法或不存在时为 null)。 */
193
201
  fileOf(name: string): string | null;
194
202
  /** 当前声音下已有的片段:键 → 文件名;以及失败的键 → 原因。 */
195
- current(voices: ResolvedVoices['voices']): {
203
+ current(voices: ResolvedVoices['voices'], extra?: string[]): {
196
204
  clips: Record<string, string>;
197
205
  failures: Record<string, {
198
206
  stepId: string;
@@ -215,6 +223,8 @@ export declare class VoiceCache {
215
223
  } | null;
216
224
  /** 已有的片段文件名(文件还在时)。 */
217
225
  clipOf(key: string): string | null;
226
+ /** 收下一段别处来的音频(D84:从已发布的分享沿用):文件名必须是内容的 sha256,否则不收。 */
227
+ adopt(key: string, file: string, bytes: Uint8Array, rec: Omit<ClipRecord, 'file' | 'bytes' | 'at'>): boolean;
218
228
  /**
219
229
  * 生成一段(已有就直接返回):返回文件名;失败记进 failures 并抛 VoiceError。
220
230
  * inflight:同一个项目共用的“正在生成”表(片段键 → 结果)。批量生成与边放边生成传同一张表,同一段同时只请求一次,后来的等先来的结果(generated 为 false)。
@@ -240,14 +250,32 @@ export type BundleReport = {
240
250
  bytes: number;
241
251
  missing: number;
242
252
  profile: string | null;
253
+ /** 从上一次发布的分享沿用、这次没有重新生成的段数(D84)。 */
254
+ reused?: number;
255
+ /** 内容语言(D84)→ 这种语言还缺几步音频。只有项目写了 locales 才有。 */
256
+ locales?: Record<string, {
257
+ missing: number;
258
+ }>;
243
259
  };
260
+ /** 上一次发布的分享(D84):它的 voiceIndex(片段键 → voice/<sha256>.<ext>)和按相对路径取文件的方法。 */
261
+ export type SharedVoice = {
262
+ index: VoiceIndex;
263
+ fetch: (file: string) => Promise<Uint8Array | null>;
264
+ };
265
+ /**
266
+ * 从上一次发布的分享沿用音频(D84):Cloud 只存分享出去的作品,不另设缓存。按当前文字和声音算片段键,
267
+ * 本机没有、分享里有的就下载到本机缓存(文件名必须是内容的 sha256),之后照常打包;上传时 Cloud 已有这些内容,不会重传。
268
+ * 本机没有供应商时按分享里的声音指纹算键。自动字幕的步骤(文字由网页按语言生成)不在这里沿用。
269
+ */
270
+ export declare function reuseSharedVoice(projectDir: string, project: Project, shared: SharedVoice, store: ProfileStore, devConfig?: VoiceConfig): Promise<number>;
244
271
  /**
245
272
  * 发布(joplo build / share):把发布 IR 里步骤用到的、当前声音的音频拷进 `<outDir>/voice/`,返回 IR 的 voiceIndex。
246
273
  * 同一步同一声音同一语言只留最新的一段(改过字之后旧的不再带上)。
247
- * missing:当前声音下还没有音频的步骤数(文字与语言无关的步骤按键判断;自动字幕的步骤只要有任意语言的音频就算有)。
248
- * 没有选用 profile 时不带任何音频(观众端用浏览器朗读)。
274
+ * 内容多语言(D84):每种内容语言按 resolveVoices(…, 语言) 选声音,voiceIndex.locales 记各语言的指纹;missing 按语言分别统计。
275
+ * missing:还没有音频的步骤数(自动字幕的步骤只要有这种语言的任意音频就算有)。
276
+ * 没有选用 profile 时:给了 fallback(已发布分享的 voiceIndex)就按它的指纹带上本机已有的音频,否则不带(观众端用浏览器朗读)。
249
277
  */
250
- export declare function bundleVoice(projectDir: string, project: Project, outDir: string, store: ProfileStore, devConfig?: VoiceConfig): {
278
+ export declare function bundleVoice(projectDir: string, project: Project, outDir: string, store: ProfileStore, devConfig?: VoiceConfig, fallback?: VoiceIndex): {
251
279
  index: VoiceIndex | null;
252
280
  report: BundleReport;
253
281
  };
package/dist/voice.js CHANGED
@@ -16,7 +16,7 @@
16
16
  import crypto from 'node:crypto';
17
17
  import fs from 'node:fs';
18
18
  import path from 'node:path';
19
- import { DEFAULT_STYLE, clipKey, speakerRoleAt, spokenLine, voiceFingerprint } from '@joplo-app/core';
19
+ import { DEFAULT_STYLE, clipKey, localizeProject, speakerRoleAt, spokenLine, voiceFingerprint } from '@joplo-app/core';
20
20
  export { DEFAULT_STYLE };
21
21
  /** OpenAI 的内置音色都能读多种语言;marin / cedar 是官方推荐的高质量音色。 */
22
22
  const OPENAI_VOICES = [
@@ -387,7 +387,28 @@ export async function synthesize(p, key, text, voice, opts = {}) {
387
387
  export function fingerprint(p, voice) {
388
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
389
  }
390
- export function resolveVoices(config, selected, store) {
390
+ /**
391
+ * 某种内容语言用哪个音色(D84):音色有口音(ElevenLabs 预设)且口音不是这种语言、而预设里有这种语言的音色时,
392
+ * 换成同语言的(优先同性别、推荐的);多语言音色(OpenAI 预设没有口音)原样用,由说话风格要求母语口音。
393
+ */
394
+ export function autoVoiceFor(profile, voice, locale) {
395
+ const choices = presetOf(profile.preset)?.voices;
396
+ const cur = choices?.find((v) => v.id === voice);
397
+ if (!locale || !choices || !cur?.accent)
398
+ return voice;
399
+ const lang = (tag) => tag.toLowerCase().split('-')[0];
400
+ if (lang(cur.accent) === lang(locale))
401
+ return voice;
402
+ const same = choices.filter((v) => v.accent && lang(v.accent) === lang(locale));
403
+ const exact = same.filter((v) => v.accent.toLowerCase() === locale.toLowerCase());
404
+ const pool = exact.length ? exact : same;
405
+ const pick = pool.find((v) => v.gender === cur.gender && v.recommended) ?? pool.find((v) => v.gender === cur.gender) ?? pool.find((v) => v.recommended) ?? pool[0];
406
+ return pick?.id ?? voice;
407
+ }
408
+ /** 传给 resolveVoices 的语言:默认语言(源文件的语言)不自动换音色,保留作者原来的选择和已生成的音频。 */
409
+ 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) {
391
412
  let profile = null;
392
413
  let source = null;
393
414
  let missing = null;
@@ -405,8 +426,9 @@ export function resolveVoices(config, selected, store) {
405
426
  }
406
427
  if (!profile)
407
428
  return { profile: null, source, missing, narrator: null, roles: {}, voices: { narrator: null, roles: {} } };
408
- const narrator = config?.narrator ?? profile.voice;
409
- const roles = { ...(config?.roles ?? {}) };
429
+ 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 ?? {}) };
410
432
  return {
411
433
  profile,
412
434
  source,
@@ -455,8 +477,8 @@ export class VoiceCache {
455
477
  return fs.existsSync(f) ? f : null;
456
478
  }
457
479
  /** 当前声音下已有的片段:键 → 文件名;以及失败的键 → 原因。 */
458
- current(voices) {
459
- const fps = new Set([voices.narrator, ...Object.values(voices.roles)].filter(Boolean));
480
+ current(voices, extra = []) {
481
+ const fps = new Set([voices.narrator, ...Object.values(voices.roles), ...extra].filter(Boolean));
460
482
  const idx = this.read();
461
483
  const clips = {};
462
484
  for (const [k, c] of Object.entries(idx.clips))
@@ -498,6 +520,17 @@ export class VoiceCache {
498
520
  const c = this.read().clips[key];
499
521
  return c && FILE_RE.test(c.file) && fs.existsSync(path.join(this.clipsDir, c.file)) ? c.file : null;
500
522
  }
523
+ /** 收下一段别处来的音频(D84:从已发布的分享沿用):文件名必须是内容的 sha256,否则不收。 */
524
+ adopt(key, file, bytes, rec) {
525
+ if (!FILE_RE.test(file) || crypto.createHash('sha256').update(bytes).digest('hex') !== file.split('.')[0])
526
+ return false;
527
+ fs.mkdirSync(this.clipsDir, { recursive: true });
528
+ const dest = path.join(this.clipsDir, file);
529
+ if (!fs.existsSync(dest))
530
+ fs.writeFileSync(dest, bytes);
531
+ this.record(key, { ...rec, file, bytes: bytes.length, at: new Date().toISOString() });
532
+ return true;
533
+ }
501
534
  /**
502
535
  * 生成一段(已有就直接返回):返回文件名;失败记进 failures 并抛 VoiceError。
503
536
  * inflight:同一个项目共用的“正在生成”表(片段键 → 结果)。批量生成与边放边生成传同一张表,同一段同时只请求一次,后来的等先来的结果(generated 为 false)。
@@ -582,20 +615,64 @@ export class VoiceCache {
582
615
  return summary;
583
616
  }
584
617
  }
618
+ function voicesPerLocale(project, resolve) {
619
+ const locales = project.i18n ? project.i18n.locales : [null];
620
+ return locales.flatMap((l) => {
621
+ const v = resolve(l);
622
+ return v ? [{ locale: l, project: l ? localizeProject(project, l) : project, voices: v }] : [];
623
+ });
624
+ }
625
+ const sharedVoices = (index) => (l) => (l && index.locales?.[l]) || { narrator: index.narrator, roles: index.roles };
626
+ /**
627
+ * 从上一次发布的分享沿用音频(D84):Cloud 只存分享出去的作品,不另设缓存。按当前文字和声音算片段键,
628
+ * 本机没有、分享里有的就下载到本机缓存(文件名必须是内容的 sha256),之后照常打包;上传时 Cloud 已有这些内容,不会重传。
629
+ * 本机没有供应商时按分享里的声音指纹算键。自动字幕的步骤(文字由网页按语言生成)不在这里沿用。
630
+ */
631
+ export async function reuseSharedVoice(projectDir, project, shared, store, devConfig) {
632
+ 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));
636
+ let reused = 0;
637
+ for (const { locale, project: p, voices } of per)
638
+ for (const sc of Object.values(p.scenarios))
639
+ for (const [i, st] of sc.steps.entries()) {
640
+ if (st.captionAuto && !st.say && !st.narrate)
641
+ continue;
642
+ const line = spokenLine(st, st.caption, speakerRoleAt(p, sc.id, i + 1));
643
+ const fp = voiceFingerprint(voices, line.role);
644
+ if (!fp || !line.text)
645
+ continue;
646
+ const text = line.text.replace(/\s+/g, ' ').trim();
647
+ const key = clipKey(fp, text);
648
+ const rel = shared.index.clips[key];
649
+ if (!rel || cache.clipOf(key))
650
+ continue;
651
+ const file = rel.replace(/^voice\//, '');
652
+ const bytes = await shared.fetch(rel).catch(() => null);
653
+ if (bytes && cache.adopt(key, file, bytes, { stepId: st.id, fp, text, locale: locale ?? 'en' }))
654
+ reused++;
655
+ }
656
+ return reused;
657
+ }
585
658
  /**
586
659
  * 发布(joplo build / share):把发布 IR 里步骤用到的、当前声音的音频拷进 `<outDir>/voice/`,返回 IR 的 voiceIndex。
587
660
  * 同一步同一声音同一语言只留最新的一段(改过字之后旧的不再带上)。
588
- * missing:当前声音下还没有音频的步骤数(文字与语言无关的步骤按键判断;自动字幕的步骤只要有任意语言的音频就算有)。
589
- * 没有选用 profile 时不带任何音频(观众端用浏览器朗读)。
661
+ * 内容多语言(D84):每种内容语言按 resolveVoices(…, 语言) 选声音,voiceIndex.locales 记各语言的指纹;missing 按语言分别统计。
662
+ * missing:还没有音频的步骤数(自动字幕的步骤只要有这种语言的任意音频就算有)。
663
+ * 没有选用 profile 时:给了 fallback(已发布分享的 voiceIndex)就按它的指纹带上本机已有的音频,否则不带(观众端用浏览器朗读)。
590
664
  */
591
- export function bundleVoice(projectDir, project, outDir, store, devConfig) {
665
+ export function bundleVoice(projectDir, project, outDir, store, devConfig, fallback) {
592
666
  const cache = new VoiceCache(projectDir);
593
667
  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));
668
+ const cfg = devConfig ?? project.voiceConfig;
669
+ const base = resolveVoices(cfg, idx.profileId, store);
670
+ const profileName = base.profile?.name ?? (fallback ? 'the published share' : null);
671
+ const empty = { index: null, report: { clips: 0, bytes: 0, missing: 0, profile: profileName } };
672
+ if (!base.profile && !fallback)
673
+ 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));
599
676
  const stepIds = new Set(Object.values(project.scenarios).flatMap((s) => s.steps.map((st) => st.id)));
600
677
  const latest = new Map();
601
678
  for (const [k, c] of Object.entries(idx.clips)) {
@@ -619,19 +696,33 @@ export function bundleVoice(projectDir, project, outDir, store, devConfig) {
619
696
  clips[k] = `voice/${c.file}`;
620
697
  }
621
698
  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
- });
699
+ const byLocale = {};
700
+ for (const { locale, project: p, voices } of per) {
701
+ let n = 0;
702
+ for (const sc of Object.values(p.scenarios))
703
+ sc.steps.forEach((st, i) => {
704
+ const line = spokenLine(st, st.caption, speakerRoleAt(p, sc.id, i + 1));
705
+ const fp = voiceFingerprint(voices, line.role);
706
+ if (!fp || !line.text)
707
+ return;
708
+ // 自动字幕在网页里按语言生成:这一步有这种语言(没有 i18n 时任意语言)的音频就算有
709
+ 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)
712
+ n++;
713
+ });
714
+ missing += n;
715
+ if (locale)
716
+ byLocale[locale] = { missing: n };
717
+ }
718
+ const head = per[0].voices;
719
+ const extra = project.i18n ? { locales: byLocale } : {};
634
720
  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 } };
721
+ 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 }]));
724
+ return {
725
+ index: { narrator: head.narrator, roles: head.roles, clips, ...(Object.keys(locales).length ? { locales } : {}) },
726
+ report: { clips: Object.keys(clips).length, bytes, missing, profile: profileName, ...extra },
727
+ };
637
728
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@joplo-app/server",
3
- "version": "0.2.16",
3
+ "version": "0.2.17",
4
4
  "description": "Joplo 本地服务:dev 看板、build 发布站、render 截图",
5
5
  "license": "PolyForm-Shield-1.0.0",
6
6
  "type": "module",
@@ -15,9 +15,9 @@
15
15
  "dist"
16
16
  ],
17
17
  "dependencies": {
18
- "@joplo-app/core": "0.2.16",
19
- "@joplo-app/kit": "0.2.16",
20
- "@joplo-app/web": "0.2.16",
18
+ "@joplo-app/core": "0.2.17",
19
+ "@joplo-app/kit": "0.2.17",
20
+ "@joplo-app/web": "0.2.17",
21
21
  "@tailwindcss/vite": "4.3.4",
22
22
  "tailwindcss": "4.3.4",
23
23
  "vite": "8.3.5",