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/README.en.md +52 -5
- package/README.ja.md +34 -3
- package/README.ko.md +34 -3
- package/README.md +33 -3
- package/client.js +812 -29
- package/docs/DETAIL.md +1 -1
- package/docs/PLAN.md +3 -3
- package/docs/REVIEW.md +105 -0
- package/index.js +191 -5
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +4 -2
- package/scripts/check-client.mjs +17 -0
- package/src/api.js +394 -21
- package/src/cues.js +28 -4
- package/src/feedback.js +59 -0
- package/src/glossary.js +252 -0
- package/src/hints.js +32 -0
- package/src/jobs.js +18 -0
- package/src/llm.js +177 -0
- package/src/messages.js +19 -0
- package/src/paths.js +11 -0
- package/src/recent.js +34 -0
- package/src/review.js +317 -0
- package/src/runtime.js +30 -8
package/src/feedback.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* feedback.json keeps the user's notes for the model:
|
|
6
|
+
*
|
|
7
|
+
* { "version": 1, "items": [{ "batch": "1-60", "range": "12-12", "note": "…" }] }
|
|
8
|
+
*
|
|
9
|
+
* A missing `range` is a batch-wide note. Notes are fed into the next
|
|
10
|
+
* translation prompt for their batch; nothing here calls a model.
|
|
11
|
+
*/
|
|
12
|
+
export function feedbackPath(projectDir) {
|
|
13
|
+
return join(projectDir, 'feedback.json')
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function loadFeedback(projectDir) {
|
|
17
|
+
const path = feedbackPath(projectDir)
|
|
18
|
+
if (!existsSync(path)) return { path, items: [] }
|
|
19
|
+
try {
|
|
20
|
+
const data = JSON.parse(readFileSync(path, 'utf8'))
|
|
21
|
+
const items = Array.isArray(data.items) ? data.items : []
|
|
22
|
+
return {
|
|
23
|
+
path,
|
|
24
|
+
items: items.filter((item) => item && typeof item.note === 'string' && item.note.trim() && item.batch),
|
|
25
|
+
}
|
|
26
|
+
} catch {
|
|
27
|
+
return { path, items: [] }
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Add or replace one note; the same batch+range keeps a single latest note. */
|
|
32
|
+
export function saveFeedback(projectDir, { batch, range, note }) {
|
|
33
|
+
const { items } = loadFeedback(projectDir)
|
|
34
|
+
const target = items.findIndex((item) => item.batch === batch && (item.range || '') === (range || ''))
|
|
35
|
+
const entry = { batch, range: range || '', note: String(note).trim(), at: new Date().toISOString() }
|
|
36
|
+
if (target >= 0) items[target] = entry
|
|
37
|
+
else items.push(entry)
|
|
38
|
+
writeFileSync(feedbackPath(projectDir), JSON.stringify({ version: 1, items }, null, 2) + '\n', 'utf8')
|
|
39
|
+
return entry
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function clearFeedback(projectDir, filter = {}) {
|
|
43
|
+
const { items } = loadFeedback(projectDir)
|
|
44
|
+
const kept = items.filter((item) => {
|
|
45
|
+
if (filter.batch && item.batch !== filter.batch) return true
|
|
46
|
+
if (filter.range && (item.range || '') !== filter.range) return true
|
|
47
|
+
return false
|
|
48
|
+
})
|
|
49
|
+
writeFileSync(feedbackPath(projectDir), JSON.stringify({ version: 1, items: kept }, null, 2) + '\n', 'utf8')
|
|
50
|
+
return items.length - kept.length
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Notes that apply to one batch, in a form the prompt can quote. */
|
|
54
|
+
export function feedbackForBatch(projectDir, batch) {
|
|
55
|
+
const { items } = loadFeedback(projectDir)
|
|
56
|
+
return items
|
|
57
|
+
.filter((item) => item.batch === batch)
|
|
58
|
+
.map((item) => (item.range ? `第 ${item.range} 条:${item.note}` : `整批:${item.note}`))
|
|
59
|
+
}
|
package/src/glossary.js
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* glossary.json sits next to cues.json:
|
|
6
|
+
*
|
|
7
|
+
* {
|
|
8
|
+
* "version": 1,
|
|
9
|
+
* "strict": false,
|
|
10
|
+
* "terms": [{ "jp": "<japanese>", "zh": "<required chinese>", "kind": "name" }],
|
|
11
|
+
* "corrections": [{ "from": "<as heard>", "to": "<correct>", "reason": "ASR mishearing" }]
|
|
12
|
+
* }
|
|
13
|
+
*
|
|
14
|
+
* `terms` constrain the Chinese rendering; `corrections` rewrite the Japanese side
|
|
15
|
+
* before it is stored, so a misheard name never reaches the cue file.
|
|
16
|
+
*/
|
|
17
|
+
export function glossaryPath(projectDir) {
|
|
18
|
+
return join(projectDir, 'glossary.json')
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const isText = (value) => typeof value === 'string' && value.trim().length > 0
|
|
22
|
+
|
|
23
|
+
export function loadGlossary(path) {
|
|
24
|
+
const empty = { path, exists: false, strict: false, terms: [], corrections: [], errors: [] }
|
|
25
|
+
if (!path || !existsSync(path)) return empty
|
|
26
|
+
let data
|
|
27
|
+
try {
|
|
28
|
+
data = JSON.parse(readFileSync(path, 'utf8'))
|
|
29
|
+
} catch (error) {
|
|
30
|
+
return { ...empty, exists: true, errors: [`glossary.json is not valid JSON: ${error.message}`] }
|
|
31
|
+
}
|
|
32
|
+
const errors = []
|
|
33
|
+
if (data.version !== 1) errors.push('version must be 1')
|
|
34
|
+
|
|
35
|
+
const terms = []
|
|
36
|
+
for (const [index, term] of (Array.isArray(data.terms) ? data.terms : []).entries()) {
|
|
37
|
+
if (!term || !isText(term.jp) || !isText(term.zh)) {
|
|
38
|
+
errors.push(`terms[${index}] needs non-empty jp and zh`)
|
|
39
|
+
continue
|
|
40
|
+
}
|
|
41
|
+
terms.push({ jp: term.jp.trim(), zh: term.zh.trim(), kind: term.kind || 'term' })
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const corrections = []
|
|
45
|
+
for (const [index, item] of (Array.isArray(data.corrections) ? data.corrections : []).entries()) {
|
|
46
|
+
if (!item || !isText(item.from) || typeof item.to !== 'string') {
|
|
47
|
+
errors.push(`corrections[${index}] needs non-empty from and a to string`)
|
|
48
|
+
continue
|
|
49
|
+
}
|
|
50
|
+
corrections.push({ from: item.from, to: item.to, reason: item.reason || '' })
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
path,
|
|
55
|
+
exists: true,
|
|
56
|
+
strict: data.strict === true,
|
|
57
|
+
terms,
|
|
58
|
+
corrections,
|
|
59
|
+
errors,
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Literal replacements, longest source first so a short rule cannot eat a long one. */
|
|
64
|
+
export function applyCorrections(text, corrections) {
|
|
65
|
+
let output = text
|
|
66
|
+
const hits = []
|
|
67
|
+
const ordered = [...corrections].sort((left, right) => right.from.length - left.from.length)
|
|
68
|
+
for (const rule of ordered) {
|
|
69
|
+
if (!rule.from || !output.includes(rule.from)) continue
|
|
70
|
+
output = output.split(rule.from).join(rule.to)
|
|
71
|
+
hits.push(rule)
|
|
72
|
+
}
|
|
73
|
+
return { text: output, hits }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Terms whose Japanese form appears here; `missing` lists the ones the Chinese lacks. */
|
|
77
|
+
export function checkTerms(jp, zh, terms) {
|
|
78
|
+
const hits = []
|
|
79
|
+
const missing = []
|
|
80
|
+
for (const term of terms) {
|
|
81
|
+
if (!jp.includes(term.jp)) continue
|
|
82
|
+
const required = term.zh.trim()
|
|
83
|
+
const hit = required.length === 0 || zh.includes(required)
|
|
84
|
+
hits.push(term)
|
|
85
|
+
if (!hit) missing.push(term)
|
|
86
|
+
}
|
|
87
|
+
return { hits, missing }
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Every term that appears anywhere in a Japanese block, for the batch header. */
|
|
91
|
+
export function termsInText(text, terms) {
|
|
92
|
+
return terms.filter((term) => text.includes(term.jp))
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// ---------------------------------------------------------------- CSV exchange
|
|
96
|
+
|
|
97
|
+
const CSV_HEADER = 'type,jp,zh,note'
|
|
98
|
+
|
|
99
|
+
function escapeField(value) {
|
|
100
|
+
const text = String(value === undefined || value === null ? '' : value)
|
|
101
|
+
return /[",\r\n]/.test(text) ? '"' + text.replace(/"/g, '""') + '"' : text
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function splitCsvLine(line) {
|
|
105
|
+
const fields = []
|
|
106
|
+
let current = ''
|
|
107
|
+
let quoted = false
|
|
108
|
+
for (let index = 0; index < line.length; index += 1) {
|
|
109
|
+
const character = line[index]
|
|
110
|
+
if (quoted) {
|
|
111
|
+
if (character === '"') {
|
|
112
|
+
if (line[index + 1] === '"') {
|
|
113
|
+
current += '"'
|
|
114
|
+
index += 1
|
|
115
|
+
} else {
|
|
116
|
+
quoted = false
|
|
117
|
+
}
|
|
118
|
+
} else {
|
|
119
|
+
current += character
|
|
120
|
+
}
|
|
121
|
+
continue
|
|
122
|
+
}
|
|
123
|
+
if (character === '"') {
|
|
124
|
+
quoted = true
|
|
125
|
+
continue
|
|
126
|
+
}
|
|
127
|
+
if (character === ',') {
|
|
128
|
+
fields.push(current)
|
|
129
|
+
current = ''
|
|
130
|
+
continue
|
|
131
|
+
}
|
|
132
|
+
current += character
|
|
133
|
+
}
|
|
134
|
+
if (quoted) return { fields: [], error: 'unterminated quote' }
|
|
135
|
+
fields.push(current)
|
|
136
|
+
return { fields, error: '' }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** One portable table so the glossary can live in a spreadsheet. */
|
|
140
|
+
export function toCsv(glossary) {
|
|
141
|
+
const lines = [CSV_HEADER]
|
|
142
|
+
for (const term of glossary.terms) lines.push(['term', term.jp, term.zh, term.kind || ''].map(escapeField).join(','))
|
|
143
|
+
for (const rule of glossary.corrections) {
|
|
144
|
+
lines.push(['correction', rule.from, rule.to, rule.reason || ''].map(escapeField).join(','))
|
|
145
|
+
}
|
|
146
|
+
return '\uFEFF' + lines.join('\r\n') + '\r\n'
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function fromCsv(text) {
|
|
150
|
+
const body = String(text || '').replace(/^\uFEFF/, '')
|
|
151
|
+
const terms = []
|
|
152
|
+
const corrections = []
|
|
153
|
+
const errors = []
|
|
154
|
+
body.split(/\r?\n/).forEach((raw, position) => {
|
|
155
|
+
const line = raw.trim()
|
|
156
|
+
if (!line || line.startsWith('#')) return
|
|
157
|
+
const parsed = splitCsvLine(line)
|
|
158
|
+
if (parsed.error) {
|
|
159
|
+
errors.push(`line ${position + 1}: ${parsed.error}`)
|
|
160
|
+
return
|
|
161
|
+
}
|
|
162
|
+
const fields = parsed.fields
|
|
163
|
+
const type = (fields[0] || '').trim().toLowerCase()
|
|
164
|
+
if (type === 'type') return
|
|
165
|
+
const jp = (fields[1] || '').trim()
|
|
166
|
+
const zh = (fields[2] || '').trim()
|
|
167
|
+
const note = (fields[3] || '').trim()
|
|
168
|
+
if (type === 'term') {
|
|
169
|
+
if (!jp || !zh) {
|
|
170
|
+
errors.push(`line ${position + 1}: a term needs jp and zh`)
|
|
171
|
+
return
|
|
172
|
+
}
|
|
173
|
+
terms.push({ jp, zh, kind: note || 'term' })
|
|
174
|
+
return
|
|
175
|
+
}
|
|
176
|
+
if (type === 'correction') {
|
|
177
|
+
if (!jp) {
|
|
178
|
+
errors.push(`line ${position + 1}: a correction needs the source text`)
|
|
179
|
+
return
|
|
180
|
+
}
|
|
181
|
+
corrections.push({ from: jp, to: zh, reason: note })
|
|
182
|
+
return
|
|
183
|
+
}
|
|
184
|
+
errors.push(`line ${position + 1}: unknown type "${type}" (use term or correction)`)
|
|
185
|
+
})
|
|
186
|
+
return { terms, corrections, errors }
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Merge an imported table into a glossary, reporting what actually changed. */
|
|
190
|
+
export function mergeGlossary(existing, incoming, options = {}) {
|
|
191
|
+
const merge = options.merge !== false
|
|
192
|
+
const terms = merge ? [...existing.terms] : []
|
|
193
|
+
const corrections = merge ? [...existing.corrections] : []
|
|
194
|
+
const termIndex = new Map(terms.map((term) => [term.jp, term]))
|
|
195
|
+
const correctionIndex = new Map(corrections.map((rule) => [rule.from, rule]))
|
|
196
|
+
|
|
197
|
+
let added = 0
|
|
198
|
+
let updated = 0
|
|
199
|
+
for (const term of incoming.terms) {
|
|
200
|
+
const current = termIndex.get(term.jp)
|
|
201
|
+
if (!current) {
|
|
202
|
+
terms.push(term)
|
|
203
|
+
termIndex.set(term.jp, term)
|
|
204
|
+
added += 1
|
|
205
|
+
continue
|
|
206
|
+
}
|
|
207
|
+
if (current.zh !== term.zh || (current.kind || '') !== (term.kind || '')) {
|
|
208
|
+
current.zh = term.zh
|
|
209
|
+
current.kind = term.kind
|
|
210
|
+
updated += 1
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
for (const rule of incoming.corrections) {
|
|
214
|
+
const current = correctionIndex.get(rule.from)
|
|
215
|
+
if (!current) {
|
|
216
|
+
corrections.push(rule)
|
|
217
|
+
correctionIndex.set(rule.from, rule)
|
|
218
|
+
added += 1
|
|
219
|
+
continue
|
|
220
|
+
}
|
|
221
|
+
if (current.to !== rule.to || (current.reason || '') !== (rule.reason || '')) {
|
|
222
|
+
current.to = rule.to
|
|
223
|
+
current.reason = rule.reason
|
|
224
|
+
updated += 1
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return {
|
|
229
|
+
glossary: { version: 1, strict: existing.strict, terms, corrections },
|
|
230
|
+
summary: { added, updated, merged: merge, total: terms.length + corrections.length },
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export function saveGlossary(path, glossary) {
|
|
235
|
+
const payload = { version: 1, strict: glossary.strict === true, terms: glossary.terms, corrections: glossary.corrections }
|
|
236
|
+
writeFileSync(path, JSON.stringify(payload, null, 2) + '\n', 'utf8')
|
|
237
|
+
return payload
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** Read a glossary table from an HTTP(S) URL, for a document kept online. */
|
|
241
|
+
export async function fetchGlossaryText(url, options = {}) {
|
|
242
|
+
const timeoutMs = options.timeoutMs || 15000
|
|
243
|
+
const response = await fetch(url, {
|
|
244
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
245
|
+
headers: { 'user-agent': 'dsh-ai-subtitle', accept: 'text/csv, text/plain, */*' },
|
|
246
|
+
})
|
|
247
|
+
if (!response.ok) throw new Error(`HTTP ${response.status} while fetching ${url}`)
|
|
248
|
+
const text = await response.text()
|
|
249
|
+
if (text.length > 1024 * 1024) throw new Error('the glossary document is larger than 1 MB')
|
|
250
|
+
return text
|
|
251
|
+
}
|
|
252
|
+
|
package/src/hints.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* hints.json carries the user's context for the translator:
|
|
6
|
+
* { "tags": ["声优节目", "广播"], "note": "称呼口语化,第三人称用「她」" } // cjk-ok: data sample
|
|
7
|
+
* Tags and note are injected into every translation prompt for the project.
|
|
8
|
+
*/
|
|
9
|
+
export function hintsPath(projectDir) {
|
|
10
|
+
return join(projectDir, 'hints.json')
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function loadHints(projectDir) {
|
|
14
|
+
try {
|
|
15
|
+
const data = JSON.parse(readFileSync(hintsPath(projectDir), 'utf8'))
|
|
16
|
+
const tags = Array.isArray(data.tags) ? data.tags.filter((tag) => typeof tag === 'string' && tag.trim()) : []
|
|
17
|
+
const note = typeof data.note === 'string' ? data.note : ''
|
|
18
|
+
return { tags: tags.slice(0, 20), note }
|
|
19
|
+
} catch {
|
|
20
|
+
return { tags: [], note: '' }
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function saveHints(projectDir, { tags, note }) {
|
|
25
|
+
const parsed = (Array.isArray(tags) ? tags : []).map((tag) => String(tag).trim()).filter(Boolean)
|
|
26
|
+
const clean = {
|
|
27
|
+
tags: [...new Set(parsed)].slice(0, 20),
|
|
28
|
+
note: String(note || '').trim(),
|
|
29
|
+
}
|
|
30
|
+
writeFileSync(hintsPath(projectDir), JSON.stringify(clean, null, 2) + '\n', 'utf8')
|
|
31
|
+
return clean
|
|
32
|
+
}
|
package/src/jobs.js
CHANGED
|
@@ -66,6 +66,24 @@ export function cancelJob(id, reason = '已取消') {
|
|
|
66
66
|
return true
|
|
67
67
|
}
|
|
68
68
|
|
|
69
|
+
export function removeJob(id) {
|
|
70
|
+
const job = jobs.get(id)
|
|
71
|
+
if (!job || job.status === 'running') return false
|
|
72
|
+
jobs.delete(id)
|
|
73
|
+
return true
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function removeFinishedJobs() {
|
|
77
|
+
let removed = 0
|
|
78
|
+
for (const [id, job] of jobs) {
|
|
79
|
+
if (job.status !== 'running') {
|
|
80
|
+
jobs.delete(id)
|
|
81
|
+
removed += 1
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return removed
|
|
85
|
+
}
|
|
86
|
+
|
|
69
87
|
export function getJob(id) {
|
|
70
88
|
return jobs.get(id)
|
|
71
89
|
}
|
package/src/llm.js
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { feedbackForBatch } from './feedback.js'
|
|
4
|
+
import { loadHints } from './hints.js'
|
|
5
|
+
import { glossaryPath, loadGlossary, termsInText } from './glossary.js'
|
|
6
|
+
import { applyBatch, loadProject, nextBatch, planBatches, renderBatch } from './review.js'
|
|
7
|
+
|
|
8
|
+
const SYSTEM_PROMPT = [
|
|
9
|
+
'你是专业的日语视频字幕翻译,把日文逐条翻译成简体中文。',
|
|
10
|
+
'输入每行格式为 "from-to|日文",输出必须保持完全相同的行数和 from-to 编号,格式为 "from-to|日文|中文"。',
|
|
11
|
+
'规则:',
|
|
12
|
+
'1. 只输出这些行,不要编号说明、不要解释、不要 Markdown 代码块。',
|
|
13
|
+
'2. 中文简洁口语化,一条字幕通常不超过 30 个汉字。',
|
|
14
|
+
'3. 标记为 <skip> 的行原样输出 "from-to|<skip>"。',
|
|
15
|
+
'4. 术语表给出的译法必须优先使用。',
|
|
16
|
+
'5. 用户的意见优先于你自己的判断,按意见修改对应条目。',
|
|
17
|
+
].join('\n')
|
|
18
|
+
|
|
19
|
+
export function routeFile(projectDir) {
|
|
20
|
+
return join(projectDir, 'translate.json')
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function readSavedRoute(projectDir) {
|
|
24
|
+
try {
|
|
25
|
+
const data = JSON.parse(readFileSync(routeFile(projectDir), 'utf8'))
|
|
26
|
+
if (data && data.provider && data.model) return { provider: data.provider, model: data.model }
|
|
27
|
+
} catch {
|
|
28
|
+
// no saved route yet
|
|
29
|
+
}
|
|
30
|
+
return null
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function saveRoute(projectDir, route) {
|
|
34
|
+
writeFileSync(
|
|
35
|
+
routeFile(projectDir),
|
|
36
|
+
JSON.stringify({ provider: route.provider, model: route.model, at: new Date().toISOString() }, null, 2) + '\n',
|
|
37
|
+
'utf8',
|
|
38
|
+
)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The account-backed route works without an API key, so prefer it over a keyed one. */
|
|
42
|
+
function preferredProvider(providers) {
|
|
43
|
+
const account = providers.find((item) => /account/i.test(item.id) || /account/i.test(item.name || ''))
|
|
44
|
+
return account || providers[0]
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Pick the provider/model the user is already signed in to, unless one is named. */
|
|
48
|
+
export async function resolveRoute(ctx, options = {}) {
|
|
49
|
+
if (!ctx || !ctx.llm || typeof ctx.llm.listProviders !== 'function') {
|
|
50
|
+
throw new Error('这个环境没有可用的模型服务(ctx.llm)')
|
|
51
|
+
}
|
|
52
|
+
const providers = ctx.llm.listProviders()
|
|
53
|
+
if (!Array.isArray(providers) || providers.length === 0) {
|
|
54
|
+
throw new Error('没有已登录的模型提供方,请先在 DSH 设置里配置模型')
|
|
55
|
+
}
|
|
56
|
+
const saved = options.projectDir ? readSavedRoute(options.projectDir) : null
|
|
57
|
+
const provider = options.provider || (saved && providers.some((item) => item.id === saved.provider) ? saved.provider : preferredProvider(providers).id)
|
|
58
|
+
if (!providers.some((item) => item.id === provider)) {
|
|
59
|
+
throw new Error(`未知的模型提供方 ${provider},可用:${providers.map((item) => item.id).join(', ')}`)
|
|
60
|
+
}
|
|
61
|
+
const models = await ctx.llm.listModels(provider)
|
|
62
|
+
if (!Array.isArray(models) || models.length === 0) {
|
|
63
|
+
throw new Error(`提供方 ${provider} 没有列出可用模型`)
|
|
64
|
+
}
|
|
65
|
+
const savedModel = saved && saved.provider === provider && models.some((item) => item.id === saved.model) ? saved.model : null
|
|
66
|
+
const model = options.model || savedModel || models[0].id
|
|
67
|
+
return { provider, model }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** One non-streaming-for-consumers call: collect the text of a single prompt. */
|
|
71
|
+
export async function completeText(ctx, route, request = {}) {
|
|
72
|
+
const controller = new AbortController()
|
|
73
|
+
const timer = setTimeout(() => controller.abort(new Error('模型调用超时')), request.timeoutMs || 180000)
|
|
74
|
+
const signal = request.signal
|
|
75
|
+
? AbortSignal.any([request.signal, controller.signal])
|
|
76
|
+
: controller.signal
|
|
77
|
+
let text = ''
|
|
78
|
+
let finish
|
|
79
|
+
try {
|
|
80
|
+
const stream = ctx.llm.stream({
|
|
81
|
+
provider: route.provider,
|
|
82
|
+
model: route.model,
|
|
83
|
+
system: SYSTEM_PROMPT,
|
|
84
|
+
messages: [{ role: 'user', content: [{ type: 'text', text: request.prompt }] }],
|
|
85
|
+
temperature: 0.2,
|
|
86
|
+
maxTokens: request.maxTokens || 8192,
|
|
87
|
+
signal,
|
|
88
|
+
})
|
|
89
|
+
for await (const chunk of stream) {
|
|
90
|
+
if (chunk.type === 'text-delta') text += chunk.text
|
|
91
|
+
else if (chunk.type === 'finish') finish = chunk.reason
|
|
92
|
+
}
|
|
93
|
+
} finally {
|
|
94
|
+
clearTimeout(timer)
|
|
95
|
+
}
|
|
96
|
+
if (finish && finish.kind === 'error') {
|
|
97
|
+
throw new Error('模型返回错误:' + (finish.failure && finish.failure.message ? finish.failure.message : 'unknown'))
|
|
98
|
+
}
|
|
99
|
+
if (finish && finish.kind === 'aborted') throw new Error('模型调用已取消')
|
|
100
|
+
return text.trim()
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The prompt for one batch: glossary, feedback, and the lines to translate. */
|
|
104
|
+
export function buildPrompt(projectDir, batch, fragments, cues, glossary, feedback, hints, mode = 'translate') {
|
|
105
|
+
const context = hints || loadHints(projectDir)
|
|
106
|
+
const block = renderBatch(batch, fragments, cues, glossary)
|
|
107
|
+
const jpText = fragments.slice(batch.from - 1, batch.to).map((item) => item.text).join('')
|
|
108
|
+
const terms = termsInText(jpText, glossary.terms)
|
|
109
|
+
const lines = []
|
|
110
|
+
if (context.tags.length > 0 || context.note) {
|
|
111
|
+
lines.push('视频背景(翻译与校对时保持这个方向):')
|
|
112
|
+
if (context.tags.length > 0) lines.push('- 标签:' + context.tags.join('、'))
|
|
113
|
+
if (context.note) lines.push('- 说明:' + context.note)
|
|
114
|
+
lines.push('')
|
|
115
|
+
}
|
|
116
|
+
lines.push('术语表(必须遵守):')
|
|
117
|
+
if (terms.length === 0) lines.push('- 本批没有命中术语')
|
|
118
|
+
for (const term of terms) lines.push(`- ${term.jp} → ${term.zh}`)
|
|
119
|
+
if (feedback.length > 0) {
|
|
120
|
+
lines.push('', '用户意见(优先处理):')
|
|
121
|
+
for (const note of feedback) lines.push(`- ${note}`)
|
|
122
|
+
}
|
|
123
|
+
if (mode === 'proofread') {
|
|
124
|
+
lines.push('')
|
|
125
|
+
lines.push('另外:先校正日文的识别错误再翻译。')
|
|
126
|
+
lines.push('- 修正同音字、漏字、重复、断句错误,保留说话人的语气、口癖和停顿感。')
|
|
127
|
+
lines.push('- 不要改写措辞,不要补出没说过的内容;没有把握的地方保持原样。')
|
|
128
|
+
lines.push('- 输出的 jp 必须是校正后的日文。')
|
|
129
|
+
}
|
|
130
|
+
lines.push('', '待翻译:', block)
|
|
131
|
+
return lines.join('\n')
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function stripFence(text) {
|
|
135
|
+
return text
|
|
136
|
+
.replace(/^```[a-z]*\s*/i, '')
|
|
137
|
+
.replace(/\s*```$/, '')
|
|
138
|
+
.trim()
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Translate one batch through the session's model and write the result back.
|
|
143
|
+
* Returns the same summary shape as applyBatch plus the route used.
|
|
144
|
+
*/
|
|
145
|
+
export async function translateBatch(ctx, projectDir, options = {}) {
|
|
146
|
+
const { cues, fragments } = loadProject(projectDir)
|
|
147
|
+
const glossary = loadGlossary(options.glossary || glossaryPath(projectDir))
|
|
148
|
+
const batches = planBatches(fragments, cues)
|
|
149
|
+
const batch = options.batch
|
|
150
|
+
? batches.find((item) => item.id === options.batch)
|
|
151
|
+
: nextBatch(batches, cues)
|
|
152
|
+
if (!batch) return { done: true, message: '所有批次都已翻译' }
|
|
153
|
+
|
|
154
|
+
const feedback = feedbackForBatch(projectDir, batch.id)
|
|
155
|
+
const route = options.route || (await resolveRoute(ctx, { ...options, projectDir }))
|
|
156
|
+
const prompt = buildPrompt(projectDir, batch, fragments, cues, glossary, feedback, undefined, options.mode)
|
|
157
|
+
const raw = await completeText(ctx, route, { prompt, signal: options.signal })
|
|
158
|
+
const lines = stripFence(raw)
|
|
159
|
+
const applied = applyBatch(projectDir, { batch: batch.id, lines })
|
|
160
|
+
saveRoute(projectDir, route)
|
|
161
|
+
return { ...applied, route: `${route.provider}/${route.model}`, feedback: feedback.length }
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Translate every remaining batch, reporting progress after each one. */
|
|
165
|
+
export async function translateRemaining(ctx, projectDir, options = {}) {
|
|
166
|
+
const route = options.route || (await resolveRoute(ctx, { ...options, projectDir }))
|
|
167
|
+
const done = []
|
|
168
|
+
for (;;) {
|
|
169
|
+
if (options.signal && options.signal.aborted) throw new Error('已取消')
|
|
170
|
+
const result = await translateBatch(ctx, projectDir, { ...options, route })
|
|
171
|
+
if (result.done) break
|
|
172
|
+
done.push(result.batch)
|
|
173
|
+
if (options.onProgress) options.onProgress(done.length, result.batch)
|
|
174
|
+
if (options.limit && done.length >= options.limit) break
|
|
175
|
+
}
|
|
176
|
+
return { batches: done, route: `${route.provider}/${route.model}` }
|
|
177
|
+
}
|
package/src/messages.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Worker progress strings are English; the panel shows them verbatim. */
|
|
2
|
+
export function transcribeMessage(message) {
|
|
3
|
+
const text = String(message || '').trim()
|
|
4
|
+
if (!text) return ''
|
|
5
|
+
let match = text.match(/^loading (.+)$/)
|
|
6
|
+
if (match) return `加载模型 ${match[1]}`
|
|
7
|
+
match = text.match(/^(\d+) speech regions$/)
|
|
8
|
+
if (match) return `共 ${match[1]} 段语音`
|
|
9
|
+
match = text.match(/^region (\d+)\/(\d+)$/)
|
|
10
|
+
if (match) return `已识别 ${match[1]}/${match[2]} 段`
|
|
11
|
+
match = text.match(/^fragments=(\d+)$/)
|
|
12
|
+
if (match) return `共 ${match[1]} 条`
|
|
13
|
+
if (text === 'done') return '完成'
|
|
14
|
+
if (text === 'reading duration') return '读取时长'
|
|
15
|
+
if (text === 'extracting 16 kHz mono wav') return '提取音频'
|
|
16
|
+
if (text === 'loading model') return '加载模型'
|
|
17
|
+
if (text === 'reading fragments') return '整理识别结果'
|
|
18
|
+
return text
|
|
19
|
+
}
|
package/src/paths.js
CHANGED
|
@@ -32,6 +32,17 @@ export function writePointer(root) {
|
|
|
32
32
|
}
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
+
/** Projects default to the user's Documents folder so they are easy to find and back up. */
|
|
36
|
+
export function defaultProjectsDir() {
|
|
37
|
+
let documents = ''
|
|
38
|
+
try {
|
|
39
|
+
documents = join(homedir(), 'Documents')
|
|
40
|
+
} catch {
|
|
41
|
+
documents = ''
|
|
42
|
+
}
|
|
43
|
+
return join(documents || homedir(), 'DshSubtitle', 'projects')
|
|
44
|
+
}
|
|
45
|
+
|
|
35
46
|
export function layout(root) {
|
|
36
47
|
const bin = join(root, 'bin')
|
|
37
48
|
const venv = join(root, 'venv')
|
package/src/recent.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs'
|
|
2
|
+
import { dirname } from 'node:path'
|
|
3
|
+
|
|
4
|
+
import { readState, writeState } from './paths.js'
|
|
5
|
+
|
|
6
|
+
/** Recent media paths the user actually transcribed, newest first. */
|
|
7
|
+
export function recentMedia(runtime, limit = 12) {
|
|
8
|
+
const state = readState(runtime.L)
|
|
9
|
+
const list = Array.isArray(state.recentMedia) ? state.recentMedia : []
|
|
10
|
+
return list.filter((item) => typeof item === 'string' && item && existsSync(item)).slice(0, limit)
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function rememberMedia(runtime, media) {
|
|
14
|
+
const state = readState(runtime.L)
|
|
15
|
+
const list = (Array.isArray(state.recentMedia) ? state.recentMedia : []).filter((item) => item !== media)
|
|
16
|
+
list.unshift(media)
|
|
17
|
+
writeState(runtime.L, { recentMedia: list.slice(0, 12) })
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Folders worth jumping to: the parents of recent media plus the projects folder. */
|
|
21
|
+
export function recentDirs(runtime, limit = 10) {
|
|
22
|
+
const dirs = []
|
|
23
|
+
const seen = new Set()
|
|
24
|
+
for (const file of recentMedia(runtime, 40)) {
|
|
25
|
+
const dir = dirname(file)
|
|
26
|
+
if (!seen.has(dir) && existsSync(dir)) {
|
|
27
|
+
seen.add(dir)
|
|
28
|
+
dirs.push(dir)
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const projects = runtime.projectRoot
|
|
32
|
+
if (projects && !seen.has(projects) && existsSync(projects)) dirs.push(projects)
|
|
33
|
+
return dirs.slice(0, limit)
|
|
34
|
+
}
|