@cloud411716/fancy-webnovel 4.18.1 → 4.20.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.
- package/docs/douyin-plugin.md +6 -3
- package/package.json +1 -1
- package/plugins/fancy-douyin/index.js +29 -10
- package/plugins/fancy-douyin/jobs.js +23 -0
- package/plugins/fancy-douyin/prompts/02-video-analysis-prompt.md +2 -2
- package/plugins/fancy-douyin/scripts/crawl-note.cjs +10 -7
- package/plugins/fancy-douyin/scripts/crawl-video.cjs +11 -3
- package/plugins/fancy-douyin/scripts/video-frames.cjs +284 -11
package/docs/douyin-plugin.md
CHANGED
|
@@ -40,7 +40,7 @@ LLM 能力自检(图片 / 视频)
|
|
|
40
40
|
→ 文章:提取标题、发布日期、阅读时长和正文
|
|
41
41
|
→ 图文:逐页判断类型
|
|
42
42
|
→ 图片页:下载轮播原图并转成 JPG(避免滚动时截到半张图)
|
|
43
|
-
→
|
|
43
|
+
→ 视频页:下载该页短视频,密集采样后按稳定画面段抽帧,拼成一张关键帧图
|
|
44
44
|
→ 视频:先判断时长
|
|
45
45
|
→ 超过 1 分钟:直接跳过并记录
|
|
46
46
|
→ 不超过 1 分钟:抽取前 5 秒关键帧,先判断是否与网文创作有关
|
|
@@ -199,10 +199,13 @@ id / kind / subkind / name / tags / genres / note / source
|
|
|
199
199
|
- 只采集个人研究/已授权账号,不要批量抓取或二次分发受版权保护的图片、视频和文案。
|
|
200
200
|
- 图文截图不是页面视口截图,而是下载每页轮播原图后再转成 JPEG,所以不会因为
|
|
201
201
|
滚动、懒加载或页面动画截到残缺图片。
|
|
202
|
-
-
|
|
203
|
-
|
|
202
|
+
- 图文作品的轮播可以混合图片页和视频页。视频页会下载该页短视频,15 秒以内每 0.2 秒采样、15–60 秒每 0.5 秒采样,
|
|
203
|
+
再按稳定画面段选帧并拼成一张关键帧图交给 LLM;这样快速切换的画面和动态字幕/标语不会被封面漏掉。
|
|
204
204
|
- 独立视频作品会先尝试下载原片并用 ffmpeg 抽帧;下载失败时退化为播放器元素截图。
|
|
205
205
|
视频时长超过 1 分钟直接跳过;前 5 秒与网文创作无关也跳过。
|
|
206
|
+
- 场景切换点本身常是过渡虚影。插件会在密集采样后用 ffmpeg blurdetect 给每帧打分,在每个稳定画面段的清晰中段选一帧,避免把文字尚未完全出现的模糊帧交给 LLM。
|
|
207
|
+
- 帧选择版本是 `frame_version: 3`;旧版本缓存的截图/关键帧会自动重新采集。
|
|
208
|
+
- 子 Agent 或 DSH 在分析途中中断时,作品任务保持 pending;下次运行会复用已采集文件重新分析。旧版本留下的 aborted/failed 任务会在启动采集时自动恢复为 pending。
|
|
206
209
|
- 抖音 DOM/类名会变,`scan-account.cjs`、`crawl-note.cjs` 和 `crawl-video.cjs`
|
|
207
210
|
的选择器可能需要维护。
|
|
208
211
|
- 每次运行结束会自动关闭 Chrome;登录态保存在 profile 和 login-state.json 中,下次运行自动复用。
|
package/package.json
CHANGED
|
@@ -41,11 +41,12 @@ import { analysisPrompt, articlePrompt, capabilityPrompt, helpText, loginQuestio
|
|
|
41
41
|
import { createJobQueue, createSerialLock, getSubagentRuntime, subagentWorkerCount } from './subagents.js';
|
|
42
42
|
import {
|
|
43
43
|
countJobsByAccount, createJob, jobKeyFor, jobRelDir,
|
|
44
|
-
listJobsForAccount, migrateCrawledJobs, openJobStore, updateJob,
|
|
44
|
+
listJobsForAccount, migrateCrawledJobs, openJobStore, recoverInterruptedJobs, updateJob,
|
|
45
45
|
} from './jobs.js';
|
|
46
46
|
|
|
47
47
|
export const inject = ['commands', 'userQuestions'];
|
|
48
48
|
|
|
49
|
+
const FRAME_SELECTION_VERSION = 3;
|
|
49
50
|
const ANALYSIS_TIMEOUT_MS = 20 * 60 * 1000;
|
|
50
51
|
const ANALYSIS_IDLE_GRACE_MS = 60 * 1000;
|
|
51
52
|
const CAPABILITY_TIMEOUT_MS = 5 * 60 * 1000;
|
|
@@ -807,7 +808,8 @@ async function runSubagentAnalysisJob({
|
|
|
807
808
|
delivery: 'caller',
|
|
808
809
|
});
|
|
809
810
|
} catch (err) {
|
|
810
|
-
|
|
811
|
+
const message = '子 Agent 启动失败:' + (err && err.message ? err.message : String(err));
|
|
812
|
+
return { ok: false, retryable: Boolean(signal && signal.aborted), error: message };
|
|
811
813
|
}
|
|
812
814
|
|
|
813
815
|
let result;
|
|
@@ -821,14 +823,25 @@ async function runSubagentAnalysisJob({
|
|
|
821
823
|
}),
|
|
822
824
|
]);
|
|
823
825
|
} catch (err) {
|
|
824
|
-
|
|
826
|
+
const message = err && err.message ? err.message : String(err);
|
|
827
|
+
return {
|
|
828
|
+
ok: false,
|
|
829
|
+
retryable: Boolean((signal && signal.aborted) || /abort|cancel|interrupt|terminated/i.test(message)),
|
|
830
|
+
error: '子 Agent 执行失败:' + message,
|
|
831
|
+
};
|
|
825
832
|
} finally {
|
|
826
833
|
if (timer) clearTimeout(timer);
|
|
827
834
|
try { await activation.dispose(); } catch { /* best effort */ }
|
|
828
835
|
}
|
|
829
836
|
if (!fs.existsSync(job.target)) {
|
|
830
|
-
const stop = result && result.stopReason ?
|
|
831
|
-
|
|
837
|
+
const stop = result && result.stopReason ? String(result.stopReason) : '';
|
|
838
|
+
const retryable = /abort|cancel|interrupt|terminated/i.test(stop)
|
|
839
|
+
|| Boolean(signal && signal.aborted);
|
|
840
|
+
return {
|
|
841
|
+
ok: false,
|
|
842
|
+
retryable,
|
|
843
|
+
error: '子 Agent 没有写入目标文件' + (stop ? '(' + stop + ')' : ''),
|
|
844
|
+
};
|
|
832
845
|
}
|
|
833
846
|
// 文件已经写出,由父进程在串行锁内统一校验、导入和写 crawled.json。
|
|
834
847
|
return { ok: true, needsFinalize: true };
|
|
@@ -878,14 +891,14 @@ function readJsonArtifact(dir, name) {
|
|
|
878
891
|
|
|
879
892
|
function reusableNote(dir) {
|
|
880
893
|
const note = readJsonArtifact(dir, 'note.json');
|
|
881
|
-
if (!note || !Array.isArray(note.screenshots) || !note.screenshots.length) return null;
|
|
894
|
+
if (!note || note.frame_version !== FRAME_SELECTION_VERSION || !Array.isArray(note.screenshots) || !note.screenshots.length) return null;
|
|
882
895
|
if (!note.screenshots.every((shot) => shot && shot.file && fs.existsSync(shot.file))) return null;
|
|
883
896
|
return note;
|
|
884
897
|
}
|
|
885
898
|
|
|
886
899
|
function reusableVideo(dir) {
|
|
887
900
|
const video = readJsonArtifact(dir, 'video.json');
|
|
888
|
-
if (!video || !Array.isArray(video.frames) || !video.frames.length) return null;
|
|
901
|
+
if (!video || video.frame_version !== FRAME_SELECTION_VERSION || !Array.isArray(video.frames) || !video.frames.length) return null;
|
|
889
902
|
if (!video.frames.every((frame) => frame && frame.file && fs.existsSync(frame.file))) return null;
|
|
890
903
|
return video;
|
|
891
904
|
}
|
|
@@ -978,6 +991,7 @@ async function runCrawl(ctx, invocation, session, taskList) {
|
|
|
978
991
|
let workerPromises = [];
|
|
979
992
|
try {
|
|
980
993
|
await migrateCrawledJobs(jobStore.db, root, accounts);
|
|
994
|
+
await recoverInterruptedJobs(jobStore.db);
|
|
981
995
|
} catch (err) {
|
|
982
996
|
await jobStore.close();
|
|
983
997
|
return notify(session, 'error', '❌ 初始化抖音任务状态表失败:' + (err && err.message ? err.message : String(err)));
|
|
@@ -1126,11 +1140,16 @@ async function runCrawl(ctx, invocation, session, taskList) {
|
|
|
1126
1140
|
materialTools,
|
|
1127
1141
|
});
|
|
1128
1142
|
}
|
|
1129
|
-
if (analyzed && analyzed.aborted) {
|
|
1130
|
-
aborted = true;
|
|
1143
|
+
if (analyzed && (analyzed.aborted || analyzed.retryable)) {
|
|
1131
1144
|
if (job.jobKey) {
|
|
1132
|
-
await updateJob(jobStore.db, job.jobKey, {
|
|
1145
|
+
await updateJob(jobStore.db, job.jobKey, {
|
|
1146
|
+
analysis_status: 'pending',
|
|
1147
|
+
import_status: 'pending',
|
|
1148
|
+
reason: '上次分析被中断,等待重试',
|
|
1149
|
+
error: '',
|
|
1150
|
+
});
|
|
1133
1151
|
}
|
|
1152
|
+
if (jobSignal.aborted) aborted = true;
|
|
1134
1153
|
return;
|
|
1135
1154
|
}
|
|
1136
1155
|
if (!analyzed || !analyzed.ok) {
|
|
@@ -168,6 +168,29 @@ export async function migrateCrawledJobs(db, root, accountList = null) {
|
|
|
168
168
|
return { migrated };
|
|
169
169
|
}
|
|
170
170
|
|
|
171
|
+
/**
|
|
172
|
+
* Reset jobs whose only failure was an interrupted child (for example a DSH
|
|
173
|
+
* restart or an aborted subagent). A real analysis failure stays failed.
|
|
174
|
+
*/
|
|
175
|
+
export async function recoverInterruptedJobs(db) {
|
|
176
|
+
const rows = firstRows(await db.query(
|
|
177
|
+
"SELECT job_key, error, reason FROM douyin_job WHERE import_status = 'failed';",
|
|
178
|
+
));
|
|
179
|
+
let recovered = 0;
|
|
180
|
+
for (const row of rows) {
|
|
181
|
+
const text = String(row.error || '') + ' ' + String(row.reason || '');
|
|
182
|
+
if (!/abort|cancel|interrupt|terminated|中断|没有写入目标文件/i.test(text)) continue;
|
|
183
|
+
await updateJob(db, row.job_key, {
|
|
184
|
+
analysis_status: 'pending',
|
|
185
|
+
import_status: 'pending',
|
|
186
|
+
reason: '上次分析被中断,等待重试',
|
|
187
|
+
error: '',
|
|
188
|
+
});
|
|
189
|
+
recovered += 1;
|
|
190
|
+
}
|
|
191
|
+
return { recovered };
|
|
192
|
+
}
|
|
193
|
+
|
|
171
194
|
export function legacyCrawledPath(root) {
|
|
172
195
|
return douyinPaths(root).crawled;
|
|
173
196
|
}
|
|
@@ -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,11 +15,10 @@ const {
|
|
|
15
15
|
safeGateResult, printJson, fail, ensureDir,
|
|
16
16
|
} = require('./lib.cjs');
|
|
17
17
|
const {
|
|
18
|
-
probeDuration, detectSceneTimes, fixedShortTimes,
|
|
18
|
+
probeDuration, detectSceneTimes, fixedShortTimes, extractDenseFramesAt,
|
|
19
19
|
} = require('./video-frames.cjs');
|
|
20
20
|
|
|
21
21
|
const UA = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36';
|
|
22
|
-
const VIDEO_FRAME_TIMES = 4;
|
|
23
22
|
|
|
24
23
|
function noteId(url) {
|
|
25
24
|
const match = String(url).match(/\/note\/(\d+)/);
|
|
@@ -309,11 +308,14 @@ async function captureSlides(page, context, outDir) {
|
|
|
309
308
|
await downloadVideo(context, current.videoSrc, videoFile);
|
|
310
309
|
duration = probeDuration(videoFile) || duration;
|
|
311
310
|
sceneTimes = detectSceneTimes(videoFile, { threshold: 0.1, maxFrames: 10 });
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
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;
|
|
317
319
|
} catch (err) {
|
|
318
320
|
log('[note] video slide ' + slideNo + ' download/frames failed: ' + (err && err.message ? err.message : String(err)));
|
|
319
321
|
}
|
|
@@ -488,6 +490,7 @@ async function main() {
|
|
|
488
490
|
description: meta.description,
|
|
489
491
|
body: meta.body,
|
|
490
492
|
slides: captured.slides,
|
|
493
|
+
frame_version: 3,
|
|
491
494
|
screenshots: captured.screenshots,
|
|
492
495
|
crawled_at: new Date().toISOString(),
|
|
493
496
|
dir: outDir,
|
|
@@ -19,7 +19,7 @@ const {
|
|
|
19
19
|
safeGateResult, printJson, fail, ensureDir,
|
|
20
20
|
} = require('./lib.cjs');
|
|
21
21
|
const {
|
|
22
|
-
probeDuration, detectSceneTimes, fixedVideoTimes,
|
|
22
|
+
probeDuration, detectSceneTimes, fixedVideoTimes, extractDenseFramesAt,
|
|
23
23
|
} = require('./video-frames.cjs');
|
|
24
24
|
|
|
25
25
|
const UA = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36';
|
|
@@ -228,6 +228,7 @@ async function main() {
|
|
|
228
228
|
frames: [],
|
|
229
229
|
first5s: [],
|
|
230
230
|
video_file: '',
|
|
231
|
+
frame_version: 3,
|
|
231
232
|
crawled_at: new Date().toISOString(),
|
|
232
233
|
dir: outDir,
|
|
233
234
|
};
|
|
@@ -276,6 +277,7 @@ async function main() {
|
|
|
276
277
|
frames: [],
|
|
277
278
|
first5s: [],
|
|
278
279
|
video_file: videoFile,
|
|
280
|
+
frame_version: 3,
|
|
279
281
|
crawled_at: new Date().toISOString(),
|
|
280
282
|
dir: outDir,
|
|
281
283
|
};
|
|
@@ -300,8 +302,13 @@ async function main() {
|
|
|
300
302
|
if (videoFile && fs.existsSync(videoFile)) {
|
|
301
303
|
try {
|
|
302
304
|
sceneTimes = detectSceneTimes(videoFile, { threshold: 0.15, maxFrames: 16 });
|
|
303
|
-
|
|
304
|
-
|
|
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;
|
|
305
312
|
} catch (err) {
|
|
306
313
|
log('[video] ffmpeg frame extraction failed: ' + (err && err.message ? err.message : String(err)));
|
|
307
314
|
}
|
|
@@ -341,6 +348,7 @@ async function main() {
|
|
|
341
348
|
fixed_times: fixedTimes,
|
|
342
349
|
video_file: videoFile,
|
|
343
350
|
download_error: downloadError,
|
|
351
|
+
frame_version: 3,
|
|
344
352
|
crawled_at: new Date().toISOString(),
|
|
345
353
|
dir: outDir,
|
|
346
354
|
};
|
|
@@ -2,14 +2,21 @@
|
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Shared ffmpeg helpers for Douyin note carousel video slides and standalone
|
|
5
|
-
* videos.
|
|
6
|
-
*
|
|
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',
|
|
@@ -96,6 +103,18 @@ function mergeFrameTimes(fixed, scene, { minGap = 0.25, maxFrames = 12 } = {}) {
|
|
|
96
103
|
return [...new Set(picked)].sort((a, b) => a - b);
|
|
97
104
|
}
|
|
98
105
|
|
|
106
|
+
function extractFrameAt(file, target, time, timeout = 60000) {
|
|
107
|
+
const result = spawnSync('ffmpeg', [
|
|
108
|
+
'-y', '-hide_banner', '-loglevel', 'error',
|
|
109
|
+
'-ss', String(time),
|
|
110
|
+
'-i', file,
|
|
111
|
+
'-frames:v', '1',
|
|
112
|
+
'-q:v', '2',
|
|
113
|
+
target,
|
|
114
|
+
], { encoding: 'utf8', timeout });
|
|
115
|
+
return result.status === 0 && fs.existsSync(target);
|
|
116
|
+
}
|
|
117
|
+
|
|
99
118
|
function extractFramesAt(file, outDir, prefix, times, { timeout = 60000 } = {}) {
|
|
100
119
|
fs.mkdirSync(outDir, { recursive: true });
|
|
101
120
|
for (const name of fs.readdirSync(outDir)) {
|
|
@@ -108,21 +127,271 @@ function extractFramesAt(file, outDir, prefix, times, { timeout = 60000 } = {})
|
|
|
108
127
|
const time = Number(times[index]);
|
|
109
128
|
if (!Number.isFinite(time) || time < 0) continue;
|
|
110
129
|
const target = path.join(outDir, prefix + '_' + String(frames.length + 1).padStart(3, '0') + '.jpg');
|
|
111
|
-
|
|
112
|
-
'-y', '-hide_banner', '-loglevel', 'error',
|
|
113
|
-
'-ss', String(time),
|
|
114
|
-
'-i', file,
|
|
115
|
-
'-frames:v', '1',
|
|
116
|
-
'-q:v', '2',
|
|
117
|
-
target,
|
|
118
|
-
], { encoding: 'utf8', timeout });
|
|
119
|
-
if (result.status === 0 && fs.existsSync(target)) {
|
|
130
|
+
if (extractFrameAt(file, target, time, timeout)) {
|
|
120
131
|
frames.push({ index: frames.length + 1, time: Math.round(time * 10) / 10, file: target });
|
|
121
132
|
}
|
|
122
133
|
}
|
|
123
134
|
return frames;
|
|
124
135
|
}
|
|
125
136
|
|
|
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;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
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.
|
|
161
|
+
*/
|
|
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 = [],
|
|
218
|
+
maxFrames = 24,
|
|
219
|
+
stableThreshold = 0.012,
|
|
220
|
+
maxGap = null,
|
|
221
|
+
} = {}) {
|
|
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
|
+
|
|
300
|
+
const selected = [];
|
|
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 });
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
selected.sort((a, b) => a.sample.time - b.sample.time);
|
|
336
|
+
const distinct = [];
|
|
337
|
+
for (const item of selected) {
|
|
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
|
+
}
|
|
346
|
+
distinct.push(item);
|
|
347
|
+
}
|
|
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
|
+
};
|
|
393
|
+
}
|
|
394
|
+
|
|
126
395
|
module.exports = {
|
|
127
396
|
probeDuration,
|
|
128
397
|
detectSceneTimes,
|
|
@@ -130,4 +399,8 @@ module.exports = {
|
|
|
130
399
|
fixedVideoTimes,
|
|
131
400
|
mergeFrameTimes,
|
|
132
401
|
extractFramesAt,
|
|
402
|
+
denseSampleInterval,
|
|
403
|
+
analyzeDenseFrames,
|
|
404
|
+
selectDenseFrameTimes,
|
|
405
|
+
extractDenseFramesAt,
|
|
133
406
|
};
|