dsh-podwave 0.11.26 → 0.11.28

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-podwave",
3
- "version": "0.11.26",
3
+ "version": "0.11.28",
4
4
  "description": "DeepSeek Harness 插件:本地优先的播客播放器 + 转写 + 双语字幕 + 字幕翻译。",
5
5
  "type": "module",
6
6
  "main": "./src/host.js",
@@ -40,6 +40,9 @@
40
40
  "url": "git+https://github.com/Watchcats211/dsh-podwave.git"
41
41
  },
42
42
  "homepage": "https://github.com/Watchcats211/dsh-podwave#readme",
43
+ "bugs": {
44
+ "url": "https://github.com/Watchcats211/dsh-podwave/issues"
45
+ },
43
46
  "scripts": {
44
47
  "build": "node build.mjs",
45
48
  "prepack": "npm run build",
@@ -1,5 +1,10 @@
1
1
  #!/usr/bin/env python3
2
- """本地字幕翻译:读取 JSON 任务,用 MLX 模型逐批翻译,结果以 JSON 写到 stdout。"""
2
+ """本地字幕翻译:读取 JSON 任务,用 MLX 模型逐批翻译,结果以 JSON 写到 stdout。
3
+
4
+ 小模型遇到很短的句子会自作主张把几行并成一行,编号就整体后移,
5
+ 下游按编号取译文时就会整批错位。所以这里校验「读回来的行数 == 送进去的行数」,
6
+ 对不上就降批重试(对半 → 最后一行一行翻),保证一行对一行。
7
+ """
3
8
  import json
4
9
  import re
5
10
  import sys
@@ -7,6 +12,56 @@ import sys
7
12
  from mlx_lm import generate, load
8
13
 
9
14
 
15
+ BATCH_SIZE = 15
16
+ MAX_TOKENS = 1024
17
+
18
+
19
+ def parse_numbered(output: str, count: int) -> dict:
20
+ parsed = {}
21
+ for line in output.splitlines():
22
+ match = re.match(r"^\s*(\d+)[.、)]\s*(.+?)\s*$", line)
23
+ if not match:
24
+ continue
25
+ index = int(match.group(1))
26
+ if 1 <= index <= count and index not in parsed:
27
+ parsed[index] = match.group(2)
28
+ if not parsed:
29
+ lines = [line.strip() for line in output.splitlines() if line.strip()]
30
+ if len(lines) == count:
31
+ parsed = {index: line for index, line in enumerate(lines, 1)}
32
+ return parsed
33
+
34
+
35
+ def translate_batch(batch: list, model, tokenizer, language: str) -> dict:
36
+ numbered = "\n".join(f"{index + 1}. {item['text']}" for index, item in enumerate(batch))
37
+ messages = [
38
+ {
39
+ "role": "system",
40
+ "content": (
41
+ "You are a professional subtitle translator. Translate each numbered line into "
42
+ f"{language}. Preserve proper names, numbers and terminology. Output only the translated "
43
+ "numbered lines in the same order, one per line, in the format '1. translation'. "
44
+ "Do not add explanations."
45
+ ),
46
+ },
47
+ {"role": "user", "content": numbered},
48
+ ]
49
+ prompt = tokenizer.apply_chat_template(
50
+ messages, add_generation_prompt=True, enable_thinking=False, tokenize=False
51
+ )
52
+ output = generate(model, tokenizer, prompt=prompt, max_tokens=MAX_TOKENS, verbose=False)
53
+ parsed = parse_numbered(output, len(batch))
54
+ if len(parsed) == len(batch):
55
+ return parsed
56
+ if len(batch) > 1:
57
+ mid = (len(batch) + 1) // 2
58
+ merged = translate_batch(batch[:mid], model, tokenizer, language)
59
+ for index, text in translate_batch(batch[mid:], model, tokenizer, language).items():
60
+ merged[index + mid] = text
61
+ return merged
62
+ return parsed
63
+
64
+
10
65
  def main() -> int:
11
66
  with open(sys.argv[1], "r", encoding="utf-8") as handle:
12
67
  config = json.load(handle)
@@ -17,37 +72,9 @@ def main() -> int:
17
72
  items = config["items"]
18
73
  results = {}
19
74
 
20
- batch_size = 15
21
- for start in range(0, len(items), batch_size):
22
- batch = items[start:start + batch_size]
23
- numbered = "\n".join(f"{index + 1}. {item['text']}" for index, item in enumerate(batch))
24
- messages = [
25
- {
26
- "role": "system",
27
- "content": (
28
- "You are a professional subtitle translator. Translate each numbered line into "
29
- f"{language}. Preserve proper names, numbers and terminology. Output only the translated "
30
- "numbered lines in the same order, one per line, in the format '1. translation'. "
31
- "Do not add explanations."
32
- ),
33
- },
34
- {"role": "user", "content": numbered},
35
- ]
36
- prompt = tokenizer.apply_chat_template(
37
- messages, add_generation_prompt=True, enable_thinking=False, tokenize=False
38
- )
39
- output = generate(model, tokenizer, prompt=prompt, max_tokens=1024, verbose=False)
40
- parsed = {}
41
- for line in output.splitlines():
42
- match = re.match(r"^\s*(\d+)[.、)]\s*(.+?)\s*$", line)
43
- if match:
44
- index = int(match.group(1))
45
- if 1 <= index <= len(batch) and index not in parsed:
46
- parsed[index] = match.group(2)
47
- if not parsed:
48
- lines = [line.strip() for line in output.splitlines() if line.strip()]
49
- if len(lines) == len(batch):
50
- parsed = {index: line for index, line in enumerate(lines, 1)}
75
+ for start in range(0, len(items), BATCH_SIZE):
76
+ batch = items[start:start + BATCH_SIZE]
77
+ parsed = translate_batch(batch, model, tokenizer, language)
51
78
  for index, item in enumerate(batch, 1):
52
79
  results[str(item["id"])] = parsed.get(index, "")
53
80
 
package/src/asr-api.js ADDED
@@ -0,0 +1,227 @@
1
+ // 云端转写:DeepSeek 语音识别接口(2026-11-13 随「全家桶」开放)。
2
+ //
3
+ // POST {base}/v1/tools/asr,multipart/form-data 上传一整段音频,返回整段文本。
4
+ // 官方硬限制:单次 ≤120 秒、≤8 MiB、16 位 PCM WAV 或 Ogg Opus;语种自动识别;
5
+ // 不支持流式;响应只有整段 text,**没有词级/句级时间戳**,所以时间轴要靠自己切块 + 按字数分配。
6
+ //
7
+ // 这里只放「调一次接口」和「把一整段文本变成带时间的行」两件事,
8
+ // 切片、并发、落盘、合并都留在 transcribe.js 里,和本地引擎复用同一套流程。
9
+ import fs from 'node:fs'
10
+ import { getSection } from './config.js'
11
+
12
+ export const API_ASR_PATH = '/v1/tools/asr'
13
+ // 官方要求 ≤120 秒。留 20 秒余量:切片是按容器时间戳切的,
14
+ // 有些音频的重采样/补帧会多出零点几秒,卡在 120 上迟早翻车。
15
+ // 块越大,句子被块边界切开的概率越低(切点还会吸附到静音处,见 transcribe.js 的 planCuts)。
16
+ export const API_CHUNK_SECONDS = 100
17
+ export const API_MAX_SECONDS = 100
18
+ export const API_MAX_BYTES = 8 * 1024 * 1024
19
+ const REQUEST_TIMEOUT_MS = 180000
20
+ const MAX_ATTEMPTS = 4
21
+
22
+ const SENTENCE_END = /[。!?!?…]/
23
+ const CLAUSE_END = /[,,;;、]/
24
+ // 紧跟句末标点的右引号/右括号要留在同一行,不然会出现「他说:」+「」」这种断裂。
25
+ const CLOSER = /[」』))】》”’"]/
26
+ // 一条字幕的长度上限(字符数)。有词边界的语言可以长一点,中日文没有空格,短一些。
27
+ const HARD_LIMIT = 84
28
+ const CJK_HARD_LIMIT = 48
29
+ // 逗号/顿号只有攒到这么长才算断点:短句里的逗号断开反而更难读。
30
+ // 中日文一行 30 字左右最好读,超过 48 字就必须断。
31
+ const SOFT_MIN = 30
32
+
33
+ function round2(value) {
34
+ return Math.round((Number(value) || 0) * 100) / 100
35
+ }
36
+
37
+ /**
38
+ * 转写走哪条路:`'api'`(默认,开箱即用)还是 `'local'`(本地模型,省钱但费机器)。
39
+ * 只有明确写了 `local` 才走本地,其它一律按云端处理,避免老配置突然掉回「没装模型」的死胡同。
40
+ */
41
+ export function asrProvider() {
42
+ const section = getSection('transcribe') || {}
43
+ return String(section.provider || '').toLowerCase() === 'local' ? 'local' : 'api'
44
+ }
45
+
46
+ /**
47
+ * 云端转写用到的端点与密钥。apiKey 留空时自动复用翻译那把 DeepSeek key ——
48
+ * 用户填一次就能同时用转写和翻译,不用记两次。
49
+ */
50
+ export function asrApiConfig() {
51
+ const api = getSection('api') || {}
52
+ const translate = getSection('translate') || {}
53
+ const base = String(api.base || translate.apiBase || 'https://api.deepseek.com')
54
+ .trim()
55
+ .replace(/\/+$/, '')
56
+ const key = String(api.key || translate.apiKey || '').trim()
57
+ return { base, url: `${base}${API_ASR_PATH}`, key, hasKey: Boolean(key) }
58
+ }
59
+
60
+ function describeFailure(status, payload) {
61
+ const message = String(payload?.error?.message || payload?.message || '').trim()
62
+ if (status === 401 || status === 403) {
63
+ return 'DeepSeek API key 无效或没有语音识别权限,请到设置里检查'
64
+ }
65
+ if (status === 402) return 'DeepSeek 账户余额不足,请充值后再转写'
66
+ if (status === 413) return '音频块太大,超过接口限制'
67
+ if (status === 429) return '请求太频繁被限流,稍后会自动重试'
68
+ if (message) return `语音识别失败:${message}`
69
+ return `语音识别失败(HTTP ${status})`
70
+ }
71
+
72
+ function sleep(ms) {
73
+ return new Promise((resolve) => setTimeout(resolve, ms))
74
+ }
75
+
76
+ /**
77
+ * 把一段音频发给 DeepSeek ASR。
78
+ * @returns {Promise<{text: string, durationMs: number}>}
79
+ */
80
+ export async function transcribeChunk(file, config = asrApiConfig(), { signal } = {}) {
81
+ if (!config.hasKey) {
82
+ throw Object.assign(new Error('还没有填 DeepSeek API key,去设置里填一个就能用云端转写'), { status: 400 })
83
+ }
84
+ const bytes = await fs.promises.readFile(file)
85
+ if (!bytes.length) throw new Error('音频块是空的')
86
+ if (bytes.length > API_MAX_BYTES) {
87
+ throw new Error(`音频块 ${(bytes.length / 1024 / 1024).toFixed(1)} MB,超过接口的 8 MB 上限`)
88
+ }
89
+
90
+ let lastError = null
91
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt += 1) {
92
+ const form = new FormData()
93
+ form.append('file', new Blob([bytes], { type: 'audio/wav' }), 'chunk.wav')
94
+ const controller = new AbortController()
95
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
96
+ const onAbort = () => controller.abort()
97
+ if (signal) signal.addEventListener('abort', onAbort, { once: true })
98
+ try {
99
+ const response = await fetch(config.url, {
100
+ method: 'POST',
101
+ headers: { authorization: `Bearer ${config.key}` },
102
+ body: form,
103
+ signal: controller.signal,
104
+ })
105
+ const raw = await response.text()
106
+ let payload = null
107
+ try {
108
+ payload = raw ? JSON.parse(raw) : null
109
+ } catch {
110
+ payload = null
111
+ }
112
+ if (!response.ok) {
113
+ const error = Object.assign(new Error(describeFailure(response.status, payload)), { status: response.status })
114
+ // 4xx 里只有 429 值得重试,其余(key 错、余额空、参数错)重试也没用。
115
+ if (response.status !== 429 && response.status < 500) throw error
116
+ lastError = error
117
+ } else {
118
+ return {
119
+ text: String(payload?.text || ''),
120
+ durationMs: Number(payload?.duration_ms) || 0,
121
+ }
122
+ }
123
+ } catch (error) {
124
+ if (error?.name === 'AbortError') {
125
+ if (signal?.aborted) throw new Error('用户取消了转写')
126
+ lastError = Object.assign(new Error('语音识别超时,稍后会自动重试'), { status: 504 })
127
+ } else if (error?.status && error.status !== 429 && error.status < 500) {
128
+ throw error
129
+ } else {
130
+ lastError = error
131
+ }
132
+ } finally {
133
+ clearTimeout(timer)
134
+ if (signal) signal.removeEventListener('abort', onAbort)
135
+ }
136
+ if (signal?.aborted) throw new Error('用户取消了转写')
137
+ if (attempt < MAX_ATTEMPTS) await sleep(600 * attempt)
138
+ }
139
+ throw lastError || new Error('语音识别失败')
140
+ }
141
+
142
+ /**
143
+ * 把一整段识别文本切成字幕句:句末标点断句;逗号只在够长时才断;
144
+ * 超长且没有标点(日语、中文常见)就退到最近的空格/标点处断,实在没有才硬断。
145
+ */
146
+ export function splitApiSentences(text) {
147
+ const chars = Array.from(String(text || ''))
148
+ const pieces = []
149
+ let buffer = ''
150
+ const flush = () => {
151
+ const piece = buffer.trim()
152
+ if (piece) pieces.push(piece)
153
+ buffer = ''
154
+ }
155
+ for (let index = 0; index < chars.length; index += 1) {
156
+ const char = chars[index]
157
+ buffer += char
158
+ const next = chars[index + 1] || ''
159
+ // 句末标点:后面还跟着右引号/右括号时先不断,等它们进来再断。
160
+ if (SENTENCE_END.test(char)) {
161
+ if (CLOSER.test(next)) continue
162
+ flush()
163
+ continue
164
+ }
165
+ if (CLOSER.test(char) && SENTENCE_END.test(chars[index - 1] || '')) {
166
+ flush()
167
+ continue
168
+ }
169
+ const length = buffer.trim().length
170
+ if (CLAUSE_END.test(char) && length >= SOFT_MIN) {
171
+ flush()
172
+ continue
173
+ }
174
+ if (length >= (/\s/.test(buffer) ? HARD_LIMIT : CJK_HARD_LIMIT)) {
175
+ const cut = lastBreakIndex(buffer)
176
+ if (cut > SOFT_MIN) {
177
+ const head = buffer.slice(0, cut).trim()
178
+ if (head) pieces.push(head)
179
+ buffer = buffer.slice(cut)
180
+ } else {
181
+ flush()
182
+ }
183
+ }
184
+ }
185
+ flush()
186
+ return pieces
187
+ }
188
+
189
+ // 在超长且没有标点的片段里挑一个断点:优先空格(英法等有词边界),其次标点。
190
+ function lastBreakIndex(text) {
191
+ for (let index = text.length - 1; index > 0; index -= 1) {
192
+ if (/[\s,,;;、]/.test(text[index])) return index + 1
193
+ }
194
+ return -1
195
+ }
196
+
197
+ /**
198
+ * 把一整段识别文本切成字幕行,并在 [start, start+duration) 之间按字数比例分配时间。
199
+ * 接口不给时间戳,这个分配是估算:块内误差可以接受,
200
+ * 比起「一行 30 秒」那种粗粒度,按句读切分读起来舒服得多。
201
+ */
202
+ export function buildApiLines(text, start, duration) {
203
+ const clean = String(text || '').replace(/\s+/g, ' ').trim()
204
+ if (!clean) return []
205
+ const pieces = splitApiSentences(clean)
206
+ if (!pieces.length) return []
207
+
208
+ const totalChars = pieces.reduce((sum, piece) => sum + piece.length, 0) || 1
209
+ const span = Math.max(Number(duration) || 0, pieces.length * 0.4)
210
+ const lines = []
211
+ let cursor = 0
212
+ for (const [index, piece] of pieces.entries()) {
213
+ const length = (piece.length / totalChars) * span
214
+ const lineStart = round2(start + cursor)
215
+ cursor += length
216
+ const isLast = index === pieces.length - 1
217
+ const lineEnd = round2(start + (isLast ? span : cursor))
218
+ lines.push({
219
+ id: index + 1,
220
+ start: lineStart,
221
+ // 单字符行(「好。」)也至少给 0.3 秒,不然播放器高亮会一闪而过。
222
+ end: Math.max(lineEnd, round2(lineStart + 0.3)),
223
+ text: piece,
224
+ })
225
+ }
226
+ return lines
227
+ }
package/src/config.js CHANGED
@@ -31,19 +31,31 @@ function cachedDefaultModels() {
31
31
  export const CONFIG_DEFAULTS = {
32
32
  schemaVersion: 1,
33
33
  ui: { showSidebarPanel: true, sidebarCollapsed: false },
34
+ // DeepSeek API 的地址 / 密钥 / 对话模型:转写和翻译共用这一份,用户只填一次。
35
+ // 老版本把这三项存在 translate 段里,读到时由 migrateApiSection() 挪过来。
36
+ api: {
37
+ base: 'https://api.deepseek.com',
38
+ key: '',
39
+ model: 'deepseek-chat',
40
+ },
34
41
  translate: {
35
42
  provider: 'api',
36
43
  target: 'zh',
37
- apiBase: 'https://api.deepseek.com',
38
- apiModel: 'deepseek-chat',
39
- apiKey: '',
40
44
  },
41
45
  // 默认模型绝不能写死 MLX:那套模型 platform 是 darwin-arm64,Windows 装不了。
42
46
  // dir 为空表示用默认目录(<数据目录>/models);用户改过则存绝对路径。
43
47
  get models() {
44
48
  return { dir: '', ...cachedDefaultModels() }
45
49
  },
46
- transcribe: { hotwords: [], chunkMinutes: 1, diarize: true },
50
+ // 转写默认走云端 API:装好插件、填一个 DeepSeek key 就能用,不用先下载 2.4G 模型。
51
+ // 想省钱可以在设置里切成本地模型(provider: 'local',需要先一键安装运行时和模型)。
52
+ // 密钥与地址统一在 api 段,转写这里只管「用哪个引擎」。
53
+ transcribe: {
54
+ provider: 'api',
55
+ hotwords: [],
56
+ chunkMinutes: 1,
57
+ diarize: true,
58
+ },
47
59
  import: { mode: 'copy' },
48
60
  }
49
61
 
@@ -112,11 +124,32 @@ function migrateLegacy() {
112
124
  let cache = null
113
125
  let cacheKey = null
114
126
 
127
+ // 老配置(0.11.28 及以前)把 API 地址/密钥/对话模型存在 translate 段里,
128
+ // 转写要再填一次。这里在读到时把它们搬进 api 段并落盘一次,之后只认 api 段。
129
+ function migrateApiSection(stored, merged) {
130
+ if (!stored || stored.api) return false
131
+ const legacy = stored.translate || {}
132
+ const base = String(legacy.apiBase || '').trim()
133
+ const model = String(legacy.apiModel || '').trim()
134
+ const apiKey = String(legacy.apiKey || '').trim()
135
+ if (!base && !model && !apiKey) return false
136
+ if (base) merged.api.base = base
137
+ if (model) merged.api.model = model
138
+ if (apiKey) merged.api.key = apiKey
139
+ return true
140
+ }
141
+
115
142
  export function loadConfig() {
116
143
  const key = statKey()
117
144
  if (cache && cacheKey === key) return clone(cache)
118
145
  const stored = key === 'missing' ? null : readJson(CONFIG_PATH)
119
146
  cache = stored ? merge(clone(CONFIG_DEFAULTS), stored) : migrateLegacy()
147
+ if (migrateApiSection(stored, cache)) {
148
+ // 迁移只做一次:写回失败也不影响本次读取,下次再试。
149
+ try {
150
+ writeConfig(cache)
151
+ } catch {}
152
+ }
120
153
  cacheKey = statKey()
121
154
  return clone(cache)
122
155
  }
package/src/host.js CHANGED
@@ -56,6 +56,7 @@ import {
56
56
  deleteTranscript,
57
57
  getTranscriptionState,
58
58
  migrateAllTranscripts,
59
+ sweepWorkDirs,
59
60
  readTranscript,
60
61
  runtimeInfo,
61
62
  startTranscription,
@@ -68,6 +69,7 @@ import {
68
69
  editTranscriptLine,
69
70
  enqueueBatch,
70
71
  mergeTranscriptLine,
72
+ resegmentTranscript,
71
73
  saveTranscript,
72
74
  splitTranscriptLine,
73
75
  validateTranscript,
@@ -256,7 +258,8 @@ function boot() {
256
258
  booted = (async () => {
257
259
  await initState()
258
260
  loadXyz()
259
- await migrateAllTranscripts().catch((error) => console.error('[dsh-podwave] transcript migration failed:', error.message))
261
+ await sweepWorkDirs().catch(() => {})
262
+ await migrateAllTranscripts().catch((error) => console.error('[dsh-podwave] transcript migration failed:', error.message))
260
263
  if (getState().folders.length) {
261
264
  scanLibrary()
262
265
  .then(() => refreshWatchers())
@@ -490,7 +493,8 @@ async function route(ctx, req, res) {
490
493
  }
491
494
  if (routePath === 'api/setup/plan' && method === 'GET') {
492
495
  const source = url.searchParams.get('source') || 'auto'
493
- return json(res, 200, planSetup({ source }))
496
+ const mode = url.searchParams.get('mode') === 'local' ? 'local' : 'basic'
497
+ return json(res, 200, planSetup({ source, mode }))
494
498
  }
495
499
 
496
500
  if (routePath === 'api/setup/verify' && method === 'GET') {
@@ -509,7 +513,7 @@ async function route(ctx, req, res) {
509
513
  return json(res, 200, {
510
514
  ok: true,
511
515
  generatedAt: new Date().toISOString(),
512
- version: '0.11.26',
516
+ version: '0.11.28',
513
517
  platform,
514
518
  engine: recommendEngine(platform),
515
519
  paths: {
@@ -526,7 +530,8 @@ async function route(ctx, req, res) {
526
530
  if (routePath === 'api/setup/install' && method === 'POST') {
527
531
  const body = await readJson(req)
528
532
  if (setupJob()?.running) return json(res, 409, { error: '安装已在进行中' })
529
- installSetup({ source: body?.source || 'auto' }).catch(() => {})
533
+ // basic:只装 ffmpeg,配合云端 API 用;local:额外装 python 运行时 + 本地模型。
534
+ installSetup({ source: body?.source || 'auto', mode: body?.mode === 'local' ? 'local' : 'basic' }).catch(() => {})
530
535
  return json(res, 200, { started: true })
531
536
  }
532
537
  if (routePath === 'api/setup/cancel' && method === 'POST') {
@@ -538,7 +543,7 @@ async function route(ctx, req, res) {
538
543
  }
539
544
  if ((method === 'GET' || method === 'HEAD') && routePath === 'api/health') {
540
545
  await mediaReady
541
- return json(res, 200, { ok: true, app: 'podwave', version: '0.11.26', mediaBase, transcribe: runtimeInfo(), diarize: diarizeInfo(), translate: publicConfig() })
546
+ return json(res, 200, { ok: true, app: 'podwave', version: '0.11.28', mediaBase, transcribe: runtimeInfo(), diarize: diarizeInfo(), translate: publicConfig() })
542
547
  }
543
548
  if (method === 'GET' && routePath === 'api/state') {
544
549
  const state = getState()
@@ -959,15 +964,21 @@ async function route(ctx, req, res) {
959
964
  }
960
965
 
961
966
  if (routePath === 'api/transcribe/settings') {
962
- if (method === 'GET') return json(res, 200, { ...getSection('transcribe'), runtime: runtimeInfo() })
967
+ if (method === 'GET') {
968
+ // 密钥统一放在「DeepSeek API」那张卡片里,这里只回引擎选择;前端看 runtime.api.hasKey 判断填没填。
969
+ const section = getSection('transcribe') || {}
970
+ return json(res, 200, { ...section, runtime: runtimeInfo() })
971
+ }
963
972
  if (method === 'PUT') {
964
973
  const body = await readJson(req)
965
974
  const patch = {}
975
+ if (typeof body?.provider === 'string') patch.provider = body.provider === 'local' ? 'local' : 'api'
966
976
  if (Array.isArray(body?.hotwords)) patch.hotwords = body.hotwords.map((word) => String(word || '').trim()).filter(Boolean).slice(0, 500)
967
977
  if (Number.isFinite(Number(body?.chunkMinutes))) patch.chunkMinutes = Math.max(1, Math.min(60, Number(body.chunkMinutes)))
968
978
  if (typeof body?.diarize === 'boolean') patch.diarize = body.diarize
969
979
  if (!Object.keys(patch).length) return json(res, 400, { error: '没有可保存的设置' })
970
- return json(res, 200, { ...updateSection('transcribe', patch), runtime: runtimeInfo() })
980
+ const saved = updateSection('transcribe', patch)
981
+ return json(res, 200, { ...saved, runtime: runtimeInfo() })
971
982
  }
972
983
  }
973
984
 
@@ -1018,6 +1029,21 @@ async function route(ctx, req, res) {
1018
1029
  }
1019
1030
  }
1020
1031
 
1032
+ const resegmentMatch = /^api\/episodes\/([^/]+)\/transcript\/resegment$/.exec(routePath)
1033
+ if (resegmentMatch && method === 'POST') {
1034
+ const id = decodeURIComponent(resegmentMatch[1])
1035
+ if (!findEpisode(id) && !isXyzId(id)) return json(res, 404, { error: '单集不存在' })
1036
+ const before = await readTranscript(id)
1037
+ if (!before) return json(res, 404, { error: '还没有转写' })
1038
+ try {
1039
+ pushUndo(id, before)
1040
+ const result = await resegmentTranscript(id)
1041
+ return json(res, 200, result)
1042
+ } catch (error) {
1043
+ return json(res, 400, { error: error.message })
1044
+ }
1045
+ }
1046
+
1021
1047
  const undoMatch = /^api\/episodes\/([^/]+)\/transcript\/undo$/.exec(routePath)
1022
1048
  if (undoMatch && method === 'POST') {
1023
1049
  const id = decodeURIComponent(undoMatch[1])
@@ -1150,7 +1176,25 @@ async function route(ctx, req, res) {
1150
1176
  })
1151
1177
  }
1152
1178
  items.sort((a, b) => (b.completedAt || 0) - (a.completedAt || 0))
1153
- return json(res, 200, { items })
1179
+ let bytes = 0
1180
+ try {
1181
+ for (const file of files) bytes += (await stat(path.join(TRANSCRIPTS_DIR, file))).size
1182
+ } catch {
1183
+ bytes = bytes || 0
1184
+ }
1185
+ return json(res, 200, { items, dir: TRANSCRIPTS_DIR, bytes })
1186
+ }
1187
+
1188
+ if (method === 'POST' && routePath === 'api/history/open') {
1189
+ try {
1190
+ fs.mkdirSync(TRANSCRIPTS_DIR, { recursive: true })
1191
+ const command = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'explorer' : 'xdg-open'
1192
+ const { spawn } = await import('node:child_process')
1193
+ spawn(command, [TRANSCRIPTS_DIR], { detached: true, stdio: 'ignore' }).unref()
1194
+ } catch {
1195
+ return json(res, 500, { error: '无法打开文件夹' })
1196
+ }
1197
+ return json(res, 200, { ok: true, dir: TRANSCRIPTS_DIR })
1154
1198
  }
1155
1199
 
1156
1200
  if (routePath === 'api/ui-settings') {
package/src/library.js CHANGED
@@ -42,7 +42,7 @@ function isInside(parent, child) {
42
42
  return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel)
43
43
  }
44
44
 
45
- async function walk(dir, depth, files) {
45
+ async function walk(dir, depth, files, root, realRoot = root) {
46
46
  let entries
47
47
  try {
48
48
  entries = await fsp.readdir(dir, { withFileTypes: true })
@@ -53,14 +53,15 @@ async function walk(dir, depth, files) {
53
53
  if (entry.name.startsWith('.')) continue
54
54
  const full = path.join(dir, entry.name)
55
55
  if (entry.isDirectory()) {
56
- if (depth < SCAN_DEPTH) await walk(full, depth + 1, files)
56
+ if (depth < SCAN_DEPTH) await walk(full, depth + 1, files, root, realRoot)
57
57
  } else if (entry.isFile() && AUDIO_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) {
58
- files.push(full)
58
+ // 记下这个文件属于哪个「添加进来的根文件夹」,前端才能按目录逐层浏览。
59
+ files.push({ file: full, root, realRoot })
59
60
  }
60
61
  }
61
62
  }
62
63
 
63
- async function readEpisode(file) {
64
+ async function readEpisode(file, root, realRoot = root) {
64
65
  const stat = await fsp.stat(file)
65
66
  const id = episodeId(file)
66
67
  const cacheKey = `${stat.mtimeMs}:${stat.size}`
@@ -107,6 +108,9 @@ async function readEpisode(file) {
107
108
  duration,
108
109
  hasCover,
109
110
  folder: path.dirname(file),
111
+ root,
112
+ // 相对根文件夹的路径('' 表示就在根目录里),前端靠它逐层浏览目录树。
113
+ rel: path.relative(realRoot || root || '', path.dirname(file)).split(path.sep).join('/'),
110
114
  file,
111
115
  }
112
116
  metaCache.set(id, { key: cacheKey, data })
@@ -125,31 +129,37 @@ async function doScan() {
125
129
  } catch {
126
130
  continue
127
131
  }
128
- await walk(folder, 0, files)
132
+ let realRoot = folder
133
+ try {
134
+ realRoot = await fsp.realpath(folder)
135
+ } catch {
136
+ realRoot = folder
137
+ }
138
+ await walk(folder, 0, files, folder, realRoot)
129
139
  }
130
140
 
131
141
  const unique = []
132
142
  const seen = new Set()
133
- for (const file of files) {
134
- let real = file
143
+ for (const entry of files) {
144
+ let real = entry.file
135
145
  try {
136
- real = await fsp.realpath(file)
146
+ real = await fsp.realpath(entry.file)
137
147
  } catch {
138
148
  /* keep the original path */
139
149
  }
140
150
  if (seen.has(real)) continue
141
151
  seen.add(real)
142
- unique.push(real)
152
+ unique.push({ file: real, root: entry.root, realRoot: entry.realRoot })
143
153
  }
144
154
 
145
155
  const items = []
146
156
  let cursor = 0
147
157
  async function worker() {
148
158
  while (cursor < unique.length) {
149
- const file = unique[cursor]
159
+ const entry = unique[cursor]
150
160
  cursor += 1
151
161
  try {
152
- items.push(await readEpisode(file))
162
+ items.push(await readEpisode(entry.file, entry.root, entry.realRoot))
153
163
  } catch {
154
164
  /* skip unreadable files */
155
165
  }
@@ -196,10 +206,10 @@ export function getEpisodePaths() {
196
206
  }
197
207
 
198
208
  export function getEpisodes() {
199
- return episodes.map(({ file, folder, ...rest }) => ({
209
+ return episodes.map(({ file, ...rest }) => ({
200
210
  ...rest,
201
- // Only expose the last two path segments to the client.
202
- location: folder.split(path.sep).slice(-2).join('/'),
211
+ // folder/root 是绝对路径,前端靠它们做逐层目录浏览;location 只是给人看的短路径。
212
+ location: (rest.folder || '').split(path.sep).slice(-2).join('/'),
203
213
  }))
204
214
  }
205
215