@cloud411716/fancy-webnovel 4.8.0 → 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.
- package/docs/douyin-plugin.md +10 -5
- package/package.json +1 -1
- package/plugins/fancy-douyin/deploy.js +2 -1
- package/plugins/fancy-douyin/index.js +31 -3
- package/plugins/fancy-douyin/prompts/01-analysis-prompt.md +3 -0
- package/plugins/fancy-douyin/scripts/crawl-note.cjs +360 -48
- package/plugins/fancy-douyin/scripts/crawl-video.cjs +19 -75
- package/plugins/fancy-douyin/scripts/video-frames.cjs +133 -0
- package/plugins/fancy-douyin/templates.js +8 -4
package/docs/douyin-plugin.md
CHANGED
|
@@ -33,8 +33,10 @@ https://www.douyin.com/user/MS4wLjABAAAA...
|
|
|
33
33
|
LLM 能力自检(图片 / 视频)
|
|
34
34
|
→ 两种能力都没有:退出并通知
|
|
35
35
|
→ 依次扫描账号主页,收集 /note/ 图文和 /video/ 视频
|
|
36
|
-
→ 跳过 crawled.json
|
|
37
|
-
→
|
|
36
|
+
→ 跳过 crawled.json 中已成功入库、已确认无关或已标记失败跳过的作品
|
|
37
|
+
→ 图文:逐页判断类型
|
|
38
|
+
→ 图片页:下载轮播原图并转成 JPG(避免滚动时截到半张图)
|
|
39
|
+
→ 视频页:下载该页短视频,用 ffmpeg scene 检测 + 固定间隔兜底抽帧,拼成一张关键帧图
|
|
38
40
|
→ 视频:先判断时长
|
|
39
41
|
→ 超过 1 分钟:直接跳过并记录
|
|
40
42
|
→ 不超过 1 分钟:抽取前 5 秒关键帧,先判断是否与网文创作有关
|
|
@@ -47,7 +49,7 @@ LLM 能力自检(图片 / 视频)
|
|
|
47
49
|
→ 继续下一篇
|
|
48
50
|
```
|
|
49
51
|
|
|
50
|
-
|
|
52
|
+
作品级失败(下载、抽帧、LLM 整理失败)会记录为 `failed + skip`,本次跳过且下次不再重试;账号扫描失败不会写入作品记录,下次运行仍会重试。
|
|
51
53
|
|
|
52
54
|
## 登录与验证
|
|
53
55
|
|
|
@@ -85,7 +87,7 @@ cookies 会额外镜像到:
|
|
|
85
87
|
```text
|
|
86
88
|
<工作区>/.fancy/douyin/
|
|
87
89
|
├── accounts.json # 账号主页记录
|
|
88
|
-
├── crawled.json #
|
|
90
|
+
├── crawled.json # 已成功入库、确认无关或失败跳过的作品 ID
|
|
89
91
|
├── login-state.json # cookies 镜像(0600)
|
|
90
92
|
├── chrome-profile/ # Chrome 登录态
|
|
91
93
|
├── chrome.json # CDP 端口、profile 与 headed/headless 模式
|
|
@@ -100,6 +102,7 @@ cookies 会额外镜像到:
|
|
|
100
102
|
├── scan-account.cjs
|
|
101
103
|
├── crawl-note.cjs
|
|
102
104
|
├── crawl-video.cjs
|
|
105
|
+
├── video-frames.cjs
|
|
103
106
|
├── lib.cjs
|
|
104
107
|
└── package.json
|
|
105
108
|
```
|
|
@@ -131,7 +134,9 @@ id / kind / subkind / name / tags / genres / note / source
|
|
|
131
134
|
- 只采集个人研究/已授权账号,不要批量抓取或二次分发受版权保护的图片、视频和文案。
|
|
132
135
|
- 图文截图不是页面视口截图,而是下载每页轮播原图后再转成 JPEG,所以不会因为
|
|
133
136
|
滚动、懒加载或页面动画截到残缺图片。
|
|
134
|
-
-
|
|
137
|
+
- 图文作品的轮播可以混合图片页和视频页。视频页会下载该页短视频,用 ffmpeg scene 检测抓画面突变帧,再用固定间隔帧兜底,
|
|
138
|
+
拼成一张关键帧图交给 LLM;这样快速切换的画面和动态字幕/标语不会被封面漏掉。
|
|
139
|
+
- 独立视频作品会先尝试下载原片并用 ffmpeg 抽帧;下载失败时退化为播放器元素截图。
|
|
135
140
|
视频时长超过 1 分钟直接跳过;前 5 秒与网文创作无关也跳过。
|
|
136
141
|
- 抖音 DOM/类名会变,`scan-account.cjs`、`crawl-note.cjs` 和 `crawl-video.cjs`
|
|
137
142
|
的选择器可能需要维护。
|
package/package.json
CHANGED
|
@@ -16,7 +16,7 @@ const HERE = __dirname;
|
|
|
16
16
|
const requireHere = createRequire(import.meta.url);
|
|
17
17
|
|
|
18
18
|
export const DOUYIN_TOOL_DIR = path.join('.fancy-tools', 'fancy-douyin');
|
|
19
|
-
export const TOOL_FILES = ['lib.cjs', 'start-chrome.cjs', 'scan-account.cjs', 'crawl-note.cjs', 'crawl-video.cjs'];
|
|
19
|
+
export const TOOL_FILES = ['lib.cjs', 'video-frames.cjs', 'start-chrome.cjs', 'scan-account.cjs', 'crawl-note.cjs', 'crawl-video.cjs'];
|
|
20
20
|
|
|
21
21
|
export function playwrightNodePath() {
|
|
22
22
|
try {
|
|
@@ -115,6 +115,7 @@ 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',
|
|
118
|
+
'视频抽帧:video-frames.cjs(ffmpeg scene 检测 + 固定间隔兜底)',
|
|
118
119
|
'登录态与采集记录在 <工作区>/.fancy/douyin/ 下。',
|
|
119
120
|
'不要手工修改本目录脚本;重新运行 /fancy-douyin 会刷新。',
|
|
120
121
|
'',
|
|
@@ -62,6 +62,10 @@ function sleep(ms) {
|
|
|
62
62
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
63
63
|
}
|
|
64
64
|
|
|
65
|
+
function authFailureText(text) {
|
|
66
|
+
return /登录|验证|login_required/i.test(String(text || ''));
|
|
67
|
+
}
|
|
68
|
+
|
|
65
69
|
function abortRequested(invocation) {
|
|
66
70
|
return Boolean(invocation && invocation.signal && invocation.signal.aborted);
|
|
67
71
|
}
|
|
@@ -693,6 +697,23 @@ async function runCrawl(ctx, invocation, session, taskList) {
|
|
|
693
697
|
for (const account of accounts) {
|
|
694
698
|
if (abortRequested(invocation)) { aborted = true; break; }
|
|
695
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
|
+
};
|
|
696
717
|
const scan = await runWithLogin(
|
|
697
718
|
ctx, invocation, session, root, tools.scripts.scan,
|
|
698
719
|
['--workspace', root, '--account', account.url, '--cdp', browser.cdp,
|
|
@@ -706,7 +727,7 @@ async function runCrawl(ctx, invocation, session, taskList) {
|
|
|
706
727
|
);
|
|
707
728
|
if (!scan.ok) {
|
|
708
729
|
failures.push({ url: account.url, reason: scan.error });
|
|
709
|
-
if (scan.cancelled) { aborted = true; break; }
|
|
730
|
+
if (scan.cancelled || authFailureText(scan.error)) { aborted = true; break; }
|
|
710
731
|
continue;
|
|
711
732
|
}
|
|
712
733
|
|
|
@@ -743,12 +764,14 @@ async function runCrawl(ctx, invocation, session, taskList) {
|
|
|
743
764
|
);
|
|
744
765
|
if (!noteResult.ok) {
|
|
745
766
|
failures.push({ id: noteId, url: card.href, reason: noteResult.error });
|
|
746
|
-
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);
|
|
747
769
|
continue;
|
|
748
770
|
}
|
|
749
771
|
const note = noteResult.json.note;
|
|
750
772
|
if (!note || !Array.isArray(note.screenshots) || !note.screenshots.length) {
|
|
751
773
|
failures.push({ id: noteId, url: card.href, reason: '没有截图' });
|
|
774
|
+
markFailed(noteId, card, { type: 'note', dir: noteDir }, '没有截图');
|
|
752
775
|
continue;
|
|
753
776
|
}
|
|
754
777
|
processedWorks += 1;
|
|
@@ -769,6 +792,7 @@ async function runCrawl(ctx, invocation, session, taskList) {
|
|
|
769
792
|
failures.push({ id: noteId, url: card.href, reason: analyzed.error });
|
|
770
793
|
if (analyzed.aborted) { aborted = true; break outer; }
|
|
771
794
|
if (analyzed.fatal) break outer;
|
|
795
|
+
markFailed(noteId, card, { type: 'note', dir: noteDir, title: note.title }, analyzed.error);
|
|
772
796
|
continue;
|
|
773
797
|
}
|
|
774
798
|
if (analyzed.skipped) {
|
|
@@ -834,7 +858,8 @@ async function runCrawl(ctx, invocation, session, taskList) {
|
|
|
834
858
|
);
|
|
835
859
|
if (!videoResult.ok) {
|
|
836
860
|
failures.push({ id: videoId, url: card.href, reason: videoResult.error });
|
|
837
|
-
if (videoResult.cancelled) { aborted = true; break outer; }
|
|
861
|
+
if (videoResult.cancelled || authFailureText(videoResult.error)) { aborted = true; break outer; }
|
|
862
|
+
markFailed(videoId, card, { type: 'video', dir: videoDir }, videoResult.error);
|
|
838
863
|
continue;
|
|
839
864
|
}
|
|
840
865
|
const video = videoResult.json.video || {};
|
|
@@ -857,6 +882,7 @@ async function runCrawl(ctx, invocation, session, taskList) {
|
|
|
857
882
|
}
|
|
858
883
|
if (!video || !Array.isArray(video.frames) || !video.frames.length) {
|
|
859
884
|
failures.push({ id: videoId, url: card.href, reason: '没有视频关键帧' });
|
|
885
|
+
markFailed(videoId, card, { type: 'video', dir: videoDir, title: video.title }, '没有视频关键帧');
|
|
860
886
|
continue;
|
|
861
887
|
}
|
|
862
888
|
processedWorks += 1;
|
|
@@ -874,6 +900,7 @@ async function runCrawl(ctx, invocation, session, taskList) {
|
|
|
874
900
|
if (!relevance.ok) {
|
|
875
901
|
failures.push({ id: videoId, url: card.href, reason: relevance.error });
|
|
876
902
|
if (relevance.aborted) { aborted = true; break outer; }
|
|
903
|
+
markFailed(videoId, card, { type: 'video', dir: videoDir, title: video.title, duration: video.duration }, relevance.error);
|
|
877
904
|
continue;
|
|
878
905
|
}
|
|
879
906
|
if (relevance.skip) {
|
|
@@ -907,6 +934,7 @@ async function runCrawl(ctx, invocation, session, taskList) {
|
|
|
907
934
|
failures.push({ id: videoId, url: card.href, reason: analyzed.error });
|
|
908
935
|
if (analyzed.aborted) { aborted = true; break outer; }
|
|
909
936
|
if (analyzed.fatal) break outer;
|
|
937
|
+
markFailed(videoId, card, { type: 'video', dir: videoDir, title: video.title, duration: video.duration }, analyzed.error);
|
|
910
938
|
continue;
|
|
911
939
|
}
|
|
912
940
|
if (analyzed.skipped) {
|
|
@@ -10,6 +10,9 @@
|
|
|
10
10
|
|
|
11
11
|
{{SCREENSHOT_LIST}}
|
|
12
12
|
|
|
13
|
+
截图可能来自图片页,也可能是同一页视频的关键帧拼图。带“第 X 页(视频……)”的图片属于同一页素材,请按从左到右读取拼图里的多个瞬间,合并提取,不要把同一页的多个瞬间当成多条素材。
|
|
14
|
+
视频关键帧里的动态字幕、标语、口播文字也要提取到 `name`、`tags` 或 `note` 中;不要只看封面图。
|
|
15
|
+
|
|
13
16
|
## 任务
|
|
14
17
|
|
|
15
18
|
分析截图中的内容,如果内容与小说网文创作的设定,素材,写作等无关的话则不进行分析;根据作品信息中的作品标题和截图中内容的排版布局(图片可能使用不同的排版布局对同类别内容进行归类)决定 kind、subkind、tags、genres 四个字段,并在 note 字段中补充一句
|
|
@@ -1,16 +1,25 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
* Open one Douyin /note/ work, capture its
|
|
5
|
-
* write note.json.
|
|
4
|
+
* Open one Douyin /note/ work, capture its carousel slides as JPG screenshots
|
|
5
|
+
* and write note.json. A slide can be a still image or a short video; video
|
|
6
|
+
* slides are downloaded and sampled into keyframes so their captions are not
|
|
7
|
+
* lost. stdout is one JSON object; Chrome stays open.
|
|
6
8
|
*/
|
|
7
9
|
|
|
8
10
|
const fs = require('fs');
|
|
9
11
|
const path = require('path');
|
|
12
|
+
const { spawnSync } = require('child_process');
|
|
10
13
|
const {
|
|
11
14
|
log, parseArgs, connect, installExternalProtocolGuard, restoreCookies, saveCookies,
|
|
12
15
|
safeGateResult, printJson, fail, ensureDir,
|
|
13
16
|
} = require('./lib.cjs');
|
|
17
|
+
const {
|
|
18
|
+
probeDuration, detectSceneTimes, fixedShortTimes, mergeFrameTimes, extractFramesAt,
|
|
19
|
+
} = require('./video-frames.cjs');
|
|
20
|
+
|
|
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;
|
|
14
23
|
|
|
15
24
|
function noteId(url) {
|
|
16
25
|
const match = String(url).match(/\/note\/(\d+)/);
|
|
@@ -33,37 +42,111 @@ async function readMetadata(page) {
|
|
|
33
42
|
});
|
|
34
43
|
}
|
|
35
44
|
|
|
36
|
-
|
|
45
|
+
async function activeSlideInfo(page) {
|
|
46
|
+
return await page.evaluate(() => {
|
|
47
|
+
const slides = [...document.querySelectorAll('.dySwiperSlide')]
|
|
48
|
+
.map((el, index) => ({ el, index, rect: el.getBoundingClientRect() }))
|
|
49
|
+
.filter((slide) => slide.rect.width > 500 && slide.rect.height > 200);
|
|
50
|
+
if (!slides.length) return null;
|
|
51
|
+
const active = slides.find((slide) => slide.rect.x > -20 && slide.rect.x < window.innerWidth / 2)
|
|
52
|
+
|| slides.slice().sort((a, b) => Math.abs(a.rect.x - 160) - Math.abs(b.rect.x - 160))[0];
|
|
53
|
+
if (!active) return null;
|
|
54
|
+
const el = active.el;
|
|
55
|
+
const video = el.querySelector('video');
|
|
56
|
+
let videoSrc = '';
|
|
57
|
+
let duration = null;
|
|
58
|
+
if (video) {
|
|
59
|
+
videoSrc = video.currentSrc || video.src || '';
|
|
60
|
+
if (!videoSrc || videoSrc.startsWith('blob:')) {
|
|
61
|
+
const source = video.querySelector('source');
|
|
62
|
+
if (source) videoSrc = source.src || source.getAttribute('src') || videoSrc;
|
|
63
|
+
}
|
|
64
|
+
if (String(videoSrc).startsWith('//')) videoSrc = 'https:' + videoSrc;
|
|
65
|
+
duration = Number.isFinite(video.duration) && video.duration > 0 ? video.duration : null;
|
|
66
|
+
}
|
|
67
|
+
const img = el.querySelector('img[src*="tplv-dy-aweme-images"], img[src*="aweme-images"]') || el.querySelector('img');
|
|
68
|
+
return {
|
|
69
|
+
domIndex: active.index,
|
|
70
|
+
x: Math.round(active.rect.x),
|
|
71
|
+
y: Math.round(active.rect.y),
|
|
72
|
+
width: Math.round(active.rect.width),
|
|
73
|
+
height: Math.round(active.rect.height),
|
|
74
|
+
hasVideo: Boolean(videoSrc && !videoSrc.startsWith('blob:')),
|
|
75
|
+
videoSrc,
|
|
76
|
+
duration,
|
|
77
|
+
imageSrc: img && img.src ? img.src : '',
|
|
78
|
+
};
|
|
79
|
+
});
|
|
80
|
+
}
|
|
37
81
|
|
|
38
|
-
async function
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
const unique = [];
|
|
48
|
-
for (const img of imgs.sort((a, b) => a.x - b.x)) {
|
|
49
|
-
if (localSeen.has(img.src)) continue;
|
|
50
|
-
localSeen.add(img.src);
|
|
51
|
-
unique.push(img.src);
|
|
82
|
+
async function freezeSlideVideos(page) {
|
|
83
|
+
await page.evaluate(() => {
|
|
84
|
+
const pause = () => {
|
|
85
|
+
for (const video of document.querySelectorAll('video')) {
|
|
86
|
+
try {
|
|
87
|
+
video.pause();
|
|
88
|
+
video.loop = true;
|
|
89
|
+
video.autoplay = false;
|
|
90
|
+
} catch { /* ignore */ }
|
|
52
91
|
}
|
|
53
|
-
|
|
92
|
+
};
|
|
93
|
+
pause();
|
|
94
|
+
if (window.__fancyDouyinPauseVideos) clearInterval(window.__fancyDouyinPauseVideos);
|
|
95
|
+
window.__fancyDouyinPauseVideos = setInterval(pause, 200);
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function unfreezeSlideVideos(page) {
|
|
100
|
+
try {
|
|
101
|
+
await page.evaluate(() => {
|
|
102
|
+
if (window.__fancyDouyinPauseVideos) clearInterval(window.__fancyDouyinPauseVideos);
|
|
103
|
+
window.__fancyDouyinPauseVideos = null;
|
|
54
104
|
});
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
105
|
+
} catch { /* page may be gone */ }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function advanceSlide(page, current) {
|
|
109
|
+
const x = Number(current && current.x) || 160;
|
|
110
|
+
const y = Number(current && current.y) || 56;
|
|
111
|
+
const width = Number(current && current.width) || 866;
|
|
112
|
+
const height = Number(current && current.height) || 833;
|
|
113
|
+
const startX = Math.round(x + width * 0.8);
|
|
114
|
+
const endX = Math.round(x + width * 0.2);
|
|
115
|
+
const centerY = Math.round(y + height * 0.5);
|
|
116
|
+
await page.mouse.move(startX, centerY);
|
|
117
|
+
await page.mouse.down();
|
|
118
|
+
await page.mouse.move(endX, centerY, { steps: 12 });
|
|
119
|
+
await page.mouse.up();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function clickNextSlide(page) {
|
|
123
|
+
const byClass = page.locator('.odSlyAjv');
|
|
124
|
+
const classCount = await byClass.count();
|
|
125
|
+
log('[note] next buttons: class=' + classCount);
|
|
126
|
+
if (classCount >= 2) {
|
|
127
|
+
try {
|
|
128
|
+
await byClass.nth(classCount - 1).click({ force: true });
|
|
129
|
+
return true;
|
|
130
|
+
} catch { /* fall through */ }
|
|
131
|
+
}
|
|
132
|
+
const arrows = page.locator('div:has(svg filter[id*="arrowRight"])');
|
|
133
|
+
if (await arrows.count()) {
|
|
134
|
+
try {
|
|
135
|
+
await arrows.last().click({ force: true });
|
|
136
|
+
return true;
|
|
137
|
+
} catch { /* fall through */ }
|
|
65
138
|
}
|
|
66
|
-
return
|
|
139
|
+
return false;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function waitActiveSlide(page) {
|
|
143
|
+
let info = null;
|
|
144
|
+
for (let attempt = 0; attempt < 8; attempt += 1) {
|
|
145
|
+
info = await activeSlideInfo(page);
|
|
146
|
+
if (info && (!info.hasVideo || info.duration)) return info;
|
|
147
|
+
await page.waitForTimeout(450);
|
|
148
|
+
}
|
|
149
|
+
return info;
|
|
67
150
|
}
|
|
68
151
|
|
|
69
152
|
async function downloadAsJpeg(context, converterPage, src, file) {
|
|
@@ -95,24 +178,252 @@ async function downloadAsJpeg(context, converterPage, src, file) {
|
|
|
95
178
|
fs.writeFileSync(file, Buffer.from(base64, 'base64'));
|
|
96
179
|
}
|
|
97
180
|
|
|
98
|
-
async function
|
|
99
|
-
const
|
|
181
|
+
async function downloadVideo(context, src, file) {
|
|
182
|
+
const response = await context.request.get(src, {
|
|
183
|
+
headers: {
|
|
184
|
+
Referer: 'https://www.douyin.com/',
|
|
185
|
+
'User-Agent': UA,
|
|
186
|
+
},
|
|
187
|
+
timeout: 120000,
|
|
188
|
+
failOnStatusCode: false,
|
|
189
|
+
});
|
|
190
|
+
if (!response.ok()) throw new Error('下载视频失败:HTTP ' + response.status());
|
|
191
|
+
const body = await response.body();
|
|
192
|
+
if (!body || !body.length) throw new Error('下载视频失败:响应为空');
|
|
193
|
+
fs.writeFileSync(file, body);
|
|
194
|
+
return body.length;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function createVideoContactSheet(frames, outDir, slideNo) {
|
|
198
|
+
const available = (frames || []).filter((frame) => frame && frame.file && fs.existsSync(frame.file));
|
|
199
|
+
if (available.length < 2) return '';
|
|
200
|
+
const file = path.join(outDir, 'slide_' + String(slideNo).padStart(2, '0') + '_frames.jpg');
|
|
201
|
+
const pattern = path.join(outDir, 'slide_' + String(slideNo).padStart(2, '0') + '_frame_*.jpg');
|
|
202
|
+
const columns = Math.min(3, available.length);
|
|
203
|
+
const rows = Math.max(1, Math.ceil(available.length / columns));
|
|
204
|
+
const result = spawnSync('ffmpeg', [
|
|
205
|
+
'-y', '-hide_banner', '-loglevel', 'error',
|
|
206
|
+
'-pattern_type', 'glob', '-i', pattern,
|
|
207
|
+
'-vf', 'scale=700:-1,tile=' + columns + 'x' + rows,
|
|
208
|
+
'-frames:v', '1',
|
|
209
|
+
file,
|
|
210
|
+
], { encoding: 'utf8', timeout: 60000 });
|
|
211
|
+
return result.status === 0 && fs.existsSync(file) ? file : '';
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async function captureVideoFramesFromPage(page, domIndex, outDir, slideNo, times) {
|
|
215
|
+
const list = Array.isArray(times) && times.length ? times : fixedShortTimes(5, 4);
|
|
216
|
+
const slide = page.locator('.dySwiperSlide').nth(domIndex);
|
|
217
|
+
let video = slide.locator('video');
|
|
218
|
+
if (!(await video.count())) video = slide;
|
|
219
|
+
const frames = [];
|
|
220
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
221
|
+
const time = list[index];
|
|
222
|
+
try {
|
|
223
|
+
await page.evaluate(async ({ domIndex: targetIndex, time: targetTime }) => {
|
|
224
|
+
const slides = [...document.querySelectorAll('.dySwiperSlide')];
|
|
225
|
+
const videoEl = slides[targetIndex] ? slides[targetIndex].querySelector('video') : null;
|
|
226
|
+
if (!videoEl) return;
|
|
227
|
+
videoEl.muted = true;
|
|
228
|
+
videoEl.pause();
|
|
229
|
+
const safe = Math.max(0, Math.min(targetTime, Math.max(0, (videoEl.duration || targetTime) - 0.05)));
|
|
230
|
+
if (Math.abs(videoEl.currentTime - safe) > 0.15) {
|
|
231
|
+
await new Promise((resolve) => {
|
|
232
|
+
let settled = false;
|
|
233
|
+
const done = () => {
|
|
234
|
+
if (settled) return;
|
|
235
|
+
settled = true;
|
|
236
|
+
resolve();
|
|
237
|
+
};
|
|
238
|
+
videoEl.addEventListener('seeked', done, { once: true });
|
|
239
|
+
videoEl.currentTime = safe;
|
|
240
|
+
setTimeout(done, 2500);
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
}, { domIndex, time });
|
|
244
|
+
await page.waitForTimeout(220);
|
|
245
|
+
const file = path.join(outDir, 'slide_' + String(slideNo).padStart(2, '0') + '_frame_' + String(index + 1).padStart(2, '0') + '.jpg');
|
|
246
|
+
await video.screenshot({ path: file, type: 'jpeg', quality: 90 });
|
|
247
|
+
frames.push({ index: frames.length + 1, time, file });
|
|
248
|
+
} catch (err) {
|
|
249
|
+
log('[note] video frame capture failed at ' + time + 's: ' + (err && err.message ? err.message : String(err)));
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
return frames;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async function captureFallbackImages(page, context, converterPage, outDir) {
|
|
256
|
+
const urls = await page.evaluate(() => [...document.querySelectorAll('img')]
|
|
257
|
+
.filter((img) => img.src && (img.src.includes('tplv-dy-aweme-images') || img.src.includes('aweme-images')))
|
|
258
|
+
.map((img) => img.src));
|
|
259
|
+
const unique = [...new Set(urls)];
|
|
260
|
+
const slides = [];
|
|
100
261
|
const screenshots = [];
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
const converter = await context.newPage();
|
|
262
|
+
for (let index = 0; index < unique.length; index += 1) {
|
|
263
|
+
const slideNo = index + 1;
|
|
264
|
+
const file = path.join(outDir, 'slide_' + String(slideNo).padStart(2, '0') + '.jpg');
|
|
105
265
|
try {
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
266
|
+
await downloadAsJpeg(context, converterPage, unique[index], file);
|
|
267
|
+
} catch (err) {
|
|
268
|
+
log('[note] fallback image ' + slideNo + ' download failed: ' + (err && err.message ? err.message : String(err)));
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
slides.push({ index: slideNo, type: 'image', file, src: unique[index] });
|
|
272
|
+
screenshots.push({ index: screenshots.length + 1, slide: slideNo, type: 'image', file, label: '第 ' + slideNo + ' 页(图片)' });
|
|
273
|
+
}
|
|
274
|
+
return { slides, screenshots };
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
async function captureSlides(page, context, outDir) {
|
|
278
|
+
const slides = [];
|
|
279
|
+
const screenshots = [];
|
|
280
|
+
let converter = null;
|
|
281
|
+
const seen = new Set();
|
|
282
|
+
try {
|
|
283
|
+
converter = await context.newPage();
|
|
284
|
+
await freezeSlideVideos(page);
|
|
285
|
+
let initialSlides = await page.evaluate(() => document.querySelectorAll('.dySwiperSlide').length);
|
|
286
|
+
if (initialSlides === 0) {
|
|
287
|
+
return await captureFallbackImages(page, context, converter, outDir);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
let current = await waitActiveSlide(page);
|
|
291
|
+
let guard = 0;
|
|
292
|
+
log('[note] carousel initial slides: ' + initialSlides + ', first domIndex: ' + (current && current.domIndex));
|
|
293
|
+
while (current && guard < 40) {
|
|
294
|
+
guard += 1;
|
|
295
|
+
const domCount = await page.evaluate(() => document.querySelectorAll('.dySwiperSlide').length);
|
|
296
|
+
if (domCount > initialSlides) initialSlides = domCount;
|
|
297
|
+
log('[note] processing domIndex ' + current.domIndex + ' (slide ' + (slides.length + 1) + ')');
|
|
298
|
+
if (!seen.has(current.domIndex)) {
|
|
299
|
+
seen.add(current.domIndex);
|
|
300
|
+
const slideNo = slides.length + 1;
|
|
301
|
+
if (current.hasVideo) {
|
|
302
|
+
const videoFile = path.join(outDir, 'slide_' + String(slideNo).padStart(2, '0') + '.mp4');
|
|
303
|
+
let duration = current.duration;
|
|
304
|
+
let frames = [];
|
|
305
|
+
let sceneTimes = [];
|
|
306
|
+
const fixedTimes = fixedShortTimes(duration || 5, 4);
|
|
307
|
+
let times = fixedTimes;
|
|
308
|
+
try {
|
|
309
|
+
await downloadVideo(context, current.videoSrc, videoFile);
|
|
310
|
+
duration = probeDuration(videoFile) || duration;
|
|
311
|
+
sceneTimes = detectSceneTimes(videoFile, { threshold: 0.1, maxFrames: 10 });
|
|
312
|
+
times = mergeFrameTimes(fixedShortTimes(duration || 5, 4), sceneTimes, {
|
|
313
|
+
minGap: 0.25,
|
|
314
|
+
maxFrames: 10,
|
|
315
|
+
});
|
|
316
|
+
frames = extractFramesAt(videoFile, outDir, 'slide_' + String(slideNo).padStart(2, '0') + '_frame', times);
|
|
317
|
+
} catch (err) {
|
|
318
|
+
log('[note] video slide ' + slideNo + ' download/frames failed: ' + (err && err.message ? err.message : String(err)));
|
|
319
|
+
}
|
|
320
|
+
if (!frames.length) {
|
|
321
|
+
frames = await captureVideoFramesFromPage(page, current.domIndex, outDir, slideNo, times.length ? times : fixedTimes);
|
|
322
|
+
}
|
|
323
|
+
const slide = {
|
|
324
|
+
index: slideNo,
|
|
325
|
+
dom_index: current.domIndex,
|
|
326
|
+
type: 'video',
|
|
327
|
+
duration: Number.isFinite(Number(duration)) ? Number(duration) : null,
|
|
328
|
+
video_file: fs.existsSync(videoFile) ? videoFile : '',
|
|
329
|
+
frames,
|
|
330
|
+
scene_times: sceneTimes,
|
|
331
|
+
fixed_times: fixedTimes,
|
|
332
|
+
cover: current.imageSrc,
|
|
333
|
+
};
|
|
334
|
+
slides.push(slide);
|
|
335
|
+
const contact = createVideoContactSheet(frames, outDir, slideNo);
|
|
336
|
+
slide.contact_file = contact;
|
|
337
|
+
if (contact) {
|
|
338
|
+
const times = frames.map((frame) => frame.time + ' 秒').join(' / ');
|
|
339
|
+
screenshots.push({
|
|
340
|
+
index: screenshots.length + 1,
|
|
341
|
+
slide: slideNo,
|
|
342
|
+
type: 'video_contact',
|
|
343
|
+
duration: slide.duration,
|
|
344
|
+
file: contact,
|
|
345
|
+
frames: frames.map((frame) => frame.file),
|
|
346
|
+
label: '第 ' + slideNo + ' 页(视频 ' + (slide.duration ? slide.duration.toFixed(1) + ' 秒' : '') + ',关键帧拼图:' + times + ')',
|
|
347
|
+
});
|
|
348
|
+
} else {
|
|
349
|
+
for (const frame of frames) {
|
|
350
|
+
screenshots.push({
|
|
351
|
+
index: screenshots.length + 1,
|
|
352
|
+
slide: slideNo,
|
|
353
|
+
type: 'video_frame',
|
|
354
|
+
time: frame.time,
|
|
355
|
+
duration: slide.duration,
|
|
356
|
+
file: frame.file,
|
|
357
|
+
label: '第 ' + slideNo + ' 页(视频 ' + (slide.duration ? slide.duration.toFixed(1) + ' 秒' : '') + ',第 ' + frame.time + ' 秒)',
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
} else {
|
|
362
|
+
const file = path.join(outDir, 'slide_' + String(slideNo).padStart(2, '0') + '.jpg');
|
|
363
|
+
let saved = false;
|
|
364
|
+
if (current.imageSrc) {
|
|
365
|
+
try {
|
|
366
|
+
await downloadAsJpeg(context, converter, current.imageSrc, file);
|
|
367
|
+
saved = true;
|
|
368
|
+
} catch (err) {
|
|
369
|
+
log('[note] image slide ' + slideNo + ' download failed: ' + (err && err.message ? err.message : String(err)));
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
if (!saved) {
|
|
373
|
+
try {
|
|
374
|
+
await page.locator('.dySwiperSlide').nth(current.domIndex).screenshot({ path: file, type: 'jpeg', quality: 90 });
|
|
375
|
+
saved = true;
|
|
376
|
+
} catch (err) {
|
|
377
|
+
log('[note] image slide ' + slideNo + ' screenshot failed: ' + (err && err.message ? err.message : String(err)));
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
if (saved) {
|
|
381
|
+
slides.push({
|
|
382
|
+
index: slideNo,
|
|
383
|
+
dom_index: current.domIndex,
|
|
384
|
+
type: 'image',
|
|
385
|
+
file,
|
|
386
|
+
src: current.imageSrc,
|
|
387
|
+
});
|
|
388
|
+
screenshots.push({
|
|
389
|
+
index: screenshots.length + 1,
|
|
390
|
+
slide: slideNo,
|
|
391
|
+
type: 'image',
|
|
392
|
+
file,
|
|
393
|
+
label: '第 ' + slideNo + ' 页(图片)',
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
// 一次只前进一格。优先点轮播右侧箭头;视频播放时按钮偶尔会被
|
|
400
|
+
// 播放器层吃掉,先暂停再重试,仍失败才退回拖拽。
|
|
401
|
+
if (slides.length >= initialSlides) break;
|
|
402
|
+
let next = null;
|
|
403
|
+
for (let press = 0; press < 3 && !next; press += 1) {
|
|
404
|
+
const clicked = await clickNextSlide(page);
|
|
405
|
+
log('[note] next click ' + press + ': ' + clicked);
|
|
406
|
+
if (!clicked) await advanceSlide(page, current);
|
|
407
|
+
for (let wait = 0; wait < 8; wait += 1) {
|
|
408
|
+
await page.waitForTimeout(500);
|
|
409
|
+
const info = await activeSlideInfo(page);
|
|
410
|
+
if (info && info.domIndex !== current.domIndex) {
|
|
411
|
+
next = info;
|
|
412
|
+
break;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
if (!next && press === 0) {
|
|
416
|
+
await page.mouse.click(current.x + current.width / 2, current.y + current.height / 2);
|
|
417
|
+
await page.waitForTimeout(500);
|
|
113
418
|
}
|
|
114
419
|
}
|
|
115
|
-
|
|
420
|
+
log('[note] next domIndex: ' + (next && next.domIndex) + ', seen: ' + [...seen].join(','));
|
|
421
|
+
if (!next || seen.has(next.domIndex)) break;
|
|
422
|
+
current = await waitActiveSlide(page);
|
|
423
|
+
}
|
|
424
|
+
} finally {
|
|
425
|
+
await unfreezeSlideVideos(page);
|
|
426
|
+
if (converter) {
|
|
116
427
|
try { await converter.close(); } catch { /* ignore */ }
|
|
117
428
|
}
|
|
118
429
|
}
|
|
@@ -121,12 +432,12 @@ async function captureSlides(page, context, outDir) {
|
|
|
121
432
|
const file = path.join(outDir, 'note.jpg');
|
|
122
433
|
try {
|
|
123
434
|
await page.screenshot({ path: file, type: 'jpeg', quality: 90, fullPage: false });
|
|
124
|
-
screenshots.push({ index: 1, file,
|
|
435
|
+
screenshots.push({ index: 1, slide: 1, type: 'image', file, label: '第 1 页(页面截图)' });
|
|
125
436
|
} catch (err) {
|
|
126
|
-
throw new Error('
|
|
437
|
+
throw new Error('没有找到可分析的图片或视频,且页面截图失败:' + (err && err.message ? err.message : String(err)));
|
|
127
438
|
}
|
|
128
439
|
}
|
|
129
|
-
return screenshots;
|
|
440
|
+
return { slides, screenshots };
|
|
130
441
|
}
|
|
131
442
|
|
|
132
443
|
async function main() {
|
|
@@ -158,7 +469,7 @@ async function main() {
|
|
|
158
469
|
}
|
|
159
470
|
|
|
160
471
|
const meta = await readMetadata(page);
|
|
161
|
-
const
|
|
472
|
+
const captured = await captureSlides(page, context, outDir);
|
|
162
473
|
|
|
163
474
|
const afterGate = await safeGateResult(page, outDir);
|
|
164
475
|
if (afterGate) {
|
|
@@ -176,7 +487,8 @@ async function main() {
|
|
|
176
487
|
title: meta.title,
|
|
177
488
|
description: meta.description,
|
|
178
489
|
body: meta.body,
|
|
179
|
-
|
|
490
|
+
slides: captured.slides,
|
|
491
|
+
screenshots: captured.screenshots,
|
|
180
492
|
crawled_at: new Date().toISOString(),
|
|
181
493
|
dir: outDir,
|
|
182
494
|
};
|
|
@@ -18,6 +18,9 @@ const {
|
|
|
18
18
|
log, parseArgs, connect, installExternalProtocolGuard, restoreCookies, saveCookies,
|
|
19
19
|
safeGateResult, printJson, fail, ensureDir,
|
|
20
20
|
} = require('./lib.cjs');
|
|
21
|
+
const {
|
|
22
|
+
probeDuration, detectSceneTimes, fixedVideoTimes, mergeFrameTimes, extractFramesAt,
|
|
23
|
+
} = require('./video-frames.cjs');
|
|
21
24
|
|
|
22
25
|
const UA = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36';
|
|
23
26
|
const FIRST_SECONDS = 5;
|
|
@@ -118,70 +121,8 @@ async function downloadVideo(context, src, file) {
|
|
|
118
121
|
return body.length;
|
|
119
122
|
}
|
|
120
123
|
|
|
121
|
-
function ffprobeDuration(file) {
|
|
122
|
-
const result = spawnSync('ffprobe', [
|
|
123
|
-
'-v', 'error',
|
|
124
|
-
'-show_entries', 'format=duration',
|
|
125
|
-
'-of', 'default=nw=1:nk=1',
|
|
126
|
-
file,
|
|
127
|
-
], { encoding: 'utf8', timeout: 30000 });
|
|
128
|
-
if (result.status !== 0) return null;
|
|
129
|
-
const value = Number(String(result.stdout || '').trim());
|
|
130
|
-
return Number.isFinite(value) && value > 0 ? value : null;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
function runFfmpeg(args) {
|
|
134
|
-
const result = spawnSync('ffmpeg', args, { encoding: 'utf8', timeout: 180000 });
|
|
135
|
-
if (result.status !== 0) {
|
|
136
|
-
throw new Error((result.stderr || result.stdout || 'ffmpeg 执行失败').trim().slice(0, 500));
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
function jpegFiles(dir, pattern) {
|
|
141
|
-
try {
|
|
142
|
-
return fs.readdirSync(dir).filter((name) => pattern.test(name)).sort();
|
|
143
|
-
} catch {
|
|
144
|
-
return [];
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
function extractFramesWithFfmpeg(videoFile, outDir) {
|
|
149
|
-
const framesDir = path.join(outDir, 'frames');
|
|
150
|
-
ensureDir(framesDir);
|
|
151
|
-
runFfmpeg([
|
|
152
|
-
'-y', '-hide_banner', '-loglevel', 'error',
|
|
153
|
-
'-i', videoFile,
|
|
154
|
-
'-t', String(FIRST_SECONDS),
|
|
155
|
-
'-vf', 'fps=1',
|
|
156
|
-
'-q:v', '2',
|
|
157
|
-
path.join(framesDir, 'first_%02d.jpg'),
|
|
158
|
-
]);
|
|
159
|
-
runFfmpeg([
|
|
160
|
-
'-y', '-hide_banner', '-loglevel', 'error',
|
|
161
|
-
'-i', videoFile,
|
|
162
|
-
'-vf', 'fps=1/' + String(FRAME_STEP_SECONDS),
|
|
163
|
-
'-q:v', '2',
|
|
164
|
-
path.join(framesDir, 'all_%02d.jpg'),
|
|
165
|
-
]);
|
|
166
|
-
|
|
167
|
-
const first5s = jpegFiles(framesDir, /^first_\d+\.jpg$/).map((name, index) => ({
|
|
168
|
-
index: index + 1,
|
|
169
|
-
time: index,
|
|
170
|
-
file: path.join(framesDir, name),
|
|
171
|
-
}));
|
|
172
|
-
const all = jpegFiles(framesDir, /^all_\d+\.jpg$/).map((name, index) => ({
|
|
173
|
-
index: index + 1,
|
|
174
|
-
time: index * FRAME_STEP_SECONDS,
|
|
175
|
-
file: path.join(framesDir, name),
|
|
176
|
-
}));
|
|
177
|
-
const later = all.filter((frame) => frame.time >= FIRST_SECONDS);
|
|
178
|
-
return {
|
|
179
|
-
first5s: first5s.length ? first5s : all.slice(0, 1),
|
|
180
|
-
frames: [...first5s, ...later],
|
|
181
|
-
};
|
|
182
|
-
}
|
|
183
124
|
|
|
184
|
-
async function captureFramesFromPage(page, outDir, duration) {
|
|
125
|
+
async function captureFramesFromPage(page, outDir, duration, times) {
|
|
185
126
|
const framesDir = path.join(outDir, 'frames');
|
|
186
127
|
ensureDir(framesDir);
|
|
187
128
|
const selector = 'video[mediatype="video"]';
|
|
@@ -189,14 +130,11 @@ async function captureFramesFromPage(page, outDir, duration) {
|
|
|
189
130
|
if (!handle) handle = await page.$('video');
|
|
190
131
|
if (!handle) throw new Error('没有找到视频元素,无法截取关键帧');
|
|
191
132
|
|
|
192
|
-
const
|
|
193
|
-
const limit = Number.isFinite(duration) && duration > 0 ? duration : FIRST_SECONDS;
|
|
194
|
-
for (let time = 0; time < Math.min(FIRST_SECONDS, limit); time += 1) times.push(time);
|
|
195
|
-
for (let time = FIRST_SECONDS; time < limit; time += FRAME_STEP_SECONDS) times.push(time);
|
|
133
|
+
const list = Array.isArray(times) && times.length ? times : fixedVideoTimes(duration || FIRST_SECONDS);
|
|
196
134
|
|
|
197
135
|
const captured = [];
|
|
198
|
-
for (let index = 0; index <
|
|
199
|
-
const time =
|
|
136
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
137
|
+
const time = list[index];
|
|
200
138
|
try {
|
|
201
139
|
await page.evaluate(async ({ selector: sel, time: target }) => {
|
|
202
140
|
const video = document.querySelector(sel) || document.querySelector('video');
|
|
@@ -310,7 +248,7 @@ async function main() {
|
|
|
310
248
|
try {
|
|
311
249
|
videoFile = path.join(outDir, 'video.mp4');
|
|
312
250
|
await downloadVideo(context, directUrl, videoFile);
|
|
313
|
-
const probed =
|
|
251
|
+
const probed = probeDuration(videoFile);
|
|
314
252
|
if (probed) duration = probed;
|
|
315
253
|
} catch (err) {
|
|
316
254
|
downloadError = err && err.message ? err.message : String(err);
|
|
@@ -356,20 +294,24 @@ async function main() {
|
|
|
356
294
|
|
|
357
295
|
let frames = [];
|
|
358
296
|
let first5s = [];
|
|
297
|
+
let sceneTimes = [];
|
|
298
|
+
const fixedTimes = fixedVideoTimes(duration);
|
|
299
|
+
let times = fixedTimes;
|
|
359
300
|
if (videoFile && fs.existsSync(videoFile)) {
|
|
360
301
|
try {
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
302
|
+
sceneTimes = detectSceneTimes(videoFile, { threshold: 0.15, maxFrames: 16 });
|
|
303
|
+
times = mergeFrameTimes(fixedTimes, sceneTimes, { minGap: 0.4, maxFrames: 24 });
|
|
304
|
+
frames = extractFramesAt(videoFile, outDir, 'video_frame', times);
|
|
364
305
|
} catch (err) {
|
|
365
306
|
log('[video] ffmpeg frame extraction failed: ' + (err && err.message ? err.message : String(err)));
|
|
366
307
|
}
|
|
367
308
|
}
|
|
368
309
|
if (!frames.length) {
|
|
369
|
-
const captured = await captureFramesFromPage(page, outDir, duration);
|
|
310
|
+
const captured = await captureFramesFromPage(page, outDir, duration, times);
|
|
370
311
|
frames = captured.frames;
|
|
371
|
-
first5s = captured.first5s;
|
|
372
312
|
}
|
|
313
|
+
first5s = frames.filter((frame) => Number(frame.time) < FIRST_SECONDS);
|
|
314
|
+
if (!first5s.length) first5s = frames.slice(0, 1);
|
|
373
315
|
if (!frames.length) throw new Error('没有抽取到视频关键帧');
|
|
374
316
|
|
|
375
317
|
const afterGate = await safeGateResult(page, outDir);
|
|
@@ -395,6 +337,8 @@ async function main() {
|
|
|
395
337
|
height: main.height || 0,
|
|
396
338
|
frames,
|
|
397
339
|
first5s,
|
|
340
|
+
scene_times: sceneTimes,
|
|
341
|
+
fixed_times: fixedTimes,
|
|
398
342
|
video_file: videoFile,
|
|
399
343
|
download_error: downloadError,
|
|
400
344
|
crawled_at: new Date().toISOString(),
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
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.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const fs = require('fs');
|
|
10
|
+
const path = require('path');
|
|
11
|
+
const { spawnSync } = require('child_process');
|
|
12
|
+
|
|
13
|
+
function probeDuration(file) {
|
|
14
|
+
const result = spawnSync('ffprobe', [
|
|
15
|
+
'-v', 'error',
|
|
16
|
+
'-show_entries', 'format=duration',
|
|
17
|
+
'-of', 'default=nw=1:nk=1',
|
|
18
|
+
file,
|
|
19
|
+
], { encoding: 'utf8', timeout: 30000 });
|
|
20
|
+
if (result.status !== 0) return null;
|
|
21
|
+
const value = Number(String(result.stdout || '').trim());
|
|
22
|
+
return Number.isFinite(value) && value > 0 ? value : null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Detect visual cuts with ffmpeg's scene score. Returns the cut timestamps in
|
|
27
|
+
* seconds, sorted and capped. The threshold is intentionally low for short
|
|
28
|
+
* carousel clips (animated captions often score only 0.1–0.2).
|
|
29
|
+
*/
|
|
30
|
+
function detectSceneTimes(file, { threshold = 0.15, maxFrames = 16, timeout = 180000 } = {}) {
|
|
31
|
+
const result = spawnSync('ffmpeg', [
|
|
32
|
+
'-hide_banner', '-loglevel', 'info',
|
|
33
|
+
'-i', file,
|
|
34
|
+
'-vf', "select='gt(scene," + threshold + ")',showinfo",
|
|
35
|
+
'-an',
|
|
36
|
+
'-f', 'null',
|
|
37
|
+
'-',
|
|
38
|
+
], { encoding: 'utf8', timeout, maxBuffer: 20 * 1024 * 1024 });
|
|
39
|
+
if (result.status !== 0) return [];
|
|
40
|
+
const times = [];
|
|
41
|
+
const re = /pts_time:\s*([0-9]+(?:\.[0-9]+)?)/g;
|
|
42
|
+
let match;
|
|
43
|
+
const text = String(result.stderr || '');
|
|
44
|
+
while ((match = re.exec(text))) {
|
|
45
|
+
const value = Number(match[1]);
|
|
46
|
+
if (Number.isFinite(value)) times.push(Math.round(value * 100) / 100);
|
|
47
|
+
}
|
|
48
|
+
return [...new Set(times)].sort((a, b) => a - b).slice(0, maxFrames);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function fixedShortTimes(duration, count = 4) {
|
|
52
|
+
const total = Number.isFinite(Number(duration)) && Number(duration) > 0 ? Number(duration) : 5;
|
|
53
|
+
const n = Math.max(1, Number(count) || 4);
|
|
54
|
+
const times = [];
|
|
55
|
+
for (let index = 0; index < n; index += 1) {
|
|
56
|
+
const ratio = n === 1 ? 0.5 : index / (n - 1);
|
|
57
|
+
const time = 0.2 + ratio * Math.max(0, total - 0.4);
|
|
58
|
+
times.push(Math.round(time * 10) / 10);
|
|
59
|
+
}
|
|
60
|
+
return [...new Set(times)];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function fixedVideoTimes(duration) {
|
|
64
|
+
const total = Number.isFinite(Number(duration)) && Number(duration) > 0 ? Number(duration) : 5;
|
|
65
|
+
const times = [];
|
|
66
|
+
const firstEnd = Math.min(5, total);
|
|
67
|
+
for (let time = 0; time < firstEnd; time += 1) times.push(time);
|
|
68
|
+
for (let time = 5; time < total; time += 5) times.push(time);
|
|
69
|
+
if (!times.length) times.push(0);
|
|
70
|
+
return [...new Set(times.map((value) => Math.round(value * 10) / 10))];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Merge scene cuts with fixed fallback times. Scene times win when two
|
|
75
|
+
* candidates are too close. If the result exceeds maxFrames, keep an evenly
|
|
76
|
+
* distributed subset so fast cuts do not crowd out the beginning/end.
|
|
77
|
+
*/
|
|
78
|
+
function mergeFrameTimes(fixed, scene, { minGap = 0.25, maxFrames = 12 } = {}) {
|
|
79
|
+
const all = [];
|
|
80
|
+
const add = (time, source) => {
|
|
81
|
+
const value = Number(time);
|
|
82
|
+
if (!Number.isFinite(value) || value < 0) return;
|
|
83
|
+
if (all.some((item) => Math.abs(item.time - value) < minGap)) return;
|
|
84
|
+
all.push({ time: value, source });
|
|
85
|
+
};
|
|
86
|
+
for (const time of scene || []) add(time, 'scene');
|
|
87
|
+
for (const time of fixed || []) add(time, 'fixed');
|
|
88
|
+
all.sort((a, b) => a.time - b.time);
|
|
89
|
+
const limit = Math.max(1, Number(maxFrames) || 12);
|
|
90
|
+
if (all.length <= limit) return all.map((item) => item.time);
|
|
91
|
+
const picked = [];
|
|
92
|
+
for (let index = 0; index < limit; index += 1) {
|
|
93
|
+
const sourceIndex = Math.round((index * (all.length - 1)) / (limit - 1));
|
|
94
|
+
picked.push(all[sourceIndex].time);
|
|
95
|
+
}
|
|
96
|
+
return [...new Set(picked)].sort((a, b) => a - b);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function extractFramesAt(file, outDir, prefix, times, { timeout = 60000 } = {}) {
|
|
100
|
+
fs.mkdirSync(outDir, { recursive: true });
|
|
101
|
+
for (const name of fs.readdirSync(outDir)) {
|
|
102
|
+
if (name.startsWith(prefix + '_') && name.endsWith('.jpg')) {
|
|
103
|
+
try { fs.rmSync(path.join(outDir, name), { force: true }); } catch { /* ignore */ }
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const frames = [];
|
|
107
|
+
for (let index = 0; index < times.length; index += 1) {
|
|
108
|
+
const time = Number(times[index]);
|
|
109
|
+
if (!Number.isFinite(time) || time < 0) continue;
|
|
110
|
+
const target = path.join(outDir, prefix + '_' + String(frames.length + 1).padStart(3, '0') + '.jpg');
|
|
111
|
+
const result = spawnSync('ffmpeg', [
|
|
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)) {
|
|
120
|
+
frames.push({ index: frames.length + 1, time: Math.round(time * 10) / 10, file: target });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return frames;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
module.exports = {
|
|
127
|
+
probeDuration,
|
|
128
|
+
detectSceneTimes,
|
|
129
|
+
fixedShortTimes,
|
|
130
|
+
fixedVideoTimes,
|
|
131
|
+
mergeFrameTimes,
|
|
132
|
+
extractFramesAt,
|
|
133
|
+
};
|
|
@@ -25,12 +25,12 @@ export function helpText() {
|
|
|
25
25
|
- 有图片识别能力:分析 /note/ 图文作品。
|
|
26
26
|
- 有视频识别能力:分析 /video/ 视频作品。
|
|
27
27
|
- 两种能力都没有:直接退出并通知,不启动采集。
|
|
28
|
-
- 图文作品会下载轮播原图并转成 JPG
|
|
28
|
+
- 图文作品会下载轮播原图并转成 JPG;如果轮播里混有视频页,会下载该页短视频,用场景变化检测 + 固定间隔兜底抽取关键帧拼图。
|
|
29
29
|
- 视频作品先判断时长:超过 1 分钟直接跳过;不超过 1 分钟的先看前 5 秒,
|
|
30
30
|
与网文创作无关就跳过,有关才继续分析关键帧。
|
|
31
31
|
- 如果内容与网文创作无关,LLM 会写入 skip 标记,该作品记为已处理并跳过。
|
|
32
32
|
- 素材按 material JSONL 格式写入数据库,source 固定为 other,kind 用中文作品主题。
|
|
33
|
-
-
|
|
33
|
+
- 已成功入库、确认无关或作品级失败的作品记录在 <工作区>/.fancy/douyin/crawled.json,后续跳过;账号级失败仍会重试。
|
|
34
34
|
- 登录态保存在 <工作区>/.fancy/douyin/chrome-profile/,并镜像到 login-state.json。
|
|
35
35
|
- 首次需要登录时用有头 Chrome;登录态有效后后续运行自动使用无头 Chrome。
|
|
36
36
|
- 每次运行结束会自动关闭 Chrome,释放资源。
|
|
@@ -74,7 +74,10 @@ export function analysisPrompt({
|
|
|
74
74
|
}) {
|
|
75
75
|
const template = fs.readFileSync(PROMPT_FILE, 'utf8');
|
|
76
76
|
const list = (screenshots || [])
|
|
77
|
-
.map((shot, index) =>
|
|
77
|
+
.map((shot, index) => {
|
|
78
|
+
const label = shot && shot.label ? '(' + shot.label + ')' : '';
|
|
79
|
+
return `${index + 1}. \`${shot.file}\`${label}`;
|
|
80
|
+
})
|
|
78
81
|
.join('\n');
|
|
79
82
|
const vars = {
|
|
80
83
|
ACCOUNT_URL: read(accountUrl),
|
|
@@ -224,7 +227,8 @@ export function summaryText({
|
|
|
224
227
|
lines.push(' - ' + (item.id || item.url || '未知') + ':' + item.reason);
|
|
225
228
|
}
|
|
226
229
|
if (failures.length > 10) lines.push(' - 其余 ' + (failures.length - 10) + ' 篇省略');
|
|
227
|
-
lines.push('
|
|
230
|
+
lines.push('失败项已跳过,不会中断其他作品。');
|
|
231
|
+
lines.push('作品级失败已记录为跳过,下次不再重试;账号级失败仍会在下次重试。');
|
|
228
232
|
}
|
|
229
233
|
lines.push('输出目录:' + outputDir);
|
|
230
234
|
lines.push('采集记录:' + stateFile);
|