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/README.en.md +6 -1
- package/README.ja.md +3 -1
- package/README.ko.md +3 -1
- package/README.md +7 -2
- package/client.js +319 -19
- package/docs/REVIEW.md +4 -4
- package/index.js +54 -3
- package/package.json +1 -1
- package/python/worker.py +86 -5
- package/src/api.js +148 -4
- package/src/audio.js +20 -0
- package/src/cues.js +222 -9
- package/src/export-name.js +22 -0
- package/src/glossary.js +21 -1
- package/src/library.js +98 -0
- package/src/llm.js +209 -26
- package/src/quality.js +61 -0
- package/src/resplit.js +143 -0
- package/src/review.js +28 -5
package/src/llm.js
CHANGED
|
@@ -3,17 +3,32 @@ import { join } from 'node:path'
|
|
|
3
3
|
import { feedbackForBatch } from './feedback.js'
|
|
4
4
|
import { loadHints } from './hints.js'
|
|
5
5
|
import { glossaryPath, loadGlossary, termsInText } from './glossary.js'
|
|
6
|
-
import { applyBatch, loadProject, nextBatch, planBatches, renderBatch } from './review.js'
|
|
6
|
+
import { applyBatch, batchState, loadProject, nextBatch, planBatches, renderBatch, salvageLines } from './review.js'
|
|
7
7
|
|
|
8
8
|
const SYSTEM_PROMPT = [
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
9
|
+
'你是专业的日语视频字幕译者,为中文观众制作可直接使用的字幕。',
|
|
10
|
+
'输入每行 "from-to|日文",已有中文时为 "from-to|日文|中文";输出 "from-to|校正后的日文|中文"。',
|
|
11
|
+
'规则:',
|
|
12
|
+
'1. 只输出这些行,不要解释、不要编号、不要 Markdown 代码块。',
|
|
13
|
+
'2. 保持与输入完全相同的行数和 from-to 编号,不要合并、拆分或越出本批。',
|
|
14
|
+
'3. 中文口语化,不逐字直译;同一句在相邻行重复时,各行的译文可以写成同一个短句,不要越写越长。',
|
|
15
|
+
'4. 标点用「,。?!——…」;每条字幕结尾不加句号,但句中该有的标点必须保留。',
|
|
16
|
+
'5. 明显不是台词的内容(纯音乐、效果音、听不清的背景人声、无意义拟声)输出 from-to|<skip>;有实际语义的对话、语气回应和笑声必须保留。',
|
|
17
|
+
'6. 朗读信件、引用他人发言、复述聊天内容、歌词等引用内容,用中文引号 “ ” 包裹;说话人自己的话不加引号;引号内再用单引号 ‘ ’。',
|
|
18
|
+
'7. 人名、作品名、术语按术语表统一。',
|
|
19
|
+
'8. 校对日文:只修正明显的同音字、漏字、重复和断句,并补上缺失的句读(、。?!);不改动措辞,不确定就保留原文。',
|
|
20
|
+
'9. 用户的意见优先于你自己的判断。',
|
|
21
|
+
'10. 译文要像中文母语者写的字幕:口语、顺、短。不要逐词对应,可以调整语序、合并重复、省略主语。',
|
|
22
|
+
'11. 避免书面词:十分→很、因此→所以、然而→不过、大约→大概、立刻→马上、以及→和。',
|
|
23
|
+
'12. 语气词只在中文里说得自然时才加(ね→嘛/吧/啊),不要每句都添。',
|
|
24
|
+
'14. 人名、作品名一律使用术语表的中文写法;原文假名与术语表对不上时,按发音和上下文判断为同一人。',
|
|
25
|
+
'13. 示例(照着这个语感写):',
|
|
26
|
+
' 日:今日はいい天気ですね / そうですね、散歩でも行きましょうか',
|
|
27
|
+
' 中:今天天气真好啊 / 是啊,要不要去散散步',
|
|
28
|
+
' 日:この店のラーメン、すごくおいしいですよ / へえ、知らなかった',
|
|
29
|
+
' 中:这家的拉面特别好吃哦 / 诶,我还不知道呢',
|
|
30
|
+
' 日:初めて来たの? / うん、友達に聞いて',
|
|
31
|
+
' 中:第一次来吗? / 嗯,听朋友说的',
|
|
17
32
|
].join('\n')
|
|
18
33
|
|
|
19
34
|
export function routeFile(projectDir) {
|
|
@@ -67,8 +82,51 @@ export async function resolveRoute(ctx, options = {}) {
|
|
|
67
82
|
return { provider, model }
|
|
68
83
|
}
|
|
69
84
|
|
|
70
|
-
/**
|
|
71
|
-
|
|
85
|
+
/**
|
|
86
|
+
* Pick a reasoning effort the model advertises, or undefined when it offers none.
|
|
87
|
+
* @param ctx - the injected model context.
|
|
88
|
+
* @param route - provider and model to ask about.
|
|
89
|
+
*/
|
|
90
|
+
async function pickEffort(ctx, route) {
|
|
91
|
+
try {
|
|
92
|
+
const info = await ctx.llm.resolveModelInfo(route.provider, route.model)
|
|
93
|
+
const efforts = info && info.reasoning && info.reasoning.efforts
|
|
94
|
+
return Array.isArray(efforts) && efforts.length > 0 ? efforts[0].id : undefined
|
|
95
|
+
} catch {
|
|
96
|
+
return undefined
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const TRANSIENT_CODES = new Set([
|
|
101
|
+
'RATE_LIMIT', 'TIMEOUT', 'NETWORK', 'SERVER', 'UNAVAILABLE', 'OVERLOADED', 'INTERNAL', 'CONNECTION',
|
|
102
|
+
])
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Whether a failed call is worth retrying: rate limits, timeouts, transport
|
|
106
|
+
* breaks and 5xx. Authentication, invalid requests and content refusals are not.
|
|
107
|
+
* @param error - error thrown by the stream or the terminal finish chunk.
|
|
108
|
+
*/
|
|
109
|
+
export function isTransientError(error) {
|
|
110
|
+
const code = String((error && error.code) || '').toUpperCase()
|
|
111
|
+
const message = String((error && error.message) || error || '')
|
|
112
|
+
if (TRANSIENT_CODES.has(code)) return true
|
|
113
|
+
return /\b(429|500|502|503|504)\b|timeout|timed out|超时|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|socket hang up|fetch failed|network/i.test(message)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Whether the provider refused the content rather than failing. These are final:
|
|
118
|
+
* retrying the same text cannot change the provider's decision.
|
|
119
|
+
* @param error - error thrown by the stream or the terminal finish chunk.
|
|
120
|
+
*/
|
|
121
|
+
export function isContentRefusal(error) {
|
|
122
|
+
const code = String((error && error.code) || '').toUpperCase()
|
|
123
|
+
const message = String((error && (error.providerMessage || error.message)) || error || '')
|
|
124
|
+
if (code === 'SENSITIVE' || code === 'CONTENT_POLICY' || code === 'MODERATION') return true
|
|
125
|
+
return /sensitive|moderation|content.?policy|safety|refus|违规|敏感/i.test(message)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** One attempt: stream the call, then expose the terminal failure with its code. */
|
|
129
|
+
async function completeOnce(ctx, route, request, reasoningEffort) {
|
|
72
130
|
const controller = new AbortController()
|
|
73
131
|
const timer = setTimeout(() => controller.abort(new Error('模型调用超时')), request.timeoutMs || 180000)
|
|
74
132
|
const signal = request.signal
|
|
@@ -80,6 +138,7 @@ export async function completeText(ctx, route, request = {}) {
|
|
|
80
138
|
const stream = ctx.llm.stream({
|
|
81
139
|
provider: route.provider,
|
|
82
140
|
model: route.model,
|
|
141
|
+
...(reasoningEffort === undefined ? {} : { reasoningEffort }),
|
|
83
142
|
system: SYSTEM_PROMPT,
|
|
84
143
|
messages: [{ role: 'user', content: [{ type: 'text', text: request.prompt }] }],
|
|
85
144
|
temperature: 0.2,
|
|
@@ -94,12 +153,41 @@ export async function completeText(ctx, route, request = {}) {
|
|
|
94
153
|
clearTimeout(timer)
|
|
95
154
|
}
|
|
96
155
|
if (finish && finish.kind === 'error') {
|
|
97
|
-
|
|
156
|
+
const failure = finish.failure || {}
|
|
157
|
+
const error = new Error('模型返回错误:' + (failure.message || 'unknown'))
|
|
158
|
+
error.code = failure.code || ''
|
|
159
|
+
error.providerMessage = failure.message || ''
|
|
160
|
+
throw error
|
|
98
161
|
}
|
|
99
162
|
if (finish && finish.kind === 'aborted') throw new Error('模型调用已取消')
|
|
100
163
|
return text.trim()
|
|
101
164
|
}
|
|
102
165
|
|
|
166
|
+
/**
|
|
167
|
+
* One call for consumers: collects the text, retries transient failures twice,
|
|
168
|
+
* and never retries a content refusal.
|
|
169
|
+
*/
|
|
170
|
+
export async function completeText(ctx, route, request = {}) {
|
|
171
|
+
const reasoningEffort = await pickEffort(ctx, route)
|
|
172
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
173
|
+
try {
|
|
174
|
+
return await completeOnce(ctx, route, request, reasoningEffort)
|
|
175
|
+
} catch (error) {
|
|
176
|
+
if (isContentRefusal(error) || !isTransientError(error) || attempt >= 2) throw error
|
|
177
|
+
const delay = 800 * (attempt + 1)
|
|
178
|
+
await new Promise((resolve, reject) => {
|
|
179
|
+
const timer = setTimeout(resolve, delay)
|
|
180
|
+
if (request.signal) {
|
|
181
|
+
request.signal.addEventListener('abort', () => {
|
|
182
|
+
clearTimeout(timer)
|
|
183
|
+
reject(new Error('模型调用已取消'))
|
|
184
|
+
}, { once: true })
|
|
185
|
+
}
|
|
186
|
+
})
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
103
191
|
/** The prompt for one batch: glossary, feedback, and the lines to translate. */
|
|
104
192
|
export function buildPrompt(projectDir, batch, fragments, cues, glossary, feedback, hints, mode = 'translate') {
|
|
105
193
|
const context = hints || loadHints(projectDir)
|
|
@@ -123,7 +211,7 @@ export function buildPrompt(projectDir, batch, fragments, cues, glossary, feedba
|
|
|
123
211
|
if (mode === 'proofread') {
|
|
124
212
|
lines.push('')
|
|
125
213
|
lines.push('另外:先校正日文的识别错误再翻译。')
|
|
126
|
-
lines.push('-
|
|
214
|
+
lines.push('- 修正同音字、漏字、重复、断句错误,补上缺失的句读(、。?!),保留说话人的语气、口癖和停顿感。')
|
|
127
215
|
lines.push('- 不要改写措辞,不要补出没说过的内容;没有把握的地方保持原样。')
|
|
128
216
|
lines.push('- 输出的 jp 必须是校正后的日文。')
|
|
129
217
|
}
|
|
@@ -142,36 +230,131 @@ function stripFence(text) {
|
|
|
142
230
|
* Translate one batch through the session's model and write the result back.
|
|
143
231
|
* Returns the same summary shape as applyBatch plus the route used.
|
|
144
232
|
*/
|
|
145
|
-
|
|
233
|
+
/**
|
|
234
|
+
* Ask the model for one batch and validate the reply without writing cues.
|
|
235
|
+
* The caller decides when to apply it, so parallel batches can be written in
|
|
236
|
+
* order and never leave a gap in the file.
|
|
237
|
+
*/
|
|
238
|
+
export async function prepareBatchLines(ctx, projectDir, options = {}) {
|
|
146
239
|
const { cues, fragments } = loadProject(projectDir)
|
|
147
240
|
const glossary = loadGlossary(options.glossary || glossaryPath(projectDir))
|
|
148
241
|
const batches = planBatches(fragments, cues)
|
|
149
242
|
const batch = options.batch
|
|
150
243
|
? batches.find((item) => item.id === options.batch)
|
|
151
244
|
: nextBatch(batches, cues)
|
|
152
|
-
if (!batch)
|
|
245
|
+
if (!batch) {
|
|
246
|
+
if (options.batch) throw new Error('批次 ' + options.batch + ' 不在当前计划里,请重试')
|
|
247
|
+
return { done: true, message: '所有批次都已翻译' }
|
|
248
|
+
}
|
|
153
249
|
|
|
154
250
|
const feedback = feedbackForBatch(projectDir, batch.id)
|
|
155
251
|
const route = options.route || (await resolveRoute(ctx, { ...options, projectDir }))
|
|
156
252
|
const prompt = buildPrompt(projectDir, batch, fragments, cues, glossary, feedback, undefined, options.mode)
|
|
157
|
-
const
|
|
158
|
-
|
|
159
|
-
const
|
|
253
|
+
const check = (candidate) => applyBatch(projectDir, { batch: batch.id, lines: candidate, dryRun: true })
|
|
254
|
+
|
|
255
|
+
const ask = async (text) => {
|
|
256
|
+
let raw
|
|
257
|
+
try {
|
|
258
|
+
raw = await completeText(ctx, route, { prompt: text, signal: options.signal })
|
|
259
|
+
} catch (error) {
|
|
260
|
+
if (isContentRefusal(error)) {
|
|
261
|
+
const detail = String(error.providerMessage || error.message || error)
|
|
262
|
+
throw new Error(
|
|
263
|
+
`批次 ${batch.id} 被模型拒绝(内容审核,${route.provider}/${route.model}):${detail}\n`
|
|
264
|
+
+ '可以换一个允许该内容的模型(例如自托管模型),或用「逐条修改」手动填写这一批。',
|
|
265
|
+
)
|
|
266
|
+
}
|
|
267
|
+
throw error
|
|
268
|
+
}
|
|
269
|
+
const stripped = stripFence(raw)
|
|
270
|
+
const lines = salvageLines(stripped)
|
|
271
|
+
if (!lines) {
|
|
272
|
+
throw new Error(
|
|
273
|
+
`模型没有按格式返回(${route.provider}/${route.model})。原始回复的前 200 字:${stripped.slice(0, 200)}`,
|
|
274
|
+
)
|
|
275
|
+
}
|
|
276
|
+
return lines
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
let lines = await ask(prompt)
|
|
280
|
+
let preview
|
|
281
|
+
try {
|
|
282
|
+
preview = check(lines)
|
|
283
|
+
} catch (error) {
|
|
284
|
+
const reason = String(error && error.message ? error.message : error)
|
|
285
|
+
const retryPrompt = `${prompt}
|
|
286
|
+
|
|
287
|
+
注意:上一轮输出没有通过校验(${reason})。请重新输出:
|
|
288
|
+
- 严格一行对一行,from-to 与输入完全一致,不合并、不拆分、不越界;
|
|
289
|
+
- 每一行都必须有中文;纯音乐、音效或无法翻译的行输出 "from-to|<skip>",不要留空。`
|
|
290
|
+
lines = await ask(retryPrompt)
|
|
291
|
+
preview = check(lines)
|
|
292
|
+
}
|
|
293
|
+
|
|
160
294
|
saveRoute(projectDir, route)
|
|
161
|
-
return {
|
|
295
|
+
return { batch, lines, route, feedback: feedback.length, preview }
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** Translate one batch and write it immediately (used by the single-batch tool). */
|
|
299
|
+
export async function translateBatch(ctx, projectDir, options = {}) {
|
|
300
|
+
const prepared = await prepareBatchLines(ctx, projectDir, options)
|
|
301
|
+
if (prepared.done) return prepared
|
|
302
|
+
const applied = applyBatch(projectDir, { batch: prepared.batch.id, lines: prepared.lines })
|
|
303
|
+
return { ...applied, route: `${prepared.route.provider}/${prepared.route.model}`, feedback: prepared.feedback }
|
|
162
304
|
}
|
|
163
305
|
|
|
164
306
|
/** Translate every remaining batch, reporting progress after each one. */
|
|
165
307
|
export async function translateRemaining(ctx, projectDir, options = {}) {
|
|
166
308
|
const route = options.route || (await resolveRoute(ctx, { ...options, projectDir }))
|
|
309
|
+
const { cues, fragments } = loadProject(projectDir)
|
|
310
|
+
const batches = planBatches(fragments, cues)
|
|
311
|
+
const pending = batches.filter((batch) => !batchState(batch, cues).translated).map((batch) => batch.id)
|
|
312
|
+
if (pending.length === 0) return { batches: [], route: `${route.provider}/${route.model}` }
|
|
313
|
+
|
|
314
|
+
const concurrency = Math.max(1, Math.min(Number(options.concurrency) || 1, 8))
|
|
315
|
+
const results = new Array(pending.length)
|
|
167
316
|
const done = []
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
317
|
+
const failures = []
|
|
318
|
+
let nextSlot = 0
|
|
319
|
+
let applySlot = 0
|
|
320
|
+
let limitHit = false
|
|
321
|
+
|
|
322
|
+
const flush = () => {
|
|
323
|
+
while (applySlot < pending.length && results[applySlot]) {
|
|
324
|
+
const item = results[applySlot]
|
|
325
|
+
applyBatch(projectDir, { batch: item.batch.id, lines: item.lines })
|
|
326
|
+
done.push(item.batch.id)
|
|
327
|
+
if (options.onProgress) options.onProgress(done.length, item.batch.id)
|
|
328
|
+
results[applySlot] = null
|
|
329
|
+
applySlot += 1
|
|
330
|
+
if (options.limit && done.length >= options.limit) limitHit = true
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const worker = async () => {
|
|
335
|
+
for (;;) {
|
|
336
|
+
if (options.signal && options.signal.aborted) throw new Error('已取消')
|
|
337
|
+
if (limitHit) return
|
|
338
|
+
const slot = nextSlot
|
|
339
|
+
if (slot >= pending.length) return
|
|
340
|
+
nextSlot += 1
|
|
341
|
+
try {
|
|
342
|
+
const prepared = await prepareBatchLines(ctx, projectDir, { ...options, route, batch: pending[slot] })
|
|
343
|
+
if (prepared.done) return
|
|
344
|
+
results[slot] = prepared
|
|
345
|
+
flush()
|
|
346
|
+
} catch (error) {
|
|
347
|
+
failures.push(String(error && error.message ? error.message : error))
|
|
348
|
+
return
|
|
349
|
+
}
|
|
350
|
+
}
|
|
175
351
|
}
|
|
352
|
+
|
|
353
|
+
// Model calls run in parallel; the writes above happen strictly in batch order,
|
|
354
|
+
// so the cue file always stays contiguous.
|
|
355
|
+
const workers = Array.from({ length: Math.min(concurrency, pending.length) }, () => worker())
|
|
356
|
+
await Promise.all(workers)
|
|
357
|
+
if (failures.length > 0) throw new Error(failures[0])
|
|
176
358
|
return { batches: done, route: `${route.provider}/${route.model}` }
|
|
177
359
|
}
|
|
360
|
+
|
package/src/quality.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Scan cues for the problems a reviewer usually looks for first. Pure function:
|
|
3
|
+
* the panel endpoint and the tests share it.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const KANA = /[\u3040-\u30ff]/
|
|
7
|
+
|
|
8
|
+
function timeOf(cue, fragments) {
|
|
9
|
+
const start = cue.start !== undefined ? cue.start : (fragments[Number(cue.from) - 1] || {}).start
|
|
10
|
+
const end = cue.end !== undefined ? cue.end : (fragments[Number(cue.to) - 1] || {}).end
|
|
11
|
+
return { start, end }
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @param cues - cue list ordered by fragment range.
|
|
16
|
+
* @param fragments - asr fragments for cue times.
|
|
17
|
+
* @param options - thresholds: minZh (3), maxZh (30), minRatio (0.35), sameGap (0.3).
|
|
18
|
+
*/
|
|
19
|
+
export function scanQuality(cues, fragments = [], options = {}) {
|
|
20
|
+
const minZh = options.minZh ?? 2
|
|
21
|
+
const maxZh = options.maxZh ?? 30
|
|
22
|
+
const minRatio = options.minRatio ?? 0.35
|
|
23
|
+
const sameGap = options.sameGap ?? 0.3
|
|
24
|
+
const counts = {}
|
|
25
|
+
const items = []
|
|
26
|
+
const add = (type, cue, detail) => {
|
|
27
|
+
counts[type] = (counts[type] || 0) + 1
|
|
28
|
+
if (items.length >= 300) return
|
|
29
|
+
const { start, end } = timeOf(cue, fragments)
|
|
30
|
+
items.push({
|
|
31
|
+
type,
|
|
32
|
+
from: cue.from,
|
|
33
|
+
to: cue.to,
|
|
34
|
+
start,
|
|
35
|
+
end,
|
|
36
|
+
jp: String(cue.jp || ''),
|
|
37
|
+
zh: String(cue.zh || ''),
|
|
38
|
+
detail,
|
|
39
|
+
})
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
for (let index = 0; index < cues.length; index += 1) {
|
|
43
|
+
const cue = cues[index]
|
|
44
|
+
const zh = String(cue.zh || '')
|
|
45
|
+
const jp = String(cue.jp || '')
|
|
46
|
+
if (!cue.skip && !zh.trim()) add('empty', cue, '没有中文')
|
|
47
|
+
if (!cue.skip && zh.trim() && zh.length < minZh) add('short', cue, '中文少于 ' + minZh + ' 字')
|
|
48
|
+
if (zh.length > maxZh) add('long', cue, '中文超过 ' + maxZh + ' 字')
|
|
49
|
+
if (KANA.test(zh)) add('kana', cue, '中文里混入假名')
|
|
50
|
+
if (jp && zh && zh.length / jp.length < minRatio) add('ratio', cue, '中文相对日文过短')
|
|
51
|
+
|
|
52
|
+
const previous = cues[index - 1]
|
|
53
|
+
if (previous && cue.jp) {
|
|
54
|
+
const gap = timeOf(cue, fragments).start - timeOf(previous, fragments).end
|
|
55
|
+
const sameText = cue.jp === previous.jp && (!zh || !previous.zh || zh === previous.zh)
|
|
56
|
+
if (sameText && gap < sameGap) add('duplicate', cue, '与上一条几乎同时重复')
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return { counts, total: Object.values(counts).reduce((sum, value) => sum + value, 0), items }
|
|
61
|
+
}
|
package/src/resplit.js
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { completeText } from './llm.js'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Split a long cue into several subtitles with the help of the model: it decides
|
|
5
|
+
* where a sentence ends and where a speaker turn happens, while the time is
|
|
6
|
+
* distributed by Japanese text length (a closer proxy for speech duration).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const MAX_ZH = 24
|
|
10
|
+
const MAX_SECONDS = 8
|
|
11
|
+
|
|
12
|
+
const PROMPT = [
|
|
13
|
+
'下面是一条日语视频字幕,内容可能包含多句话、停顿,或两人一来一回的对话。',
|
|
14
|
+
'请按语义和说话人转折把它拆成若干条更适合阅读的字幕:',
|
|
15
|
+
'- 每条 8–20 个汉字,最多 24 个;',
|
|
16
|
+
'- 在说话人切换、问答、语气转折处断开;联系紧密的句子不要拆开;',
|
|
17
|
+
'- 日文与中文按同样的断点切分,不能漏内容,也不要改写;',
|
|
18
|
+
'- 只输出拆分结果,每行 "序号|日文|中文",序号从 1 开始;',
|
|
19
|
+
'- 如果确实无法再分,只输出一行。',
|
|
20
|
+
'',
|
|
21
|
+
'日文:{jp}',
|
|
22
|
+
'中文:{zh}',
|
|
23
|
+
].join('\n')
|
|
24
|
+
|
|
25
|
+
/** Rows worth a model pass: long text or a long on-screen time. */
|
|
26
|
+
export function needsResplit(cue, duration) {
|
|
27
|
+
if (!cue || cue.skip) return false
|
|
28
|
+
return String(cue.zh || '').length > MAX_ZH || duration > MAX_SECONDS
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function buildResplitPrompt(cue) {
|
|
32
|
+
return PROMPT.replace('{jp}', String(cue.jp || '')).replace('{zh}', String(cue.zh || ''))
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Parse "1|日文|中文" lines; returns [] when the reply is unusable. */
|
|
36
|
+
export function parseResplit(text) {
|
|
37
|
+
const rows = []
|
|
38
|
+
for (const raw of String(text || '').split(/\r?\n/)) {
|
|
39
|
+
const match = /^\s*(\d+)\s*\|\s*(.*?)\s*\|\s*(.*)$/.exec(raw.trim())
|
|
40
|
+
if (!match) continue
|
|
41
|
+
const jp = match[2].trim()
|
|
42
|
+
const zh = match[3].trim()
|
|
43
|
+
if (!jp || !zh) continue
|
|
44
|
+
rows.push({ jp, zh })
|
|
45
|
+
}
|
|
46
|
+
return rows
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A split is only accepted when the text is roughly the same length. */
|
|
50
|
+
export function validSplit(rows, cue) {
|
|
51
|
+
if (rows.length < 2) return false
|
|
52
|
+
const join = (rows, key) => rows.map((row) => row[key].replace(/\s+/g, '')).join('')
|
|
53
|
+
const jpBefore = String(cue.jp || '').replace(/\s+/g, '').length
|
|
54
|
+
const zhBefore = String(cue.zh || '').replace(/\s+/g, '').length
|
|
55
|
+
const jpAfter = join(rows, 'jp').length
|
|
56
|
+
const zhAfter = join(rows, 'zh').length
|
|
57
|
+
if (jpBefore > 0 && (jpAfter < jpBefore * 0.85 || jpAfter > jpBefore * 1.2)) return false
|
|
58
|
+
if (zhBefore > 0 && (zhAfter < zhBefore * 0.7 || zhAfter > zhBefore * 1.35)) return false
|
|
59
|
+
return true
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Replace one cue with its pieces, spreading the original span by jp length. */
|
|
63
|
+
export function applyResplit(cues, index, rows, durationOf) {
|
|
64
|
+
const cue = cues[index]
|
|
65
|
+
const start = cue.start !== undefined ? Number(cue.start) : durationOf(cue).start
|
|
66
|
+
const end = cue.end !== undefined ? Number(cue.end) : durationOf(cue).end
|
|
67
|
+
const weights = rows.map((row) => Math.max(1, row.jp.replace(/\s+/g, '').length))
|
|
68
|
+
const total = weights.reduce((sum, value) => sum + value, 0)
|
|
69
|
+
const round = (value) => Number(value.toFixed(3))
|
|
70
|
+
const pieces = []
|
|
71
|
+
let cursor = start
|
|
72
|
+
for (let piece = 0; piece < rows.length; piece += 1) {
|
|
73
|
+
const next = piece === rows.length - 1 ? end : round(cursor + ((end - start) * weights[piece]) / total)
|
|
74
|
+
pieces.push({ from: cue.from, to: cue.to, jp: rows[piece].jp, zh: rows[piece].zh, start: round(cursor), end: next })
|
|
75
|
+
cursor = next
|
|
76
|
+
}
|
|
77
|
+
return [...cues.slice(0, index), ...pieces, ...cues.slice(index + 1)]
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Walk the cues once, asking the model only about lines worth splitting.
|
|
82
|
+
* @returns counts for the job message.
|
|
83
|
+
*/
|
|
84
|
+
export async function resplitAll(ctx, cues, fragments, options = {}) {
|
|
85
|
+
const durationOf = (cue) => {
|
|
86
|
+
if (cue.start !== undefined && cue.end !== undefined) return { start: cue.start, end: cue.end }
|
|
87
|
+
const from = fragments[Number(cue.from) - 1]
|
|
88
|
+
const to = fragments[Number(cue.to) - 1]
|
|
89
|
+
return { start: from.start, end: to.end }
|
|
90
|
+
}
|
|
91
|
+
const score = (cue) => {
|
|
92
|
+
const span = durationOf(cue)
|
|
93
|
+
return needsResplit(cue, span.end - span.start)
|
|
94
|
+
}
|
|
95
|
+
const total = cues.filter(score).length
|
|
96
|
+
const out = []
|
|
97
|
+
let split = 0
|
|
98
|
+
let failed = 0
|
|
99
|
+
let examined = 0
|
|
100
|
+
for (const cue of cues) {
|
|
101
|
+
if (!score(cue)) {
|
|
102
|
+
out.push(cue)
|
|
103
|
+
continue
|
|
104
|
+
}
|
|
105
|
+
examined += 1
|
|
106
|
+
options.onProgress?.(examined, total)
|
|
107
|
+
let raw
|
|
108
|
+
try {
|
|
109
|
+
raw = await completeText(ctx, options.route || { provider: options.provider, model: options.model }, {
|
|
110
|
+
prompt: buildResplitPrompt(cue),
|
|
111
|
+
signal: options.signal,
|
|
112
|
+
maxTokens: 2048,
|
|
113
|
+
})
|
|
114
|
+
} catch {
|
|
115
|
+
failed += 1
|
|
116
|
+
out.push(cue)
|
|
117
|
+
continue
|
|
118
|
+
}
|
|
119
|
+
const rows = parseResplit(raw)
|
|
120
|
+
if (!validSplit(rows, cue)) {
|
|
121
|
+
failed += 1
|
|
122
|
+
out.push(cue)
|
|
123
|
+
continue
|
|
124
|
+
}
|
|
125
|
+
const span = durationOf(cue)
|
|
126
|
+
const pieces = (() => {
|
|
127
|
+
const weights = rows.map((row) => Math.max(1, row.jp.replace(/\s+/g, '').length))
|
|
128
|
+
const sum = weights.reduce((value, item) => value + item, 0)
|
|
129
|
+
const round = (value) => Number(value.toFixed(3))
|
|
130
|
+
const list = []
|
|
131
|
+
let cursor = span.start
|
|
132
|
+
for (let index = 0; index < rows.length; index += 1) {
|
|
133
|
+
const next = index === rows.length - 1 ? span.end : round(cursor + ((span.end - span.start) * weights[index]) / sum)
|
|
134
|
+
list.push({ from: cue.from, to: cue.to, jp: rows[index].jp, zh: rows[index].zh, start: round(cursor), end: next })
|
|
135
|
+
cursor = next
|
|
136
|
+
}
|
|
137
|
+
return list
|
|
138
|
+
})()
|
|
139
|
+
out.push(...pieces)
|
|
140
|
+
split += rows.length - 1
|
|
141
|
+
}
|
|
142
|
+
return { cues: out, split, failed, examined }
|
|
143
|
+
}
|
package/src/review.js
CHANGED
|
@@ -97,6 +97,25 @@ export function renderBatch(batch, fragments, cues, glossary, hints) {
|
|
|
97
97
|
return lines.join('\n')
|
|
98
98
|
}
|
|
99
99
|
|
|
100
|
+
/**
|
|
101
|
+
* Keep only the lines that look like batch rows, so a model that wraps its answer
|
|
102
|
+
* in prose or a numbered list still lands. Returns '' when nothing matches.
|
|
103
|
+
* @param text - raw model output.
|
|
104
|
+
* @returns the salvaged row text, one row per line.
|
|
105
|
+
*/
|
|
106
|
+
export function salvageLines(text) {
|
|
107
|
+
const kept = []
|
|
108
|
+
for (const raw of String(text || '').split(/\r?\n/)) {
|
|
109
|
+
let line = raw.trim()
|
|
110
|
+
if (!line) continue
|
|
111
|
+
line = line.replace(/^[-*•]\s+/, '').replace(/^\d+[.)]\s+(?=\d)/, '')
|
|
112
|
+
line = line.replace(/^(\d+(?:\s*-\s*\d+)?)\s*\|\s*/, '$1|')
|
|
113
|
+
line = line.replace(/\s*\|\s*/g, '|')
|
|
114
|
+
if (BATCH_LINE.test(line)) kept.push(line)
|
|
115
|
+
}
|
|
116
|
+
return kept.join('\n')
|
|
117
|
+
}
|
|
118
|
+
|
|
100
119
|
export function parseLines(text) {
|
|
101
120
|
const rows = []
|
|
102
121
|
const errors = []
|
|
@@ -120,7 +139,8 @@ export function parseLines(text) {
|
|
|
120
139
|
const separator = rest.indexOf('|')
|
|
121
140
|
const jp = (separator >= 0 ? rest.slice(0, separator) : rest).trim()
|
|
122
141
|
const zh = separator >= 0 ? rest.slice(separator + 1).trim() : ''
|
|
123
|
-
|
|
142
|
+
// Models sometimes put the marker in the Chinese column; treat it the same.
|
|
143
|
+
if (jp === '<skip>' || jp.toLowerCase() === '<skip>' || zh === '<skip>' || zh.toLowerCase() === '<skip>') {
|
|
124
144
|
rows.push({ from, to, jp: '', zh: '', skip: true, line: position + 1 })
|
|
125
145
|
return
|
|
126
146
|
}
|
|
@@ -227,10 +247,13 @@ export function applyBatch(projectDir, options = {}) {
|
|
|
227
247
|
}
|
|
228
248
|
|
|
229
249
|
const merged = mergeCues(cues, rows, batch)
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
250
|
+
// A dry run only checks the batch's own rows; the real write happens later in
|
|
251
|
+
// batch order, so a temporary gap from a parallel translation is fine here.
|
|
252
|
+
if (!options.dryRun) {
|
|
253
|
+
const coverage = validateCues(merged, fragments.length, { requireFull: false })
|
|
254
|
+
if (!coverage.ok) throw new Error('字幕内容不连续:' + describeCoverageErrors(coverage.errors).slice(0, 5).join(';'))
|
|
255
|
+
writeAtomic(cuesPath, merged)
|
|
256
|
+
}
|
|
234
257
|
return {
|
|
235
258
|
batch: batch.id,
|
|
236
259
|
cues: rows.length,
|