@cloud411716/fancy-webnovel 4.0.1 → 4.0.3
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 +5 -0
- package/lib/scraper-utils.js +38 -2
- package/lib/workspace.js +28 -0
- package/package.json +1 -1
- package/plugins/fancy-scan/scripts/run-scan.js +9 -7
- package/plugins/fancy-scan/scripts/scrapers/fanqie-rank-scraper.js +12 -2
- package/plugins/fancy-scan/scripts/scrapers/jjwxc-rank-scraper.js +60 -22
package/README.md
CHANGED
|
@@ -37,6 +37,11 @@ allowBuilds:
|
|
|
37
37
|
|
|
38
38
|
然后重新执行安装。`tesseract.js` 的 postinstall 只是 OpenCollective 提示;不允许构建时 OCR 模式不可用,但插件其余功能不受影响。
|
|
39
39
|
|
|
40
|
+
番茄 OCR 模式会优先使用本地 `chi_sim.traineddata`,不会默认走 jsdelivr 下载:
|
|
41
|
+
依次查找 `FANCY_TESSDATA_DIR`、`$DSH_HOME`、`~/.dsh`、工作区 `.fancy/tessdata`、
|
|
42
|
+
工作区 `tessdata` 和系统 tessdata 目录。DSH 沙箱里外网请求经常是 `fetch failed`,
|
|
43
|
+
把 `chi_sim.traineddata` 放到上述任一目录即可离线 OCR。
|
|
44
|
+
|
|
40
45
|
## 依赖解析
|
|
41
46
|
|
|
42
47
|
依赖声明在 `dependencies` / `peerDependencies` 中。用 `dsh plugin add` 从 npm 安装时,
|
package/lib/scraper-utils.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* scraper-utils.js — 采集脚本公共工具
|
|
3
3
|
*
|
|
4
|
-
* 提供各平台 scraper
|
|
4
|
+
* 提供各平台 scraper 公用的纯函数;除 tesseract 本地语言包定位外不依赖外部服务。
|
|
5
5
|
*/
|
|
6
|
+
import fs from 'fs';
|
|
7
|
+
import os from 'os';
|
|
8
|
+
import path from 'path';
|
|
6
9
|
|
|
7
10
|
export function getArg(args, name) {
|
|
8
11
|
const i = args.indexOf(name);
|
|
@@ -13,6 +16,36 @@ export function getArg(args, name) {
|
|
|
13
16
|
return inline === undefined ? null : String(inline).slice(prefix.length);
|
|
14
17
|
}
|
|
15
18
|
|
|
19
|
+
/**
|
|
20
|
+
* 找本地 chi_sim.traineddata,避免 tesseract.js 默认从 jsdelivr 下载。
|
|
21
|
+
*
|
|
22
|
+
* DSH 的 bash 沙箱通常只放行工作区/本机文件,外网请求会直接 fetch failed。
|
|
23
|
+
* ~/.dsh 下已经有安装时带的 chi_sim.traineddata,直接把它作为 langPath +
|
|
24
|
+
* cachePath 即可:worker 先读 cache,读到了就不会再走网络。
|
|
25
|
+
*
|
|
26
|
+
* 支持 chi_sim.traineddata(未压缩)和 chi_sim.traineddata.gz(压缩)。
|
|
27
|
+
*
|
|
28
|
+
* @returns {{dir:string,gzip:boolean}|null}
|
|
29
|
+
*/
|
|
30
|
+
export function resolveTessdata() {
|
|
31
|
+
const home = process.env.HOME || os.homedir();
|
|
32
|
+
const dshHome = process.env.DSH_HOME || path.join(home, '.dsh');
|
|
33
|
+
const candidates = [
|
|
34
|
+
process.env.FANCY_TESSDATA_DIR,
|
|
35
|
+
dshHome,
|
|
36
|
+
path.join(process.cwd(), '.fancy', 'tessdata'),
|
|
37
|
+
path.join(process.cwd(), 'tessdata'),
|
|
38
|
+
'/usr/share/tesseract-ocr/5/tessdata',
|
|
39
|
+
'/usr/share/tesseract-ocr/4.00/tessdata',
|
|
40
|
+
'/usr/share/tessdata',
|
|
41
|
+
].filter(Boolean);
|
|
42
|
+
for (const dir of candidates) {
|
|
43
|
+
if (fs.existsSync(path.join(dir, 'chi_sim.traineddata'))) return { dir, gzip: false };
|
|
44
|
+
if (fs.existsSync(path.join(dir, 'chi_sim.traineddata.gz'))) return { dir, gzip: true };
|
|
45
|
+
}
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
|
|
16
49
|
// ---------------------------------------------------------------------------
|
|
17
50
|
// 扫描方式(取数路径)
|
|
18
51
|
// ---------------------------------------------------------------------------
|
|
@@ -260,7 +293,10 @@ export function runCli(promise, label, opts = {}) {
|
|
|
260
293
|
throw new Error("no output was written");
|
|
261
294
|
}
|
|
262
295
|
if (outcome.written < 1) {
|
|
263
|
-
|
|
296
|
+
const reasons = Array.isArray(outcome.partialReasons) && outcome.partialReasons.length
|
|
297
|
+
? ': ' + outcome.partialReasons.join(';')
|
|
298
|
+
: '';
|
|
299
|
+
throw new Error("no output was written" + reasons);
|
|
264
300
|
}
|
|
265
301
|
|
|
266
302
|
// 写结构化 receipt 到 stdout
|
package/lib/workspace.js
CHANGED
|
@@ -286,6 +286,34 @@ export function registerGlobalWorkspace(root, opts = {}) {
|
|
|
286
286
|
return entry;
|
|
287
287
|
}
|
|
288
288
|
|
|
289
|
+
/**
|
|
290
|
+
* Remove a workspace from the machine-level registry.
|
|
291
|
+
*
|
|
292
|
+
* Test helpers create temporary workspaces through `initWorkspace`; without
|
|
293
|
+
* unregistering, every run leaves a stale `/tmp/fancy-ws-test-*` entry behind.
|
|
294
|
+
* Also moves the legacy pointer if it still targets the removed workspace.
|
|
295
|
+
*
|
|
296
|
+
* @param {string} root workspace directory
|
|
297
|
+
* @returns {boolean} true when an entry was removed
|
|
298
|
+
*/
|
|
299
|
+
export function unregisterGlobalWorkspace(root) {
|
|
300
|
+
const workspacePath = path.resolve(root);
|
|
301
|
+
const registry = readGlobalRegistry();
|
|
302
|
+
const remaining = registry.workspaces.filter((entry) => entry.workspace !== workspacePath);
|
|
303
|
+
const removed = remaining.length !== registry.workspaces.length;
|
|
304
|
+
if (removed) writeGlobalRegistry({ ...registry, workspaces: remaining });
|
|
305
|
+
|
|
306
|
+
const pointer = readGlobalPointer();
|
|
307
|
+
if (pointer && pointer.workspace === workspacePath) {
|
|
308
|
+
if (remaining.length) {
|
|
309
|
+
writeGlobalPointer(remaining[0].workspace);
|
|
310
|
+
} else {
|
|
311
|
+
try { fs.unlinkSync(globalPointerPath()); } catch { /* already gone */ }
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
return removed;
|
|
315
|
+
}
|
|
316
|
+
|
|
289
317
|
export function listGlobalWorkspaces() {
|
|
290
318
|
return readGlobalRegistry().workspaces
|
|
291
319
|
.map((entry) => ({ ...entry, exists: isWorkspace(entry.workspace) }))
|
package/package.json
CHANGED
|
@@ -487,13 +487,15 @@ async function runScraper(platform, rank, outDir, scanMode) {
|
|
|
487
487
|
}
|
|
488
488
|
|
|
489
489
|
if (receipt.ok === false) {
|
|
490
|
-
// receipt.error 可能为 undefined(scraper 没设置),fallback 到 stderr
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
490
|
+
// receipt.error 可能为 undefined(scraper 没设置),fallback 到 stderr。
|
|
491
|
+
// 像 "no output was written" 这种通用错误,stderr 里往往有真正的
|
|
492
|
+
// 页面/网络原因,必须一起带给用户,否则只会看到一句无从排查的文案。
|
|
493
|
+
const stderrTail = (result.stderr || '').trim().slice(-600);
|
|
494
|
+
const generic = !receipt.error || /^no output was written/.test(String(receipt.error));
|
|
495
|
+
const error = generic && stderrTail
|
|
496
|
+
? `${receipt.error || 'no output was written'};stderr: ${stderrTail}`
|
|
497
|
+
: (receipt.error || stderrTail || 'scraper 报告失败(无错误详情)');
|
|
498
|
+
return { ok: false, error, stderr: result.stderr };
|
|
497
499
|
}
|
|
498
500
|
|
|
499
501
|
const writtenFiles = receipt.files || receipt.written || receipt.scan_files || [];
|
|
@@ -26,7 +26,7 @@ import path from 'path';
|
|
|
26
26
|
import { pathToFileURL } from 'url';
|
|
27
27
|
import { chromium } from 'playwright-core';
|
|
28
28
|
import Tesseract from 'tesseract.js';
|
|
29
|
-
import { getArg, localDateStamp, runCli, normalizeScanMode, SCAN_MODE_API, renderIntroLines, sanitizeBookFields, sanitizeMarkdownInline } from '#scraper-utils';
|
|
29
|
+
import { getArg, localDateStamp, runCli, normalizeScanMode, SCAN_MODE_API, renderIntroLines, sanitizeBookFields, sanitizeMarkdownInline, resolveTessdata } from '#scraper-utils';
|
|
30
30
|
|
|
31
31
|
// 捕获未处理的 promise 错误——只写 stderr,让上层重试逻辑处理,不要直接退出
|
|
32
32
|
process.on('unhandledRejection', (reason) => {
|
|
@@ -181,7 +181,17 @@ async function resetOcrWorker() {
|
|
|
181
181
|
async function getOcrWorker() {
|
|
182
182
|
if (_ocrWorker) return _ocrWorker;
|
|
183
183
|
if (_ocrInitPromise) return _ocrInitPromise;
|
|
184
|
-
const
|
|
184
|
+
const tessdata = resolveTessdata();
|
|
185
|
+
if (!tessdata) {
|
|
186
|
+
process.stderr.write('[ocr] 未找到本地 chi_sim.traineddata,将尝试在线下载;如果网络被沙箱拦截,请把文件放到 ~/.dsh/ 或设置 FANCY_TESSDATA_DIR\n');
|
|
187
|
+
}
|
|
188
|
+
const init = Tesseract.createWorker('chi_sim', 1, tessdata
|
|
189
|
+
? {
|
|
190
|
+
langPath: tessdata.dir,
|
|
191
|
+
cachePath: tessdata.dir,
|
|
192
|
+
gzip: tessdata.gzip,
|
|
193
|
+
}
|
|
194
|
+
: {});
|
|
185
195
|
_ocrInitPromise = (async () => {
|
|
186
196
|
try {
|
|
187
197
|
const w = await withTimeout(init, OCR_INIT_TIMEOUT_MS, 'OCR worker 初始化');
|
|
@@ -262,32 +262,39 @@ async function scrapeRank(browser, rankTypeId, channelId) {
|
|
|
262
262
|
const partialReasons = [];
|
|
263
263
|
|
|
264
264
|
try {
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
265
|
+
// 晋江页面偶尔会 networkidle 一直不触发(广告/统计请求),
|
|
266
|
+
// 用 networkidle + 30s 超时会把一次正常的慢加载误判成失败。
|
|
267
|
+
// 改成 domcontentloaded + 等 table,并给一次整页重试。
|
|
268
|
+
let data = null;
|
|
269
|
+
let totalBooks = 0;
|
|
270
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
271
|
+
try {
|
|
272
|
+
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 45000 });
|
|
273
|
+
await page.waitForSelector('table', { timeout: 15000 }).catch(() => {});
|
|
274
|
+
data = await extractRankData(page);
|
|
275
|
+
totalBooks = 0;
|
|
276
|
+
for (const ch of data?.channels || []) totalBooks += ch.books.length;
|
|
277
|
+
if (!data?.channels?.length) {
|
|
278
|
+
throw new Error('未解析到榜单(页面结构可能变动或未加载)');
|
|
279
|
+
}
|
|
280
|
+
if (totalBooks === 0) {
|
|
281
|
+
throw new Error('页面解析到 0 本书(选择器可能失效或页面未加载)');
|
|
282
|
+
}
|
|
283
|
+
break;
|
|
284
|
+
} catch (e) {
|
|
285
|
+
if (attempt === 1) throw e;
|
|
286
|
+
console.error(` ⚠ 晋江-${rt.label}(${chLabel})第 ${attempt + 1} 次加载失败,重试:${e.message}`);
|
|
287
|
+
await page.waitForTimeout(1500);
|
|
288
|
+
}
|
|
271
289
|
}
|
|
272
290
|
|
|
273
|
-
let totalBooks = 0;
|
|
274
291
|
data.channels.forEach((ch) => {
|
|
275
|
-
totalBooks += ch.books.length;
|
|
276
292
|
const authors = new Set(ch.books.map((b) => b.author));
|
|
277
293
|
if (ch.books.length >= 5 && authors.size / ch.books.length < 0.2) {
|
|
278
294
|
console.error(` ⚠ ${ch.name}:${ch.books.length} 本只有 ${authors.size} 个唯一作者,可能提取有误`);
|
|
279
295
|
}
|
|
280
296
|
});
|
|
281
297
|
console.error(` ✓ 列表:${data.channels.length} 个频道,共 ${totalBooks} 本`);
|
|
282
|
-
// 解析到 0 本 = 页面结构变了 / 选择器失效 / 没加载出来。
|
|
283
|
-
// extractRankData 永远至少返回一个 `{ name: '全站', books: [] }`,
|
|
284
|
-
// 所以上面的 `!data.channels.length` 守卫**永远不触发** ——
|
|
285
|
-
// 结果是写出一个只有 "## 全站 — 0 本" 的空文件,
|
|
286
|
-
// 上层 `ok: scanFiles.length > 0` 还判定成功,用户拿到空报告。
|
|
287
|
-
if (totalBooks === 0) {
|
|
288
|
-
console.error(`❌ 晋江-${rt.label}(${chLabel})采集失败:页面解析到 0 本书(选择器可能失效或页面未加载)。请人工打开 ${url} 确认。`);
|
|
289
|
-
return null;
|
|
290
|
-
}
|
|
291
298
|
|
|
292
299
|
// 逐本进详情页补**简介**和**内容标签**(列表页没有这两个字段)。
|
|
293
300
|
// 此前 fetchDetails 写好了却从没被调用 —— 晋江产出的 md 里因此一直没有
|
|
@@ -356,6 +363,22 @@ async function scrapeRank(browser, rankTypeId, channelId) {
|
|
|
356
363
|
}
|
|
357
364
|
}
|
|
358
365
|
|
|
366
|
+
/**
|
|
367
|
+
* 确保 browser 有效;断线后重新 launch。
|
|
368
|
+
* 一次榜单采集把 browser 跑崩后,后续榜单不能全部陪着失败。
|
|
369
|
+
*/
|
|
370
|
+
async function ensureBrowser(browserRef) {
|
|
371
|
+
if (browserRef.current) {
|
|
372
|
+
let alive = false;
|
|
373
|
+
try { alive = browserRef.current.isConnected(); } catch (_) { alive = false; }
|
|
374
|
+
if (alive) return browserRef.current;
|
|
375
|
+
try { await browserRef.current.close(); } catch (_) {}
|
|
376
|
+
browserRef.current = null;
|
|
377
|
+
}
|
|
378
|
+
browserRef.current = await chromium.launch({ headless: true, timeout: 60000 });
|
|
379
|
+
return browserRef.current;
|
|
380
|
+
}
|
|
381
|
+
|
|
359
382
|
// ---------------------------------------------------------------------------
|
|
360
383
|
// 主函数
|
|
361
384
|
// ---------------------------------------------------------------------------
|
|
@@ -380,16 +403,16 @@ async function main() {
|
|
|
380
403
|
const files = [];
|
|
381
404
|
|
|
382
405
|
// 启动浏览器
|
|
383
|
-
|
|
406
|
+
const browserRef = { current: null };
|
|
384
407
|
// 被 SIGTERM 杀时(上游超时或中断)主动关掉浏览器,
|
|
385
408
|
// 否则 chromium 会留在系统里继续占 CPU/内存。
|
|
386
409
|
// close 必须带超时兜底:浏览器正在导航时 close() 可能挂住,
|
|
387
410
|
// 无超时的话进程会卡住不退出(实测过)。
|
|
388
411
|
process.on('SIGTERM', async () => {
|
|
389
412
|
try {
|
|
390
|
-
if (
|
|
413
|
+
if (browserRef.current) {
|
|
391
414
|
await Promise.race([
|
|
392
|
-
|
|
415
|
+
browserRef.current.close(),
|
|
393
416
|
new Promise((_, reject) => setTimeout(() => reject(new Error('close timeout')), 5000)),
|
|
394
417
|
]);
|
|
395
418
|
}
|
|
@@ -397,7 +420,7 @@ async function main() {
|
|
|
397
420
|
process.exit(143);
|
|
398
421
|
});
|
|
399
422
|
try {
|
|
400
|
-
|
|
423
|
+
await ensureBrowser(browserRef);
|
|
401
424
|
} catch (launchErr) {
|
|
402
425
|
console.log(JSON.stringify({ ok: false, error: `晋江采集失败:浏览器启动失败:${launchErr.message}` }));
|
|
403
426
|
process.exit(1);
|
|
@@ -412,6 +435,7 @@ async function main() {
|
|
|
412
435
|
// → 整榜已经采好的 content 被 catch 吞掉、整榜不落盘。
|
|
413
436
|
// 只要有一本详情页失败就触发,等于"详情页偶发失败 = 整个榜单没了"。
|
|
414
437
|
const rtInfo = RANK_TYPES.find((r) => r.id === rt);
|
|
438
|
+
const browser = await ensureBrowser(browserRef);
|
|
415
439
|
const result = await scrapeRank(browser, rt, ch);
|
|
416
440
|
if (!result) {
|
|
417
441
|
failed++;
|
|
@@ -444,9 +468,23 @@ async function main() {
|
|
|
444
468
|
}
|
|
445
469
|
}
|
|
446
470
|
} finally {
|
|
447
|
-
|
|
471
|
+
if (browserRef.current) {
|
|
472
|
+
try {
|
|
473
|
+
await Promise.race([
|
|
474
|
+
browserRef.current.close(),
|
|
475
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error('close timeout')), 5000)),
|
|
476
|
+
]);
|
|
477
|
+
} catch (_) { /* best effort */ }
|
|
478
|
+
}
|
|
448
479
|
}
|
|
449
480
|
|
|
481
|
+
// 一个文件都没写出来时,不要把 "no output was written" 当成最终错误 ——
|
|
482
|
+
// 那会把真正的页面/网络原因全部吞掉。把每个榜单的具体失败原因带出去。
|
|
483
|
+
if (written === 0) {
|
|
484
|
+
throw new Error(partialReasons.length
|
|
485
|
+
? `所有榜单均未产出数据:${partialReasons.join(';')}`
|
|
486
|
+
: '所有榜单均未产出数据(无具体错误)');
|
|
487
|
+
}
|
|
450
488
|
return {
|
|
451
489
|
planned: rankTypes.length * channels.length,
|
|
452
490
|
written,
|