-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiffusers_API.js
More file actions
881 lines (848 loc) · 43.6 KB
/
Copy pathDiffusers_API.js
File metadata and controls
881 lines (848 loc) · 43.6 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
(function() {
// ======================
// 🚀 常量与配置
// ======================
const API_CONFIG = {
baseUrl: getApiBaseUrl(),
statusEndpoint: '/api/status',
generateEndpoint: '/api/generate',
checkInterval: 3000,
timeout: 2000,
autoTriggerInterval: 800
};
// ======================
// 🧠 状态管理(闭包内私有)
// ======================
let promptPool = []; // 全局提示词池
let currentConfig = null; // 当前生效配置
let pendingConfig = null; // 待切换配置
let isGenerating = false; // 是否正在生成
let firstGenerationDone = false; // 是否完成首次生成
let apiConnected = false;
let statusPolling = null;
// ======================
// 🔍 工具函数
// ======================
function getApiBaseUrl() {
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.has('api_base')) {
const apiBase = urlParams.get('api_base');
localStorage.setItem('diffusers-api-base', apiBase);
return apiBase;
}
return localStorage.getItem('diffusers-api-base') || 'http://127.0.0.1:8188';
}
function checkApiAvailable() {
return new Promise(resolve => {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), API_CONFIG.timeout);
fetch(API_CONFIG.baseUrl + API_CONFIG.generateEndpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
prompt: "",
modelName: "dummy",
batch: 1,
width: 64,
height: 64,
outputFormat: "jpg"
}),
mode: 'cors',
signal: controller.signal
})
.then(res => resolve(res.status < 500))
.catch(() => resolve(false))
.finally(() => clearTimeout(timeoutId));
});
}
function getParamValue(id, defaultValue) {
const el = document.getElementById(id);
if (!el) return defaultValue;
return el.type === 'checkbox' ? el.checked : el.value || defaultValue;
}
// 统一获取UI参数的函数,用于配置保存、加载和当前状态获取
function getParamsFromUI() {
return {
modelName: getParamValue('param-model-name', 'oneObsession_v16Noobai'),
modelDir: getParamValue('param-model-dir', '../ComfyUI/models/checkpoints'),
outputDir: getParamValue('param-output-dir', '../ComfyUI/output'),
vpred: getParamValue('param-vpred', false),
seed: getParamValue('param-seed', ''),
width: parseInt(getParamValue('param-width', '832')) || 832,
height: parseInt(getParamValue('param-height', '1216')) || 1216,
cfg: parseFloat(getParamValue('param-cfg', '5')) || 5,
steps: parseInt(getParamValue('param-steps', '30')) || 30,
upscale: parseFloat(getParamValue('param-upscale', '1.5')) || 1.5,
denoise: parseFloat(getParamValue('param-denoise', '0.4')) || 0.4,
hiresSteps: parseInt(getParamValue('param-hires-steps', '20')) || 20,
batchSize: parseInt(getParamValue('param-batch', '6')) || 6,
outputFormat: getParamValue('param-output-format', 'jpg'),
promptAdd: getParamValue('param-prompt-add', "masterpiece,best quality,amazing quality,high quality,very awa,very aesthetic,newest,absurdres,highres,"),
negative: getParamValue('param-negative', "worst quality,low quality,bad quality,worst aesthetic,ugly,old,early,lowres,worst detail,low details,jpeg artifacts,bad anatomy,bad hands,bad fingers,bad feet,")
};
}
function onParamChange() {
const newConfig = getParamsFromUI();
if (!currentConfig || JSON.stringify(currentConfig) !== JSON.stringify(newConfig)) {
console.log('参数配置已更改,等待当前任务完成后切换');
pendingConfig = newConfig;
}
}
// ======================
// 🖥️ UI 更新函数
// ======================
function createApiControls() {
const container = document.getElementById('api-controls-container');
if (!container) {
console.error('❌ 未找到 #api-controls-container 容器,请检查 HTML 结构');
return;
}
container.innerHTML = `
<div class="param-section" id="api-controls-section" style="margin-top: 20px;">
<h2>图像生成控制</h2>
<div class="api-status">
<span class="api-status-indicator disconnected" id="api-status-indicator"></span>
<span id="api-status-text">检测API服务中...</span>
</div>
<div class="status-indicator" style="margin-top: 10px;">
<span class="status-dot idle" id="generation-status-dot"></span>
<span id="generation-status-text">就绪</span>
</div>
<div class="progress-container">
<div class="progress-bar" id="progress-bar"></div>
</div>
<div class="generation-status" id="generation-status-details"></div>
<div class="error-details" id="error-details" style="display: none;">
<strong>错误详情:</strong>
<pre id="error-details-content"></pre>
</div>
<div class="action-buttons" style="margin-top: 15px;">
<button id="start-generation-btn" class="btn btn-success">开始生成</button>
<button id="clear-pending-queue-btn" class="btn btn-secondary" style="margin-left: 10px;">清空待处理队列</button>
</div>
<div class="queue-info" style="margin-top: 10px; font-size: 0.9rem; color: #666;">
待处理任务: <span id="queue-count">0</span>
</div>
<div id="queue-preview" style="margin-top: 15px; padding: 10px; background-color: #f9f9f9; border-radius: 6px; border-left: 4px solid #007bff; font-size: 0.85rem; color: #333; max-height: 180px; overflow-y: auto;">
<strong>📋 队列预览:</strong><br>
<em>等待生成的任务将在此显示...</em>
</div>
<!-- ==================== 动态生成的参数配置表单 ==================== -->
<div class="param-grid" style="margin-top: 20px; display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 12px;">
<!-- 模型相关参数 -->
<div class="param-item">
<label style="display: block; margin-bottom: 4px; font-size: 0.9rem; color: #666;">模型名称</label>
<input type="text" id="param-model-name" style="width: 100%; padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.95rem;" value="oneObsession_v16Noobai">
</div>
<div class="param-item">
<label style="display: block; margin-bottom: 4px; font-size: 0.9rem; color: #666;">模型目录</label>
<input type="text" id="param-model-dir" style="width: 100%; padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.95rem;" value="../ComfyUI/models/checkpoints">
</div>
<div class="param-item">
<label style="display: block; margin-bottom: 4px; font-size: 0.9rem; color: #666;">输出目录</label>
<input type="text" id="param-output-dir" style="width: 100%; padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.95rem;" value="../ComfyUI/output">
</div>
<!-- 尺寸相关参数 -->
<div class="param-item">
<label style="display: block; margin-bottom: 4px; font-size: 0.9rem; color: #666;">宽度</label>
<input type="number" id="param-width" min="128" max="4096" style="width: 100%; padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.95rem;" value="832">
</div>
<div class="param-item">
<label style="display: block; margin-bottom: 4px; font-size: 0.9rem; color: #666;">高度</label>
<input type="number" id="param-height" min="128" max="4096" style="width: 100%; padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.95rem;" value="1216">
</div>
<div class="param-item">
<label style="display: block; margin-bottom: 4px; font-size: 0.9rem; color: #666;">CFG Scale</label>
<input type="number" id="param-cfg" min="1" max="30" step="0.1" style="width: 100%; padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.95rem;" value="5">
</div>
<!-- 步骤相关参数 -->
<div class="param-item">
<label style="display: block; margin-bottom: 4px; font-size: 0.9rem; color: #666;">基础步数</label>
<input type="number" id="param-steps" min="1" max="150" style="width: 100%; padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.95rem;" value="30">
</div>
<div class="param-item">
<label style="display: block; margin-bottom: 4px; font-size: 0.9rem; color: #666;">高清修复步数</label>
<input type="number" id="param-hires-steps" min="1" max="100" style="width: 100%; padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.95rem;" value="20">
</div>
<div class="param-item">
<label style="display: block; margin-bottom: 4px; font-size: 0.9rem; color: #666;">高清修复比例</label>
<input type="number" id="param-upscale" min="1" max="4" step="0.1" style="width: 100%; padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.95rem;" value="1.5">
</div>
<div class="param-item">
<label style="display: block; margin-bottom: 4px; font-size: 0.9rem; color: #666;">降噪强度</label>
<input type="number" id="param-denoise" min="0" max="1" step="0.01" style="width: 100%; padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.95rem;" value="0.4">
</div>
<!-- 批次和格式 -->
<div class="param-item">
<label style="display: block; margin-bottom: 4px; font-size: 0.9rem; color: #666;">批次大小</label>
<input type="number" id="param-batch" min="1" max="50" style="width: 100%; padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.95rem;" value="6">
</div>
<div class="param-item">
<label style="display: block; margin-bottom: 4px; font-size: 0.9rem; color: #666;">输出格式</label>
<select id="param-output-format" style="width: 100%; padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.95rem;">
<option value="jpg">JPG</option>
<option value="png">PNG</option>
</select>
</div>
<!-- 其他选项 -->
<div class="param-item">
<label style="display: block; margin-bottom: 4px; font-size: 0.9rem; color: #666;">VPrediction</label>
<div style="display: flex; align-items: center;">
<input type="checkbox" id="param-vpred" style="margin-right: 6px;">
<span style="font-size: 0.9rem;">启用 VPrediction 模式</span>
</div>
</div>
<div class="param-item">
<label style="display: block; margin-bottom: 4px; font-size: 0.9rem; color: #666;">种子</label>
<input type="text" id="param-seed" placeholder="留空为随机" style="width: 100%; padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.95rem;">
</div>
<!-- 新增的提示词参数 -->
<div class="param-item" style="grid-column: 1 / -1;">
<label style="display: block; margin-bottom: 4px; font-size: 0.9rem; color: #666;">附加提示词 (PROMPT_ADD)</label>
<textarea id="param-prompt-add" style="width: 100%; padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.95rem; min-height: 60px; resize: vertical;">masterpiece,best quality,amazing quality,high quality,very awa,very aesthetic,newest,absurdres,highres,</textarea>
</div>
<div class="param-item" style="grid-column: 1 / -1;">
<label style="display: block; margin-bottom: 4px; font-size: 0.9rem; color: #666;">负面提示词 (NEGATIVE_PROMPT)</label>
<textarea id="param-negative" style="width: 100%; padding: 6px 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.95rem; min-height: 60px; resize: vertical;">worst quality,low quality,bad quality,worst aesthetic,ugly,old,early,lowres,worst detail,low details,jpeg artifacts,bad anatomy,bad hands,bad fingers,bad feet,</textarea>
</div>
</div>
<!-- ==================== 配置管理面板 ==================== -->
<div class="config-controls" style="display: flex; gap: 10px; margin-top: 15px; flex-wrap: wrap; align-items: center;">
<div style="display: flex; gap: 5px; align-items: center;">
<span style="font-size: 0.9rem;">配置名称:</span>
<input type="text" id="config-name" placeholder="我的配置" style="padding: 4px 8px; border: 1px solid #ddd; border-radius: 4px; font-size: 0.9rem; min-width: 120px;">
</div>
<button id="save-config-btn" class="btn" style="padding: 4px 10px; font-size: 0.9rem;">保存配置</button>
<button id="load-config-btn" class="btn btn-secondary" style="padding: 4px 10px; font-size: 0.9rem;">加载配置</button>
<button id="export-config-btn" class="btn" style="padding: 4px 10px; font-size: 0.9rem;">导出所有配置</button>
<button id="import-config-btn" class="btn btn-secondary" style="padding: 4px 10px; font-size: 0.9rem;">导入配置</button>
<button id="reset-config-btn" class="btn btn-secondary" style="padding: 4px 10px; font-size: 0.9rem;">重置为默认</button>
<button id="clear-all-configs-btn" class="btn btn-secondary" style="padding: 4px 10px; font-size: 0.9rem;">清空所有已保存设置</button>
<div class="config-status" id="config-status" style="font-size: 0.85rem; color: #666; margin-left: 10px;"></div>
</div>
<div id="saved-configs-list" style="margin-top: 10px; display: flex; flex-wrap: wrap; gap: 8px;"></div>
<input type="file" id="import-config-file" accept=".json" style="display: none;">
</div>
`;
container.style.display = 'block';
initApiFeatures();
}
function updateGenerationStatus(status) {
const dot = document.getElementById('generation-status-dot');
const text = document.getElementById('generation-status-text');
const bar = document.getElementById('progress-bar');
const details = document.getElementById('generation-status-details');
const errorEl = document.getElementById('error-details');
const errorContent = document.getElementById('error-details-content');
if (!dot || !text || !bar || !details) return;
if (status.isRunning) {
isGenerating = true;
dot.className = 'status-dot warning';
text.textContent = status.currentStep || '生成中...';
bar.style.width = `${status.progress}%`;
details.innerHTML = `已处理: ${status.processedImages || 0}/${status.totalImages || 0} 张图像`;
if (status.error) {
errorContent.textContent = status.error;
if (status.lastErrorTraceback) errorContent.textContent += '\n\n' + status.lastErrorTraceback;
errorEl.style.display = 'block';
} else {
errorEl.style.display = 'none';
}
} else {
isGenerating = false;
dot.className = status.error ? 'status-dot error' : 'status-dot success';
text.textContent = status.error ? '生成失败' : '就绪';
bar.style.width = `${status.progress || 0}%`;
details.innerHTML = status.error
? `<span class="status-error">错误: ${status.error}</span>`
: status.totalImages > 0
? `<span class="status-ok">成功生成 ${status.totalImages} 张图像!</span>`
: '就绪';
if (status.error) {
errorContent.textContent = status.error;
if (status.lastErrorTraceback) errorContent.textContent += '\n\n' + status.lastErrorTraceback;
errorEl.style.display = 'block';
} else {
errorEl.style.display = 'none';
}
}
}
function updateQueueCount() {
const el = document.getElementById('queue-count');
if (el) el.textContent = promptPool.length;
}
function updateQueuePreview() {
const previewEl = document.getElementById('queue-preview');
if (!previewEl) return;
let html = '<strong>📋 队列预览:</strong><br>';
const useConfig = pendingConfig || currentConfig;
const batchSize = useConfig?.batchSize || 6;
const remaining = promptPool.length;
const fullBatches = Math.floor(remaining / batchSize);
const remainder = remaining % batchSize;
if (remaining > 0) {
html += `
<div style="margin: 5px 0; padding: 8px; background: #f9f9f9; border-radius: 6px; border-left: 4px solid #007bff;">
<strong>总计 ${remaining} 条提示词</strong><br>
${fullBatches > 0 ? `${fullBatches} 个完整批次 (${batchSize} 条/批)` : ''}
${remainder > 0 ? (fullBatches > 0 ? ' + ' : '') + `${remainder} 条待满批次` : ''}
${pendingConfig ? '<br><span style="color: #ff6b6b;">⚠️ 配置已变更,等待当前任务完成后切换</span>' : ''}
</div>
`;
const previewCount = Math.min(3, remaining);
for (let i = 0; i < previewCount; i++) {
const p = promptPool[i];
const display = p.length > 40 ? p.substring(0, 40) + '...' : p;
html += `
<div style="margin: 2px 0; padding: 3px; font-size: 0.85rem; color: #555; background: #f0f0f0; border-radius: 3px;">
${i + 1}. "${display}"
</div>
`;
}
if (remaining > 3) {
html += `<div style="margin-top: 5px; font-size: 0.8rem; color: #888;">+ ${remaining - 3} 条更多...</div>`;
}
} else {
html += '<em>🟢 暂无待处理提示词</em>';
}
previewEl.innerHTML = html;
}
// ======================
// 🔄 核心业务逻辑
// ======================
function startBatchGeneration() {
if (isGenerating || promptPool.length === 0) return;
isGenerating = true;
const config = currentConfig;
const batchPrompts = promptPool.splice(0, config.batchSize);
console.log(`🚀 开始生成批次: ${batchPrompts.length} 条提示词 (模型: ${config.modelName})`);
const requestData = {
modelName: config.modelName,
modelDir: config.modelDir,
outputDir: config.outputDir,
vpred: config.vpred,
seed: config.seed,
width: config.width,
height: config.height,
cfg: config.cfg,
steps: config.steps,
upscale: config.upscale,
denoise: config.denoise,
hiresSteps: config.hiresSteps,
promptAdd: config.promptAdd,
negative: config.negative,
batch: config.batchSize,
outputFormat: config.outputFormat,
prompt: batchPrompts.join('\n')
};
const statusText = document.getElementById('generation-status-text');
const statusDot = document.getElementById('generation-status-dot');
const progressBar = document.getElementById('progress-bar');
if (statusText) statusText.textContent = `正在生成 ${batchPrompts.length} 条提示词...`;
if (statusDot) statusDot.className = 'status-dot warning';
if (progressBar) progressBar.style.width = '10%';
fetch(API_CONFIG.baseUrl + API_CONFIG.generateEndpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(requestData)
})
.then(res => {
if (!res.ok) return res.json().then(err => { throw new Error(err.error || `API错误: ${res.status}`); });
return res.json();
})
.then(data => {
console.log('✅ 生成请求成功:', data);
if (statusText) statusText.textContent = '生成已启动';
if (progressBar) progressBar.style.width = '15%';
})
.catch(error => {
console.error('❌ 生成请求失败:', error);
if (statusText) statusText.textContent = '请求失败';
if (statusDot) statusDot.className = 'status-dot error';
const details = document.getElementById('generation-status-details');
if (details) details.innerHTML = `<span class="status-error">错误: ${error.message}</span>`;
const errorDetails = document.getElementById('error-details');
const errorContent = document.getElementById('error-details-content');
if (errorDetails && errorContent) {
errorContent.textContent = error.message;
errorDetails.style.display = 'block';
}
})
.finally(() => {
isGenerating = false;
if (pendingConfig && !isGenerating) {
console.log('🔄 切换至新配置');
currentConfig = pendingConfig;
pendingConfig = null;
}
if (promptPool.length > 0 && !isGenerating) {
console.log(`🔁 池中仍有 ${promptPool.length} 条提示词,立即启动下一个批次`);
startBatchGeneration();
} else if (promptPool.length === 0 && !isGenerating) {
const text = document.getElementById('generation-status-text');
const dot = document.getElementById('generation-status-dot');
if (text) text.textContent = '就绪';
if (dot) dot.className = 'status-dot success';
}
updateQueueCount();
updateQueuePreview();
});
}
function autoTriggerGeneration() {
if (!isGenerating && promptPool.length > 0) {
console.log(`🔁 自动触发:检测到 ${promptPool.length} 条提示词,立即启动生成`);
startBatchGeneration();
}
}
function handleStartGeneration() {
if (!apiConnected) {
alert('请先确保API服务已连接!');
return;
}
const input = document.getElementById('tag-input');
if (!input) {
console.error('未找到提示词输入框');
return;
}
const value = input.value.trim();
if (!value) {
alert('请输入至少一个提示词!');
return;
}
currentConfig = getParamsFromUI(); // 强制刷新当前配置
const lines = value.split('\n').map(l => l.trim()).filter(l => l);
const newPrompts = [];
lines.forEach(line => {
const hasTrailingComma = line.endsWith(',');
const tags = line.split(',').map(t => t.trim()).filter(t => t !== '');
if (tags.length === 0) return;
let promptLine = tags.join(', ');
if (hasTrailingComma) promptLine += ',';
newPrompts.push(promptLine);
});
if (newPrompts.length === 0) {
alert('请输入有效的提示词!');
return;
}
promptPool.push(...newPrompts);
updateQueueCount();
updateQueuePreview();
if (!firstGenerationDone && promptPool.length > 0) {
console.log('✅ 首次生成,立即执行,无视 batchSize');
firstGenerationDone = true;
startBatchGeneration();
return;
}
if (!isGenerating && promptPool.length > 0) {
console.log(`✅ 空闲状态检测到 ${promptPool.length} 条提示词,立即启动生成`);
startBatchGeneration();
}
}
function clearPendingQueue() {
if (!confirm('确定要清空所有待处理的生成任务吗?(正在生成的任务不受影响)')) return;
promptPool = [];
updateQueueCount();
updateQueuePreview();
const text = document.getElementById('generation-status-text');
if (text) {
text.textContent = '待处理队列已清空';
setTimeout(() => {
if (text.textContent === '待处理队列已清空') {
text.textContent = isGenerating ? '生成中...' : '就绪';
}
}, 2000);
}
console.log('待处理队列已清空');
}
// ======================
// 🚦 状态轮询与连接检查
// ======================
function checkApiConnection() {
checkApiAvailable().then(available => {
const indicator = document.getElementById('api-status-indicator');
const statusText = document.getElementById('api-status-text');
if (available && !apiConnected) {
apiConnected = true;
indicator.className = 'api-status-indicator connected';
statusText.textContent = 'API已连接';
startStatusPolling();
console.log('✅ API连接已建立');
document.dispatchEvent(new CustomEvent('apiConnectionChanged', { detail: { connected: true } }));
} else if (!available && apiConnected) {
apiConnected = false;
isGenerating = false;
indicator.className = 'api-status-indicator disconnected';
statusText.textContent = 'API未连接';
stopStatusPolling();
const dot = document.getElementById('generation-status-dot');
const text = document.getElementById('generation-status-text');
const details = document.getElementById('generation-status-details');
if (dot) dot.className = 'status-dot error';
if (text) text.textContent = 'API未连接';
if (details) details.innerHTML = '<span class="status-error">API服务未启动或不可用</span>';
console.log('❌ API连接已断开');
document.dispatchEvent(new CustomEvent('apiConnectionChanged', { detail: { connected: false } }));
} else if (available && apiConnected) {
statusText.textContent = 'API已连接';
} else {
statusText.textContent = '检测API服务中...';
}
}).catch(e => {
console.error('API连接检查出错:', e);
});
}
function startStatusPolling() {
stopStatusPolling();
statusPolling = setInterval(() => {
fetch(API_CONFIG.baseUrl + API_CONFIG.statusEndpoint, {
mode: 'cors',
cache: 'no-cache'
})
.then(r => r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`)))
.then(updateGenerationStatus)
.catch(error => {
console.error('获取状态失败:', error);
apiConnected = false;
stopStatusPolling();
});
}, 500);
}
function stopStatusPolling() {
if (statusPolling) {
clearInterval(statusPolling);
statusPolling = null;
}
}
// ======================
// 🧩 配置管理功能
// ======================
const DEFAULT_PARAMS = {
modelName: 'oneObsession_v16Noobai',
modelDir: '../ComfyUI/models/checkpoints',
outputDir: '../ComfyUI/output',
vpred: false,
seed: '',
width: 832,
height: 1216,
cfg: 5,
steps: 30,
upscale: 1.5,
denoise: 0.4,
hiresSteps: 20,
batchSize: 6,
outputFormat: 'jpg',
promptAdd: 'masterpiece,best quality,amazing quality,high quality,very awa,very aesthetic,newest,absurdres,highres,',
negative: 'worst quality,low quality,bad quality,worst aesthetic,ugly,old,early,lowres,worst detail,low details,jpeg artifacts,bad anatomy,bad hands,bad fingers,bad feet,'
};
function saveConfig() {
const configName = document.getElementById('config-name').value.trim();
if (!configName) {
updateConfigStatus('请输入配置名称', true);
return;
}
const params = getParamsFromUI();
const savedConfigs = JSON.parse(localStorage.getItem('diffusers-configs') || '{}');
savedConfigs[configName] = params;
localStorage.setItem('diffusers-configs', JSON.stringify(savedConfigs));
updateConfigStatus(`配置 "${configName}" 已保存`, false);
renderSavedConfigs();
document.getElementById('config-name').value = configName;
}
function loadConfig(configName) {
const savedConfigs = JSON.parse(localStorage.getItem('diffusers-configs') || '{}');
const config = savedConfigs[configName];
if (!config) {
updateConfigStatus(`配置 "${configName}" 不存在`, true);
return;
}
applyParamsToUI(config);
document.getElementById('config-name').value = configName;
updateConfigStatus(`已加载配置 "${configName}"`, false);
}
function deleteConfig(configName) {
if (!confirm(`确定要删除配置 "${configName}" 吗?`)) return;
const savedConfigs = JSON.parse(localStorage.getItem('diffusers-configs') || '{}');
delete savedConfigs[configName];
localStorage.setItem('diffusers-configs', JSON.stringify(savedConfigs));
updateConfigStatus(`配置 "${configName}" 已删除`, false);
renderSavedConfigs();
if (document.getElementById('config-name').value === configName) {
document.getElementById('config-name').value = '';
}
}
function clearAllConfigs() {
if (!confirm('确定要删除所有已保存的配置吗?此操作不可恢复!')) return;
localStorage.removeItem('diffusers-configs');
updateConfigStatus('所有配置已删除', false);
renderSavedConfigs();
document.getElementById('config-name').value = '';
}
function exportAllConfigs() {
const savedConfigs = JSON.parse(localStorage.getItem('diffusers-configs') || '{}');
const lastParams = JSON.parse(localStorage.getItem('diffusers-last-params') || 'null');
const allConfigs = {
version: '1.2',
timestamp: new Date().toISOString(),
configs: savedConfigs,
lastParams: lastParams,
defaultParams: DEFAULT_PARAMS
};
const jsonContent = JSON.stringify(allConfigs, null, 2);
const blob = new Blob([jsonContent], {type: 'application/json'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `diffusers-configs-${new Date().toISOString().replace(/[:.]/g, '-')}.json`;
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
URL.revokeObjectURL(url);
}, 0);
updateConfigStatus(`已导出 ${Object.keys(savedConfigs).length} 个配置`, false);
}
function importAllConfigs() {
const fileInput = document.getElementById('import-config-file');
fileInput.value = '';
fileInput.click();
}
function handleImportedAllConfigs(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(e) {
try {
const allConfigs = JSON.parse(e.target.result);
if (!allConfigs.configs || typeof allConfigs.configs !== 'object') {
throw new Error('配置文件格式不正确或缺少必要参数');
}
localStorage.setItem('diffusers-configs', JSON.stringify(allConfigs.configs));
if (allConfigs.lastParams) {
localStorage.setItem('diffusers-last-params', JSON.stringify(allConfigs.lastParams));
}
renderSavedConfigs();
initParams();
updateConfigStatus(`已导入 ${Object.keys(allConfigs.configs).length} 个配置`, false);
} catch (error) {
updateConfigStatus(`导入失败: ${error.message}`, true);
console.error('配置导入失败:', error);
}
event.target.value = null;
};
reader.readAsText(file);
}
function resetToDefault() {
applyParamsToUI(DEFAULT_PARAMS);
document.getElementById('config-name').value = '默认配置';
updateConfigStatus('已重置为默认参数', false);
}
function applyParamsToUI(params) {
const els = {
'param-model-name': params.modelName,
'param-model-dir': params.modelDir,
'param-output-dir': params.outputDir,
'param-vpred': params.vpred,
'param-seed': params.seed,
'param-width': params.width,
'param-height': params.height,
'param-cfg': params.cfg,
'param-steps': params.steps,
'param-upscale': params.upscale,
'param-denoise': params.denoise,
'param-hires-steps': params.hiresSteps,
'param-batch': params.batchSize,
'param-output-format': params.outputFormat,
'param-prompt-add': params.promptAdd,
'param-negative': params.negative
};
Object.entries(els).forEach(([id, value]) => {
const el = document.getElementById(id);
if (el) {
if (el.type === 'checkbox') {
el.checked = value;
} else {
el.value = value || '';
}
}
});
}
function saveLastParams() {
const params = getParamsFromUI();
localStorage.setItem('diffusers-last-params', JSON.stringify(params));
}
function renderSavedConfigs() {
const savedConfigs = JSON.parse(localStorage.getItem('diffusers-configs') || '{}');
const configList = document.getElementById('saved-configs-list');
configList.innerHTML = '';
Object.keys(savedConfigs).forEach(configName => {
const configItem = document.createElement('div');
configItem.className = 'config-item';
configItem.style = `
padding: 4px 8px;
border-radius: 4px;
font-size: 0.85rem;
cursor: pointer;
transition: all 0.2s;
position: relative;
display: inline-flex;
align-items: center;
gap: 6px;
`;
if (document.body.classList.contains('dark')) {
configItem.style.backgroundColor = '#333';
configItem.style.color = '#eee';
} else {
configItem.style.backgroundColor = '#f0f0f0';
configItem.style.color = '#333';
}
const nameSpan = document.createElement('span');
nameSpan.textContent = configName;
configItem.appendChild(nameSpan);
const deleteBtn = document.createElement('span');
deleteBtn.className = 'delete-config';
deleteBtn.innerHTML = '×';
deleteBtn.style = `
cursor: pointer;
font-weight: bold;
color: #c62828;
padding: 0 2px;
margin-left: 4px;
display: inline-block;
`;
deleteBtn.onclick = (e) => {
e.stopPropagation();
deleteConfig(configName);
};
configItem.appendChild(deleteBtn);
configItem.onmouseover = () => {
configItem.style.opacity = '0.8';
};
configItem.onmouseout = () => {
configItem.style.opacity = '1';
};
configItem.onclick = () => loadConfig(configName);
configList.appendChild(configItem);
});
if (Object.keys(savedConfigs).length === 0) {
const noConfig = document.createElement('span');
noConfig.style.fontSize = '0.85rem';
noConfig.style.color = document.body.classList.contains('dark') ? '#aaa' : '#999';
noConfig.textContent = '暂无保存的配置';
configList.appendChild(noConfig);
}
}
function updateConfigStatus(message, isError = false) {
const statusEl = document.getElementById('config-status');
if (!statusEl) return;
statusEl.textContent = message;
statusEl.style.color = isError ? '#c62828' : '#2e7d32';
if (document.body.classList.contains('dark')) {
statusEl.style.color = isError ? '#ff8a80' : '#69f0ae';
}
setTimeout(() => {
if (statusEl.textContent === message) {
statusEl.textContent = '';
}
}, 3000);
}
// ======================
// 🧩 初始化入口
// ======================
function initApiFeatures() {
const lastParams = JSON.parse(localStorage.getItem('diffusers-last-params') || 'null');
if (lastParams) {
const completeParams = {
...DEFAULT_PARAMS,
...lastParams
};
applyParamsToUI(completeParams);
document.getElementById('config-name').value = '上次使用的配置';
} else {
resetToDefault();
}
const paramIds = [
'param-model-name', 'param-model-dir', 'param-output-dir', 'param-vpred',
'param-seed', 'param-width', 'param-height', 'param-cfg', 'param-steps',
'param-upscale', 'param-denoise', 'param-hires-steps', 'param-batch',
'param-output-format', 'param-prompt-add', 'param-negative'
];
paramIds.forEach(id => {
const el = document.getElementById(id);
if (el) {
el.addEventListener('change', onParamChange);
el.addEventListener('change', saveLastParams);
}
});
document.getElementById('save-config-btn').addEventListener('click', saveConfig);
document.getElementById('load-config-btn').addEventListener('click', () => {
const configName = document.getElementById('config-name').value.trim();
if (configName) loadConfig(configName);
});
document.getElementById('reset-config-btn').addEventListener('click', resetToDefault);
document.getElementById('export-config-btn').addEventListener('click', exportAllConfigs);
document.getElementById('import-config-btn').addEventListener('click', importAllConfigs);
document.getElementById('import-config-file').addEventListener('change', handleImportedAllConfigs);
document.getElementById('clear-all-configs-btn').addEventListener('click', clearAllConfigs);
renderSavedConfigs();
setInterval(autoTriggerGeneration, API_CONFIG.autoTriggerInterval);
checkApiConnection();
setInterval(checkApiConnection, API_CONFIG.checkInterval);
const generateBtn = document.getElementById('start-generation-btn');
if (generateBtn) generateBtn.addEventListener('click', handleStartGeneration);
const clearBtn = document.getElementById('clear-pending-queue-btn');
if (clearBtn) clearBtn.addEventListener('click', clearPendingQueue);
currentConfig = getParamsFromUI();
console.log('✅ API控制功能已初始化(独立模块)');
}
// ======================
// 🌐 页面加载与API地址监听
// ======================
document.addEventListener('DOMContentLoaded', function() {
const apiUrlInput = document.getElementById('api-base-url');
if (apiUrlInput) {
const savedApiBase = localStorage.getItem('diffusers-api-base') || 'http://127.0.0.1:8188';
apiUrlInput.value = savedApiBase;
apiUrlInput.addEventListener('blur', function() {
const newUrl = this.value.trim();
if (newUrl && (newUrl.startsWith('http://') || newUrl.startsWith('https://'))) {
localStorage.setItem('diffusers-api-base', newUrl);
API_CONFIG.baseUrl = newUrl;
console.log('API地址已更新:', API_CONFIG.baseUrl);
checkApiConnection();
}
});
document.getElementById('save-api-url-btn').addEventListener('click', function() {
const newUrl = apiUrlInput.value.trim();
if (newUrl && (newUrl.startsWith('http://') || newUrl.startsWith('https://'))) {
localStorage.setItem('diffusers-api-base', newUrl);
API_CONFIG.baseUrl = newUrl;
console.log('API地址已更新:', API_CONFIG.baseUrl);
checkApiConnection();
}
});
}
const container = document.getElementById('api-controls-container');
if (container) {
createApiControls();
} else {
console.error('❌ 未找到 #api-controls-container 容器,请确认HTML结构');
}
window.addEventListener('apiConnectionChanged', (e) => {
apiConnected = e.detail.connected;
const statusEl = document.getElementById('api-connection-status');
if (statusEl) {
statusEl.textContent = e.detail.connected ? 'API已连接' : 'API未连接';
statusEl.className = e.detail.connected ? 'status-ok' : 'status-error';
}
});
});
window.addEventListener('error', event => {
console.error('全局JavaScript错误:', {
message: event.message,
source: event.filename,
line: event.lineno,
column: event.colno,
error: event.error
});
});
})();