forked from MikuLXK/MoRanJiangHu
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathImageGenerationSettings.tsx
More file actions
2059 lines (1952 loc) · 120 KB
/
Copy pathImageGenerationSettings.tsx
File metadata and controls
2059 lines (1952 loc) · 120 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, { useEffect, useMemo, useState } from 'react';
import type {
接口设置结构,
功能模型占位配置结构,
单接口配置结构,
画师串预设结构,
词组转化器提示词预设结构,
PNG画风预设结构,
文生图接口配置结构,
文生图后端类型,
文生图预设接口路径类型
} from '@/types';
import GameButton from '../../../ui/GameButton';
import ToggleSwitch from '../../../ui/ToggleSwitch';
import InlineSelect from '../../../ui/InlineSelect';
import { 规范化接口设置 } from '../../../../utils/apiConfig';
import { 自动场景横屏尺寸选项, 自动场景竖屏尺寸选项 } from '../../../../utils/imageSizeOptions';
import type { Props, 生图模型字段, 设置分页, 画师串适用页签, 词组预设页签 } from './types';
import {
初始化模型列表,
初始化加载状态,
基础页面选项,
文生图后端选项,
接口路径模式选项,
预设路径选项映射,
NovelAI模型建议,
NovelAI采样器选项,
NovelAI噪点表选项,
获取后端设置标签,
图片后端需要模型选择,
图片后端需要鉴权,
ComfyUI工作流占位提示,
页面容器样式,
卡片样式,
标签样式,
创建文生图配置模板,
创建空画师串预设,
创建空词组预设
} from './helpers';
const ImageGenerationSettings: React.FC<Props> = ({ settings, onSave }) => {
const [form, setForm] = useState<接口设置结构>(() => 规范化接口设置(settings));
const [selectedConfigId, setSelectedConfigId] = useState<string | null>(null);
const [selectedImageGenConfigId, setSelectedImageGenConfigId] = useState<string | null>(null);
const [newImageGenBackend, setNewImageGenBackend] = useState<文生图后端类型>('openai');
const [modelOptions, setModelOptions] = useState<Record<生图模型字段, string[]>>(初始化模型列表);
const [modelLoading, setModelLoading] = useState<Record<生图模型字段, boolean>>(初始化加载状态);
const [activePage, setActivePage] = useState<设置分页>('basic');
const [artistPresetScope, setArtistPresetScope] = useState<画师串适用页签>('npc');
const [transformerPresetScope, setTransformerPresetScope] = useState<词组预设页签>('nai');
const [message, setMessage] = useState('');
const [showSuccess, setShowSuccess] = useState(false);
const [testingConnection, setTestingConnection] = useState(false);
const [testResultModal, setTestResultModal] = useState<{ open: boolean; title: string; content: string; ok: boolean }>({ open: false, title: '', content: '', ok: false });
const artistImportRef = React.useRef<HTMLInputElement | null>(null);
const transformerImportRef = React.useRef<HTMLInputElement | null>(null);
const [workflowDialogOpen, setWorkflowDialogOpen] = useState(false);
const [workflowList, setWorkflowList] = useState<Array<{ path: string; name: string; category: string }>>([]);
const [workflowLoading, setWorkflowLoading] = useState(false);
const [workflowError, setWorkflowError] = useState('');
const [workflowFilter, setWorkflowFilter] = useState<string>('all');
useEffect(() => {
const normalized = 规范化接口设置(settings);
setForm(normalized);
setSelectedConfigId(normalized.activeConfigId || normalized.configs[0]?.id || null);
const imgConfigs = normalized.功能模型占位.文生图配置列表 || [];
setSelectedImageGenConfigId(normalized.功能模型占位.当前文生图配置ID || imgConfigs[0]?.id || null);
setModelOptions(初始化模型列表());
setModelLoading(初始化加载状态());
setActivePage('basic');
setArtistPresetScope('npc');
setTransformerPresetScope('nai');
}, [settings]);
const activeConfig = useMemo<单接口配置结构 | null>(() => {
if (!form.configs.length) return null;
return form.configs.find((cfg) => cfg.id === selectedConfigId) || form.configs[0] || null;
}, [form.configs, selectedConfigId]);
const 文生图配置列表 = form.功能模型占位.文生图配置列表 || [];
const 当前文生图配置 = useMemo<文生图接口配置结构 | null>(() => {
if (!文生图配置列表.length) return null;
return 文生图配置列表.find((cfg) => cfg.id === selectedImageGenConfigId) || 文生图配置列表[0] || null;
}, [文生图配置列表, selectedImageGenConfigId]);
const updateImageGenConfig = (patch: Partial<文生图接口配置结构>) => {
if (!当前文生图配置) return;
setForm((prev) => ({
...prev,
功能模型占位: {
...prev.功能模型占位,
文生图配置列表: prev.功能模型占位.文生图配置列表.map((cfg) =>
cfg.id === 当前文生图配置.id ? { ...cfg, ...patch, updatedAt: Date.now() } : cfg
)
}
}));
};
const handleCreateImageGenConfig = () => {
const created = 创建文生图配置模板(newImageGenBackend);
setForm((prev) => ({
...prev,
功能模型占位: {
...prev.功能模型占位,
文生图配置列表: [...(prev.功能模型占位.文生图配置列表 || []), created],
当前文生图配置ID: created.id
}
}));
setSelectedImageGenConfigId(created.id);
setMessage(`已新增 ${文生图后端选项.find(b => b.value === newImageGenBackend)?.label || newImageGenBackend} 配置,请填写后保存。`);
};
const handleDeleteImageGenConfig = () => {
if (!当前文生图配置) return;
setForm((prev) => {
const remaining = (prev.功能模型占位.文生图配置列表 || []).filter((cfg) => cfg.id !== 当前文生图配置.id);
const fallbackId = remaining[0]?.id || null;
setSelectedImageGenConfigId(fallbackId);
return {
...prev,
功能模型占位: {
...prev.功能模型占位,
文生图配置列表: remaining,
当前文生图配置ID: fallbackId
}
};
});
setMessage('配置已删除。');
};
const handleLoadWorkflowFromCNB = async () => {
setWorkflowDialogOpen(true);
setWorkflowLoading(true);
setWorkflowError('');
setWorkflowFilter('all');
try {
const res = await fetch('/api/comfyui-workflows?action=list');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
setWorkflowList(data.workflows || []);
} catch (err: unknown) {
setWorkflowError(`加载工作流列表失败: ${err instanceof Error ? err.message : String(err)}`);
setWorkflowList([]);
} finally {
setWorkflowLoading(false);
}
};
const handleSelectWorkflow = async (workflowPath: string, workflowName: string) => {
setWorkflowLoading(true);
setWorkflowError('');
try {
const res = await fetch(`/api/comfyui-workflows?action=get&file=${encodeURIComponent(workflowPath)}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
if (data.workflow) {
updateImageGenConfig({ ComfyUI工作流JSON: JSON.stringify(data.workflow, null, 2) });
setWorkflowDialogOpen(false);
setMessage(`已加载工作流: ${workflowName}`);
} else {
setWorkflowError('获取工作流失败: 返回为空');
}
} catch (err: unknown) {
setWorkflowError(`加载工作流失败: ${err instanceof Error ? err.message : String(err)}`);
} finally {
setWorkflowLoading(false);
}
};
const 主剧情解析模型 = useMemo(() => {
return (activeConfig?.model || '').trim() || (form.功能模型占位.主剧情使用模型 || '').trim();
}, [activeConfig?.model, form.功能模型占位.主剧情使用模型]);
const 当前后端 = form.功能模型占位.文生图后端类型;
const 当前场景后端 = form.功能模型占位.场景生图独立接口启用
? form.功能模型占位.场景生图后端类型
: 当前后端;
const 当前预设路径选项 = 预设路径选项映射[当前后端];
const 当前预设路径值集合 = new Set(当前预设路径选项.map((item) => item.value));
const 当前预设路径 = 当前预设路径值集合.has(form.功能模型占位.文生图预设接口路径)
? form.功能模型占位.文生图预设接口路径
: 当前预设路径选项[0]?.value || 'openai_images';
const 文生图模型选项 = Array.from(new Set(
(当前后端 === 'novelai' ? NovelAI模型建议 : [])
.concat(modelOptions.文生图模型使用模型, form.功能模型占位.文生图模型使用模型)
.map((item) => (item || '').trim())
.filter(Boolean)
));
const 词组转化器模型选项 = Array.from(new Set(
modelOptions.词组转化器使用模型
.concat(form.功能模型占位.词组转化器使用模型, 主剧情解析模型)
.map((item) => (item || '').trim())
.filter(Boolean)
));
const PNG提炼模型选项 = Array.from(new Set(
modelOptions.PNG提炼使用模型
.concat(form.功能模型占位.PNG提炼使用模型, 主剧情解析模型)
.map((item) => (item || '').trim())
.filter(Boolean)
));
const 场景文生图模型选项 = Array.from(new Set(
(当前场景后端 === 'novelai' ? NovelAI模型建议 : [])
.concat(modelOptions.场景生图模型使用模型, form.功能模型占位.场景生图模型使用模型, form.功能模型占位.文生图模型使用模型)
.map((item) => (item || '').trim())
.filter(Boolean)
));
const 可见页面 = useMemo(() => 基础页面选项.map((item) => (
item.value === 'provider'
? { ...item, label: 获取后端设置标签(当前后端) }
: item
)), [当前后端]);
const 是否强制启用词组转化器 = 当前后端 === 'novelai';
const artistPresets = useMemo(
() => (Array.isArray(form.功能模型占位.画师串预设列表) ? form.功能模型占位.画师串预设列表 : [])
.filter((item) => item && typeof item.id === 'string' && !item.id.startsWith('png_artist_')),
[form.功能模型占位.画师串预设列表]
);
const scopedArtistPresets = useMemo(() => artistPresets.filter((item) => item.适用范围 === artistPresetScope || item.适用范围 === 'all'), [artistPresets, artistPresetScope]);
const currentArtistPresetId = artistPresetScope === 'scene'
? form.功能模型占位.当前场景画师串预设ID
: form.功能模型占位.当前NPC画师串预设ID;
const pngStylePresets = useMemo<PNG画风预设结构[]>(
() => Array.isArray(form.功能模型占位.PNG画风预设列表) ? form.功能模型占位.PNG画风预设列表 : [],
[form.功能模型占位.PNG画风预设列表]
);
const currentAutoPngPresetId = artistPresetScope === 'scene'
? form.功能模型占位.当前场景PNG画风预设ID
: form.功能模型占位.当前NPCPNG画风预设ID;
const selectedArtistPreset = scopedArtistPresets.find((item) => item.id === currentArtistPresetId)
|| scopedArtistPresets[0]
|| null;
const transformerPresets = useMemo(() => Array.isArray(form.功能模型占位.词组转化器提示词预设列表) ? form.功能模型占位.词组转化器提示词预设列表 : [], [form.功能模型占位.词组转化器提示词预设列表]);
const scopedTransformerPresets = useMemo(() => transformerPresets.filter((item) => item.类型 === transformerPresetScope), [transformerPresets, transformerPresetScope]);
const currentTransformerPresetId = transformerPresetScope === 'nai'
? form.功能模型占位.当前NAI词组转化器提示词预设ID
: transformerPresetScope === 'scene'
? form.功能模型占位.当前场景词组转化器提示词预设ID
: form.功能模型占位.当前NPC词组转化器提示词预设ID;
const selectedTransformerPreset = scopedTransformerPresets.find((item) => item.id === currentTransformerPresetId)
|| scopedTransformerPresets[0]
|| null;
const updatePlaceholder = <K extends keyof 功能模型占位配置结构>(key: K, value: 功能模型占位配置结构[K]) => {
setForm((prev) => ({
...prev,
功能模型占位: {
...prev.功能模型占位,
[key]: value
}
}));
};
const 更新当前画师串预设ID = (scope: 画师串适用页签, presetId: string) => {
updatePlaceholder(scope === 'scene' ? '当前场景画师串预设ID' : '当前NPC画师串预设ID', presetId);
};
const 更新当前PNG预设ID = (scope: 画师串适用页签, presetId: string) => {
updatePlaceholder(scope === 'scene' ? '当前场景PNG画风预设ID' : '当前NPCPNG画风预设ID', presetId);
};
const 更新当前词组预设ID = (scope: 词组预设页签, presetId: string) => {
if (scope === 'nai') {
updatePlaceholder('当前NAI词组转化器提示词预设ID', presetId);
return;
}
if (scope === 'scene') {
updatePlaceholder('当前场景词组转化器提示词预设ID', presetId);
return;
}
updatePlaceholder('当前NPC词组转化器提示词预设ID', presetId);
};
const updateArtistPreset = (presetId: string, updater: (preset: 画师串预设结构) => 画师串预设结构) => {
setForm((prev) => ({
...prev,
功能模型占位: {
...prev.功能模型占位,
画师串预设列表: (Array.isArray(prev.功能模型占位.画师串预设列表) ? prev.功能模型占位.画师串预设列表 : []).map((preset) => (
preset.id === presetId ? updater(preset) : preset
))
}
}));
};
const updateTransformerPreset = (presetId: string, updater: (preset: 词组转化器提示词预设结构) => 词组转化器提示词预设结构) => {
setForm((prev) => ({
...prev,
功能模型占位: {
...prev.功能模型占位,
词组转化器提示词预设列表: (Array.isArray(prev.功能模型占位.词组转化器提示词预设列表) ? prev.功能模型占位.词组转化器提示词预设列表 : []).map((preset) => (
preset.id === presetId ? updater(preset) : preset
))
}
}));
};
const handleAddArtistPreset = () => {
const nextPreset = 创建空画师串预设(artistPresetScope);
setForm((prev) => ({
...prev,
功能模型占位: {
...prev.功能模型占位,
画师串预设列表: [...(Array.isArray(prev.功能模型占位.画师串预设列表) ? prev.功能模型占位.画师串预设列表 : []), nextPreset],
当前NPC画师串预设ID: artistPresetScope === 'npc' ? nextPreset.id : prev.功能模型占位.当前NPC画师串预设ID,
当前场景画师串预设ID: artistPresetScope === 'scene' ? nextPreset.id : prev.功能模型占位.当前场景画师串预设ID
}
}));
};
const handleDeleteArtistPreset = () => {
if (!selectedArtistPreset) return;
const remaining = artistPresets.filter((item) => item.id !== selectedArtistPreset.id);
const nextNpcId = form.功能模型占位.当前NPC画师串预设ID === selectedArtistPreset.id
? (remaining.find((item) => item.适用范围 === 'npc' || item.适用范围 === 'all')?.id || '')
: form.功能模型占位.当前NPC画师串预设ID;
const nextSceneId = form.功能模型占位.当前场景画师串预设ID === selectedArtistPreset.id
? (remaining.find((item) => item.适用范围 === 'scene' || item.适用范围 === 'all')?.id || '')
: form.功能模型占位.当前场景画师串预设ID;
setForm((prev) => ({
...prev,
功能模型占位: {
...prev.功能模型占位,
画师串预设列表: remaining,
当前NPC画师串预设ID: nextNpcId,
当前场景画师串预设ID: nextSceneId
}
}));
};
const handleAddTransformerPreset = () => {
const nextPreset = 创建空词组预设(transformerPresetScope);
setForm((prev) => ({
...prev,
功能模型占位: {
...prev.功能模型占位,
词组转化器提示词预设列表: [...(Array.isArray(prev.功能模型占位.词组转化器提示词预设列表) ? prev.功能模型占位.词组转化器提示词预设列表 : []), nextPreset],
当前NAI词组转化器提示词预设ID: transformerPresetScope === 'nai' ? nextPreset.id : prev.功能模型占位.当前NAI词组转化器提示词预设ID,
当前NPC词组转化器提示词预设ID: transformerPresetScope === 'npc' ? nextPreset.id : prev.功能模型占位.当前NPC词组转化器提示词预设ID,
当前场景词组转化器提示词预设ID: transformerPresetScope === 'scene' ? nextPreset.id : prev.功能模型占位.当前场景词组转化器提示词预设ID
}
}));
};
const handleDeleteTransformerPreset = () => {
if (!selectedTransformerPreset) return;
const remaining = transformerPresets.filter((item) => item.id !== selectedTransformerPreset.id);
const nextByScope = (scope: 词组预设页签) => remaining.find((item) => item.类型 === scope)?.id || '';
setForm((prev) => ({
...prev,
功能模型占位: {
...prev.功能模型占位,
词组转化器提示词预设列表: remaining,
当前NAI词组转化器提示词预设ID: prev.功能模型占位.当前NAI词组转化器提示词预设ID === selectedTransformerPreset.id ? nextByScope('nai') : prev.功能模型占位.当前NAI词组转化器提示词预设ID,
当前NPC词组转化器提示词预设ID: prev.功能模型占位.当前NPC词组转化器提示词预设ID === selectedTransformerPreset.id ? nextByScope('npc') : prev.功能模型占位.当前NPC词组转化器提示词预设ID,
当前场景词组转化器提示词预设ID: prev.功能模型占位.当前场景词组转化器提示词预设ID === selectedTransformerPreset.id ? nextByScope('scene') : prev.功能模型占位.当前场景词组转化器提示词预设ID
}
}));
};
const 导出JSON文件 = (filename: string, payload: unknown) => {
const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json;charset=utf-8' });
const url = URL.createObjectURL(blob);
const anchor = document.createElement('a');
anchor.href = url;
anchor.download = filename;
anchor.click();
URL.revokeObjectURL(url);
};
const 读取JSON文件 = async (file: File): Promise<any> => {
const text = await file.text();
return JSON.parse(text);
};
const handleBackendChange = (value: 功能模型占位配置结构['文生图后端类型']) => {
const fallbackPreset = 预设路径选项映射[value][0]?.value || 'openai_images';
setForm((prev) => ({
...prev,
功能模型占位: {
...prev.功能模型占位,
文生图后端类型: value,
文生图预设接口路径: fallbackPreset,
NPC生图使用词组转化器: value === 'novelai' ? true : prev.功能模型占位.NPC生图使用词组转化器,
文生图模型API地址: value === 'novelai' && !prev.功能模型占位.文生图模型API地址.trim()
? 'https://image.novelai.net'
: prev.功能模型占位.文生图模型API地址,
文生图OpenAI自定义格式: value === 'openai' ? prev.功能模型占位.文生图OpenAI自定义格式 : false,
文生图响应格式: value === 'openai' ? prev.功能模型占位.文生图响应格式 : 'url'
}
}));
if (activePage === 'provider') setActivePage('provider');
};
const handleToggleTransformerIndependent = (checked: boolean) => {
setForm((prev) => {
const currentModel = (prev.功能模型占位.词组转化器使用模型 || '').trim();
return {
...prev,
功能模型占位: {
...prev.功能模型占位,
词组转化器启用独立模型: checked,
词组转化器使用模型: checked ? (currentModel || 主剧情解析模型 || '') : ''
}
};
});
};
const handleToggleSceneMode = (checked: boolean) => {
setForm((prev) => {
const currentModel = (prev.功能模型占位.词组转化器使用模型 || '').trim();
return {
...prev,
功能模型占位: {
...prev.功能模型占位,
场景生图启用: checked,
词组转化器启用独立模型: checked ? true : prev.功能模型占位.词组转化器启用独立模型,
词组转化器使用模型: checked
? (currentModel || 主剧情解析模型 || '')
: prev.功能模型占位.词组转化器使用模型
}
};
});
};
const handleToggleSceneIndependentImageApi = (checked: boolean) => {
setForm((prev) => ({
...prev,
功能模型占位: {
...prev.功能模型占位,
场景生图独立接口启用: checked,
场景生图使用配置ID: checked ? prev.功能模型占位.场景生图使用配置ID : null,
场景生图后端类型: checked
? prev.功能模型占位.场景生图后端类型
: prev.功能模型占位.场景生图后端类型,
场景生图模型使用模型: checked
? ((prev.功能模型占位.场景生图模型使用模型 || '').trim() || (prev.功能模型占位.文生图模型使用模型 || '').trim())
: prev.功能模型占位.场景生图模型使用模型,
场景生图模型API地址: checked
? ((prev.功能模型占位.场景生图模型API地址 || '').trim() || (prev.功能模型占位.文生图模型API地址 || '').trim())
: prev.功能模型占位.场景生图模型API地址,
场景生图模型API密钥: checked
? ((prev.功能模型占位.场景生图模型API密钥 || '').trim() || (prev.功能模型占位.文生图模型API密钥 || '').trim())
: prev.功能模型占位.场景生图模型API密钥
}
}));
};
const fetchModelsFromCurrentConfig = async (key: 生图模型字段): Promise<string[] | null> => {
const feature = form.功能模型占位;
const isProviderTab = key === '文生图模型使用模型' && !feature.场景生图独立接口启用;
const providerConfig = isProviderTab ? 当前文生图配置 : null;
const sceneBackend = feature.场景生图独立接口启用 ? feature.场景生图后端类型 : feature.文生图后端类型;
const targetBackend = key === '文生图模型使用模型'
? (isProviderTab && providerConfig ? providerConfig.后端类型 : feature.文生图后端类型)
: key === '场景生图模型使用模型'
? sceneBackend
: feature.文生图后端类型;
const customBaseUrl = key === '文生图模型使用模型'
? isProviderTab
? (providerConfig?.API地址 || '').trim()
: (feature.文生图模型API地址 || '').trim()
: key === '场景生图模型使用模型'
? ((feature.场景生图独立接口启用 ? feature.场景生图模型API地址 : feature.文生图模型API地址) || '').trim()
: key === 'PNG提炼使用模型'
? ((feature.PNG提炼启用独立模型 ? feature.PNG提炼API地址 : '') || '').trim()
: ((feature.词组转化器启用独立模型 ? feature.词组转化器API地址 : '') || '').trim();
const customApiKey = key === '文生图模型使用模型'
? isProviderTab
? (providerConfig?.API密钥 || '').trim()
: (feature.文生图模型API密钥 || '').trim()
: key === '场景生图模型使用模型'
? ((feature.场景生图独立接口启用 ? feature.场景生图模型API密钥 : feature.文生图模型API密钥) || '').trim()
: key === 'PNG提炼使用模型'
? ((feature.PNG提炼启用独立模型 ? feature.PNG提炼API密钥 : '') || '').trim()
: ((feature.词组转化器启用独立模型 ? feature.词组转化器API密钥 : '') || '').trim();
const canReuseMainConnection = key !== '场景生图模型使用模型' || !feature.场景生图独立接口启用 || sceneBackend === feature.文生图后端类型;
const resolvedBaseUrl = customBaseUrl || (canReuseMainConnection ? (activeConfig?.baseUrl || '').trim() : '');
const resolvedApiKey = customApiKey || (canReuseMainConnection ? (activeConfig?.apiKey || '').trim() : '');
const targetNeedsModel = key === '词组转化器使用模型' || key === 'PNG提炼使用模型'
? true
: 图片后端需要模型选择(targetBackend);
const targetNeedsAuth = key === '词组转化器使用模型' || key === 'PNG提炼使用模型'
? true
: 图片后端需要鉴权(targetBackend);
if (!targetNeedsModel) {
setMessage(`${文生图后端选项.find((item) => item.value === targetBackend)?.label || '当前后端'}不需要模型选择,也不提供模型列表。`);
return null;
}
if (!resolvedBaseUrl || (targetNeedsAuth && !resolvedApiKey)) {
setMessage(key === 'PNG提炼使用模型'
? '请先填写 PNG 提炼 API 地址与 API Key。'
: (targetBackend === 'novelai' ? '请先填写 API 地址与 Persistent API Token。' : '请先填写 API 地址与 API Key。'));
return null;
}
try {
if (targetBackend === 'novelai' && (key === '文生图模型使用模型' || key === '场景生图模型使用模型')) return NovelAI模型建议;
const base = resolvedBaseUrl.replace(/\/+$/, '');
const normalized = base.replace(/\/v1$/i, '');
const candidateUrls = Array.from(new Set([
`${normalized}/v1/models`,
`${normalized}/models`,
`${base}/models`
]));
for (const url of candidateUrls) {
const res = await fetch(url, {
headers: targetNeedsAuth ? { Authorization: `Bearer ${resolvedApiKey}` } : undefined
});
if (!res.ok) continue;
const data = await res.json();
if (data && Array.isArray(data.data)) {
return data.data.map((m: any) => m?.id).filter(Boolean);
}
}
setMessage(`获取模型列表失败:${resolvedBaseUrl}`);
return null;
} catch (e: any) {
setMessage(`获取模型列表失败:${e.message}`);
return null;
}
};
const handleFetchModels = async (key: 生图模型字段, label: string) => {
setModelLoading((prev) => ({ ...prev, [key]: true }));
setMessage('');
const result = await fetchModelsFromCurrentConfig(key);
if (result) {
setModelOptions((prev) => ({ ...prev, [key]: result }));
setMessage(`${label}获取成功`);
}
setModelLoading((prev) => ({ ...prev, [key]: false }));
};
const handleTestImageConnection = async (config: 文生图接口配置结构) => {
const backendType = config.后端类型;
const isCnbMode = backendType === 'comfyui' && form.功能模型占位.comfyui地址模式 === 'cnb';
const resolvedBaseUrl = isCnbMode
? (form.功能模型占位.cnbComfyui地址?.trim() || '')
: (config.API地址?.trim() || '');
const hasBaseUrl = Boolean(resolvedBaseUrl);
const needsApiKey = backendType === 'openai' || backendType === 'grok' || backendType === 'novelai';
const needsModel = backendType === 'openai' || backendType === 'grok' || backendType === 'novelai';
const needsWorkflow = backendType === 'comfyui';
const missingChecks: string[] = [];
if (!hasBaseUrl) missingChecks.push(isCnbMode ? 'CNB ComfyUI 地址' : 'API 地址');
if (needsApiKey && !config.API密钥?.trim()) missingChecks.push('API 密钥');
if (needsModel && !config.模型?.trim()) missingChecks.push('模型名称');
if (needsWorkflow && !config.ComfyUI工作流JSON?.trim()) missingChecks.push('ComfyUI 工作流 JSON');
if (missingChecks.length > 0) {
setMessage(`请先填写: ${missingChecks.join('、')}`);
return;
}
setMessage('');
setTestingConnection(true);
try {
const imageAIService = await import('../../../../services/ai/image');
const result = await imageAIService.testImageConnection({
id: config.id,
名称: config.名称,
供应商: backendType === 'grok' ? 'grok' : 'openai',
baseUrl: resolvedBaseUrl,
apiKey: config.API密钥?.trim() || '',
model: config.模型?.trim() || '',
图片后端类型: backendType,
图片接口路径: config.接口路径模式 === 'custom' ? config.自定义接口路径 : undefined,
图片接口路径模式: config.接口路径模式,
图片响应格式: config.响应格式,
图片走OpenAI自定义格式: config.OpenAI自定义格式 === true,
ComfyUI工作流JSON: config.ComfyUI工作流JSON
});
const backendLabel = 文生图后端选项.find((o) => o.value === result.backendType)?.label || result.backendType;
const addressLabel = isCnbMode ? `CNB 地址: ${form.功能模型占位.cnbComfyui地址}` : `API 地址: ${config.API地址}`;
const meta = [
`配置: ${config.名称 || config.id}`,
`后端: ${backendLabel}`,
addressLabel,
'',
'---',
'',
result.detail
].join('\n');
setTestResultModal({
open: true,
title: result.ok ? '连接测试成功' : '连接测试失败',
content: meta,
ok: result.ok
});
} catch (e: any) {
setTestResultModal({
open: true,
title: '连接测试失败',
content: String(e?.message || '未知错误'),
ok: false
});
} finally {
setTestingConnection(false);
}
};
const handleExportArtistPresets = () => {
导出JSON文件('artist-presets.json', {
version: 1,
type: 'artist_prompt_presets',
presets: artistPresets
});
setMessage('画师串预设已导出。');
};
const handleExportTransformerPresets = () => {
导出JSON文件('transformer-presets.json', {
version: 1,
type: 'transformer_prompt_presets',
presets: transformerPresets
});
setMessage('词组转化器预设已导出。');
};
const handleImportArtistPresets = async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
try {
const parsed = await 读取JSON文件(file);
const presets = Array.isArray(parsed?.presets) ? parsed.presets : [];
const normalized = 规范化接口设置({
...form,
功能模型占位: {
...form.功能模型占位,
画师串预设列表: presets
}
});
setForm(normalized);
setMessage(`已导入 ${normalized.功能模型占位.画师串预设列表.length} 条画师串预设。`);
} catch (error: any) {
setMessage(`导入画师串预设失败:${error?.message || '文件格式错误'}`);
} finally {
event.target.value = '';
}
};
const handleImportTransformerPresets = async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
try {
const parsed = await 读取JSON文件(file);
const presets = Array.isArray(parsed?.presets) ? parsed.presets : [];
const normalized = 规范化接口设置({
...form,
功能模型占位: {
...form.功能模型占位,
词组转化器提示词预设列表: presets
}
});
setForm(normalized);
setMessage(`已导入 ${normalized.功能模型占位.词组转化器提示词预设列表.length} 条词组转化器预设。`);
} catch (error: any) {
setMessage(`导入词组转化器预设失败:${error?.message || '文件格式错误'}`);
} finally {
event.target.value = '';
}
};
const handleSave = () => {
const normalized = 规范化接口设置({
...form,
activeConfigId: selectedConfigId || form.activeConfigId,
功能模型占位: {
...form.功能模型占位,
词组转化器提示词: '',
NPC生图使用词组转化器: 当前后端 === 'novelai' ? true : form.功能模型占位.NPC生图使用词组转化器
}
});
onSave(normalized);
setForm(normalized);
setSelectedConfigId(normalized.activeConfigId || normalized.configs[0]?.id || null);
setShowSuccess(true);
setTimeout(() => setShowSuccess(false), 2000);
};
const renderBasicPage = () => (
<div className={页面容器样式}>
<div className="grid gap-4 lg:grid-cols-[1.1fr_0.9fr]">
<div className={卡片样式}>
<div className="flex items-center justify-between gap-3">
<div>
<div className="text-base font-bold text-fuchsia-200">文生图总开关</div>
</div>
<ToggleSwitch
checked={form.功能模型占位.文生图功能启用}
onChange={(next) => updatePlaceholder('文生图功能启用', next)}
ariaLabel="切换文生图总开关"
/>
</div>
</div>
<div className="rounded-xl border border-emerald-500/20 bg-emerald-950/10 p-4">
<div className="text-base font-bold text-emerald-200">当前后端</div>
<div className="mt-2 text-xl font-serif text-white">
{当前文生图配置 ? 文生图后端选项.find((item) => item.value === 当前文生图配置.后端类型)?.label : '请在接口设置中配置'}
</div>
</div>
</div>
</div>
);
const renderProviderPage = () => {
if (!当前文生图配置) {
return (
<div className={页面容器样式}>
<div className="rounded-xl border border-white/10 bg-black/20 p-8 text-center">
<div className="mb-4 text-lg font-bold text-fuchsia-200">暂无文生图配置</div>
<div className="mb-6 text-sm text-gray-400">请新建一个配置以开始使用文生图功能</div>
<div className="flex flex-wrap items-center justify-center gap-3">
<InlineSelect
value={newImageGenBackend}
options={文生图后端选项}
onChange={(value) => setNewImageGenBackend(value as 文生图后端类型)}
buttonClassName="bg-black/50 border-gray-600 py-2.5"
/>
<GameButton onClick={handleCreateImageGenConfig} variant="primary">
新建配置
</GameButton>
</div>
</div>
</div>
);
}
const 当前配置后端 = 当前文生图配置.后端类型;
const 当前配置预设路径选项 = 预设路径选项映射[当前配置后端];
return (
<div className={页面容器样式}>
<div className="mb-5 flex flex-wrap items-center gap-3 rounded-xl border border-fuchsia-500/20 bg-fuchsia-950/10 p-4">
<div className="flex flex-1 items-center gap-2">
<span className="text-sm text-fuchsia-200">当前配置:</span>
<InlineSelect
value={selectedImageGenConfigId || ''}
options={文生图配置列表.map((cfg) => ({ value: cfg.id, label: cfg.名称 }))}
onChange={(id) => {
setSelectedImageGenConfigId(id);
setForm((prev) => ({
...prev,
功能模型占位: {
...prev.功能模型占位,
当前文生图配置ID: id
}
}));
}}
buttonClassName="bg-black/50 border-gray-600 py-1.5 text-sm min-w-[140px]"
placeholder="选择配置"
/>
</div>
<div className="flex items-center gap-2">
<InlineSelect
value={newImageGenBackend}
options={文生图后端选项}
onChange={(value) => setNewImageGenBackend(value as 文生图后端类型)}
buttonClassName="bg-black/50 border-gray-600 py-1.5 text-sm"
/>
<GameButton onClick={handleCreateImageGenConfig} variant="secondary" className="text-xs px-3 py-1.5">
+ 新建
</GameButton>
<button
type="button"
onClick={handleDeleteImageGenConfig}
disabled={文生图配置列表.length <= 1}
className="rounded-lg border border-red-500/30 bg-red-950/20 px-3 py-1.5 text-xs text-red-200 disabled:opacity-40"
>
删除
</button>
</div>
</div>
<div className="space-y-2">
<label className={标签样式}>配置名称</label>
<input
type="text"
value={当前文生图配置.名称}
onChange={(e) => updateImageGenConfig({ 名称: e.target.value })}
className="w-full rounded-md border-2 border-transparent bg-black/50 p-3 text-white outline-none transition-all focus:border-fuchsia-400"
/>
</div>
<div className={卡片样式}>
<div className="grid gap-4 md:grid-cols-[1fr_auto]">
<div className="space-y-2">
<label className={标签样式}>后端类型</label>
<InlineSelect
value={当前配置后端}
options={文生图后端选项}
onChange={(value) => updateImageGenConfig({ 后端类型: value as 文生图后端类型 })}
buttonClassName="bg-black/50 border-gray-600 py-2.5"
/>
</div>
<div className="rounded-xl border border-fuchsia-500/20 bg-fuchsia-950/10 px-4 py-3 text-sm text-white">
{文生图后端选项.find((item) => item.value === 当前配置后端)?.label}
</div>
</div>
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<label className={标签样式}>API 地址</label>
<input
type="text"
value={当前文生图配置.API地址}
onChange={(e) => updateImageGenConfig({ API地址: e.target.value })}
placeholder={当前配置后端 === 'novelai'
? 'https://image.novelai.net'
: 当前配置后端 === 'sd_webui'
? '例如:http://127.0.0.1:7860'
: 当前配置后端 === 'comfyui'
? '例如:http://127.0.0.1:8188'
: 'https://api.openai.com/v1'}
className="w-full rounded-md border-2 border-transparent bg-black/50 p-3 text-white outline-none transition-all focus:border-fuchsia-400"
/>
</div>
<div className="space-y-2">
<label className={标签样式}>{当前配置后端 === 'novelai' ? 'Persistent API Token' : 'API Key'}</label>
<input
type="password"
value={当前文生图配置.API密钥}
onChange={(e) => updateImageGenConfig({ API密钥: e.target.value })}
placeholder={当前配置后端 === 'novelai'
? '在 NovelAI 账户设置中生成 Persistent API Token'
: 当前配置后端 === 'sd_webui' || 当前配置后端 === 'comfyui'
? '可留空;默认不会发送 Authorization'
: '留空则回退当前接口配置'}
className="w-full rounded-md border-2 border-transparent bg-black/50 p-3 text-white outline-none transition-all focus:border-fuchsia-400"
/>
</div>
</div>
</div>
<div className={卡片样式}>
{图片后端需要模型选择(当前配置后端) ? (
<>
<div className="flex flex-col gap-3 md:flex-row md:items-end">
<div className="flex-1 space-y-2">
<label className={标签样式}>模型名称</label>
<InlineSelect
value={当前文生图配置.模型}
onChange={(model) => updateImageGenConfig({ 模型: model })}
options={文生图模型选项.map((model) => ({ value: model, label: model }))}
placeholder="请选择或输入模型名"
buttonClassName="bg-black/50 border-gray-600 py-2.5"
panelClassName="max-w-full"
/>
</div>
<GameButton
onClick={() => handleFetchModels('文生图模型使用模型', '文生图模型列表')}
variant="secondary"
className="px-4 py-2 text-xs md:min-w-[96px]"
disabled={modelLoading.文生图模型使用模型}
>
{modelLoading.文生图模型使用模型 ? '...' : '获取列表'}
</GameButton>
</div>
<input
type="text"
value={当前文生图配置.模型}
onChange={(e) => updateImageGenConfig({ 模型: e.target.value })}
placeholder="例如:gpt-image-1 / nai-diffusion-4-5-full"
className="w-full rounded-md border-2 border-transparent bg-black/50 p-3 text-white outline-none transition-all focus:border-fuchsia-400"
/>
</>
) : (
<div className="rounded-xl border border-sky-500/20 bg-sky-950/10 px-4 py-3 text-sm text-sky-100">
当前后端直接调用固定生图接口,不需要选择模型名称。
</div>
)}
</div>
<div className={卡片样式}>
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<label className={标签样式}>接口路径模式</label>
<InlineSelect
value={当前文生图配置.接口路径模式}
onChange={(value) => updateImageGenConfig({ 接口路径模式: value as 'preset' | 'custom' })}
options={接口路径模式选项}
buttonClassName="bg-black/50 border-gray-600 py-2.5"
/>
</div>
</div>
{当前文生图配置.接口路径模式 === 'preset' ? (
<div className="space-y-2">
<label className={标签样式}>预设路径</label>
<InlineSelect
value={当前文生图配置.预设接口路径}
onChange={(value) => updateImageGenConfig({ 预设接口路径: value as 文生图预设接口路径类型 })}
options={当前配置预设路径选项.map((item) => ({ value: item.value, label: item.label }))}
buttonClassName="bg-black/50 border-gray-600 py-2.5"
/>
</div>
) : (
<div className="space-y-2">
<label className={标签样式}>自定义接口路径</label>
<input
type="text"
value={当前文生图配置.自定义接口路径}
onChange={(e) => updateImageGenConfig({ 自定义接口路径: e.target.value })}
placeholder={当前配置后端 === 'novelai'
? '/ai/generate-image'
: 当前配置后端 === 'sd_webui'
? '/sdapi/v1/txt2img'
: 当前配置后端 === 'comfyui'
? '/prompt'
: '/v1/images/generations'}
className="w-full rounded-md border-2 border-transparent bg-black/50 p-3 text-white outline-none transition-all focus:border-fuchsia-400"
/>
</div>
)}
</div>
{当前配置后端 === 'openai' && (
<div className={卡片样式}>
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<label className={标签样式}>图片响应格式</label>
<InlineSelect
value={当前文生图配置.响应格式}
onChange={(value) => updateImageGenConfig({ 响应格式: value as 'url' | 'b64_json' })}
options={[
{ value: 'url', label: 'URL' },
{ value: 'b64_json', label: 'Base64 / b64_json' }
]}
buttonClassName="bg-black/50 border-gray-600 py-2.5"
/>
</div>
<div className="flex items-center justify-between gap-3 rounded-xl border border-fuchsia-500/20 bg-fuchsia-950/10 p-3">
<div className="text-sm font-bold text-fuchsia-200">OpenAI 兼容图片请求体</div>
<ToggleSwitch
checked={当前文生图配置.OpenAI自定义格式}
onChange={(next) => updateImageGenConfig({ OpenAI自定义格式: next })}
ariaLabel="切换 OpenAI 图片请求体"
/>
</div>
</div>
</div>
)}
{当前配置后端 === 'novelai' && (
<div className="rounded-2xl border border-emerald-500/25 bg-[radial-gradient(circle_at_top,_rgba(16,185,129,0.18),_transparent_55%),rgba(1,10,16,0.7)] p-5 space-y-5">
<div className="flex items-center justify-between gap-3">
<div className="text-base font-bold text-emerald-200">NovelAI 自定义参数</div>
<ToggleSwitch
checked={当前文生图配置.NovelAI启用自定义参数}
onChange={(next) => updateImageGenConfig({ NovelAI启用自定义参数: next })}
ariaLabel="切换 NovelAI 自定义参数"
/>
</div>
<div className="grid gap-4 md:grid-cols-3">
<div className="space-y-2">
<label className="text-sm font-bold text-emerald-200">采样方法</label>
<InlineSelect
value={当前文生图配置.NovelAI采样器}
onChange={(value) => updateImageGenConfig({ NovelAI采样器: value as any })}
options={NovelAI采样器选项}
buttonClassName="bg-black/50 border-gray-600 py-2.5"
disabled={!当前文生图配置.NovelAI启用自定义参数}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-bold text-emerald-200">噪点表</label>
<InlineSelect
value={当前文生图配置.NovelAI噪点表}
onChange={(value) => updateImageGenConfig({ NovelAI噪点表: value as any })}
options={NovelAI噪点表选项}
buttonClassName="bg-black/50 border-gray-600 py-2.5"
disabled={!当前文生图配置.NovelAI启用自定义参数}
/>
</div>
<div className="space-y-2">
<label className="text-sm font-bold text-emerald-200">步数</label>
<input
type="number"
min={1}
max={50}
value={当前文生图配置.NovelAI步数}
onChange={(e) => updateImageGenConfig({ NovelAI步数: Math.max(1, Math.min(50, Number(e.target.value) || 28)) })}
disabled={!当前文生图配置.NovelAI启用自定义参数}
className="w-full rounded-md border-2 border-transparent bg-black/50 p-3 text-white outline-none transition-all focus:border-emerald-400 disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
</div>
<div className="space-y-2">
<label className="text-sm font-bold text-emerald-200">负面提示词</label>
<textarea
value={当前文生图配置.NovelAI负面提示词}
onChange={(e) => updateImageGenConfig({ NovelAI负面提示词: e.target.value })}
rows={6}