@cloud411716/fancy-webnovel 4.7.2 → 4.8.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.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * fancy-douyin — crawl Douyin image-text works into the material library.
2
+ * fancy-douyin — crawl Douyin image-text and video works into the material library.
3
3
  *
4
4
  * Commands:
5
5
  * /fancy-douyin crawl every recorded account
@@ -32,13 +32,19 @@ import {
32
32
  readCrawled,
33
33
  removeAccount,
34
34
  } from './state.js';
35
- import { analysisPrompt, helpText, loginQuestion, summaryText } from './templates.js';
35
+ import { analysisPrompt, capabilityPrompt, helpText, loginQuestion, summaryText, videoAnalysisPrompt, videoRelevancePrompt } from './templates.js';
36
36
 
37
37
  export const inject = ['commands', 'userQuestions'];
38
38
 
39
39
  const ANALYSIS_TIMEOUT_MS = 20 * 60 * 1000;
40
40
  const ANALYSIS_IDLE_GRACE_MS = 60 * 1000;
41
+ const CAPABILITY_TIMEOUT_MS = 5 * 60 * 1000;
42
+ const CAPABILITY_IDLE_GRACE_MS = 30 * 1000;
43
+ const RELEVANCE_TIMEOUT_MS = 5 * 60 * 1000;
44
+ const RELEVANCE_IDLE_GRACE_MS = 30 * 1000;
41
45
  const SCRIPT_TIMEOUT_MS = 4 * 60 * 1000;
46
+ const VIDEO_SCRIPT_TIMEOUT_MS = 10 * 60 * 1000;
47
+ const MAX_VIDEO_SECONDS = 60;
42
48
  const LOGIN_RETRIES = 5;
43
49
  const NOTE_DELAY_MIN_MS = 6000;
44
50
  const NOTE_DELAY_MAX_MS = 12000;
@@ -56,6 +62,10 @@ function sleep(ms) {
56
62
  return new Promise((resolve) => setTimeout(resolve, ms));
57
63
  }
58
64
 
65
+ function authFailureText(text) {
66
+ return /登录|验证|login_required/i.test(String(text || ''));
67
+ }
68
+
59
69
  function abortRequested(invocation) {
60
70
  return Boolean(invocation && invocation.signal && invocation.signal.aborted);
61
71
  }
@@ -132,9 +142,9 @@ async function stopChrome(root, tools, paths) {
132
142
  } catch { /* best effort */ }
133
143
  }
134
144
 
135
- async function runWithLogin(ctx, invocation, session, root, toolPath, args, outDir, paths, label, nodePath, browser, tools) {
145
+ async function runWithLogin(ctx, invocation, session, root, toolPath, args, outDir, paths, label, nodePath, browser, tools, timeout = SCRIPT_TIMEOUT_MS) {
136
146
  for (let attempt = 1; attempt <= LOGIN_RETRIES; attempt += 1) {
137
- const { result, json } = await runTool(toolPath, args, { root, nodePath });
147
+ const { result, json } = await runTool(toolPath, args, { root, nodePath, timeout });
138
148
  if (json && json.login_required) {
139
149
  if (browser.mode === 'headless') {
140
150
  // Headless cannot show a login UI. Close it, start headed Chrome and
@@ -247,14 +257,18 @@ export async function importOtherMaterials(root, file) {
247
257
  try {
248
258
  for (const record of records) {
249
259
  try {
250
- await db.create(new RecordId('material', record.id)).content({
260
+ const content = {
251
261
  source: 'other',
252
262
  kind: record.kind,
253
263
  name: record.name,
254
264
  tags: record.tags,
255
265
  genres: record.genres,
256
266
  note: typeof record.note === 'string' ? record.note : '',
257
- });
267
+ };
268
+ if (typeof record.subkind === 'string' && record.subkind.trim()) {
269
+ content.subkind = record.subkind.trim();
270
+ }
271
+ await db.create(new RecordId('material', record.id)).content(content);
258
272
  inserted += 1;
259
273
  } catch (err) {
260
274
  if (DUPLICATE_RE.test(err && err.message ? err.message : String(err))) {
@@ -272,11 +286,11 @@ export async function importOtherMaterials(root, file) {
272
286
 
273
287
  function retryPrompt(target, detail) {
274
288
  return [
275
- '上一批素材文件没有通过校验。',
289
+ '上一批素材文件没有通过检查。',
276
290
  '',
277
291
  '目标文件:`' + target + '`',
278
292
  '',
279
- '校验错误:',
293
+ '问题:',
280
294
  '```text',
281
295
  String(detail || '').trim(),
282
296
  '```',
@@ -287,18 +301,163 @@ function retryPrompt(target, detail) {
287
301
  ].join('\n');
288
302
  }
289
303
 
290
- async function analyzeNote(ctx, invocation, session, {
291
- root, note, screenshots, target, materialTools, paths, taskList,
304
+ export function expectedItemCount(title) {
305
+ const match = String(title || '').match(/(\d+)\s*\+?\s*(?:个|种|条)/);
306
+ if (!match) return 0;
307
+ const count = Number(match[1]);
308
+ return Number.isFinite(count) && count >= 5 ? count : 0;
309
+ }
310
+
311
+ const CJK_RE = /[\u3400-\u9fff\uf900-\ufaff]/;
312
+
313
+ /**
314
+ * 抖音素材的 kind 必须是中文作品主题,方便 LLM 直接用中文查询。
315
+ * 旧提示词会把 kind 写成 color_word / person_appearance,导致按中文查不到,
316
+ * 所以这里做一次硬校验,发现英文 kind 就带着错误重试。
317
+ */
318
+ export function kindLanguageProblem(file) {
319
+ let records;
320
+ try {
321
+ records = readJsonl(file);
322
+ } catch {
323
+ return '';
324
+ }
325
+ const bad = records
326
+ .map((record) => (typeof record.kind === 'string' ? record.kind.trim() : ''))
327
+ .filter((kind) => kind && !CJK_RE.test(kind));
328
+ if (!bad.length) return '';
329
+ return '以下素材的 kind 不是中文:' + [...new Set(bad)].slice(0, 8).join('、')
330
+ + '。抖音 source=other 素材的 kind 必须写中文作品主题(如 唇色、瞳色、特殊体质),'
331
+ + '不要写 color_word、person_appearance 这类英文内部标识。请改写后重新写入同一个文件。';
332
+ }
333
+
334
+ /**
335
+ * 清单类作品(标题里写“100个/100种”)必须按条目数量逐条提取,
336
+ * 并额外产出 10 条同 kind + 同 subkind 的扩写素材。
337
+ * 只有格式校验不够:模型可能只提炼了 20 条创作句,却完全漏掉原清单。
338
+ */
339
+ export function coverageProblem(file, title) {
340
+ const expected = expectedItemCount(title);
341
+ if (!expected) return '';
342
+ const required = expected + 10;
343
+ let records;
344
+ try {
345
+ records = readJsonl(file);
346
+ } catch {
347
+ return '';
348
+ }
349
+ if (records.length >= required) return '';
350
+ return '作品标题写着 ' + expected + ' 条清单,加上同 kind + 同 subkind 的 10 条扩写素材,'
351
+ + '至少应有 ' + required + ' 条,但当前只有 ' + records.length
352
+ + ' 条。清单类内容必须逐条输出:name 保留原文条目,不要只提炼一部分或改写成意象句;'
353
+ + '补全原始条目和 10 条扩写素材后,重新写入同一个文件。';
354
+ }
355
+
356
+ function parseFirstJsonObject(text) {
357
+ let cleaned = String(text || '').replace(/^\uFEFF/, '').trim();
358
+ cleaned = cleaned
359
+ .replace(/^```(?:json)?\s*/i, '')
360
+ .replace(/\s*```$/, '')
361
+ .trim();
362
+ if (!cleaned) return null;
363
+ const candidates = [cleaned, cleaned.split(/\r?\n/).find((line) => line.trim()) || ''];
364
+ for (const candidate of candidates) {
365
+ try {
366
+ const value = JSON.parse(candidate.trim());
367
+ if (value && typeof value === 'object' && !Array.isArray(value)) return value;
368
+ } catch { /* try next */ }
369
+ }
370
+ return null;
371
+ }
372
+
373
+ function truthyFlag(value) {
374
+ return value === true || String(value).toLowerCase() === 'true';
375
+ }
376
+
377
+ /**
378
+ * Parse the capability self-check file. Missing fields default to false so a
379
+ * malformed answer never silently enables a modality the model cannot handle.
380
+ */
381
+ export function parseCapabilityResult(text) {
382
+ const data = parseFirstJsonObject(text);
383
+ if (!data) return null;
384
+ return {
385
+ image_supported: truthyFlag(data.image_supported),
386
+ video_supported: truthyFlag(data.video_supported),
387
+ reason: typeof data.reason === 'string' ? data.reason.trim() : '',
388
+ };
389
+ }
390
+
391
+ /**
392
+ * Read the first-5-seconds relevance marker written by the LLM.
393
+ * Returns null when the file is missing/unparseable, so the caller can retry.
394
+ */
395
+ export function readRelevanceMarker(file) {
396
+ let text;
397
+ try {
398
+ text = fs.readFileSync(file, 'utf8');
399
+ } catch {
400
+ return null;
401
+ }
402
+ const data = parseFirstJsonObject(text);
403
+ if (!data) return null;
404
+ if (truthyFlag(data.skip)) {
405
+ return { skip: true, reason: String(data.reason || '前 5 秒与网文创作无关').trim() };
406
+ }
407
+ if (truthyFlag(data.relevant) || truthyFlag(data.related)) {
408
+ return { skip: false, reason: String(data.reason || '').trim() };
409
+ }
410
+ return null;
411
+ }
412
+
413
+ async function detectCapabilities(ctx, invocation, session, taskList, root, runDir) {
414
+ const file = path.join(runDir, 'capabilities.json');
415
+ try { fs.rmSync(file, { force: true }); } catch { /* ignore */ }
416
+ taskList.watchTurns(invocation);
417
+ let before = null;
418
+ for (let attempt = 1; attempt <= 2; attempt += 1) {
419
+ const sent = await llmFollowup(invocation, capabilityPrompt({ capabilityFile: file }), {
420
+ appendTempRule: false,
421
+ });
422
+ if (!sent || sent.ok !== true) {
423
+ return {
424
+ ok: false,
425
+ error: '能力自检提示词发送失败:' + ((sent && sent.error) || '未知错误'),
426
+ };
427
+ }
428
+ const waitForTurn = makeWaitForTurn(invocation, {
429
+ timeoutMs: CAPABILITY_TIMEOUT_MS,
430
+ idleGraceMs: CAPABILITY_IDLE_GRACE_MS,
431
+ signal: invocation.signal,
432
+ changed: (files, baseline) => {
433
+ try {
434
+ const text = fs.readFileSync(files[0], 'utf8');
435
+ return baseline === null || baseline === undefined ? text.trim().length > 0 : text !== baseline;
436
+ } catch {
437
+ return false;
438
+ }
439
+ },
440
+ });
441
+ const waited = await waitForTurn([file], before);
442
+ if (waited && waited.ok) {
443
+ let text = '';
444
+ try { text = fs.readFileSync(file, 'utf8'); } catch { /* retry */ }
445
+ const parsed = parseCapabilityResult(text);
446
+ if (parsed) return { ok: true, ...parsed };
447
+ before = text || null;
448
+ continue;
449
+ }
450
+ if (waited && waited.code === 'ABORTED') {
451
+ return { ok: false, aborted: true, error: '用户中断' };
452
+ }
453
+ try { before = fs.readFileSync(file, 'utf8'); } catch { before = null; }
454
+ }
455
+ return { ok: false, error: 'LLM 没有返回可解析的能力自检结果' };
456
+ }
457
+
458
+ async function analyzeMaterials(ctx, invocation, session, {
459
+ root, prompt, target, title, materialTools, taskList,
292
460
  }) {
293
- const prompt = analysisPrompt({
294
- accountUrl: note.account_url,
295
- note,
296
- screenshots,
297
- targetFile: target,
298
- workspace: root,
299
- queryScript: materialTools.queryScript,
300
- validateScript: materialTools.validateScript,
301
- });
302
461
  const waitForTurn = makeWaitForTurn(invocation, {
303
462
  timeoutMs: ANALYSIS_TIMEOUT_MS,
304
463
  idleGraceMs: ANALYSIS_IDLE_GRACE_MS,
@@ -360,6 +519,16 @@ async function analyzeNote(ctx, invocation, session, {
360
519
  detail = checked.detail;
361
520
  continue;
362
521
  }
522
+ const kindProblem = kindLanguageProblem(target);
523
+ if (kindProblem) {
524
+ detail = kindProblem;
525
+ continue;
526
+ }
527
+ const coverage = coverageProblem(target, title);
528
+ if (coverage) {
529
+ detail = coverage;
530
+ continue;
531
+ }
363
532
  try {
364
533
  const result = await importOtherMaterials(root, target);
365
534
  return { ok: true, ...result };
@@ -370,6 +539,98 @@ async function analyzeNote(ctx, invocation, session, {
370
539
  return { ok: false, error: '素材没有通过校验:' + detail };
371
540
  }
372
541
 
542
+ async function analyzeNote(ctx, invocation, session, {
543
+ root, note, screenshots, target, materialTools, paths, taskList,
544
+ }) {
545
+ const prompt = analysisPrompt({
546
+ accountUrl: note.account_url,
547
+ note,
548
+ screenshots,
549
+ targetFile: target,
550
+ workspace: root,
551
+ queryScript: materialTools.queryScript,
552
+ validateScript: materialTools.validateScript,
553
+ });
554
+ return analyzeMaterials(ctx, invocation, session, {
555
+ root,
556
+ prompt,
557
+ target,
558
+ title: note.title,
559
+ materialTools,
560
+ taskList,
561
+ });
562
+ }
563
+
564
+ async function analyzeVideoRelevance(ctx, invocation, session, {
565
+ root, accountUrl, video, target, taskList,
566
+ }) {
567
+ const file = path.join(video.dir, 'relevance.json');
568
+ try { fs.rmSync(file, { force: true }); } catch { /* ignore */ }
569
+ taskList.watchTurns(invocation);
570
+ const prompt = videoRelevancePrompt({
571
+ accountUrl,
572
+ video,
573
+ firstFrames: video.first5s || [],
574
+ targetFile: file,
575
+ });
576
+ let before = null;
577
+ for (let attempt = 1; attempt <= 2; attempt += 1) {
578
+ const sent = await llmFollowup(invocation, attempt === 1 ? prompt : prompt + '\n\n上一次没有写出可解析的 relevance.json,请重新判断并覆盖写入同一个路径。', {
579
+ appendTempRule: false,
580
+ });
581
+ if (!sent || sent.ok !== true) {
582
+ return { ok: false, error: '前 5 秒判断提示词发送失败:' + ((sent && sent.error) || '未知错误') };
583
+ }
584
+ const waitForTurn = makeWaitForTurn(invocation, {
585
+ timeoutMs: RELEVANCE_TIMEOUT_MS,
586
+ idleGraceMs: RELEVANCE_IDLE_GRACE_MS,
587
+ signal: invocation.signal,
588
+ changed: (files, baseline) => {
589
+ try {
590
+ const text = fs.readFileSync(files[0], 'utf8');
591
+ return baseline === null || baseline === undefined ? text.trim().length > 0 : text !== baseline;
592
+ } catch {
593
+ return false;
594
+ }
595
+ },
596
+ });
597
+ const waited = await waitForTurn([file], before);
598
+ if (waited && waited.ok) {
599
+ const marker = readRelevanceMarker(file);
600
+ if (marker) return { ok: true, ...marker };
601
+ try { before = fs.readFileSync(file, 'utf8'); } catch { before = null; }
602
+ continue;
603
+ }
604
+ if (waited && waited.code === 'ABORTED') {
605
+ return { ok: false, aborted: true, error: '用户中断' };
606
+ }
607
+ try { before = fs.readFileSync(file, 'utf8'); } catch { before = null; }
608
+ }
609
+ return { ok: false, error: '前 5 秒相关性判断没有返回可解析结果' };
610
+ }
611
+
612
+ async function analyzeVideo(ctx, invocation, session, {
613
+ root, accountUrl, video, target, materialTools, taskList,
614
+ }) {
615
+ const prompt = videoAnalysisPrompt({
616
+ accountUrl,
617
+ video,
618
+ frames: video.frames || [],
619
+ targetFile: target,
620
+ workspace: root,
621
+ queryScript: materialTools.queryScript,
622
+ validateScript: materialTools.validateScript,
623
+ });
624
+ return analyzeMaterials(ctx, invocation, session, {
625
+ root,
626
+ prompt,
627
+ target,
628
+ title: video.title,
629
+ materialTools,
630
+ taskList,
631
+ });
632
+ }
633
+
373
634
  async function runCrawl(ctx, invocation, session, taskList) {
374
635
  const root = workspaceOf(session);
375
636
  const paths = ensureDouyinDir(root);
@@ -378,6 +639,25 @@ async function runCrawl(ctx, invocation, session, taskList) {
378
639
  return notify(session, 'error', '还没有记录抖音账号。先运行:/fancy-douyin add <主页地址>');
379
640
  }
380
641
 
642
+ const runDir = path.join(paths.output, stampOfNow());
643
+ fs.mkdirSync(runDir, { recursive: true });
644
+
645
+ // 先做能力自检:如果模型既不能看图也不能看视频,直接退出,
646
+ // 不启动 Chrome,也不扫描账号。
647
+ taskList.advance(1);
648
+ taskList.progress('LLM 能力自检(图片 / 视频)');
649
+ const capabilities = await detectCapabilities(ctx, invocation, session, taskList, root, runDir);
650
+ if (!capabilities.ok) {
651
+ return notify(session, 'error', '❌ LLM 能力自检失败:' + capabilities.error);
652
+ }
653
+ if (!capabilities.image_supported && !capabilities.video_supported) {
654
+ return notify(session, 'error', [
655
+ '❌ 当前模型既没有图片识别能力,也没有视频识别能力,已退出。',
656
+ capabilities.reason ? '模型说明:' + capabilities.reason : '',
657
+ '请切换到支持视觉识别的模型后重试。',
658
+ ].filter(Boolean).join('\n'));
659
+ }
660
+
381
661
  const tools = deployDouyinTools(root);
382
662
  if (!tools.ok) {
383
663
  return notify(session, 'error', '❌ 部署抖音脚本失败:\n' + (tools.problems.join('\n') || '未知错误'));
@@ -394,19 +674,21 @@ async function runCrawl(ctx, invocation, session, taskList) {
394
674
  return notify(session, 'error', '❌ 启动 Chrome 失败:' + started.error);
395
675
  }
396
676
  const browser = { cdp: started.cdp, mode: started.mode };
397
- taskList.advance(1);
677
+ taskList.advance(2);
398
678
  taskList.watchTurns(invocation);
399
679
 
400
680
  try {
401
- const runDir = path.join(paths.output, stampOfNow());
402
- fs.mkdirSync(runDir, { recursive: true });
403
681
  const crawled = readCrawled(root);
404
682
  const failures = [];
405
683
  let scannedAccounts = 0;
406
684
  let foundNotes = 0;
685
+ let foundVideos = 0;
407
686
  let skippedNotes = 0;
408
- let processedNotes = 0;
687
+ let skippedNotesByCapability = 0;
688
+ let skippedVideosByCapability = 0;
689
+ let processedWorks = 0;
409
690
  let skippedIrrelevant = 0;
691
+ let skippedLongVideos = 0;
410
692
  let inserted = 0;
411
693
  let skippedMaterials = 0;
412
694
  let aborted = false;
@@ -415,6 +697,23 @@ async function runCrawl(ctx, invocation, session, taskList) {
415
697
  for (const account of accounts) {
416
698
  if (abortRequested(invocation)) { aborted = true; break; }
417
699
  const accountDir = path.join(runDir, accountSlug(account.url));
700
+ const markFailed = (id, card, data, reason) => {
701
+ if (!id) return;
702
+ markCrawled(root, id, {
703
+ account_url: account.url,
704
+ url: data.url || card.href,
705
+ title: data.title || card.text || '',
706
+ type: data.type,
707
+ duration: data.duration,
708
+ dir: data.dir,
709
+ inserted: 0,
710
+ skipped: 0,
711
+ skip: true,
712
+ failed: true,
713
+ reason,
714
+ });
715
+ crawled[id] = true;
716
+ };
418
717
  const scan = await runWithLogin(
419
718
  ctx, invocation, session, root, tools.scripts.scan,
420
719
  ['--workspace', root, '--account', account.url, '--cdp', browser.cdp,
@@ -428,16 +727,23 @@ async function runCrawl(ctx, invocation, session, taskList) {
428
727
  );
429
728
  if (!scan.ok) {
430
729
  failures.push({ url: account.url, reason: scan.error });
431
- if (scan.cancelled) { aborted = true; break; }
730
+ if (scan.cancelled || authFailureText(scan.error)) { aborted = true; break; }
432
731
  continue;
433
732
  }
434
733
 
435
734
  scannedAccounts += 1;
436
735
  const notes = Array.isArray(scan.json.notes) ? scan.json.notes : [];
736
+ const videos = Array.isArray(scan.json.videos) ? scan.json.videos : [];
437
737
  foundNotes += notes.length;
438
- taskList.advance(2);
738
+ foundVideos += videos.length;
739
+ taskList.advance(3);
740
+
439
741
  for (const card of notes) {
440
742
  if (abortRequested(invocation)) { aborted = true; break outer; }
743
+ if (!capabilities.image_supported) {
744
+ skippedNotesByCapability += 1;
745
+ continue;
746
+ }
441
747
  const noteId = noteIdFromUrl(card.href);
442
748
  if (!noteId) continue;
443
749
  if (crawled[noteId]) {
@@ -451,25 +757,27 @@ async function runCrawl(ctx, invocation, session, taskList) {
451
757
  '--out', noteDir, '--login-state', paths.loginState],
452
758
  noteDir,
453
759
  paths,
454
- '采集作品',
760
+ '采集图文作品',
455
761
  tools.nodePath,
456
762
  browser,
457
763
  tools,
458
764
  );
459
765
  if (!noteResult.ok) {
460
766
  failures.push({ id: noteId, url: card.href, reason: noteResult.error });
461
- if (noteResult.cancelled) { aborted = true; break outer; }
767
+ if (noteResult.cancelled || authFailureText(noteResult.error)) { aborted = true; break outer; }
768
+ markFailed(noteId, card, { type: 'note', dir: noteDir }, noteResult.error);
462
769
  continue;
463
770
  }
464
771
  const note = noteResult.json.note;
465
772
  if (!note || !Array.isArray(note.screenshots) || !note.screenshots.length) {
466
773
  failures.push({ id: noteId, url: card.href, reason: '没有截图' });
774
+ markFailed(noteId, card, { type: 'note', dir: noteDir }, '没有截图');
467
775
  continue;
468
776
  }
469
- processedNotes += 1;
777
+ processedWorks += 1;
470
778
  note.account_url = account.url;
471
779
  const target = path.join(noteDir, 'materials.jsonl');
472
- taskList.advance(3);
780
+ taskList.advance(4);
473
781
  taskList.progress(`LLM 整理图文素材(${note.title || noteId})`);
474
782
  const analyzed = await analyzeNote(ctx, invocation, session, {
475
783
  root,
@@ -484,6 +792,7 @@ async function runCrawl(ctx, invocation, session, taskList) {
484
792
  failures.push({ id: noteId, url: card.href, reason: analyzed.error });
485
793
  if (analyzed.aborted) { aborted = true; break outer; }
486
794
  if (analyzed.fatal) break outer;
795
+ markFailed(noteId, card, { type: 'note', dir: noteDir, title: note.title }, analyzed.error);
487
796
  continue;
488
797
  }
489
798
  if (analyzed.skipped) {
@@ -492,6 +801,7 @@ async function runCrawl(ctx, invocation, session, taskList) {
492
801
  account_url: account.url,
493
802
  url: note.url || card.href,
494
803
  title: note.title || card.text || '',
804
+ type: 'note',
495
805
  screenshots: note.screenshots.map((shot) => shot.file),
496
806
  dir: noteDir,
497
807
  inserted: 0,
@@ -506,6 +816,7 @@ async function runCrawl(ctx, invocation, session, taskList) {
506
816
  account_url: account.url,
507
817
  url: note.url || card.href,
508
818
  title: note.title || card.text || '',
819
+ type: 'note',
509
820
  screenshots: note.screenshots.map((shot) => shot.file),
510
821
  dir: noteDir,
511
822
  inserted: analyzed.inserted,
@@ -518,16 +829,162 @@ async function runCrawl(ctx, invocation, session, taskList) {
518
829
  await sleep(delay);
519
830
  }
520
831
  }
832
+
833
+ for (const card of videos) {
834
+ if (abortRequested(invocation)) { aborted = true; break outer; }
835
+ if (!capabilities.video_supported) {
836
+ skippedVideosByCapability += 1;
837
+ continue;
838
+ }
839
+ const videoId = noteIdFromUrl(card.href);
840
+ if (!videoId) continue;
841
+ if (crawled[videoId]) {
842
+ skippedNotes += 1;
843
+ continue;
844
+ }
845
+ const videoDir = path.join(accountDir, videoId);
846
+ const videoResult = await runWithLogin(
847
+ ctx, invocation, session, root, tools.scripts.video,
848
+ ['--workspace', root, '--video', card.href, '--cdp', browser.cdp,
849
+ '--out', videoDir, '--login-state', paths.loginState,
850
+ '--max-seconds', String(MAX_VIDEO_SECONDS)],
851
+ videoDir,
852
+ paths,
853
+ '采集视频作品',
854
+ tools.nodePath,
855
+ browser,
856
+ tools,
857
+ VIDEO_SCRIPT_TIMEOUT_MS,
858
+ );
859
+ if (!videoResult.ok) {
860
+ failures.push({ id: videoId, url: card.href, reason: videoResult.error });
861
+ if (videoResult.cancelled || authFailureText(videoResult.error)) { aborted = true; break outer; }
862
+ markFailed(videoId, card, { type: 'video', dir: videoDir }, videoResult.error);
863
+ continue;
864
+ }
865
+ const video = videoResult.json.video || {};
866
+ if (videoResult.json.skip) {
867
+ skippedLongVideos += 1;
868
+ markCrawled(root, videoId, {
869
+ account_url: account.url,
870
+ url: video.url || card.href,
871
+ title: video.title || card.text || '',
872
+ type: 'video',
873
+ duration: video.duration,
874
+ dir: videoDir,
875
+ inserted: 0,
876
+ skipped: 0,
877
+ skip: true,
878
+ reason: videoResult.json.reason || '视频时长超过 1 分钟',
879
+ });
880
+ crawled[videoId] = true;
881
+ continue;
882
+ }
883
+ if (!video || !Array.isArray(video.frames) || !video.frames.length) {
884
+ failures.push({ id: videoId, url: card.href, reason: '没有视频关键帧' });
885
+ markFailed(videoId, card, { type: 'video', dir: videoDir, title: video.title }, '没有视频关键帧');
886
+ continue;
887
+ }
888
+ processedWorks += 1;
889
+ video.account_url = account.url;
890
+ const target = path.join(videoDir, 'materials.jsonl');
891
+ taskList.advance(4);
892
+ taskList.progress(`LLM 判断视频前 5 秒(${video.title || videoId})`);
893
+ const relevance = await analyzeVideoRelevance(ctx, invocation, session, {
894
+ root,
895
+ accountUrl: account.url,
896
+ video,
897
+ target,
898
+ taskList,
899
+ });
900
+ if (!relevance.ok) {
901
+ failures.push({ id: videoId, url: card.href, reason: relevance.error });
902
+ if (relevance.aborted) { aborted = true; break outer; }
903
+ markFailed(videoId, card, { type: 'video', dir: videoDir, title: video.title, duration: video.duration }, relevance.error);
904
+ continue;
905
+ }
906
+ if (relevance.skip) {
907
+ skippedIrrelevant += 1;
908
+ markCrawled(root, videoId, {
909
+ account_url: account.url,
910
+ url: video.url || card.href,
911
+ title: video.title || card.text || '',
912
+ type: 'video',
913
+ duration: video.duration,
914
+ dir: videoDir,
915
+ inserted: 0,
916
+ skipped: 0,
917
+ skip: true,
918
+ reason: relevance.reason || '前 5 秒与网文创作无关',
919
+ });
920
+ crawled[videoId] = true;
921
+ continue;
922
+ }
923
+
924
+ taskList.progress(`LLM 整理视频素材(${video.title || videoId})`);
925
+ const analyzed = await analyzeVideo(ctx, invocation, session, {
926
+ root,
927
+ accountUrl: account.url,
928
+ video,
929
+ target,
930
+ materialTools,
931
+ taskList,
932
+ });
933
+ if (!analyzed.ok) {
934
+ failures.push({ id: videoId, url: card.href, reason: analyzed.error });
935
+ if (analyzed.aborted) { aborted = true; break outer; }
936
+ if (analyzed.fatal) break outer;
937
+ markFailed(videoId, card, { type: 'video', dir: videoDir, title: video.title, duration: video.duration }, analyzed.error);
938
+ continue;
939
+ }
940
+ if (analyzed.skipped) {
941
+ skippedIrrelevant += 1;
942
+ markCrawled(root, videoId, {
943
+ account_url: account.url,
944
+ url: video.url || card.href,
945
+ title: video.title || card.text || '',
946
+ type: 'video',
947
+ duration: video.duration,
948
+ dir: videoDir,
949
+ inserted: 0,
950
+ skipped: 0,
951
+ skip: true,
952
+ reason: analyzed.reason || '与网文创作无关',
953
+ });
954
+ } else {
955
+ inserted += analyzed.inserted;
956
+ skippedMaterials += analyzed.skipped;
957
+ markCrawled(root, videoId, {
958
+ account_url: account.url,
959
+ url: video.url || card.href,
960
+ title: video.title || card.text || '',
961
+ type: 'video',
962
+ duration: video.duration,
963
+ dir: videoDir,
964
+ inserted: analyzed.inserted,
965
+ skipped: analyzed.skipped,
966
+ });
967
+ }
968
+ crawled[videoId] = true;
969
+ if (NOTE_DELAY_MIN_MS < NOTE_DELAY_MAX_MS) {
970
+ const delay = NOTE_DELAY_MIN_MS + Math.floor(Math.random() * (NOTE_DELAY_MAX_MS - NOTE_DELAY_MIN_MS));
971
+ await sleep(delay);
972
+ }
973
+ }
521
974
  }
522
975
 
523
- taskList.advance(4);
976
+ taskList.advance(5);
524
977
  return notify(session, (aborted || failures.length) ? 'error' : 'success', summaryText({
525
978
  accounts: accounts.length,
526
979
  scannedAccounts,
527
980
  foundNotes,
981
+ foundVideos,
982
+ skippedNotesByCapability,
983
+ skippedVideosByCapability,
528
984
  skippedNotes,
529
- processedNotes,
985
+ processedNotes: processedWorks,
530
986
  skippedIrrelevant,
987
+ skippedLongVideos,
531
988
  inserted,
532
989
  skippedMaterials,
533
990
  failures,
@@ -580,13 +1037,20 @@ function douyinTaskTitles(invocation) {
580
1037
  if (command === 'add') return ['解析主页地址', '保存账号'];
581
1038
  if (command === 'list') return ['读取账号列表'];
582
1039
  if (command === 'remove') return ['解析目标账号', '删除账号'];
583
- return ['检查浏览器与素材库', '扫描账号主页', '采集笔记图片', 'LLM 整理图文素材', '写入素材库'];
1040
+ return [
1041
+ '检查账号与素材库',
1042
+ 'LLM 能力自检(图片 / 视频)',
1043
+ '扫描账号主页',
1044
+ '采集图文 / 视频作品',
1045
+ 'LLM 整理素材',
1046
+ '写入素材库',
1047
+ ];
584
1048
  }
585
1049
 
586
1050
  export async function apply(ctx) {
587
1051
  registerCommandWithTasks(ctx, {
588
1052
  name: 'fancy-douyin',
589
- description: '🎬 抖音图文采集 ( usage: /fancy-douyin [add <主页> | list | remove <序号|地址> | help] )',
1053
+ description: '🎬 抖音素材采集 ( usage: /fancy-douyin [add <主页> | list | remove <序号|地址> | help] )',
590
1054
  input: { hint: '[add <主页> | list | remove <序号|地址> | help]' },
591
1055
  handler: async (invocation, taskList) => {
592
1056
  const session = invocation.agent.session;