@cloud411716/fancy-webnovel 4.27.2 → 4.28.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/docs/douyin-plugin.md +9 -1
- package/docs/material-library/README.md +3 -1
- package/docs/material-library/prompt.md +7 -4
- package/docs/material-library/schema.surql +40 -1
- package/lib/material-db.js +9 -2
- package/package.json +1 -1
- package/plugins/fancy-bootstrap/index.js +1 -1
- package/plugins/fancy-db/index.js +1 -1
- package/plugins/fancy-douyin/index.js +83 -39
- package/plugins/fancy-douyin/state.js +24 -1
- package/plugins/fancy-douyin/style-distill.js +197 -0
- package/plugins/fancy-douyin/templates.js +8 -1
- package/plugins/fancy-material/builtin-styles.js +448 -0
- package/plugins/fancy-material/index.js +92 -8
- package/plugins/fancy-material/styles.js +441 -0
- package/plugins/fancy-material/templates.js +12 -0
|
@@ -31,6 +31,7 @@ import { exportMaterials } from './exporter.js';
|
|
|
31
31
|
import { allKnownGenres } from './genres.js';
|
|
32
32
|
import { buildExistingIndex, countByKind, countKind } from './inventory.js';
|
|
33
33
|
import { KIND_LABELS, MATERIAL_KINDS, customFocusBlock, focusBlock, renderKindTable, resolveCustomKinds, resolveFocus } from './kinds.js';
|
|
34
|
+
import { loadStyleRegistry, selectStyles, styleBatchSummary, stylePromptBlock, styleSummaryText } from './styles.js';
|
|
34
35
|
import { exportMaterialDatabase, importMaterialDatabase } from './native-backup.js';
|
|
35
36
|
import { nextBatchRequest, planMaterialQueue } from './queue.js';
|
|
36
37
|
import { deployMaterialTools } from './tool-deploy.js';
|
|
@@ -120,6 +121,9 @@ function renderBasePrompt({
|
|
|
120
121
|
batchSize = DEFAULT_BATCH_SIZE,
|
|
121
122
|
focusBlockText = '',
|
|
122
123
|
custom = null,
|
|
124
|
+
styleBlock = '',
|
|
125
|
+
styleRules = '',
|
|
126
|
+
audience = '',
|
|
123
127
|
}) {
|
|
124
128
|
const sourceFixed = mode === 'other' ? 'other' : 'builtin';
|
|
125
129
|
const sourceNote = sourceFixed === 'other'
|
|
@@ -136,8 +140,9 @@ function renderBasePrompt({
|
|
|
136
140
|
FOCUS_BLOCK: focusBlockText || focusBlock(focus),
|
|
137
141
|
TARGET_PER_KIND: String(targetPerKind),
|
|
138
142
|
BATCH_SIZE: String(batchSize),
|
|
139
|
-
AUDIENCE: '男频 / 女频 / 通用',
|
|
140
|
-
STYLE_RULES: '未指定(执行通用创作标准)',
|
|
143
|
+
AUDIENCE: audience || '男频 / 女频 / 通用',
|
|
144
|
+
STYLE_RULES: styleRules || '未指定(执行通用创作标准)',
|
|
145
|
+
STYLE_BLOCK: styleBlock || '(本次未选择账号风格,按通用规则生成。)',
|
|
141
146
|
BATCH_ID: batchId || 'material-YYYYMMDD-01',
|
|
142
147
|
SEED: batchId || 'material-v4',
|
|
143
148
|
EXISTING_INDEX: existingIndex || '(运行 /fancy-material 时由插件提供)',
|
|
@@ -160,6 +165,38 @@ function stripQuotes(value) {
|
|
|
160
165
|
return text;
|
|
161
166
|
}
|
|
162
167
|
|
|
168
|
+
/**
|
|
169
|
+
* 从参数里抽取 --style。
|
|
170
|
+
* 支持:--style suci / --style=suci / --style suci,crazy-fish。
|
|
171
|
+
* 返回清洗后的参数(保持其它参数的相对顺序)。
|
|
172
|
+
*/
|
|
173
|
+
export function splitStyleOption(rawTokens) {
|
|
174
|
+
const tokens = [];
|
|
175
|
+
const styles = [];
|
|
176
|
+
let missing = false;
|
|
177
|
+
for (let i = 0; i < rawTokens.length; i += 1) {
|
|
178
|
+
const token = rawTokens[i];
|
|
179
|
+
if (token === '--style') {
|
|
180
|
+
const value = rawTokens[i + 1];
|
|
181
|
+
if (!value || value.startsWith('--')) {
|
|
182
|
+
missing = true;
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
styles.push(value);
|
|
186
|
+
i += 1;
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
if (token.startsWith('--style=')) {
|
|
190
|
+
const value = token.slice('--style='.length).trim();
|
|
191
|
+
if (!value) missing = true;
|
|
192
|
+
else styles.push(value);
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
tokens.push(token);
|
|
196
|
+
}
|
|
197
|
+
return { tokens, styleRaw: styles.join(','), missing };
|
|
198
|
+
}
|
|
199
|
+
|
|
163
200
|
/**
|
|
164
201
|
* Resolve a user-provided import path. Relative paths are resolved from the
|
|
165
202
|
* session cwd first, then from the workspace directory.
|
|
@@ -565,6 +602,22 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
|
|
|
565
602
|
return notify(session, 'error', '❌ 部署素材查询脚本失败:\n' + (tools.problems.join('\n') || '未知错误'));
|
|
566
603
|
}
|
|
567
604
|
const database = materialDatabaseName(readWorkspace(root));
|
|
605
|
+
const styleRegistry = await loadStyleRegistry(root);
|
|
606
|
+
let selectedStyles = [];
|
|
607
|
+
try {
|
|
608
|
+
selectedStyles = selectStyles(styleRegistry.styles, {
|
|
609
|
+
genres: plan.genres,
|
|
610
|
+
explicit: opts.styleRaw || 'auto',
|
|
611
|
+
limit: 3,
|
|
612
|
+
});
|
|
613
|
+
} catch (err) {
|
|
614
|
+
return notify(session, 'error', '❌ ' + (err && err.message ? err.message : String(err)));
|
|
615
|
+
}
|
|
616
|
+
const styleBlock = stylePromptBlock(styleRegistry.styles, selectedStyles, { genres: plan.genres });
|
|
617
|
+
const styleRules = selectedStyles.length
|
|
618
|
+
? '本次使用账号风格:' + styleSummaryText(selectedStyles) + ';风格核心优先于题材命名体例。'
|
|
619
|
+
: '未指定账号风格(执行通用创作标准)。';
|
|
620
|
+
const styleSummary = styleBatchSummary(selectedStyles);
|
|
568
621
|
const counts = await countByKind(root, plan.genres);
|
|
569
622
|
// 自定义素材第一轮 kind 由 LLM 决定,这里先用一个占位项跑一条队列。
|
|
570
623
|
const kinds = isCustom
|
|
@@ -603,6 +656,8 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
|
|
|
603
656
|
batchSize: config.batchSize,
|
|
604
657
|
focusBlockText,
|
|
605
658
|
custom: isCustom ? { genre: plan.customGenre, materialType: plan.customMaterialType } : null,
|
|
659
|
+
styleBlock,
|
|
660
|
+
styleRules,
|
|
606
661
|
});
|
|
607
662
|
|
|
608
663
|
const queue = planned.all.map((item) => ({
|
|
@@ -634,6 +689,12 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
|
|
|
634
689
|
genre_mode: plan.mode,
|
|
635
690
|
genres: plan.genres,
|
|
636
691
|
source: plan.mode === 'other' ? 'other' : 'builtin',
|
|
692
|
+
styles: selectedStyles.map((style) => ({
|
|
693
|
+
style_key: style.style_key,
|
|
694
|
+
style_name: style.style_name,
|
|
695
|
+
style_type: style.style_type,
|
|
696
|
+
genre_tags: style.genre_tags,
|
|
697
|
+
})),
|
|
637
698
|
...(isCustom ? {
|
|
638
699
|
custom_genre: plan.customGenre,
|
|
639
700
|
custom_material_type: plan.customMaterialType,
|
|
@@ -739,6 +800,7 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
|
|
|
739
800
|
: null,
|
|
740
801
|
customKindPending: isCustom && !item.kind,
|
|
741
802
|
sourceFixed: plan.mode === 'other' ? 'other' : 'builtin',
|
|
803
|
+
styleSummary,
|
|
742
804
|
});
|
|
743
805
|
const sent = await llmFollowup(invocation, prompt, { appendTempRule: false });
|
|
744
806
|
if (!sent || sent.ok !== true) {
|
|
@@ -959,13 +1021,15 @@ async function runGenerate(ctx, invocation, session, focusRaw = '', taskList, op
|
|
|
959
1021
|
batches: batchCount,
|
|
960
1022
|
total,
|
|
961
1023
|
progressFile,
|
|
1024
|
+
styles: selectedStyles.map((style) => ({ style_key: style.style_key, style_name: style.style_name })),
|
|
962
1025
|
aborted,
|
|
963
1026
|
stopReason,
|
|
964
1027
|
}));
|
|
965
1028
|
}
|
|
966
1029
|
|
|
967
1030
|
function materialTaskTitles(invocation) {
|
|
968
|
-
const
|
|
1031
|
+
const parsed = splitStyleOption(String(invocation.rawInput || '').trim().split(/\s+/).filter(Boolean));
|
|
1032
|
+
const tokens = parsed.tokens;
|
|
969
1033
|
const command = (tokens[0] || '').toLowerCase();
|
|
970
1034
|
if (command === 'help' || command === '?') return ['显示素材库帮助'];
|
|
971
1035
|
if (command === 'prompt') return ['读取题材列表', '渲染素材提示词'];
|
|
@@ -985,12 +1049,17 @@ function materialTaskTitles(invocation) {
|
|
|
985
1049
|
export async function apply(ctx) {
|
|
986
1050
|
registerCommandWithTasks(ctx, {
|
|
987
1051
|
name: 'fancy-material',
|
|
988
|
-
description: '🧩 素材库 ( usage: /fancy-material [素材类型] | load <文件> | dump | export | import | init | remove | prompt | help )',
|
|
989
|
-
input: { hint: '[素材类型] | load <文件.jsonl> | dump | export [文件.surql] | import [文件.surql]' },
|
|
1052
|
+
description: '🧩 素材库 ( usage: /fancy-material [--style <key>] [素材类型] | load <文件> | dump | export | import | init | remove | prompt | help )',
|
|
1053
|
+
input: { hint: '[--style <key>] [素材类型] | load <文件.jsonl> | dump | export [文件.surql] | import [文件.surql]' },
|
|
990
1054
|
handler: async (invocation, taskList) => {
|
|
991
1055
|
const session = invocation.agent.session;
|
|
992
1056
|
const raw = String(invocation.rawInput || '').trim();
|
|
993
|
-
const
|
|
1057
|
+
const parsedStyle = splitStyleOption(raw.split(/\s+/).filter(Boolean));
|
|
1058
|
+
if (parsedStyle.missing) {
|
|
1059
|
+
return notify(session, 'error', '用法:--style <style_key>,多个用逗号分隔;可用 /fancy-douyin list 查看风格 key。');
|
|
1060
|
+
}
|
|
1061
|
+
const tokens = parsedStyle.tokens;
|
|
1062
|
+
const styleRaw = parsedStyle.styleRaw;
|
|
994
1063
|
const command = (tokens[0] || '').toLowerCase();
|
|
995
1064
|
|
|
996
1065
|
if (command === 'help' || command === '?') return notify(session, 'success', helpText());
|
|
@@ -1001,6 +1070,18 @@ export async function apply(ctx) {
|
|
|
1001
1070
|
let root = null;
|
|
1002
1071
|
try { root = workspaceOf(session); } catch { /* prompt also works outside a workspace */ }
|
|
1003
1072
|
const genres = allKnownGenres(root);
|
|
1073
|
+
let styleBlock = '';
|
|
1074
|
+
let styleRules = '';
|
|
1075
|
+
if (root) {
|
|
1076
|
+
try {
|
|
1077
|
+
const registry = await loadStyleRegistry(root);
|
|
1078
|
+
const selected = selectStyles(registry.styles, { genres, explicit: 'auto', limit: 3 });
|
|
1079
|
+
styleBlock = stylePromptBlock(registry.styles, selected, { genres });
|
|
1080
|
+
styleRules = selected.length
|
|
1081
|
+
? '本次预览风格:' + styleSummaryText(selected) + '(实际运行时按题材自动选择)'
|
|
1082
|
+
: '未指定账号风格(执行通用创作标准)。';
|
|
1083
|
+
} catch { /* 预览提示词不因风格库失败而中断 */ }
|
|
1084
|
+
}
|
|
1004
1085
|
const rendered = renderBasePrompt({
|
|
1005
1086
|
mode: 'builtin',
|
|
1006
1087
|
genres,
|
|
@@ -1011,6 +1092,8 @@ export async function apply(ctx) {
|
|
|
1011
1092
|
workspace: root || '(运行时提供)',
|
|
1012
1093
|
focus: null,
|
|
1013
1094
|
validateScript: VALIDATE_SCRIPT,
|
|
1095
|
+
styleBlock,
|
|
1096
|
+
styleRules,
|
|
1014
1097
|
});
|
|
1015
1098
|
return notify(session, 'success', promptDisplayText(rendered));
|
|
1016
1099
|
} catch (err) {
|
|
@@ -1020,7 +1103,7 @@ export async function apply(ctx) {
|
|
|
1020
1103
|
|
|
1021
1104
|
const SPECIAL = new Set(['load', 'dump', 'export', 'import', 'init', 'remove', 'prompt']);
|
|
1022
1105
|
try {
|
|
1023
|
-
if (!command) return await runGenerate(ctx, invocation, session, '', taskList);
|
|
1106
|
+
if (!command) return await runGenerate(ctx, invocation, session, '', taskList, { styleRaw });
|
|
1024
1107
|
if (command === 'load') {
|
|
1025
1108
|
if (tokens.length < 2) return notify(session, 'error', '用法:/fancy-material load <文件.jsonl>');
|
|
1026
1109
|
return await runLoad(ctx, invocation, session, tokens.slice(1).join(' '), taskList);
|
|
@@ -1058,10 +1141,11 @@ export async function apply(ctx) {
|
|
|
1058
1141
|
materialType: allKinds ? 'all' : materialTypeRaw,
|
|
1059
1142
|
allKinds,
|
|
1060
1143
|
},
|
|
1144
|
+
styleRaw,
|
|
1061
1145
|
});
|
|
1062
1146
|
}
|
|
1063
1147
|
// 其它单参数视为素材类型重点,例如 /fancy-material 地名
|
|
1064
|
-
return await runGenerate(ctx, invocation, session,
|
|
1148
|
+
return await runGenerate(ctx, invocation, session, tokens.join(' '), taskList, { styleRaw });
|
|
1065
1149
|
} catch (err) {
|
|
1066
1150
|
return notify(session, 'error', '❌ ' + (err && err.message ? err.message : String(err)));
|
|
1067
1151
|
}
|
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 风格注册表:内置风格 + 数据库 douyin_style。
|
|
3
|
+
*
|
|
4
|
+
* 风格是跨 kind 的不变量;kind 只决定"写什么信息点"。
|
|
5
|
+
* 这里不处理具体生成,只负责加载、合并、按题材选择、渲染成提示词。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { RecordId } from 'surrealdb';
|
|
9
|
+
import { connectMaterial } from '#material-db';
|
|
10
|
+
import { BUILTIN_STYLES, SELECTABLE_STYLE_TYPES } from './builtin-styles.js';
|
|
11
|
+
|
|
12
|
+
export const STYLE_TABLE = 'douyin_style';
|
|
13
|
+
|
|
14
|
+
function asArray(value) {
|
|
15
|
+
return Array.isArray(value) ? value : [];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function asObject(value) {
|
|
19
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function unique(values) {
|
|
23
|
+
return [...new Set(values.filter(Boolean))];
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function mergeObject(base, patch) {
|
|
27
|
+
const out = { ...asObject(base) };
|
|
28
|
+
for (const [key, value] of Object.entries(asObject(patch))) {
|
|
29
|
+
if (Array.isArray(value)) {
|
|
30
|
+
out[key] = unique([...asArray(out[key]), ...value]);
|
|
31
|
+
} else if (value && typeof value === 'object' && !Array.isArray(value)) {
|
|
32
|
+
out[key] = mergeObject(out[key], value);
|
|
33
|
+
} else if (value !== undefined && value !== null && value !== '') {
|
|
34
|
+
out[key] = value;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function normalizeStyle(raw, origin = 'database') {
|
|
41
|
+
const style = raw && typeof raw === 'object' ? raw : {};
|
|
42
|
+
const profile = asObject(style.profile_json);
|
|
43
|
+
const merged = { ...profile, ...style };
|
|
44
|
+
return {
|
|
45
|
+
style_key: String(merged.style_key || '').trim(),
|
|
46
|
+
style_name: String(merged.style_name || merged.name || merged.style_key || '').trim(),
|
|
47
|
+
style_type: ['naming', 'structure', 'teaching', 'visual'].includes(String(merged.style_type || '').trim())
|
|
48
|
+
? String(merged.style_type).trim()
|
|
49
|
+
: 'naming',
|
|
50
|
+
account_names: unique([
|
|
51
|
+
...asArray(merged.account_names),
|
|
52
|
+
merged.account_name,
|
|
53
|
+
].map((v) => String(v || '').trim()).filter(Boolean)),
|
|
54
|
+
account_urls: unique([
|
|
55
|
+
...asArray(merged.account_urls),
|
|
56
|
+
merged.account_url,
|
|
57
|
+
].map((v) => String(v || '').trim()).filter(Boolean)),
|
|
58
|
+
genre_tags: unique(asArray(merged.genre_tags).map((v) => String(v || '').trim())),
|
|
59
|
+
dna: String(merged.dna || '').trim(),
|
|
60
|
+
naming_rules: asObject(merged.naming_rules),
|
|
61
|
+
lexicon: asObject(merged.lexicon),
|
|
62
|
+
cross_kind_examples: asObject(merged.cross_kind_examples),
|
|
63
|
+
anti_examples: unique(asArray(merged.anti_examples).map((v) => String(v || '').trim())),
|
|
64
|
+
compatibility: asObject(merged.compatibility),
|
|
65
|
+
confidence: Math.max(0, Math.min(1, Number(merged.confidence) || 0)),
|
|
66
|
+
source_works: Number(merged.source_works) || 0,
|
|
67
|
+
source_materials: Number(merged.source_materials) || 0,
|
|
68
|
+
version: Number(merged.version) || 1,
|
|
69
|
+
status: String(merged.status || 'active'),
|
|
70
|
+
origin: style.origin || origin,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function mergeStyle(base, patch) {
|
|
75
|
+
const a = normalizeStyle(base, base.origin || 'builtin');
|
|
76
|
+
const b = normalizeStyle(patch, patch.origin || 'database');
|
|
77
|
+
return {
|
|
78
|
+
...a,
|
|
79
|
+
...b,
|
|
80
|
+
style_key: b.style_key || a.style_key,
|
|
81
|
+
style_name: b.style_name || a.style_name,
|
|
82
|
+
style_type: b.style_type || a.style_type,
|
|
83
|
+
account_names: unique([...a.account_names, ...b.account_names]),
|
|
84
|
+
account_urls: unique([...a.account_urls, ...b.account_urls]),
|
|
85
|
+
genre_tags: unique([...a.genre_tags, ...b.genre_tags]),
|
|
86
|
+
dna: b.dna || a.dna,
|
|
87
|
+
naming_rules: mergeObject(a.naming_rules, b.naming_rules),
|
|
88
|
+
lexicon: mergeObject(a.lexicon, b.lexicon),
|
|
89
|
+
cross_kind_examples: mergeObject(a.cross_kind_examples, b.cross_kind_examples),
|
|
90
|
+
anti_examples: unique([...a.anti_examples, ...b.anti_examples]),
|
|
91
|
+
compatibility: { ...a.compatibility, ...b.compatibility },
|
|
92
|
+
confidence: Math.max(a.confidence, b.confidence),
|
|
93
|
+
source_works: Math.max(a.source_works, b.source_works),
|
|
94
|
+
source_materials: Math.max(a.source_materials, b.source_materials),
|
|
95
|
+
version: Math.max(a.version, b.version),
|
|
96
|
+
origin: b.origin === 'database' ? 'merged' : a.origin,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function databaseStyles(db) {
|
|
101
|
+
if (!db) return [];
|
|
102
|
+
try {
|
|
103
|
+
const result = await db.query(
|
|
104
|
+
"SELECT style_key, account_url, account_name, style_name, style_type, genre_tags, dna, naming_rules, lexicon, cross_kind_examples, anti_examples, compatibility, confidence, source_works, source_materials, version, status, profile_json FROM douyin_style WHERE status = 'active';",
|
|
105
|
+
);
|
|
106
|
+
const rows = Array.isArray(result) && Array.isArray(result[0]) ? result[0] : [];
|
|
107
|
+
return rows.map((row) => normalizeStyle({ ...row, origin: 'database' }, 'database'))
|
|
108
|
+
.filter((style) => style.style_key);
|
|
109
|
+
} catch {
|
|
110
|
+
// 旧库还没执行 schema v13 时不应阻断生成。
|
|
111
|
+
return [];
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function styleIdentity(style) {
|
|
116
|
+
return String(style.style_name || '').trim() + '\u0000' + String(style.dna || '').trim();
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** 同账号组可能产生多个 style_key(带账号前缀),按名称+DNA 去重。 */
|
|
120
|
+
function dedupeStyles(styles) {
|
|
121
|
+
const byIdentity = new Map();
|
|
122
|
+
for (const style of styles) {
|
|
123
|
+
const key = styleIdentity(style);
|
|
124
|
+
if (!key || key === '\u0000') {
|
|
125
|
+
byIdentity.set(style.style_key, style);
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
const existing = byIdentity.get(key);
|
|
129
|
+
if (!existing) {
|
|
130
|
+
byIdentity.set(key, style);
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
const merged = mergeStyle(existing, style);
|
|
134
|
+
merged.style_key = existing.style_key;
|
|
135
|
+
merged.origin = 'merged';
|
|
136
|
+
byIdentity.set(key, merged);
|
|
137
|
+
}
|
|
138
|
+
return [...byIdentity.values()];
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* 加载内置 + 数据库风格,同 style_key 合并;数据库字段优先。
|
|
143
|
+
*
|
|
144
|
+
* @param {string} root 工作区
|
|
145
|
+
* @param {{db?: object}} [options] 传入已有连接可避免重复连接
|
|
146
|
+
* @returns {Promise<{styles: object[], builtin: number, database: number}>}
|
|
147
|
+
*/
|
|
148
|
+
export async function loadStyleRegistry(root, { db = null } = {}) {
|
|
149
|
+
const byKey = new Map();
|
|
150
|
+
for (const style of BUILTIN_STYLES) {
|
|
151
|
+
const normalized = normalizeStyle(style, 'builtin');
|
|
152
|
+
if (normalized.style_key) byKey.set(normalized.style_key, normalized);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
let ownedDb = null;
|
|
156
|
+
let useDb = db;
|
|
157
|
+
if (!useDb) {
|
|
158
|
+
try {
|
|
159
|
+
const connected = await connectMaterial(root);
|
|
160
|
+
ownedDb = connected.db;
|
|
161
|
+
useDb = connected.db;
|
|
162
|
+
} catch {
|
|
163
|
+
useDb = null;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
let rows = [];
|
|
167
|
+
try {
|
|
168
|
+
rows = await databaseStyles(useDb);
|
|
169
|
+
} finally {
|
|
170
|
+
if (ownedDb) {
|
|
171
|
+
try { await ownedDb.close(); } catch { /* ignore */ }
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
for (const row of rows) {
|
|
176
|
+
if (!row.style_key) continue;
|
|
177
|
+
const existing = byKey.get(row.style_key);
|
|
178
|
+
byKey.set(row.style_key, existing ? mergeStyle(existing, row) : row);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
return {
|
|
182
|
+
styles: dedupeStyles([...byKey.values()]),
|
|
183
|
+
builtin: BUILTIN_STYLES.length,
|
|
184
|
+
database: rows.length,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function compatibilityLevel(style, genres) {
|
|
189
|
+
let score = 0;
|
|
190
|
+
for (const raw of genres) {
|
|
191
|
+
const genre = String(raw || '').trim();
|
|
192
|
+
if (!genre) continue;
|
|
193
|
+
for (const [key, level] of Object.entries(style.compatibility || {})) {
|
|
194
|
+
if (!key) continue;
|
|
195
|
+
if (genre.includes(key) || key.includes(genre)) {
|
|
196
|
+
if (level === 'native') score += 6;
|
|
197
|
+
else if (level === 'adaptable') score += 3;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
for (const tag of style.genre_tags || []) {
|
|
201
|
+
if (tag && (genre.includes(tag) || tag.includes(genre))) score += 4;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return score;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function parseExplicit(explicit) {
|
|
208
|
+
if (Array.isArray(explicit)) return explicit.map((v) => String(v || '').trim()).filter(Boolean);
|
|
209
|
+
return String(explicit || '')
|
|
210
|
+
.split(/[,,、]/)
|
|
211
|
+
.map((v) => v.trim())
|
|
212
|
+
.filter(Boolean);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* 选择本次风格。
|
|
217
|
+
*
|
|
218
|
+
* explicit:
|
|
219
|
+
* '' / 'auto' -> 自动按题材选 2-3 个
|
|
220
|
+
* 'none' -> 不使用账号风格
|
|
221
|
+
* 'suci,...' -> 手动指定 style_key
|
|
222
|
+
*/
|
|
223
|
+
export function selectStyles(styles, {
|
|
224
|
+
genres = [],
|
|
225
|
+
explicit = '',
|
|
226
|
+
limit = 3,
|
|
227
|
+
} = {}) {
|
|
228
|
+
const keys = parseExplicit(explicit);
|
|
229
|
+
const lower = keys.map((key) => key.toLowerCase());
|
|
230
|
+
if (lower.includes('none')) return [];
|
|
231
|
+
const all = Array.isArray(styles) ? styles : [];
|
|
232
|
+
const byKey = new Map(all.map((style) => [style.style_key.toLowerCase(), style]));
|
|
233
|
+
|
|
234
|
+
if (keys.length && !lower.includes('auto')) {
|
|
235
|
+
const selected = [];
|
|
236
|
+
const unknown = [];
|
|
237
|
+
for (const key of keys) {
|
|
238
|
+
const style = byKey.get(key.toLowerCase());
|
|
239
|
+
if (style) selected.push(style);
|
|
240
|
+
else unknown.push(key);
|
|
241
|
+
}
|
|
242
|
+
if (unknown.length) {
|
|
243
|
+
const available = all.map((style) => style.style_key).filter(Boolean).join('、');
|
|
244
|
+
throw new Error('未找到风格:' + unknown.join('、') + '\n可用风格:' + (available || '(暂无)'));
|
|
245
|
+
}
|
|
246
|
+
return selected.slice(0, Math.max(1, limit));
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const ranked = all
|
|
250
|
+
.filter((style) => SELECTABLE_STYLE_TYPES.has(style.style_type))
|
|
251
|
+
.map((style) => ({ style, score: compatibilityLevel(style, genres) }))
|
|
252
|
+
.filter((item) => item.score > 0)
|
|
253
|
+
.sort((a, b) => (b.score - a.score) || (b.style.confidence - a.style.confidence));
|
|
254
|
+
return ranked.slice(0, Math.max(1, limit)).map((item) => item.style);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export function stylesForAccount(styles, account) {
|
|
258
|
+
const name = String(account && (account.name || account.account_name) || '').trim();
|
|
259
|
+
const url = String(account && (account.url || account.account_url) || '').trim();
|
|
260
|
+
return (Array.isArray(styles) ? styles : []).filter((style) => {
|
|
261
|
+
if (url && (style.account_urls || []).includes(url)) return true;
|
|
262
|
+
if (name && (style.account_names || []).includes(name)) return true;
|
|
263
|
+
return false;
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export function styleExamples(style, limit = 3) {
|
|
268
|
+
const out = [];
|
|
269
|
+
for (const values of Object.values(style.cross_kind_examples || {})) {
|
|
270
|
+
for (const value of asArray(values)) {
|
|
271
|
+
if (value && !out.includes(value)) out.push(value);
|
|
272
|
+
if (out.length >= limit) return out;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
return out;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
export function styleIndexLines(styles, { limit = 20 } = {}) {
|
|
279
|
+
return (Array.isArray(styles) ? styles : [])
|
|
280
|
+
.filter((style) => SELECTABLE_STYLE_TYPES.has(style.style_type))
|
|
281
|
+
.slice(0, limit)
|
|
282
|
+
.map((style) => `- \`${style.style_key}\`(${style.style_name})|${(style.genre_tags || []).join('、') || '通用'}|${style.dna}`);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* 生成注入 prompt 的风格块。
|
|
287
|
+
* 只展开本次选中的风格;其余只给索引,避免上下文爆炸。
|
|
288
|
+
*/
|
|
289
|
+
export function stylePromptBlock(styles, selected, { genres = [] } = {}) {
|
|
290
|
+
const all = Array.isArray(styles) ? styles : [];
|
|
291
|
+
const picked = Array.isArray(selected) ? selected : [];
|
|
292
|
+
const lines = [
|
|
293
|
+
'## 风格锁定(最高优先级)',
|
|
294
|
+
'',
|
|
295
|
+
'风格是跨 kind 的不变量:kind 决定“写什么信息点”,风格决定“用什么方式写”。',
|
|
296
|
+
'如果下面的风格规则与题材命名体例冲突,以风格规则为准;题材只负责换词汇和禁用项。',
|
|
297
|
+
'',
|
|
298
|
+
'### 可用风格索引',
|
|
299
|
+
...styleIndexLines(all),
|
|
300
|
+
'',
|
|
301
|
+
];
|
|
302
|
+
if (!picked.length) {
|
|
303
|
+
lines.push('本次未选择账号风格,按通用规则生成。');
|
|
304
|
+
return lines.join('\n');
|
|
305
|
+
}
|
|
306
|
+
lines.push('### 本次选中的风格');
|
|
307
|
+
for (const style of picked) {
|
|
308
|
+
lines.push('');
|
|
309
|
+
lines.push(`#### \`${style.style_key}\`(${style.style_name})`);
|
|
310
|
+
lines.push('- 风格类型:' + style.style_type);
|
|
311
|
+
lines.push('- 适用题材:' + (style.genre_tags || []).join('、'));
|
|
312
|
+
lines.push('- DNA:' + style.dna);
|
|
313
|
+
const rules = style.naming_rules || {};
|
|
314
|
+
if (rules.length) lines.push('- 长度:' + (Array.isArray(rules.length) ? rules.length.join('–') + ' 字' : rules.length));
|
|
315
|
+
if (rules.syntax) lines.push('- 句式:' + asArray(rules.syntax).join(';'));
|
|
316
|
+
if (rules.suffixes) lines.push('- 可用后缀:' + (asArray(rules.suffixes).join('、') || '无固定后缀'));
|
|
317
|
+
if (rules.forbidden) lines.push('- 禁用:' + asArray(rules.forbidden).join('、'));
|
|
318
|
+
if (rules.tone) lines.push('- 语气:' + rules.tone);
|
|
319
|
+
const preferred = asArray(style.lexicon && style.lexicon.preferred);
|
|
320
|
+
const forbidden = asArray(style.lexicon && style.lexicon.forbidden);
|
|
321
|
+
if (preferred.length) lines.push('- 偏好意象:' + preferred.join('、'));
|
|
322
|
+
if (forbidden.length) lines.push('- 禁用意象:' + forbidden.join('、'));
|
|
323
|
+
lines.push('- 跨 kind 正例:');
|
|
324
|
+
for (const [kind, values] of Object.entries(style.cross_kind_examples || {})) {
|
|
325
|
+
const list = asArray(values).slice(0, 6);
|
|
326
|
+
if (list.length) lines.push(` - \`${kind}\`:${list.join('、')}`);
|
|
327
|
+
}
|
|
328
|
+
if (style.anti_examples && style.anti_examples.length) {
|
|
329
|
+
lines.push('- 反例(出现即废弃):' + style.anti_examples.slice(0, 12).join('、'));
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
lines.push('');
|
|
333
|
+
lines.push('本批题材:' + (genres.join('、') || '通用'));
|
|
334
|
+
lines.push('把选中风格的“核心语法”投射到本次题材和本批 kind 上;不要照抄正例,也不要退回通用仙气/古风形容词。');
|
|
335
|
+
return lines.join('\n');
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
export function styleSummaryText(styles) {
|
|
339
|
+
return (Array.isArray(styles) ? styles : [])
|
|
340
|
+
.map((style) => `${style.style_key}(${style.style_name})`)
|
|
341
|
+
.join('、');
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
export function styleBatchSummary(styles) {
|
|
345
|
+
return (Array.isArray(styles) ? styles : []).map((style) => {
|
|
346
|
+
const rules = style.naming_rules || {};
|
|
347
|
+
const bits = [
|
|
348
|
+
`- ${style.style_key}(${style.style_name}):${String(style.dna || '').replace(/[。;;]+$/u, '')}`,
|
|
349
|
+
];
|
|
350
|
+
if (rules.length) bits.push(`长度 ${Array.isArray(rules.length) ? rules.length.join('–') + ' 字' : rules.length}`);
|
|
351
|
+
if (rules.forbidden && rules.forbidden.length) bits.push('禁用 ' + rules.forbidden.join('、'));
|
|
352
|
+
return bits.join(';');
|
|
353
|
+
}).join('\n');
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* 把风格 patch 合并进数据库(同 style_key 做增量合并,不覆盖旧例子)。
|
|
358
|
+
* 只增/改 douyin_style,不碰 material、douyin_account、douyin_job。
|
|
359
|
+
*/
|
|
360
|
+
function accountKeyPrefix(account) {
|
|
361
|
+
const raw = String((account && (account.url || account.name)) || 'account')
|
|
362
|
+
.split('/')
|
|
363
|
+
.filter(Boolean)
|
|
364
|
+
.pop() || 'account';
|
|
365
|
+
return raw.replace(/[^A-Za-z0-9]/g, '').toLowerCase().slice(0, 24) || 'account';
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
export async function upsertStyleProfiles(db, profiles, { account = null } = {}) {
|
|
369
|
+
if (!db || !Array.isArray(profiles)) return [];
|
|
370
|
+
const saved = [];
|
|
371
|
+
for (const raw of profiles) {
|
|
372
|
+
if (!raw || !raw.style_key) continue;
|
|
373
|
+
let key = String(raw.style_key).trim();
|
|
374
|
+
if (!/^[a-z][a-z0-9_-]*$/i.test(key)) continue;
|
|
375
|
+
let existing = null;
|
|
376
|
+
// 内置风格已经有归属账号;别的账号复用同一个 key 时自动加账号前缀。
|
|
377
|
+
const builtin = BUILTIN_STYLES.find((style) => style.style_key === key);
|
|
378
|
+
if (builtin && account && account.name && !(builtin.account_names || []).includes(account.name)) {
|
|
379
|
+
key = accountKeyPrefix(account) + '_' + key;
|
|
380
|
+
}
|
|
381
|
+
try {
|
|
382
|
+
const result = await db.query('SELECT * FROM douyin_style WHERE style_key = $key LIMIT 1;', { key });
|
|
383
|
+
existing = Array.isArray(result) && Array.isArray(result[0]) ? result[0][0] : null;
|
|
384
|
+
} catch { /* table may not exist yet */ }
|
|
385
|
+
// 同 key 已被另一个账号占用时,加上账号前缀,避免跨账号覆盖。
|
|
386
|
+
if (existing && account && existing.account_url && account.url && existing.account_url !== account.url) {
|
|
387
|
+
key = accountKeyPrefix(account) + '_' + key;
|
|
388
|
+
try {
|
|
389
|
+
const result = await db.query('SELECT * FROM douyin_style WHERE style_key = $key LIMIT 1;', { key });
|
|
390
|
+
existing = Array.isArray(result) && Array.isArray(result[0]) ? result[0][0] : null;
|
|
391
|
+
} catch { existing = null; }
|
|
392
|
+
}
|
|
393
|
+
const base = existing ? normalizeStyle({ ...existing, origin: 'database' }) : null;
|
|
394
|
+
const patch = normalizeStyle({
|
|
395
|
+
...raw,
|
|
396
|
+
style_key: key,
|
|
397
|
+
account_url: raw.account_url || (account && account.url) || '',
|
|
398
|
+
account_name: raw.account_name || (account && account.name) || '',
|
|
399
|
+
origin: 'database',
|
|
400
|
+
}, 'database');
|
|
401
|
+
const merged = base ? mergeStyle(base, patch) : patch;
|
|
402
|
+
merged.style_key = key;
|
|
403
|
+
merged.version = Math.max(1, Number(base?.version || 0) + 1);
|
|
404
|
+
merged.source_works = Math.max(Number(base?.source_works || 0), Number(patch.source_works || 0));
|
|
405
|
+
merged.source_materials = Math.max(Number(base?.source_materials || 0), Number(patch.source_materials || 0));
|
|
406
|
+
merged.status = 'active';
|
|
407
|
+
const content = {
|
|
408
|
+
style_key: merged.style_key,
|
|
409
|
+
account_url: (account && account.url) || merged.account_urls[0] || '',
|
|
410
|
+
account_name: (account && account.name) || merged.account_names[0] || '',
|
|
411
|
+
style_name: merged.style_name,
|
|
412
|
+
style_type: merged.style_type,
|
|
413
|
+
genre_tags: merged.genre_tags,
|
|
414
|
+
dna: merged.dna,
|
|
415
|
+
naming_rules: merged.naming_rules,
|
|
416
|
+
lexicon: merged.lexicon,
|
|
417
|
+
cross_kind_examples: merged.cross_kind_examples,
|
|
418
|
+
anti_examples: merged.anti_examples,
|
|
419
|
+
compatibility: merged.compatibility,
|
|
420
|
+
confidence: merged.confidence,
|
|
421
|
+
source_works: merged.source_works,
|
|
422
|
+
source_materials: merged.source_materials,
|
|
423
|
+
version: merged.version,
|
|
424
|
+
status: merged.status,
|
|
425
|
+
profile_json: {
|
|
426
|
+
account_names: merged.account_names,
|
|
427
|
+
account_urls: merged.account_urls,
|
|
428
|
+
naming_rules: merged.naming_rules,
|
|
429
|
+
lexicon: merged.lexicon,
|
|
430
|
+
cross_kind_examples: merged.cross_kind_examples,
|
|
431
|
+
anti_examples: merged.anti_examples,
|
|
432
|
+
compatibility: merged.compatibility,
|
|
433
|
+
},
|
|
434
|
+
};
|
|
435
|
+
const record = db.upsert(new RecordId(STYLE_TABLE, key));
|
|
436
|
+
if (existing) await record.merge(content);
|
|
437
|
+
else await record.content(content);
|
|
438
|
+
saved.push(merged);
|
|
439
|
+
}
|
|
440
|
+
return saved;
|
|
441
|
+
}
|