-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathhelper.py
1650 lines (1339 loc) · 48.6 KB
/
helper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import traceback
import datetime
import glob
import os
import json
import time
import argparse
import platform
import shutil
import statistics
import signal
import subprocess
from PIL import Image, ImageDraw
from PyQt5.QtCore import pyqtProperty, pyqtSignal, pyqtSlot, QObject, QUrl, QThread, QCoreApplication, Qt, QRunnable, QThreadPool, QPointF
from PyQt5.QtGui import QDesktopServices, QFont, QImage
from PyQt5.QtQml import QQmlApplicationEngine, qmlRegisterSingletonType
from PyQt5.QtWidgets import QFileDialog, QApplication
from PyQt5.QtQuick import QQuickImageProvider
import qml_rc
CONFIG = "config.json"
EXT = [".png", ".jpg", ".jpeg", ".webp"]
MX_TAGS = 30
SMILES = ["0_0","(o)_(o)","+_+","+_-","._.","<o>_<o>","<|>_<|>","=_=",">_<","3_3","6_9",">_o","@_@","^_^","o_o","u_u","x_x","|_|","||_||"]
ELLIPSIS = "•••"
MX_FILE = 250
MX_PATH = 4000
if platform.system() == "Windows":
MX_PATH = 250
def get_metadata(image_file):
tags = []
m1 = image_file + ".txt"
m2 = ".".join(image_file.split(".")[:-1]) + ".txt"
for m in [m1, m2]:
if os.path.isfile(m):
tags = get_tags(m)
break
else:
g = image_file + ".json"
if os.path.isfile(g):
tags = get_tags_gallerydl(g)
return tags
def get_images(images_path, staging_path):
images = []
files = []
for e in EXT:
files += glob.glob(images_path + "/*" + e)
for f in files:
old_m = os.path.join("staging", os.path.basename(f) + ".json")
m = os.path.join(staging_path, os.path.basename(f) + ".json")
if os.path.exists(old_m) and not os.path.exists(m):
print(f"INFO: migrating {old_m} to {m}")
shutil.copy(old_m, m)
img = Img(f, m)
img.readStagingData()
if not img.ready:
img.tags = get_metadata(f)
images += [img]
return images
def positionContain(w, h, d):
if w > h:
w,h = d, (h/w)*d
else:
w,h = (w/h)*d, d
x = int((d-w)/2)
y = int((d-h)/2)
return x, y, w, h
def positionCenter(w, h, d):
if w < h:
w,h = d, (h/w)*d
else:
w,h = (w/h)*d, d
x = int((d-w)/2)
y = int((d-h)/2)
return x, y, w, h
def extract_tags_gallerydl(text):
j = json.loads(text)
booru = j["category"]
tags = []
if booru == "danbooru" or booru == "sankaku":
tags = j["tag_string"].split()
elif booru == "gelbooru" or booru == "rule34":
tags = j["tags"].split()
else:
print(f"ERROR: {booru} is UNSUPPORTED!")
exit(1)
tags = [t.strip() for t in tags]
return tags
def extract_tags(text):
seperator = " "
if "," in text:
seperator = ","
tags = [t.strip().replace(" ", "_") for t in text.split(seperator)]
return tags
def tags_to_prompt(tags):
tags = tags.copy()
for i in range(len(tags)):
t = tags[i]
if not t in SMILES:
tags[i] = t.replace("_", " ")
prompt = ", ".join(tags)
return prompt
def get_tags(tag_file):
with open(tag_file, "r", encoding="utf-8") as f:
return extract_tags(f.read())
def get_tags_gallerydl(tag_file):
with open(tag_file, "r", encoding="utf-8") as f:
return extract_tags_gallerydl(f.read())
def get_tags_from_csv(path):
tags = []
with open(path, "r", encoding="utf-8") as file:
for line in file:
t = line.rstrip().split(",")
if len(t) >= 2:
tags += [(t[0],int(t[1]))]
else:
tags += [(t[0],0)]
return tags
def put_tag_in_csv(path, tag):
with open(path, "a", encoding="utf-8") as file:
file.write(f"{tag},6\n")
def get_json(file):
if not os.path.isfile(file):
return {}
with open(file, "r", encoding="utf-8") as f:
return json.loads(f.read())
def put_json(j, file, append=True):
if append and os.path.isfile(file):
jj = get_json(file)
for k in jj:
if not k in j:
j[k] = jj[k]
with open(file, "w", encoding="utf-8") as f:
json.dump(j, f)
def to_filename(base, tags):
illegal = '<>:"/\\|?*'
name = ''.join([c for c in tags_to_prompt(tags) if not c in illegal])
return os.path.join(base, name)
class DDBWorker(QObject):
resultCallback = pyqtSignal(list)
loadedCallback = pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent)
def add_import_paths(self, webui_folder):
self.webui_folder = webui_folder
sys.path.insert(0, self.webui_folder)
venv_folder = os.path.join(self.webui_folder, 'venv', 'lib', '*')
for venv_path in glob.glob(venv_folder, recursive = True):
if not venv_path.endswith("site-packages"):
venv_path = os.path.join(venv_path, "site-packages")
if os.path.isdir(venv_path):
sys.path.insert(0, venv_path)
# torch will segfault if we dont import it on the main thread first
import torch
@pyqtSlot()
def load(self):
print("STATUS: loading deepdanbooru model...")
model_path = os.path.join(self.webui_folder, "models", "torch_deepdanbooru", "model-resnet_custom_v3.pt")
if not os.path.exists(model_path):
print("NO DDB MODEL FOUND")
return
import torch
from modules import deepbooru_model
self.model = deepbooru_model.DeepDanbooruModel()
self.model.load_state_dict(torch.load(model_path, map_location="cpu"))
self.model.to("cpu", torch.float32)
self.loadedCallback.emit()
@pyqtSlot('QString', bool, float, float, float)
def interrogate(self, file, ready, x, y, s):
img = Img(file, "")
if ready:
img.setCrop(x,y,s)
else:
img.prepare()
img = img.doCrop(512)
import numpy as np
import torch
a = np.expand_dims(np.array(img, dtype=np.float32), 0) / 255
with torch.no_grad():
x = torch.from_numpy(a).to("cpu")
y = self.model(x)[0].detach().cpu().numpy()
outputs = []
for tag, probability in zip(self.model.tags, y):
outputs += [(tag, probability)]
outputs.sort(key=lambda a: a[1], reverse=True)
if len(outputs) > 100:
outputs = outputs[:100]
outputs = [t[0] for t in outputs]
self.resultCallback.emit(outputs)
class CropRunnableSignals(QObject):
completed = pyqtSignal(int, 'QString')
class CropRunnable(QRunnable):
def __init__(self, index, img, dim, out_folder, img_mode, prompt_mode, ext_mode):
super(CropRunnable, self).__init__()
self.index = index
self.img = img
self.dim = dim
self.out_folder = out_folder
self.img_mode = img_mode
self.prompt_mode = prompt_mode
self.ext_mode = ext_mode
self.signals = CropRunnableSignals()
@pyqtSlot()
def run(self):
source_name = os.path.basename(self.img.source)
img_path = os.path.join(self.out_folder, os.path.splitext(source_name)[0])
if self.prompt_mode == 0:
self.img.writePrompt(img_path+".txt")
elif self.prompt_mode == 1:
self.img.writePromptJson(img_path+".json")
elif self.prompt_mode == 2 and self.img.tags:
tags = self.img.getTags()
while True:
img_path = to_filename(self.out_folder, tags)
if len(img_path) < MX_PATH and len(img_path)-len(self.out_folder) < MX_FILE:
break
tags = tags[:-1]
if self.img_mode != 3:
img_ext = ""
if self.ext_mode == 0:
img_ext = ".jpg"
elif self.ext_mode == 1:
img_ext = ".png"
elif self.ext_mode == 2:
img_ext = os.path.splitext(self.img.source)[1]
img_file = img_path+img_ext
if self.img_mode == 0:
self.img.writeCrop(img_file, self.dim)
elif self.img_mode == 1:
self.img.writeScale(img_file, self.dim)
elif self.img_mode == 2:
self.img.writeOriginal(img_file)
self.signals.completed.emit(self.index, source_name)
class CropWorker(QObject):
progressCallback = pyqtSignal(float, 'QString')
def __init__(self, images, out_folder, dimension, parent=None):
super().__init__(parent)
self.images = images
self.out_folder = out_folder
self.dim = dimension
self.image_mode = 0
self.ext_mode = 0
self.prompt_mode = 0
self.thread_count = 0
self.pool = QThreadPool()
@pyqtSlot(int, int, int, int)
def setup(self, img_mode, ext_mode, prompt_mode, thread_count):
self.img_mode = img_mode
self.ext_mode = ext_mode
self.prompt_mode = prompt_mode
self.thread_count = thread_count
@pyqtSlot()
def start(self):
self.progress = 0
self.total = len(self.images)
self.finishTotal = self.total
self.progressCallback.emit(0.0, "Starting...")
self.pool.setMaxThreadCount(self.thread_count)
args = (self.dim, self.out_folder, self.img_mode, self.prompt_mode, self.ext_mode)
runnables = [CropRunnable(i, self.images[i], *args) for i in range(len(self.images))]
for r in runnables:
r.signals.completed.connect(self.runnableCompleted)
r.setAutoDelete(True)
self.pool.start(r)
@pyqtSlot()
def stop(self):
self.pool.clear()
self.finishTotal = self.progress + self.pool.activeThreadCount()
@pyqtSlot(int, 'QString')
def runnableCompleted(self, index, name):
self.progress += 1
self.progressCallback.emit(self.progress/self.total, name)
if self.progress == self.finishTotal:
self.progressCallback.emit(-1.0, "Done")
class Cache:
def __init__(self, mx):
self.mx = mx
self.queue = []
self.cache = {}
def fetch(self, file):
if not file in self.cache:
if len(self.queue) == self.mx:
pop = self.queue[0]
del self.cache[pop]
self.queue += [file]
self.cache[file] = Image.open(file).convert("RGB")
return self.cache[file]
class Img:
def __init__(self, image_path, staging_path):
self.cache = None
self.globals = None
self.source = image_path
self.staging_path = staging_path
self.ready = False # ready to be displayed (needs crop offsets/scale)
self.changed = False
self.ddb = []
self.w, self.h = None, None
self.offset_x, self.offset_y, self.scale = None, None, None
self.letterboxs = []
self.tags = []
try:
with Image.open(self.source) as img:
pass
except Exception as e:
raise Exception(f"failed to load {self.source}, probably corrupted")
def contain(self):
if not self.w or not self.h:
with Image.open(self.source) as img:
self.w, self.h = img.size
x, y, w, h = positionContain(self.w, self.h, 1024)
self.setCrop(x/1024, y/1024, 1.0)
def center(self):
if not self.w or not self.h:
with Image.open(self.source) as img:
self.w, self.h = img.size
x, y, w, h = positionCenter(self.w, self.h, 1024)
_, _, w2, _ = positionContain(self.w, self.h, 1024)
self.setCrop(x/1024, y/1024, w/w2)
def readStagingData(self):
if not os.path.isfile(self.staging_path):
self.tags = []
return False
data = {}
with open(self.staging_path, 'r', encoding="utf-8") as f:
data = json.load(f)
x,y,s = data["offset_x"], data["offset_y"], data["scale"]
self.setCrop(x,y,s)
self.tags = data["tags"]
return True
def writeStagingData(self):
data = {"offset_x": self.offset_x,
"offset_y": self.offset_y,
"scale": self.scale,
"tags": self.tags}
with open(self.staging_path, 'w', encoding="utf-8") as f:
json.dump(data, f)
self.changed = False
def addLetterbox(self, polygon, edges):
self.letterboxs += [(polygon, edges)]
def computeLetterboxs(self, w, h, dim):
x, y = int(self.offset_x*dim), int(self.offset_y*dim)
L, T = x>0, y>0
R, B = x<(dim-w)-1, y<(dim-h)-1
lx, rx = x, w-1+x
ty, by = y, h-1+y
d = dim - 1
self.letterboxs = []
# number of pixels to inset the edge
s = 1
#L,R,B,T
if(L and not T and not B):
self.addLetterbox([(0,0), (lx,0), (lx, d), (0, d)], [((lx+s,s), (lx+s, d-s))])
if(R and not T and not B):
self.addLetterbox([(d,0), (d, d), (rx, d), (rx,0)], [((rx-s,s), (rx-s, d-s))])
if(T and not L and not R):
self.addLetterbox([(0,0), (d,0), (d, ty), (0, ty)], [((s, ty+s), (d-s, ty+s))])
if(B and not L and not R):
self.addLetterbox([(0, d), (0,by), (d,by), (d, d)], [((s,by-s), (d-s,by-s))])
#TL, BL, TR, BR
if(L and T and not R and not B):
poly = [(0,0), (d,0), (d, ty), (lx, ty), (lx, d), (0, d)]
edges = [((lx+s, ty+s), (d-s, ty+s)), ((lx+s, ty+s), (lx+s, d-s))]
self.addLetterbox(poly, edges)
if(L and B and not R and not T):
poly = [(0,0), (lx,0), (lx, by), (d, by), (d, d), (0, d)]
edges = [((lx+s, s), (lx+s, by-s)), ((lx+s, by-s), (d-s, by-s))]
self.addLetterbox(poly, edges)
if(R and T and not L and not B):
poly = [(0,0), (d,0), (d, d), (rx, d), (rx, ty), (0, ty)]
edges = [((s, ty+s), (rx-s, ty+s)), ((rx-s, ty+s), (rx-s, d-s))]
self.addLetterbox(poly, edges)
if(R and B and not L and not T):
poly = [(d,0), (d, d), (0, d), (0, by), (rx, by), (rx,0)]
edges = [((rx-s, s), (rx-s, by-s)), ((rx-s, by-s), (s, by-s))]
self.addLetterbox(poly, edges)
#LU, TU, RU, BU
if(L and T and B and not R):
poly = [(0,0), (d,0), (d, ty), (lx, ty), (lx, by), (d, by), (d, d), (0, d)]
edges = [((lx+s, ty+s), (d-s,ty+s)), ((lx+s, ty+s), (lx+s, by-s)), ((lx+s, by-s), (d-s, by-s))]
self.addLetterbox(poly, edges)
if(T and L and R and not B):
poly = [(0,0), (d,0), (d, d), (rx, d), (rx, ty), (lx, ty), (lx, d), (0, d)]
edges = [((lx+s,d-s), (lx+s,ty+s)), ((lx+s, ty+s), (rx-s, ty+s)), ((rx-s, ty+s), (rx-s, d-s))]
self.addLetterbox(poly, edges)
if(R and T and B and not L):
poly = [(0,0), (d,0), (d, d), (0, d), (0, by), (rx, by), (rx, ty), (0, ty)]
edges = [((s, ty+s), (rx-s,ty+s)), ((rx-s,ty+s), (rx-s, by-s)), ((rx-s, by-s), (s, by-s))]
self.addLetterbox(poly, edges)
if(B and L and R and not T):
poly = [(0,0), (lx,0), (lx, by), (rx, by), (rx, 0), (d, 0), (d, d), (0, d)]
edges = [((lx+s,s), (lx+s,by-s)), ((lx+s, by-s), (rx-s, by-s)), ((rx-s, by-s), (rx-s, s))]
self.addLetterbox(poly, edges)
#All
dh = d//2
if(L and R and T and B):
poly = [(0,0), (d, 0), (d, d), (dh, d), (dh, by), (rx, by), (rx, ty), (lx, ty), (lx, by), (dh, by), (dh,d), (0,d)]
edges = [((lx+s, ty+s), (rx-s, ty+s)), ((rx-s, ty+s), (rx-s, by-s)), ((rx-s, by-s), (lx+s, by-s)), ((lx+s, by-s), (lx+s, ty+s))]
self.addLetterbox(poly, edges)
def computeEdgeColor(self, crop, center, letterbox):
_, edges = letterbox
cx, cy = center
s = 32
samples = []
for i in range(len(edges)):
a, b = edges[i]
ax, ay = a
bx, by = b
dx, dy = (bx-ax)/s, (by-ay)/s
for k in range(1,s):
x, y = int(ax+dx*k), int(ay+dy*k)
p = crop.getpixel((x,y))
samples += [p]
c = (0,0,0)
for d in samples:
c = (c[0]+d[0], c[1]+d[1], c[2]+d[2])
l = len(samples)
color = (int(c[0]//l),int(c[1]//l),int(c[2]//l))
var = statistics.variance([sum(d)//3 for d in samples])
return color, var
def doCrop(self, dim):
if self.cache:
img = self.cache.fetch(self.source)
else:
img = Image.open(self.source).convert('RGB')
self.w, self.h = img.size[0], img.size[1]
x, y, w, h = positionContain(img.size[0], img.size[1], dim)
s = (w/img.size[0]) * self.scale
img = img.resize((int(round(img.size[0] * s)),int(round(img.size[1] * s))))
self.computeLetterboxs(img.size[0], img.size[1], dim)
crop = Image.new(mode='RGB',size=(dim,dim))
crop.paste(img, (int(self.offset_x*dim), int(self.offset_y*dim)))
draw = ImageDraw.Draw(crop)
center = (self.offset_x*dim + img.size[0]//2, self.offset_y*dim + img.size[1]//2)
for letterbox in self.letterboxs:
color, var = self.computeEdgeColor(crop, center, letterbox)
if var < 200:
polygon, _ = letterbox
draw.polygon(polygon, fill=color)
#crop.paste(img, (int(self.offset_x*dim), int(self.offset_y*dim)))
return crop
def getTags(self):
if self.globals:
return self.globals.composite(self.tags).copy()
else:
return self.tags.copy()
def buildPrompt(self):
return tags_to_prompt(self.getTags())
def writeCrop(self, crop_file, dim):
if not self.ready:
self.center()
crop = self.doCrop(dim)
if crop_file.endswith(".jpg"):
crop.save(crop_file, quality=95)
else:
crop.save(crop_file)
def writeScale(self, scale_file, dim):
if self.cache:
img = self.cache.fetch(self.source)
else:
img = Image.open(self.source).convert('RGB')
self.w, self.h = img.size[0], img.size[1]
s = dim/min(self.w, self.h)
if self.w > self.h:
w = self.w * s
h = dim
else:
w = dim
h = self.h * s
img = img.resize((int(w),int(h)))
if scale_file.endswith(".jpg"):
img.save(scale_file, quality=95)
else:
img.save(scale_file)
def writeOriginal(self, out_file):
in_ext = os.path.splitext(self.source)[1]
out_ext = os.path.splitext(out_file)[1]
if in_ext == out_ext:
shutil.copyfile(self.source, out_file)
return
if self.cache:
img = self.cache.fetch(self.source)
else:
img = Image.open(self.source).convert('RGB')
self.w, self.h = img.size[0], img.size[1]
if out_file.endswith(".jpg"):
img.save(out_file, quality=95)
else:
img.save(out_file)
def writePrompt(self, prompt_file):
with open(prompt_file, "w", encoding="utf-8") as f:
f.write(self.buildPrompt())
def writePromptJson(self, prompt_file):
tags = []
if self.globals:
tags = self.globals.composite(self.tags)
else:
tags = self.tags
put_json({"tags": tags}, prompt_file)
def setCrop(self, x, y, s):
if(self.ready and x == self.offset_x and y == self.offset_y and s == self.scale):
return
self.offset_x = x
self.offset_y = y
self.scale = s
if self.ready:
self.changed = True
else:
self.ready = True
def addTag(self, tag, prefix=False):
if not tag in self.tags:
if prefix:
self.tags.insert(0, tag)
else:
self.tags.append(tag)
self.changed = True
def deleteTag(self, idx):
del self.tags[idx]
self.changed = True
def moveTag(self, from_idx, to_idx):
self.tags.insert(to_idx, self.tags.pop(from_idx))
self.changed = True
def setTags(self, tags):
self.tags = tags
self.changed = True
def reset(self):
if not self.readStagingData():
self.center()
self.changed = False
def fullReset(self):
self.tags = get_metadata(self.source)
self.prepare()
self.writeStagingData()
self.changed = False
def prepare(self):
self.center()
class PreviewProviderSignals(QObject):
updated = pyqtSignal()
class PreviewProvider(QQuickImageProvider):
def __init__(self):
super(PreviewProvider, self).__init__(QQuickImageProvider.Image)
self.preview = None
self.source = None
self.dim = 0
self.count = 0
self.last = None
self.signals = PreviewProviderSignals()
def setSource(self, source, dim):
self.source = source
self.dim = dim
def requestImage(self, p_str, size):
if p_str != self.last:
img = self.source.doCrop(self.dim)
data = img.convert("RGB").tobytes("raw", "RGB")
self.preview = QImage(data, img.size[0], img.size[1], QImage.Format_RGB888)
self.last = p_str
self.signals.updated.emit()
return self.preview, self.preview.size()
class Globals():
def __init__(self, config):
self.config_path = config
self.tags = [ELLIPSIS]
self.changed = False
self.readStagingData()
def composite(self, input):
i = self.tags.index(ELLIPSIS)
a, b = self.tags[:i], self.tags[i+1:]
a = [t for t in a if not t in input]
b = [t for t in b if not t in input]
output = a + input + b
return output
def addTag(self, tag, prefix=False):
if not tag in self.tags:
if prefix:
self.tags.insert(0, tag)
else:
self.tags.append(tag)
self.changed = True
def deleteTag(self, idx):
del self.tags[idx]
self.changed = True
def moveTag(self, from_idx, to_idx):
self.tags.insert(to_idx, self.tags.pop(from_idx))
self.changed = True
def buildPrompt(self):
return tags_to_prompt(self.tags)
def writeStagingData(self):
data = {"global": self.tags}
put_json(data, self.config_path)
self.changed = False
def readStagingData(self):
self.tags = [ELLIPSIS]
if not os.path.isfile(self.config_path):
return
cfg = get_json(self.config_path)
if "global" in cfg:
self.tags = cfg["global"]
class Backend(QObject):
updated = pyqtSignal()
changedUpdated = pyqtSignal()
tagsUpdated = pyqtSignal()
imageUpdated = pyqtSignal()
searchUpdated = pyqtSignal()
favUpdated = pyqtSignal()
suggestionsUpdated = pyqtSignal()
previewUpdated = pyqtSignal()
listEvent = pyqtSignal(int)
cropWorkerUpdated = pyqtSignal()
cropWorkerSetup = pyqtSignal(int,int,int,int)
cropWorkerStart = pyqtSignal()
cropWorkerStop = pyqtSignal()
ddbWorkerUpdated = pyqtSignal()
ddbWorkerLoad = pyqtSignal()
ddbWorkerInterrogate = pyqtSignal('QString', bool, float, float, float)
def __init__(self, in_folder, tags_file, webui_folder, parent=None):
super().__init__(parent)
self.cache = Cache(8)
# crop worker & state
self.cropThread = QThread(self)
self.cropWorker = None
self.setInputFolder(in_folder, True)
self.webui_folder = webui_folder
# general state
self.isShowingGlobal = False
self.isPrefixingTags = False
# global tag list
self.tags_file = tags_file
tags = get_tags_from_csv(tags_file)
self.tagLookup = {}
for t in tags:
self.tagLookup[t[0]] = t[1]
self.tagIndex = [t[0] for t in tags]
# GUI state
self.isShowingTagColors = False
self.currentSearch = ""
self.searchResults = []
self.listIndex = 0
self.imgIndex = -1
self.current = None
self.fav = []
self.freq = {}
self.isShowingFrequent = True
self.previewProvider = PreviewProvider()
self.previewProvider.signals.updated.connect(self.previewCallback)
self.previewCount = 0
self.previewPrompt = ""
self.previewVisible = False
self.cycleDelta = None
self.setActive(0)
# GUI init
self.search("")
self.loadConfig()
self.saveConfig()
# ddb worker & state
self.ddbWorker = DDBWorker()
self.ddbCurrent = -1
self.ddbLoading = True
self.ddbAll = False
self.ddbAdd = False
self.ddbActive = self.webui_folder != None
self.ddbThread = None
if self.ddbActive:
self.ddbInit()
# clean up ddb thread
parent.aboutToQuit.connect(self.closing)
def load(self):
self.in_config = os.path.join(self.in_folder, CONFIG)
in_cfg = get_json(self.in_config)
self.out_folder = None
self.staging_folder = None
self.dim = None
if "output" in in_cfg:
self.out_folder = in_cfg["output"]
if "staging" in in_cfg:
self.staging_folder = in_cfg["staging"]
if "dimension" in in_cfg:
self.dim = in_cfg["dimension"]
if not self.out_folder:
self.out_folder = os.path.join(self.in_folder, "output")
if not self.staging_folder:
self.staging_folder = os.path.join(self.in_folder, "staging")
if not self.dim:
self.dim = 1024
if not os.path.exists(self.out_folder):
os.makedirs(self.out_folder)
if not os.path.exists(self.staging_folder):
os.makedirs(self.staging_folder)
self.globals = Globals(self.in_config)
self.images = get_images(self.in_folder, self.staging_folder)
print(f"STATUS: loaded {len(self.images)} images, {len([i for i in self.images if i.tags])} have tags")
if len(self.images) == 0:
print(f"ERROR: no images found!")
exit(1)
for i in self.images:
i.cache = self.cache
i.globals = self.globals
self.buildCropWorker()
def setInputFolder(self, folder, fresh):
if not folder:
if fresh:
cfg = get_json(CONFIG)
if "input" in cfg:
folder = cfg["input"]
if not folder:
folder = str(QFileDialog.getExistingDirectory(None, "Select Input Folder"))
if not folder:
return False
self.in_folder = folder
self.load()
return True
def buildCropWorker(self):
if self.cropWorker:
self.cropWorkerStop.emit()
while self.cropWorker.pool.activeThreadCount() > 0:
time.sleep(0.01)
self.cropWorker.deleteLater()
self.cropWorker = CropWorker(self.images, self.out_folder, self.dim)
self.cropWorkerActive = False
self.cropWorkerProgress = 0.0
self.cropWorkerStatus = ""
self.cropInit()
### Properties
@pyqtProperty(int, constant=True)
def total(self):
return len(self.images)
@pyqtProperty(int, notify=updated)
def active(self):
return self.imgIndex
@active.setter
def active(self, a):
self.setActive(a % len(self.images))
def setActive(self, a):
if self.isShowingGlobal:
return
self.imgIndex = a
self.current = self.images[self.imgIndex]
# setting the default crop state is expensive
# (requires loading the image)
# so only do it on demand
if not self.current.ready:
self.current.prepare()
self.current.writeStagingData()
self.setPreview()
if not self.current.ddb:
self.isShowingFrequent = True
self.doUpdate()
def doUpdate(self):
self.changedUpdated.emit()
self.imageUpdated.emit()
self.tagsUpdated.emit()
self.suggestionsUpdated.emit()
self.previewUpdated.emit()
self.updated.emit()
@pyqtProperty('QString', notify=updated)
def source(self):
if self.isShowingGlobal:
return "qrc:/icons/globe.png"
return "file:///" + self.current.source
@pyqtProperty(bool, notify=changedUpdated)
def changed(self):
return self.current.changed
@pyqtProperty(float, notify=imageUpdated)
def offset_x(self):
if self.isShowingGlobal:
return 0
return self.current.offset_x
@pyqtProperty(float, notify=imageUpdated)
def offset_y(self):
if self.isShowingGlobal:
return 0
return self.current.offset_y
@pyqtProperty(float, notify=imageUpdated)
def scale(self):
if self.isShowingGlobal:
return 1
return self.current.scale
@pyqtProperty(int, notify=updated)
def dimension(self):
return self.dim
@pyqtProperty('QString', notify=previewUpdated)
def preview(self):
if self.isShowingGlobal:
return "qrc:/icons/globe.png"
return f"image://preview/{self.previewCount}.png"
@pyqtProperty('QString', notify=tagsUpdated)
def prompt(self):
return self.current.buildPrompt()
@pyqtProperty(list, notify=tagsUpdated)
def tags(self):
return self.current.tags
@pyqtProperty(list, notify=searchUpdated)
def results(self):
return self.searchResults
@pyqtProperty('QString', notify=cropWorkerUpdated)
def cropStatus(self):
return self.cropWorkerStatus
@pyqtProperty(float, notify=cropWorkerUpdated)
def cropProgress(self):
return self.cropWorkerProgress
@pyqtProperty(bool, notify=cropWorkerUpdated)
def cropActive(self):
return self.cropWorkerActive
@pyqtProperty('QString', notify=updated)
def title(self):
if self.isShowingGlobal:
return "Tagging Global"
return f"Tagging {self.imgIndex+1} of {len(self.images)}"
@pyqtProperty(list, notify=favUpdated)
def favourites(self):
return self.fav