dsh-podwave 0.11.27 → 0.11.29

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-podwave",
3
- "version": "0.11.27",
3
+ "version": "0.11.29",
4
4
  "description": "DeepSeek Harness 插件:本地优先的播客播放器 + 转写 + 双语字幕 + 字幕翻译。",
5
5
  "type": "module",
6
6
  "main": "./src/host.js",
@@ -0,0 +1,114 @@
1
+ #!/usr/bin/env python3
2
+ """常驻说话人声纹服务:给每行字幕算一个声纹向量,供在线聚类用。
3
+
4
+ 模型加载一次要一两秒,而实时跟播时每 12 秒就会来好几行,
5
+ 所以这里做成常驻进程:父进程按行写 JSON 请求,这里按行回 JSON。
6
+
7
+ 请求:{"id": 1, "audio": "/path/part.wav", "start": 1.23, "end": 4.56}
8
+ 响应:{"id": 1, "embedding": [...]} 或 {"id": 1, "error": "..."}
9
+
10
+ start/end 是「相对该音频文件」的秒数;音频必须是 16kHz 单声道 16bit PCM WAV
11
+ (transcribe.js 切出来的块就是这个格式,所以不用重新解码,直接用 numpy 切片)。
12
+ """
13
+ import json
14
+ import os
15
+ import sys
16
+ import wave
17
+
18
+ import numpy as np
19
+
20
+ SAMPLE_RATE = 16000
21
+ MIN_SECONDS = 0.35 # 太短的片段算不出稳定声纹,直接让调用方回退
22
+ MIN_SAMPLES = int(SAMPLE_RATE * MIN_SECONDS)
23
+
24
+
25
+ def read_samples(path):
26
+ with wave.open(path, 'rb') as handle:
27
+ rate = handle.getframerate()
28
+ channels = handle.getnchannels()
29
+ width = handle.getsampwidth()
30
+ frames = handle.readframes(handle.getnframes())
31
+ if width != 2:
32
+ raise RuntimeError(f'只支持 16-bit PCM,收到 {width * 8}-bit')
33
+ if rate != SAMPLE_RATE:
34
+ raise RuntimeError(f'只支持 {SAMPLE_RATE}Hz,收到 {rate}Hz')
35
+ data = np.frombuffer(frames, dtype=np.int16).astype(np.float32) / 32768.0
36
+ if channels > 1:
37
+ data = data.reshape(-1, channels).mean(axis=1)
38
+ return data
39
+
40
+
41
+ class Server:
42
+ def __init__(self, model):
43
+ import sherpa_onnx
44
+
45
+ config = sherpa_onnx.SpeakerEmbeddingExtractorConfig(model=model, num_threads=1)
46
+ self.extractor = sherpa_onnx.SpeakerEmbeddingExtractor(config)
47
+ self.cached_path = None
48
+ self.cached = None
49
+
50
+ def samples(self, path):
51
+ if self.cached_path != path or self.cached is None:
52
+ self.cached = read_samples(path)
53
+ self.cached_path = path
54
+ return self.cached
55
+
56
+ def embed(self, path, start, end):
57
+ data = self.samples(path)
58
+ begin = max(0, int(round(float(start) * SAMPLE_RATE)))
59
+ finish = min(len(data), int(round(float(end) * SAMPLE_RATE)))
60
+ if finish - begin < MIN_SAMPLES:
61
+ return None
62
+ chunk = data[begin:finish]
63
+ stream = self.extractor.create_stream()
64
+ stream.accept_waveform(SAMPLE_RATE, chunk)
65
+ stream.input_finished()
66
+ if not self.extractor.is_ready(stream):
67
+ return None
68
+ return [float(value) for value in self.extractor.compute(stream)]
69
+
70
+
71
+ def main():
72
+ model = None
73
+ args = sys.argv[1:]
74
+ for index, item in enumerate(args):
75
+ if item == '--model' and index + 1 < len(args):
76
+ model = args[index + 1]
77
+ if not model or not os.path.exists(model):
78
+ print(json.dumps({'error': f'找不到声纹模型:{model}'}), flush=True)
79
+ return 2
80
+
81
+ try:
82
+ server = Server(model)
83
+ except Exception as error: # noqa: BLE001 - 起不来就明确告诉父进程
84
+ print(json.dumps({'error': f'声纹模型加载失败:{error}'}), flush=True)
85
+ return 2
86
+
87
+ # 模型加载完先打个招呼,父进程据此认为「服务就绪」。
88
+ print(json.dumps({'ready': True, 'dim': int(server.extractor.dim)}), flush=True)
89
+
90
+ for line in sys.stdin:
91
+ line = line.strip()
92
+ if not line:
93
+ continue
94
+ try:
95
+ request = json.loads(line)
96
+ except Exception: # noqa: BLE001 - 坏行直接跳过,不要拖垮常驻进程
97
+ continue
98
+ request_id = request.get('id')
99
+ try:
100
+ embedding = server.embed(
101
+ request.get('audio', ''),
102
+ request.get('start', 0),
103
+ request.get('end', 0),
104
+ )
105
+ if embedding is None:
106
+ print(json.dumps({'id': request_id, 'embedding': None}), flush=True)
107
+ else:
108
+ print(json.dumps({'id': request_id, 'embedding': embedding}), flush=True)
109
+ except Exception as error: # noqa: BLE001 - 单次失败不影响后续请求
110
+ print(json.dumps({'id': request_id, 'error': str(error)}), flush=True)
111
+
112
+
113
+ if __name__ == '__main__':
114
+ sys.exit(main())
@@ -1,5 +1,10 @@
1
1
  #!/usr/bin/env python3
2
- """本地字幕翻译:读取 JSON 任务,用 MLX 模型逐批翻译,结果以 JSON 写到 stdout。"""
2
+ """本地字幕翻译:读取 JSON 任务,用 MLX 模型逐批翻译,结果以 JSON 写到 stdout。
3
+
4
+ 小模型遇到很短的句子会自作主张把几行并成一行,编号就整体后移,
5
+ 下游按编号取译文时就会整批错位。所以这里校验「读回来的行数 == 送进去的行数」,
6
+ 对不上就降批重试(对半 → 最后一行一行翻),保证一行对一行。
7
+ """
3
8
  import json
4
9
  import re
5
10
  import sys
@@ -7,6 +12,56 @@ import sys
7
12
  from mlx_lm import generate, load
8
13
 
9
14
 
15
+ BATCH_SIZE = 15
16
+ MAX_TOKENS = 1024
17
+
18
+
19
+ def parse_numbered(output: str, count: int) -> dict:
20
+ parsed = {}
21
+ for line in output.splitlines():
22
+ match = re.match(r"^\s*(\d+)[.、)]\s*(.+?)\s*$", line)
23
+ if not match:
24
+ continue
25
+ index = int(match.group(1))
26
+ if 1 <= index <= count and index not in parsed:
27
+ parsed[index] = match.group(2)
28
+ if not parsed:
29
+ lines = [line.strip() for line in output.splitlines() if line.strip()]
30
+ if len(lines) == count:
31
+ parsed = {index: line for index, line in enumerate(lines, 1)}
32
+ return parsed
33
+
34
+
35
+ def translate_batch(batch: list, model, tokenizer, language: str) -> dict:
36
+ numbered = "\n".join(f"{index + 1}. {item['text']}" for index, item in enumerate(batch))
37
+ messages = [
38
+ {
39
+ "role": "system",
40
+ "content": (
41
+ "You are a professional subtitle translator. Translate each numbered line into "
42
+ f"{language}. Preserve proper names, numbers and terminology. Output only the translated "
43
+ "numbered lines in the same order, one per line, in the format '1. translation'. "
44
+ "Do not add explanations."
45
+ ),
46
+ },
47
+ {"role": "user", "content": numbered},
48
+ ]
49
+ prompt = tokenizer.apply_chat_template(
50
+ messages, add_generation_prompt=True, enable_thinking=False, tokenize=False
51
+ )
52
+ output = generate(model, tokenizer, prompt=prompt, max_tokens=MAX_TOKENS, verbose=False)
53
+ parsed = parse_numbered(output, len(batch))
54
+ if len(parsed) == len(batch):
55
+ return parsed
56
+ if len(batch) > 1:
57
+ mid = (len(batch) + 1) // 2
58
+ merged = translate_batch(batch[:mid], model, tokenizer, language)
59
+ for index, text in translate_batch(batch[mid:], model, tokenizer, language).items():
60
+ merged[index + mid] = text
61
+ return merged
62
+ return parsed
63
+
64
+
10
65
  def main() -> int:
11
66
  with open(sys.argv[1], "r", encoding="utf-8") as handle:
12
67
  config = json.load(handle)
@@ -17,37 +72,9 @@ def main() -> int:
17
72
  items = config["items"]
18
73
  results = {}
19
74
 
20
- batch_size = 15
21
- for start in range(0, len(items), batch_size):
22
- batch = items[start:start + batch_size]
23
- numbered = "\n".join(f"{index + 1}. {item['text']}" for index, item in enumerate(batch))
24
- messages = [
25
- {
26
- "role": "system",
27
- "content": (
28
- "You are a professional subtitle translator. Translate each numbered line into "
29
- f"{language}. Preserve proper names, numbers and terminology. Output only the translated "
30
- "numbered lines in the same order, one per line, in the format '1. translation'. "
31
- "Do not add explanations."
32
- ),
33
- },
34
- {"role": "user", "content": numbered},
35
- ]
36
- prompt = tokenizer.apply_chat_template(
37
- messages, add_generation_prompt=True, enable_thinking=False, tokenize=False
38
- )
39
- output = generate(model, tokenizer, prompt=prompt, max_tokens=1024, verbose=False)
40
- parsed = {}
41
- for line in output.splitlines():
42
- match = re.match(r"^\s*(\d+)[.、)]\s*(.+?)\s*$", line)
43
- if match:
44
- index = int(match.group(1))
45
- if 1 <= index <= len(batch) and index not in parsed:
46
- parsed[index] = match.group(2)
47
- if not parsed:
48
- lines = [line.strip() for line in output.splitlines() if line.strip()]
49
- if len(lines) == len(batch):
50
- parsed = {index: line for index, line in enumerate(lines, 1)}
75
+ for start in range(0, len(items), BATCH_SIZE):
76
+ batch = items[start:start + BATCH_SIZE]
77
+ parsed = translate_batch(batch, model, tokenizer, language)
51
78
  for index, item in enumerate(batch, 1):
52
79
  results[str(item["id"])] = parsed.get(index, "")
53
80
 
package/src/asr-api.js ADDED
@@ -0,0 +1,230 @@
1
+ // 云端转写:DeepSeek 语音识别接口(2026-11-13 随「全家桶」开放)。
2
+ //
3
+ // POST {base}/v1/tools/asr,multipart/form-data 上传一整段音频,返回整段文本。
4
+ // 官方硬限制:单次 ≤120 秒、≤8 MiB、16 位 PCM WAV 或 Ogg Opus;语种自动识别;
5
+ // 不支持流式;响应只有整段 text,**没有词级/句级时间戳**,所以时间轴要靠自己切块 + 按字数分配。
6
+ //
7
+ // 这里只放「调一次接口」和「把一整段文本变成带时间的行」两件事,
8
+ // 切片、并发、落盘、合并都留在 transcribe.js 里,和本地引擎复用同一套流程。
9
+ import fs from 'node:fs'
10
+ import { getSection } from './config.js'
11
+
12
+ export const API_ASR_PATH = '/v1/tools/asr'
13
+ // 官方要求 ≤120 秒。留 20 秒余量:切片是按容器时间戳切的,
14
+ // 有些音频的重采样/补帧会多出零点几秒,卡在 120 上迟早翻车。
15
+ // 块越大,句子被块边界切开的概率越低(切点还会吸附到静音处,见 transcribe.js 的 planCuts)。
16
+ export const API_CHUNK_SECONDS = 100
17
+ // 实时跟播模式(边播边出字幕)用小段滚动:块越小,字幕越跟手,代价是块边界的
18
+ // 重复开销(识别成本大约上浮 15%~30%)。12 秒在「延迟 3~5 秒」和成本之间折中。
19
+ export const REALTIME_CHUNK_SECONDS = 12
20
+ export const API_MAX_SECONDS = 100
21
+ export const API_MAX_BYTES = 8 * 1024 * 1024
22
+ const REQUEST_TIMEOUT_MS = 180000
23
+ const MAX_ATTEMPTS = 4
24
+
25
+ const SENTENCE_END = /[。!?!?…]/
26
+ const CLAUSE_END = /[,,;;、]/
27
+ // 紧跟句末标点的右引号/右括号要留在同一行,不然会出现「他说:」+「」」这种断裂。
28
+ const CLOSER = /[」』))】》”’"]/
29
+ // 一条字幕的长度上限(字符数)。有词边界的语言可以长一点,中日文没有空格,短一些。
30
+ const HARD_LIMIT = 84
31
+ const CJK_HARD_LIMIT = 48
32
+ // 逗号/顿号只有攒到这么长才算断点:短句里的逗号断开反而更难读。
33
+ // 中日文一行 30 字左右最好读,超过 48 字就必须断。
34
+ const SOFT_MIN = 30
35
+
36
+ function round2(value) {
37
+ return Math.round((Number(value) || 0) * 100) / 100
38
+ }
39
+
40
+ /**
41
+ * 转写走哪条路:`'api'`(默认,开箱即用)还是 `'local'`(本地模型,省钱但费机器)。
42
+ * 只有明确写了 `local` 才走本地,其它一律按云端处理,避免老配置突然掉回「没装模型」的死胡同。
43
+ */
44
+ export function asrProvider() {
45
+ const section = getSection('transcribe') || {}
46
+ return String(section.provider || '').toLowerCase() === 'local' ? 'local' : 'api'
47
+ }
48
+
49
+ /**
50
+ * 云端转写用到的端点与密钥。apiKey 留空时自动复用翻译那把 DeepSeek key ——
51
+ * 用户填一次就能同时用转写和翻译,不用记两次。
52
+ */
53
+ export function asrApiConfig() {
54
+ const api = getSection('api') || {}
55
+ const translate = getSection('translate') || {}
56
+ const base = String(api.base || translate.apiBase || 'https://api.deepseek.com')
57
+ .trim()
58
+ .replace(/\/+$/, '')
59
+ const key = String(api.key || translate.apiKey || '').trim()
60
+ return { base, url: `${base}${API_ASR_PATH}`, key, hasKey: Boolean(key) }
61
+ }
62
+
63
+ function describeFailure(status, payload) {
64
+ const message = String(payload?.error?.message || payload?.message || '').trim()
65
+ if (status === 401 || status === 403) {
66
+ return 'DeepSeek API key 无效或没有语音识别权限,请到设置里检查'
67
+ }
68
+ if (status === 402) return 'DeepSeek 账户余额不足,请充值后再转写'
69
+ if (status === 413) return '音频块太大,超过接口限制'
70
+ if (status === 429) return '请求太频繁被限流,稍后会自动重试'
71
+ if (message) return `语音识别失败:${message}`
72
+ return `语音识别失败(HTTP ${status})`
73
+ }
74
+
75
+ function sleep(ms) {
76
+ return new Promise((resolve) => setTimeout(resolve, ms))
77
+ }
78
+
79
+ /**
80
+ * 把一段音频发给 DeepSeek ASR。
81
+ * @returns {Promise<{text: string, durationMs: number}>}
82
+ */
83
+ export async function transcribeChunk(file, config = asrApiConfig(), { signal } = {}) {
84
+ if (!config.hasKey) {
85
+ throw Object.assign(new Error('还没有填 DeepSeek API key,去设置里填一个就能用云端转写'), { status: 400 })
86
+ }
87
+ const bytes = await fs.promises.readFile(file)
88
+ if (!bytes.length) throw new Error('音频块是空的')
89
+ if (bytes.length > API_MAX_BYTES) {
90
+ throw new Error(`音频块 ${(bytes.length / 1024 / 1024).toFixed(1)} MB,超过接口的 8 MB 上限`)
91
+ }
92
+
93
+ let lastError = null
94
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt += 1) {
95
+ const form = new FormData()
96
+ form.append('file', new Blob([bytes], { type: 'audio/wav' }), 'chunk.wav')
97
+ const controller = new AbortController()
98
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
99
+ const onAbort = () => controller.abort()
100
+ if (signal) signal.addEventListener('abort', onAbort, { once: true })
101
+ try {
102
+ const response = await fetch(config.url, {
103
+ method: 'POST',
104
+ headers: { authorization: `Bearer ${config.key}` },
105
+ body: form,
106
+ signal: controller.signal,
107
+ })
108
+ const raw = await response.text()
109
+ let payload = null
110
+ try {
111
+ payload = raw ? JSON.parse(raw) : null
112
+ } catch {
113
+ payload = null
114
+ }
115
+ if (!response.ok) {
116
+ const error = Object.assign(new Error(describeFailure(response.status, payload)), { status: response.status })
117
+ // 4xx 里只有 429 值得重试,其余(key 错、余额空、参数错)重试也没用。
118
+ if (response.status !== 429 && response.status < 500) throw error
119
+ lastError = error
120
+ } else {
121
+ return {
122
+ text: String(payload?.text || ''),
123
+ durationMs: Number(payload?.duration_ms) || 0,
124
+ }
125
+ }
126
+ } catch (error) {
127
+ if (error?.name === 'AbortError') {
128
+ if (signal?.aborted) throw new Error('用户取消了转写')
129
+ lastError = Object.assign(new Error('语音识别超时,稍后会自动重试'), { status: 504 })
130
+ } else if (error?.status && error.status !== 429 && error.status < 500) {
131
+ throw error
132
+ } else {
133
+ lastError = error
134
+ }
135
+ } finally {
136
+ clearTimeout(timer)
137
+ if (signal) signal.removeEventListener('abort', onAbort)
138
+ }
139
+ if (signal?.aborted) throw new Error('用户取消了转写')
140
+ if (attempt < MAX_ATTEMPTS) await sleep(600 * attempt)
141
+ }
142
+ throw lastError || new Error('语音识别失败')
143
+ }
144
+
145
+ /**
146
+ * 把一整段识别文本切成字幕句:句末标点断句;逗号只在够长时才断;
147
+ * 超长且没有标点(日语、中文常见)就退到最近的空格/标点处断,实在没有才硬断。
148
+ */
149
+ export function splitApiSentences(text) {
150
+ const chars = Array.from(String(text || ''))
151
+ const pieces = []
152
+ let buffer = ''
153
+ const flush = () => {
154
+ const piece = buffer.trim()
155
+ if (piece) pieces.push(piece)
156
+ buffer = ''
157
+ }
158
+ for (let index = 0; index < chars.length; index += 1) {
159
+ const char = chars[index]
160
+ buffer += char
161
+ const next = chars[index + 1] || ''
162
+ // 句末标点:后面还跟着右引号/右括号时先不断,等它们进来再断。
163
+ if (SENTENCE_END.test(char)) {
164
+ if (CLOSER.test(next)) continue
165
+ flush()
166
+ continue
167
+ }
168
+ if (CLOSER.test(char) && SENTENCE_END.test(chars[index - 1] || '')) {
169
+ flush()
170
+ continue
171
+ }
172
+ const length = buffer.trim().length
173
+ if (CLAUSE_END.test(char) && length >= SOFT_MIN) {
174
+ flush()
175
+ continue
176
+ }
177
+ if (length >= (/\s/.test(buffer) ? HARD_LIMIT : CJK_HARD_LIMIT)) {
178
+ const cut = lastBreakIndex(buffer)
179
+ if (cut > SOFT_MIN) {
180
+ const head = buffer.slice(0, cut).trim()
181
+ if (head) pieces.push(head)
182
+ buffer = buffer.slice(cut)
183
+ } else {
184
+ flush()
185
+ }
186
+ }
187
+ }
188
+ flush()
189
+ return pieces
190
+ }
191
+
192
+ // 在超长且没有标点的片段里挑一个断点:优先空格(英法等有词边界),其次标点。
193
+ function lastBreakIndex(text) {
194
+ for (let index = text.length - 1; index > 0; index -= 1) {
195
+ if (/[\s,,;;、]/.test(text[index])) return index + 1
196
+ }
197
+ return -1
198
+ }
199
+
200
+ /**
201
+ * 把一整段识别文本切成字幕行,并在 [start, start+duration) 之间按字数比例分配时间。
202
+ * 接口不给时间戳,这个分配是估算:块内误差可以接受,
203
+ * 比起「一行 30 秒」那种粗粒度,按句读切分读起来舒服得多。
204
+ */
205
+ export function buildApiLines(text, start, duration) {
206
+ const clean = String(text || '').replace(/\s+/g, ' ').trim()
207
+ if (!clean) return []
208
+ const pieces = splitApiSentences(clean)
209
+ if (!pieces.length) return []
210
+
211
+ const totalChars = pieces.reduce((sum, piece) => sum + piece.length, 0) || 1
212
+ const span = Math.max(Number(duration) || 0, pieces.length * 0.4)
213
+ const lines = []
214
+ let cursor = 0
215
+ for (const [index, piece] of pieces.entries()) {
216
+ const length = (piece.length / totalChars) * span
217
+ const lineStart = round2(start + cursor)
218
+ cursor += length
219
+ const isLast = index === pieces.length - 1
220
+ const lineEnd = round2(start + (isLast ? span : cursor))
221
+ lines.push({
222
+ id: index + 1,
223
+ start: lineStart,
224
+ // 单字符行(「好。」)也至少给 0.3 秒,不然播放器高亮会一闪而过。
225
+ end: Math.max(lineEnd, round2(lineStart + 0.3)),
226
+ text: piece,
227
+ })
228
+ }
229
+ return lines
230
+ }
package/src/config.js CHANGED
@@ -30,20 +30,43 @@ function cachedDefaultModels() {
30
30
 
31
31
  export const CONFIG_DEFAULTS = {
32
32
  schemaVersion: 1,
33
- ui: { showSidebarPanel: true, sidebarCollapsed: false },
33
+ ui: {
34
+ showSidebarPanel: true,
35
+ sidebarCollapsed: false,
36
+ // 字幕字号(px):字幕面板和悬浮字幕共用这一个设置,用拖动条调。
37
+ subtitleSize: 15,
38
+ // 悬浮字幕:是否开启、停留在屏幕上的位置(null = 用默认的右下角)。
39
+ captionOpen: false,
40
+ captionX: null,
41
+ captionY: null,
42
+ },
43
+ // DeepSeek API 的地址 / 密钥 / 对话模型:转写和翻译共用这一份,用户只填一次。
44
+ // 老版本把这三项存在 translate 段里,读到时由 migrateApiSection() 挪过来。
45
+ api: {
46
+ base: 'https://api.deepseek.com',
47
+ key: '',
48
+ model: 'deepseek-chat',
49
+ },
34
50
  translate: {
35
51
  provider: 'api',
36
52
  target: 'zh',
37
- apiBase: 'https://api.deepseek.com',
38
- apiModel: 'deepseek-chat',
39
- apiKey: '',
40
53
  },
41
54
  // 默认模型绝不能写死 MLX:那套模型 platform 是 darwin-arm64,Windows 装不了。
42
55
  // dir 为空表示用默认目录(<数据目录>/models);用户改过则存绝对路径。
43
56
  get models() {
44
57
  return { dir: '', ...cachedDefaultModels() }
45
58
  },
46
- transcribe: { hotwords: [], chunkMinutes: 1, diarize: true },
59
+ // 转写默认走云端 API:装好插件、填一个 DeepSeek key 就能用,不用先下载 2.4G 模型。
60
+ // 想省钱可以在设置里切成本地模型(provider: 'local',需要先一键安装运行时和模型)。
61
+ // 密钥与地址统一在 api 段,转写这里只管「用哪个引擎」。
62
+ transcribe: {
63
+ provider: 'api',
64
+ hotwords: [],
65
+ chunkMinutes: 1,
66
+ diarize: true,
67
+ // 边播边出字幕:播放某集时自动用小段滚动转写,字幕/译文/说话人跟着播放进度出现。
68
+ realtime: true,
69
+ },
47
70
  import: { mode: 'copy' },
48
71
  }
49
72
 
@@ -112,11 +135,32 @@ function migrateLegacy() {
112
135
  let cache = null
113
136
  let cacheKey = null
114
137
 
138
+ // 老配置(0.11.28 及以前)把 API 地址/密钥/对话模型存在 translate 段里,
139
+ // 转写要再填一次。这里在读到时把它们搬进 api 段并落盘一次,之后只认 api 段。
140
+ function migrateApiSection(stored, merged) {
141
+ if (!stored || stored.api) return false
142
+ const legacy = stored.translate || {}
143
+ const base = String(legacy.apiBase || '').trim()
144
+ const model = String(legacy.apiModel || '').trim()
145
+ const apiKey = String(legacy.apiKey || '').trim()
146
+ if (!base && !model && !apiKey) return false
147
+ if (base) merged.api.base = base
148
+ if (model) merged.api.model = model
149
+ if (apiKey) merged.api.key = apiKey
150
+ return true
151
+ }
152
+
115
153
  export function loadConfig() {
116
154
  const key = statKey()
117
155
  if (cache && cacheKey === key) return clone(cache)
118
156
  const stored = key === 'missing' ? null : readJson(CONFIG_PATH)
119
157
  cache = stored ? merge(clone(CONFIG_DEFAULTS), stored) : migrateLegacy()
158
+ if (migrateApiSection(stored, cache)) {
159
+ // 迁移只做一次:写回失败也不影响本次读取,下次再试。
160
+ try {
161
+ writeConfig(cache)
162
+ } catch {}
163
+ }
120
164
  cacheKey = statKey()
121
165
  return clone(cache)
122
166
  }