forked from vavo/TagPilot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtagpilot.html
More file actions
1844 lines (1633 loc) · 95.7 KB
/
Copy pathtagpilot.html
File metadata and controls
1844 lines (1633 loc) · 95.7 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TagPilot ✈️</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.1/cropper.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.6.1/cropper.min.js"></script>
<style>
body { font-family: 'Inter', sans-serif; }
::-webkit-scrollbar { width: 8px; }
::-webkit-scrollbar-track { background: #2d3748; }
::-webkit-scrollbar-thumb { background: #4a5568; border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: #718096; }
.settings-icon { position: fixed; top: 10px; left: 10px; display: flex; align-items: center; gap: 8px; font-size: 15px; font-weight: 600; cursor: pointer; z-index: 1000; color: #e5e7eb; background: rgba(31, 41, 55, 0.9); border: 1px solid #374151; border-radius: 8px; padding: 8px 10px; }
.settings-icon-symbol { font-size: 22px; line-height: 1; }
.modal { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.7); z-index: 2000; justify-content: center; align-items: center; }
.modal-content { background: #1f2937; padding: 24px; border-radius: 12px; width: 320px; color: white; }
.settings-modal-content { width: min(960px, calc(100vw - 32px)); max-height: 90vh; overflow-y: auto; }
.close { float: right; cursor: pointer; font-size: 24px; }
.collapsible-content { transition: max-height 0.3s ease-out; max-height: 0; overflow: hidden; }
.collapsible-content.expanded { max-height: 1000px; overflow-y: auto; }
.rotate-icon { transition: transform 0.3s ease; }
.rotate-icon.expanded { transform: rotate(180deg); }
</style>
</head>
<body class="bg-gray-900 text-gray-200">
<!-- Settings Icon -->
<div id="settings-icon" class="settings-icon">
<span class="settings-icon-symbol">⚙️</span>
<span>Settings</span>
</div>
<div id="lora-pilot-family-link" class="fixed bottom-3 right-3 z-[900] text-xs text-gray-500">
Part of <a href="https://github.com/vavo/lora-pilot" target="_blank" rel="noopener noreferrer" class="text-gray-400 hover:text-indigo-300 underline underline-offset-2">Lora Pilot</a> family
</div>
<!-- Settings Modal -->
<div id="settingsModal" class="modal">
<div class="modal-content settings-modal-content">
<span class="close" id="closeSettings">×</span>
<h2 class="text-2xl mb-4">Settings</h2>
<div class="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-5">
<section class="border border-gray-700 rounded-lg p-4 bg-gray-900/40">
<h3 class="text-lg font-semibold text-white mb-3">Tagging Options</h3>
<label class="block mb-2 text-sm text-gray-400">Default model</label>
<select id="tag-default-model" class="w-full bg-gray-700 p-2 rounded mb-4">
<option value="gemini">Gemini</option>
<option value="grok">Grok</option>
<option value="openai">OpenAI</option>
<option value="claude">Claude</option>
<option value="vllm">vLLM OpenAI compatible</option>
<option value="deepdanbooru">DeepDanbooru</option>
<option value="wd14">WD1.4 Tagger</option>
</select>
<label class="block mb-2 text-sm text-gray-400">Max number of tags per image</label>
<input type="number" id="setting-max-tags" value="30" min="1" max="100" class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 text-white focus:outline-none focus:border-indigo-500 mb-4">
<label class="block mb-2 text-sm text-gray-400">System prompt</label>
<textarea id="tag-system-prompt" class="w-full h-40 bg-gray-900 border border-gray-600 rounded p-2 text-xs text-gray-300 focus:outline-none focus:border-indigo-500"></textarea>
</section>
<section class="border border-gray-700 rounded-lg p-4 bg-gray-900/40">
<h3 class="text-lg font-semibold text-white mb-3">Captioning Options</h3>
<label class="block mb-2 text-sm text-gray-400">Default model</label>
<select id="caption-default-model" class="w-full bg-gray-700 p-2 rounded mb-4">
<option value="gemini">Gemini</option>
<option value="grok">Grok</option>
<option value="openai">OpenAI</option>
<option value="claude">Claude</option>
<option value="vllm">vLLM OpenAI compatible</option>
</select>
<label class="block mb-2 text-sm text-gray-400">Max caption length (words)</label>
<input type="number" id="setting-max-caption-len" value="50" min="5" max="200" class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 text-white focus:outline-none focus:border-purple-500 mb-4">
<label class="block mb-2 text-sm text-gray-400">System prompt</label>
<textarea id="caption-system-prompt" class="w-full h-40 bg-gray-900 border border-gray-600 rounded p-2 text-xs text-gray-300 focus:outline-none focus:border-purple-500"></textarea>
</section>
</div>
<section class="border border-gray-700 rounded-lg p-4 bg-gray-900/40 mb-5">
<h3 class="text-lg font-semibold text-white mb-3">Crop Options</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label class="block mb-2 text-sm text-gray-400">Crop Size</label>
<select id="crop-aspect-ratio" class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 text-white focus:outline-none focus:border-indigo-500">
<option value="freeform">Free form</option>
<option value="1:1">1:1 Square</option>
<option value="16:9">16:9 Landscape</option>
<option value="3:2">3:2 Landscape</option>
<option value="4:3">4:3 Landscape</option>
<option value="21:9">21:9 Widescreen</option>
<option value="9:16">9:16 Portrait</option>
<option value="2:3">2:3 Portrait</option>
<option value="3:4">3:4 Portrait</option>
</select>
</div>
<div>
<label class="block mb-2 text-sm text-gray-400">Crop width (px)</label>
<input type="number" id="crop-width" value="1024" min="64" max="8192" step="64" class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 text-white focus:outline-none focus:border-indigo-500">
</div>
</div>
</section>
<section class="border border-gray-700 rounded-lg p-4 bg-gray-900/40 mb-5">
<h3 class="text-lg font-semibold text-white mb-3">Model API Keys</h3>
<div class="overflow-x-auto">
<table id="model-api-key-table" class="w-full text-sm">
<thead class="text-gray-400">
<tr>
<th class="text-left font-medium py-2 pr-4">Model</th>
<th class="text-left font-medium py-2 pr-4">API key</th>
<th class="text-left font-medium py-2">Status</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-700">
<tr>
<td class="py-2 pr-4 text-gray-200">Gemini</td>
<td class="py-2 pr-4"><input type="password" id="api-key-gemini" class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 text-white focus:outline-none focus:border-indigo-500"></td>
<td class="py-2 text-xs text-gray-500" data-key-status="gemini">Not saved</td>
</tr>
<tr>
<td class="py-2 pr-4 text-gray-200">Grok</td>
<td class="py-2 pr-4"><input type="password" id="api-key-grok" class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 text-white focus:outline-none focus:border-indigo-500"></td>
<td class="py-2 text-xs text-gray-500" data-key-status="grok">Not saved</td>
</tr>
<tr>
<td class="py-2 pr-4 text-gray-200">OpenAI</td>
<td class="py-2 pr-4"><input type="password" id="api-key-openai" class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 text-white focus:outline-none focus:border-indigo-500"></td>
<td class="py-2 text-xs text-gray-500" data-key-status="openai">Not saved</td>
</tr>
<tr>
<td class="py-2 pr-4 text-gray-200">Claude</td>
<td class="py-2 pr-4"><input type="password" id="api-key-claude" class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 text-white focus:outline-none focus:border-indigo-500"></td>
<td class="py-2 text-xs text-gray-500" data-key-status="claude">Not saved</td>
</tr>
<tr>
<td class="py-2 pr-4 text-gray-200">vLLM OpenAI compatible</td>
<td class="py-2 pr-4"><input type="password" id="api-key-vllm" placeholder="sk-pod-id" class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 text-white focus:outline-none focus:border-indigo-500"></td>
<td class="py-2 text-xs text-gray-500" data-key-status="vllm">Not saved</td>
</tr>
<tr>
<td class="py-2 pr-4 text-gray-200">DeepDanbooru</td>
<td class="py-2 pr-4"><input type="text" id="api-key-deepdanbooru" disabled value="No key required" class="w-full bg-gray-800 border border-gray-700 rounded px-3 py-2 text-gray-500"></td>
<td class="py-2 text-xs text-teal-400">Ready</td>
</tr>
<tr>
<td class="py-2 pr-4 text-gray-200">WD1.4 Tagger</td>
<td class="py-2 pr-4"><input type="password" id="api-key-wd14" class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 text-white focus:outline-none focus:border-indigo-500"></td>
<td class="py-2 text-xs text-gray-500" data-key-status="wd14">Not saved</td>
</tr>
</tbody>
</table>
</div>
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 mt-4">
<div>
<label class="block mb-2 text-sm text-gray-400">DeepDanbooru threshold</label>
<input type="number" id="ddThreshold" min="0" max="1" step="0.05" value="0.5" class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 text-white focus:outline-none focus:border-indigo-500">
</div>
<div>
<label class="block mb-2 text-sm text-gray-400">WD1.4 general threshold</label>
<input type="number" id="wdGeneralThresh" min="0" max="1" step="0.05" value="0.35" class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 text-white focus:outline-none focus:border-indigo-500">
</div>
<div>
<label class="block mb-2 text-sm text-gray-400">WD1.4 character threshold</label>
<input type="number" id="wdCharThresh" min="0" max="1" step="0.05" value="0.85" class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 text-white focus:outline-none focus:border-indigo-500">
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4 pt-4 border-t border-gray-700">
<div>
<label class="block mb-2 text-sm text-gray-400">vLLM endpoint URL</label>
<input type="url" id="vllm-endpoint" placeholder="https://pod-id-8000.proxy.runpod.net" class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 text-white focus:outline-none focus:border-indigo-500">
</div>
<div>
<label class="block mb-2 text-sm text-gray-400">vLLM model preset</label>
<select id="vllm-model-preset" class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 text-white focus:outline-none focus:border-indigo-500">
<option value="">Custom model ID</option>
<option value="Qwen/Qwen2.5-VL-3B-Instruct">Qwen2.5 VL 3B Instruct</option>
<option value="Qwen/Qwen2.5-VL-7B-Instruct">Qwen2.5 VL 7B Instruct</option>
<option value="Qwen/Qwen3-VL-4B-Instruct">Qwen3 VL 4B Instruct</option>
<option value="Qwen/Qwen3-VL-8B-Instruct">Qwen3 VL 8B Instruct</option>
<option value="Qwen/Qwen3.5-9B-Instruct">Qwen3.5 9B Instruct</option>
<option value="google/gemma-3-4b-it">Gemma 3 4B IT</option>
<option value="google/gemma-3-12b-it">Gemma 3 12B IT</option>
<option value="mistralai/Pixtral-12B-2409">Mistral Pixtral 12B</option>
<option value="mistralai/Mistral-Small-3.1-24B-Instruct-2503">Mistral Small 3.1 24B</option>
</select>
</div>
<div class="md:col-span-2">
<label class="block mb-2 text-sm text-gray-400">vLLM model type</label>
<input type="text" id="vllm-model-type" value="Qwen/Qwen3-8B" placeholder="Qwen/Qwen3-8B" class="w-full bg-gray-700 border border-gray-600 rounded px-3 py-2 text-white focus:outline-none focus:border-indigo-500">
</div>
</div>
</section>
<div class="flex justify-end">
<button id="saveSettings" class="bg-indigo-600 hover:bg-indigo-700 px-4 py-2 rounded">Save</button>
</div>
</div>
</div>
<!-- Notification -->
<div id="notification" class="hidden fixed top-5 right-5 bg-yellow-500 text-gray-900 py-3 px-5 rounded-lg shadow-lg z-50 transition-all duration-300 transform translate-x-full">
<p id="notification-text"></p>
</div>
<div class="container mx-auto p-4 md:p-8">
<header class="text-center mb-8">
<h1 class="text-4xl font-bold text-white mb-2">TagPilot ✈️</h1>
<p class="text-lg text-gray-400">Advanced LoRA Dataset Tagger</p>
</header>
<div class="bg-gray-800 p-6 rounded-lg shadow-lg mb-8">
<h2 class="text-2xl font-semibold mb-4 text-white">1. Load Your Dataset</h2>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 max-w-4xl mx-auto">
<div>
<label for="image-upload" class="w-full h-full flex flex-col items-center justify-center p-6 bg-gray-700 hover:bg-indigo-600 border-2 border-dashed border-gray-500 rounded-lg cursor-pointer transition-all">
<svg class="w-10 h-10 mb-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
<span class="font-semibold">Upload Photos</span>
<span class="text-sm text-gray-400">Select individual image files</span>
</label>
<input id="image-upload" type="file" class="hidden" multiple accept="image/png, image/jpeg, image/webp">
</div>
<div>
<label for="zip-upload" class="w-full h-full flex flex-col items-center justify-center p-6 bg-gray-700 hover:bg-indigo-600 border-2 border-dashed border-gray-500 rounded-lg cursor-pointer transition-all">
<svg class="w-10 h-10 mb-3 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path></svg>
<span class="font-semibold">Upload ZIP Dataset</span>
<span class="text-sm text-gray-400">.zip file with images and .txt files</span>
</label>
<input id="zip-upload" type="file" class="hidden" accept=".zip">
</div>
</div>
</div>
<div id="tagger-section" class="hidden">
<div class="bg-gray-800 p-4 rounded-lg shadow-lg mb-6 flex flex-col gap-4">
<div class="flex flex-col sm:flex-row justify-between items-center gap-4 flex-wrap">
<h2 class="text-2xl font-semibold text-white">2. Edit Tags</h2>
<div class="flex items-center gap-4 flex-wrap justify-center w-full sm:w-auto">
<button id="reset-button" class="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg transition-colors shadow-md">
Reset All
</button>
<button id="clear-tags-button" class="bg-orange-600 hover:bg-orange-700 text-white font-bold py-2 px-4 rounded-lg transition-colors shadow-md">
Clear Tags/Captions
</button>
<div class="relative flex items-center">
<span id="trigger-word-label" class="absolute left-3 text-gray-400 text-sm">Trigger Word:</span>
<input type="text" id="trigger-word-input" placeholder="e.g. ohwx man" class="bg-gray-700 border border-gray-600 rounded-md py-2 pl-24 pr-3 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 w-40 sm:w-48">
</div>
<div class="relative flex items-center">
<span id="dataset-name-label" class="absolute left-3 text-gray-400 text-sm">Dataset Name:</span>
<input type="text" id="dataset-name-input" placeholder="filename" class="bg-gray-700 border border-gray-600 rounded-md py-2 pl-28 pr-3 text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 w-40 sm:w-48">
</div>
<button id="tag-all-button" class="bg-teal-600 hover:bg-teal-700 text-white font-bold py-2 px-4 rounded-lg transition-colors shadow-md">Tag All</button>
<button id="caption-all-button" class="bg-purple-600 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded-lg transition-colors shadow-md">Caption All</button>
<button id="export-button" class="bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 px-4 rounded-lg transition-colors shadow-md">
Export as ZIP
</button>
</div>
</div>
</div>
<div id="tag-viewer-section" class="bg-gray-800 rounded-lg shadow-lg mb-6 overflow-hidden hidden">
<div id="tag-viewer-header" class="p-4 bg-gray-750 flex justify-between items-center cursor-pointer hover:bg-gray-700 transition-colors border-b border-gray-700">
<div class="flex items-center gap-3">
<h3 class="text-lg font-semibold text-white">Tag Viewer</h3>
<span id="total-tags-badge" class="bg-indigo-900 text-indigo-200 text-xs px-2 py-1 rounded-full font-mono">0 tags</span>
</div>
<svg id="tag-viewer-arrow" class="w-5 h-5 text-gray-400 rotate-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path></svg>
</div>
<div id="tag-viewer-content" class="collapsible-content bg-gray-800">
<div id="tag-viewer-list" class="p-4 flex flex-wrap gap-2">
</div>
</div>
</div>
<div id="image-grid" class="grid grid-cols-1 gap-6"></div>
<div id="placeholder" class="text-center py-20 bg-gray-800 rounded-lg">
<svg class="mx-auto h-12 w-12 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
<path vector-effect="non-scaling-stroke" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 13h6m-3-3v6m-9 1V7a2 2 0 012-2h6l2 2h6a2 2 0 01-2 2H5a2 2 0 01-2-2z" />
</svg>
<h3 class="mt-2 text-sm font-medium text-gray-300">No images loaded</h3>
<p class="mt-1 text-sm text-gray-500">Upload some photos or a ZIP file to get started.</p>
</div>
</div>
<div id="loader" class="hidden fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center z-50">
<div class="flex flex-col items-center">
<svg class="animate-spin h-10 w-10 text-white mb-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
<p id="loader-text" class="text-white text-lg">Processing ZIP file...</p>
</div>
</div>
<div id="tag-settings-modal" class="hidden fixed inset-0 bg-black bg-opacity-80 flex items-center justify-center z-50 p-4">
<div class="bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6 border border-gray-700">
<div id="tag-settings-config">
<h3 class="text-xl font-bold text-white mb-4">Tagging Settings</h3>
<div class="mb-6">
<label class="block text-gray-400 text-sm mb-2">If tags exist:</label>
<div class="space-y-2">
<label class="flex items-center space-x-3 cursor-pointer">
<input type="radio" name="tag-mode" value="ignore" checked class="form-radio text-indigo-600 h-4 w-4 bg-gray-900 border-gray-600 focus:ring-indigo-500">
<span class="text-gray-300">Ignore (Skip already tagged images)</span>
</label>
<label class="flex items-center space-x-3 cursor-pointer">
<input type="radio" name="tag-mode" value="append" class="form-radio text-indigo-600 h-4 w-4 bg-gray-900 border-gray-600 focus:ring-indigo-500">
<span class="text-gray-300">Append (Add new to existing)</span>
</label>
<label class="flex items-center space-x-3 cursor-pointer">
<input type="radio" name="tag-mode" value="overwrite" class="form-radio text-indigo-600 h-4 w-4 bg-gray-900 border-gray-600 focus:ring-indigo-500">
<span class="text-gray-300">Overwrite (Replace existing)</span>
</label>
</div>
</div>
<div class="flex justify-end gap-3">
<button id="cancel-tagging-btn" class="px-4 py-2 bg-gray-600 hover:bg-gray-500 text-white rounded transition-colors">Cancel</button>
<button id="start-tagging-btn" class="px-4 py-2 bg-indigo-600 hover:bg-indigo-500 text-white font-bold rounded transition-colors">Start</button>
</div>
</div>
<div id="tag-settings-progress" class="hidden text-center">
<h3 class="text-xl font-bold text-white mb-2">Auto-Tagging in Progress...</h3>
<p class="text-gray-400 mb-4">Please wait while TagPilot processes your images.</p>
<div class="w-full bg-gray-700 rounded-full h-4 mb-2 overflow-hidden">
<div id="tag-progress-bar" class="bg-teal-500 h-4 rounded-full transition-all duration-300" style="width: 0%"></div>
</div>
<p id="tag-progress-text" class="text-sm text-gray-300 mb-6">0 / 0</p>
<button id="stop-tagging-btn" class="px-6 py-2 bg-red-600 hover:bg-red-500 text-white font-bold rounded transition-colors">Stop</button>
</div>
</div>
</div>
<div id="caption-settings-modal" class="hidden fixed inset-0 bg-black bg-opacity-80 flex items-center justify-center z-50 p-4">
<div class="bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6 border border-gray-700">
<div id="caption-settings-config">
<h3 class="text-xl font-bold text-white mb-4">Caption Settings</h3>
<div class="mb-4">
<label class="block text-gray-400 text-sm mb-2">If text exists:</label>
<div class="space-y-2">
<label class="flex items-center space-x-3 cursor-pointer">
<input type="radio" name="caption-mode" value="ignore" checked class="form-radio text-purple-600 h-4 w-4 bg-gray-900 border-gray-600 focus:ring-purple-500">
<span class="text-gray-300">Ignore (Skip)</span>
</label>
<label class="flex items-center space-x-3 cursor-pointer">
<input type="radio" name="caption-mode" value="append" class="form-radio text-purple-600 h-4 w-4 bg-gray-900 border-gray-600 focus:ring-purple-500">
<span class="text-gray-300">Append (Add to end)</span>
</label>
<label class="flex items-center space-x-3 cursor-pointer">
<input type="radio" name="caption-mode" value="overwrite" class="form-radio text-purple-600 h-4 w-4 bg-gray-900 border-gray-600 focus:ring-purple-500">
<span class="text-gray-300">Overwrite (Replace)</span>
</label>
</div>
</div>
<div class="flex justify-end gap-3">
<button id="cancel-captioning-btn" class="px-4 py-2 bg-gray-600 hover:bg-gray-500 text-white rounded transition-colors">Cancel</button>
<button id="start-captioning-btn" class="px-4 py-2 bg-purple-600 hover:bg-purple-500 text-white font-bold rounded transition-colors">Start</button>
</div>
</div>
<div id="caption-settings-progress" class="hidden text-center">
<h3 class="text-xl font-bold text-white mb-2">Auto-Captioning...</h3>
<p class="text-gray-400 mb-4">TagPilot is writing descriptions for your images.</p>
<div class="w-full bg-gray-700 rounded-full h-4 mb-2 overflow-hidden">
<div id="caption-progress-bar" class="bg-purple-500 h-4 rounded-full transition-all duration-300" style="width: 0%"></div>
</div>
<p id="caption-progress-text" class="text-sm text-gray-300 mb-6">0 / 0</p>
<button id="stop-captioning-btn" class="px-6 py-2 bg-red-600 hover:bg-red-500 text-white font-bold rounded transition-colors">Stop</button>
</div>
</div>
</div>
<div id="preview-modal" class="hidden fixed inset-0 bg-black bg-opacity-80 flex items-center justify-center z-50 p-4">
<img id="preview-image" src="" class="max-w-full max-h-full object-contain rounded-lg">
<button id="preview-crop" class="absolute top-4 right-20 bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg shadow-lg">Crop</button>
<button id="preview-close" class="absolute top-4 right-4 text-white text-4xl font-bold">×</button>
</div>
<div id="crop-modal" class="hidden fixed inset-0 bg-gray-900 bg-opacity-90 flex flex-col items-center justify-center z-50 p-4">
<div class="w-full max-w-4xl h-4/5">
<img id="crop-image" src="" class="max-w-full max-h-full">
</div>
<div class="mt-4 flex gap-4">
<button id="crop-save" class="bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 px-6 rounded-lg">Save Crop</button>
<button id="crop-cancel" class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-6 rounded-lg">Cancel</button>
</div>
</div>
</div>
<script>
let dataset = [];
let currentTriggerWord = "";
let isBatchProcessing = false;
let cropper = null;
let currentCropItemId = null;
let currentPreviewItemId = null;
let nextDatasetItemId = 1;
const fileObjectUrls = new Map();
const transientObjectUrls = new Set();
const DEFAULT_TAG_PROMPT = `You are an expert for creating photorealistic AI training datasets. Your task is to generate descriptive tags for the provided image for the purpose of SDXL lora training using kohya_ss.
Follow these rules strictly:
1. Focus on Unique Features:** Prioritize tags that describe the subject's unique identity, specific clothing (e.g., 'blue denim jacket', not just 'jacket'), hairstyle and color, distinct facial features (e.g., 'freckles', 'defined jawline'), and overall style cues (e.g., 'goth style', 'business casual').
2. Avoid Noise:** Do NOT use generic, low-impact tags like 'solo', '1girl', 'looking at viewer', 'realistic', 'photorealistic'.
3. Prioritize Impact:** List the most descriptive and important tags first.
4. Balance Character and Context:** Aim for approximately two-thirds of the tags describing the character (person, clothing, hair, accessories) and one-third describing the background, composition, and lighting (e.g., 'outdoors', 'city street at night', 'soft lighting').
5. Be Concise and Specific:** Avoid redundant tags. For example, use 'blue eyes' instead of 'blue color, eyes'.
The final output MUST be a comma-separated list of tags. No comments, no 'Here is:', no 'Let me know..'. Just a list of comma separated tags.`;
const DEFAULT_CAPTION_PROMPT = `You are an expert for creating photorealistic AI training datasets. Your task is to generate descriptive caption for the provided image for the purpose of Lora training using tools like kohya_ss, OneTrainer or diffusion pipes. Follow these rules strictly:
1. Information sufficiency: Captions should include all meaningful content and be comprehensive, especially for complex scenes that may be overlooked by general captions.
2. Minimal redundancy: Captions should be concise and avoid unnecessary repetition of information.
3. Human comprehensibility: Captions should be phrased naturally using correct spelling, grammar, and punctuation to be easily understood by humans.
4. Grounded descriptions: For more specific tasks, provide region-specific captions that describe a particular area of the image defined by a bounding box, rather than just the general scene.
5. Variety: Ensure a diverse set of captions for each image, including both general descriptions and more detailed ones, to provide richer training data.
Expected outcome is a human-readable continuous text consisting of several sentences without the use of numbering or bullet points.`;
const TEXT_MODEL_IDS = ['gemini', 'grok', 'openai', 'claude', 'vllm'];
const TAG_MODEL_IDS = [...TEXT_MODEL_IDS, 'deepdanbooru', 'wd14'];
const API_KEY_MODEL_IDS = [...TEXT_MODEL_IDS, 'wd14'];
const DEEPDANBOORU_API_BASE = 'https://hysts-deepdanbooru.hf.space/gradio_api';
const VLLM_DEFAULT_MODEL = 'Qwen/Qwen3-8B';
const VLLM_MODEL_PRESETS = [
'Qwen/Qwen2.5-VL-3B-Instruct',
'Qwen/Qwen2.5-VL-7B-Instruct',
'Qwen/Qwen3-VL-4B-Instruct',
'Qwen/Qwen3-VL-8B-Instruct',
'Qwen/Qwen3.5-9B-Instruct',
'google/gemma-3-4b-it',
'google/gemma-3-12b-it',
'mistralai/Pixtral-12B-2409',
'mistralai/Mistral-Small-3.1-24B-Instruct-2503'
];
const CROP_ASPECT_RATIOS = {
'1:1': 1,
'16:9': 16 / 9,
'3:2': 3 / 2,
'4:3': 4 / 3,
'21:9': 21 / 9,
'9:16': 9 / 16,
'2:3': 2 / 3,
'3:4': 3 / 4
};
// DOM elements
const settingsIcon = document.getElementById('settings-icon');
const settingsModal = document.getElementById('settingsModal');
const closeSettingsBtn = document.getElementById('closeSettings');
const tagDefaultModel = document.getElementById('tag-default-model');
const captionDefaultModel = document.getElementById('caption-default-model');
const cropAspectRatioSelect = document.getElementById('crop-aspect-ratio');
const cropWidthInput = document.getElementById('crop-width');
const apiKeyInputs = {
gemini: document.getElementById('api-key-gemini'),
grok: document.getElementById('api-key-grok'),
openai: document.getElementById('api-key-openai'),
claude: document.getElementById('api-key-claude'),
vllm: document.getElementById('api-key-vllm'),
wd14: document.getElementById('api-key-wd14')
};
const vllmEndpointInput = document.getElementById('vllm-endpoint');
const vllmModelPresetSelect = document.getElementById('vllm-model-preset');
const vllmModelTypeInput = document.getElementById('vllm-model-type');
const ddThreshold = document.getElementById('ddThreshold');
const wdGeneralThresh = document.getElementById('wdGeneralThresh');
const wdCharThresh = document.getElementById('wdCharThresh');
const saveSettingsBtn = document.getElementById('saveSettings');
const imageUpload = document.getElementById('image-upload');
const zipUpload = document.getElementById('zip-upload');
const imageGrid = document.getElementById('image-grid');
const placeholder = document.getElementById('placeholder');
const taggerSection = document.getElementById('tagger-section');
const exportButton = document.getElementById('export-button');
const resetButton = document.getElementById('reset-button');
const clearTagsButton = document.getElementById('clear-tags-button');
const tagAllButton = document.getElementById('tag-all-button');
const captionAllButton = document.getElementById('caption-all-button');
const datasetNameInput = document.getElementById('dataset-name-input');
const triggerWordInput = document.getElementById('trigger-word-input');
const datasetNameLabel = document.getElementById('dataset-name-label');
const triggerWordLabel = document.getElementById('trigger-word-label');
const loader = document.getElementById('loader');
const loaderText = document.getElementById('loader-text');
const previewModal = document.getElementById('preview-modal');
const previewImage = document.getElementById('preview-image');
const previewClose = document.getElementById('preview-close');
const previewCropButton = document.getElementById('preview-crop');
const notification = document.getElementById('notification');
const notificationText = document.getElementById('notification-text');
const tagViewerSection = document.getElementById('tag-viewer-section');
const tagViewerHeader = document.getElementById('tag-viewer-header');
const tagViewerContent = document.getElementById('tag-viewer-content');
const tagViewerList = document.getElementById('tag-viewer-list');
const tagViewerArrow = document.getElementById('tag-viewer-arrow');
const totalTagsBadge = document.getElementById('total-tags-badge');
const tagSettingsModal = document.getElementById('tag-settings-modal');
const tagSettingsConfig = document.getElementById('tag-settings-config');
const tagSettingsProgress = document.getElementById('tag-settings-progress');
const startTaggingBtn = document.getElementById('start-tagging-btn');
const cancelTaggingBtn = document.getElementById('cancel-tagging-btn');
const stopTaggingBtn = document.getElementById('stop-tagging-btn');
const settingMaxTags = document.getElementById('setting-max-tags');
const tagProgressBar = document.getElementById('tag-progress-bar');
const tagProgressText = document.getElementById('tag-progress-text');
const tagSystemPrompt = document.getElementById('tag-system-prompt');
const captionSettingsModal = document.getElementById('caption-settings-modal');
const captionSettingsConfig = document.getElementById('caption-settings-config');
const captionSettingsProgress = document.getElementById('caption-settings-progress');
const startCaptioningBtn = document.getElementById('start-captioning-btn');
const cancelCaptioningBtn = document.getElementById('cancel-captioning-btn');
const stopCaptioningBtn = document.getElementById('stop-captioning-btn');
const settingMaxCaptionLen = document.getElementById('setting-max-caption-len');
const captionProgressBar = document.getElementById('caption-progress-bar');
const captionProgressText = document.getElementById('caption-progress-text');
const captionSystemPrompt = document.getElementById('caption-system-prompt');
const cropModal = document.getElementById('crop-modal');
const cropImage = document.getElementById('crop-image');
const cropSaveButton = document.getElementById('crop-save');
const cropCancelButton = document.getElementById('crop-cancel');
loadSettingsValues();
// Event listeners
settingsIcon.addEventListener('click', openSettings);
closeSettingsBtn.addEventListener('click', closeSettings);
saveSettingsBtn.addEventListener('click', saveSettings);
Object.values(apiKeyInputs).forEach(input => input.addEventListener('input', updateSettingsFields));
vllmModelPresetSelect.addEventListener('change', applyVllmModelPreset);
vllmModelTypeInput.addEventListener('input', syncVllmModelPreset);
imageUpload.addEventListener('change', handleImageUpload);
zipUpload.addEventListener('change', handleZipUpload);
exportButton.addEventListener('click', handleExport);
resetButton.addEventListener('click', handleReset);
clearTagsButton.addEventListener('click', handleClearTags);
tagAllButton.addEventListener('click', openTagSettings);
captionAllButton.addEventListener('click', openCaptionSettings);
startTaggingBtn.addEventListener('click', startBatchTagging);
cancelTaggingBtn.addEventListener('click', closeTagSettings);
stopTaggingBtn.addEventListener('click', stopBatchProcessing);
startCaptioningBtn.addEventListener('click', startBatchCaptioning);
cancelCaptioningBtn.addEventListener('click', closeCaptionSettings);
stopCaptioningBtn.addEventListener('click', stopBatchProcessing);
previewClose.addEventListener('click', hidePreview);
previewCropButton.addEventListener('click', cropPreviewImage);
triggerWordInput.addEventListener('input', handleTriggerWordInput);
datasetNameInput.addEventListener('input', updateInputPrefixLabels);
updateInputPrefixLabels();
tagViewerHeader.addEventListener('click', () => {
tagViewerContent.classList.toggle('expanded');
tagViewerArrow.classList.toggle('expanded');
});
previewModal.addEventListener('click', (e) => e.target === previewModal && hidePreview());
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
hidePreview();
cancelCrop();
if (!isBatchProcessing) {
closeTagSettings();
closeCaptionSettings();
}
}
});
cropSaveButton.addEventListener('click', saveCrop);
cropCancelButton.addEventListener('click', cancelCrop);
// Settings functions
function isTagModel(model) {
return TAG_MODEL_IDS.includes(model);
}
function isCaptionModel(model) {
return TEXT_MODEL_IDS.includes(model);
}
function getSavedTagModel() {
const saved = localStorage.getItem('tagModel');
if (isTagModel(saved)) return saved;
const legacy = localStorage.getItem('selectedModel');
if (isTagModel(legacy)) return legacy;
return 'gemini';
}
function getSavedCaptionModel() {
const saved = localStorage.getItem('captionModel');
if (isCaptionModel(saved)) return saved;
const legacy = localStorage.getItem('selectedModel');
if (isCaptionModel(legacy)) return legacy;
return 'gemini';
}
function getSavedCropAspectRatio() {
const saved = localStorage.getItem('cropAspectRatio') || 'freeform';
return saved === 'freeform' || Object.prototype.hasOwnProperty.call(CROP_ASPECT_RATIOS, saved) ? saved : 'freeform';
}
function getProviderKeyStorageName(model) {
return model === 'wd14' ? 'wd14ApiKey' : `${model}ApiKey`;
}
function updateSettingsFields() {
API_KEY_MODEL_IDS.forEach(model => {
const status = document.querySelector(`[data-key-status='${model}']`);
if (!status) return;
const hasKey = Boolean(apiKeyInputs[model]?.value.trim());
status.textContent = hasKey ? 'Saved' : 'Not saved';
status.classList.toggle('text-teal-400', hasKey);
status.classList.toggle('text-gray-500', !hasKey);
});
}
function loadSettingsValues() {
tagDefaultModel.value = getSavedTagModel();
captionDefaultModel.value = getSavedCaptionModel();
settingMaxTags.value = localStorage.getItem('settingMaxTags') || '30';
settingMaxCaptionLen.value = localStorage.getItem('settingMaxCaptionLen') || '50';
cropAspectRatioSelect.value = getSavedCropAspectRatio();
cropWidthInput.value = localStorage.getItem('cropWidth') || '1024';
tagSystemPrompt.value = localStorage.getItem('tagSystemPrompt') || DEFAULT_TAG_PROMPT;
captionSystemPrompt.value = localStorage.getItem('captionSystemPrompt') || DEFAULT_CAPTION_PROMPT;
vllmEndpointInput.value = localStorage.getItem('vllmEndpoint') || '';
vllmModelTypeInput.value = localStorage.getItem('vllmModelType') || VLLM_DEFAULT_MODEL;
syncVllmModelPreset();
ddThreshold.value = localStorage.getItem('ddThreshold') || '0.5';
wdGeneralThresh.value = localStorage.getItem('wdGeneralThresh') || '0.35';
wdCharThresh.value = localStorage.getItem('wdCharThresh') || '0.85';
API_KEY_MODEL_IDS.forEach(model => {
apiKeyInputs[model].value = localStorage.getItem(getProviderKeyStorageName(model)) || '';
});
updateSettingsFields();
}
function applyVllmModelPreset() {
if (vllmModelPresetSelect.value) {
vllmModelTypeInput.value = vllmModelPresetSelect.value;
}
}
function syncVllmModelPreset() {
const modelType = vllmModelTypeInput.value.trim();
vllmModelPresetSelect.value = VLLM_MODEL_PRESETS.includes(modelType) ? modelType : '';
}
function openSettings() {
settingsModal.style.display = 'flex';
loadSettingsValues();
}
function closeSettings() {
settingsModal.style.display = 'none';
}
function saveSettings() {
localStorage.setItem('tagModel', tagDefaultModel.value);
localStorage.setItem('captionModel', captionDefaultModel.value);
localStorage.setItem('selectedModel', tagDefaultModel.value);
API_KEY_MODEL_IDS.forEach(model => {
localStorage.setItem(getProviderKeyStorageName(model), apiKeyInputs[model].value.trim());
});
localStorage.setItem('settingMaxTags', settingMaxTags.value);
localStorage.setItem('settingMaxCaptionLen', settingMaxCaptionLen.value);
localStorage.setItem('cropAspectRatio', cropAspectRatioSelect.value);
localStorage.setItem('cropWidth', String(getCropWidth()));
localStorage.setItem('tagSystemPrompt', tagSystemPrompt.value.trim());
localStorage.setItem('captionSystemPrompt', captionSystemPrompt.value.trim());
localStorage.setItem('vllmEndpoint', vllmEndpointInput.value.trim());
localStorage.setItem('vllmModelType', vllmModelTypeInput.value.trim() || VLLM_DEFAULT_MODEL);
localStorage.setItem('ddThreshold', ddThreshold.value);
localStorage.setItem('wdGeneralThresh', wdGeneralThresh.value);
localStorage.setItem('wdCharThresh', wdCharThresh.value);
updateSettingsFields();
closeSettings();
showNotification('Settings saved');
}
function getTagModel() { return isTagModel(tagDefaultModel.value) ? tagDefaultModel.value : getSavedTagModel(); }
function getCaptionModel() { return isCaptionModel(captionDefaultModel.value) ? captionDefaultModel.value : getSavedCaptionModel(); }
function getModel() { return getTagModel(); }
function getApiKey(model = getModel()) { return localStorage.getItem(getProviderKeyStorageName(model)) || ''; }
function getWDKey() { return getApiKey('wd14'); }
function getVllmModelType() { return localStorage.getItem('vllmModelType') || VLLM_DEFAULT_MODEL; }
function getVllmEndpoint() {
const endpoint = (localStorage.getItem('vllmEndpoint') || '').trim();
if (!endpoint) throw new Error('vLLM endpoint URL required');
return normalizeVllmEndpoint(endpoint);
}
function normalizeVllmEndpoint(endpoint) {
const trimmed = endpoint.replace(/\/+$/, '');
if (/\/v1\/chat\/completions$/.test(trimmed)) return trimmed;
if (/\/v1$/.test(trimmed)) return `${trimmed}/chat/completions`;
return `${trimmed}/v1/chat/completions`;
}
function getIntegerSetting(input, fallback, min, max) {
const parsed = parseInt(input.value, 10);
if (!Number.isFinite(parsed)) return fallback;
return Math.min(max, Math.max(min, parsed));
}
function getTagLimit() {
return getIntegerSetting(settingMaxTags, 30, 1, 100);
}
function getCaptionWordLimit() {
return getIntegerSetting(settingMaxCaptionLen, 50, 5, 200);
}
function getCropWidth() {
return getIntegerSetting(cropWidthInput, 1024, 64, 8192);
}
function getCropAspectRatio() {
return CROP_ASPECT_RATIOS[cropAspectRatioSelect.value] || NaN;
}
function getCropCanvasOptions() {
const width = getCropWidth();
const aspectRatio = getCropAspectRatio();
if (Number.isFinite(aspectRatio)) {
return { width, height: Math.round(width / aspectRatio) };
}
if (cropper && typeof cropper.getData === 'function') {
const cropData = cropper.getData();
if (cropData?.width > 0 && cropData?.height > 0) {
return { width, height: Math.round(width * cropData.height / cropData.width) };
}
}
return { width };
}
function getPromptValue(input, fallback) {
return input.value.trim() || fallback;
}
function buildTagPrompt(maxTags) {
return `${getPromptValue(tagSystemPrompt, DEFAULT_TAG_PROMPT)}
Limit the output to ${maxTags} comma-separated tags or fewer.`;
}
function buildCaptionPrompt(maxWords) {
return `${getPromptValue(captionSystemPrompt, DEFAULT_CAPTION_PROMPT)}
Limit the caption to ${maxWords} words or fewer.`;
}
function trimCaptionToWordLimit(text, maxWords) {
const words = text.trim().split(/\s+/).filter(Boolean);
if (words.length <= maxWords) return text.trim();
return words.slice(0, maxWords).join(' ');
}
function buildResponsesVisionInput(promptText, imageUrl) {
return [{
role: 'user',
content: [
{ type: 'input_text', text: promptText },
{ type: 'input_image', image_url: imageUrl, detail: 'high' }
]
}];
}
function extractResponsesText(data) {
if (typeof data.output_text === 'string') return data.output_text.trim();
const parts = [];
(data.output || []).forEach(item => {
(item.content || []).forEach(content => {
if (typeof content.text === 'string') parts.push(content.text);
});
});
return parts.join('\n').trim();
}
function extractClaudeText(data) {
return (data.content || [])
.filter(part => part.type === 'text' && typeof part.text === 'string')
.map(part => part.text)
.join('\n')
.trim();
}
function extractChatCompletionText(data) {
const content = data?.choices?.[0]?.message?.content;
if (typeof content === 'string') return content.trim();
if (Array.isArray(content)) {
return content
.map(part => typeof part.text === 'string' ? part.text : '')
.join('\n')
.trim();
}
return '';
}
function getImageMimeType(file) {
if (file.type && file.type.startsWith('image/')) return file.type;
const name = (file.name || '').toLowerCase();
if (name.endsWith('.jpg') || name.endsWith('.jpeg')) return 'image/jpeg';
if (name.endsWith('.webp')) return 'image/webp';
if (name.endsWith('.gif')) return 'image/gif';
return 'image/png';
}
function getFileUploadName(file) {
return file?.name || 'image.png';
}
function createResponsesProvider(name, endpoint, modelName) {
return {
name,
async request({ apiKey, promptText, base64 }) {
const resp = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` },
body: JSON.stringify({
model: modelName,
input: buildResponsesVisionInput(promptText, base64),
max_output_tokens: 300,
store: false
})
});
const data = await readProviderJson(resp, name);
return extractResponsesText(data);
}
};
}
const TEXT_PROVIDERS = {
gemini: {
name: 'Gemini',
async request({ apiKey, promptText, imageData, imageMimeType }) {
const resp = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-flash-lite:generateContent?key=${apiKey}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contents: [{ parts: [
{ text: promptText },
{ inline_data: { mime_type: imageMimeType, data: imageData } }
] }]
})
});
const data = await readProviderJson(resp, 'Gemini');
return data.candidates[0].content.parts[0].text;
}
},
grok: createResponsesProvider('Grok', 'https://api.x.ai/v1/responses', 'grok-4.3'),
openai: createResponsesProvider('OpenAI', 'https://api.openai.com/v1/responses', 'gpt-5.4-mini'),
claude: {
name: 'Claude',
async request({ apiKey, promptText, imageData, imageMimeType }) {
const resp = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': apiKey,
'anthropic-version': '2023-06-01',
'anthropic-dangerous-direct-browser-access': 'true'
},
body: JSON.stringify({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 300,
messages: [{
role: 'user',
content: [
{
type: 'image',
source: {
type: 'base64',
media_type: imageMimeType,
data: imageData
}
},
{ type: 'text', text: promptText }
]
}]
})
});
const data = await readProviderJson(resp, 'Claude');
return extractClaudeText(data);
}
},
vllm: {
name: 'vLLM',
async request({ apiKey, promptText, base64 }) {
const resp = await fetch(getVllmEndpoint(), {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` },
body: JSON.stringify({
model: getVllmModelType(),
messages: [{
role: 'user',
content: [
{ type: 'text', text: promptText },
{ type: 'image_url', image_url: { url: base64 } }
]
}],
max_tokens: 300
})
});
const data = await readProviderJson(resp, 'vLLM');
return extractChatCompletionText(data);
}
}
};
function getTextProviderIds() {
return Object.keys(TEXT_PROVIDERS);
}
function isTextProvider(model) {
return Object.prototype.hasOwnProperty.call(TEXT_PROVIDERS, model);
}
function getTextProvider(model) {
const provider = TEXT_PROVIDERS[model];
if (!provider) throw new Error(`Unsupported provider: ${model}`);
return provider;
}
function getProviderName(model) {
if (TEXT_PROVIDERS[model]) return TEXT_PROVIDERS[model].name;
return model;
}
function extractApiErrorMessage(data) {
if (!data) return 'Request failed';
if (typeof data.error === 'string') return data.error;
if (typeof data.error?.message === 'string') return data.error.message;
if (typeof data.message === 'string') return data.message;
return 'Request failed';
}
async function readProviderJson(resp, providerName) {
let data = null;
try {
data = await resp.json();
} catch (error) {
if (resp.ok) throw error;
}
if (!resp.ok) {
throw new Error(`${providerName} API error ${resp.status}: ${extractApiErrorMessage(data)}`);
}
return data;
}
function getDeepDanbooruThreshold() {
const threshold = parseFloat(localStorage.getItem('ddThreshold') || '0.5');
if (!Number.isFinite(threshold)) return 0.5;
return Math.min(1, Math.max(0, threshold));
}
async function fetchDeepDanbooru(path, options) {
try {
return await fetch(`${DEEPDANBOORU_API_BASE}${path}`, options);
} catch (error) {
throw new Error('DeepDanbooru request failed. The public Hugging Face Space may be unavailable.');
}
}
function parseDeepDanbooruSse(text) {
const blocks = String(text || '').trim().split(/\r?\n\r?\n/).filter(Boolean);
const completeBlock = blocks.find(block => block.split(/\r?\n/).some(line => line.trim() === 'event: complete'));
if (!completeBlock) throw new Error('DeepDanbooru returned no completed result');
const dataText = completeBlock
.split(/\r?\n/)
.filter(line => line.startsWith('data:'))
.map(line => line.replace(/^data:\s?/, ''))
.join('\n');
if (!dataText) throw new Error('DeepDanbooru returned no tag data');
return JSON.parse(dataText);
}
function extractDeepDanbooruTags(output, threshold) {
const confidences = output?.[0]?.confidences;
if (Array.isArray(confidences)) {
return formatTags(confidences
.filter(item => Number(item.confidence) >= threshold)
.map(item => item.label));
}
const scoreMap = output?.[1];
if (scoreMap && typeof scoreMap === 'object' && !Array.isArray(scoreMap)) {
return formatTags(Object.entries(scoreMap)
.filter(([, confidence]) => Number(confidence) >= threshold)