dsh-ai-subtitle 0.2.0 → 0.3.1

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/review.js ADDED
@@ -0,0 +1,317 @@
1
+ import { copyFileSync, existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { describeCoverageErrors, validateCues } from './cues.js'
4
+ import { applyCorrections, checkTerms, glossaryPath, loadGlossary, termsInText } from './glossary.js'
5
+
6
+ export const MAX_FRAGMENTS = 60
7
+ export const MAX_CHARS = 1500
8
+
9
+ const BATCH_LINE = /^(\d+)(?:\s*-\s*(\d+))?\s*\|(.*)$/
10
+
11
+ function strip(text) {
12
+ return String(text || '').replace(/\s+/g, '')
13
+ }
14
+
15
+ /**
16
+ * Fixed-size windows over the fragment list, extended so a split never lands inside
17
+ * an existing cue. Ids are the fragment range, which keeps them stable while cues change.
18
+ */
19
+ export function planBatches(fragments, cues = [], options = {}) {
20
+ const maxFragments = options.maxFragments || MAX_FRAGMENTS
21
+ const maxChars = options.maxChars || MAX_CHARS
22
+ const batches = []
23
+ let index = 0
24
+ while (index < fragments.length) {
25
+ const from = index + 1
26
+ let chars = 0
27
+ let count = 0
28
+ while (index < fragments.length) {
29
+ const length = strip(fragments[index].text).length
30
+ if (count > 0 && (count >= maxFragments || chars + length > maxChars)) break
31
+ chars += length
32
+ count += 1
33
+ index += 1
34
+ }
35
+ let to = from + count - 1
36
+ const straddling = cues.find((cue) => Number(cue.from) <= to && Number(cue.to) > to && Number(cue.from) >= from)
37
+ if (straddling) {
38
+ to = Number(straddling.to)
39
+ index = to
40
+ }
41
+ batches.push({ id: `${from}-${to}`, from, to, fragments: to - from + 1, chars })
42
+ }
43
+ return batches
44
+ }
45
+
46
+ /** A batch is complete when every fragment is covered, translated when all coverings have text. */
47
+ export function batchState(batch, cues) {
48
+ const overlapping = cues.filter((cue) => Number(cue.to) >= batch.from && Number(cue.from) <= batch.to)
49
+ let covered = 0
50
+ for (let index = batch.from; index <= batch.to; index += 1) {
51
+ if (overlapping.some((cue) => Number(cue.from) <= index && Number(cue.to) >= index)) covered += 1
52
+ }
53
+ const complete = covered === batch.fragments
54
+ const translated = complete && overlapping.every((cue) => cue.skip === true || String(cue.zh || '').trim().length > 0)
55
+ return { overlapping, covered, complete, translated }
56
+ }
57
+
58
+ export function nextBatch(batches, cues) {
59
+ return batches.find((batch) => !batchState(batch, cues).translated) || null
60
+ }
61
+
62
+ function clock(seconds) {
63
+ const total = Math.max(0, Math.round(seconds))
64
+ const minutes = Math.floor(total / 60)
65
+ return `${String(minutes).padStart(2, '0')}:${String(total % 60).padStart(2, '0')}`
66
+ }
67
+
68
+ /** The block handed to a model: one line per cue (or per uncovered fragment). */
69
+ export function renderBatch(batch, fragments, cues, glossary, hints) {
70
+ const first = fragments[batch.from - 1]
71
+ const last = fragments[batch.to - 1]
72
+ const lines = [
73
+ `# batch ${batch.id} · ${batch.fragments} fragments · ${clock(first.start)}-${clock(last.end)} · ${batch.chars} jp chars`,
74
+ ]
75
+
76
+ const terms = glossary ? termsInText(fragments.slice(batch.from - 1, batch.to).map((item) => item.text).join(''), glossary.terms) : []
77
+ if (terms.length > 0) lines.push(`# terms: ${terms.map((term) => `${term.jp}→${term.zh}`).join('; ')}`)
78
+ if (hints && (hints.tags.length > 0 || hints.note)) {
79
+ const context = []
80
+ if (hints.tags.length > 0) context.push('标签 ' + hints.tags.join('、'))
81
+ if (hints.note) context.push('说明 ' + hints.note)
82
+ lines.push('# 背景: ' + context.join(';'))
83
+ }
84
+
85
+ const byFragment = (index) => cues.find((cue) => Number(cue.from) <= index && Number(cue.to) >= index)
86
+ let index = batch.from
87
+ while (index <= batch.to) {
88
+ const cue = byFragment(index)
89
+ if (cue) {
90
+ lines.push(cue.skip === true ? `${cue.from}-${cue.to}|<skip>` : `${cue.from}-${cue.to}|${cue.jp}|${cue.zh ?? ''}`)
91
+ index = Number(cue.to) + 1
92
+ continue
93
+ }
94
+ lines.push(`${index}|${fragments[index - 1].text}`)
95
+ index += 1
96
+ }
97
+ return lines.join('\n')
98
+ }
99
+
100
+ export function parseLines(text) {
101
+ const rows = []
102
+ const errors = []
103
+ String(text || '')
104
+ .split(/\r?\n/)
105
+ .forEach((raw, position) => {
106
+ const line = raw.trim()
107
+ if (!line || line.startsWith('#') || line.startsWith('//')) return
108
+ const match = BATCH_LINE.exec(line)
109
+ if (!match) {
110
+ errors.push(`第 ${position + 1} 行格式不对:应该是 "from-to|jp|zh",实际是 "${line.slice(0, 60)}"`)
111
+ return
112
+ }
113
+ const from = Number(match[1])
114
+ const to = match[2] ? Number(match[2]) : from
115
+ if (!Number.isInteger(from) || !Number.isInteger(to) || to < from) {
116
+ errors.push(`第 ${position + 1} 行的范围无效:${match[1]}-${match[2]}`)
117
+ return
118
+ }
119
+ const rest = match[3]
120
+ const separator = rest.indexOf('|')
121
+ const jp = (separator >= 0 ? rest.slice(0, separator) : rest).trim()
122
+ const zh = separator >= 0 ? rest.slice(separator + 1).trim() : ''
123
+ if (jp === '<skip>' || jp.toLowerCase() === '<skip>') {
124
+ rows.push({ from, to, jp: '', zh: '', skip: true, line: position + 1 })
125
+ return
126
+ }
127
+ if (!jp) {
128
+ errors.push(`第 ${position + 1} 行没有日文`)
129
+ return
130
+ }
131
+ rows.push({ from, to, jp, zh, line: position + 1 })
132
+ })
133
+ return { rows, errors }
134
+ }
135
+
136
+ export function validateBatch(rows, batch) {
137
+ const errors = []
138
+ if (rows.length === 0) return ['no cue lines were returned']
139
+ if (rows[0].from !== batch.from) errors.push(`第一行从第 ${rows[0].from} 句开始,但这一批从第 ${batch.from} 句开始`)
140
+ if (rows[rows.length - 1].to !== batch.to) {
141
+ errors.push(`最后一行到第 ${rows[rows.length - 1].to} 句,但这一批到第 ${batch.to} 句`)
142
+ }
143
+ let cursor = batch.from
144
+ for (const row of rows) {
145
+ if (row.from !== cursor) errors.push(`第 ${row.line} 行:这里应该从第 ${cursor} 句开始,实际是第 ${row.from} 句`)
146
+ if (row.to < row.from) errors.push(`第 ${row.line} 行:范围为空`)
147
+ cursor = row.to + 1
148
+ }
149
+ return errors
150
+ }
151
+
152
+ /** Replace every cue that overlaps the batch, then keep the file ordered by range. */
153
+ export function mergeCues(cues, rows, batch) {
154
+ const kept = cues.filter((cue) => Number(cue.to) < batch.from || Number(cue.from) > batch.to)
155
+ const next = kept.concat(
156
+ rows.map((row) => (row.skip ? { from: row.from, to: row.to, jp: '', zh: '', skip: true } : { from: row.from, to: row.to, jp: row.jp, zh: row.zh })),
157
+ )
158
+ return next.sort((left, right) => Number(left.from) - Number(right.from))
159
+ }
160
+
161
+ export function loadProject(projectDir) {
162
+ const asrPath = join(projectDir, 'asr.json')
163
+ const cuesPath = join(projectDir, 'cues.json')
164
+ if (!existsSync(asrPath)) throw new Error(`项目里没有识别结果(asr.json):${projectDir}`)
165
+ const asr = JSON.parse(readFileSync(asrPath, 'utf8'))
166
+ if (!Array.isArray(asr.fragments) || asr.fragments.length === 0) throw new Error('识别结果里没有内容(asr.json)')
167
+ const cues = existsSync(cuesPath) ? JSON.parse(readFileSync(cuesPath, 'utf8')) : []
168
+ if (!Array.isArray(cues)) throw new Error('字幕内容文件格式不对(应该是数组)')
169
+ return { asr, cues, fragments: asr.fragments, asrPath, cuesPath }
170
+ }
171
+
172
+ function writeAtomic(path, cues) {
173
+ if (existsSync(path)) copyFileSync(path, path + '.bak')
174
+ const temp = path + '.tmp'
175
+ writeFileSync(temp, JSON.stringify(cues, null, 1), 'utf8')
176
+ renameSync(temp, path)
177
+ }
178
+
179
+ export function applyBatch(projectDir, options = {}) {
180
+ const { cues, fragments, cuesPath } = loadProject(projectDir)
181
+ const glossary = loadGlossary(options.glossary || glossaryPath(projectDir))
182
+ const batches = planBatches(fragments, cues, options)
183
+ const batch = batches.find((item) => item.id === options.batch)
184
+ if (!batch) {
185
+ const ids = batches.map((item) => item.id)
186
+ throw new Error(`没有这个批次:${options.batch};可用的是 ${ids.slice(0, 8).join(', ')}${ids.length > 8 ? '…' : ''}`)
187
+ }
188
+
189
+ const parsed = parseLines(options.lines)
190
+ const errors = [...parsed.errors, ...validateBatch(parsed.rows, batch)]
191
+ if (errors.length > 0) throw new Error(errors.slice(0, 10).join('; '))
192
+
193
+ const allowEmpty = options.allowEmpty === true
194
+ const missingText = parsed.rows.filter((row) => !row.skip && !row.zh && !allowEmpty)
195
+ if (missingText.length > 0) {
196
+ throw new Error(
197
+ `这些行没有中文:第 ${missingText.map((row) => row.line).join('、')} 行;音乐或音效可用「允许空中文」`,
198
+ )
199
+ }
200
+
201
+ const correctionHits = []
202
+ const termMissing = []
203
+ const rows = parsed.rows.map((row) => {
204
+ if (row.skip) return row
205
+ const corrected = applyCorrections(row.jp, glossary.corrections)
206
+ correctionHits.push(...corrected.hits)
207
+ const check = checkTerms(corrected.text, row.zh, glossary.terms)
208
+ termMissing.push(...check.missing)
209
+ return { ...row, jp: corrected.text }
210
+ })
211
+
212
+ if (glossary.strict && termMissing.length > 0) {
213
+ throw new Error(`glossary (strict): ${termMissing.map((term) => `${term.jp}→${term.zh}`).join('; ')}`)
214
+ }
215
+
216
+ const before = new Map(
217
+ cues
218
+ .filter((cue) => Number(cue.to) >= batch.from && Number(cue.from) <= batch.to)
219
+ .map((cue) => [`${cue.from}-${cue.to}`, String(cue.jp || '')]),
220
+ )
221
+ let jpChanged = 0
222
+ for (const row of rows) {
223
+ if (row.skip) continue
224
+ const key = `${row.from}-${row.to}`
225
+ const previous = before.get(key)
226
+ if (previous !== undefined && previous !== row.jp) jpChanged += 1
227
+ }
228
+
229
+ const merged = mergeCues(cues, rows, batch)
230
+ const coverage = validateCues(merged, fragments.length, { requireFull: false })
231
+ if (!coverage.ok) throw new Error('字幕内容不连续:' + describeCoverageErrors(coverage.errors).slice(0, 5).join(';'))
232
+
233
+ writeAtomic(cuesPath, merged)
234
+ return {
235
+ batch: batch.id,
236
+ cues: rows.length,
237
+ totalCues: merged.length,
238
+ corrections: [...new Set(correctionHits.map((rule) => `${rule.from}→${rule.to}`))],
239
+ glossaryMissing: [...new Set(termMissing.map((term) => `${term.jp}→${term.zh}`))],
240
+ skipped: rows.filter((row) => row.skip).length,
241
+ emptyAllowed: rows.filter((row) => !row.skip && !row.zh).length,
242
+ jpChanged,
243
+ }
244
+ }
245
+
246
+ export function reviewStatus(projectDir, options = {}) {
247
+ const { cues, fragments } = loadProject(projectDir)
248
+ const glossary = loadGlossary(options.glossary || glossaryPath(projectDir))
249
+ const batches = planBatches(fragments, cues, options)
250
+ const states = batches.map((batch) => ({ batch, ...batchState(batch, cues) }))
251
+ const translated = states.filter((state) => state.translated).length
252
+ const next = states.find((state) => !state.translated)
253
+ return {
254
+ fragments: fragments.length,
255
+ batches: batches.length,
256
+ translated,
257
+ remaining: batches.length - translated,
258
+ next: next ? next.batch.id : null,
259
+ glossary: { path: glossary.path, exists: glossary.exists, strict: glossary.strict, terms: glossary.terms.length, corrections: glossary.corrections.length, errors: glossary.errors },
260
+ }
261
+ }
262
+
263
+ export function reviewReport(projectDir, options = {}) {
264
+ const { cues, fragments } = loadProject(projectDir)
265
+ const glossary = loadGlossary(options.glossary || glossaryPath(projectDir))
266
+ const batches = planBatches(fragments, cues, options)
267
+ const rows = []
268
+ const outliers = []
269
+ for (const batch of batches) {
270
+ const state = batchState(batch, cues)
271
+ const status = state.translated ? 'done' : state.complete ? 'no-zh' : state.covered > 0 ? 'partial' : 'empty'
272
+ rows.push(`${batch.id.padEnd(10)} ${status.padEnd(8)} ${state.covered}/${batch.fragments} fragments`)
273
+ for (const cue of state.overlapping) {
274
+ const jp = strip(cue.jp).length
275
+ const zh = strip(cue.zh).length
276
+ if (!zh || jp === 0) continue
277
+ const ratio = zh / jp
278
+ if (ratio < 0.4 || ratio > 1.6) outliers.push({ cue: `${cue.from}-${cue.to}`, jp, zh, ratio: Number(ratio.toFixed(2)) })
279
+ }
280
+ }
281
+ const glossaryMissing = cues.flatMap((cue) =>
282
+ checkTerms(String(cue.jp || ''), String(cue.zh || ''), glossary.terms).missing.map((term) => `${cue.from}-${cue.to}: ${term.jp}→${term.zh}`),
283
+ )
284
+ return { batches: rows, outliers: outliers.slice(0, 20), glossaryMissing: [...new Set(glossaryMissing)].slice(0, 20), glossary }
285
+ }
286
+
287
+ export function formatStatus(status) {
288
+ const lines = [
289
+ `project: ${status.fragments} fragments · ${status.batches} batches · translated ${status.translated}/${status.batches}`,
290
+ `next batch: ${status.next || '(none, everything translated)'}`,
291
+ `glossary: ${status.glossary.exists ? `${status.glossary.terms} terms, ${status.glossary.corrections} corrections, strict=${status.glossary.strict}` : 'not found, no terms enforced'}`,
292
+ ]
293
+ if (status.glossary.errors.length > 0) lines.push('glossary errors: ' + status.glossary.errors.join('; '))
294
+ return lines.join('\n')
295
+ }
296
+
297
+ export function formatReport(report) {
298
+ const lines = ['batches:', ...report.batches.map((row) => ' ' + row)]
299
+ if (report.outliers.length > 0) {
300
+ lines.push('', 'length outliers (zh/jp outside 0.4-1.6):')
301
+ for (const item of report.outliers) lines.push(` cue ${item.cue}: jp ${item.jp}, zh ${item.zh} (${item.ratio})`)
302
+ }
303
+ if (report.glossaryMissing.length > 0) {
304
+ lines.push('', 'glossary misses:')
305
+ for (const item of report.glossaryMissing) lines.push(' ' + item)
306
+ }
307
+ return lines.join('\n')
308
+ }
309
+
310
+ export function formatApply(result) {
311
+ const lines = [`batch ${result.batch}: wrote ${result.cues} cues (${result.totalCues} total)`]
312
+ if (result.corrections.length > 0) lines.push(`corrections: ${result.corrections.join(', ')}`)
313
+ if (result.glossaryMissing.length > 0) lines.push(`glossary misses: ${result.glossaryMissing.join(', ')}`)
314
+ if (result.skipped > 0) lines.push(`${result.skipped} range(s) marked skip`)
315
+ if (result.emptyAllowed > 0) lines.push(`${result.emptyAllowed} cue(s) kept with empty Chinese`)
316
+ return lines.join('\n')
317
+ }
package/src/runtime.js CHANGED
@@ -2,7 +2,8 @@ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, r
2
2
  import { basename, dirname, join, relative, resolve, sep } from 'node:path'
3
3
  import { execFileSync } from 'node:child_process'
4
4
  import { DEFAULT_MODEL, hfEnv, installRuntime, run } from './installer.js'
5
- import { ensureDirs, layout, packageDir, readState, resolveDefaultRoot, writePointer, writeState } from './paths.js'
5
+ import { defaultProjectsDir, ensureDirs, layout, packageDir, readState, resolveDefaultRoot, writePointer, writeState } from './paths.js'
6
+ import { transcribeMessage } from './messages.js'
6
7
  import { loadRegistry, saveRegistry } from './registry.js'
7
8
  import { startJob } from './jobs.js'
8
9
 
@@ -76,11 +77,25 @@ function applyOverrides(L, state) {
76
77
  }
77
78
  }
78
79
 
80
+ /** An explicit setting wins; an existing legacy folder is kept; new installs use Documents. */
81
+ function resolveProjectsDir(state, root) {
82
+ if (state && typeof state.projectsDir === 'string' && state.projectsDir) return state.projectsDir
83
+ const legacy = join(root, 'projects')
84
+ try {
85
+ if (existsSync(legacy) && readdirSync(legacy).length > 0) return legacy
86
+ } catch {
87
+ // unreadable legacy folder: fall back to the default
88
+ }
89
+ return defaultProjectsDir()
90
+ }
91
+
79
92
  export class Runtime {
80
93
  constructor(installDir) {
81
94
  const root = installDir || process.env.DSH_SUBTITLE_DIR || resolveDefaultRoot()
82
95
  this.L = layout(root)
83
- applyOverrides(this.L, readState(this.L))
96
+ const state = readState(this.L)
97
+ applyOverrides(this.L, state)
98
+ this.L.projects = resolveProjectsDir(state, this.L.root)
84
99
  ensureDirs(this.L)
85
100
  this.adopt()
86
101
  }
@@ -93,6 +108,13 @@ export class Runtime {
93
108
  return this.L.projects
94
109
  }
95
110
 
111
+ /** Persist a new projects directory; callers move existing projects themselves. */
112
+ setProjectsDir(dir) {
113
+ this.L.projects = dir
114
+ ensureDirs(this.L)
115
+ writeState(this.L, { projectsDir: dir })
116
+ }
117
+
96
118
  /** A runtime is ours when it carries the marker, or was installed by this plugin. */
97
119
  ownsRuntime() {
98
120
  if (existsSync(join(this.L.root, MARKER))) return true
@@ -290,12 +312,12 @@ export class Runtime {
290
312
  const wav = join(projectDir, 'audio.wav')
291
313
  const asrPath = join(projectDir, 'asr.json')
292
314
 
293
- job.report(2, 'probe', 'reading duration')
315
+ job.report(2, 'probe', transcribeMessage('reading duration'))
294
316
  const probe = await run(L.ffprobe, ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', media], { signal: job.signal })
295
317
  const duration = Number((probe.stdout || '0').trim()) || 0
296
318
  job.note(`duration ${secondsToClock(duration)}`)
297
319
 
298
- job.report(4, 'audio', 'extracting 16 kHz mono wav')
320
+ job.report(4, 'audio', transcribeMessage('extracting 16 kHz mono wav'))
299
321
  let lastPct = 4
300
322
  const ffmpeg = await run(
301
323
  L.ffmpeg,
@@ -317,7 +339,7 @@ export class Runtime {
317
339
  )
318
340
  if (ffmpeg.code !== 0) throw new Error(`ffmpeg failed: ${ffmpeg.stderr.slice(-500)}`)
319
341
 
320
- job.report(21, 'asr', 'loading model')
342
+ job.report(21, 'asr', transcribeMessage('loading model'))
321
343
  const worker = join(packageDir(), 'python', 'worker.py')
322
344
  const child = run(
323
345
  L.venvPython,
@@ -336,8 +358,8 @@ export class Runtime {
336
358
  if (line.startsWith('{')) {
337
359
  try {
338
360
  const event = JSON.parse(line)
339
- if (event.type === 'stage') job.report(22 + (event.pct || 0) * 0.7, 'asr', event.msg || '')
340
- else if (event.type === 'progress') job.report(22 + (event.pct || 0) * 0.7, 'asr', event.msg || '')
361
+ if (event.type === 'stage') job.report(22 + (event.pct || 0) * 0.7, 'asr', transcribeMessage(event.msg))
362
+ else if (event.type === 'progress') job.report(22 + (event.pct || 0) * 0.7, 'asr', transcribeMessage(event.msg))
341
363
  else if (event.type === 'info') job.note(event.msg)
342
364
  } catch {
343
365
  job.note(line)
@@ -351,7 +373,7 @@ export class Runtime {
351
373
  const result = await child
352
374
  if (result.code !== 0) throw new Error(`worker failed: ${(result.stderr || '').slice(-800)}`)
353
375
 
354
- job.report(95, 'post', 'reading fragments')
376
+ job.report(95, 'post', transcribeMessage('reading fragments'))
355
377
  const asr = JSON.parse(readFileSync(asrPath, 'utf8'))
356
378
  const fragments = asr.fragments || []
357
379
  writeFileSync(