@cloud411716/fancy-webnovel 4.7.2 → 4.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,364 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Open one Douyin /video/ work, check its duration, download it when possible,
5
+ * and extract keyframes for LLM analysis. stdout is one JSON object; Chrome
6
+ * stays open.
7
+ *
8
+ * Rules from the command layer:
9
+ * - videos longer than --max-seconds (default 60) are skipped before analysis;
10
+ * - the first 5 seconds are extracted separately for the relevance gate;
11
+ * - the full video gets a sparse storyboard (one frame every 5 seconds).
12
+ */
13
+
14
+ const fs = require('fs');
15
+ const path = require('path');
16
+ const { spawnSync } = require('child_process');
17
+ const {
18
+ log, parseArgs, connect, installExternalProtocolGuard, restoreCookies, saveCookies,
19
+ safeGateResult, printJson, fail, ensureDir,
20
+ } = require('./lib.cjs');
21
+ const {
22
+ probeDuration, detectSceneTimes, fixedVideoTimes, mergeFrameTimes, extractFramesAt,
23
+ } = require('./video-frames.cjs');
24
+
25
+ const UA = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36';
26
+ const FIRST_SECONDS = 5;
27
+ const FRAME_STEP_SECONDS = 5;
28
+
29
+ function videoId(url) {
30
+ const match = String(url).match(/\/video\/(\d+)/);
31
+ if (match) return match[1];
32
+ return String(url).replace(/[?#].*$/, '').split('/').filter(Boolean).pop() || '';
33
+ }
34
+
35
+ async function readMetadata(page) {
36
+ return await page.evaluate(() => {
37
+ const meta = (name) => {
38
+ const el = document.querySelector('meta[name="' + name + '"]');
39
+ return el && el.content ? el.content : '';
40
+ };
41
+ return {
42
+ url: location.href,
43
+ title: document.title || '',
44
+ description: meta('description'),
45
+ body: (document.body && document.body.innerText ? document.body.innerText : '').slice(0, 6000),
46
+ };
47
+ });
48
+ }
49
+
50
+ function absoluteVideoUrl(value) {
51
+ const text = String(value || '').trim();
52
+ if (!text) return '';
53
+ if (text.startsWith('//')) return 'https:' + text;
54
+ return text;
55
+ }
56
+
57
+ async function waitForMainVideo(page) {
58
+ let fallback = null;
59
+ for (let round = 0; round < 12; round += 1) {
60
+ const info = await page.evaluate(() => {
61
+ const videos = [...document.querySelectorAll('video')].map((video) => {
62
+ const rect = video.getBoundingClientRect();
63
+ let src = video.currentSrc || video.src || '';
64
+ if (!src || src.startsWith('blob:')) {
65
+ const source = video.querySelector('source');
66
+ if (source) src = source.src || source.getAttribute('src') || src;
67
+ }
68
+ if (String(src).startsWith('//')) src = 'https:' + src;
69
+ return {
70
+ src,
71
+ duration: Number.isFinite(video.duration) && video.duration > 0 ? video.duration : null,
72
+ readyState: video.readyState,
73
+ width: rect.width,
74
+ height: rect.height,
75
+ mediatype: video.getAttribute('mediatype'),
76
+ index: video.getAttribute('data-index'),
77
+ };
78
+ });
79
+ const isHttp = (value) => /^https?:\/\//.test(String(value || ''));
80
+ const main = videos.find((video) => video.mediatype === 'video' && isHttp(video.src))
81
+ || videos.filter((video) => video.width > 0 && video.height > 0)
82
+ .sort((a, b) => (b.width * b.height) - (a.width * a.height))[0]
83
+ || videos.find((video) => isHttp(video.src))
84
+ || videos[0]
85
+ || null;
86
+ return { main, videos };
87
+ });
88
+ if (info.main && info.main.src) {
89
+ fallback = info;
90
+ // 时长通常在页面加载后 3–6 秒才可读。先等它出现,才能在下载前
91
+ // 判断「超过 1 分钟直接跳过」,避免白下载长视频。
92
+ if (info.main.duration) return info;
93
+ }
94
+ try {
95
+ await page.evaluate(() => {
96
+ const video = document.querySelector('video[mediatype="video"]') || document.querySelector('video');
97
+ if (!video) return;
98
+ video.muted = true;
99
+ const played = video.play();
100
+ if (played && typeof played.catch === 'function') played.catch(() => {});
101
+ });
102
+ } catch { /* page may be navigating */ }
103
+ await page.waitForTimeout(900);
104
+ }
105
+ return fallback;
106
+ }
107
+
108
+ async function downloadVideo(context, src, file) {
109
+ const response = await context.request.get(src, {
110
+ headers: {
111
+ Referer: 'https://www.douyin.com/',
112
+ 'User-Agent': UA,
113
+ },
114
+ timeout: 120000,
115
+ failOnStatusCode: false,
116
+ });
117
+ if (!response.ok()) throw new Error('下载视频失败:HTTP ' + response.status());
118
+ const body = await response.body();
119
+ if (!body || !body.length) throw new Error('下载视频失败:响应为空');
120
+ fs.writeFileSync(file, body);
121
+ return body.length;
122
+ }
123
+
124
+
125
+ async function captureFramesFromPage(page, outDir, duration, times) {
126
+ const framesDir = path.join(outDir, 'frames');
127
+ ensureDir(framesDir);
128
+ const selector = 'video[mediatype="video"]';
129
+ let handle = await page.$(selector);
130
+ if (!handle) handle = await page.$('video');
131
+ if (!handle) throw new Error('没有找到视频元素,无法截取关键帧');
132
+
133
+ const list = Array.isArray(times) && times.length ? times : fixedVideoTimes(duration || FIRST_SECONDS);
134
+
135
+ const captured = [];
136
+ for (let index = 0; index < list.length; index += 1) {
137
+ const time = list[index];
138
+ try {
139
+ await page.evaluate(async ({ selector: sel, time: target }) => {
140
+ const video = document.querySelector(sel) || document.querySelector('video');
141
+ if (!video) return;
142
+ video.muted = true;
143
+ video.pause();
144
+ const safe = Math.max(0, Math.min(target, Math.max(0, (video.duration || target) - 0.05)));
145
+ if (Math.abs(video.currentTime - safe) > 0.15) {
146
+ await new Promise((resolve) => {
147
+ let settled = false;
148
+ const done = () => {
149
+ if (settled) return;
150
+ settled = true;
151
+ resolve();
152
+ };
153
+ video.addEventListener('seeked', done, { once: true });
154
+ video.currentTime = safe;
155
+ setTimeout(done, 3000);
156
+ });
157
+ }
158
+ }, { selector, time });
159
+ await page.waitForTimeout(250);
160
+ const file = path.join(framesDir, 'page_' + String(index + 1).padStart(2, '0') + '.jpg');
161
+ await handle.screenshot({ path: file, type: 'jpeg', quality: 90 });
162
+ captured.push({ index: index + 1, time, file });
163
+ } catch (err) {
164
+ log('[video] frame capture failed at ' + time + 's: ' + (err && err.message ? err.message : String(err)));
165
+ }
166
+ }
167
+ const first5s = captured.filter((frame) => frame.time < FIRST_SECONDS);
168
+ return {
169
+ first5s: first5s.length ? first5s : captured.slice(0, 1),
170
+ frames: captured,
171
+ };
172
+ }
173
+
174
+ async function main() {
175
+ const args = parseArgs(process.argv.slice(2));
176
+ const workspace = path.resolve(String(args.workspace || process.cwd()));
177
+ const videoUrl = String(args.video || '');
178
+ const cdp = String(args.cdp || 'http://127.0.0.1:9222');
179
+ const outDir = path.resolve(String(args.out || path.join(workspace, '.fancy', 'douyin', 'output', 'video')));
180
+ const loginState = path.resolve(String(args['login-state'] || path.join(workspace, '.fancy', 'douyin', 'login-state.json')));
181
+ const maxSeconds = Number(args['max-seconds'] || 60);
182
+ if (!/\/video\//.test(videoUrl)) throw new Error('不是抖音视频作品地址:' + videoUrl);
183
+ ensureDir(outDir);
184
+
185
+ const { context } = await connect(cdp);
186
+ let page = null;
187
+ let keepPage = false;
188
+ try {
189
+ await restoreCookies(context, loginState);
190
+ page = await context.newPage();
191
+ await installExternalProtocolGuard(page);
192
+ await page.goto(videoUrl, { waitUntil: 'domcontentloaded', timeout: 60000 });
193
+ await page.waitForTimeout(3500);
194
+
195
+ const firstGate = await safeGateResult(page, outDir);
196
+ if (firstGate) {
197
+ keepPage = true;
198
+ await saveCookies(context, loginState, page.url());
199
+ printJson(firstGate);
200
+ return;
201
+ }
202
+
203
+ const meta = await readMetadata(page);
204
+ const found = await waitForMainVideo(page);
205
+ const main = found && found.main ? found.main : null;
206
+ if (!main || !main.src) throw new Error('没有找到视频播放地址');
207
+
208
+ let duration = main.duration;
209
+ let videoFile = '';
210
+ let downloadError = '';
211
+ const directUrl = absoluteVideoUrl(main.src);
212
+ if (!directUrl || directUrl.startsWith('blob:')) {
213
+ downloadError = '视频地址不是可直接下载的 http(s) 地址';
214
+ log('[video] ' + downloadError + ',将使用播放器截图');
215
+ }
216
+
217
+ if (Number.isFinite(Number(duration)) && Number(duration) > maxSeconds) {
218
+ const video = {
219
+ id: videoId(videoUrl),
220
+ url: videoUrl,
221
+ final_url: meta.url,
222
+ type: 'video',
223
+ title: meta.title,
224
+ description: meta.description,
225
+ body: meta.body,
226
+ duration: Number(duration),
227
+ max_seconds: maxSeconds,
228
+ frames: [],
229
+ first5s: [],
230
+ video_file: '',
231
+ crawled_at: new Date().toISOString(),
232
+ dir: outDir,
233
+ };
234
+ const videoFileJson = path.join(outDir, 'video.json');
235
+ fs.writeFileSync(videoFileJson, JSON.stringify(video, null, 2) + '\n', 'utf8');
236
+ printJson({
237
+ ok: true,
238
+ login_required: false,
239
+ skip: true,
240
+ reason: '视频时长 ' + Number(duration).toFixed(1) + ' 秒,超过 ' + maxSeconds + ' 秒',
241
+ video,
242
+ video_file: videoFileJson,
243
+ });
244
+ return;
245
+ }
246
+
247
+ if (directUrl && !directUrl.startsWith('blob:')) {
248
+ try {
249
+ videoFile = path.join(outDir, 'video.mp4');
250
+ await downloadVideo(context, directUrl, videoFile);
251
+ const probed = probeDuration(videoFile);
252
+ if (probed) duration = probed;
253
+ } catch (err) {
254
+ downloadError = err && err.message ? err.message : String(err);
255
+ log('[video] download failed: ' + downloadError);
256
+ videoFile = '';
257
+ }
258
+ }
259
+
260
+ if (!Number.isFinite(Number(duration)) || Number(duration) <= 0) {
261
+ throw new Error('无法判断视频时长' + (downloadError ? '(' + downloadError + ')' : ''));
262
+ }
263
+ duration = Number(duration);
264
+
265
+ if (duration > maxSeconds) {
266
+ const video = {
267
+ id: videoId(videoUrl),
268
+ url: videoUrl,
269
+ final_url: meta.url,
270
+ type: 'video',
271
+ title: meta.title,
272
+ description: meta.description,
273
+ body: meta.body,
274
+ duration,
275
+ max_seconds: maxSeconds,
276
+ frames: [],
277
+ first5s: [],
278
+ video_file: videoFile,
279
+ crawled_at: new Date().toISOString(),
280
+ dir: outDir,
281
+ };
282
+ const videoFileJson = path.join(outDir, 'video.json');
283
+ fs.writeFileSync(videoFileJson, JSON.stringify(video, null, 2) + '\n', 'utf8');
284
+ printJson({
285
+ ok: true,
286
+ login_required: false,
287
+ skip: true,
288
+ reason: '视频时长 ' + duration.toFixed(1) + ' 秒,超过 ' + maxSeconds + ' 秒',
289
+ video,
290
+ video_file: videoFileJson,
291
+ });
292
+ return;
293
+ }
294
+
295
+ let frames = [];
296
+ let first5s = [];
297
+ let sceneTimes = [];
298
+ const fixedTimes = fixedVideoTimes(duration);
299
+ let times = fixedTimes;
300
+ if (videoFile && fs.existsSync(videoFile)) {
301
+ try {
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);
305
+ } catch (err) {
306
+ log('[video] ffmpeg frame extraction failed: ' + (err && err.message ? err.message : String(err)));
307
+ }
308
+ }
309
+ if (!frames.length) {
310
+ const captured = await captureFramesFromPage(page, outDir, duration, times);
311
+ frames = captured.frames;
312
+ }
313
+ first5s = frames.filter((frame) => Number(frame.time) < FIRST_SECONDS);
314
+ if (!first5s.length) first5s = frames.slice(0, 1);
315
+ if (!frames.length) throw new Error('没有抽取到视频关键帧');
316
+
317
+ const afterGate = await safeGateResult(page, outDir);
318
+ if (afterGate) {
319
+ keepPage = true;
320
+ await saveCookies(context, loginState, page.url());
321
+ printJson(afterGate);
322
+ return;
323
+ }
324
+
325
+ await saveCookies(context, loginState, page.url());
326
+ const video = {
327
+ id: videoId(videoUrl),
328
+ url: videoUrl,
329
+ final_url: meta.url,
330
+ type: 'video',
331
+ title: meta.title,
332
+ description: meta.description,
333
+ body: meta.body,
334
+ duration,
335
+ max_seconds: maxSeconds,
336
+ width: main.width || 0,
337
+ height: main.height || 0,
338
+ frames,
339
+ first5s,
340
+ scene_times: sceneTimes,
341
+ fixed_times: fixedTimes,
342
+ video_file: videoFile,
343
+ download_error: downloadError,
344
+ crawled_at: new Date().toISOString(),
345
+ dir: outDir,
346
+ };
347
+ const videoFileJson = path.join(outDir, 'video.json');
348
+ fs.writeFileSync(videoFileJson, JSON.stringify(video, null, 2) + '\n', 'utf8');
349
+ printJson({
350
+ ok: true,
351
+ login_required: false,
352
+ video,
353
+ video_file: videoFileJson,
354
+ });
355
+ } finally {
356
+ if (page && !keepPage) {
357
+ try { await page.close(); } catch { /* ignore */ }
358
+ }
359
+ }
360
+ }
361
+
362
+ main()
363
+ .then(() => process.exit(0))
364
+ .catch((err) => { fail(err); process.exit(0); });
@@ -1,7 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  /**
4
- * Scan one Douyin account homepage and return its /note/ image-text works.
4
+ * Scan one Douyin account homepage and return its /note/ image-text works
5
+ * and /video/ video works.
5
6
  *
6
7
  * stdout is one JSON object. Progress goes to stderr. The script never closes
7
8
  * Chrome; it closes only its own page, so login state stays in the profile.
@@ -163,7 +164,7 @@ async function main() {
163
164
  account,
164
165
  title: await page.title(),
165
166
  notes,
166
- videos: videos.length,
167
+ videos,
167
168
  cards_file: cardsFile,
168
169
  });
169
170
  } finally {
@@ -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
+ };
@@ -5,9 +5,10 @@
5
5
  * live under <workspace>/.fancy/douyin. The deployed crawler scripts live under
6
6
  * <workspace>/.fancy-tools/fancy-douyin.
7
7
  *
8
- * The crawl history is keyed by the note id parsed from /note/<id>. A note is
9
- * written only after its screenshot analysis has been imported into the
10
- * material library, so failed notes are retried on the next run.
8
+ * The crawl history is keyed by the note/video id parsed from /note/<id> or
9
+ * /video/<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.
11
12
  */
12
13
 
13
14
  import fs from 'fs';