@cloud411716/fancy-webnovel 4.10.0 → 4.11.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.
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Douyin job state stored in the material database.
3
+ *
4
+ * Keeping this next to `material` means a database backup/restore carries both
5
+ * the imported materials and the knowledge of which works produced them. The
6
+ * workspace `crawled.json` remains only as a legacy migration source/backup.
7
+ */
8
+
9
+ import fs from 'fs';
10
+ import path from 'path';
11
+ import { RecordId } from 'surrealdb';
12
+
13
+ import { connectMaterial } from '#material-db';
14
+ import { accountSlug, douyinPaths, readAccounts, readCrawled } from './state.js';
15
+
16
+ export const JOB_TABLE = 'douyin_job';
17
+ export const META_TABLE = 'douyin_meta';
18
+
19
+ export function jobKeyFor(accountUrl, workId) {
20
+ return accountSlug(accountUrl) + '_' + workId;
21
+ }
22
+
23
+ export function jobRelDir(accountUrl, workId) {
24
+ return path.join(accountSlug(accountUrl), String(workId));
25
+ }
26
+
27
+ export async function openJobStore(root) {
28
+ const { db } = await connectMaterial(root);
29
+ return {
30
+ db,
31
+ async close() {
32
+ try { await db.close(); } catch { /* ignore */ }
33
+ },
34
+ };
35
+ }
36
+
37
+ function firstRows(result) {
38
+ return Array.isArray(result) && Array.isArray(result[0]) ? result[0] : [];
39
+ }
40
+
41
+ export async function getJob(db, key) {
42
+ const rows = firstRows(await db.query('SELECT * FROM douyin_job WHERE job_key = $key LIMIT 1;', { key }));
43
+ return rows[0] || null;
44
+ }
45
+
46
+ export async function listJobsForAccount(db, accountUrl) {
47
+ const rows = firstRows(await db.query(
48
+ 'SELECT * FROM douyin_job WHERE account_url = $account_url ORDER BY work_id;',
49
+ { account_url: accountUrl },
50
+ ));
51
+ return rows;
52
+ }
53
+
54
+ export async function countJobsByAccount(db) {
55
+ const rows = firstRows(await db.query(
56
+ "SELECT account_url, count() AS n FROM douyin_job WHERE import_status IN ['imported', 'skipped', 'failed'] GROUP BY account_url;",
57
+ ));
58
+ const counts = new Map();
59
+ for (const row of rows) {
60
+ if (!row || !row.account_url) continue;
61
+ counts.set(String(row.account_url), Number(row.n) || 0);
62
+ }
63
+ return counts;
64
+ }
65
+
66
+ export async function createJob(db, data) {
67
+ const key = data.job_key || jobKeyFor(data.account_url, data.work_id);
68
+ const existing = await getJob(db, key);
69
+ if (existing) return existing;
70
+ const record = {
71
+ job_key: key,
72
+ account_url: data.account_url,
73
+ account_name: data.account_name || '',
74
+ douyin_id: data.douyin_id || '',
75
+ account_sec_uid: data.account_sec_uid || '',
76
+ work_id: String(data.work_id),
77
+ work_type: data.work_type,
78
+ work_url: data.work_url,
79
+ title: data.title || '',
80
+ crawl_status: data.crawl_status || 'pending',
81
+ analysis_status: data.analysis_status || 'pending',
82
+ import_status: data.import_status || 'pending',
83
+ dir_rel: data.dir_rel || '',
84
+ material_count: Number(data.material_count) || 0,
85
+ attempts: Number(data.attempts) || 0,
86
+ reason: data.reason || '',
87
+ error: data.error || '',
88
+ created_at: new Date(),
89
+ updated_at: new Date(),
90
+ ...(data.imported_at ? { imported_at: new Date(data.imported_at) } : {}),
91
+ };
92
+ await db.upsert(new RecordId(JOB_TABLE, key)).content(record);
93
+ return record;
94
+ }
95
+
96
+ export async function updateJob(db, key, patch) {
97
+ await db.upsert(new RecordId(JOB_TABLE, key)).merge({
98
+ ...patch,
99
+ updated_at: new Date(),
100
+ });
101
+ }
102
+
103
+ async function getMeta(db, key) {
104
+ const rows = firstRows(await db.query('SELECT meta_value FROM douyin_meta WHERE meta_key = $key LIMIT 1;', { key }));
105
+ return rows[0] ? String(rows[0].meta_value || '') : '';
106
+ }
107
+
108
+ async function setMeta(db, key, value) {
109
+ await db.upsert(new RecordId(META_TABLE, key)).content({
110
+ meta_key: key,
111
+ meta_value: String(value),
112
+ updated_at: new Date(),
113
+ });
114
+ }
115
+
116
+ function inferWorkType(record, workId) {
117
+ if (record.type === 'note' || record.type === 'video' || record.type === 'article') return record.type;
118
+ const url = String(record.url || '');
119
+ if (url.includes('/article/')) return 'article';
120
+ if (url.includes('/video/')) return 'video';
121
+ return 'note';
122
+ }
123
+
124
+ /**
125
+ * One-time migration from the legacy workspace crawled.json into douyin_job.
126
+ * Existing database rows win; the marker prevents re-running the migration.
127
+ */
128
+ export async function migrateCrawledJobs(db, root) {
129
+ if (await getMeta(db, 'crawled_migrated') === '1') return { migrated: 0 };
130
+ const crawled = readCrawled(root);
131
+ const accounts = new Map(readAccounts(root).map((item) => [item.url, item]));
132
+ let migrated = 0;
133
+ for (const [workId, record] of Object.entries(crawled)) {
134
+ if (!record || typeof record !== 'object' || !record.account_url) continue;
135
+ const key = jobKeyFor(record.account_url, workId);
136
+ if (await getJob(db, key)) continue;
137
+ const account = accounts.get(record.account_url) || {};
138
+ const failed = record.failed === true;
139
+ const skipped = record.skip === true;
140
+ const inserted = Number(record.inserted) || 0;
141
+ const parsedImportedAt = record.crawled_at ? new Date(record.crawled_at) : new Date();
142
+ const importedAt = Number.isNaN(parsedImportedAt.getTime()) ? new Date() : parsedImportedAt;
143
+ await createJob(db, {
144
+ job_key: key,
145
+ account_url: record.account_url,
146
+ account_name: account.name || '',
147
+ douyin_id: account.douyin_id || '',
148
+ account_sec_uid: account.sec_uid || '',
149
+ work_id: String(workId),
150
+ work_type: inferWorkType(record, workId),
151
+ work_url: record.url || '',
152
+ title: record.title || '',
153
+ crawl_status: failed ? 'failed' : 'crawled',
154
+ analysis_status: failed ? 'failed' : 'analyzed',
155
+ import_status: failed ? 'failed' : (skipped ? 'skipped' : 'imported'),
156
+ dir_rel: '',
157
+ material_count: inserted,
158
+ reason: record.reason || '',
159
+ error: failed ? (record.reason || '') : '',
160
+ imported_at: importedAt,
161
+ });
162
+ migrated += 1;
163
+ }
164
+ await setMeta(db, 'crawled_migrated', '1');
165
+ return { migrated };
166
+ }
167
+
168
+ export function legacyCrawledPath(root) {
169
+ return douyinPaths(root).crawled;
170
+ }
171
+
172
+ export function jobArtifactsExist(root, record) {
173
+ if (!record || !record.dir_rel) return false;
174
+ const dir = path.join(douyinPaths(root).base, 'jobs', record.dir_rel);
175
+ try {
176
+ if (!fs.statSync(dir).isDirectory()) return false;
177
+ return fs.existsSync(path.join(dir, 'materials.jsonl'))
178
+ || fs.existsSync(path.join(dir, 'note.json'))
179
+ || fs.existsSync(path.join(dir, 'video.json'))
180
+ || fs.existsSync(path.join(dir, 'article.json'));
181
+ } catch {
182
+ return false;
183
+ }
184
+ }
@@ -28,6 +28,7 @@ export function douyinPaths(root) {
28
28
  profile: path.join(base, 'chrome-profile'),
29
29
  captchaLog: path.join(base, 'captcha.log'),
30
30
  output: path.join(base, 'output'),
31
+ jobs: path.join(base, 'jobs'),
31
32
  };
32
33
  }
33
34
 
@@ -204,7 +205,7 @@ export function markCrawled(root, noteId, data) {
204
205
  return state[noteId];
205
206
  }
206
207
 
207
- export function accountListText(root) {
208
+ export function accountListText(root, countsOverride = null) {
208
209
  const accounts = readAccounts(root);
209
210
  if (!accounts.length) {
210
211
  return [
@@ -212,11 +213,13 @@ export function accountListText(root) {
212
213
  '先添加账号主页:/fancy-douyin add https://www.douyin.com/user/...',
213
214
  ].join('\n');
214
215
  }
215
- const crawled = readCrawled(root);
216
- const counts = new Map();
217
- for (const item of Object.values(crawled)) {
218
- if (!item || typeof item !== 'object' || !item.account_url) continue;
219
- counts.set(item.account_url, (counts.get(item.account_url) || 0) + 1);
216
+ const counts = countsOverride instanceof Map ? countsOverride : new Map();
217
+ if (!(countsOverride instanceof Map)) {
218
+ const crawled = readCrawled(root);
219
+ for (const item of Object.values(crawled)) {
220
+ if (!item || typeof item !== 'object' || !item.account_url) continue;
221
+ counts.set(item.account_url, (counts.get(item.account_url) || 0) + 1);
222
+ }
220
223
  }
221
224
  const lines = ['已记录的抖音账号:'];
222
225
  accounts.forEach((item, index) => {
@@ -68,3 +68,39 @@ export function createSerialLock() {
68
68
  return next;
69
69
  };
70
70
  }
71
+
72
+ /**
73
+ * A single-producer / multi-consumer async queue. The parent pushes crawled
74
+ * jobs as soon as their files are ready; analysis workers consume them while
75
+ * the parent continues scanning and crawling.
76
+ */
77
+ export function createJobQueue() {
78
+ const items = [];
79
+ const waiters = [];
80
+ let closed = false;
81
+ const wake = () => {
82
+ const waiter = waiters.shift();
83
+ if (waiter) waiter();
84
+ };
85
+ return {
86
+ push(item) {
87
+ if (closed) throw new Error('job queue is closed');
88
+ items.push(item);
89
+ wake();
90
+ },
91
+ close() {
92
+ closed = true;
93
+ while (waiters.length) wake();
94
+ },
95
+ async next() {
96
+ while (true) {
97
+ if (items.length) return items.shift();
98
+ if (closed) return null;
99
+ await new Promise((resolve) => waiters.push(resolve));
100
+ }
101
+ },
102
+ get size() {
103
+ return items.length;
104
+ },
105
+ };
106
+ }
@@ -29,13 +29,15 @@ export function helpText() {
29
29
  - 图片和视频能力都没有时,跳过图文/视频,只处理文章。
30
30
  - 图文作品会下载轮播原图并转成 JPG;如果轮播里混有视频页,会下载该页短视频,用场景变化检测 + 固定间隔兜底抽取关键帧拼图。
31
31
  - 文章作品直接提取标题、发布日期、阅读时长和正文,按长文设定拆成原子素材。
32
- - 采集完成后可由 DSH 子 Agent 并行分析作品:父进程负责采集、校验、入库和写 crawled.json,子 Agent 只写各作品的 materials.jsonl。
32
+ - 扫描一个账号后,未处理作品会边采集边交给子 Agent 分析,不再等所有账号采集完。
33
+ - 父进程负责采集、校验、入库和任务状态;子 Agent 只写各作品的 materials.jsonl。
34
+ - 作品任务状态记录在素材库的 douyin_job 表;中途重启会复用稳定任务目录,已导入/已跳过的作品不会重采。
33
35
  - 子 Agent 并发数由 FANCY_DOUYIN_SUBAGENTS 控制(默认 3,0 关闭);DSH 没有 subagent 服务或 spawn provider 时自动回退单 Agent 串行。
34
36
  - 视频作品先判断时长:超过 1 分钟直接跳过;不超过 1 分钟的先看前 5 秒,
35
37
  与网文创作无关就跳过,有关才继续分析关键帧。
36
38
  - 如果内容与网文创作无关,LLM 会写入 skip 标记,该作品记为已处理并跳过。
37
39
  - 素材按 material JSONL 格式写入数据库,source 固定为 other,kind 用中文作品主题。
38
- - 已成功入库、确认无关或作品级失败的作品记录在 <工作区>/.fancy/douyin/crawled.json,后续跳过;账号级失败仍会重试。
40
+ - 已成功入库、确认无关或作品级失败的作品记录在素材库 douyin_job 表,后续跳过;账号级失败仍会重试。
39
41
  - 登录态保存在 <工作区>/.fancy/douyin/chrome-profile/,并镜像到 login-state.json。
40
42
  - 首次需要登录时用有头 Chrome;登录态有效后后续运行自动使用无头 Chrome。
41
43
  - 每次运行结束会自动关闭 Chrome,释放资源。