dsh-ai-subtitle 0.2.0 → 0.3.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/src/api.js CHANGED
@@ -1,12 +1,20 @@
1
1
  import { appendFileSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
2
2
  import { createRequire } from 'node:module'
3
- import { basename, dirname, extname, join, resolve, sep } from 'node:path'
3
+ import { basename, dirname, extname, isAbsolute, join, resolve, sep } from 'node:path'
4
4
  import { homedir } from 'node:os'
5
- import { cancelJob, getJob, listJobs, describeJob } from './jobs.js'
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, toSrt, validateCues } from './cues.js'
7
+ import { buildRows, cueStats, deriveCueTimes, describeCoverageErrors, toSrt, validateCues } from './cues.js'
8
8
  import { forgetProject, loadRegistry, patchProject } from './registry.js'
9
+ import { defaultProjectsDir } from './paths.js'
10
+ import { recentMedia, rememberMedia } from './recent.js'
9
11
  import { chooseSources, sourcesFromState } from './sources.js'
12
+ import { applyBatch, batchState, loadProject, nextBatch, planBatches, renderBatch, reviewStatus } from './review.js'
13
+ import { buildPrompt, resolveRoute, saveRoute, translateBatch, translateRemaining } from './llm.js'
14
+ import { feedbackForBatch, loadFeedback, saveFeedback } from './feedback.js'
15
+ import { loadHints, saveHints } from './hints.js'
16
+
17
+ import { fetchGlossaryText, fromCsv, glossaryPath, loadGlossary, mergeGlossary, saveGlossary, toCsv } from './glossary.js'
10
18
 
11
19
  const PREFIX = '/dsh-ai-subtitle/api'
12
20
 
@@ -101,8 +109,66 @@ async function nativePick(mode) {
101
109
  }
102
110
  }
103
111
 
112
+ /** Reveal a folder in Explorer/Finder; the desktop shell is the polite way in. */
113
+ async function openFolder(target) {
114
+ try {
115
+ const requireFromHere = createRequire(import.meta.url)
116
+ const electron = requireFromHere('electron')
117
+ const shell = electron && electron.shell
118
+ if (shell && typeof shell.openPath === 'function') {
119
+ const failure = await shell.openPath(target)
120
+ return failure ? { ok: false, error: failure } : { ok: true }
121
+ }
122
+ } catch {
123
+ // not running inside Electron: fall through to the platform shell
124
+ }
125
+ try {
126
+ const { spawn } = await import('node:child_process')
127
+ if (process.platform === 'win32') {
128
+ spawn('explorer.exe', [target], { detached: true, stdio: 'ignore' }).unref()
129
+ return { ok: true }
130
+ }
131
+ if (process.platform === 'darwin') {
132
+ spawn('open', [target], { detached: true, stdio: 'ignore' }).unref()
133
+ return { ok: true }
134
+ }
135
+ spawn('xdg-open', [target], { detached: true, stdio: 'ignore' }).unref()
136
+ return { ok: true }
137
+ } catch (error) {
138
+ return { ok: false, error: String(error.message || error) }
139
+ }
140
+ }
141
+
142
+ /** Name the SRT after the source video; fall back to the project folder name. */
143
+ function srtFileName(meta, dir) {
144
+ const media = meta && typeof meta.media === 'string' ? meta.media : ''
145
+ if (media) {
146
+ const base = basename(media, extname(media))
147
+ if (base) return base + '.srt'
148
+ }
149
+ return basename(dir) + '.srt'
150
+ }
151
+
104
152
  const projectCache = new Map()
105
153
 
154
+ /** Review progress for the project list: how many batches still lack Chinese text. */
155
+ function reviewProgress(fragments, cues) {
156
+ if (!Array.isArray(fragments) || fragments.length === 0) return null
157
+ const list = Array.isArray(cues) ? cues : []
158
+ const batches = planBatches(fragments, list)
159
+ const states = batches.map((batch) => ({ batch, ...batchState(batch, list) }))
160
+ const translated = states.filter((state) => state.translated).length
161
+ const next = states.find((state) => !state.translated)
162
+ const covered = states.reduce((sum, state) => sum + state.covered, 0)
163
+ return {
164
+ batches: batches.length,
165
+ translated,
166
+ remaining: batches.length - translated,
167
+ covered,
168
+ next: next ? next.batch.id : '',
169
+ }
170
+ }
171
+
106
172
  const MEDIA_EXTENSIONS = new Set([
107
173
  '.mp4', '.mkv', '.webm', '.mov', '.avi', '.m4v', '.flv', '.wmv', '.ts', '.m2ts', '.mpg', '.mpeg',
108
174
  '.mp3', '.m4a', '.wav', '.flac', '.aac', '.ogg', '.opus', '.wma',
@@ -156,8 +222,18 @@ function fileStamp(path) {
156
222
  }
157
223
  }
158
224
 
159
- function listProjects(root) {
160
- const projectRoot = join(root, 'projects')
225
+ function copyDir(from, to) {
226
+ mkdirSync(to, { recursive: true })
227
+ for (const entry of readdirSync(from, { withFileTypes: true })) {
228
+ const source = join(from, entry.name)
229
+ const target = join(to, entry.name)
230
+ if (entry.isDirectory()) copyDir(source, target)
231
+ else copyFileSync(source, target)
232
+ }
233
+ }
234
+
235
+ function listProjects(root, explicitRoot) {
236
+ const projectRoot = explicitRoot || join(root, 'projects')
161
237
  if (!existsSync(projectRoot)) return []
162
238
  const registry = loadRegistry(root).projects
163
239
  const rows = []
@@ -171,22 +247,25 @@ function listProjects(root) {
171
247
  const metaPath = join(dir, 'meta.json')
172
248
  const asrPath = join(dir, 'asr.json')
173
249
  const cuesPath = join(dir, 'cues.json')
174
- const srtPath = join(dir, 'subtitles.srt')
175
- const stamp = `${fileStamp(metaPath)}|${fileStamp(asrPath)}|${fileStamp(cuesPath)}|${fileStamp(srtPath)}`
250
+ const meta = readJsonFile(metaPath)
251
+ const srtPath = join(dir, srtFileName(meta, dir))
252
+ const legacySrt = join(dir, 'subtitles.srt')
253
+ const stamp = `${fileStamp(metaPath)}|${fileStamp(asrPath)}|${fileStamp(cuesPath)}|${fileStamp(srtPath)}|${fileStamp(legacySrt)}`
176
254
  const cached = projectCache.get(dir)
177
255
  let info
178
256
  if (cached && cached.stamp === stamp) {
179
257
  info = cached.info
180
258
  } else {
181
- const meta = readJsonFile(metaPath)
182
259
  const asr = readJsonFile(asrPath)
183
260
  const cues = readJsonFile(cuesPath)
261
+ const fragmentList = asr && Array.isArray(asr.fragments) ? asr.fragments : []
184
262
  info = {
185
263
  media: (meta && meta.media) || '',
186
264
  duration: (meta && meta.duration) || 0,
187
- fragments: asr && Array.isArray(asr.fragments) ? asr.fragments.length : 0,
265
+ fragments: fragmentList.length,
188
266
  cues: Array.isArray(cues) ? cues.length : 0,
189
- srt: existsSync(srtPath),
267
+ srt: existsSync(srtPath) || existsSync(legacySrt),
268
+ review: reviewProgress(fragmentList, cues),
190
269
  }
191
270
  projectCache.set(dir, { stamp, info })
192
271
  }
@@ -199,6 +278,7 @@ function listProjects(root) {
199
278
  fragments: info.fragments,
200
279
  cues: info.cues,
201
280
  srt: info.srt,
281
+ review: info.review,
202
282
  pinned: Boolean(state.pinned),
203
283
  hidden: Boolean(state.hidden),
204
284
  })
@@ -213,7 +293,7 @@ function projectDetail(dir, limit = 300) {
213
293
  const asr = readJsonFile(join(dir, 'asr.json'))
214
294
  const cues = readJsonFile(join(dir, 'cues.json'))
215
295
  const meta = readJsonFile(join(dir, 'meta.json')) || {}
216
- if (!asr || !Array.isArray(asr.fragments)) return { error: 'asr.json missing in this project' }
296
+ if (!asr || !Array.isArray(asr.fragments)) return { error: '项目里没有识别结果(asr.json)' }
217
297
  if (!Array.isArray(cues)) {
218
298
  return {
219
299
  name: basename(dir),
@@ -224,7 +304,8 @@ function projectDetail(dir, limit = 300) {
224
304
  stats: null,
225
305
  rows: [],
226
306
  cueList: [],
227
- errors: ['cues.json 还没有生成'],
307
+ review: reviewProgress(asr.fragments, []),
308
+ errors: ['还没有字幕内容'],
228
309
  }
229
310
  }
230
311
  const check = validateCues(cues, asr.fragments.length)
@@ -243,6 +324,7 @@ function projectDetail(dir, limit = 300) {
243
324
  start: +(Number.isFinite(times.start) ? times.start : Number(first.start) || 0).toFixed(2),
244
325
  end: +(Number.isFinite(times.end) ? times.end : Number(last.end) || 0).toFixed(2),
245
326
  fixed,
327
+ skip: cue.skip === true,
246
328
  jp: String(cue.jp || ''),
247
329
  zh: String(cue.zh || ''),
248
330
  }
@@ -266,7 +348,8 @@ function projectDetail(dir, limit = 300) {
266
348
  stats,
267
349
  rows,
268
350
  cueList,
269
- errors: check.errors,
351
+ review: reviewProgress(asr.fragments, cues),
352
+ errors: check.ok ? [] : describeCoverageErrors(check.errors),
270
353
  }
271
354
  }
272
355
 
@@ -274,11 +357,12 @@ function projectDetail(dir, limit = 300) {
274
357
  * Local JSON API for the studio panel. Registered as a handler route because the
275
358
  * panel needs POST for install, transcribe, import, save and export.
276
359
  */
277
- export function registerApi(ctx, runtimeFor) {
360
+ export function registerApi(ctx, runtimeFor, modelContext) {
278
361
  const handler = async (request, response) => {
279
362
  const url = new URL(request.url || '/', 'http://local')
280
363
  const path = url.pathname.slice(PREFIX.length) || '/'
281
364
  const runtime = runtimeFor(url.searchParams.get('installDir') || undefined)
365
+ const llm = () => typeof modelContext === 'function' ? modelContext() : null
282
366
  const projectRoot = runtime.projectRoot
283
367
  const rootPath = resolve(projectRoot)
284
368
  const inside = (dir) => {
@@ -321,6 +405,16 @@ export function registerApi(ctx, runtimeFor) {
321
405
  return send(response, { ok: cancelled, error: cancelled ? undefined : '该任务已结束或不存在' })
322
406
  }
323
407
 
408
+ if (method === 'POST' && path === '/job/remove') {
409
+ const payload = await readBody(request)
410
+ if (!payload.id) return send(response, { error: 'id is required' }, 400)
411
+ return send(response, { ok: removeJob(String(payload.id)) })
412
+ }
413
+
414
+ if (method === 'POST' && path === '/job/clear') {
415
+ return send(response, { ok: true, removed: removeFinishedJobs() })
416
+ }
417
+
324
418
  if (method === 'GET' && path === '/job') {
325
419
  const job = getJob(url.searchParams.get('id'))
326
420
  if (!job) return send(response, { error: 'unknown job' }, 404)
@@ -346,6 +440,92 @@ export function registerApi(ctx, runtimeFor) {
346
440
  return send(response, await nativePick(mode))
347
441
  }
348
442
 
443
+ if (method === 'POST' && path === '/open-folder') {
444
+ const payload = await readBody(request)
445
+ const target = payload.dir ? resolve(payload.dir) : projectRoot
446
+ if (!existsSync(target)) return send(response, { error: '目录不存在' }, 400)
447
+ if (target !== resolve(projectRoot) && !inside(target)) {
448
+ return send(response, { error: '只能打开项目目录内的路径' }, 400)
449
+ }
450
+ return send(response, await openFolder(target))
451
+ }
452
+
453
+ if (method === 'GET' && path === '/settings') {
454
+ return send(response, {
455
+ projectsDir: projectRoot,
456
+ defaultDir: defaultProjectsDir(),
457
+ legacyDir: join(runtime.root, 'projects'),
458
+ })
459
+ }
460
+
461
+ if (method === 'POST' && path === '/settings/projects') {
462
+ const payload = await readBody(request)
463
+ const target = String(payload.dir || '').trim()
464
+ if (!target || !isAbsolute(target)) return send(response, { error: '需要绝对路径' }, 400)
465
+ const next = resolve(target)
466
+ const previous = projectRoot
467
+ try {
468
+ mkdirSync(next, { recursive: true })
469
+ writeFileSync(join(next, '.write-test'), 'ok', 'utf8')
470
+ rmSync(join(next, '.write-test'), { force: true })
471
+ } catch (error) {
472
+ return send(response, { error: '目录不可写:' + String(error.message || error) }, 400)
473
+ }
474
+ let moved = 0
475
+ let failed = []
476
+ if (payload.move && previous !== next) {
477
+ for (const name of readdirSync(previous)) {
478
+ const from = join(previous, name)
479
+ const to = join(next, name)
480
+ try {
481
+ if (!statSync(from).isDirectory()) continue
482
+ if (existsSync(to)) {
483
+ failed.push(name)
484
+ continue
485
+ }
486
+ renameSync(from, to)
487
+ moved += 1
488
+ } catch (error) {
489
+ try {
490
+ copyDir(from, to)
491
+ rmSync(from, { recursive: true, force: true })
492
+ moved += 1
493
+ } catch (copyError) {
494
+ failed.push(name)
495
+ }
496
+ }
497
+ }
498
+ }
499
+ runtime.setProjectsDir(next)
500
+ return send(response, { ok: true, projectsDir: next, moved, failed })
501
+ }
502
+
503
+ if (method === 'GET' && path === '/recent') {
504
+ const files = []
505
+ const seen = new Set()
506
+ for (const entry of recentMedia(runtime)) {
507
+ files.push(entry)
508
+ seen.add(entry)
509
+ }
510
+ for (const row of listProjects(runtime.root, projectRoot)) {
511
+ if (row.media && !seen.has(row.media) && existsSync(row.media)) {
512
+ files.push(row.media)
513
+ seen.add(row.media)
514
+ }
515
+ }
516
+ const dirs = []
517
+ const seenDir = new Set()
518
+ for (const file of files) {
519
+ const folder = dirname(file)
520
+ if (!seenDir.has(folder) && existsSync(folder)) {
521
+ seenDir.add(folder)
522
+ dirs.push(folder)
523
+ }
524
+ }
525
+ if (!seenDir.has(projectRoot) && existsSync(projectRoot)) dirs.push(projectRoot)
526
+ return send(response, { files: files.slice(0, 12), dirs: dirs.slice(0, 10) })
527
+ }
528
+
349
529
  if (method === 'GET' && path === '/fs/places') {
350
530
  return send(response, { places: browsePlaces(projectRoot) })
351
531
  }
@@ -366,8 +546,185 @@ export function registerApi(ctx, runtimeFor) {
366
546
  }
367
547
  }
368
548
 
549
+ if (method === 'GET' && path === '/review/status') {
550
+ const dir = url.searchParams.get('dir')
551
+ if (!dir) return send(response, { error: 'dir is required' }, 400)
552
+ if (!inside(dir)) return send(response, { error: 'outside the project root' }, 400)
553
+ try {
554
+ return send(response, reviewStatus(resolve(dir)))
555
+ } catch (error) {
556
+ return send(response, { error: String(error.message || error) }, 400)
557
+ }
558
+ }
559
+
560
+ if (method === 'GET' && path === '/review/next') {
561
+ const dir = url.searchParams.get('dir')
562
+ if (!dir) return send(response, { error: 'dir is required' }, 400)
563
+ if (!inside(dir)) return send(response, { error: 'outside the project root' }, 400)
564
+ try {
565
+ const { cues, fragments } = loadProject(resolve(dir))
566
+ const batches = planBatches(fragments, cues)
567
+ const wanted = url.searchParams.get('batch')
568
+ const batch = wanted ? batches.find((item) => item.id === wanted) : nextBatch(batches, cues)
569
+ if (!batch) return send(response, { done: true })
570
+ const glossary = loadGlossary(glossaryPath(resolve(dir)))
571
+ const hints = loadHints(resolve(dir))
572
+ const batchCues = cues
573
+ .filter((cue) => Number(cue.to) >= batch.from && Number(cue.from) <= batch.to)
574
+ .map((cue) => ({ from: Number(cue.from), to: Number(cue.to), jp: String(cue.jp || ''), zh: String(cue.zh || ''), skip: cue.skip === true }))
575
+ return send(response, { batch: batch.id, lines: renderBatch(batch, fragments, cues, glossary, hints), cues: batchCues })
576
+ } catch (error) {
577
+ return send(response, { error: String(error.message || error) }, 400)
578
+ }
579
+ }
580
+
581
+ if (method === 'GET' && path === '/llm/route') {
582
+ try {
583
+ const scoped = llm()
584
+ const providers = scoped.llm.listProviders()
585
+ const catalog = []
586
+ for (const provider of providers) {
587
+ let models = []
588
+ try {
589
+ models = (await scoped.llm.listModels(provider.id)).map((model) => model.id)
590
+ } catch {
591
+ models = []
592
+ }
593
+ catalog.push({ id: provider.id, name: provider.name, models })
594
+ }
595
+ let active = null
596
+ try {
597
+ active = await resolveRoute(scoped, {
598
+ provider: url.searchParams.get('provider') || undefined,
599
+ model: url.searchParams.get('model') || undefined,
600
+ })
601
+ } catch {
602
+ active = null
603
+ }
604
+ return send(response, { providers: catalog, active })
605
+ } catch (error) {
606
+ return send(response, { error: String(error.message || error) }, 400)
607
+ }
608
+ }
609
+
610
+ if (method === 'POST' && path === '/llm/route') {
611
+ const payload = await readBody(request)
612
+ if (!payload.dir || !payload.provider || !payload.model) {
613
+ return send(response, { error: 'dir, provider and model are required' }, 400)
614
+ }
615
+ if (!inside(payload.dir)) return send(response, { error: 'outside the project root' }, 400)
616
+ saveRoute(resolve(payload.dir), { provider: String(payload.provider), model: String(payload.model) })
617
+ return send(response, { ok: true })
618
+ }
619
+
620
+ if (method === 'GET' && path === '/hints') {
621
+ const dir = url.searchParams.get('dir')
622
+ if (!dir) return send(response, { error: 'dir is required' }, 400)
623
+ if (!inside(dir)) return send(response, { error: 'outside the project root' }, 400)
624
+ return send(response, loadHints(resolve(dir)))
625
+ }
626
+
627
+ if (method === 'POST' && path === '/hints') {
628
+ const payload = await readBody(request)
629
+ if (!payload.dir) return send(response, { error: 'dir is required' }, 400)
630
+ if (!inside(payload.dir)) return send(response, { error: 'outside the project root' }, 400)
631
+ return send(response, { ok: true, hints: saveHints(resolve(payload.dir), payload) })
632
+ }
633
+
634
+ if (method === 'GET' && path === '/glossary') {
635
+ const dir = url.searchParams.get('dir')
636
+ if (!dir) return send(response, { error: 'dir is required' }, 400)
637
+ if (!inside(dir)) return send(response, { error: 'outside the project root' }, 400)
638
+ const glossary = loadGlossary(glossaryPath(resolve(dir)))
639
+ return send(response, { path: glossaryPath(resolve(dir)), glossary })
640
+ }
641
+
642
+ if (method === 'POST' && path === '/glossary/import') {
643
+ const payload = await readBody(request)
644
+ if (!payload.dir) return send(response, { error: 'dir is required' }, 400)
645
+ if (!inside(payload.dir)) return send(response, { error: 'outside the project root' }, 400)
646
+ const projectDir = resolve(payload.dir)
647
+ try {
648
+ let source = ''
649
+ if (payload.from) source = await fetchGlossaryText(payload.from)
650
+ else if (payload.path) source = readFileSync(payload.path, 'utf8')
651
+ else if (payload.text) source = payload.text
652
+ else return send(response, { error: '需要 text、path 或 from' }, 400)
653
+ const parsed = fromCsv(source)
654
+ const current = loadGlossary(glossaryPath(projectDir))
655
+ const merged = mergeGlossary(current, parsed, { merge: payload.merge !== false })
656
+ saveGlossary(glossaryPath(projectDir), merged.glossary)
657
+ return send(response, { ok: true, summary: merged.summary })
658
+ } catch (error) {
659
+ return send(response, { error: String(error.message || error) }, 400)
660
+ }
661
+ }
662
+
663
+ if (method === 'POST' && path === '/glossary/export') {
664
+ const payload = await readBody(request)
665
+ if (!payload.dir) return send(response, { error: 'dir is required' }, 400)
666
+ if (!inside(payload.dir)) return send(response, { error: 'outside the project root' }, 400)
667
+ const projectDir = resolve(payload.dir)
668
+ const glossary = loadGlossary(glossaryPath(projectDir))
669
+ const csv = toCsv(glossary)
670
+ const out = join(projectDir, 'glossary.csv')
671
+ writeFileSync(out, csv, 'utf8')
672
+ return send(response, { ok: true, path: out, csv })
673
+ }
674
+
675
+ if (method === 'GET' && path === '/review/feedback') {
676
+ const dir = url.searchParams.get('dir')
677
+ if (!dir) return send(response, { error: 'dir is required' }, 400)
678
+ if (!inside(dir)) return send(response, { error: 'outside the project root' }, 400)
679
+ return send(response, { items: loadFeedback(resolve(dir)).items })
680
+ }
681
+
682
+ if (method === 'POST' && path === '/review/feedback') {
683
+ const payload = await readBody(request)
684
+ if (!payload.dir || !payload.batch || typeof payload.note !== 'string') {
685
+ return send(response, { error: 'dir, batch and note are required' }, 400)
686
+ }
687
+ if (!inside(payload.dir)) return send(response, { error: 'outside the project root' }, 400)
688
+ const entry = saveFeedback(resolve(payload.dir), { batch: payload.batch, range: payload.range, note: payload.note })
689
+ return send(response, { ok: true, entry })
690
+ }
691
+
692
+ if (method === 'POST' && path === '/review/translate') {
693
+ const payload = await readBody(request)
694
+ if (!payload.dir) return send(response, { error: 'dir is required' }, 400)
695
+ if (!inside(payload.dir)) return send(response, { error: 'outside the project root' }, 400)
696
+ const dir = resolve(payload.dir)
697
+ const routeOptions = { provider: payload.provider, model: payload.model }
698
+ try {
699
+ if (payload.all) {
700
+ const before = reviewStatus(dir)
701
+ const total = before.remaining
702
+ const job = startJob('translate', `翻译 ${basename(dir)}`, async (current) => {
703
+ const progress = { done: 0 }
704
+ const result = await translateRemaining(llm(), dir, {
705
+ mode: payload.mode === 'proofread' ? 'proofread' : 'translate',
706
+ ...routeOptions,
707
+ signal: current.signal,
708
+ onProgress: (count, batch) => {
709
+ progress.done = count
710
+ current.report(total ? (count / total) * 100 : 50, 'translate', `${count}/${total} 批 · 第 ${batch} 句`)
711
+ },
712
+ })
713
+ current.note(`translated ${result.batches.length} batch(es) with ${result.route}`)
714
+ return { batches: result.batches, route: result.route, remaining: reviewStatus(dir).remaining }
715
+ }, { projectDir: dir })
716
+ return send(response, { jobId: job.id, total })
717
+ }
718
+ const route = await resolveRoute(llm(), routeOptions)
719
+ const result = await translateBatch(llm(), dir, { batch: payload.batch, route, mode: payload.mode === 'proofread' ? 'proofread' : 'translate' })
720
+ return send(response, { ok: true, ...result })
721
+ } catch (error) {
722
+ return send(response, { error: String(error.message || error) }, 400)
723
+ }
724
+ }
725
+
369
726
  if (method === 'GET' && path === '/projects') {
370
- return send(response, { root: projectRoot, projects: listProjects(runtime.root) })
727
+ return send(response, { root: projectRoot, projects: listProjects(runtime.root, projectRoot) })
371
728
  }
372
729
 
373
730
  if (method === 'GET' && path === '/project') {
@@ -388,9 +745,11 @@ export function registerApi(ctx, runtimeFor) {
388
745
  if (method === 'POST' && path === '/transcribe') {
389
746
  if (!body.media) return send(response, { error: 'media is required' }, 400)
390
747
  const target = runtimeFor(body.installDir || undefined)
391
- if (!existsSync(body.media)) return send(response, { error: `media not found: ${body.media}` }, 400)
748
+ if (!existsSync(body.media)) return send(response, { error: `找不到这个文件:${body.media}` }, 400)
392
749
  try {
393
- const job = target.transcribe({ media: resolve(body.media), model: body.model })
750
+ const mediaPath = resolve(body.media)
751
+ rememberMedia(target, mediaPath)
752
+ const job = target.transcribe({ media: mediaPath, model: body.model })
394
753
  return send(response, { jobId: job.id, projectDir: job.projectDir })
395
754
  } catch (error) {
396
755
  return send(response, { error: String(error.message || error) }, 400)
@@ -443,6 +802,7 @@ export function registerApi(ctx, runtimeFor) {
443
802
  if (!inside(body.dir)) return send(response, { error: 'outside the project root' }, 400)
444
803
  const clean = body.cues.map((cue) => {
445
804
  const out = { from: Number(cue.from), to: Number(cue.to), jp: String(cue.jp ?? ''), zh: String(cue.zh ?? '') }
805
+ if (cue.skip === true) out.skip = true
446
806
  const start = Number(cue.start)
447
807
  const end = Number(cue.end)
448
808
  if (Number.isFinite(start)) out.start = Math.max(0, +start.toFixed(3))
@@ -457,18 +817,31 @@ export function registerApi(ctx, runtimeFor) {
457
817
  return send(response, { ok: true, count: clean.length })
458
818
  }
459
819
 
820
+ if (method === 'POST' && path === '/review/apply') {
821
+ if (!body.dir || !body.batch || typeof body.lines !== 'string') {
822
+ return send(response, { error: 'dir, batch and lines are required' }, 400)
823
+ }
824
+ if (!inside(body.dir)) return send(response, { error: 'outside the project root' }, 400)
825
+ try {
826
+ return send(response, applyBatch(resolve(body.dir), { batch: body.batch, lines: body.lines, allowEmpty: Boolean(body.allowEmpty) }))
827
+ } catch (error) {
828
+ return send(response, { error: String(error.message || error) }, 400)
829
+ }
830
+ }
831
+
460
832
  if (method === 'POST' && path === '/export') {
461
833
  if (!body.dir) return send(response, { error: 'dir is required' }, 400)
462
834
  if (!inside(body.dir)) return send(response, { error: 'outside the project root' }, 400)
463
835
  const dir = resolve(body.dir)
464
836
  const asr = readJsonFile(join(dir, 'asr.json'))
465
837
  const cues = readJsonFile(join(dir, 'cues.json'))
466
- if (!asr || !Array.isArray(asr.fragments)) return send(response, { error: 'asr.json missing' }, 400)
467
- if (!Array.isArray(cues)) return send(response, { error: 'cues.json missing' }, 400)
838
+ if (!asr || !Array.isArray(asr.fragments)) return send(response, { error: '项目里没有识别结果(asr.json)' }, 400)
839
+ if (!Array.isArray(cues)) return send(response, { error: '还没有字幕内容,请先翻译' }, 400)
468
840
  const check = validateCues(cues, asr.fragments.length)
469
- if (!check.ok) return send(response, { error: 'cue coverage failed', details: check.errors }, 400)
841
+ if (!check.ok) return send(response, { error: '字幕内容不完整', details: describeCoverageErrors(check.errors) }, 400)
470
842
  const rows = buildRows(asr.fragments, cues, { minDuration: 1.2, maxDuration: 9 })
471
- const out = join(dir, 'subtitles.srt')
843
+ const meta = readJsonFile(join(dir, 'meta.json')) || {}
844
+ const out = join(dir, srtFileName(meta, dir))
472
845
  writeFileSync(out, '\uFEFF' + toSrt(rows), 'utf8')
473
846
  return send(response, { ok: true, out, stats: cueStats(rows) })
474
847
  }
package/src/cues.js CHANGED
@@ -14,7 +14,7 @@ export function loadCues(paths) {
14
14
  * Coverage must be contiguous. A single long fragment may be split into several
15
15
  * cues, which then repeat the same from=to index back to back; that is allowed.
16
16
  */
17
- export function validateCues(cues, total) {
17
+ export function validateCues(cues, total, options = {}) {
18
18
  const errors = []
19
19
  if (cues.length === 0) return { ok: false, errors: ['no cues'] }
20
20
  let cursor = Number(cues[0].from)
@@ -42,10 +42,27 @@ export function validateCues(cues, total) {
42
42
  cursor = Math.max(cursor, to + 1)
43
43
  lastTo = Math.max(lastTo, to)
44
44
  }
45
- if (lastTo !== total) errors.push(`coverage ends at ${lastTo}, expected ${total}`)
45
+ // Export needs the whole file; an incremental write only needs a contiguous prefix.
46
+ if (options.requireFull !== false && lastTo !== total) errors.push(`coverage ends at ${lastTo}, expected ${total}`)
46
47
  return { ok: errors.length === 0, errors: errors.slice(0, 20) }
47
48
  }
48
49
 
50
+ /** Panel-facing wording for the coverage problems written by validateCues. */
51
+ export function describeCoverageErrors(errors) {
52
+ const list = Array.isArray(errors) ? errors : []
53
+ return list.map((line) => {
54
+ const text = String(line)
55
+ const ends = text.match(/^coverage ends at (\d+), expected (\d+)/)
56
+ if (ends) return `字幕只覆盖到第 ${ends[1]} 句,应该有 ${ends[2]} 句`
57
+ const from = text.match(/^expected from=(\d+), got (\d+)/)
58
+ if (from) return `第 ${from[2]} 句的位置对不上:这里应该是第 ${from[1]} 句`
59
+ if (/^no cues$/.test(text)) return '还没有字幕内容'
60
+ if (/^invalid range/.test(text)) return `有一处句子的范围无效:${text}`
61
+ if (/^non-integer range/.test(text)) return `有一处句子的编号不是整数:${text}`
62
+ return text
63
+ })
64
+ }
65
+
49
66
  export function cueStats(rows) {
50
67
  const durations = rows.map((row) => (row.end - row.start) / 1000)
51
68
  const chars = rows.map((row) => row.jp.length)
@@ -80,10 +97,12 @@ function cueRuns(cues) {
80
97
  const from = Number(cue.from)
81
98
  const to = Number(cue.to)
82
99
  const fixed = Number.isFinite(cue.start) || Number.isFinite(cue.end)
100
+ const skip = cue.skip === true
83
101
  const previous = runs[runs.length - 1]
84
- const sameFragment = previous && !fixed && !previous.fixed && from === to && previous.from === from && previous.to === to
102
+ const sameFragment =
103
+ previous && !fixed && !skip && !previous.fixed && !previous.skip && from === to && previous.from === from && previous.to === to
85
104
  if (sameFragment) previous.items.push(cue)
86
- else runs.push({ from, to, fixed, items: [cue] })
105
+ else runs.push({ from, to, fixed, skip, items: [cue] })
87
106
  }
88
107
  return runs
89
108
  }
@@ -142,6 +161,10 @@ export function deriveCueTimes(fragments, cues) {
142
161
  const spanStart = Number(first.start) * 1000 || 0
143
162
  const spanEnd = Number(last.end) * 1000 || 0
144
163
 
164
+ if (run.skip) {
165
+ times.push({ start: spanStart / 1000, end: spanEnd / 1000, fixed: false, skip: true })
166
+ continue
167
+ }
145
168
  if (run.fixed) {
146
169
  for (const item of run.items) {
147
170
  const start = seconds(item.start, spanStart)
@@ -171,6 +194,7 @@ export function buildRows(fragments, cues, options = {}) {
171
194
  const maxDuration = (options.maxDuration ?? 9) * 1000
172
195
  const rows = []
173
196
  for (const run of cueRuns(cues)) {
197
+ if (run.skip) continue
174
198
  const first = fragments[run.from - 1]
175
199
  const last = fragments[run.to - 1]
176
200
  if (!first || !last) throw new Error(`cue ${run.from}-${run.to} is outside the fragment list`)