@cloud411716/fancy-webnovel 4.24.1 → 4.26.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/README.md +6 -0
- package/package.json +1 -1
- package/plugins/fancy-scan/index.js +36 -3
- package/plugins/fancy-scan/scripts/run-scan.js +14 -8
- package/plugins/fancy-scan/scripts/scrapers/fanqie-rank-scraper.js +58 -8
- package/plugins/fancy-scan/scripts/scrapers/jjwxc-rank-scraper.js +51 -9
- package/plugins/fancy-scan/scripts/scrapers/qimao-rank-scraper.js +46 -0
- package/plugins/fancy-scan/scripts/scrapers/selfcheck.js +715 -0
- package/plugins/fancy-scan/templates.js +10 -1
- package/plugins/fancy-scan/visual-selfcheck.js +536 -0
|
@@ -0,0 +1,715 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 前置视觉自检(scraper 侧)。
|
|
3
|
+
*
|
|
4
|
+
* scraper 打开榜单页后截图,把 request.json + ready.json 写进
|
|
5
|
+
* <工作区>/.tmp/fancy-scan-selfcheck/<run>/,然后**保持同一个 page 等待**
|
|
6
|
+
* 父进程用 LLM 写出 result.json。收到结果后:
|
|
7
|
+
*
|
|
8
|
+
* 晋江 / 七猫 —— 用样例文本反查 DOM,推断字段选择器/表格列位置;
|
|
9
|
+
* 番茄 OCR —— 用候选编号还原字段选择器(DOM 文本是 PUA,不能按文本反查)。
|
|
10
|
+
*
|
|
11
|
+
* 置信度不足就返回 null,调用方走原逻辑。
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import fs from 'fs';
|
|
15
|
+
import path from 'path';
|
|
16
|
+
|
|
17
|
+
import { atomicWriteJSON } from '#atomic-write';
|
|
18
|
+
|
|
19
|
+
export const SELF_CHECK_FIELDS = {
|
|
20
|
+
jinjiang: ['title', 'author', 'type', 'status', 'words', 'score'],
|
|
21
|
+
qimao: ['title', 'author', 'heat', 'intro'],
|
|
22
|
+
fanqie: ['title', 'author', 'status', 'desc'],
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** 番茄 OCR 路径的默认字段选择器。 */
|
|
26
|
+
export const FANQIE_DEFAULT_SELECTORS = {
|
|
27
|
+
title: '.book-item-text .title',
|
|
28
|
+
author: '.book-item-text .author',
|
|
29
|
+
status: '.book-item-footer .book-item-footer-status',
|
|
30
|
+
desc: '.book-item-text .desc',
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const DEFAULT_WAIT_MS = 8 * 60 * 1000;
|
|
34
|
+
const POLL_MS = 300;
|
|
35
|
+
|
|
36
|
+
export function normalizeText(value) {
|
|
37
|
+
return String(value == null ? '' : value)
|
|
38
|
+
.replace(/\u00a0/g, ' ')
|
|
39
|
+
.replace(/[《》]/g, '')
|
|
40
|
+
.replace(/[,\uFF0C]/g, '')
|
|
41
|
+
.replace(/\s+/g, ' ')
|
|
42
|
+
.trim();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function parseResult(text) {
|
|
46
|
+
const src = String(text || '').replace(/^\uFEFF/, '').trim();
|
|
47
|
+
const fenced = src.match(/```(?:json)?\s*([\s\S]*?)```/i);
|
|
48
|
+
const candidate = fenced ? fenced[1].trim() : src;
|
|
49
|
+
const start = candidate.indexOf('{');
|
|
50
|
+
if (start < 0) throw new Error('没有 JSON 对象');
|
|
51
|
+
let depth = 0;
|
|
52
|
+
let inString = false;
|
|
53
|
+
let escaped = false;
|
|
54
|
+
for (let i = start; i < candidate.length; i += 1) {
|
|
55
|
+
const ch = candidate[i];
|
|
56
|
+
if (inString) {
|
|
57
|
+
if (escaped) escaped = false;
|
|
58
|
+
else if (ch === '\\') escaped = true;
|
|
59
|
+
else if (ch === '"') inString = false;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (ch === '"') { inString = true; continue; }
|
|
63
|
+
if (ch === '{') depth += 1;
|
|
64
|
+
if (ch === '}') {
|
|
65
|
+
depth -= 1;
|
|
66
|
+
if (depth === 0) return JSON.parse(candidate.slice(start, i + 1));
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
throw new Error('JSON 对象没有闭合');
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* 截图 → 写请求 → 等父进程 LLM 结果。超时/不支持/无效都返回 null。
|
|
74
|
+
* @returns {Promise<{books: object[], request: object}|null>}
|
|
75
|
+
*/
|
|
76
|
+
export async function runVisualSelfCheck(page, {
|
|
77
|
+
dir,
|
|
78
|
+
platform,
|
|
79
|
+
rank,
|
|
80
|
+
url,
|
|
81
|
+
selector = '',
|
|
82
|
+
screenshotLocator = null,
|
|
83
|
+
maxHeight = 0,
|
|
84
|
+
timeoutMs = DEFAULT_WAIT_MS,
|
|
85
|
+
} = {}) {
|
|
86
|
+
if (!dir) return null;
|
|
87
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
88
|
+
const screenshot = path.join(dir, 'screenshot.jpg');
|
|
89
|
+
let shot = false;
|
|
90
|
+
let previousViewport = null;
|
|
91
|
+
try {
|
|
92
|
+
const locator = screenshotLocator || (selector ? page.locator(selector).first() : null);
|
|
93
|
+
if (locator && await locator.count()) {
|
|
94
|
+
const box = await locator.boundingBox();
|
|
95
|
+
if (maxHeight > 0 && box && box.height > maxHeight) {
|
|
96
|
+
previousViewport = page.viewportSize();
|
|
97
|
+
const width = previousViewport ? previousViewport.width : 1280;
|
|
98
|
+
await page.setViewportSize({ width, height: Math.min(2600, Math.max(maxHeight + 200, previousViewport ? previousViewport.height : 720)) });
|
|
99
|
+
await locator.scrollIntoViewIfNeeded().catch(() => {});
|
|
100
|
+
const box2 = await locator.boundingBox();
|
|
101
|
+
const scroll = await page.evaluate(() => ({ x: scrollX, y: scrollY }));
|
|
102
|
+
await page.screenshot({
|
|
103
|
+
path: screenshot,
|
|
104
|
+
type: 'jpeg',
|
|
105
|
+
quality: 90,
|
|
106
|
+
clip: {
|
|
107
|
+
x: Math.round(box2.x + scroll.x),
|
|
108
|
+
y: Math.round(box2.y + scroll.y),
|
|
109
|
+
width: Math.round(box2.width),
|
|
110
|
+
height: Math.min(maxHeight, Math.round(box2.height)),
|
|
111
|
+
},
|
|
112
|
+
});
|
|
113
|
+
shot = true;
|
|
114
|
+
} else {
|
|
115
|
+
await locator.screenshot({ path: screenshot, type: 'jpeg', quality: 90 });
|
|
116
|
+
shot = true;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
} catch { /* fall through */ }
|
|
120
|
+
finally {
|
|
121
|
+
if (previousViewport) {
|
|
122
|
+
try { await page.setViewportSize(previousViewport); } catch { /* ignore */ }
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (!shot) {
|
|
126
|
+
try {
|
|
127
|
+
await page.screenshot({ path: screenshot, type: 'jpeg', quality: 90, fullPage: false });
|
|
128
|
+
shot = true;
|
|
129
|
+
} catch {
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const fields = SELF_CHECK_FIELDS[platform] || [];
|
|
135
|
+
const request = {
|
|
136
|
+
version: 1,
|
|
137
|
+
platform,
|
|
138
|
+
rank,
|
|
139
|
+
url: url || page.url(),
|
|
140
|
+
screenshot,
|
|
141
|
+
screenshots: [screenshot],
|
|
142
|
+
fields,
|
|
143
|
+
created_at: new Date().toISOString(),
|
|
144
|
+
};
|
|
145
|
+
atomicWriteJSON(path.join(dir, 'request.json'), request, { mode: 0o600 });
|
|
146
|
+
atomicWriteJSON(path.join(dir, 'ready.json'), { ready: true, created_at: request.created_at }, { mode: 0o600 });
|
|
147
|
+
|
|
148
|
+
const resultPath = path.join(dir, 'result.json');
|
|
149
|
+
const deadline = Date.now() + timeoutMs;
|
|
150
|
+
while (Date.now() < deadline) {
|
|
151
|
+
if (fs.existsSync(resultPath)) {
|
|
152
|
+
try {
|
|
153
|
+
const parsed = parseResult(fs.readFileSync(resultPath, 'utf8'));
|
|
154
|
+
if (!parsed || parsed.vision_supported === false) return null;
|
|
155
|
+
if (!Array.isArray(parsed.books) || !parsed.books.length) return null;
|
|
156
|
+
return { books: parsed.books, request };
|
|
157
|
+
} catch {
|
|
158
|
+
// 模型可能正在写;继续等。
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
await new Promise((resolve) => setTimeout(resolve, POLL_MS));
|
|
162
|
+
}
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* 晋江:样例值 → 表格列号。
|
|
169
|
+
* 只返回达到阈值的字段;没达到的字段调用方继续用默认列。
|
|
170
|
+
*/
|
|
171
|
+
export async function inferJinjiangColumns(page, books, { threshold = 0.8, minMatched = 5 } = {}) {
|
|
172
|
+
if (!Array.isArray(books) || books.length < 3) return null;
|
|
173
|
+
const result = await page.evaluate((samples) => {
|
|
174
|
+
const norm = (v) => String(v == null ? '' : v)
|
|
175
|
+
.replace(/\u00a0/g, ' ')
|
|
176
|
+
.replace(/[《》]/g, '')
|
|
177
|
+
.replace(/[,\uFF0C]/g, '')
|
|
178
|
+
.replace(/\s+/g, ' ')
|
|
179
|
+
.trim();
|
|
180
|
+
const fields = ['title', 'author', 'type', 'status', 'words', 'score'];
|
|
181
|
+
const tables = [...document.querySelectorAll('table')]
|
|
182
|
+
.sort((a, b) => b.querySelectorAll('tr').length - a.querySelectorAll('tr').length);
|
|
183
|
+
const table = tables[0];
|
|
184
|
+
if (!table) return null;
|
|
185
|
+
const rows = [...table.querySelectorAll('tr')]
|
|
186
|
+
.map((tr) => [...tr.querySelectorAll('td')]);
|
|
187
|
+
const counts = Object.fromEntries(fields.map((field) => [field, new Map()]));
|
|
188
|
+
let matched = 0;
|
|
189
|
+
for (const sample of samples) {
|
|
190
|
+
const title = norm(sample && sample.title);
|
|
191
|
+
if (!title) continue;
|
|
192
|
+
const row = rows.find((cells) => cells.some((cell) => norm(cell.innerText) === title));
|
|
193
|
+
if (!row) continue;
|
|
194
|
+
matched += 1;
|
|
195
|
+
for (const field of fields) {
|
|
196
|
+
const value = norm(sample[field]);
|
|
197
|
+
if (!value) continue;
|
|
198
|
+
const index = row.findIndex((cell) => norm(cell.innerText) === value);
|
|
199
|
+
if (index >= 0) counts[field].set(index, (counts[field].get(index) || 0) + 1);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
const columns = {};
|
|
203
|
+
const confidence = {};
|
|
204
|
+
for (const field of fields) {
|
|
205
|
+
let best = null;
|
|
206
|
+
let max = 0;
|
|
207
|
+
for (const [index, count] of counts[field]) {
|
|
208
|
+
if (count > max) { max = count; best = index; }
|
|
209
|
+
}
|
|
210
|
+
columns[field] = best;
|
|
211
|
+
confidence[field] = matched ? max / matched : 0;
|
|
212
|
+
}
|
|
213
|
+
return { columns, confidence, matched, tableRows: rows.length };
|
|
214
|
+
}, books);
|
|
215
|
+
if (!result || result.matched < minMatched) return null;
|
|
216
|
+
const accepted = {};
|
|
217
|
+
for (const [field, confidence] of Object.entries(result.confidence || {})) {
|
|
218
|
+
if (confidence >= threshold && result.columns[field] !== null) {
|
|
219
|
+
accepted[field] = result.columns[field];
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
if (accepted.title === undefined) return null;
|
|
223
|
+
return {
|
|
224
|
+
columns: accepted,
|
|
225
|
+
confidence: result.confidence,
|
|
226
|
+
matched: result.matched,
|
|
227
|
+
threshold,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* 七猫:样例值 → 卡片内字段的相对 selector。
|
|
234
|
+
* 只在 title 选择器置信度达标时返回;其他字段没达标就不覆盖原逻辑。
|
|
235
|
+
*/
|
|
236
|
+
export async function inferQimaoSelectors(page, books, { threshold = 0.8, minMatched = 5 } = {}) {
|
|
237
|
+
if (!Array.isArray(books) || books.length < 3) return null;
|
|
238
|
+
const result = await page.evaluate((samples) => {
|
|
239
|
+
const norm = (v) => String(v == null ? '' : v)
|
|
240
|
+
.replace(/\u00a0/g, ' ')
|
|
241
|
+
.replace(/[《》]/g, '')
|
|
242
|
+
.replace(/[,\uFF0C]/g, '')
|
|
243
|
+
.replace(/\s+/g, ' ')
|
|
244
|
+
.trim();
|
|
245
|
+
const compact = (v) => norm(v).replace(/\s+/g, '');
|
|
246
|
+
const fields = ['title', 'author', 'heat', 'intro'];
|
|
247
|
+
const counts = Object.fromEntries(fields.map((field) => [field, new Map()]));
|
|
248
|
+
const cardCounts = new Map();
|
|
249
|
+
let matched = 0;
|
|
250
|
+
|
|
251
|
+
const selectorPath = (node, card) => {
|
|
252
|
+
const parts = [];
|
|
253
|
+
let cur = node;
|
|
254
|
+
while (cur && cur !== card && parts.length < 8) {
|
|
255
|
+
let part = cur.tagName.toLowerCase();
|
|
256
|
+
const cls = String(cur.className || '').trim().split(/\s+/).filter(Boolean);
|
|
257
|
+
if (cls.length) part += '.' + cls.join('.');
|
|
258
|
+
const parent = cur.parentElement;
|
|
259
|
+
if (parent) {
|
|
260
|
+
const same = [...parent.children].filter((child) => child.tagName === cur.tagName && child.className === cur.className);
|
|
261
|
+
if (same.length > 1) {
|
|
262
|
+
const sameTag = [...parent.children].filter((child) => child.tagName === cur.tagName);
|
|
263
|
+
part += `:nth-of-type(${sameTag.indexOf(cur) + 1})`;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
parts.unshift(part);
|
|
267
|
+
cur = cur.parentElement;
|
|
268
|
+
}
|
|
269
|
+
return parts.join(' > ');
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
const all = [...document.querySelectorAll('li.rank-list-item, li')];
|
|
273
|
+
const cards = all.filter((el) => el.querySelector('a.s-book-title, a[href*="/shuku/"]'));
|
|
274
|
+
for (const sample of samples) {
|
|
275
|
+
const title = norm(sample && sample.title);
|
|
276
|
+
if (!title) continue;
|
|
277
|
+
const card = cards.find((el) => [...el.querySelectorAll('a, span, p, div')].some((node) => norm(node.textContent) === title));
|
|
278
|
+
if (!card) continue;
|
|
279
|
+
matched += 1;
|
|
280
|
+
cardCounts.set(card.className, (cardCounts.get(card.className) || 0) + 1);
|
|
281
|
+
for (const field of fields) {
|
|
282
|
+
const value = norm(sample[field]);
|
|
283
|
+
if (!value) continue;
|
|
284
|
+
const nodes = [...card.querySelectorAll('a, span, em, p, div')]
|
|
285
|
+
.filter((node) => {
|
|
286
|
+
const text = norm(node.textContent);
|
|
287
|
+
if (field === 'heat' || field === 'intro') return compact(text).includes(compact(value));
|
|
288
|
+
return text === value;
|
|
289
|
+
})
|
|
290
|
+
.sort((a, b) => a.querySelectorAll('*').length - b.querySelectorAll('*').length);
|
|
291
|
+
const node = nodes[0];
|
|
292
|
+
if (!node) continue;
|
|
293
|
+
const sel = selectorPath(node, card);
|
|
294
|
+
if (sel) counts[field].set(sel, (counts[field].get(sel) || 0) + 1);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
const selectors = {};
|
|
298
|
+
const confidence = {};
|
|
299
|
+
for (const field of fields) {
|
|
300
|
+
let best = '';
|
|
301
|
+
let max = 0;
|
|
302
|
+
for (const [sel, count] of counts[field]) {
|
|
303
|
+
if (count > max) { max = count; best = sel; }
|
|
304
|
+
}
|
|
305
|
+
selectors[field] = best;
|
|
306
|
+
confidence[field] = matched ? max / matched : 0;
|
|
307
|
+
}
|
|
308
|
+
let cardSelector = '';
|
|
309
|
+
let cardMax = 0;
|
|
310
|
+
for (const [cls, count] of cardCounts) {
|
|
311
|
+
if (count > cardMax) { cardMax = count; cardSelector = cls ? `li.${String(cls).trim().split(/\s+/).join('.')}` : 'li'; }
|
|
312
|
+
}
|
|
313
|
+
return { selectors, confidence, matched, cardSelector, cardConfidence: matched ? cardMax / matched : 0 };
|
|
314
|
+
}, books);
|
|
315
|
+
if (!result || result.matched < minMatched) return null;
|
|
316
|
+
if (!result.cardSelector || result.cardConfidence < threshold) return null;
|
|
317
|
+
if (!result.selectors.title || result.confidence.title < threshold) return null;
|
|
318
|
+
const selectors = { title: result.selectors.title };
|
|
319
|
+
for (const field of ['author', 'heat', 'intro']) {
|
|
320
|
+
if (result.selectors[field] && result.confidence[field] >= threshold) {
|
|
321
|
+
selectors[field] = result.selectors[field];
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
return {
|
|
325
|
+
cardSelector: result.cardSelector,
|
|
326
|
+
selectors,
|
|
327
|
+
confidence: result.confidence,
|
|
328
|
+
cardConfidence: result.cardConfidence,
|
|
329
|
+
matched: result.matched,
|
|
330
|
+
threshold,
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* 用推断出的选择器按卡片提取七猫字段。
|
|
336
|
+
* 只在 title 选择器存在时调用;其他字段缺失时留空,由调用方合并。
|
|
337
|
+
*/
|
|
338
|
+
export async function extractQimaoByMapping(page, mapping, { limit = 100 } = {}) {
|
|
339
|
+
if (!mapping || !mapping.cardSelector || !mapping.selectors || !mapping.selectors.title) return null;
|
|
340
|
+
return await page.evaluate(({ mapping, limit }) => {
|
|
341
|
+
const cards = [...document.querySelectorAll(mapping.cardSelector)].slice(0, limit);
|
|
342
|
+
const books = [];
|
|
343
|
+
const norm = (v) => String(v == null ? '' : v).replace(/\s+/g, ' ').trim();
|
|
344
|
+
for (const card of cards) {
|
|
345
|
+
const titleEl = card.querySelector(mapping.selectors.title);
|
|
346
|
+
const title = titleEl ? norm(titleEl.textContent) : '';
|
|
347
|
+
if (!title) continue;
|
|
348
|
+
const pick = (field) => {
|
|
349
|
+
const sel = mapping.selectors[field];
|
|
350
|
+
if (!sel) return '';
|
|
351
|
+
const el = card.querySelector(sel);
|
|
352
|
+
return el ? norm(el.textContent) : '';
|
|
353
|
+
};
|
|
354
|
+
const link = titleEl.closest('a') || titleEl;
|
|
355
|
+
books.push({
|
|
356
|
+
rank: String(books.length + 1),
|
|
357
|
+
title,
|
|
358
|
+
author: pick('author'),
|
|
359
|
+
heat: pick('heat').replace(/热度/g, '').replace(/[^\d.万亿]/g, ''),
|
|
360
|
+
desc: pick('intro'),
|
|
361
|
+
url: link.href || link.getAttribute('href') || '',
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
return books;
|
|
365
|
+
}, { mapping, limit });
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// ---------------------------------------------------------------------------
|
|
369
|
+
// 番茄 OCR:候选编号模式
|
|
370
|
+
//
|
|
371
|
+
// 番茄榜单页的书名/作者/简介在 DOM 里是 U+E000–U+F8FF 私用区字符,
|
|
372
|
+
// 截图里才是正常文字,所以不能像晋江/七猫那样“用截图文本反查 DOM”。
|
|
373
|
+
// 这里改为:
|
|
374
|
+
// 1) 给第一张卡片里的叶子元素编号;
|
|
375
|
+
// 2) 把编号 + 元素渲染内容截成候选清单;
|
|
376
|
+
// 3) LLM 从截图判断 title/author/status/desc 各对应哪个编号;
|
|
377
|
+
// 4) 代码把编号还原成相对卡片的选择器,并在本页所有卡片上验证命中率。
|
|
378
|
+
// ---------------------------------------------------------------------------
|
|
379
|
+
|
|
380
|
+
const FANQIE_CANDIDATE_ATTR = 'data-fancy-sc-candidate';
|
|
381
|
+
const FANQIE_PANEL_ID = 'fancy-sc-panel';
|
|
382
|
+
|
|
383
|
+
async function screenshotFanqieCard(page, card, filepath) {
|
|
384
|
+
const box = await card.evaluate((el) => {
|
|
385
|
+
const r = el.getBoundingClientRect();
|
|
386
|
+
return {
|
|
387
|
+
x: r.left + window.scrollX,
|
|
388
|
+
y: r.top + window.scrollY,
|
|
389
|
+
width: r.width,
|
|
390
|
+
height: r.height,
|
|
391
|
+
};
|
|
392
|
+
});
|
|
393
|
+
if (!box || box.width <= 0 || box.height <= 0) throw new Error('无法获取卡片位置');
|
|
394
|
+
fs.mkdirSync(path.dirname(filepath), { recursive: true });
|
|
395
|
+
const buf = await page.screenshot({
|
|
396
|
+
type: 'jpeg',
|
|
397
|
+
quality: 95,
|
|
398
|
+
fullPage: true,
|
|
399
|
+
clip: box,
|
|
400
|
+
});
|
|
401
|
+
fs.writeFileSync(filepath, buf);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* 在第一张卡片上安装候选编号,并生成一个固定定位的候选清单面板。
|
|
406
|
+
* 返回候选数量;页面状态由 cleanupFanqieCandidatePanel 还原。
|
|
407
|
+
*/
|
|
408
|
+
async function installFanqieCandidatePanel(page, cardSelector) {
|
|
409
|
+
return await page.evaluate(({ cardSelector, attr, panelId }) => {
|
|
410
|
+
document.getElementById(panelId)?.remove();
|
|
411
|
+
const card = document.querySelector(cardSelector);
|
|
412
|
+
if (!card) return { count: 0 };
|
|
413
|
+
|
|
414
|
+
const leaves = [...card.querySelectorAll('*')].filter((el) => {
|
|
415
|
+
if (el.children.length) return false;
|
|
416
|
+
if (/^(SCRIPT|STYLE|NOSCRIPT|IMG|SVG|PATH)$/.test(el.tagName)) return false;
|
|
417
|
+
// 名次/升降、最近更新、更新时间不是 OCR 目标字段,排除后候选清单更聚焦,
|
|
418
|
+
// 也避免 LLM 把大字号的名次误认成书名。
|
|
419
|
+
if (el.closest('.book-item-index, .book-item-footer-last, .book-item-footer-time')) return false;
|
|
420
|
+
const text = (el.textContent || '').trim();
|
|
421
|
+
if (!text) return false;
|
|
422
|
+
const r = el.getBoundingClientRect();
|
|
423
|
+
return r.width > 0 && r.height > 0;
|
|
424
|
+
});
|
|
425
|
+
|
|
426
|
+
const panel = document.createElement('div');
|
|
427
|
+
panel.id = panelId;
|
|
428
|
+
panel.style.cssText = [
|
|
429
|
+
'position:fixed',
|
|
430
|
+
'left:16px',
|
|
431
|
+
'top:16px',
|
|
432
|
+
'z-index:2147483647',
|
|
433
|
+
'width:840px',
|
|
434
|
+
'background:#fff',
|
|
435
|
+
'color:#000',
|
|
436
|
+
'border:2px solid #000',
|
|
437
|
+
'padding:12px',
|
|
438
|
+
'font:14px/1.5 system-ui,sans-serif',
|
|
439
|
+
'box-sizing:border-box',
|
|
440
|
+
].join(';');
|
|
441
|
+
|
|
442
|
+
const header = document.createElement('div');
|
|
443
|
+
header.textContent = '候选元素清单(按页面从上到下)';
|
|
444
|
+
header.style.cssText = 'font-weight:700;font-size:16px;margin-bottom:8px;';
|
|
445
|
+
panel.appendChild(header);
|
|
446
|
+
|
|
447
|
+
leaves.forEach((el, index) => {
|
|
448
|
+
const num = index + 1;
|
|
449
|
+
el.setAttribute(attr, String(num));
|
|
450
|
+
|
|
451
|
+
const row = document.createElement('div');
|
|
452
|
+
row.style.cssText = 'display:flex;gap:10px;padding:4px 0;border-top:1px solid #ddd;align-items:flex-start;';
|
|
453
|
+
|
|
454
|
+
const badge = document.createElement('div');
|
|
455
|
+
badge.textContent = `[${num}]`;
|
|
456
|
+
badge.style.cssText = 'flex:0 0 42px;font-weight:700;color:#c00;';
|
|
457
|
+
|
|
458
|
+
const text = document.createElement('div');
|
|
459
|
+
text.style.cssText = 'flex:1 1 auto;max-height:4.5em;overflow:hidden;';
|
|
460
|
+
|
|
461
|
+
const clone = el.cloneNode(true);
|
|
462
|
+
clone.removeAttribute(attr);
|
|
463
|
+
clone.removeAttribute('id');
|
|
464
|
+
const cs = getComputedStyle(el);
|
|
465
|
+
const baseStyle = clone.getAttribute('style') || '';
|
|
466
|
+
clone.setAttribute('style', [
|
|
467
|
+
baseStyle,
|
|
468
|
+
`font-family:${cs.fontFamily}`,
|
|
469
|
+
`font-size:${cs.fontSize}`,
|
|
470
|
+
`font-weight:${cs.fontWeight}`,
|
|
471
|
+
`line-height:${cs.lineHeight}`,
|
|
472
|
+
'color:#000',
|
|
473
|
+
'white-space:normal',
|
|
474
|
+
'-webkit-line-clamp:unset',
|
|
475
|
+
'overflow:visible',
|
|
476
|
+
'max-height:none',
|
|
477
|
+
].filter(Boolean).join(';'));
|
|
478
|
+
text.appendChild(clone);
|
|
479
|
+
|
|
480
|
+
row.appendChild(badge);
|
|
481
|
+
row.appendChild(text);
|
|
482
|
+
panel.appendChild(row);
|
|
483
|
+
});
|
|
484
|
+
|
|
485
|
+
document.body.appendChild(panel);
|
|
486
|
+
return { count: leaves.length };
|
|
487
|
+
}, { cardSelector, attr: FANQIE_CANDIDATE_ATTR, panelId: FANQIE_PANEL_ID });
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
async function screenshotFanqieCandidates(page, filepath) {
|
|
491
|
+
const panel = page.locator(`#${FANQIE_PANEL_ID}`);
|
|
492
|
+
if (!(await panel.count())) throw new Error('候选清单面板不存在');
|
|
493
|
+
const previous = page.viewportSize();
|
|
494
|
+
let changed = false;
|
|
495
|
+
try {
|
|
496
|
+
const box = await panel.boundingBox();
|
|
497
|
+
if (previous && box && box.height + 40 > previous.height) {
|
|
498
|
+
await page.setViewportSize({
|
|
499
|
+
width: previous.width,
|
|
500
|
+
height: Math.min(3200, Math.ceil(box.height + 40)),
|
|
501
|
+
});
|
|
502
|
+
changed = true;
|
|
503
|
+
await page.waitForTimeout(100);
|
|
504
|
+
}
|
|
505
|
+
fs.mkdirSync(path.dirname(filepath), { recursive: true });
|
|
506
|
+
await panel.screenshot({ path: filepath, type: 'jpeg', quality: 95 });
|
|
507
|
+
} finally {
|
|
508
|
+
if (changed) {
|
|
509
|
+
try { await page.setViewportSize(previous); } catch { /* ignore */ }
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
async function cleanupFanqieCandidatePanel(page) {
|
|
515
|
+
try {
|
|
516
|
+
await page.evaluate(({ attr, panelId }) => {
|
|
517
|
+
document.getElementById(panelId)?.remove();
|
|
518
|
+
for (const el of document.querySelectorAll(`[${attr}]`)) el.removeAttribute(attr);
|
|
519
|
+
}, { attr: FANQIE_CANDIDATE_ATTR, panelId: FANQIE_PANEL_ID });
|
|
520
|
+
} catch { /* page may already be closed */ }
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* 用候选编号还原选择器,并在本页卡片上统计命中率。
|
|
525
|
+
* 只返回达到阈值的字段;title 不达标时整个映射作废。
|
|
526
|
+
*/
|
|
527
|
+
export async function applyFanqieCandidateFields(page, fields, {
|
|
528
|
+
cardSelector = '.rank-book-item',
|
|
529
|
+
threshold = 0.8,
|
|
530
|
+
maxCards = 10,
|
|
531
|
+
} = {}) {
|
|
532
|
+
const titleNum = Number(fields && fields.title);
|
|
533
|
+
if (!Number.isInteger(titleNum) || titleNum <= 0) return null;
|
|
534
|
+
const result = await page.evaluate(({ fields, cardSelector, attr, threshold, maxCards }) => {
|
|
535
|
+
const card = document.querySelector(cardSelector);
|
|
536
|
+
if (!card) return null;
|
|
537
|
+
const cards = [...document.querySelectorAll(cardSelector)].slice(0, maxCards);
|
|
538
|
+
const esc = (s) => (window.CSS && CSS.escape ? CSS.escape(s) : String(s).replace(/[^A-Za-z0-9_-]/g, '\\$&'));
|
|
539
|
+
const classesOf = (el) => [...el.classList].filter((c) => !/^font-/.test(c) && !c.startsWith('fancy-sc'));
|
|
540
|
+
const selectorFor = (root, el) => {
|
|
541
|
+
const parts = [];
|
|
542
|
+
let cur = el;
|
|
543
|
+
while (cur && cur !== root && parts.length < 10) {
|
|
544
|
+
let part = cur.tagName.toLowerCase();
|
|
545
|
+
const classes = classesOf(cur);
|
|
546
|
+
if (classes.length) part += classes.map((c) => `.${esc(c)}`).join('');
|
|
547
|
+
const parent = cur.parentElement;
|
|
548
|
+
if (parent) {
|
|
549
|
+
const same = [...parent.children].filter((sib) => {
|
|
550
|
+
if (sib.tagName !== cur.tagName) return false;
|
|
551
|
+
const sibClasses = classesOf(sib);
|
|
552
|
+
return classes.length
|
|
553
|
+
? classes.every((c) => sib.classList.contains(c))
|
|
554
|
+
: true;
|
|
555
|
+
});
|
|
556
|
+
if (same.length > 1) {
|
|
557
|
+
const sameTag = [...parent.children].filter((sib) => sib.tagName === cur.tagName);
|
|
558
|
+
part += `:nth-of-type(${sameTag.indexOf(cur) + 1})`;
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
parts.unshift(part);
|
|
562
|
+
cur = cur.parentElement;
|
|
563
|
+
}
|
|
564
|
+
return parts.join(' > ');
|
|
565
|
+
};
|
|
566
|
+
|
|
567
|
+
const selectors = {};
|
|
568
|
+
const confidence = {};
|
|
569
|
+
for (const [field, raw] of Object.entries(fields || {})) {
|
|
570
|
+
const num = Number(raw);
|
|
571
|
+
if (!Number.isInteger(num) || num <= 0) continue;
|
|
572
|
+
const el = card.querySelector(`[${attr}="${num}"]`);
|
|
573
|
+
if (!el) continue;
|
|
574
|
+
const sel = selectorFor(card, el);
|
|
575
|
+
if (!sel) continue;
|
|
576
|
+
selectors[field] = sel;
|
|
577
|
+
let matched = 0;
|
|
578
|
+
for (const c of cards) {
|
|
579
|
+
const found = c.querySelector(sel);
|
|
580
|
+
if (found && (found.textContent || '').trim()) matched += 1;
|
|
581
|
+
}
|
|
582
|
+
confidence[field] = cards.length ? matched / cards.length : 0;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
const accepted = {};
|
|
586
|
+
for (const [field, value] of Object.entries(confidence)) {
|
|
587
|
+
if (value >= threshold) accepted[field] = selectors[field];
|
|
588
|
+
}
|
|
589
|
+
return { selectors: accepted, rawSelectors: selectors, confidence, totalCards: cards.length };
|
|
590
|
+
}, { fields, cardSelector, attr: FANQIE_CANDIDATE_ATTR, threshold, maxCards });
|
|
591
|
+
if (!result || !result.selectors.title) return null;
|
|
592
|
+
return {
|
|
593
|
+
cardSelector,
|
|
594
|
+
selectors: result.selectors,
|
|
595
|
+
rawSelectors: result.rawSelectors,
|
|
596
|
+
confidence: result.confidence,
|
|
597
|
+
totalCards: result.totalCards,
|
|
598
|
+
threshold,
|
|
599
|
+
};
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/**
|
|
603
|
+
* 在后续题材页上验证已推断的选择器;不重新让 LLM 识别。
|
|
604
|
+
*/
|
|
605
|
+
export async function validateFanqieSelectors(page, mapping, {
|
|
606
|
+
cardSelector = '.rank-book-item',
|
|
607
|
+
threshold = 0.8,
|
|
608
|
+
maxCards = 10,
|
|
609
|
+
} = {}) {
|
|
610
|
+
if (!mapping || !mapping.selectors || !mapping.selectors.title) return null;
|
|
611
|
+
const result = await page.evaluate(({ selectors, cardSelector, threshold, maxCards }) => {
|
|
612
|
+
const cards = [...document.querySelectorAll(cardSelector)].slice(0, maxCards);
|
|
613
|
+
const accepted = {};
|
|
614
|
+
const confidence = {};
|
|
615
|
+
for (const [field, sel] of Object.entries(selectors)) {
|
|
616
|
+
let matched = 0;
|
|
617
|
+
for (const c of cards) {
|
|
618
|
+
const found = c.querySelector(sel);
|
|
619
|
+
if (found && (found.textContent || '').trim()) matched += 1;
|
|
620
|
+
}
|
|
621
|
+
confidence[field] = cards.length ? matched / cards.length : 0;
|
|
622
|
+
if (confidence[field] >= threshold) accepted[field] = sel;
|
|
623
|
+
}
|
|
624
|
+
return { selectors: accepted, confidence, totalCards: cards.length };
|
|
625
|
+
}, { selectors: mapping.selectors, cardSelector, threshold, maxCards });
|
|
626
|
+
if (!result || !result.selectors.title) return null;
|
|
627
|
+
return {
|
|
628
|
+
cardSelector,
|
|
629
|
+
selectors: result.selectors,
|
|
630
|
+
confidence: result.confidence,
|
|
631
|
+
totalCards: result.totalCards,
|
|
632
|
+
threshold,
|
|
633
|
+
};
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/**
|
|
637
|
+
* 番茄 OCR 路径的入口:截图 → 候选编号 → 等 LLM → 还原并验证选择器。
|
|
638
|
+
* 超时/不支持/结果无效/置信度不足都返回 null,调用方回退默认选择器。
|
|
639
|
+
*/
|
|
640
|
+
export async function runFanqieOcrSelfCheck(page, {
|
|
641
|
+
dir,
|
|
642
|
+
rank,
|
|
643
|
+
category = '全部',
|
|
644
|
+
url = '',
|
|
645
|
+
cardSelector = '.rank-book-item',
|
|
646
|
+
timeoutMs = DEFAULT_WAIT_MS,
|
|
647
|
+
} = {}) {
|
|
648
|
+
if (!dir) return null;
|
|
649
|
+
const card = page.locator(cardSelector).first();
|
|
650
|
+
if ((await card.count().catch(() => 0)) === 0) return null;
|
|
651
|
+
|
|
652
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
653
|
+
const cardPath = path.join(dir, 'fanqie-card.jpg');
|
|
654
|
+
const candidatesPath = path.join(dir, 'fanqie-candidates.jpg');
|
|
655
|
+
const resultPath = path.join(dir, 'result.json');
|
|
656
|
+
|
|
657
|
+
let installed = null;
|
|
658
|
+
try {
|
|
659
|
+
await screenshotFanqieCard(page, card, cardPath);
|
|
660
|
+
installed = await installFanqieCandidatePanel(page, cardSelector);
|
|
661
|
+
if (!installed || installed.count < 4) return null;
|
|
662
|
+
await screenshotFanqieCandidates(page, candidatesPath);
|
|
663
|
+
|
|
664
|
+
const request = {
|
|
665
|
+
version: 1,
|
|
666
|
+
mode: 'candidate',
|
|
667
|
+
platform: 'fanqie',
|
|
668
|
+
rank,
|
|
669
|
+
category,
|
|
670
|
+
url: url || page.url(),
|
|
671
|
+
screenshot: cardPath,
|
|
672
|
+
screenshots: [cardPath, candidatesPath],
|
|
673
|
+
screenshot_roles: ['榜单卡片', '候选元素清单'],
|
|
674
|
+
fields: SELF_CHECK_FIELDS.fanqie,
|
|
675
|
+
candidate_count: installed.count,
|
|
676
|
+
created_at: new Date().toISOString(),
|
|
677
|
+
};
|
|
678
|
+
atomicWriteJSON(path.join(dir, 'request.json'), request, { mode: 0o600 });
|
|
679
|
+
atomicWriteJSON(path.join(dir, 'ready.json'), {
|
|
680
|
+
ready: true,
|
|
681
|
+
mode: 'candidate',
|
|
682
|
+
created_at: request.created_at,
|
|
683
|
+
}, { mode: 0o600 });
|
|
684
|
+
|
|
685
|
+
const deadline = Date.now() + timeoutMs;
|
|
686
|
+
while (Date.now() < deadline) {
|
|
687
|
+
if (fs.existsSync(resultPath)) {
|
|
688
|
+
try {
|
|
689
|
+
const parsed = parseResult(fs.readFileSync(resultPath, 'utf8'));
|
|
690
|
+
if (!parsed || parsed.vision_supported === false) return null;
|
|
691
|
+
if (!parsed.fields || typeof parsed.fields !== 'object') {
|
|
692
|
+
await new Promise((resolve) => setTimeout(resolve, POLL_MS));
|
|
693
|
+
continue;
|
|
694
|
+
}
|
|
695
|
+
const applied = await applyFanqieCandidateFields(page, parsed.fields, {
|
|
696
|
+
cardSelector,
|
|
697
|
+
threshold: 0.8,
|
|
698
|
+
});
|
|
699
|
+
if (!applied) return null;
|
|
700
|
+
return {
|
|
701
|
+
...applied,
|
|
702
|
+
candidateCount: installed.count,
|
|
703
|
+
rawFields: parsed.fields,
|
|
704
|
+
};
|
|
705
|
+
} catch {
|
|
706
|
+
// 模型可能正在写文件;继续等。
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
await new Promise((resolve) => setTimeout(resolve, POLL_MS));
|
|
710
|
+
}
|
|
711
|
+
return null;
|
|
712
|
+
} finally {
|
|
713
|
+
await cleanupFanqieCandidatePanel(page);
|
|
714
|
+
}
|
|
715
|
+
}
|