dsh-laivox-tts 0.7.24 → 0.7.26

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/README.en.md CHANGED
@@ -38,7 +38,7 @@ This installs the prebuilt package from npm—nothing is compiled locally and no
38
38
 
39
39
  ### Install from GitHub Release or offline package
40
40
 
41
- If npm is unavailable or you prefer pinning a release tarball, install via URL or download `dsh-laivox-tts.tgz` from [Releases](https://github.com/xiaolai181/dsh_laivox_tts/releases) (replace `latest/download` with `download/v0.7.24` to pin a version):
41
+ If npm is unavailable or you prefer pinning a release tarball, install via URL or download `dsh-laivox-tts.tgz` from [Releases](https://github.com/xiaolai181/dsh_laivox_tts/releases) (replace `latest/download` with `download/v0.7.26` to pin a version):
42
42
 
43
43
  ```sh
44
44
  dsh plugin --profile desktop add "https://github.com/xiaolai181/dsh_laivox_tts/releases/latest/download/dsh-laivox-tts.tgz"
package/README.md CHANGED
@@ -40,7 +40,7 @@ dsh plugin --profile desktop add dsh-laivox-tts
40
40
 
41
41
  ### GitHub Release 链接或离线安装包安装
42
42
 
43
- 如需锁定版本或无法直连 npm,可使用 Release 下载链接(将 `latest/download` 替换为 `download/v0.7.24` 可锁定版本),或从 [Releases](https://github.com/xiaolai181/dsh_laivox_tts/releases) 下载 `dsh-laivox-tts.tgz` 到本地后安装:
43
+ 如需锁定版本或无法直连 npm,可使用 Release 下载链接(将 `latest/download` 替换为 `download/v0.7.26` 可锁定版本),或从 [Releases](https://github.com/xiaolai181/dsh_laivox_tts/releases) 下载 `dsh-laivox-tts.tgz` 到本地后安装:
44
44
 
45
45
  ```sh
46
46
  dsh plugin --profile desktop add "https://github.com/xiaolai181/dsh_laivox_tts/releases/latest/download/dsh-laivox-tts.tgz"
package/lib/client.js CHANGED
@@ -4603,7 +4603,7 @@ function applySpokenParts(parts, { speakText, roles } = {}) {
4603
4603
  }
4604
4604
 
4605
4605
  // src/domain/script-lines.mjs
4606
- var EXTRACT_SCRIPT = false;
4606
+ var EXTRACT_SCRIPT = true;
4607
4607
  function removedRanges(text, removed) {
4608
4608
  const hidden = new Set(removed ?? []);
4609
4609
  return sourceLines(text).filter((line2) => hidden.has(line2.id)).map((line2) => ({ start: line2.start, end: line2.start + line2.text.length }));
@@ -5496,7 +5496,7 @@ function PlanSheet({ dialog, answer, narratorSetting, account }) {
5496
5496
  plan.aiPlan?.selection && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)("p", { children: modelIdentity(plan.aiPlan.selection) }),
5497
5497
  /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)("p", { children: [
5498
5498
  translate("\u9884\u8BA1 {requests} \u6B21\u5E38\u89C4\u8BF7\u6C42\uFF0C\u4F7F\u7528 DSH \u6A21\u578B\u989D\u5EA6\u3002", { requests: plan.estimate.requests }),
5499
- plan.estimate.cast > 0 ? EXTRACT_SCRIPT ? translate("\u7F16\u5267\u6BCF\u6BB5\u53EF\u80FD\u518D\u9009\u89D2\u4E00\u6B21\u3001\u518D\u8865\u5199\u4E00\u6B21\uFF0C\u901A\u5E38\u4E0D\u8D85\u8FC7 {max} \u6B21\u3002", { max: plan.estimate.requests + 2 * plan.estimate.cast }) : translate("\u6A21\u578B\u8F93\u51FA\u9700\u8981\u4FEE\u590D\u65F6\uFF0C\u8BF7\u6C42\u6570\u53EF\u80FD\u589E\u52A0\u3002") : "",
5499
+ plan.estimate.cast > 0 ? translate("\u7F16\u5267\u6BCF\u6BB5\u53EF\u80FD\u518D\u9009\u89D2\u4E00\u6B21\u3001\u518D\u8865\u5199\u4E00\u6B21\uFF0C\u901A\u5E38\u4E0D\u8D85\u8FC7 {max} \u6B21\u3002", { max: plan.estimate.requests + 2 * plan.estimate.cast }) : "",
5500
5500
  plan.estimate.provisional ? translate("\u6E05\u6D17\u5B8C\u6210\u540E\uFF0C\u7F16\u5267\u6B21\u6570\u53EF\u80FD\u8C03\u6574\u3002") : ""
5501
5501
  ] })
5502
5502
  ] }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-laivox-tts",
3
- "version": "0.7.24",
3
+ "version": "0.7.26",
4
4
  "private": false,
5
5
  "description": "把 TXT、EPUB、PDF 小说做成单人朗读或多角色有声书,也能一键朗读对话里的 AI 回答,支持本地书架与 MP3/WAV 导出。",
6
6
  "license": "MIT",
@@ -1,9 +1,7 @@
1
1
  import { hasSpeakable, isSeparator, sourceLines } from './segment.mjs'
2
2
  import { stripSpeakerPrefix } from './spoken-text.mjs'
3
3
 
4
- // New multi-role scripts only. A saved version 3 script and a job that already
5
- // started as extract-v1 keep working whatever this says.
6
- export const EXTRACT_SCRIPT = false
4
+ export const EXTRACT_SCRIPT = true
7
5
  export const SCRIPT_VERSION = 3
8
6
 
9
7
  const openers = { '「': '」', '『': '』', '“': '”' }
package/src/host/cast.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createHash } from 'node:crypto'
2
2
  import { normalizeInstruct } from '../domain/voice-direction.mjs'
3
3
  import { ROLE_AGES } from '../domain/voice-assignment.mjs'
4
- import { dialogueMatches, hasSpeakable, isSeparator, sourceLines } from '../domain/segment.mjs'
4
+ import { dialogueMatches, hasSpeakable } from '../domain/segment.mjs'
5
5
  import { alignLine, uncoveredSpeakable } from '../domain/script-lines.mjs'
6
6
 
7
7
  export const EMOTIONS = ['neutral', 'happy', 'sad', 'angry', 'afraid', 'tense', 'gentle']
@@ -20,8 +20,6 @@ export const CAST = [
20
20
  '3. 复用 roles 里已有角色的 ref(c1、c2 这种短编号);旁白固定写 narrator。同一人物的别称复用同一个 ref,不要重复建角色。',
21
21
  '4. 新角色先在 roles 声明 {"ref":"new1","name":"角色名","gender":"female|male|","age":"child|teen|young|middle|elder|"},最多 12 个,再在 items 中用 ref 引用。age 按原文线索判断年龄段:child 儿童,teen 少年,young 青年,middle 中年,elder 老年;没有线索时留空。没有新角色时 roles 为空数组。',
22
22
  '5. 笔录、剧本或聊天里,段首如果只是纯角色名加冒号,instruct 只描述冒号后面真正说出的话。不要改写原文。',
23
- '6. segments 里带 "scene":true 的段,和上一段之间隔着分场符(如 ※※※、——),场景已经切换:从这一段起,没写名字的引号对白不要沿用分场前的说话人,按分场后的动作、称呼和对话双方重新判断。',
24
- '7. 带 "cont":"X" 的段,和前一段同属一行以「X:」开头、没有引号的笔录或聊天,被切成了几段。X 只是纯名字时,这一段仍是 X 在说,继续标 X,不要改标 narrator;X 带动作或神态时忽略 cont,按第 1 条判断。',
25
23
  '',
26
24
  '【表演方式】每段给出 emotion、intensity、instruct:',
27
25
  '1. emotion 只能是 neutral,happy,sad,angry,afraid,tense,gentle 之一;intensity 只能是整数 0、1、2(0 平淡,1 明显,2 强烈);neutral 时 intensity 必须为 0。',
@@ -33,7 +31,7 @@ export const CAST = [
33
31
  '',
34
32
  '【输出】',
35
33
  'items 每条用紧凑键以节省输出:s=segmentId,r=角色 ref(已知角色用 c1、c2,旁白用 narrator,新角色用 new1),e=emotion,n=intensity,i=instruct,a=该段原文去掉空白后的前 8 个字(不足 8 个字就写到段尾,标点照算,空白不算)。',
36
- '每个输入 segmentId 恰好返回一条,保留原编号,禁止遗漏或重复。用 context 辅助判断,但只标注 segments。scene、cont 只是提示,不写进输出。引号内对白不确定说话人时,新建“男人”“女人”“陌生人”这类称呼,不得用 narrator。没有引号、也看不出是内心独白的叙述、动作、环境,才用 narrator。不确定情绪时用 neutral、强度 0。旁白的 instruct 写「自然叙述,语气平稳。」;对白的 instruct 写「自然交谈,语速适中。」。只返回一个 JSON 对象,不要 Markdown 或任何说明文字。',
34
+ '每个输入 segmentId 恰好返回一条,保留原编号,禁止遗漏或重复。用 context 辅助判断,但只标注 segments。引号内对白不确定说话人时,新建“男人”“女人”“陌生人”这类称呼,不得用 narrator。没有引号、也看不出是内心独白的叙述、动作、环境,才用 narrator。不确定情绪时用 neutral、强度 0。旁白的 instruct 写「自然叙述,语气平稳。」;对白的 instruct 写「自然交谈,语速适中。」。只返回一个 JSON 对象,不要 Markdown 或任何说明文字。',
37
35
  '示例输入 segments [{"segmentId":41,"text":"  他走进了房间。"},{"segmentId":42,"text":"“快走,他们马上就到了!”"}]',
38
36
  '示例输出 {"roles":[{"ref":"new1","name":"林月","gender":"female","age":"young"}],"items":[{"s":41,"r":"narrator","e":"neutral","n":0,"i":"客观叙述,语气平稳。","a":"他走进了房间。"},{"s":42,"r":"new1","e":"tense","n":1,"i":"压低嗓音,带着警惕。","a":"“快走,他们马上"}]}',
39
37
  ].join('\n')
@@ -142,38 +140,6 @@ function castResult(value, segments, bookRoles, lookupRoles = bookRoles) {
142
140
  return accepted
143
141
  }
144
142
 
145
- const leadingName = /^\s*([^\s,。!?;:、]{1,6})[::]/u
146
- const attributionEnd = /[说說問问答道喊叫叹嘆]$/u
147
-
148
- // Hints only; the model still decides the speaker.
149
- // scene: a separator or decorative line (kept, or removed by cleaning) lies between
150
- // this part and the previous speakable part.
151
- // cont: this part continues an unquoted "名字:" line the segmenter cut into pieces.
152
- export function castHints(text, segments) {
153
- const lines = sourceLines(String(text ?? ''))
154
- const breaks = new Array(lines.length + 1).fill(0)
155
- for (let i = 0; i < lines.length; i++) {
156
- const body = lines[i].text
157
- breaks[i + 1] = breaks[i] + (body.trim() && (isSeparator(body) || !hasSpeakable(body)) ? 1 : 0)
158
- }
159
- const hints = new Map()
160
- let previous = null
161
- for (const part of segments) {
162
- if (!hasSpeakable(part.text)) continue
163
- const hint = {}
164
- if (previous && Number.isInteger(part.line) && Number.isInteger(previous.line)
165
- && breaks[part.line] - breaks[previous.line + 1] > 0) hint.scene = true
166
- const line = lines[part.line]
167
- if (previous?.line === part.line && line && part.start > line.start) {
168
- const lead = leadingName.exec(line.text)
169
- if (lead && !attributionEnd.test(lead[1]) && dialogueMatches(line.text).next().done) hint.cont = lead[1].normalize('NFKC')
170
- }
171
- if (hint.scene || hint.cont) hints.set(part.id, hint)
172
- previous = part
173
- }
174
- return hints
175
- }
176
-
177
143
  // palette carries the directions already accepted in this chapter so the model
178
144
  // can reuse narrator wording verbatim and keep each speaker's tone continuous.
179
145
  export async function recoverCastBatch(group, bookRoles, context, request, palette = { narrator: [], roles: [] }, lookupRoles = bookRoles) {
@@ -205,12 +171,7 @@ export async function recoverCastBatch(group, bookRoles, context, request, palet
205
171
  const reply = await request(repair ? CAST + '\n' + REPAIR : CAST, {
206
172
  roles: promptRoles(roles),
207
173
  palette: promptPalette, context: contextLines, segments: segments.map(part => {
208
- const body = {
209
- segmentId: part.id,
210
- text: part.text,
211
- ...(part.scene ? { scene: true } : {}),
212
- ...(part.cont ? { cont: part.cont } : {}),
213
- }
174
+ const body = { segmentId: part.id, text: part.text }
214
175
  if (!repair) return body
215
176
  const index = group.indexOf(part)
216
177
  return { ...body, before: neighbor(group[index - 1]), after: neighbor(group[index + 1]) }
package/src/host/edge.mjs CHANGED
@@ -1,170 +1,162 @@
1
- import { spawn } from 'node:child_process'
2
- import { setTimeout as delay } from 'node:timers/promises'
3
- import { fileURLToPath } from 'node:url'
4
- import { hasSpeakable } from '../domain/segment.mjs'
5
-
6
- // Order matters: chooseVoices hands out the first unused voice of a matching
7
- // gender, so new voices are only ever appended. Appending leaves every role that
8
- // already had its own voice untouched. auto: false voices (regional accents)
9
- // are offered in the picker but never assigned automatically.
10
- // Added after 10/10 real synthesis runs each (5 simplified, 5
11
- // traditional); zh-TW-YunJheNeural failed 4/10 with truncated streams and is excluded.
12
- // Later voices are appended. Chinese automatic assignment still walks the
13
- // original zh-CN / zh-TW entries first, so roles that already had a voice keep it.
14
- export const edgeVoices = [
15
- { id: 'zh-CN-XiaoxiaoNeural', name: '晓晓', gender: 'female', age: 'adult', auto: true },
16
- { id: 'zh-CN-YunxiNeural', name: '云希', gender: 'male', age: 'adult', auto: true },
17
- { id: 'zh-CN-YunjianNeural', name: '云健', gender: 'male', age: 'adult', auto: true },
18
- { id: 'zh-CN-XiaoyiNeural', name: '晓伊', gender: 'female', age: 'adult', auto: true },
19
- { id: 'zh-TW-HsiaoChenNeural', name: '曉臻', gender: 'female', age: 'adult', auto: true },
20
- { id: 'zh-TW-HsiaoYuNeural', name: '曉雨', gender: 'female', age: 'adult', auto: true },
21
- { id: 'zh-CN-YunyangNeural', name: '云扬', gender: 'male', age: 'adult', auto: true },
22
- { id: 'zh-CN-YunxiaNeural', name: '云夏', gender: 'male', age: 'child', auto: true },
23
- { id: 'zh-CN-XiaohanNeural', name: '晓涵', gender: 'female', age: 'adult', auto: true },
24
- { id: 'zh-CN-XiaoxuanNeural', name: '晓萱', gender: 'female', age: 'adult', auto: true },
25
- { id: 'zh-CN-XiaoruiNeural', name: '晓睿', gender: 'female', age: 'adult', auto: true },
26
- { id: 'zh-CN-XiaoshuangNeural', name: '晓双', gender: 'female', age: 'child', auto: true },
27
- { id: 'zh-CN-YunfengNeural', name: '云枫', gender: 'male', age: 'adult', auto: true },
28
- { id: 'zh-CN-YunhaoNeural', name: '云皓', gender: 'male', age: 'adult', auto: true },
29
- { id: 'zh-CN-YunyeNeural', name: '云野', gender: 'male', age: 'adult', auto: true },
30
- { id: 'zh-CN-YunzeNeural', name: '云泽', gender: 'male', age: 'adult', auto: true },
31
- { id: 'en-US-AriaNeural', name: 'Aria(美式英语)', gender: 'female', age: 'adult', auto: true },
32
- { id: 'en-US-JennyNeural', name: 'Jenny(美式英语)', gender: 'female', age: 'adult', auto: true },
33
- { id: 'en-US-GuyNeural', name: 'Guy(美式英语)', gender: 'male', age: 'adult', auto: true },
34
- { id: 'en-US-DavisNeural', name: 'Davis(美式英语)', gender: 'male', age: 'adult', auto: true },
35
- { id: 'en-GB-SoniaNeural', name: 'Sonia(英式英语)', gender: 'female', age: 'adult', auto: true },
36
- { id: 'en-GB-RyanNeural', name: 'Ryan(英式英语)', gender: 'male', age: 'adult', auto: true },
37
- { id: 'en-US-AnaNeural', name: 'Ana(美式英语)', gender: 'female', age: 'child', auto: true },
38
- { id: 'zh-CN-liaoning-XiaobeiNeural', name: '晓北(东北口音)', gender: 'female', age: 'adult', auto: false },
39
- { id: 'zh-CN-shaanxi-XiaoniNeural', name: '晓妮(陕西口音)', gender: 'female', age: 'adult', auto: false },
40
- ]
41
-
42
- const workerFile = fileURLToPath(new URL('./edge-worker.mjs', import.meta.url))
43
- const DETAIL_LIMIT = 600
44
- const STDERR_LIMIT = 8 * 1024
45
-
46
- // Pauses between attempts. Three attempts in total ride out short network
47
- // blips before the job pauses with the last error.
48
- export const EDGE_RETRY_WAITS = [800, 2500]
49
-
50
- export async function retryEdge(once, signal, waits = EDGE_RETRY_WAITS, wait = delay) {
51
- for (let attempt = 0; ; attempt++) {
52
- signal.throwIfAborted()
53
- try {
54
- return await once()
55
- } catch (error) {
56
- signal.throwIfAborted()
57
- if (attempt >= waits.length) throw error
58
- await wait(waits[attempt], undefined, { signal })
59
- }
60
- }
61
- }
62
-
63
- export async function synthesizeEdge(input, signal, options = {}) {
64
- if (!edgeVoices.some(voice => voice.id === input.voiceId)) throw new Error('EDGE_INVALID_VOICE')
65
- if (![...input.text].length || [...input.text].length > 500) throw new Error('EDGE_INVALID_TEXT')
66
- return retryEdge(() => synthesizeOnce(input, signal, options), signal, edgeRetryWaits(input.text))
67
- }
68
-
69
- // Text with nothing to pronounce comes back empty on every attempt, so a second
70
- // try only costs another connection and another few seconds of the job.
71
- export function edgeRetryWaits(text) {
72
- return hasSpeakable(text) ? EDGE_RETRY_WAITS : []
73
- }
74
-
75
- const strip = value => String(value ?? '').replace(/\u001b\[[0-9;]*m/gu, '').replace(/\r/gu, '').trim()
76
-
77
- // Turn the child's stderr into one short line. The worker writes a JSON error
78
- // line for expected msedge-tts failures; crashes fall back to the last lines.
79
- // The reported code lets the parent pick a concrete error instead of always
80
- // calling it an outage.
81
- function edgeFailure(stderr) {
82
- const raw = strip(stderr)
83
- if (!raw) return { detail: '', code: null }
84
- const lines = raw.split('\n').map(line => line.trim()).filter(Boolean)
85
- for (let index = lines.length - 1; index >= 0; index--) {
86
- if (!lines[index].startsWith('{')) continue
87
- try {
88
- const value = JSON.parse(lines[index])
89
- if (value && typeof value.message === 'string' && value.message) {
90
- const name = typeof value.error === 'string' && value.error ? value.error + ': ' : ''
91
- const code = value.code ? ' (' + value.code + ')' : ''
92
- return {
93
- detail: (name + value.message + code).slice(0, DETAIL_LIMIT),
94
- code: typeof value.code === 'string' && value.code ? value.code : null,
95
- }
96
- }
97
- } catch { /* not the structured line */ }
98
- }
99
- return { detail: lines.slice(-4).join(' | ').slice(0, DETAIL_LIMIT), code: null }
100
- }
101
-
102
- export function edgeFailureDetail(stderr) {
103
- return edgeFailure(stderr).detail
104
- }
105
-
106
- const TIMING_LIMIT = 512 * 1024
107
-
108
- // Words as { o: start ms, d: duration ms, t: text } in speaking order; anything unreadable yields none.
109
- export function parseTiming(raw) {
110
- const line = String(raw ?? '').trim().split('\n').at(-1)
111
- if (!line) return []
112
- try {
113
- const words = JSON.parse(line)
114
- return Array.isArray(words) ? words.filter(word => Number.isFinite(word?.o) && Number.isFinite(word?.d) && typeof word?.t === 'string' && word.t) : []
115
- } catch { return [] }
116
- }
117
-
118
- export function synthesizeOnce(input, signal, { timeout = 23_000, command = process.execPath, args = [workerFile] } = {}) {
119
- return new Promise((resolve, reject) => {
120
- const child = spawn(command, args, {
121
- // fd 3 carries word timing from the worker (one JSON line).
122
- windowsHide: true, stdio: ['pipe', 'pipe', 'pipe', 'pipe'],
123
- env: { ...process.env, NODE_OPTIONS: '', ELECTRON_RUN_AS_NODE: '1' },
124
- })
125
- const chunks = []
126
- let size = 0
127
- let stderr = ''
128
- let timing = ''
129
- let failure
130
- function terminate(error) {
131
- failure ??= error
132
- child.kill()
133
- }
134
- const abort = () => terminate(signal.reason)
135
- const timer = setTimeout(() => terminate(new Error('EDGE_TIMEOUT')), timeout)
136
- signal.addEventListener('abort', abort, { once: true })
137
- if (signal.aborted) abort()
138
- child.stdout.on('data', chunk => {
139
- size += chunk.length
140
- if (size <= 8 * 1024 * 1024) chunks.push(chunk)
141
- else terminate(new Error('EDGE_AUDIO_TOO_LARGE'))
142
- })
143
- child.stderr.on('data', chunk => {
144
- if (stderr.length < STDERR_LIMIT) stderr += chunk.toString('utf8')
145
- })
146
- child.stdio[3]?.on('data', chunk => { if (timing.length < TIMING_LIMIT) timing += chunk.toString('utf8') })
147
- child.stdio[3]?.on('error', () => {})
148
- child.stdin.on('error', () => {})
149
- child.on('error', error => {
150
- failure ??= Object.assign(new Error('EDGE_WORKER_START_FAILED'), { detail: strip(error?.message ?? error) || null })
151
- })
152
- child.on('close', code => {
153
- clearTimeout(timer)
154
- signal.removeEventListener('abort', abort)
155
- if (!failure && code === 0 && size > 0) {
156
- // The audio stays a Buffer for every caller; timing rides along as a property.
157
- const audio = Buffer.concat(chunks)
158
- audio.marks = parseTiming(timing)
159
- resolve(audio)
160
- return
161
- }
162
- const { detail, code: reported } = edgeFailure(stderr)
163
- // An empty turn is its own failure: it is a content result, not an outage.
164
- const error = failure ?? (reported === 'EDGE_EMPTY_AUDIO' ? new Error('EDGE_EMPTY_AUDIO') : new Error('EDGE_UNAVAILABLE'))
165
- if (detail && !error.detail) error.detail = detail
166
- reject(error)
167
- })
168
- child.stdin.end(JSON.stringify(input))
169
- })
170
- }
1
+ import { spawn } from 'node:child_process'
2
+ import { setTimeout as delay } from 'node:timers/promises'
3
+ import { fileURLToPath } from 'node:url'
4
+ import { hasSpeakable } from '../domain/segment.mjs'
5
+
6
+ // Order matters: chooseVoices hands out the first unused voice of a matching
7
+ // gender, so new voices are only ever appended. Appending leaves every role that
8
+ // already had its own voice untouched. auto: false voices (regional accents)
9
+ // are offered in the picker but never assigned automatically.
10
+ // Use only IDs listed by the Edge Read Aloud voice directory.
11
+ // Added after 10/10 real synthesis runs each (5 simplified, 5
12
+ // traditional); zh-TW-YunJheNeural failed 4/10 with truncated streams and is excluded.
13
+ // Later voices are appended. Chinese automatic assignment still walks the
14
+ // original zh-CN / zh-TW entries first, so roles that already had a voice keep it.
15
+ export const edgeVoices = [
16
+ { id: 'zh-CN-XiaoxiaoNeural', name: '晓晓', gender: 'female', age: 'adult', auto: true },
17
+ { id: 'zh-CN-YunxiNeural', name: '云希', gender: 'male', age: 'adult', auto: true },
18
+ { id: 'zh-CN-YunjianNeural', name: '云健', gender: 'male', age: 'adult', auto: true },
19
+ { id: 'zh-CN-XiaoyiNeural', name: '晓伊', gender: 'female', age: 'adult', auto: true },
20
+ { id: 'zh-TW-HsiaoChenNeural', name: '曉臻', gender: 'female', age: 'adult', auto: true },
21
+ { id: 'zh-TW-HsiaoYuNeural', name: '曉雨', gender: 'female', age: 'adult', auto: true },
22
+ { id: 'zh-CN-YunyangNeural', name: '云扬', gender: 'male', age: 'adult', auto: true },
23
+ { id: 'zh-CN-YunxiaNeural', name: '云夏', gender: 'male', age: 'child', auto: true },
24
+ { id: 'en-US-AriaNeural', name: 'Aria(美式英语)', gender: 'female', age: 'adult', auto: true },
25
+ { id: 'en-US-JennyNeural', name: 'Jenny(美式英语)', gender: 'female', age: 'adult', auto: true },
26
+ { id: 'en-US-GuyNeural', name: 'Guy(美式英语)', gender: 'male', age: 'adult', auto: true },
27
+ { id: 'en-GB-SoniaNeural', name: 'Sonia(英式英语)', gender: 'female', age: 'adult', auto: true },
28
+ { id: 'en-GB-RyanNeural', name: 'Ryan(英式英语)', gender: 'male', age: 'adult', auto: true },
29
+ { id: 'en-US-AnaNeural', name: 'Ana(美式英语)', gender: 'female', age: 'child', auto: true },
30
+ { id: 'zh-CN-liaoning-XiaobeiNeural', name: '晓北(东北口音)', gender: 'female', age: 'adult', auto: false },
31
+ { id: 'zh-CN-shaanxi-XiaoniNeural', name: '晓妮(陕西口音)', gender: 'female', age: 'adult', auto: false },
32
+ ]
33
+
34
+ const workerFile = fileURLToPath(new URL('./edge-worker.mjs', import.meta.url))
35
+ const DETAIL_LIMIT = 600
36
+ const STDERR_LIMIT = 8 * 1024
37
+
38
+ // Pauses between attempts. Three attempts in total ride out short network
39
+ // blips before the job pauses with the last error.
40
+ export const EDGE_RETRY_WAITS = [800, 2500]
41
+
42
+ export async function retryEdge(once, signal, waits = EDGE_RETRY_WAITS, wait = delay) {
43
+ for (let attempt = 0; ; attempt++) {
44
+ signal.throwIfAborted()
45
+ try {
46
+ return await once()
47
+ } catch (error) {
48
+ signal.throwIfAborted()
49
+ if (attempt >= waits.length) throw error
50
+ await wait(waits[attempt], undefined, { signal })
51
+ }
52
+ }
53
+ }
54
+
55
+ export async function synthesizeEdge(input, signal, options = {}) {
56
+ if (!edgeVoices.some(voice => voice.id === input.voiceId)) throw new Error('EDGE_INVALID_VOICE')
57
+ if (![...input.text].length || [...input.text].length > 500) throw new Error('EDGE_INVALID_TEXT')
58
+ return retryEdge(() => synthesizeOnce(input, signal, options), signal, edgeRetryWaits(input.text))
59
+ }
60
+
61
+ // Text with nothing to pronounce comes back empty on every attempt, so a second
62
+ // try only costs another connection and another few seconds of the job.
63
+ export function edgeRetryWaits(text) {
64
+ return hasSpeakable(text) ? EDGE_RETRY_WAITS : []
65
+ }
66
+
67
+ const strip = value => String(value ?? '').replace(/\u001b\[[0-9;]*m/gu, '').replace(/\r/gu, '').trim()
68
+
69
+ // Turn the child's stderr into one short line. The worker writes a JSON error
70
+ // line for expected msedge-tts failures; crashes fall back to the last lines.
71
+ // The reported code lets the parent pick a concrete error instead of always
72
+ // calling it an outage.
73
+ function edgeFailure(stderr) {
74
+ const raw = strip(stderr)
75
+ if (!raw) return { detail: '', code: null }
76
+ const lines = raw.split('\n').map(line => line.trim()).filter(Boolean)
77
+ for (let index = lines.length - 1; index >= 0; index--) {
78
+ if (!lines[index].startsWith('{')) continue
79
+ try {
80
+ const value = JSON.parse(lines[index])
81
+ if (value && typeof value.message === 'string' && value.message) {
82
+ const name = typeof value.error === 'string' && value.error ? value.error + ': ' : ''
83
+ const code = value.code ? ' (' + value.code + ')' : ''
84
+ return {
85
+ detail: (name + value.message + code).slice(0, DETAIL_LIMIT),
86
+ code: typeof value.code === 'string' && value.code ? value.code : null,
87
+ }
88
+ }
89
+ } catch { /* not the structured line */ }
90
+ }
91
+ return { detail: lines.slice(-4).join(' | ').slice(0, DETAIL_LIMIT), code: null }
92
+ }
93
+
94
+ export function edgeFailureDetail(stderr) {
95
+ return edgeFailure(stderr).detail
96
+ }
97
+
98
+ const TIMING_LIMIT = 512 * 1024
99
+
100
+ // Words as { o: start ms, d: duration ms, t: text } in speaking order; anything unreadable yields none.
101
+ export function parseTiming(raw) {
102
+ const line = String(raw ?? '').trim().split('\n').at(-1)
103
+ if (!line) return []
104
+ try {
105
+ const words = JSON.parse(line)
106
+ return Array.isArray(words) ? words.filter(word => Number.isFinite(word?.o) && Number.isFinite(word?.d) && typeof word?.t === 'string' && word.t) : []
107
+ } catch { return [] }
108
+ }
109
+
110
+ export function synthesizeOnce(input, signal, { timeout = 23_000, command = process.execPath, args = [workerFile] } = {}) {
111
+ return new Promise((resolve, reject) => {
112
+ const child = spawn(command, args, {
113
+ // fd 3 carries word timing from the worker (one JSON line).
114
+ windowsHide: true, stdio: ['pipe', 'pipe', 'pipe', 'pipe'],
115
+ env: { ...process.env, NODE_OPTIONS: '', ELECTRON_RUN_AS_NODE: '1' },
116
+ })
117
+ const chunks = []
118
+ let size = 0
119
+ let stderr = ''
120
+ let timing = ''
121
+ let failure
122
+ function terminate(error) {
123
+ failure ??= error
124
+ child.kill()
125
+ }
126
+ const abort = () => terminate(signal.reason)
127
+ const timer = setTimeout(() => terminate(new Error('EDGE_TIMEOUT')), timeout)
128
+ signal.addEventListener('abort', abort, { once: true })
129
+ if (signal.aborted) abort()
130
+ child.stdout.on('data', chunk => {
131
+ size += chunk.length
132
+ if (size <= 8 * 1024 * 1024) chunks.push(chunk)
133
+ else terminate(new Error('EDGE_AUDIO_TOO_LARGE'))
134
+ })
135
+ child.stderr.on('data', chunk => {
136
+ if (stderr.length < STDERR_LIMIT) stderr += chunk.toString('utf8')
137
+ })
138
+ child.stdio[3]?.on('data', chunk => { if (timing.length < TIMING_LIMIT) timing += chunk.toString('utf8') })
139
+ child.stdio[3]?.on('error', () => {})
140
+ child.stdin.on('error', () => {})
141
+ child.on('error', error => {
142
+ failure ??= Object.assign(new Error('EDGE_WORKER_START_FAILED'), { detail: strip(error?.message ?? error) || null })
143
+ })
144
+ child.on('close', code => {
145
+ clearTimeout(timer)
146
+ signal.removeEventListener('abort', abort)
147
+ if (!failure && code === 0 && size > 0) {
148
+ // The audio stays a Buffer for every caller; timing rides along as a property.
149
+ const audio = Buffer.concat(chunks)
150
+ audio.marks = parseTiming(timing)
151
+ resolve(audio)
152
+ return
153
+ }
154
+ const { detail, code: reported } = edgeFailure(stderr)
155
+ // An empty turn is its own failure: it is a content result, not an outage.
156
+ const error = failure ?? (reported === 'EDGE_EMPTY_AUDIO' ? new Error('EDGE_EMPTY_AUDIO') : new Error('EDGE_UNAVAILABLE'))
157
+ if (detail && !error.detail) error.detail = detail
158
+ reject(error)
159
+ })
160
+ child.stdin.end(JSON.stringify(input))
161
+ })
162
+ }
@@ -7,8 +7,8 @@ import { voiceAssignments } from '../domain/voice-assignment.mjs'
7
7
  import { messageFor } from '../domain/messages.mjs'
8
8
  import { addModelUsage, normalizeModelUsage } from './model-usage.mjs'
9
9
 
10
- import { NARRATOR, castHints, extractRoster, extractWindow, narrationSlice, recoverCastBatch } from './cast.mjs'
11
- import { partsFromLines, splitOversized, uncoveredSpeakable } from '../domain/script-lines.mjs'
10
+ import { NARRATOR, extractRoster, extractWindow, narrationSlice, recoverCastBatch } from './cast.mjs'
11
+ import { EXTRACT_SCRIPT, partsFromLines, splitOversized, uncoveredSpeakable } from '../domain/script-lines.mjs'
12
12
  import { assertModelProviderReady, createStreamGate, MODEL_IDLE_MS, MODEL_TOTAL_MS, readModelStream } from './model-stream.mjs'
13
13
 
14
14
  export { EMOTIONS, NARRATOR } from './cast.mjs'
@@ -463,7 +463,7 @@ export function createEditorialService(llm, library, {
463
463
  }
464
464
  let annotations = {}
465
465
  let scriptLines = null
466
- if (spec.cast && progress.script === 'extract-v1') {
466
+ if (spec.cast && EXTRACT_SCRIPT && progress.script === 'extract-v1') {
467
467
  progress.stage = 'scripting'
468
468
  const windowLimit = Number.isSafeInteger(extractChars) && extractChars > 0 ? extractChars : extractWindowChars(spec.selection)
469
469
  progress.windows ??= extractSourceWindows(chapter.text, removed, windowLimit).map(item => ({ ...item, state: 'pending', splits: 0 }))
@@ -566,7 +566,6 @@ export function createEditorialService(llm, library, {
566
566
  progress.castWindow ??= progress.cast?.length ? LEGACY_CAST_WINDOW
567
567
  : { chars: castWindow.chars, segments: castSegmentsFor(spec.selection, castWindow.segments) }
568
568
  const groups = windows(segments, progress.castWindow.chars, progress.castWindow.segments)
569
- const hints = castHints(chapter.text, segments)
570
569
  progress.cast ??= []
571
570
  progress.castTotal = groups.length
572
571
  progress.stage = 'scripting'
@@ -599,7 +598,6 @@ export function createEditorialService(llm, library, {
599
598
  return { text: part.text, roleName: names.get(note?.roleId) ?? '' }
600
599
  })
601
600
  const spoken = group.filter(part => !isSeparator(part.text))
602
- .map(part => (hints.has(part.id) ? { ...part, ...hints.get(part.id) } : part))
603
601
  signal.throwIfAborted()
604
602
  const request = async (prompt, payload) => {
605
603
  assertModelProviderReady(spec.selection?.provider, gate)
package/src/host/jobs.mjs CHANGED
@@ -75,7 +75,7 @@ function retakeStored(row, part) {
75
75
  return Boolean(row) && part.retake === true && row.writeId && row.writeId === part.localWriteId
76
76
  }
77
77
 
78
- export function createJobQueue({ library, editorial, llm, gatewayFor, errorCode, logger, synthesize = synthesizePart, edgeConcurrency = EDGE_CONCURRENCY, autoResumeWaits = EDGE_AUTO_RESUME_WAITS, transientWindow = LAIVOX_TRANSIENT_WINDOW, extractScripts = EXTRACT_SCRIPT }) {
78
+ export function createJobQueue({ library, editorial, llm, gatewayFor, errorCode, logger, synthesize = synthesizePart, edgeConcurrency = EDGE_CONCURRENCY, autoResumeWaits = EDGE_AUTO_RESUME_WAITS, transientWindow = LAIVOX_TRANSIENT_WINDOW }) {
79
79
  let guardBookExport = async (_book, run) => run()
80
80
  let flight
81
81
  let dispatcher
@@ -229,8 +229,7 @@ export function createJobQueue({ library, editorial, llm, gatewayFor, errorCode,
229
229
  const choice = spec.laivoxNarratorDefault
230
230
  const narratorDefault = gateway && (!choice?.account || choice.account === gateway.account) ? choice ?? null : null
231
231
  const legacyCast = Array.isArray(progress.cast) && progress.cast.length > 0 && progress.script !== 'extract-v1'
232
- const extractJob = spec.cast ? extractScripts : chapter.editorial?.version === 3
233
- if ((spec.mode === 'multi' || (spec.purpose === 'cast' && spec.mode === 'reading')) && !legacyCast && !progress.parts?.length && extractJob) {
232
+ if (EXTRACT_SCRIPT && (spec.mode === 'multi' || (spec.purpose === 'cast' && spec.mode === 'reading')) && !legacyCast && !progress.parts?.length && (spec.cast || chapter.editorial?.version === 3)) {
234
233
  progress.script = 'extract-v1'
235
234
  progress.speakText = 'extract-v1'
236
235
  progress.segmentVersion = 3
@@ -955,7 +954,7 @@ export function createJobQueue({ library, editorial, llm, gatewayFor, errorCode,
955
954
  signal?.throwIfAborted()
956
955
  const estimated = await library.estimateGroup(group.map(row => row.id), input, {
957
956
  cleanWindow: CLEAN_WINDOW, castWindow: { chars: CAST_WINDOW, segments: castSegmentsFor(resolved) },
958
- extract: extractScripts, extractChars: extractWindowChars(resolved),
957
+ extract: EXTRACT_SCRIPT, extractChars: extractWindowChars(resolved),
959
958
  })
960
959
  for (const item of estimated) counted.set(item.id, item)
961
960
  }