dsh-ai-subtitle 0.3.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,12 +1,14 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
- import { existsSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import { copyFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs'
3
3
  import { basename, dirname, extname, join, resolve } from 'node:path'
4
4
  import { Runtime } from './src/runtime.js'
5
5
  import { registerApi } from './src/api.js'
6
6
  import { cancelAll, getJob, listJobs, waitJob, describeJob, startJob } from './src/jobs.js'
7
7
  import { rememberMedia } from './src/recent.js'
8
8
  import { loadHints } from './src/hints.js'
9
- import { buildRows, cueStats, loadCues, validateCues, writeSrt } from './src/cues.js'
9
+ import { translateBatch, translateRemaining } from './src/llm.js'
10
+ import { resplitAll } from './src/resplit.js'
11
+ import { buildRows, cueStats, loadCues, mergeShortCues, splitLongCues, validateCues, writeSrt } from './src/cues.js'
10
12
  import {
11
13
  applyBatch,
12
14
  formatApply,
@@ -197,11 +199,12 @@ export function apply(ctx, config = {}) {
197
199
  'Batch workflow for bilingual cues. "translate" translates a batch (or every remaining batch as a background job) through the DSH model service, using glossary.json and the saved feedback notes; "status"/"next"/"report" inspect progress; "apply" writes manually produced lines back with coverage and glossary validation; "feedback" records notes that steer the next translation.',
198
200
  parameters: {
199
201
  project: { type: 'string', required: true, description: 'Absolute path of the project directory (contains asr.json and cues.json).' },
200
- action: { type: 'string', required: true, description: 'One of "status", "next", "apply", "report", "translate", "feedback".' },
202
+ action: { type: 'string', required: true, description: 'One of "status", "next", "apply", "report", "translate", "feedback", "merge", "split", "resplit".' },
201
203
  batch: { type: 'string', description: 'Batch id such as "61-120". Required for apply; optional for next to re-open a specific batch.' },
202
204
  lines: { type: 'string', description: 'For apply: the returned lines, one per cue, formatted "from-to|jp|zh".' },
203
205
  glossary: { type: 'string', description: 'Path to glossary.json; defaults to <project>/glossary.json.' },
204
206
  allowEmpty: { type: 'boolean', description: 'Accept empty Chinese text, for music or sound effects.' },
207
+ concurrency: { type: 'number', description: 'For translate all: how many batches to run at once (default 1, sequential).' },
205
208
  all: { type: 'boolean', description: 'For translate: translate every remaining batch as a background job.' },
206
209
  note: { type: 'string', description: 'For feedback: the note to attach to a batch or one cue.' },
207
210
  range: { type: 'string', description: 'For feedback: a cue range such as "12-12"; omit for a batch-wide note.' },
@@ -230,12 +233,60 @@ export function apply(ctx, config = {}) {
230
233
  if (!args.lines) throw new Error('apply needs the returned lines')
231
234
  return formatApply(applyBatch(project, options))
232
235
  }
236
+ if (args.action === 'merge') {
237
+ const asrPath = join(project, 'asr.json')
238
+ const cuesPath = join(project, 'cues.json')
239
+ if (!existsSync(cuesPath)) throw new Error('还没有字幕内容,请先翻译')
240
+ const asr = JSON.parse(readFileSync(asrPath, 'utf8'))
241
+ const cues = JSON.parse(readFileSync(cuesPath, 'utf8'))
242
+ const result = mergeShortCues(cues, asr.fragments)
243
+ const check = validateCues(result.cues, asr.fragments.length, { requireFull: false })
244
+ if (!check.ok) throw new Error('合并后字幕不连续:' + check.errors.slice(0, 3).join(';'))
245
+ copyFileSync(cuesPath, cuesPath + '.bak')
246
+ writeFileSync(cuesPath, JSON.stringify(result.cues, null, 1) + '\n', 'utf8')
247
+ return `merged ${result.merged} pair(s): ${cues.length} cues -> ${result.cues.length} cues`
248
+ }
249
+ if (args.action === 'split') {
250
+ const asrPath = join(project, 'asr.json')
251
+ const cuesPath = join(project, 'cues.json')
252
+ if (!existsSync(cuesPath)) throw new Error('还没有字幕内容,请先翻译')
253
+ const asr = JSON.parse(readFileSync(asrPath, 'utf8'))
254
+ const cues = JSON.parse(readFileSync(cuesPath, 'utf8'))
255
+ const result = splitLongCues(cues, asr.fragments)
256
+ const check = validateCues(result.cues, asr.fragments.length, { requireFull: false })
257
+ if (!check.ok) throw new Error('拆分后字幕不连续:' + check.errors.slice(0, 3).join(';'))
258
+ copyFileSync(cuesPath, cuesPath + '.bak')
259
+ writeFileSync(cuesPath, JSON.stringify(result.cues, null, 1) + '\n', 'utf8')
260
+ return `split ${result.split} long cue(s): ${cues.length} cues -> ${result.cues.length} cues`
261
+ }
262
+ if (args.action === 'resplit') {
263
+ const asrPath = join(project, 'asr.json')
264
+ const cuesPath = join(project, 'cues.json')
265
+ if (!existsSync(cuesPath)) throw new Error('还没有字幕内容,请先翻译')
266
+ const job = startJob('resplit', `智能拆分 ${args.project}`, async (current) => {
267
+ const asr = JSON.parse(readFileSync(asrPath, 'utf8'))
268
+ const cues = JSON.parse(readFileSync(cuesPath, 'utf8'))
269
+ const result = await resplitAll(modelContext(), cues, asr.fragments, {
270
+ provider: args.provider,
271
+ model: args.model,
272
+ signal: current.signal,
273
+ onProgress: (done, total) => current.report(total ? (done / total) * 100 : 0, 'resplit', `第 ${done}/${total} 条`),
274
+ })
275
+ const check = validateCues(result.cues, asr.fragments.length, { requireFull: false })
276
+ if (!check.ok) throw new Error('拆分后字幕不连续:' + check.errors.slice(0, 3).join(';'))
277
+ copyFileSync(cuesPath, cuesPath + '.bak')
278
+ writeFileSync(cuesPath, JSON.stringify(result.cues, null, 1) + '\n', 'utf8')
279
+ return { split: result.split, failed: result.failed, cues: result.cues.length }
280
+ }, { projectDir: project })
281
+ return `resplit job started: ${job.id}\nPoll with subtitle_job { id: "${job.id}", waitSeconds: 60 }.`
282
+ }
233
283
  if (args.action === 'translate') {
234
284
  const routeOptions = { provider: args.provider, model: args.model }
235
285
  if (args.all) {
236
286
  const before = reviewStatus(project)
237
287
  const job = startJob('translate', `翻译 ${args.project}`, async (current) => {
238
288
  const result = await translateRemaining(modelContext(), project, {
289
+ concurrency: Number(args.concurrency) || 1,
239
290
  ...routeOptions,
240
291
  mode: args.proofread ? 'proofread' : 'translate',
241
292
  signal: current.signal,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-ai-subtitle",
3
- "version": "0.3.2",
3
+ "version": "0.4.0",
4
4
  "description": "Japanese video to bilingual JP/zh subtitles inside DeepSeek Harness: a self-installing ffmpeg, Python and Whisper runtime, cue editing and SRT export.",
5
5
  "type": "module",
6
6
  "main": "index.js",
package/python/worker.py CHANGED
@@ -10,6 +10,7 @@ over silence, which is exactly what a 19-minute talk recording is full of.
10
10
  """
11
11
  import argparse
12
12
  import json
13
+ import re
13
14
  import sys
14
15
  import wave
15
16
 
@@ -30,7 +31,7 @@ def read_wav(path):
30
31
  return audio, rate
31
32
 
32
33
 
33
- def speech_regions(audio, rate=16000, frame_ms=20, min_speech=0.22, min_gap=0.25, pad=0.10):
34
+ def speech_regions(audio, rate=16000, frame_ms=20, min_speech=0.18, min_gap=0.45, pad=0.10):
34
35
  """Return [(start_s, end_s)] speech regions using frame energy."""
35
36
  frame = int(rate * frame_ms / 1000)
36
37
  count = len(audio) // frame
@@ -75,6 +76,7 @@ def speech_regions(audio, rate=16000, frame_ms=20, min_speech=0.22, min_gap=0.25
75
76
  start_s = max(0.0, begin * frame / rate - pad)
76
77
  end_s = min(len(audio) / rate, end * frame / rate + pad)
77
78
  result.append((start_s, end_s))
79
+
78
80
  return result
79
81
 
80
82
 
@@ -123,6 +125,10 @@ def build_pipeline(model_id, device, dtype):
123
125
  )
124
126
 
125
127
 
128
+ LEAD_IN = 2.0
129
+ LEAD_OUT = 0.4
130
+
131
+
126
132
  def transcribe_torch(args, audio, rate):
127
133
  import torch
128
134
 
@@ -149,7 +155,12 @@ def transcribe_torch(args, audio, rate):
149
155
 
150
156
  fragments = []
151
157
  for index, (begin, end) in enumerate(pieces):
152
- clip = audio[int(begin * rate): int(end * rate)]
158
+ # Whisper loops when a clip starts in the middle of a sentence; give it a
159
+ # little of the preceding audio, then drop whatever it re-transcribes from
160
+ # that lead-in so nothing is duplicated.
161
+ clip_start = max(0.0, begin - LEAD_IN)
162
+ clip_end = min(len(audio) / rate, end + LEAD_OUT)
163
+ clip = audio[int(clip_start * rate): int(clip_end * rate)]
153
164
  if len(clip) < rate * 0.2:
154
165
  continue
155
166
  try:
@@ -162,12 +173,82 @@ def transcribe_torch(args, audio, rate):
162
173
  except Exception as exc:
163
174
  emit(type="info", msg="region %.1f-%.1fs failed: %s" % (begin, end, str(exc)[:120]))
164
175
  continue
165
- text = " ".join((result.get("text") or "").split())
166
- if text:
167
- fragments.append({"start": round(begin, 3), "end": round(end, 3), "text": text})
176
+ # Whisper returns sentence-level chunks with timestamps relative to the
177
+ # clip; emitting one fragment per chunk gives real times instead of
178
+ # spreading the VAD region's span over the text.
179
+ chunks = result.get("chunks") or []
180
+ added = 0
181
+ span = clip_end - clip_start
182
+ for chunk in chunks:
183
+ stamp = chunk.get("timestamp") or (None, None)
184
+ chunk_start, chunk_end = stamp
185
+ chunk_text = " ".join((chunk.get("text") or "").split())
186
+ if not chunk_text:
187
+ continue
188
+ start_s = clip_start + (0.0 if chunk_start is None else max(0.0, float(chunk_start)))
189
+ end_s = clip_start + (span if chunk_end is None else min(span, float(chunk_end)))
190
+ # Content that lies entirely in the lead-in was already transcribed by
191
+ # the previous region; skip it, and clamp a straddling chunk to begin.
192
+ if end_s <= begin + 0.05:
193
+ continue
194
+ if start_s < begin:
195
+ start_s = begin
196
+ if end_s <= start_s:
197
+ end_s = min(end, start_s + 0.3)
198
+ # Regions can overlap slightly (VAD padding plus the lead-in), so a chunk
199
+ # may repeat text that already exists nearby. Drop it against any of the
200
+ # last few fragments whose time range overlaps.
201
+ folded = False
202
+ if fragments:
203
+ for prior in reversed(fragments[-6:]):
204
+ if start_s > prior["end"] + 0.3:
205
+ continue
206
+ previous = re.sub(r"[\s、。?!…,.!?]", "", prior["text"])
207
+ current = re.sub(r"[\s、。?!…,.!?]", "", chunk_text)
208
+ if previous and current == previous:
209
+ prior["end"] = max(prior["end"], round(end_s, 3))
210
+ folded = True
211
+ break
212
+ if previous and current.startswith(previous):
213
+ chunk_text = chunk_text.strip()
214
+ chunk_text = re.sub(r"^[、。?!…,.!?\s]+", "", chunk_text[len(prior["text"]):]).strip()
215
+ if not chunk_text:
216
+ prior["end"] = max(prior["end"], round(end_s, 3))
217
+ folded = True
218
+ break
219
+ if folded:
220
+ continue
221
+ fragments.append({
222
+ "start": round(start_s, 3),
223
+ "end": round(end_s, 3),
224
+ "text": chunk_text,
225
+ })
226
+ added += 1
227
+ if added == 0:
228
+ text = " ".join((result.get("text") or "").split())
229
+ if text:
230
+ fragments.append({"start": round(begin, 3), "end": round(end, 3), "text": text})
168
231
  if index % 5 == 0 or index == total - 1:
169
232
  emit(type="progress", pct=12 + 80 * (index + 1) / total, msg="region %d/%d" % (index + 1, total))
170
233
 
234
+ # Regions can overlap by a fraction of a second, so the same line can be
235
+ # appended twice. Clean the list as a whole: fold a fragment into a nearby
236
+ # one with identical text when their time ranges overlap.
237
+ cleaned = []
238
+ for frag in fragments:
239
+ duplicate = None
240
+ for prior in reversed(cleaned[-8:]):
241
+ if frag["start"] >= prior["end"] + 0.2:
242
+ break
243
+ if frag["text"].strip() == prior["text"].strip():
244
+ duplicate = prior
245
+ break
246
+ if duplicate is not None:
247
+ duplicate["end"] = max(duplicate["end"], frag["end"])
248
+ continue
249
+ cleaned.append(frag)
250
+ fragments = cleaned
251
+
171
252
  emit(type="info", msg="fragments=%d" % len(fragments))
172
253
  return fragments, ("cuda" if device == 0 else "cpu"), "vad"
173
254
 
package/src/api.js CHANGED
@@ -4,16 +4,18 @@ import { basename, dirname, extname, isAbsolute, join, resolve, sep } from 'node
4
4
  import { homedir } from 'node:os'
5
5
  import { cancelJob, getJob, listJobs, describeJob, removeFinishedJobs, removeJob, startJob } from './jobs.js'
6
6
  import { DEFAULT_MODEL } from './installer.js'
7
- import { buildRows, cueStats, deriveCueTimes, describeCoverageErrors, toSrt, validateCues } from './cues.js'
7
+ import { buildRows, cueStats, deriveCueTimes, describeCoverageErrors, mergeShortCues, splitLongCues, toSrt, validateCues } from './cues.js'
8
8
  import { forgetProject, loadRegistry, patchProject } from './registry.js'
9
9
  import { defaultProjectsDir } from './paths.js'
10
10
  import { rejectRequest } from './admission.js'
11
+ import { makeRoom } from './export-name.js'
11
12
  import { recentMedia, rememberMedia } from './recent.js'
12
13
  import { chooseSources, sourcesFromState } from './sources.js'
13
14
  import { applyBatch, batchState, loadProject, nextBatch, planBatches, renderBatch, reviewStatus } from './review.js'
14
15
  import { buildPrompt, resolveRoute, saveRoute, translateBatch, translateRemaining } from './llm.js'
15
16
  import { feedbackForBatch, loadFeedback, saveFeedback } from './feedback.js'
16
17
  import { loadHints, saveHints } from './hints.js'
18
+ import { absorbProjectTerms, loadLibrary, removeHintPreset, removeTerm, saveHintPreset, upsertTerm } from './library.js'
17
19
 
18
20
  import { fetchGlossaryText, fromCsv, glossaryPath, loadGlossary, mergeGlossary, saveGlossary, toCsv } from './glossary.js'
19
21
 
@@ -350,7 +352,12 @@ function projectDetail(dir, limit = 300) {
350
352
  rows,
351
353
  cueList,
352
354
  review: reviewProgress(asr.fragments, cues),
353
- errors: check.ok ? [] : describeCoverageErrors(check.errors),
355
+ // A project that is still being translated ends early by design; only a gap
356
+ // inside what has been written is a real problem worth flagging here.
357
+ errors: (() => {
358
+ const problems = check.errors.filter((line) => !/^coverage ends at/.test(String(line)))
359
+ return problems.length > 0 ? describeCoverageErrors(problems) : []
360
+ })(),
354
361
  }
355
362
  }
356
363
 
@@ -651,6 +658,61 @@ export function registerApi(ctx, runtimeFor, modelContext, connectionFor) {
651
658
  return send(response, { path: glossaryPath(resolve(dir)), glossary })
652
659
  }
653
660
 
661
+ if (method === 'GET' && path === '/quality') {
662
+ const url = new URL(request.url, 'http://local')
663
+ const dir = url.searchParams.get('dir')
664
+ if (!dir) return send(response, { error: 'dir is required' }, 400)
665
+ if (!inside(dir)) return send(response, { error: 'outside the project root' }, 400)
666
+ const project = resolve(dir)
667
+ const asr = readJsonFile(join(project, 'asr.json'))
668
+ const cues = readJsonFile(join(project, 'cues.json'))
669
+ if (!asr || !Array.isArray(asr.fragments)) return send(response, { error: '项目里没有识别结果' }, 400)
670
+ return send(response, scanQuality(Array.isArray(cues) ? cues : [], asr.fragments))
671
+ }
672
+
673
+ if (method === 'GET' && path === '/library') {
674
+ const url = new URL(request.url, 'http://local')
675
+ const dir = url.searchParams.get('dir')
676
+ if (!dir) return send(response, { error: 'dir is required' }, 400)
677
+ if (!inside(dir)) return send(response, { error: 'outside the project root' }, 400)
678
+ return send(response, { library: loadLibrary(resolve(dir)) })
679
+ }
680
+
681
+ if (method === 'POST' && path === '/library') {
682
+ const payload = await readBody(request)
683
+ if (!payload.dir) return send(response, { error: 'dir is required' }, 400)
684
+ if (!inside(payload.dir)) return send(response, { error: 'outside the project root' }, 400)
685
+ const dir = resolve(payload.dir)
686
+ try {
687
+ if (payload.action === 'add-term') {
688
+ return send(response, { library: upsertTerm(dir, payload) })
689
+ }
690
+ if (payload.action === 'remove-term') {
691
+ return send(response, { library: removeTerm(dir, payload.jp) })
692
+ }
693
+ if (payload.action === 'absorb-project') {
694
+ const file = glossaryPath(dir)
695
+ const raw = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : { terms: [] }
696
+ return send(response, { library: absorbProjectTerms(dir, Array.isArray(raw.terms) ? raw.terms : []) })
697
+ }
698
+ if (payload.action === 'save-hint') {
699
+ return send(response, { library: saveHintPreset(dir, payload) })
700
+ }
701
+ if (payload.action === 'remove-hint') {
702
+ return send(response, { library: removeHintPreset(dir, payload.name) })
703
+ }
704
+ if (payload.action === 'apply-hint') {
705
+ const preset = loadLibrary(dir).hints.find((item) => item.name === payload.name)
706
+ if (!preset) return send(response, { error: '模板不存在' }, 400)
707
+ saveHints(dir, { tags: preset.tags || [], note: preset.note || '' })
708
+ return send(response, { ok: true })
709
+ }
710
+ return send(response, { error: 'unknown action' }, 400)
711
+ } catch (error) {
712
+ return send(response, { error: String(error.message || error) }, 400)
713
+ }
714
+ }
715
+
654
716
  if (method === 'POST' && path === '/glossary/import') {
655
717
  const payload = await readBody(request)
656
718
  if (!payload.dir) return send(response, { error: 'dir is required' }, 400)
@@ -714,6 +776,7 @@ export function registerApi(ctx, runtimeFor, modelContext, connectionFor) {
714
776
  const job = startJob('translate', `翻译 ${basename(dir)}`, async (current) => {
715
777
  const progress = { done: 0 }
716
778
  const result = await translateRemaining(llm(), dir, {
779
+ concurrency: Number(payload.concurrency) || 1,
717
780
  mode: payload.mode === 'proofread' ? 'proofread' : 'translate',
718
781
  ...routeOptions,
719
782
  signal: current.signal,
@@ -768,6 +831,15 @@ export function registerApi(ctx, runtimeFor, modelContext, connectionFor) {
768
831
  }
769
832
  }
770
833
 
834
+ if (method === 'POST' && path === '/project/audio') {
835
+ const payload = await readBody(request)
836
+ if (!payload.dir) return send(response, { error: 'dir is required' }, 400)
837
+ if (!inside(payload.dir)) return send(response, { error: 'outside the project root' }, 400)
838
+ const freed = removeProjectAudio(resolve(payload.dir))
839
+ if (freed === null) return send(response, { error: '这个项目没有音频文件' }, 400)
840
+ return send(response, { ok: true, freed })
841
+ }
842
+
771
843
  if (method === 'POST' && path === '/pin') {
772
844
  if (!body.dir) return send(response, { error: 'dir is required' }, 400)
773
845
  if (!inside(body.dir)) return send(response, { error: 'outside the project root' }, 400)
@@ -829,6 +901,69 @@ export function registerApi(ctx, runtimeFor, modelContext, connectionFor) {
829
901
  return send(response, { ok: true, count: clean.length })
830
902
  }
831
903
 
904
+ if (method === 'POST' && path === '/review/merge') {
905
+ const payload = await readBody(request)
906
+ if (!payload.dir) return send(response, { error: 'dir is required' }, 400)
907
+ if (!inside(payload.dir)) return send(response, { error: 'outside the project root' }, 400)
908
+ const dir = resolve(payload.dir)
909
+ const asr = readJsonFile(join(dir, 'asr.json'))
910
+ const cues = readJsonFile(join(dir, 'cues.json'))
911
+ if (!asr || !Array.isArray(asr.fragments)) return send(response, { error: '项目里没有识别结果(asr.json)' }, 400)
912
+ if (!Array.isArray(cues) || cues.length === 0) return send(response, { error: '还没有字幕内容,请先翻译' }, 400)
913
+ const result = mergeShortCues(cues, asr.fragments, payload)
914
+ const check = validateCues(result.cues, asr.fragments.length, { requireFull: false })
915
+ if (!check.ok) {
916
+ return send(response, { error: '合并后字幕不连续', details: describeCoverageErrors(check.errors) }, 400)
917
+ }
918
+ copyFileSync(join(dir, 'cues.json'), join(dir, 'cues.json.bak'))
919
+ writeFileSync(join(dir, 'cues.json'), JSON.stringify(result.cues, null, 1) + '\n', 'utf8')
920
+ return send(response, { ok: true, before: cues.length, after: result.cues.length, merged: result.merged })
921
+ }
922
+
923
+ if (method === 'POST' && path === '/review/split') {
924
+ const payload = await readBody(request)
925
+ if (!payload.dir) return send(response, { error: 'dir is required' }, 400)
926
+ if (!inside(payload.dir)) return send(response, { error: 'outside the project root' }, 400)
927
+ const dir = resolve(payload.dir)
928
+ const asr = readJsonFile(join(dir, 'asr.json'))
929
+ const cues = readJsonFile(join(dir, 'cues.json'))
930
+ if (!asr || !Array.isArray(asr.fragments)) return send(response, { error: '项目里没有识别结果(asr.json)' }, 400)
931
+ if (!Array.isArray(cues) || cues.length === 0) return send(response, { error: '还没有字幕内容,请先翻译' }, 400)
932
+ const result = splitLongCues(cues, asr.fragments, payload)
933
+ const check = validateCues(result.cues, asr.fragments.length, { requireFull: false })
934
+ if (!check.ok) {
935
+ return send(response, { error: '拆分后字幕不连续', details: describeCoverageErrors(check.errors) }, 400)
936
+ }
937
+ copyFileSync(join(dir, 'cues.json'), join(dir, 'cues.json.bak'))
938
+ writeFileSync(join(dir, 'cues.json'), JSON.stringify(result.cues, null, 1) + '\n', 'utf8')
939
+ return send(response, { ok: true, before: cues.length, after: result.cues.length, split: result.split })
940
+ }
941
+
942
+ if (method === 'POST' && path === '/review/resplit') {
943
+ const payload = await readBody(request)
944
+ if (!payload.dir) return send(response, { error: 'dir is required' }, 400)
945
+ if (!inside(payload.dir)) return send(response, { error: 'outside the project root' }, 400)
946
+ const dir = resolve(payload.dir)
947
+ const asr = readJsonFile(join(dir, 'asr.json'))
948
+ const cues = readJsonFile(join(dir, 'cues.json'))
949
+ if (!asr || !Array.isArray(asr.fragments)) return send(response, { error: '项目里没有识别结果(asr.json)' }, 400)
950
+ if (!Array.isArray(cues) || cues.length === 0) return send(response, { error: '还没有字幕内容,请先翻译' }, 400)
951
+ const job = startJob('resplit', `智能拆分 ${basename(dir)}`, async (current) => {
952
+ const result = await resplitAll(llm(), cues, asr.fragments, {
953
+ provider: payload.provider,
954
+ model: payload.model,
955
+ signal: current.signal,
956
+ onProgress: (done, total) => current.report(total ? (done / total) * 100 : 0, 'resplit', `第 ${done}/${total} 条`),
957
+ })
958
+ const check = validateCues(result.cues, asr.fragments.length, { requireFull: false })
959
+ if (!check.ok) throw new Error('拆分后字幕不连续:' + check.errors.slice(0, 3).join(';'))
960
+ copyFileSync(join(dir, 'cues.json'), join(dir, 'cues.json.bak'))
961
+ writeFileSync(join(dir, 'cues.json'), JSON.stringify(result.cues, null, 1) + '\n', 'utf8')
962
+ return { split: result.split, failed: result.failed, cues: result.cues.length }
963
+ }, { projectDir: dir })
964
+ return send(response, { jobId: job.id })
965
+ }
966
+
832
967
  if (method === 'POST' && path === '/review/apply') {
833
968
  if (!body.dir || !body.batch || typeof body.lines !== 'string') {
834
969
  return send(response, { error: 'dir, batch and lines are required' }, 400)
@@ -853,9 +988,18 @@ export function registerApi(ctx, runtimeFor, modelContext, connectionFor) {
853
988
  if (!check.ok) return send(response, { error: '字幕内容不完整', details: describeCoverageErrors(check.errors) }, 400)
854
989
  const rows = buildRows(asr.fragments, cues, { minDuration: 1.2, maxDuration: 9 })
855
990
  const meta = readJsonFile(join(dir, 'meta.json')) || {}
856
- const out = join(dir, srtFileName(meta, dir))
991
+ let out = join(dir, srtFileName(meta, dir))
992
+ let backup = null
993
+ if (body.location === 'video') {
994
+ const media = typeof meta.media === 'string' ? meta.media : ''
995
+ if (!media) return send(response, { error: '这个项目没有记录视频路径' }, 400)
996
+ const videoDir = dirname(media)
997
+ if (!existsSync(videoDir)) return send(response, { error: '视频所在目录不存在:' + videoDir }, 400)
998
+ out = join(videoDir, basename(media, extname(media)) + '.srt')
999
+ backup = makeRoom(out)
1000
+ }
857
1001
  writeFileSync(out, '\uFEFF' + toSrt(rows), 'utf8')
858
- return send(response, { ok: true, out, stats: cueStats(rows) })
1002
+ return send(response, { ok: true, out, backup, stats: cueStats(rows) })
859
1003
  }
860
1004
 
861
1005
  if (method === 'POST' && path === '/runtime/probe') {
package/src/audio.js ADDED
@@ -0,0 +1,20 @@
1
+ import { existsSync, rmSync, statSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
4
+ /** Path of the extracted audio inside a project directory. */
5
+ export function projectAudioPath(projectDir) {
6
+ return join(projectDir, 'audio.wav')
7
+ }
8
+
9
+ /**
10
+ * Delete the project's extracted audio and report how many bytes were freed.
11
+ * Cues and asr.json are left untouched.
12
+ * @returns freed bytes, or null when the file was already absent.
13
+ */
14
+ export function removeProjectAudio(projectDir) {
15
+ const file = projectAudioPath(projectDir)
16
+ if (!existsSync(file)) return null
17
+ const freed = statSync(file).size
18
+ rmSync(file, { force: true })
19
+ return freed
20
+ }