deep-read-summarize 0.3.19 → 0.5.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.
@@ -6,6 +6,17 @@
6
6
  // 标题/作者里出现引号时不会再截断 frontmatter(旧版是裸拼 "...")。
7
7
  function yamlStr(v) { return JSON.stringify(v == null ? "" : String(v)); }
8
8
 
9
+ function fatalWorkflowError(error) {
10
+ return !!error && (error.fatal === true || error.code === "UNSUPPORTED_SCHEMA" ||
11
+ /\[FATAL\]|\bUNSUPPORTED_SCHEMA\b/.test(String(error.message || error)));
12
+ }
13
+ const workflowStartedAt = Date.now();
14
+ const timings = { detect: 0, fetch: 0, read: 0, draft: 0, quality: 0, total: 0 };
15
+ function timedResult(result) {
16
+ timings.total = Date.now() - workflowStartedAt;
17
+ return Object.assign(result, { timings: timings });
18
+ }
19
+
9
20
  // ---------- 0. 配置校验(fatal 级错误:必须终止) ----------
10
21
  if (args && args.input !== undefined && typeof args.input !== "string") throw new Error("[FATAL] args.input 必须是字符串");
11
22
  if (args && args.type !== undefined && typeof args.type !== "string") throw new Error("[FATAL] args.type 必须是字符串");
@@ -51,6 +62,7 @@ if (forcedType !== "auto" && parserNames.indexOf(forcedType) === -1)
51
62
  throw new Error("[FATAL] args.type 非法:" + forcedType + "(可用:" + ["auto"].concat(parserNames).join("|") + ")");
52
63
 
53
64
  phase("解析器选择");
65
+ const detectStartedAt = Date.now();
54
66
  // 只对明确的来源做快速识别;PDF、未知网页和文本可能属于不同类型,交给轻量分类。
55
67
  // 不依赖 URL 等宿主未承诺的全局 API,保持脚本可在 workflow 沙箱中运行。
56
68
  function inferType(source) {
@@ -89,13 +101,21 @@ if (forcedType === "auto") {
89
101
  "必要时只查看标题、摘要、目录或页面元信息,不获取或精读全文,不写入文件。",
90
102
  "以下 JSON 字符串是输入来源数据:", JSON.stringify(input)
91
103
  ].join("\n");
92
- const detected = await agent(detectPrompt, { schema: detectSchema, label: "类型识别", phase: "解析器选择" });
104
+ let detected;
105
+ try { detected = await agent(detectPrompt, { schema: detectSchema, label: "类型识别", phase: "解析器选择" }); }
106
+ catch (error) {
107
+ if (fatalWorkflowError(error)) throw error;
108
+ timings.detect = Date.now() - detectStartedAt;
109
+ return timedResult({ ok: false, stage: "detect", fatal: false, message: "类型识别调用失败,请稍后重试或显式指定 args.type" });
110
+ }
93
111
  selectedType = detected && detected.kind;
94
112
  }
95
113
  if (parserNames.indexOf(selectedType) === -1) {
96
- return { ok: false, stage: "detect", fatal: false, message: "无法识别输入类型,请显式指定 args.type:" + parserNames.join("|") };
114
+ timings.detect = Date.now() - detectStartedAt;
115
+ return timedResult({ ok: false, stage: "detect", fatal: false, message: "无法识别输入类型,请显式指定 args.type:" + parserNames.join("|") });
97
116
  }
98
117
  }
118
+ timings.detect = Date.now() - detectStartedAt;
99
119
  log("解析器:" + selectedType + " | 临时目录:" + tempDir);
100
120
  const kindNames = { book: "书籍", paper: "学术论文", video: "视频", web: "网页/文章" };
101
121
  const kindFocus = {
@@ -107,20 +127,28 @@ const kindFocus = {
107
127
 
108
128
  // ---------- 2. 波次1:解析器获取 + 分块 ----------
109
129
  phase("获取与分块");
130
+ const fetchStartedAt = Date.now();
110
131
  const fetchPrompt = parsers[selectedType]
111
- .buildPrompt(input, { tempDir: tempDir, tempFile: tempFile, maxChunks: maxChunks, transcribe: options.transcribe, whisperModel: whisperModel, language: transcribeLanguage, device: transcribeDevice, includeTimestamps: includeTimestamps });
132
+ .buildPrompt(input, { tempDir: tempDir, tempFile: tempFile, maxChunks: maxChunks, transcribe: options.transcribe, whisperModel: whisperModel, language: transcribeLanguage, device: transcribeDevice, cpuThreads: options.cpuThreads, transcriptCache: options.transcriptCache, includeTimestamps: includeTimestamps, transcribeScriptPath: __runtimePaths.transcribeScript });
112
133
  // fetchSchema 由插件在构建时从 schemas/index.js 注入(单一真相,避免两份 schema 漂移)。
113
134
 
114
- const fetched = await agent(fetchPrompt, { schema: fetchSchema, label: "获取+分块", phase: "获取与分块" });
135
+ let fetched;
136
+ try { fetched = await agent(fetchPrompt, { schema: fetchSchema, label: "获取+分块", phase: "获取与分块" }); }
137
+ catch (error) {
138
+ if (fatalWorkflowError(error)) throw error;
139
+ timings.fetch = Date.now() - fetchStartedAt;
140
+ return timedResult({ ok: false, stage: "fetch", fatal: false, message: "内容获取调用失败,请稍后重试或手动提供文本" });
141
+ }
115
142
 
116
143
  // 失败纪律:内容获取失败 = 可降级错误(返回失败结果,不抛 fatal)
117
144
  if (!fetched || !fetched.saved) {
118
- return { ok: false, stage: "fetch", fatal: false, message: (fetched && fetched.message) || "获取失败(可降级:检查输入或手动提供文本)" };
145
+ timings.fetch = Date.now() - fetchStartedAt;
146
+ return timedResult({ ok: false, stage: "fetch", fatal: false, message: (fetched && fetched.message) || "获取失败(可降级:检查输入或手动提供文本)" });
119
147
  }
120
148
  // 先校验完整计划,按行排序、裁掉重复覆盖并补齐缺口,再合并相邻块。
121
149
  // 块数上限约束的是子代理数量,不能通过丢掉尾部原文来实现。
122
150
  const rawPlan = (fetched && fetched.chunkPlan) || [];
123
- if (rawPlan.length === 0) return { ok: false, stage: "fetch", fatal: false, message: "分块计划为空" };
151
+ if (rawPlan.length === 0) { timings.fetch = Date.now() - fetchStartedAt; return timedResult({ ok: false, stage: "fetch", fatal: false, message: "分块计划为空" }); }
124
152
  const lineCount = Number(fetched.totalLines);
125
153
  const declaredLines = Number.isFinite(lineCount) && lineCount > 0 ? Math.floor(lineCount) : 0;
126
154
  const validPlan = [];
@@ -136,7 +164,7 @@ for (let i = 0; i < rawPlan.length; i++) {
136
164
  endLine: declaredLines > 0 ? Math.min(e, declaredLines) : e
137
165
  });
138
166
  }
139
- if (validPlan.length === 0) return { ok: false, stage: "fetch", fatal: false, message: "分块计划无效:行号区间缺失或非法" };
167
+ if (validPlan.length === 0) { timings.fetch = Date.now() - fetchStartedAt; return timedResult({ ok: false, stage: "fetch", fatal: false, message: "分块计划无效:行号区间缺失或非法" }); }
140
168
  validPlan.sort(function (a, b) { return a.startLine - b.startLine || a.endLine - b.endLine; });
141
169
  const coveredPlan = [];
142
170
  let nextLine = 1;
@@ -153,14 +181,17 @@ if (declaredLines > 0 && nextLine <= declaredLines) {
153
181
  coveredPlan.push({ topic: "补充尾部内容", startLine: nextLine, endLine: declaredLines });
154
182
  }
155
183
  const chunkPlan = [];
156
- const groups = Math.min(maxChunks, coveredPlan.length);
184
+ const knownLines = coveredPlan[coveredPlan.length - 1].endLine;
185
+ const groups = Math.min(maxChunks, coveredPlan.length, knownLines);
157
186
  for (let i = 0; i < groups; i++) {
158
- const from = Math.floor(i * coveredPlan.length / groups);
159
- const to = Math.floor((i + 1) * coveredPlan.length / groups);
160
- const parts = coveredPlan.slice(from, to);
187
+ // Balance source lines, not the number of logical topics: a very long topic
188
+ // may span workers, and every line still belongs to exactly one worker.
189
+ const startLine = Math.floor(i * knownLines / groups) + 1;
190
+ const endLine = Math.floor((i + 1) * knownLines / groups);
191
+ const parts = coveredPlan.filter(function (c) { return c.startLine <= endLine && c.endLine >= startLine; });
161
192
  chunkPlan.push({
162
193
  id: i + 1, topic: parts.map(function (c) { return c.topic; }).join(" / "),
163
- startLine: parts[0].startLine, endLine: parts[parts.length - 1].endLine
194
+ startLine: startLine, endLine: endLine
164
195
  });
165
196
  }
166
197
  const coverageComplete = declaredLines > 0;
@@ -171,13 +202,22 @@ log("分块计划:" + rawPlan.length + " -> " + chunkPlan.length + " 块(上
171
202
  const kind = selectedType;
172
203
  const metadata = (fetched && fetched.metadata) || {};
173
204
  const textSource = (metadata && metadata.textSource) || "unknown";
205
+ // Reading every line of a description does not establish coverage of a video.
206
+ // Full transcripts/subtitles remain eligible; descriptions and unknown video
207
+ // sources must retain their source-level gap even if the note is well written.
208
+ const sourceComplete = kind !== "video" || ["subtitle", "transcription", "manual"].indexOf(textSource) !== -1;
209
+ const sourceNotice = sourceComplete ? "" : textSource === "desc"
210
+ ? "> 来源限制:本笔记仅依据视频简介生成,未取得完整字幕或逐字稿,不能代表完整视频内容的精读。"
211
+ : "> 来源限制:本次视频来源尚未确认为完整字幕或逐字稿,本笔记不能代表完整视频内容的精读。";
174
212
  const srcLabels = { desc: "视频简介/desc", subtitle: "平台字幕", transcription: "完整语音转写", manual: "用户提供转写文本" };
175
213
  const srcLabel = srcLabels[textSource] || textSource;
176
214
  log("[source] " + textSource + " -> " + srcLabel);
177
215
  log("类型:" + kind + " 行数:" + fetched.totalLines + " 块数:" + chunkPlan.length);
216
+ timings.fetch = Date.now() - fetchStartedAt;
178
217
 
179
218
  // ---------- 3. 波次2:并行精读(Map) ----------
180
219
  phase("并行精读");
220
+ const readStartedAt = Date.now();
181
221
  const chunkPrompts = chunkPlan.map(function (c) {
182
222
  return [
183
223
  "请深度精读以下内容块,输出结构化精读笔记。",
@@ -193,18 +233,23 @@ const chunkPrompts = chunkPlan.map(function (c) {
193
233
  ].join("\n");
194
234
  });
195
235
 
196
- const reads = [];
197
- const readBatch = 3;
198
- for (let bi = 0; bi < chunkPrompts.length; bi += readBatch) {
199
- const batch = chunkPrompts.slice(bi, bi + readBatch);
200
- const batchReads = await parallel(batch.map(function (p) {
201
- return async function () {
202
- try { return await agent(p, { label: "精读块", phase: "并行精读" }); }
203
- catch (error) { log("精读调用失败,保留对应分块缺口"); return ""; }
204
- };
205
- }));
206
- for (let k = 0; k < batchReads.length; k++) reads.push(batchReads[k]);
236
+ const reads = new Array(chunkPrompts.length);
237
+ let nextRead = 0;
238
+ let stopReading = false;
239
+ const readWorkers = [];
240
+ for (let worker = 0; worker < Math.min(3, chunkPrompts.length); worker++) {
241
+ readWorkers.push(async function () {
242
+ while (!stopReading && nextRead < chunkPrompts.length) {
243
+ const index = nextRead++;
244
+ try { reads[index] = await agent(chunkPrompts[index], { label: "精读块", phase: "并行精读" }); }
245
+ catch (error) {
246
+ if (fatalWorkflowError(error)) { stopReading = true; throw error; }
247
+ log("精读调用失败,保留对应分块缺口"); reads[index] = "";
248
+ }
249
+ }
250
+ });
207
251
  }
252
+ await parallel(readWorkers);
208
253
  const validReads = reads.filter(function (r) { return typeof r === "string" && r.trim().length > 0; });
209
254
  const readEvidence = chunkPlan.map(function (chunk, i) {
210
255
  return { chunkId: chunk.id, topic: chunk.topic, startLine: chunk.startLine, endLine: chunk.endLine,
@@ -215,18 +260,40 @@ const failedChunkIds = readEvidence.filter(function (r) { return !r.readSucceede
215
260
 
216
261
  // 失败纪律:某块精读失败 = 可降级(跳过该块,标记缺口继续)
217
262
  const failedChunks = chunkPlan.length - validReads.length;
218
- if (validReads.length === 0) return { ok: false, stage: "read", fatal: false, message: "所有分块精读均失败" };
263
+ timings.read = Date.now() - readStartedAt;
264
+ if (validReads.length === 0) return timedResult({ ok: false, stage: "read", fatal: false, message: "所有分块精读均失败" });
219
265
  if (failedChunks > 0) log("警告:" + failedChunks + " 块精读失败,标记缺口继续成稿");
220
266
  log("精读完成:" + validReads.length + "/" + chunkPlan.length);
221
267
 
222
268
  // ---------- 4. 波次3:成稿 + 内嵌质量自检(Reduce) ----------
223
269
  phase("汇总成稿");
270
+ const draftStartedAt = Date.now();
224
271
  const todayDate = new Date();
225
272
  const today = todayDate.getFullYear() + "-" + ("0" + (todayDate.getMonth() + 1)).slice(-2) + "-" + ("0" + todayDate.getDate()).slice(-2);
226
273
  // 标题先折叠换行/制表与连续空白:否则会同时污染 .md 文件名和 frontmatter。
227
274
  const finalTitle = String(metadata.title || "").replace(/[\r\n\t]+/g, " ").replace(/\s+/g, " ").trim() || "未命名内容";
228
- // 文件名清洗:去掉 Windows 非法字符;全部非法时兜底,避免写出 ./output/.md 这种隐藏文件。
229
- const safeTitle = finalTitle.replace(/[\\/:*?"<>|]/g, " ").replace(/\s+/g, " ").trim() || "未命名内容";
275
+ // Keep normal titles stable. Changed/long titles receive a deterministic suffix
276
+ // so distinct unsafe titles do not collapse onto the same sanitized filename.
277
+ function titleHash(value) {
278
+ let hash = 2166136261;
279
+ for (let i = 0; i < value.length; i++) { hash ^= value.charCodeAt(i); hash = Math.imul(hash, 16777619); }
280
+ return ("00000000" + (hash >>> 0).toString(16)).slice(-8);
281
+ }
282
+ function utf8Prefix(value, budget) {
283
+ let result = "", bytes = 0;
284
+ for (const character of value) {
285
+ const point = character.codePointAt(0);
286
+ const size = point <= 127 ? 1 : point <= 2047 ? 2 : point <= 65535 ? 3 : 4;
287
+ if (bytes + size > budget) break;
288
+ result += character; bytes += size;
289
+ }
290
+ return result;
291
+ }
292
+ let safeTitle = finalTitle.replace(/[\u0000-\u001f\u007f\\/:*?"<>|]/g, " ").replace(/\s+/g, " ").trim().replace(/[. ]+$/, "") || "未命名内容";
293
+ if (/^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(safeTitle)) safeTitle = "_" + safeTitle;
294
+ if (safeTitle !== finalTitle || utf8Prefix(safeTitle, 197) !== safeTitle) {
295
+ safeTitle = (utf8Prefix(safeTitle, 188).replace(/[. ]+$/, "") || "未命名内容") + "-" + titleHash(finalTitle);
296
+ }
230
297
  const mdPath = outputDir.replace(/[\\/]+$/, "") + "/" + safeTitle + ".md";
231
298
 
232
299
  const extraSections = fastMode ? [] : [
@@ -266,6 +333,7 @@ fm.push("---");
266
333
 
267
334
  const draftPrompt = [
268
335
  "将以下多块精读结果整合为完整的结构化精读笔记,只输出标准 Markdown(含 YAML frontmatter)。",
336
+ sourceComplete ? "来源完整性仍需由独立原文核验确认。" : "本次来源不完整。必须在正文开头保留以下可见来源限制,不得称为完整视频精读或补写未取得的视频内容:\n" + sourceNotice,
269
337
  "模板:"
270
338
  ].concat(fm, [
271
339
  "# 《" + finalTitle + "》深度精读笔记", "",
@@ -287,11 +355,17 @@ const draftPrompt = [
287
355
 
288
356
  let draft;
289
357
  try { draft = await agent(draftPrompt, { label: "汇总成稿", phase: "汇总成稿" }); }
290
- catch (error) { return { ok: false, stage: "draft", fatal: false, message: "成稿调用失败,未产生可保存的笔记" }; }
291
- if (typeof draft !== "string" || !draft.trim()) return { ok: false, stage: "draft", fatal: false, message: "成稿为空或不是字符串" };
358
+ catch (error) {
359
+ if (fatalWorkflowError(error)) throw error;
360
+ timings.draft = Date.now() - draftStartedAt;
361
+ return timedResult({ ok: false, stage: "draft", fatal: false, message: "成稿调用失败,未产生可保存的笔记" });
362
+ }
363
+ timings.draft = Date.now() - draftStartedAt;
364
+ if (typeof draft !== "string" || !draft.trim()) return timedResult({ ok: false, stage: "draft", fatal: false, message: "成稿为空或不是字符串" });
292
365
 
293
366
  // ---------- 5. 程序检查 + 独立原文核验 ----------
294
367
  phase("质量校验");
368
+ const qualityStartedAt = Date.now();
295
369
  let verified = draft;
296
370
  let passed = false;
297
371
  let issues = [];
@@ -299,7 +373,11 @@ let qualityChecks = {};
299
373
  let qualityEvidence = { sourceFile: tempFile, totalLines: declaredLines, failedChunkIds: failedChunkIds, chunkChecks: [], citationChecks: [] };
300
374
  const structureOptions = { minWords: minWords, fastMode: fastMode, expectedFrontmatter: fm };
301
375
  const sourceContext = { sourceFile: tempFile, input: input, totalLines: declaredLines,
302
- chunkPlan: chunkPlan, readEvidence: readEvidence, failedChunkIds: failedChunkIds, coverageComplete: coverageComplete };
376
+ kind: kind, textSource: textSource, sourceComplete: sourceComplete,
377
+ chunkPlan: chunkPlan, readEvidence: readEvidence.map(function (r) {
378
+ return { chunkId: r.chunkId, topic: r.topic, startLine: r.startLine, endLine: r.endLine, readSucceeded: r.readSucceeded };
379
+ }), failedChunkIds: failedChunkIds, coverageComplete: coverageComplete };
380
+ const repairableSource = sourceComplete && coverageComplete && failedChunkIds.length === 0;
303
381
  for (let round = 0; round <= maxRetries; round++) {
304
382
  const localCheck = __quality.checkNoteStructure(verified, structureOptions);
305
383
  const checkPrompt = [
@@ -330,9 +408,12 @@ for (let round = 0; round <= maxRetries; round++) {
330
408
  };
331
409
  let check = null;
332
410
  try { check = await agent(checkPrompt, { schema: checkSchema, label: "质量校验", phase: "质量校验" }); }
333
- catch (error) { log("原文核验调用失败,保留当前有效笔记并报告质量未通过"); }
411
+ catch (error) {
412
+ if (fatalWorkflowError(error)) throw error;
413
+ log("原文核验调用失败,保留当前有效笔记并报告质量未通过");
414
+ }
334
415
  const sourceCheck = __quality.validateSourceCheck(check, {
335
- chunkPlan: chunkPlan, failedChunkIds: failedChunkIds, coverageComplete: coverageComplete,
416
+ chunkPlan: chunkPlan, failedChunkIds: failedChunkIds, coverageComplete: coverageComplete, sourceComplete: sourceComplete, textSource: textSource,
336
417
  requireCitations: requireCitations, note: verified, visibleNote: localCheck.visibleText, quotes: localCheck.quotes
337
418
  });
338
419
  issues = Array.from(new Set(localCheck.issues.concat(sourceCheck.issues)));
@@ -342,6 +423,9 @@ for (let round = 0; round <= maxRetries; round++) {
342
423
  chunkChecks: sourceCheck.chunkChecks, citationChecks: sourceCheck.citationChecks };
343
424
  log("校验:" + (passed ? "通过" : "发现问题 " + issues.length + " 条"));
344
425
  if (passed) break;
426
+ // A rewrite cannot recover missing source lines, failed reads, or a full
427
+ // transcript. Preserve the candidate and report the gap after one audit.
428
+ if (!repairableSource) break;
345
429
  if (round < maxRetries) {
346
430
  const fixPrompt = [
347
431
  "修正以下笔记以解决校验问题,输出完整修正版:",
@@ -352,7 +436,10 @@ for (let round = 0; round <= maxRetries; round++) {
352
436
  ].join("\n");
353
437
  let repaired;
354
438
  try { repaired = await agent(fixPrompt, { label: "修正笔记", phase: "质量校验" }); }
355
- catch (error) { issues.push("修正调用失败,已保留上一份有效笔记"); break; }
439
+ catch (error) {
440
+ if (fatalWorkflowError(error)) throw error;
441
+ issues.push("修正调用失败,已保留上一份有效笔记"); break;
442
+ }
356
443
  if (typeof repaired !== "string" || !repaired.trim()) {
357
444
  issues.push("修正结果为空或不是字符串,已保留上一份有效笔记"); break;
358
445
  }
@@ -365,7 +452,17 @@ for (let round = 0; round <= maxRetries; round++) {
365
452
  }
366
453
 
367
454
  // ---------- 结果 ----------
368
- return {
455
+ if (!sourceComplete) {
456
+ // Enforce source disclosure even when the drafting model omits it. Keep the
457
+ // YAML at the beginning and insert the notice outside any model-made fence.
458
+ const front = verified.match(/^\s*---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/);
459
+ const prefix = front ? front[0].trim() + "\n\n" : "";
460
+ const body = (front ? verified.slice(front[0].length) : verified).split(/\r?\n/)
461
+ .filter(function (line) { return line.trim() !== sourceNotice; }).join("\n").replace(/^\s*\n/, "");
462
+ verified = prefix + sourceNotice + "\n\n" + body;
463
+ }
464
+ timings.quality = Date.now() - qualityStartedAt;
465
+ return timedResult({
369
466
  ok: true, kind: kind, title: finalTitle,
370
467
  filePath: mdPath, chunksCount: chunkPlan.length, fastMode: fastMode,
371
468
  qualityPassed: passed, qualityIssues: issues,
@@ -373,5 +470,6 @@ return {
373
470
  failedChunks: failedChunks,
374
471
  coverageComplete: coverageComplete,
375
472
  textSource: textSource,
473
+ sourceComplete: sourceComplete,
376
474
  note: verified
377
- };
475
+ });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "deep-read-summarize",
3
- "version": "0.3.19",
4
- "description": "Deep reading & summarization for DSH: books/papers/videos/web → structured Markdown notes (Obsidian / Logseq / static sites). Plugin parsers, MapReduce deep-read, JSON Schema-constrained sub-tasks.",
3
+ "version": "0.5.0",
4
+ "description": "Deep reading & summarization for DSH: books/papers/videos/web → structured Markdown notes with YAML frontmatter. Plugin parsers, MapReduce deep-read, JSON Schema-constrained sub-tasks.",
5
5
  "type": "commonjs",
6
6
  "main": "index.js",
7
7
  "exports": {
@@ -16,12 +16,14 @@
16
16
  "index.js",
17
17
  "workflow.js",
18
18
  "parsers",
19
+ "custom-parsers",
19
20
  "schemas",
20
21
  "lib",
21
22
  "skills",
22
23
  "scripts",
23
24
  "!scripts/release.js",
24
25
  "docs/RELEASE.md",
26
+ "docs/ASR_BENCHMARK.md",
25
27
  "cordis.patch.yml",
26
28
  "CHANGELOG.md",
27
29
  "README.md",
package/parsers/index.js CHANGED
@@ -29,11 +29,22 @@ const builtins = {
29
29
  * 同名类型会覆盖内置解析器(用户按需替换)。
30
30
  */
31
31
  class ParserRegistry {
32
- constructor() {
32
+ constructor(settings = {}) {
33
+ if (!settings || typeof settings !== 'object' || Array.isArray(settings)) throw new Error('parser registry settings must be an object');
34
+ if (settings.customParsersDir !== undefined && (typeof settings.customParsersDir !== 'string' || !settings.customParsersDir.trim() || /[\u0000\r\n]/.test(settings.customParsersDir))) {
35
+ throw new Error('customParsersDir must be a non-empty directory path');
36
+ }
33
37
  this.parsers = Object.create(null);
34
38
  this._sources = new WeakMap();
35
39
  for (const type of Object.keys(builtins)) this.register(builtins[type], require.resolve('./' + type));
36
- this._loadCustom();
40
+ const bundledDir = path.join(__dirname, '..', 'custom-parsers');
41
+ this._loadCustom(bundledDir);
42
+ // Explicit profile/project paths overlay package-owned defaults. Never scan
43
+ // arbitrary working directories for executable code without configuration.
44
+ if (settings.customParsersDir !== undefined) {
45
+ const customDir = path.resolve(settings.baseDir || process.cwd(), settings.customParsersDir);
46
+ if (customDir !== path.resolve(bundledDir)) this._loadCustom(customDir, true);
47
+ }
37
48
  }
38
49
 
39
50
  /** Remember the module, not just its function: module factories preserve helpers and closures. */
@@ -60,11 +71,16 @@ class ParserRegistry {
60
71
  return undefined;
61
72
  }
62
73
 
63
- _loadCustom() {
64
- const customDir = path.join(__dirname, "..", "custom-parsers");
65
- if (!fs.existsSync(customDir)) return;
66
- for (const file of fs.readdirSync(customDir)) {
67
- if (!file.endsWith(".js")) continue;
74
+ _loadCustom(customDir, explicit) {
75
+ if (!fs.existsSync(customDir)) {
76
+ if (explicit) console.warn('[parsers] custom parser directory does not exist:', customDir);
77
+ return;
78
+ }
79
+ let files;
80
+ try { files = fs.readdirSync(customDir); }
81
+ catch (error) { console.warn('[parsers] cannot read custom parser directory:', customDir, error.message); return; }
82
+ for (const file of files.sort()) {
83
+ if (!/\.(?:js|cjs)$/.test(file)) continue;
68
84
  try {
69
85
  const filename = path.join(customDir, file);
70
86
  const mod = require(filename);
package/parsers/video.js CHANGED
@@ -31,8 +31,25 @@ module.exports = {
31
31
  const whisperModel = o.whisperModel || "small";
32
32
  const language = o.language || "zh";
33
33
  const device = o.device || "cpu";
34
+ const cpuThreads = Number.isInteger(o.cpuThreads) ? o.cpuThreads : 0;
35
+ const useTranscriptCache = o.transcriptCache !== false;
34
36
  const includeTimestamps = o.includeTimestamps === true;
35
37
  const degradeMsg = "需要人工提供转写文本或视频文案";
38
+ const sourceUrl = String(input).match(/https?:\/\/[^\s<>"']+/i);
39
+ const source = sourceUrl ? sourceUrl[0] : String(input);
40
+ const isBilibili = /^https?:\/\/(?:[^/?#]*@)?(?:[^/?#:]+\.)?(?:bilibili\.com|b23\.tv)(?=[:/?#]|$)/i.test(source);
41
+ const pageMatch = isBilibili ? source.split('#')[0].match(/[?&]p=([^&#]*)/) : null;
42
+ let pageValue = pageMatch ? pageMatch[1] : '';
43
+ try { pageValue = decodeURIComponent(pageValue); } catch (error) { pageValue = 'invalid'; }
44
+ if (pageMatch && (!/^[1-9]\d*$/.test(pageValue) || !Number.isSafeInteger(Number(pageValue)))) {
45
+ return 'B站输入的 p 分P参数非法,必须是从 1 开始的整数。不要获取字幕或音频,也不要转写。只输出 ' +
46
+ JSON.stringify({ saved: false, message: 'B站 p 分P参数非法,请指定有效的正整数分P编号' });
47
+ }
48
+ const requestedPage = pageMatch ? Number(pageValue) : null;
49
+ const scriptPath = typeof o.transcribeScriptPath === 'string' && o.transcribeScriptPath ? o.transcribeScriptPath : '';
50
+ // JSON encoding preserves arbitrary package paths as data. The executing
51
+ // agent must quote the path for its shell, rather than copying raw text.
52
+ const scriptCommand = scriptPath ? JSON.stringify(scriptPath) : '<脚本路径>';
36
53
 
37
54
  const noSubtitleBranch = wantTranscribe
38
55
  ? "② 若**无公开字幕**,用插件自带 faster-whisper 转写得到全文;③ 仍不可行才降级(提示人工提供转写文本 或 退回 desc 作背景)。"
@@ -53,9 +70,10 @@ module.exports = {
53
70
  ? "保留真实时间定位:B站字幕保留每条 from/to,YouTube CC 保留每条 cue 的 start/end;转成文本时每段独占一行,格式为 [HH:MM:SS.mmm --> HH:MM:SS.mmm] 原文。写入目标文件时保留这些时间,不可把全文压成一行。简介/人工文案若没有真实时间信息,明确注明无法提供时间戳,禁止猜测或编造。"
54
71
  : "字幕或转写按原有分段逐段换行写入目标文件,保留内容结构,不要把全文压成一行;本次不要求在正文标时间戳。",
55
72
  "统一流程:① 先取视频字幕(B站 AI 字幕 / YouTube yt-dlp CC);" + noSubtitleBranch,
56
- "若输入是 B 站链接(bilibili.com / b23.tv,短链先用 curl -L 跟随重定向提取 BV 号):用 curl(Windows 10+ 与 macOS/Linux 均自带,零安装)调官方公开 API:\n" +
57
- " 1) 元数据+简介:curl 'https://api.bilibili.com/x/web-interface/view?bvid=<BV>' → 取 title / desc(简介仅作背景/补充,不满一篇精读)/ owner.name / duration / aid / cid\n" +
58
- " 2) 字幕(**优先,最快**):curl 'https://api.bilibili.com/x/player/v2?aid=<aid>&cid=<cid>' 取 subtitle 列表;若有则下载转文本(textSource=subtitle)——这已是完整逐字稿,直接使用\n" +
73
+ "若输入是 B 站链接(bilibili.com / b23.tv):用 curl(Windows 10+ 与 macOS/Linux 均自带,零安装)调官方公开 API:\n" +
74
+ " 0) 短链用 curl -L 取得完整最终 URL,保留 query。输入明确带 p 时保留该分P选择;否则读取重定向最终 URL 的 p;都没有才默认 p=1。不能只提取 BV 号而丢掉 p。p 必须为正整数,非法则 saved=false,禁止偷偷改读第1P。" + (requestedPage === null ? '' : '本次输入明确指定 p=' + requestedPage + '。') + "\n" +
75
+ " 1) 元数据+简介:curl 'https://api.bilibili.com/x/web-interface/view?bvid=<BV>' → 取 title / desc(简介仅作背景/补充,不满一篇精读)/ owner.name / aid / pages。检查 p <= pages.length,取 selectedPage = pages[p-1](并核对 selectedPage.page === p);越界或该项缺失则 saved=false。选用 selectedPage.cid / selectedPage.part / selectedPage.duration;不能取顶层 cid/duration 代替指定分P。metadata 记录 bvid / page / cid / part / duration,标题包含分P名称,来源 URL 保留 p。\n" +
76
+ " 2) 字幕(**优先,最快**):curl 'https://api.bilibili.com/x/player/v2?aid=<aid>&cid=<selectedPage.cid>' 取 subtitle 列表;若有则下载转文本(textSource=subtitle)——只使用选中分P的字幕\n" +
59
77
  biliNoSubtitle,
60
78
 
61
79
  "若输入是抖音链接/分享口令(douyin.com / v.douyin.com):用户分享时复制的文字本身就是该视频的文案(desc)。" + douyinTail,
@@ -66,11 +84,13 @@ module.exports = {
66
84
  if (wantTranscribe) {
67
85
  steps.push(
68
86
  "转写执行(faster-whisper " + whisperModel + " / int8 / " + language + ",镜像+缓存,保证本机与用户一致):\n" +
69
- " ① 先取音频:B站用 playurl(curl 'https://api.bilibili.com/x/player/playurl?avid=<aid>&cid=<cid>&fnval=16&fourk=1' 的 dash.audio[0].baseUrl)或 yt-dlp,下载存到 '" + tempDir + "/audio.m4a';\n" +
70
- " ② 定位插件转写脚本(文件名固定 `transcribe.js`):Windows 用 `Get-ChildItem -Path $env:USERPROFILE/.dsh -Recurse -Filter transcribe.js`;macOS/Linux 用 `find \"$HOME/.dsh\" -name transcribe.js`(也可直接用 glob 搜 *transcribe.js);\n" +
71
- " ③ 运行(**三平台命令行完全一致**,脚本是 Node 写的,与 pwsh / bash 无关):`node <脚本路径> --audio '" + tempDir + "/audio.m4a' --out '" + tempDir + "/transcript.txt' --device " + device + " --model " + whisperModel + " --language " + language + (includeTimestamps ? " --timestamps" : "") + "`;\n" +
72
- " ④ 转写可能较慢:可用 run_in_background: true 启动,但必须跟踪**本次启动的进程**直到结束;只有确认**本次进程退出码为 0**,且本次目标文件 '" + tempDir + "/transcript.txt' 存在并非空,才算成功。脚本先写本次独有的暂存文件,校验后才原子发布目标文件;**不要仅凭文件非空/稳定或日志出现 DONE 判断完成,不要复用其他任务或上次运行的逐字稿**。设合理超时,超时则终止本次进程;超时/非 0 退出/空产物均按降级处理;\n" +
73
- " ⑤ 成功后读取 transcript.txt 作为全文(textSource=transcription)。脚本自举:uv 建 Python 3.12 环境 + 镜像装 faster-whisper + hf-mirror 下模型并缓存;Windows/macOS/Linux 是**同一份实现**。**⚠️ 首次转写会先下载模型(small 约 484MB,hf-mirror,非 GitHub)并较慢——先向用户说明这是正常的一次性下载,勿当成卡死;之后缓存复用、秒开。**\n" +
87
+ " ① 先取音频:B站用 playurl(curl 'https://api.bilibili.com/x/player/playurl?avid=<aid>&cid=<selectedPage.cid>&fnval=16&fourk=1' 的 dash.audio[0].baseUrl)或 yt-dlp,下载存到 '" + tempDir + "/audio.m4a';B站必须使用上面选中的 selectedPage.cid,yt-dlp 也必须保留指定分P,禁止改用第1P;\n" +
88
+ (scriptPath
89
+ ? " ② 插件已定位本版本转写脚本:" + JSON.stringify(scriptPath) + "。直接使用这个文件;不要递归搜索其他安装目录或选取其他版本。路径是 JSON 字符串数据,执行前按当前 shell 规则正确引用(空格/引号/美元符号等不能作为命令解释);\n"
90
+ : " ② 定位插件转写脚本(文件名固定 `transcribe.js`):Windows 用 `Get-ChildItem -Path $env:USERPROFILE/.dsh -Recurse -Filter transcribe.js`;macOS/Linux 用 `find \"$HOME/.dsh\" -name transcribe.js`(也可直接用 glob 搜 *transcribe.js);\n") +
91
+ " ③ 运行(**三平台命令行完全一致**,脚本是 Node 写的,与 pwsh / bash 无关):`node " + scriptCommand + " --audio '" + tempDir + "/audio.m4a' --out '" + tempDir + "/transcript.txt' --device " + device + " --model " + whisperModel + " --language " + language + " --cpu-threads " + cpuThreads + (useTranscriptCache ? "" : " --no-cache") + (includeTimestamps ? " --timestamps" : "") + "`;\n" +
92
+ " ④ 转写可能较慢:可用 run_in_background: true 启动,但必须跟踪**本次启动的进程**直到结束;只有确认**本次进程退出码为 0**,且本次目标文件 '" + tempDir + "/transcript.txt' 存在并非空,才算成功。脚本先写本次独有的暂存文件,校验后才原子发布目标文件;**不要仅凭文件非空/稳定或日志出现 DONE 判断完成,不要自行复用其他任务或上次运行的逐字稿**。仅脚本可以按音频 SHA-256、环境/模型快照和解码配置验证逐字稿缓存,命中后仍发布本次产物;缓存不能代替后续精读和独立原文核验。记录脚本输出的 metrics(cacheHit、实际 device、阶段毫秒耗时),不要推测不存在的计时。设合理超时,超时则终止本次进程;超时/非 0 退出/空产物均按降级处理;\n" +
93
+ " ⑤ 成功后读取 transcript.txt 作为全文(textSource=transcription)。脚本自举:uv 建 Python 3.12 环境 + 镜像装 faster-whisper + hf-mirror 下模型并缓存;Windows/macOS/Linux 是**同一份实现**。**⚠️ 首次转写会先下载模型(small 约 484MB,hf-mirror,非 GitHub)并较慢——先向用户说明这是正常的一次性下载,勿当成卡死;之后复用模型文件,新音频仍需推理。**\n" +
74
94
  " ⑥ 若 `node` 不在 PATH(macOS 从图形界面启动时常见),先用 `command -v node` 确认;确认不可用就直接降级,不要为了跑转写脚本去安装 Node。"
75
95
  );
76
96
  } else {