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