@cloud411716/fancy-webnovel 4.27.3 → 4.29.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,197 @@
1
+ /**
2
+ * 从账号已入库作品中提炼/增量 patch 风格。
3
+ *
4
+ * 这里只负责:
5
+ * 1. 从 douyin_job + material 采样;
6
+ * 2. 生成结构化风格提炼提示词;
7
+ * 3. 解析 LLM 返回的 styles[];
8
+ * 4. 交给 fancy-material/styles.js 的 upsertStyleProfiles 增量写入。
9
+ *
10
+ * 不删除任何素材;只写 douyin_style。
11
+ */
12
+
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+
16
+ function unique(values) {
17
+ return [...new Set(values.filter(Boolean))];
18
+ }
19
+
20
+ function stripJsonFence(text) {
21
+ return String(text || '')
22
+ .replace(/^\uFEFF/, '')
23
+ .trim()
24
+ .replace(/^```(?:json)?\s*/i, '')
25
+ .replace(/\s*```$/, '')
26
+ .trim();
27
+ }
28
+
29
+ export function parseStyleDistillResult(text) {
30
+ const src = stripJsonFence(text);
31
+ let data;
32
+ try {
33
+ data = JSON.parse(src);
34
+ } catch {
35
+ const start = src.indexOf('{');
36
+ const end = src.lastIndexOf('}');
37
+ if (start < 0 || end <= start) throw new Error('风格提炼结果不是 JSON 对象');
38
+ data = JSON.parse(src.slice(start, end + 1));
39
+ }
40
+ const styles = Array.isArray(data) ? data : data.styles;
41
+ if (!Array.isArray(styles) || !styles.length) throw new Error('风格提炼结果缺少 styles 数组');
42
+ return styles;
43
+ }
44
+
45
+ export function styleDistillPrompt({ account, samples, existing = [], resultPath }) {
46
+ const kinds = samples && samples.kinds ? samples.kinds : {};
47
+ const titles = (samples && samples.titles) || [];
48
+ const lines = [
49
+ '你是抖音账号风格提炼器。你只分析账号已入库的作品标题和素材名,提炼可跨 kind 使用的风格,不写新素材。',
50
+ '',
51
+ '## 账号',
52
+ `- 名称:${account.name || '未命名'}`,
53
+ `- 地址:${account.url || ''}`,
54
+ `- 已导入作品:${samples?.sourceWorks ?? 0} 篇`,
55
+ `- 已入库素材:${samples?.sourceMaterials ?? 0} 条`,
56
+ '',
57
+ '## 已有风格(用于增量 patch;没有则为空)',
58
+ '```json',
59
+ JSON.stringify(existing, null, 2),
60
+ '```',
61
+ '',
62
+ '## 作品标题样本',
63
+ ...titles.slice(0, 30).map((title) => '- ' + title),
64
+ '',
65
+ '## 素材名样本(按 kind 分组)',
66
+ ];
67
+ for (const [kind, names] of Object.entries(kinds)) {
68
+ lines.push(`### ${kind}`);
69
+ lines.push((names || []).slice(0, 30).join('、') || '(无)');
70
+ lines.push('');
71
+ }
72
+ lines.push(
73
+ '## 提炼目标',
74
+ '提炼 1–3 个**跨 kind 的风格核心**,不是给单个 kind 分类。每个风格要能同时解释:地名、势力、功法/能力、物品、怪物、等级、规则等不同 kind 的写法。',
75
+ '如果账号明显是教学/视觉资产库而不是小说命名风格,style_type 写 teaching 或 visual,并在 dna 里说明。',
76
+ '',
77
+ '## 输出格式(只输出 JSON,不要 Markdown 解释)',
78
+ '```json',
79
+ JSON.stringify({
80
+ styles: [{
81
+ style_key: 'stable_ascii_slug',
82
+ style_name: '中文风格名',
83
+ style_type: 'naming',
84
+ genre_tags: ['仙侠', '古风'],
85
+ dna: '一句话风格 DNA',
86
+ naming_rules: {
87
+ length: [2, 4],
88
+ syntax: ['意象+意象', '动词+宾语'],
89
+ suffixes: [],
90
+ forbidden: ['秘境', '令', '诀'],
91
+ tone: '冷、克制',
92
+ },
93
+ lexicon: { preferred: ['灯', '骨'], forbidden: ['系统'] },
94
+ cross_kind_examples: {
95
+ place_name: ['无灯巷'],
96
+ faction_name: ['无面祠'],
97
+ skill_name: ['问骨'],
98
+ item_name: ['无字灯'],
99
+ monster_name: ['背灯人'],
100
+ rank_name: ['点灯'],
101
+ world_rule: ['灯灭之前,不能回头。'],
102
+ },
103
+ anti_examples: ['无灯巷秘境'],
104
+ compatibility: { 仙侠: 'native', 都市: 'adaptable' },
105
+ confidence: 0.8,
106
+ source_works: samples?.sourceWorks ?? 0,
107
+ source_materials: samples?.sourceMaterials ?? 0,
108
+ }],
109
+ }, null, 2),
110
+ '```',
111
+ '',
112
+ '规则:',
113
+ '- 每个 style_key 用稳定的小写 ASCII;已有风格沿用原 style_key,只补新增例子/词汇/规则。',
114
+ '- 不要照抄作品标题;示例要短,能体现命名语法。',
115
+ '- 风格必须跨 kind 成立;不要只写“这个账号会写地名”。',
116
+ '- 没有把握的风格不要编造;宁少勿多。',
117
+ '',
118
+ `把结果写入:\`${resultPath}\``,
119
+ );
120
+ return lines.join('\n');
121
+ }
122
+
123
+ /**
124
+ * 一次读取 jobs + material,按账号聚合采样。
125
+ * 只读,不修改素材。
126
+ */
127
+ export async function loadStyleSamplesByAccount(db, { maxNamesPerKind = 30, maxTitles = 30 } = {}) {
128
+ const jobResult = await db.query(
129
+ "SELECT account_url, work_id, title FROM douyin_job WHERE import_status = 'imported';",
130
+ );
131
+ const jobRows = Array.isArray(jobResult) && Array.isArray(jobResult[0]) ? jobResult[0] : [];
132
+ const materialResult = await db.query(
133
+ "SELECT id, kind, subkind, name FROM material WHERE source = 'other';",
134
+ );
135
+ const materialRows = Array.isArray(materialResult) && Array.isArray(materialResult[0]) ? materialResult[0] : [];
136
+ return groupStyleSamples(jobRows, materialRows, { maxNamesPerKind, maxTitles });
137
+ }
138
+
139
+ export function groupStyleSamples(jobRows, materialRows, { maxNamesPerKind = 30, maxTitles = 30 } = {}) {
140
+ const jobByWork = new Map();
141
+ for (const job of Array.isArray(jobRows) ? jobRows : []) {
142
+ if (!job || !job.account_url || !job.work_id) continue;
143
+ jobByWork.set(String(job.work_id), {
144
+ account_url: String(job.account_url),
145
+ title: String(job.title || '').trim(),
146
+ });
147
+ }
148
+ const out = new Map();
149
+ const ensure = (url) => {
150
+ if (!out.has(url)) {
151
+ out.set(url, { titles: [], kinds: {}, sourceWorks: 0, sourceMaterials: 0, _works: new Set() });
152
+ }
153
+ return out.get(url);
154
+ };
155
+ for (const job of jobByWork.values()) {
156
+ const bucket = ensure(job.account_url);
157
+ if (job.title && !bucket.titles.includes(job.title) && bucket.titles.length < maxTitles) {
158
+ bucket.titles.push(job.title);
159
+ }
160
+ }
161
+ for (const row of Array.isArray(materialRows) ? materialRows : []) {
162
+ const m = /^material:dy_(\d+)_/.exec(String(row && row.id));
163
+ if (!m) continue;
164
+ const job = jobByWork.get(m[1]);
165
+ if (!job) continue;
166
+ const bucket = ensure(job.account_url);
167
+ const kind = String(row.kind || '未分类').trim();
168
+ if (!bucket.kinds[kind]) bucket.kinds[kind] = [];
169
+ if (bucket.kinds[kind].length < maxNamesPerKind && row.name) {
170
+ bucket.kinds[kind].push(String(row.name));
171
+ }
172
+ bucket.sourceMaterials += 1;
173
+ bucket._works.add(m[1]);
174
+ }
175
+ for (const bucket of out.values()) {
176
+ bucket.sourceWorks = bucket._works.size;
177
+ delete bucket._works;
178
+ }
179
+ return out;
180
+ }
181
+
182
+ export async function persistStyleProfiles(db, profiles, { account = null } = {}) {
183
+ const { upsertStyleProfiles } = await import('../fancy-material/styles.js');
184
+ return upsertStyleProfiles(db, profiles, { account });
185
+ }
186
+
187
+ export function styleResultPath(runDir, account) {
188
+ const slug = String(account?.url || account?.name || 'account')
189
+ .replace(/^https?:\/\//, '')
190
+ .replace(/[^A-Za-z0-9_-]/g, '_')
191
+ .slice(0, 80);
192
+ return path.join(runDir, 'styles', slug + '.json');
193
+ }
194
+
195
+ export function removeStyleResult(file) {
196
+ try { fs.rmSync(file, { force: true }); } catch { /* ignore */ }
197
+ }
@@ -19,7 +19,7 @@ export function helpText() {
19
19
  return `🎬 抖音素材采集 用法
20
20
 
21
21
  /fancy-douyin add <主页地址> 记录一个抖音账号主页
22
- /fancy-douyin list 查看账号名、抖音号和已采集数量
22
+ /fancy-douyin list 查看账号名、抖音号、已采集数量和账号风格(style_key/DNA/示例)
23
23
  /fancy-douyin remove <序号|地址> 删除已记录的账号
24
24
  /fancy-douyin 依次采集所有账号下未处理的图文、视频和文章作品
25
25
  /fancy-douyin help 显示本帮助
@@ -45,6 +45,8 @@ export function helpText() {
45
45
  15. 每次运行结束会自动关闭 Chrome,释放资源。
46
46
  16. 需要登录或安全验证时会弹窗,请在 Chrome 窗口手动完成,然后选择「已登陆」。
47
47
  17. 浏览器脚本部署在 <工作区>/.fancy-tools/fancy-douyin/。
48
+ 18. 每次运行结束后会从已入库作品提炼账号风格,增量 patch 到素材库 douyin_style 表(只增改风格,不删除素材)。
49
+ 19. 生成的 style_key 可直接用于 /fancy-material --style <key> ...;不指定时按题材自动选 2-3 个兼容风格。
48
50
  `;
49
51
  }
50
52
 
@@ -254,6 +256,7 @@ export function summaryText({
254
256
  mode,
255
257
  analysisMode = 'single',
256
258
  subagentWorkers = 0,
259
+ stylesUpdated = [],
257
260
  }) {
258
261
  const lines = [
259
262
  aborted ? '⚠️ 抖音采集已中断' : '✅ 抖音采集完成',
@@ -279,7 +282,11 @@ export function summaryText({
279
282
  lines.push('失败项已跳过,不会中断其他作品。');
280
283
  lines.push('作品级失败已记录为跳过,下次不再重试;账号级失败仍会在下次重试。');
281
284
  }
285
+ if (Array.isArray(stylesUpdated) && stylesUpdated.length) {
286
+ lines.push('风格更新:' + stylesUpdated.join('、'));
287
+ }
282
288
  lines.push('输出目录:' + outputDir);
283
289
  lines.push('任务状态:素材库 douyin_job 表');
290
+ lines.push('风格状态:素材库 douyin_style 表');
284
291
  return lines.join('\n');
285
292
  }