-
Notifications
You must be signed in to change notification settings - Fork 5
/
viewer.html
executable file
·2632 lines (2280 loc) · 96.9 KB
/
viewer.html
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>
<!--
Fooocus Log Viewer
Github repository
https://github.com/toutjavascript/Fooocus-Log-Viewer
https://github.com/lllyasviel/Fooocus/discussions/693#discussioncomment-7853694
Created by https://github.com/sngazm
Modestly updated by https://github.com/toutjavascript
https://www.toutjavascript.com
File Version 2024-02-19/A1
-->
<html lang="us">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Viewer:Fooocus Log Viewer</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css" rel="stylesheet" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script>
<script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsdiff/5.1.0/diff.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/gh/StephanWagner/[email protected]/dist/jBox.all.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/gh/StephanWagner/[email protected]/dist/jBox.all.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@honatas/multi-select-webcomponent/dist/multi-select-webcomponent.min.js" crossorigin="anonymous"></script>
</head>
<body class="text-white">
<div id="app"></div>
<script type="text/babel">
var LOGVIEWER_RELEASE="1.5.6"
$("span#logviewer-release").html("Release "+LOGVIEWER_RELEASE)
window.customElements.define('multi-select', MultiselectWebcomponent);
var configs=[
{item: "autoReloadToday", type: "checkbox", label: "Auto Reload (only on today page)", value: false},
{item: "workingDates", type: "text", label: "Working Dates", value: ""},
{item: "playSound", type: "checkbox", label: "Play Sound when new Image is detected", value: true},
{item: "soundFile", type: "text", label: "Sound File", value: "https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"},
{item: "viewerDate", type: "text", label: "Start Date", value: ""},
{item: "displayDiff", type:"checkbox", label:"Display Differences between batches", value: false},
{item: "displayDetails", type:"checkbox", label:"View Batch Prompt Details", value: true},
{item: "displayMetaBlock", type:"checkbox", label:"View Meta Detail on Zoomed Image", value: true},
{item: "nbColumns", type:"integer", label:"Number of columns in the grid", value: 3},
{item: "nbImagePerPage", type:"integer", label:"Number of images displayed per page", value: 32},
];
var nbDaysToScan=250; /* Number of days to scan for working dates befor today */
var workingDates=[], detailDates=[];
var allBatches=[], allModels=[], allStyles=[], allImages=[];
var nbImageNotFoundByBatches=[]; /* Number of images not found by batch (deleted by user) : use to display on each batch block */
var searchResults=[]; /* Array of images found by searchBox */
var nbImageNotFoundBySearch=0; /* Number of images not found on search via searchBox */
var modeSearch=false; /* Flag that indicates if searchBox is active */
var promiseAll=false; /* Flag that indicates if all images are loaded: calendar and search button could be active */
var searchPaginationPage=0; /* Actual Pagination page for search results */
var searchPaginationNbImage=60; /* Number of images per page for search results */
function getParam(item) {
return localStorage.getItem(item);
}
function saveParam(item, value) {
localStorage.setItem(item, value);
}
/* Load configurations and localStorage on App init */
function loadConfig() {
setTimeout(checkNewImage, 1000);
}
function goPlaySound() {
if (localStorage.getItem("playSound")=="true") {
var audio =new Audio("https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3");
audio.play();
}
}
/* Detection of new Image on today folder */
var nbTodayImages=0;
function checkNewImage() {
let today=new Date(); today=today.toISOString().substr(0,10);
fetch(`./${today}/log.html`, { cache: "no-store" })
.then(function(response) {
return response.text();
})
.then((text) => {
let matches=text.match(/<div id=\"([a-z0-9_\-])+\"/g);
let nb=((matches|| []).length);
if ((nb>nbTodayImages)&&(nbTodayImages>0)) {
let n=nbTodayImages-nb;
matches.sort();
let src=matches[matches.length-1].replace('<div id="',"").replace("_png",".png").replace("_jpg",".jpg").replace("_jpeg",".jpeg").replace("_webp",".webp").replace('"',"");
new jBox('Notice', {
content: "Yeah! "+n+" new Image"+(n>1?'s':'')+" generated now on today folder<br><img src='./"+today+"/"+src+"' class='imageNotice'>",
theme: "TooltipNewImage"
});
goPlaySound();
}
nbTodayImages=nb;
/* Update calendar */
/* Check if today is in workingDates */
if (nbTodayImages>0) {
if (workingDates.includes(today)) {
detailDates[today]=nb;
} else {
/* Add today at 0 index to workingDates*/
workingDates.unshift(today);
detailDates[today]=nb;
}
toggleCalendar(); toggleCalendar(); /* Update div#calendarList*/
/* Reprocess of today log.html */
var newData=parseLog(text);
/* Remove all images where image.dt=today from allImages */
for (let i=0; i<allImages.length; i++) {
if (allImages[i].dt==today) {
allImages.splice(i,1);
i--;
}
}
/* Re-add today images to allImages */
for (let i=newData.data.length-1; i>=0; i--) {
let img=newData.data[i];
img.dt=today;
if (allModels.includes(img["Base Model"])==false) {
allModels.push(img["Base Model"]);
}
img.styles=[];
if (img.Styles!="[]") {
let reg=new RegExp("(')", "g");
if (img.Styles) img.styles=img.Styles.replace("[","").replace(reg,"").replace("]","").split(", ");
}
for (let j=0; j<img.styles.length; j++) {
if (allStyles.includes(img.styles[j])==false) {
allStyles.push(img.styles[j]);
}
}
allImages.unshift(img);
}
/* if mode Search active, refresh search box display */
if (modeSearch) {
goSearch(false);
}
}
setTimeout(checkNewImage, 5000);
});
}
/* Create an empty image
Update batch label error
*/
function getNotFoundImg(batchNumber) {
if (typeof nbImageNotFoundByBatches[batchNumber]=="undefined") {
nbImageNotFoundByBatches[batchNumber]=0;
}
nbImageNotFoundByBatches[batchNumber]++;
$("span#batchNumber-"+batchNumber).html(" / "+nbImageNotFoundByBatches[batchNumber]+" not found").attr("title", "Probably deleted by user");
/* Generate image not found */
let svgElement = document.createElementNS("http://www.w3.org/2000/svg", 'svg'); // Create a new SVG element
svgElement.setAttribute('width', '500'); // Set the width and height of the SVG canvas
svgElement.setAttribute('height', '500');
let rect = document.createElementNS("http://www.w3.org/2000/svg", 'rect'); // Create a new <rect> element to represent border
rect.setAttribute('x', 2); // Position the rectangle at (50,50) on the SVG canvas
rect.setAttribute('y', 2);
rect.setAttribute('width', '492'); // Set width and height of the rectangle to cover entire SVG area
rect.setAttribute('height', '492');
rect.style.fill = 'none'; // Set fill color of the rectangle to none (transparent)
rect.style.stroke = '#aaa'; // Set stroke color of the rectangle
rect.style.strokeWidth = '4'; // Set width of the border
svgElement.appendChild(rect); // Append the <rect> element to the SVG canvas
let text = document.createElementNS("http://www.w3.org/2000/svg", 'text'); // Create a new <text> element for "Not Found"
text.setAttribute('x', 60); // Position the text at (50,50) on the SVG canvas
text.setAttribute('y', 250);
text.style.fontSize = '48'; // Set the font size of the text
text.style.fill = '#aaa'; // Set the color of the text
text.innerHTML = "Image Not Found"; // Set the content of the <text> element to "Not Found"
svgElement.appendChild(text); // Append the <text> element to the SVG canvas
// Serialize the SVG to a string
let serializer = new XMLSerializer();
let svgString = serializer.serializeToString(svgElement);
// Convert the SVG string to a data URL
let svgDataUrl = 'data:image/svg+xml,' + encodeURIComponent(svgString);
return svgDataUrl;
}
function App() {
const [date, setDate] = React.useState(() => {
const date = localStorage.getItem("viewerDate")
? new Date(localStorage.getItem("viewerDate"))
: new Date();
return date;
});
const [data, setData] = React.useState([]);
const [isLoading, setIsLoading] = React.useState(false);
const [isCorsError, setIsCorsError] = React.useState(false);
const [isNotFoundError, setIsNotFoundError] = React.useState(false);
const [playSound, setPlaySound] = React.useState(false);
const [autoReload, setAutoReload] = React.useState(() => {
const autoReload = localStorage.getItem("autoReload")
? localStorage.getItem("autoReload") == "true"
: false;
return autoReload;
});
React.useEffect(() => {
localStorage.setItem("autoReload", autoReload.toString());
}, [autoReload]);
const isToday = date.toDateString() === new Date().toDateString();
const dateStr = getDateStr(date);
const handleUpdateDate = (dateStr) => {
const [year, month, day] = dateStr
.split("-")
.map((str) => parseInt(str));
setDate(new Date(year, month - 1, day));
};
/* Use the workingDates array to navigate directly to a date with images */
const getWorkingDate = (dt, way) => {
let dtComp=dt.toISOString().substr(0,10);
console.log("getWorkingDate("+dt+","+way+")")
if (workingDates.length>0) {
if (way>0) {
for (let i=workingDates.length-1; i>=0; i--) {
console.log(i+" workingDates[i]="+workingDates[i])
if (workingDates[i]>=dtComp) {
console.log("ok")
return new Date(workingDates[i])
}
}
} else {
for (let i=0; i<workingDates.length; i++) {
if (workingDates[i]<=dtComp) {return new Date(workingDates[i])}
}
}
}
return dt;
}
const goTomorrow = () => {
const tomorrow = new Date(date);
tomorrow.setDate(tomorrow.getDate() + 1);
setDate(getWorkingDate(tomorrow, 1));
};
const goYesterday = () => {
const yesterday = new Date(date);
yesterday.setDate(yesterday.getDate() - 1);
setDate(getWorkingDate(yesterday, -1));
};
const goDate0 = (e) => {
console.log("goDate("+e.target.value+")");
const day = new Date(e.target.value);
console.log("day="+day);
day.setDate(day.getDate());
console.log("day="+day);
setDate(day);
}
const goDate = (e) => {
console.log("goDate("+e.target.value+")");
// Changed the direct entry into Date with a split version of the date string broken by year, month, day
let wd_sp = e.target.value.split("-"); // split date into its parts
const day = new Date(parseInt(wd_sp[0]), parseInt(wd_sp[1])-1, parseInt(wd_sp[2])); // loading parts directly in Date object
console.log("day="+day);
day.setDate(day.getDate());
console.log("day="+day);
setDate(day);
}
const fetchData = () => {
if (!isToday) {
setAutoReload(false);
}
localStorage.setItem("viewerDate", date.toDateString());
setIsLoading(true);
fetch(`./${dateStr}/log.html`, { cache: "no-store" })
.then((response) => {
if (!response.ok) {
console.log(`Nothing to load on ${dateStr}`);
}
return response.text()
})
.then((text) => parseLog(text))
.then((data) => {
const newData = data.data;
console.log("newData: ", newData);
setData(newData);
setIsNotFoundError(false);
setIsCorsError(false);
setIsLoading(false);
})
.catch((e) => {
// CORS error
// console.error(e);
//console.log(e)
//console.log(`Nothing to load on ${dateStr}`);
if (e.name === "TypeError") {
setIsCorsError(true);
}
if (e.name === "SyntaxError") {
setIsNotFoundError(true);
}
setData(null);
setIsLoading(false);
});
};
React.useEffect(fetchData, [date]);
React.useEffect(() => {
if (autoReload) {
const interval = setInterval(() => {
fetchData();
}, 15000);
return () => clearInterval(interval);
}
}, [autoReload]);
return (
<div className="pb-2">
<div className="px-1 py-0">
<button id="config" onClick={() => viewConfig() }
className={ (window.location.href.indexOf("#debug")>0) ? "px-2 mx-2 text-xl " : "px-2 mx-2 text-xl hidden" }
type="text"
>
⚙
</button>
<span class="smartphoneHidden">Fooocus Log Viewer</span>
<button className="px-2 mx-2 text-xl" onClick={() => goYesterday()}>
◀️
</button>
<input id="inputDay"
className="text-gray-900"
type="date"
value={dateStr}
onChange={(e) => {
handleUpdateDate(e.target.value);
}}
/>
<button className="px-2 mx-2 text-xl" onClick={() => {
goTomorrow();
}}
>
▶️
</button>
<input id="changeCalendar"
className="hidden"
type="text"
onClick={(e) => {
console.log(e);
goDate(e);
}}
/>
<button id="config" onClick={() => viewSearchBox() }
className="px-2 mx-2 text-xl "
type="text"
>
🔍
</button>
<div id="calendar" class="px-2 text-2xl cursor-pointer" title="Show list of all working days"> 📅 </div>
<label>
Sound on new Image:
<input
class="ml-1 mr-3"
type="checkbox"
checked={playSound}
onChange={() => {
console.log("onchange playSound");
setPlaySound(!playSound);
saveParam("playSound", !playSound);
}}
/>
</label>
{isToday ? (
<>
<label>
{isLoading ? (
<span className="text-gray-500">Loading...</span>
) : (
"AutoReload:"
)}
<input
class="ml-1 mr-3"
type="checkbox"
checked={autoReload}
onChange={() => {
if (!autoReload) {
fetchData();
}
setAutoReload(!autoReload);
saveParam("autoReloadToday", !autoReload);
}}
/>
</label>
</>
) : (
isLoading && <span className="text-gray-500">Loading...</span>
)}
</div>
<div id="searchBox" class="px-2 pt-2 pb-1"></div>
<div id="calendarList" class="px-2 pt-2 pb-1"></div>
{!isLoading && (
<>
{isCorsError && (
<p className="text-center m-16">
Put this viewer.html file in Fooocus/outputs directory
<br />
<br />
Please access viewer.html from your Fooocus local server.{" "}<br />
In most cases, the URL is{" "}<br />
<button class="p-2 shadow-sm bg-purple-500 rounded-md"><a href="http://localhost:7860/file=outputs/viewer.html">
http://localhost:7860/file=outputs/viewer.html
</a></button>{" "}
<br /><br />
or
<br /><br />
<a class="p-2 shadow-sm bg-purple-500 rounded-md" href="http://localhost:7865/file=outputs/viewer.html">
http://localhost:7865/file=outputs/viewer.html
</a>
<br /><br /><br /><br />
</p>
)}
{isNotFoundError && (
<p className="text-center m-16">
{dateStr}/all.json Not found.
</p>
)}
</>
)}
{data && data.length > 0 ? (
<ImageViewer dateStr={dateStr} data={data} />
) : (
<div>
<p className="text-center m-16">No data in this folder</p>
<p className="text-center m-2">Looking for last folder with images. </p>
<p className="text-center m-2"><a class="p-2 shadow-sm bg-purple-500 rounded-md hidden cursor-pointer" id="nearestDate">Click to see the earliest generation date</a></p>
</div>
)}
</div>
);
}
/* Configuration block */
function saveConfig() {
/* Save the config in localStorage */
}
function deleteConfig() {
// Clears the entire local storage
localStorage.clear();
}
/* Activate the search mode */
function viewSearchBox() {
console.log("Start viewSearchBox()");
deleteMouseOverThumbnail();
if (!promiseAll) {
new jBox('Notice', {
content: "All logs and images are not processed. Please wait...",
theme: 'TooltipDark',
attributes: {x: "right", y: "bottom"},
offset: { x: 20, y: 45 }
});
return;
}
if (modeSearch) {
modeSearch=false;
$("div#searchBox").hide();
$("div#reactBox").show();
return;
} else {
modeSearch=true;
$("div#searchBox").show();
$("div#reactBox").hide();
$("div#calendarList").hide();
}
/* First opening */
if ($("div#searchBox").html()=="") {
let m="";
for (let i=0; i<allModels.length; i++) {
m+="<option value='"+allModels[i].replace(".safetensor","")+"'>"+allModels[i].replace(".safetensor","")+"</option>";
}
let s="";
for (let i=0; i<allStyles.length; i++) {
s+="<option value='"+allStyles[i]+"'>"+allStyles[i]+"</option>";
}
let html=`
<form name="formSearch" id='formSearch' class="p-1 rounded" onsubmit='return false' method="post">
<div class='text-center' ><strong>SearchBox Active : ${allImages.length} images in ${workingDates.length} outputs folders</strong></div>
<label>
Text in prompts (AND):
<input type='text' name='searchText' id='searchText' class='p-2' placeholder='Type text to search'>
</label>
<label>
Models (AND):
<multi-select name='searchModel' id='searchModel' class='p-1'
selecteditem="badge cursor-pointer bg-primary pt-1 m-1"
dropdown="border"
dropdownitem="p-1"
selectallbutton="btn btn-sm btn-light"
selectallbuttonspan="bi-check2-all text-success"
clearbutton="btn btn-sm btn-light"
clearbuttonspan="bi-x-circle text-danger">
${m}
</multi-select>
</label>
<label>
Styles (OR):
<multi-select name='searchStyle' id='searchStyle' class='p-1'
selecteditem="badge bg-primary pt-1 m-1"
dropdown="border"
dropdownitem="p-1"
selectallbutton="btn btn-sm btn-light"
selectallbuttonspan="bi-check2-all text-success"
clearbutton="btn btn-sm btn-light"
clearbuttonspan="bi-x-circle text-danger">
${s}
</multi-select>
</label>
<button class='text-lg bg-lime-500 hover:bg-lime-700 px-2 py-1.5 leading-5 rounded-md font-semibold text-white' onclick='return goSearch()'>Search</button>
<button class='text-lg bg-slate-500 hover:bg-slate-700 px-2 py-1.5 leading-5 rounded-md font-semibold text-white' onclick='viewSearchBox()'>Quit Search Mode</button>
</form>
<div id="resultBox" class="px-0 mt-1 "></div>
`;
$("div#searchBox").html(html);
}
}
/* Display all images with pagination */
function displaySearchResult() {
deleteMouseOverThumbnail();
nbImageNotFoundBySearch=0;
console.log("searchPaginationPage="+searchPaginationPage);
if (searchResults.length==0) {
$("div#resultBox").html("<div class='text-lg text-center m-5 p-5'>∅ No images found with this search options</div>");
} else {
let html="<div class='text-lg text-center'>Search results: "+searchResults.length+" images found <span id='nbImageNotFoundBySearch' class='batchError'></span></div>";
let pagination="";
if (searchResults.length>searchPaginationNbImage) {
let buttonPrevious="<button class='button-pagination text-lg bg-sky-500 hover:bg-sky-700 px-2 py-1.5 leading-5 rounded-md font-semibold text-white' onclick='searchPaginationPage--; displaySearchResult()'>Previous</button>";
if (searchPaginationPage==0) {
buttonPrevious="<button class='button-pagination text-lg bg-slate-500 px-2 py-1.5 leading-5 rounded-md font-semibold text-white' >Previous</button>";
}
let buttonNext="<button class='button-pagination text-lg bg-sky-500 hover:bg-sky-700 px-2 py-1.5 leading-5 rounded-md font-semibold text-white' onclick='searchPaginationPage++; displaySearchResult()'>Next</button>";
if (searchPaginationPage==Math.ceil(searchResults.length/searchPaginationNbImage)-1) {
buttonNext="<button class='button-pagination text-lg bg-slate-500 px-2 py-1.5 leading-5 rounded-md font-semibold text-white' >Next</button>";
}
let combo=`<select class="px-2" id="combo-pagination" onchange="searchPaginationPage=parseInt(this.options[this.selectedIndex].value); displaySearchResult()">`;
for (let i=0; i<Math.ceil(searchResults.length/searchPaginationNbImage); i++) {
combo+=`<option value="${i}" ${i==searchPaginationPage?"selected":""}>${i+1}</option>`;
}
combo+="</select>";
pagination=`<div class="flex flex-row justify-center text-base">
${buttonPrevious}
<span class="pagination">Page </span> ${combo} <span class="pagination"> of ${Math.ceil(searchResults.length/searchPaginationNbImage)}</span>
${buttonNext}
</div>`;
}
html+=pagination;
html+=`<div id="containerFilesX">
<div id="filesX" class="grid gap-1 p-1 grid-cols-${getParam("nbColumns")} imgViewer">`;
for (let i=(searchPaginationPage)*searchPaginationNbImage; i<Math.min(searchResults.length, (searchPaginationPage+1)*searchPaginationNbImage); i++) {
let data=searchResults[i];
let json=JSON.stringify(data).replace(/"/g, """);
html+=`
<div class="col p-1 imgViewer">
<img src="/file=outputs/${data.dt}/${data.src}"
loading="lazy"
alt="${data.src}"
class="responsive thumbnail cursor-zoom-in"
alt={data.src}
data-seed="${data.Seed}"
data-name="${data.src}"
data-json="${json}"
data-error="false"
onerror="errorImageSearch(this)"
onload="loadImageSearch(this, ${i}, ${searchResults.length})"
onmouseover="mouseOverThumbnailSearch(this)"
/>
<div class="fileName">${data.src}</div>
</div>`;
}
html+=`</div>
</div>`;
html+=pagination;
$("div#resultBox").html(html);
}
}
/* Search text in all prompts */
function goSearch(newSearch=true) {
deleteMouseOverThumbnail();
if (newSearch) { /* If refresh when new image detected, newSearch=false */
nbImageNotFoundBySearch=0;
searchPaginationPage=0;
}
let txt=document.forms["formSearch"].searchText.value.trim();
let models=document.querySelector("#searchModel").value;
let styles=document.querySelector("#searchStyle").value;
searchResults=[];
if ((txt=="")&&(models.length==0)&&(styles.length==0)) {
$("div#resultBox").html("<div class='text-lg text-center m-5 p-5'>∅ No search options selected</div>");
return false;
}
var reg=new RegExp("[ ,;]+", "g");
for (let i=0; i<allImages.length; i++) {
let found=false;
let img=allImages[i];
if (txt!="") {
var mots=txt.split(reg);
for (let j=0; j<mots.length; j++) {
if (img.Prompt.toLowerCase().indexOf(mots[j].toLowerCase().trim())>=0) {
found=true;
} else {
found=false;
break;
}
}
} else {
/* Check text: if empty, image is always found */
found=true;
}
/* Check Models (or) */
if ((models.length>0)&&(found)) {
found=false;
if (models.includes(img["Base Model"].replace(".safetensor",""))) {
found=true;
}
}
/* Check Styles (and) */
if ((styles.length>0)&&(found)) {
for (let j=0; j<styles.length; j++) {
if (!img.Styles.includes(styles[j])) {
/* If only one style is not in the image, it's not found */
found=false;
}
}
}
if (found) {
searchResults.push(img);
}
}
displaySearchResult();
return false;
}
function mouseOverThumbnailSearch(img) {
if (img.dataset.error=="false") {
deleteMouseOverThumbnail();
$('<div id="divIMGMeta">').css({
top: $(img).offset().top+'px',
left: $(img).offset().left+'px',
}).html('Metadatas: click to copy all')
.attr("title", "Click to copy MetaDatas to clipboard")
.on("click", function(evt) {
evt.stopPropagation();
$("div#divIMGMeta").addClass("flash");
copyMetadatatoClipboard(img.dataset.json);
})
.appendTo('body');
let format=reduce(img.dataset.width, img.dataset.height);
$('<div id="divIMGSize">').css({
top: ($(img).offset().top+$(img).height()-24)+'px',
left: $(img).offset().left+'px'
})
.html(img.dataset.width+"×"+img.dataset.height+" ("+format.join("/")+")"+" - "+(img.dataset.size>0?format_filesize(img.dataset.size):""))
.appendTo('body');
$('<div id="divIMGDownload">').css({
top: ($(img).offset().top+$(img).height()-42)+'px',
left: ($(img).offset().left+$(img).width()-34)+'px'
}).html('<button id="download" title="Click to download" class="text-2xl" style="display: inline-block; position: absolute; top: 10px; left: 1px; text-align: center;">⬇</button>')
.on("click", (evt) => {
evt.stopPropagation();
downloadImage(img.src, img.dataset.name)
.then(() => { console.log('The image has been downloaded'); })
.catch(err => {console.log('Error downloading image: ', err);});
})
.appendTo('body');
}
}
function loadImageSearch(image, index, max) {
image.setAttribute("data-index", index);
image.setAttribute("id", "img-load-detection-"+index);
/* Get images info width, height and filesize */
get_filesize(image.src, function(size) {
image.setAttribute("data-size", size);
});
let i=new Image();
i.src=image.src;
i.addEventListener("load", function() {
image.setAttribute("data-width", i.width)
image.setAttribute("data-height", i.height)
if ((typeof image.dataset.onclick == "undefined")&&(image.dataset.error=="false")) {
/* Add only one eventClickListener, necessary because multiple calls*/
/* Add only if image is not broken */
$(image).addClass("cursor-zoom-in").addClass("img-load-detection");
image.setAttribute("data-onclick", "1");
image.addEventListener("click", function(evt) {
zoomImage(evt.target);
})
$(image).on("mouseover", function(evt) {
});
}
});
}
function errorImageSearch(img) {
nbImageNotFoundBySearch++;
$("span#nbImageNotFoundBySearch").html("(but "+nbImageNotFoundBySearch+" images deleted by user)");
$(img).parent().hide();
}
function viewConfig() {
if ($("#configDiv").length>0) {
$("#configDiv").remove();
return;
}
let html="<div class='text-lg text-center'>Fooocus Log Viewer Configuration</div>";
for (let i=0; i<configs.length; i++) {
let config=configs[i];
if (config.type=="checkbox") {
html+="<div class='flex flex-row justify-between text-base'><label class='text-sm'>"+config.label+"</label>";
html+="<input type='checkbox' id='"+config.item+"' class='configItem' "+(localStorage.getItem(config.item)=="true" ? "checked" : "")+">";
html+="</div>";
}
if (config.type=="integer") {
html+="<div class='flex flex-row justify-between text-base'><label class='text-sm'>"+config.label+"</label>";
html+="<span type='text' id='"+config.item+"' class='' value=''>"+localStorage.getItem(config.item)+"</span>";
html+="</div>";
}
}
html+="<div class='flex flex-row justify-between'><button class='text-lg bg-red-500 hover:bg-red-700 px-2 py-1.5 leading-5 rounded-md font-semibold text-white m-1 bg-red-500 leading-5 rounded-md font-semibold text-white' onclick='viewConfig()'>Cancel</button> <button class='text-lg m-1 bg-sky-500 hover:bg-sky-700 px-2 py-1.5 leading-5 rounded-md font-semibold text-white' onclick=''>Save Config</button> </div> <button class='text-lg m-1 bg-sky-500 hover:bg-sky-700 px-2 py-1.5 leading-5 rounded-md font-semibold text-white' onclick='deleteConfig()'>Delete Config</button> </div>";
var conf=$('<div id="configDiv">').css({
position: 'absolute',
top: '50px',
left: '20px',
color: '#ffffff',
backgroundColor: '#000000',
border:"3px solid #999",
boxShadow:"5px 5px 5px #333",
padding: '10px',
borderRadius: '10px',
fontSize: '12px',
opacity:1,
color:'#fff',
width: '320px'
})
.addClass("")
.html(html).appendTo(document.body);
}
function ImageViewer({ data, dateStr }) {
const [mode, setMode] = React.useState("images"); // images, batches
const [currentPage, setCurrentPage] = React.useState(1);
const itemsPerPageSelects = [8, 16, 32, 64, 128];
/* Get Item per pages from localStorage if exists */
let perPage=32;
if (getParam("nbImagePerPage")) {
perPage=parseInt(getParam("nbImagePerPage"));
} else {
itemsPerPageSelects[2];
saveParam("nbImagePerPage", perPage);
}
const [itemsPerPage, setItemsPerPage] = React.useState( perPage );
const [asc, setAsc] = React.useState(false);
const [showDiff, setShowDiff] = React.useState(false);
const [showDetail, setShowDetail] = React.useState(false);
// Init numCols from body width or from localStorage
let numCols=2;
if ($("body").width()>800) numCols=3;
if ($("body").width()>1200) numCols=5;
if (getParam("nbColumns")) {
numCols=parseInt(getParam("nbColumns"));
} else {
saveParam("nbColumns", numCols);
}
const [numColumns, setNumColumns] = React.useState(numCols);
// Sort the data based on the title (generated timestamp)
const sortedData = [...data].sort((a, b) => {
if (asc) {
return a.src.localeCompare(b.src);
} else {
return b.src.localeCompare(a.src);
}
});
const batchData = getBatchData(sortedData);
React.useEffect(() => {
nbImageNotFoundByBatches=[];
setShowDetail(getParam("displayDetails")=="true"?true:false);
setShowDiff(getParam("displayDiff")=="true"?true:false);
if (currentPage > Math.ceil(data.length / itemsPerPage)) {
setCurrentPage(Math.ceil(data.length / itemsPerPage));
}
imgLoadDetection();
}, [itemsPerPage, dateStr, mode, sortedData]);
// Calculate the range of data for the current page
let startIndex, endIndex, numPages, firstImageInPage, lastImageInPage;
if (mode === "images") {
startIndex = (currentPage - 1) * itemsPerPage;
endIndex = startIndex + itemsPerPage;
numPages = Math.ceil(data.length / itemsPerPage);
firstImageInPage = (currentPage - 1) * itemsPerPage + 1;
lastImageInPage = Math.min(currentPage * itemsPerPage, data.length);
}
if (mode === "batches") {
startIndex = batchData[currentPage - 1].startIndex;
endIndex = batchData[currentPage - 1].endIndex + 1;
numPages = batchData.length;
firstImageInPage = startIndex + 1;
lastImageInPage = endIndex;
}
const currentBatches = getCurrentBatchData(
sortedData,
batchData,
startIndex,
endIndex
);
const pageInfo = {
mode,
currentPage,
setCurrentPage,
numPages,
numImages: data.length,
firstImageInPage,
lastImageInPage,
};
const pageData = [];
pageData.push(sortedData.slice(startIndex, endIndex));
return (
<div id="reactBox">
<div className="px-4 py-1 flex flex-row flex-wrap justify-between">
<div className="sm:basis-1/2 basis-full">
<div className="">
Mode:{" "}
{mode === "images" ? (
<span className="font-bold cursor-pointer">Images</span>
) : (
<span className="cursor-pointer" onClick={() => setMode("images")}>Images</span>
)}{" "}
|{" "}
{mode === "batches" ? (
<span className="font-bold cursor-pointer">Batches</span>
) : (
<span className="cursor-pointer" onClick={() => setMode("batches")}>Batches</span>
)}
</div>
<div className="">
{mode === "images" && (
<>
Images/page:{" "}
{itemsPerPageSelects.map((value) => (
<label key={value} class="labelImgPerPage">
<input
id="itemsPerPage"
type="radio"
value={value}
checked={itemsPerPage === value}
onChange={() => {setItemsPerPage(value); saveParam("nbImagePerPage", value);}}
/>{" "}
{value}
</label>
))}
<br />
</>
)}
<label>