@cloud411716/fancy-webnovel 4.19.0 → 4.21.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.
@@ -40,7 +40,7 @@ LLM 能力自检(图片 / 视频)
40
40
  → 文章:提取标题、发布日期、阅读时长和正文
41
41
  → 图文:逐页判断类型
42
42
  → 图片页:下载轮播原图并转成 JPG(避免滚动时截到半张图)
43
- → 视频页:下载该页短视频,用 ffmpeg scene 检测 + 固定间隔兜底抽帧,拼成一张关键帧图
43
+ → 视频页:下载该页短视频,密集采样后按稳定画面段抽帧,拼成一张关键帧图
44
44
  → 视频:先判断时长
45
45
  → 超过 1 分钟:直接跳过并记录
46
46
  → 不超过 1 分钟:抽取前 5 秒关键帧,先判断是否与网文创作有关
@@ -91,7 +91,7 @@ cookies 会额外镜像到:
91
91
  ```text
92
92
  <工作区>/.fancy/douyin/
93
93
  ├── accounts.json # 旧版账号文件;首次运行会迁移到 douyin_account 表
94
- ├── crawled.json # 旧版本地记录,仅用于一次性迁移/备份
94
+ ├── crawled.json # 旧版本地记录;仅检测到旧文件时读取迁移,不再生成
95
95
  ├── jobs/<账号>/<作品ID>/ # 稳定作品目录,重启后复用;含截图/关键帧、note.json/video.json/article.json/article.md、materials.jsonl
96
96
  ├── jobs/_runs/<时间>/ # 每次运行的 LLM 能力自检、账号扫描 profile_cards.json、登录门禁截图
97
97
  ├── login-state.json # cookies 镜像(0600)
@@ -143,7 +143,7 @@ FANCY_DOUYIN_SUBAGENTS=0 # 关闭子 Agent,回退单 Agent 串行
143
143
 
144
144
  要求 DSH 挂载了 subagent 服务和 `spawn` provider。没有子 Agent 服务、provider 不存在或并发数为 0 时,会自动回退到原来的单 Agent 流程。
145
145
 
146
- 子 Agent 不操作 Chrome,不修改 `crawled.json`,不运行 `import.js`,也不直接写素材数据库;数据库导入和采集状态只由父进程串行处理,避免并发覆盖。
146
+ 子 Agent 不操作 Chrome,不写本地状态文件,不运行 `import.js`,也不直接写素材数据库;数据库导入和采集状态只由父进程串行处理,避免并发覆盖。
147
147
 
148
148
  采集、分析和入库重叠时,任务列表会同时把“采集作品”“分析素材”“写入素材库”标为进行中:采集行显示已扫描账号数和已入队作品数,分析行显示已分析/已入队和当前并发数,写入行显示已写入/已入队作品数。所有账号采集完成后,“采集作品”才标记完成;“分析素材”和“写入素材库”继续转圈,直到所有作品分析、校验和入库完成。
149
149
 
@@ -192,18 +192,19 @@ id / kind / subkind / name / tags / genres / note / source
192
192
  - `analysis_status`:pending / analyzing / analyzed / failed
193
193
  - `import_status`:pending / imported / skipped / failed
194
194
 
195
- 旧版 `crawled.json` 会在首次运行时一次性迁移到 `douyin_job`,之后数据库是状态源;本地文件只保留作迁移来源和备份。
195
+ 数据库里的 `douyin_job` 是唯一运行时状态源,新版本不再生成 `crawled.json`。如果旧工作区里已经存在这个文件,首次运行仍会把它一次性迁移到 `douyin_job`(已迁移过的由 `douyin_meta` 标记阻止重复导入)。
196
196
 
197
197
  ## 注意
198
198
 
199
199
  - 只采集个人研究/已授权账号,不要批量抓取或二次分发受版权保护的图片、视频和文案。
200
200
  - 图文截图不是页面视口截图,而是下载每页轮播原图后再转成 JPEG,所以不会因为
201
201
  滚动、懒加载或页面动画截到残缺图片。
202
- - 图文作品的轮播可以混合图片页和视频页。视频页会下载该页短视频,用 ffmpeg scene 检测抓画面突变帧,再用固定间隔帧兜底,
203
- 拼成一张关键帧图交给 LLM;这样快速切换的画面和动态字幕/标语不会被封面漏掉。
202
+ - 图文作品的轮播可以混合图片页和视频页。视频页会下载该页短视频,15 秒以内每 0.2 秒采样、15–60 秒每 0.5 秒采样,
203
+ 再按稳定画面段选帧并拼成一张关键帧图交给 LLM;这样快速切换的画面和动态字幕/标语不会被封面漏掉。
204
204
  - 独立视频作品会先尝试下载原片并用 ffmpeg 抽帧;下载失败时退化为播放器元素截图。
205
205
  视频时长超过 1 分钟直接跳过;前 5 秒与网文创作无关也跳过。
206
- - 场景切换点本身常是过渡虚影;插件会在切换后取多个候选帧,用 ffmpeg blurdetect 选择最清晰的一帧,避免把文字尚未完全出现的模糊帧交给 LLM。
206
+ - 场景切换点本身常是过渡虚影。插件会在密集采样后用 ffmpeg blurdetect 给每帧打分,在每个稳定画面段的清晰中段选一帧,避免把文字尚未完全出现的模糊帧交给 LLM。
207
+ - 帧选择版本是 `frame_version: 3`;旧版本缓存的截图/关键帧会自动重新采集。
207
208
  - 子 Agent 或 DSH 在分析途中中断时,作品任务保持 pending;下次运行会复用已采集文件重新分析。旧版本留下的 aborted/failed 任务会在启动采集时自动恢复为 pending。
208
209
  - 抖音 DOM/类名会变,`scan-account.cjs`、`crawl-note.cjs` 和 `crawl-video.cjs`
209
210
  的选择器可能需要维护。
@@ -129,7 +129,7 @@ namespace: fancy
129
129
  跳过,不超过 1 分钟的先看前 5 秒,与网文创作无关也跳过;文章按标题层级拆成原子
130
130
  设定。内容交给 LLM 提取素材,按 material JSONL 写入数据库,`source` 固定为
131
131
  `other`。作品任务状态记录在素材库的 `douyin_job` 表中,旧版工作区的
132
- `/.fancy/douyin/crawled.json` 会一次性迁移。采集完成后可由 DSH 子 Agent 并行分析,`FANCY_DOUYIN_SUBAGENTS` 控制并发数(默认 5,0 关闭);没有 subagent 服务时自动回退单 Agent。
132
+ 旧版 `/.fancy/douyin/crawled.json` 如果存在,会一次性迁移;新版本不再生成该文件。采集完成后可由 DSH 子 Agent 并行分析,`FANCY_DOUYIN_SUBAGENTS` 控制并发数(默认 5,0 关闭);没有 subagent 服务时自动回退单 Agent。
133
133
 
134
134
  登录态保存在工作区 `/.fancy/douyin/chrome-profile/`,并镜像 cookies 到
135
135
  `login-state.json`。首次需要登录时使用有头 Chrome,登录态有效后后续运行自动
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloud411716/fancy-webnovel",
3
- "version": "4.19.0",
3
+ "version": "4.21.0",
4
4
  "type": "module",
5
5
  "main": "index.js",
6
6
  "exports": {
@@ -115,8 +115,8 @@ export function deployDouyinTools(root) {
115
115
  writeToolFile(path.join(target, 'README.txt'), [
116
116
  '本目录由 fancy-douyin 自动部署。',
117
117
  '浏览器脚本:start-chrome.cjs / scan-account.cjs / crawl-note.cjs / crawl-video.cjs / crawl-article.cjs',
118
- '视频抽帧:video-frames.cjs(ffmpeg scene 检测 + 固定间隔兜底)',
119
- '登录态与采集记录在 <工作区>/.fancy/douyin/ 下。',
118
+ '视频抽帧:video-frames.cjs(密集采样 + 稳定画面段 + 清晰度评分)',
119
+ '登录态在 <工作区>/.fancy/douyin/ 下;采集任务状态在素材库 douyin_job 表。',
120
120
  '不要手工修改本目录脚本;重新运行 /fancy-douyin 会刷新。',
121
121
  '',
122
122
  ].join('\n'), problems);
@@ -26,7 +26,6 @@ import {
26
26
  accountSlug,
27
27
  douyinPaths,
28
28
  ensureDouyinDir,
29
- markCrawled,
30
29
  noteIdFromUrl,
31
30
  readCrawled,
32
31
  } from './state.js';
@@ -46,7 +45,7 @@ import {
46
45
 
47
46
  export const inject = ['commands', 'userQuestions'];
48
47
 
49
- const FRAME_SELECTION_VERSION = 2;
48
+ const FRAME_SELECTION_VERSION = 3;
50
49
  const ANALYSIS_TIMEOUT_MS = 20 * 60 * 1000;
51
50
  const ANALYSIS_IDLE_GRACE_MS = 60 * 1000;
52
51
  const CAPABILITY_TIMEOUT_MS = 5 * 60 * 1000;
@@ -765,7 +764,7 @@ function first5sFrameText(video) {
765
764
  export function subagentTaskPrompt(job, root, materialTools) {
766
765
  const lines = [
767
766
  '你是 fancy-douyin 的分析子 Agent,只处理下面这一篇作品。',
768
- '不要扫描账号,不要启动或操作 Chrome,不要修改 crawled.json,不要运行 import.js 或直接写素材数据库。',
767
+ '不要扫描账号,不要启动或操作 Chrome,不要写本地状态文件,不要运行 import.js 或直接写素材数据库。',
769
768
  '只读取给定文件,按提示词提取素材,写入目标 JSONL,运行 validate.js 后结束。',
770
769
  '如果需要创建测试文件,放在当前项目的 `.tmp` 目录下(绝对路径:`' + path.join(root, '.tmp') + '`),并且测试后不需要删除测试文件。',
771
770
  '禁止执行 rm、rmdir、find -delete、git clean 等删除命令,也不要删除已有文件。',
@@ -843,7 +842,7 @@ async function runSubagentAnalysisJob({
843
842
  error: '子 Agent 没有写入目标文件' + (stop ? '(' + stop + ')' : ''),
844
843
  };
845
844
  }
846
- // 文件已经写出,由父进程在串行锁内统一校验、导入和写 crawled.json。
845
+ // 文件已经写出,由父进程在串行锁内统一校验、导入和更新 douyin_job。
847
846
  return { ok: true, needsFinalize: true };
848
847
  }
849
848
 
@@ -1015,25 +1014,6 @@ async function runCrawl(ctx, invocation, session, taskList) {
1015
1014
  const withStateLock = createSerialLock();
1016
1015
  const markJobFailedLocked = async (job, reason, { crawl = false } = {}) => {
1017
1016
  if (!job || !job.id) return;
1018
- markCrawled(root, job.id, {
1019
- account_url: job.accountUrl,
1020
- url: job.url || (job.card && job.card.href) || '',
1021
- title: job.title || (job.card && job.card.text) || '',
1022
- type: job.type,
1023
- duration: job.duration,
1024
- screenshots: job.type === 'note' && Array.isArray(job.screenshots)
1025
- ? job.screenshots.map((shot) => shot.file)
1026
- : undefined,
1027
- body_file: job.article && job.article.body_file,
1028
- reading_time: job.article && job.article.reading_time,
1029
- body_length: job.article && job.article.body_length,
1030
- dir: job.dir,
1031
- inserted: 0,
1032
- skipped: 0,
1033
- skip: true,
1034
- failed: true,
1035
- reason,
1036
- });
1037
1017
  crawled[job.id] = true;
1038
1018
  if (job.jobKey) {
1039
1019
  await updateJob(jobStore.db, job.jobKey, {
@@ -1050,18 +1030,6 @@ async function runCrawl(ctx, invocation, session, taskList) {
1050
1030
 
1051
1031
  const markJobSkippedLocked = async (job, reason, { crawl = false } = {}) => {
1052
1032
  if (!job || !job.id) return;
1053
- markCrawled(root, job.id, {
1054
- account_url: job.accountUrl,
1055
- url: job.url || (job.card && job.card.href) || '',
1056
- title: job.title || (job.card && job.card.text) || '',
1057
- type: job.type,
1058
- duration: job.duration,
1059
- dir: job.dir,
1060
- inserted: 0,
1061
- skipped: 0,
1062
- skip: true,
1063
- reason,
1064
- });
1065
1033
  crawled[job.id] = true;
1066
1034
  if (job.jobKey) {
1067
1035
  await updateJob(jobStore.db, job.jobKey, {
@@ -1110,22 +1078,6 @@ async function runCrawl(ctx, invocation, session, taskList) {
1110
1078
  if (writeActive) taskList.progressAt(5, writeText());
1111
1079
  };
1112
1080
 
1113
- const jobRecord = (job, extra = {}) => ({
1114
- account_url: job.accountUrl,
1115
- url: job.url,
1116
- title: job.title || (job.card && job.card.text) || '',
1117
- type: job.type,
1118
- duration: job.duration,
1119
- screenshots: job.type === 'note' && Array.isArray(job.screenshots)
1120
- ? job.screenshots.map((shot) => shot.file)
1121
- : undefined,
1122
- body_file: job.article && job.article.body_file,
1123
- reading_time: job.article && job.article.reading_time,
1124
- body_length: job.article && job.article.body_length,
1125
- dir: job.dir,
1126
- ...extra,
1127
- });
1128
-
1129
1081
  const finalizeJob = async (job, analyzed) => {
1130
1082
  await withStateLock(async () => {
1131
1083
  if (!writeActive) {
@@ -1162,12 +1114,6 @@ async function runCrawl(ctx, invocation, session, taskList) {
1162
1114
  }
1163
1115
  if (analyzed.skipped) {
1164
1116
  skippedIrrelevant += 1;
1165
- markCrawled(root, job.id, jobRecord(job, {
1166
- inserted: 0,
1167
- skipped: 0,
1168
- skip: true,
1169
- reason: analyzed.reason || '与网文创作无关',
1170
- }));
1171
1117
  if (job.jobKey) {
1172
1118
  await updateJob(jobStore.db, job.jobKey, {
1173
1119
  analysis_status: 'analyzed',
@@ -1181,10 +1127,6 @@ async function runCrawl(ctx, invocation, session, taskList) {
1181
1127
  } else {
1182
1128
  inserted += analyzed.inserted || 0;
1183
1129
  skippedMaterials += analyzed.skipped || 0;
1184
- markCrawled(root, job.id, jobRecord(job, {
1185
- inserted: analyzed.inserted || 0,
1186
- skipped: analyzed.skipped || 0,
1187
- }));
1188
1130
  if (job.jobKey) {
1189
1131
  await updateJob(jobStore.db, job.jobKey, {
1190
1132
  analysis_status: 'analyzed',
@@ -1800,7 +1742,6 @@ async function runCrawl(ctx, invocation, session, taskList) {
1800
1742
  skippedMaterials,
1801
1743
  failures,
1802
1744
  outputDir: runDir,
1803
- stateFile: paths.crawled,
1804
1745
  aborted,
1805
1746
  mode: browser.mode,
1806
1747
  analysisMode: useSubagents ? 'subagent' : 'single',
@@ -2,8 +2,8 @@
2
2
  * Douyin job state stored in the material database.
3
3
  *
4
4
  * Keeping this next to `material` means a database backup/restore carries both
5
- * the imported materials and the knowledge of which works produced them. The
6
- * workspace `crawled.json` remains only as a legacy migration source/backup.
5
+ * the imported materials and the knowledge of which works produced them. A
6
+ * legacy workspace `crawled.json` is only read for one-time migration.
7
7
  */
8
8
 
9
9
  import fs from 'fs';
@@ -1,4 +1,4 @@
1
- 你正在分析一篇抖音视频作品,把视频画面、字幕、口播内容拆成可以直接进入网文素材库的小积木。
1
+ 你正在分析一篇抖音视频作品,把视频画面、字幕和屏幕文字拆成可以直接进入网文素材库的小积木。
2
2
 
3
3
  ## 作品信息
4
4
 
@@ -19,7 +19,7 @@
19
19
 
20
20
  - 关键帧按时间顺序看,先看前 5 秒,再看后续。
21
21
  - 同一内容跨帧只输出一次,不要每帧重复生成。
22
- - 字幕、口播、贴纸、屏幕文字都要读;音频里出现但画面没有的信息也可以提取。
22
+ - 字幕、贴纸、屏幕文字都要读;画面里没有的信息不要编造。
23
23
  - 片头、片尾、广告、水印、按钮、点赞信息跳过。
24
24
  - 如果关键帧是拼图,按从左到右、从上到下读取。
25
25
  - 画面切换很快时,只提取能确认的内容,不要猜。
@@ -15,12 +15,10 @@ const {
15
15
  safeGateResult, printJson, fail, ensureDir,
16
16
  } = require('./lib.cjs');
17
17
  const {
18
- probeDuration, detectSceneTimes, fixedShortTimes, mergeFrameTimes, extractFramesAt,
19
- extractSharpFramesAt,
18
+ probeDuration, detectSceneTimes, fixedShortTimes, extractDenseFramesAt,
20
19
  } = require('./video-frames.cjs');
21
20
 
22
21
  const UA = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36';
23
- const VIDEO_FRAME_TIMES = 4;
24
22
 
25
23
  function noteId(url) {
26
24
  const match = String(url).match(/\/note\/(\d+)/);
@@ -310,11 +308,14 @@ async function captureSlides(page, context, outDir) {
310
308
  await downloadVideo(context, current.videoSrc, videoFile);
311
309
  duration = probeDuration(videoFile) || duration;
312
310
  sceneTimes = detectSceneTimes(videoFile, { threshold: 0.1, maxFrames: 10 });
313
- times = mergeFrameTimes(fixedShortTimes(duration || 5, 4), sceneTimes, {
314
- minGap: 0.25,
315
- maxFrames: 10,
316
- });
317
- frames = extractSharpFramesAt(videoFile, outDir, 'slide_' + String(slideNo).padStart(2, '0') + '_frame', times, { duration });
311
+ const dense = extractDenseFramesAt(
312
+ videoFile,
313
+ outDir,
314
+ 'slide_' + String(slideNo).padStart(2, '0') + '_frame',
315
+ { duration, sceneTimes, maxFrames: 12 },
316
+ );
317
+ frames = dense.frames;
318
+ if (dense.times.length) times = dense.times;
318
319
  } catch (err) {
319
320
  log('[note] video slide ' + slideNo + ' download/frames failed: ' + (err && err.message ? err.message : String(err)));
320
321
  }
@@ -489,7 +490,7 @@ async function main() {
489
490
  description: meta.description,
490
491
  body: meta.body,
491
492
  slides: captured.slides,
492
- frame_version: 2,
493
+ frame_version: 3,
493
494
  screenshots: captured.screenshots,
494
495
  crawled_at: new Date().toISOString(),
495
496
  dir: outDir,
@@ -19,8 +19,7 @@ const {
19
19
  safeGateResult, printJson, fail, ensureDir,
20
20
  } = require('./lib.cjs');
21
21
  const {
22
- probeDuration, detectSceneTimes, fixedVideoTimes, mergeFrameTimes, extractFramesAt,
23
- extractSharpFramesAt,
22
+ probeDuration, detectSceneTimes, fixedVideoTimes, extractDenseFramesAt,
24
23
  } = require('./video-frames.cjs');
25
24
 
26
25
  const UA = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36';
@@ -229,7 +228,7 @@ async function main() {
229
228
  frames: [],
230
229
  first5s: [],
231
230
  video_file: '',
232
- frame_version: 2,
231
+ frame_version: 3,
233
232
  crawled_at: new Date().toISOString(),
234
233
  dir: outDir,
235
234
  };
@@ -278,7 +277,7 @@ async function main() {
278
277
  frames: [],
279
278
  first5s: [],
280
279
  video_file: videoFile,
281
- frame_version: 2,
280
+ frame_version: 3,
282
281
  crawled_at: new Date().toISOString(),
283
282
  dir: outDir,
284
283
  };
@@ -303,8 +302,13 @@ async function main() {
303
302
  if (videoFile && fs.existsSync(videoFile)) {
304
303
  try {
305
304
  sceneTimes = detectSceneTimes(videoFile, { threshold: 0.15, maxFrames: 16 });
306
- times = mergeFrameTimes(fixedTimes, sceneTimes, { minGap: 0.4, maxFrames: 24 });
307
- frames = extractSharpFramesAt(videoFile, outDir, 'video_frame', times, { duration });
305
+ const dense = extractDenseFramesAt(videoFile, outDir, 'video_frame', {
306
+ duration,
307
+ sceneTimes,
308
+ maxFrames: 24,
309
+ });
310
+ frames = dense.frames;
311
+ if (dense.times.length) times = dense.times;
308
312
  } catch (err) {
309
313
  log('[video] ffmpeg frame extraction failed: ' + (err && err.message ? err.message : String(err)));
310
314
  }
@@ -344,7 +348,7 @@ async function main() {
344
348
  fixed_times: fixedTimes,
345
349
  video_file: videoFile,
346
350
  download_error: downloadError,
347
- frame_version: 2,
351
+ frame_version: 3,
348
352
  crawled_at: new Date().toISOString(),
349
353
  dir: outDir,
350
354
  };
@@ -2,14 +2,21 @@
2
2
 
3
3
  /**
4
4
  * Shared ffmpeg helpers for Douyin note carousel video slides and standalone
5
- * videos. Keeping this in one deployed module means the note crawler and the
6
- * video crawler use the same scene-detection / fixed-fallback strategy.
5
+ * videos. Videos are sampled densely, then split into stable visual states so
6
+ * animated captions are represented after they finish appearing instead of at
7
+ * a transition frame.
7
8
  */
8
9
 
9
10
  const fs = require('fs');
10
11
  const path = require('path');
11
12
  const { spawnSync } = require('child_process');
12
13
 
14
+ const SHORT_VIDEO_SECONDS = 15;
15
+ const MEDIUM_VIDEO_SECONDS = 60;
16
+ const SHORT_VIDEO_INTERVAL = 0.2;
17
+ const MEDIUM_VIDEO_INTERVAL = 0.5;
18
+ const LONG_VIDEO_INTERVAL = 1;
19
+
13
20
  function probeDuration(file) {
14
21
  const result = spawnSync('ffprobe', [
15
22
  '-v', 'error',
@@ -127,93 +134,262 @@ function extractFramesAt(file, outDir, prefix, times, { timeout = 60000 } = {})
127
134
  return frames;
128
135
  }
129
136
 
130
- /** Lower is sharper. Uses ffmpeg's blurdetect filter; null when unavailable. */
131
- function frameBlurScore(file) {
132
- const result = spawnSync('ffmpeg', [
133
- '-hide_banner', '-i', file,
134
- '-vf', 'blurdetect,metadata=print',
135
- '-an', '-f', 'null', '-',
136
- ], { encoding: 'utf8', timeout: 30000 });
137
- if (result.status !== 0) return null;
138
- const text = String(result.stderr || '');
139
- const values = [...text.matchAll(/lavfi\.blur=([0-9]+(?:\.[0-9]+)?)/g)]
140
- .map((match) => Number(match[1]))
141
- .filter((value) => Number.isFinite(value));
142
- if (values.length) return values[0];
143
- const mean = text.match(/blur mean:\s*([0-9]+(?:\.[0-9]+)?)/);
144
- return mean ? Number(mean[1]) : null;
137
+ /** 15 秒以内每 0.2 秒采样,15–60 秒每 0.5 秒采样。 */
138
+ function denseSampleInterval(duration) {
139
+ const total = Number(duration);
140
+ if (!Number.isFinite(total) || total <= 0) return SHORT_VIDEO_INTERVAL;
141
+ if (total <= SHORT_VIDEO_SECONDS) return SHORT_VIDEO_INTERVAL;
142
+ if (total <= MEDIUM_VIDEO_SECONDS) return MEDIUM_VIDEO_INTERVAL;
143
+ return LONG_VIDEO_INTERVAL;
144
+ }
145
+
146
+ function parseMetric(text, name) {
147
+ const re = new RegExp('lavfi\\.' + name + '=([0-9]+(?:\\.[0-9]+)?)', 'g');
148
+ const values = [];
149
+ let match;
150
+ while ((match = re.exec(text))) {
151
+ const value = Number(match[1]);
152
+ if (Number.isFinite(value)) values.push(value);
153
+ }
154
+ return values;
145
155
  }
146
156
 
147
157
  /**
148
- * Extract one representative frame per source time, choosing the sharpest
149
- * post-transition candidate. Scene cuts happen before animated text has fully
150
- * appeared, so the cut timestamp itself is often a blurry transition frame.
158
+ * One ffmpeg pass over the clip. The fps filter reduces the stream to the
159
+ * requested sample interval, select computes the difference against the
160
+ * previous sample, and blurdetect scores the sharpness of that sample.
151
161
  */
152
- function extractSharpFramesAt(file, outDir, prefix, times, {
153
- duration = null,
154
- timeout = 60000,
155
- offsets = [0.2, 0.55, 0.95],
162
+ function analyzeDenseFrames(file, { duration = null, interval = null, timeout = 240000 } = {}) {
163
+ const total = Number.isFinite(Number(duration)) && Number(duration) > 0
164
+ ? Number(duration)
165
+ : probeDuration(file);
166
+ const step = Number.isFinite(Number(interval)) && Number(interval) > 0
167
+ ? Number(interval)
168
+ : denseSampleInterval(total);
169
+ const fps = Math.round((1 / step) * 1000) / 1000;
170
+ const offset = Math.round(step * 50) / 100;
171
+ const baseArgs = ['-hide_banner', '-loglevel', 'info', '-i', file];
172
+ const outputArgs = ['-an', '-f', 'null', '-'];
173
+ const prefix = (total && total > offset ? "trim=start=" + offset + ",setpts=PTS-STARTPTS," : "setpts=PTS-STARTPTS,");
174
+ const withBlur = prefix + "fps=" + fps
175
+ + ",select='gte(scene,0)',metadata=print:key=lavfi.scene_score"
176
+ + ",blurdetect,metadata=print:key=lavfi.blur";
177
+ let result = spawnSync('ffmpeg', [
178
+ ...baseArgs, '-vf', withBlur, ...outputArgs,
179
+ ], { encoding: 'utf8', timeout, maxBuffer: 64 * 1024 * 1024 });
180
+ let text = String(result.stderr || '');
181
+ let scores = parseMetric(text, 'scene_score');
182
+ let blurs = parseMetric(text, 'blur');
183
+ if (result.status !== 0 || !scores.length) {
184
+ // blurdetect is optional in some ffmpeg builds; keep scene-only metrics.
185
+ result = spawnSync('ffmpeg', [
186
+ ...baseArgs,
187
+ '-vf', prefix + "fps=" + fps
188
+ + ",select='gte(scene,0)',metadata=print:key=lavfi.scene_score",
189
+ ...outputArgs,
190
+ ], { encoding: 'utf8', timeout, maxBuffer: 64 * 1024 * 1024 });
191
+ text = String(result.stderr || '');
192
+ scores = parseMetric(text, 'scene_score');
193
+ blurs = [];
194
+ }
195
+ const count = Math.max(scores.length, blurs.length);
196
+ const samples = [];
197
+ for (let index = 0; index < count; index += 1) {
198
+ samples.push({
199
+ time: Math.round((offset + index * step) * 100) / 100,
200
+ scene: index < scores.length ? scores[index] : 0,
201
+ blur: index < blurs.length ? blurs[index] : null,
202
+ });
203
+ }
204
+ return { interval: step, samples };
205
+ }
206
+
207
+ /**
208
+ * Split dense samples into stable states. A frame is stable when neither the
209
+ * step into it nor the step out of it changes the picture much. Runs of stable
210
+ * frames become visual states; the latest sharp frame in each run represents
211
+ * the state, which gives animated text time to finish appearing. Uncovered
212
+ * stretches (constant motion, no stable plateau) still get a sharp frame so a
213
+ * long clip cannot lose a whole segment.
214
+ */
215
+ function selectDenseFrameTimes(samples, {
216
+ interval = SHORT_VIDEO_INTERVAL,
217
+ sceneTimes = [],
156
218
  maxFrames = 24,
219
+ stableThreshold = 0.012,
220
+ maxGap = null,
157
221
  } = {}) {
158
- const baseTimes = [...new Set((Array.isArray(times) ? times : [])
159
- .map((value) => Number(value))
160
- .filter((value) => Number.isFinite(value) && value >= 0))]
161
- .sort((a, b) => a - b)
162
- .slice(0, maxFrames);
163
- if (!baseTimes.length) return [];
164
- fs.mkdirSync(outDir, { recursive: true });
165
- const total = Number.isFinite(Number(duration)) && Number(duration) > 0 ? Number(duration) : null;
166
- const tempDir = fs.mkdtempSync(path.join(outDir, '.sharp-frames-'));
222
+ const list = (Array.isArray(samples) ? samples : [])
223
+ .map((sample) => ({
224
+ time: Number(sample.time),
225
+ scene: Number.isFinite(Number(sample.scene)) ? Number(sample.scene) : 0,
226
+ blur: Number.isFinite(Number(sample.blur)) ? Number(sample.blur) : null,
227
+ }))
228
+ .filter((sample) => Number.isFinite(sample.time) && sample.time >= 0)
229
+ .sort((a, b) => a.time - b.time);
230
+ if (!list.length) return [];
231
+ const step = Number.isFinite(Number(interval)) && Number(interval) > 0
232
+ ? Number(interval)
233
+ : SHORT_VIDEO_INTERVAL;
234
+ const total = list[list.length - 1].time + step;
235
+ const gapLimit = Number.isFinite(Number(maxGap)) && Number(maxGap) > 0
236
+ ? Number(maxGap)
237
+ : (total <= SHORT_VIDEO_SECONDS ? 2.5 : 5);
238
+
239
+ // A scene cut must never be folded into the previous state.
240
+ const cutIndexes = new Set();
241
+ for (const raw of sceneTimes || []) {
242
+ const time = Number(raw);
243
+ if (!Number.isFinite(time)) continue;
244
+ const index = list.findIndex((sample) => sample.time >= time - step * 0.25);
245
+ if (index > 0) cutIndexes.add(index);
246
+ }
247
+
248
+ const stableFlags = list.map((sample, index) => {
249
+ if (sample.scene >= stableThreshold) return false;
250
+ const next = index + 1 < list.length ? list[index + 1].scene : 0;
251
+ if (next >= stableThreshold) return false;
252
+ return !cutIndexes.has(index + 1);
253
+ });
254
+
255
+ const runs = [];
256
+ let current = [];
257
+ let gap = 0;
258
+ for (let index = 0; index < list.length; index += 1) {
259
+ if (stableFlags[index]) {
260
+ current.push(list[index]);
261
+ gap = 0;
262
+ continue;
263
+ }
264
+ if (!current.length) continue;
265
+ const hardCut = cutIndexes.has(index) || list[index].scene >= 0.08;
266
+ // A single noisy sample inside an otherwise static state should not split
267
+ // it; a real cut always does.
268
+ if (!hardCut && gap < 1) {
269
+ gap += 1;
270
+ continue;
271
+ }
272
+ runs.push(current);
273
+ current = [];
274
+ gap = 0;
275
+ }
276
+ if (current.length) runs.push(current);
277
+
278
+ const chooseRepresentative = (pool) => {
279
+ if (!pool.length) return null;
280
+ // Trim the edges of long runs so fade-in ghosting and fade-out frames do
281
+ // not win. The sharpest frame in the stable middle is the representative.
282
+ const trim = pool.length >= 4 ? Math.max(1, Math.floor(pool.length * 0.2)) : 0;
283
+ const middle = trim ? pool.slice(trim, pool.length - trim) : pool;
284
+ const candidates = middle.length ? middle : pool;
285
+ const scored = candidates.filter((sample) => sample.blur !== null);
286
+ if (!scored.length) return candidates[candidates.length - 1];
287
+ const best = Math.min(...scored.map((sample) => sample.blur));
288
+ const acceptable = candidates.filter(
289
+ (sample) => sample.blur === null || sample.blur <= best * 1.25 + 0.5,
290
+ );
291
+ let chosen = null;
292
+ for (const sample of acceptable) {
293
+ if (sample.blur === null) continue;
294
+ if (!chosen || sample.blur < chosen.blur - 0.05) chosen = sample;
295
+ else if (Math.abs(sample.blur - chosen.blur) <= 0.05 && sample.time > chosen.time) chosen = sample;
296
+ }
297
+ return chosen || acceptable[acceptable.length - 1] || candidates[candidates.length - 1];
298
+ };
299
+
167
300
  const selected = [];
168
- try {
169
- for (let index = 0; index < baseTimes.length; index += 1) {
170
- const base = baseTimes[index];
171
- const next = baseTimes[index + 1];
172
- const limit = Math.min(
173
- total === null ? Number.POSITIVE_INFINITY : total - 0.05,
174
- Number.isFinite(next) ? next - 0.12 : Number.POSITIVE_INFINITY,
175
- );
176
- const candidates = [];
177
- for (const offset of offsets) {
178
- const at = Math.round((base + offset) * 100) / 100;
179
- if (at > limit) continue;
180
- const candidateFile = path.join(tempDir, 'candidate_' + String(index).padStart(3, '0')
181
- + '_' + String(candidates.length).padStart(2, '0') + '.jpg');
182
- if (!extractFrameAt(file, candidateFile, at, timeout)) continue;
183
- let size = 0;
184
- try { size = fs.statSync(candidateFile).size; } catch { /* ignore */ }
185
- candidates.push({ time: at, file: candidateFile, size, blur: frameBlurScore(candidateFile) });
186
- }
187
- if (!candidates.length) {
188
- // Near the end of the clip there may be no room for post-roll.
189
- const fallbackFile = path.join(tempDir, 'candidate_' + String(index).padStart(3, '0') + '_base.jpg');
190
- if (extractFrameAt(file, fallbackFile, base, timeout)) {
191
- candidates.push({ time: base, file: fallbackFile, size: 0, blur: frameBlurScore(fallbackFile) });
192
- }
193
- }
194
- if (!candidates.length) continue;
195
- const scored = candidates.filter((item) => Number.isFinite(item.blur));
196
- if (scored.length) {
197
- const best = Math.min(...scored.map((item) => item.blur));
198
- const acceptable = scored.filter((item) => item.blur <= best * 1.15 + 0.5);
199
- // Prefer the latest acceptable frame: animated text has had time to
200
- // finish, while blurdetect still rejects transition ghosting.
201
- selected.push(acceptable[acceptable.length - 1]);
202
- } else {
203
- // No blurdetect support: use the largest JPEG as a sharpness proxy.
204
- selected.push(candidates.slice().sort((a, b) => b.size - a.size)[0]);
205
- }
301
+ const covered = [];
302
+ for (const run of runs) {
303
+ // A single frame at the very start is usually the fade-in black/white
304
+ // frame. A real static title lasts multiple samples and is kept.
305
+ if (run.length === 1 && run[0].time <= step * 1.5 + 0.001 && list.length > 2) continue;
306
+ const representative = chooseRepresentative(run);
307
+ if (!representative) continue;
308
+ selected.push({ sample: representative, stable: true });
309
+ covered.push([run[0].time, run[run.length - 1].time]);
310
+ }
311
+
312
+ // Fill parts of the clip that have no stable run at all. This keeps a
313
+ // continuously animated intro or a long moving shot from disappearing.
314
+ covered.sort((a, b) => a[0] - b[0]);
315
+ const uncovered = [];
316
+ let cursor = 0;
317
+ for (const [start, end] of covered) {
318
+ if (start - cursor > step / 2) uncovered.push([cursor, start]);
319
+ cursor = Math.max(cursor, end);
320
+ }
321
+ if (total - cursor > step / 2) uncovered.push([cursor, total]);
322
+ for (const [start, end] of uncovered) {
323
+ const span = end - start;
324
+ if (span < gapLimit * 0.6) continue;
325
+ const chunks = Math.max(1, Math.ceil(span / gapLimit));
326
+ for (let chunk = 0; chunk < chunks; chunk += 1) {
327
+ const from = start + (span * chunk) / chunks;
328
+ const to = start + (span * (chunk + 1)) / chunks;
329
+ const pool = list.filter((sample) => sample.time >= from && sample.time < to);
330
+ const representative = chooseRepresentative(pool);
331
+ if (representative) selected.push({ sample: representative, stable: false });
206
332
  }
207
- } finally {
208
- try { fs.rmSync(tempDir, { recursive: true, force: true }); } catch { /* ignore */ }
209
333
  }
210
334
 
335
+ selected.sort((a, b) => a.sample.time - b.sample.time);
211
336
  const distinct = [];
212
337
  for (const item of selected) {
213
- if (distinct.some((other) => Math.abs(other.time - item.time) < 0.3)) continue;
338
+ const minGap = Math.max(0.3, step * 1.5);
339
+ const clash = distinct.findIndex((other) => Math.abs(other.sample.time - item.sample.time) < minGap);
340
+ if (clash >= 0) {
341
+ // A stable-state frame is a better representative than a coverage
342
+ // filler that happened to land on the transition next to it.
343
+ if (item.stable && !distinct[clash].stable) distinct[clash] = item;
344
+ continue;
345
+ }
214
346
  distinct.push(item);
215
347
  }
216
- return extractFramesAt(file, outDir, prefix, distinct.map((item) => item.time), { timeout });
348
+ distinct.sort((a, b) => a.sample.time - b.sample.time);
349
+ const limit = Math.max(1, Number(maxFrames) || 24);
350
+ if (distinct.length <= limit) {
351
+ return distinct.map((item) => Math.round(item.sample.time * 100) / 100);
352
+ }
353
+ const picked = [];
354
+ for (let index = 0; index < limit; index += 1) {
355
+ const sourceIndex = Math.round((index * (distinct.length - 1)) / (limit - 1));
356
+ picked.push(distinct[sourceIndex]);
357
+ }
358
+ return [...new Set(picked.map((item) => Math.round(item.sample.time * 100) / 100))].sort((a, b) => a - b);
359
+ }
360
+
361
+ /**
362
+ * Dense sample + stable-state selection + frame extraction. Returns the
363
+ * selected frames along with the sampling metadata for note.json/video.json.
364
+ */
365
+ function extractDenseFramesAt(file, outDir, prefix, {
366
+ duration = null,
367
+ interval = null,
368
+ sceneTimes = [],
369
+ maxFrames = 24,
370
+ timeout = 240000,
371
+ extractTimeout = 60000,
372
+ } = {}) {
373
+ fs.mkdirSync(outDir, { recursive: true });
374
+ const total = Number.isFinite(Number(duration)) && Number(duration) > 0
375
+ ? Number(duration)
376
+ : probeDuration(file);
377
+ if (!total) return { frames: [], times: [], interval: null, sample_count: 0 };
378
+ const step = Number.isFinite(Number(interval)) && Number(interval) > 0
379
+ ? Number(interval)
380
+ : denseSampleInterval(total);
381
+ const analysis = analyzeDenseFrames(file, { duration: total, interval: step, timeout });
382
+ const fallback = fixedShortTimes(total, Math.min(8, Math.max(2, Number(maxFrames) || 8)));
383
+ const times = analysis.samples.length
384
+ ? selectDenseFrameTimes(analysis.samples, { interval: step, sceneTimes, maxFrames })
385
+ : fallback;
386
+ const frames = extractFramesAt(file, outDir, prefix, times, { timeout: extractTimeout });
387
+ return {
388
+ frames,
389
+ times: frames.map((frame) => frame.time),
390
+ interval: step,
391
+ sample_count: analysis.samples.length,
392
+ };
217
393
  }
218
394
 
219
395
  module.exports = {
@@ -223,6 +399,8 @@ module.exports = {
223
399
  fixedVideoTimes,
224
400
  mergeFrameTimes,
225
401
  extractFramesAt,
226
- extractSharpFramesAt,
227
- frameBlurScore,
402
+ denseSampleInterval,
403
+ analyzeDenseFrames,
404
+ selectDenseFrameTimes,
405
+ extractDenseFramesAt,
228
406
  };
@@ -1,14 +1,13 @@
1
1
  /**
2
2
  * Workspace state for fancy-douyin.
3
3
  *
4
- * Accounts, crawl history, the Chrome profile and downloaded screenshots all
4
+ * Account and work state live in the material database (`douyin_account` and
5
+ * `douyin_job`). The Chrome profile, login cookies and downloaded screenshots
5
6
  * live under <workspace>/.fancy/douyin. The deployed crawler scripts live under
6
7
  * <workspace>/.fancy-tools/fancy-douyin.
7
8
  *
8
- * The crawl history is keyed by the work id parsed from /note/<id>, /video/<id>
9
- * or /article/<id>. A work is written only after its analysis has been imported into
10
- * the material library, or after it was confirmed irrelevant/long and skipped,
11
- * so failed works are retried on the next run.
9
+ * A legacy `crawled.json` is only read when an old workspace still has one, so
10
+ * it can be migrated once into `douyin_job`; new runs never write it.
12
11
  */
13
12
 
14
13
  import fs from 'fs';
@@ -187,26 +186,16 @@ export function removeAccount(root, selector) {
187
186
  return { removed: true, url: removed.url, accounts };
188
187
  }
189
188
 
189
+ /**
190
+ * Legacy workspace crawl history. Runtime state lives in `douyin_job`; this
191
+ * reader exists only so old workspaces can still skip/migrate entries that
192
+ * predate the database. New runs never write this file.
193
+ */
190
194
  export function readCrawled(root) {
191
195
  const value = readJsonFile(douyinPaths(root).crawled);
192
196
  return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
193
197
  }
194
198
 
195
- export function writeCrawled(root, state) {
196
- const paths = ensureDouyinDir(root);
197
- atomicWriteJson(paths.crawled, state, { mode: 0o600 });
198
- }
199
-
200
- export function markCrawled(root, noteId, data) {
201
- const state = readCrawled(root);
202
- state[noteId] = {
203
- ...data,
204
- crawled_at: new Date().toISOString(),
205
- };
206
- writeCrawled(root, state);
207
- return state[noteId];
208
- }
209
-
210
199
  export function accountListText(accountsOrRoot, countsOverride = null) {
211
200
  const accounts = Array.isArray(accountsOrRoot) ? accountsOrRoot : readAccounts(accountsOrRoot);
212
201
  if (!accounts.length) {
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * The Douyin crawler still runs in the parent process. Only the LLM analysis
5
5
  * of already-prepared works is delegated to child agents. That keeps Chrome,
6
- * `crawled.json`, and material imports single-writer while allowing several
6
+ * the job database, and material imports single-writer while allowing several
7
7
  * image/video/article analyses to run at once.
8
8
  */
9
9
 
@@ -57,7 +57,7 @@ export async function runJobPool(items, concurrency, worker) {
57
57
 
58
58
  /**
59
59
  * A small async mutex. Finalization is deliberately serialized because it
60
- * writes crawled.json and opens the material database; the LLM work itself is
60
+ * updates douyin_job and opens the material database; the LLM work itself is
61
61
  * already parallel.
62
62
  */
63
63
  export function createSerialLock() {
@@ -242,7 +242,6 @@ export function summaryText({
242
242
  skippedMaterials,
243
243
  failures,
244
244
  outputDir,
245
- stateFile,
246
245
  aborted,
247
246
  mode,
248
247
  analysisMode = 'single',
@@ -273,6 +272,6 @@ export function summaryText({
273
272
  lines.push('作品级失败已记录为跳过,下次不再重试;账号级失败仍会在下次重试。');
274
273
  }
275
274
  lines.push('输出目录:' + outputDir);
276
- lines.push('采集记录:' + stateFile);
275
+ lines.push('任务状态:素材库 douyin_job 表');
277
276
  return lines.join('\n');
278
277
  }