-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcaptions_helper.py
1499 lines (1173 loc) · 58.4 KB
/
captions_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 argparse
import os
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QLabel, QGridLayout, QVBoxLayout, QHBoxLayout,
QLineEdit, QPushButton, QSpinBox, QGraphicsDropShadowEffect, QFrame, QTextEdit,
QScrollArea, QMessageBox, QSizePolicy, QAbstractItemView, QListView, QAbstractScrollArea,
QStyledItemDelegate, QCheckBox)
from PyQt5.QtGui import QPixmap, QColor, QIcon, QPalette, QTransform, QImage, QTextCharFormat, QTextCursor, QDrag, \
QBrush
from PyQt5.QtCore import Qt, QSize, QPoint, QTimer, QRegularExpression, QRect
from PyQt5.QtWidgets import QMainWindow, QAction, QMenu, QMenuBar, QDialog
from PyQt5.QtWidgets import QListWidget, QListWidgetItem
from PIL import Image, UnidentifiedImageError
import piexif
import json
import re
class ItemDelegate(QStyledItemDelegate):
def __init__(self, parent=None):
super().__init__(parent)
self.parent = parent
def paint(self, painter, option, index):
enabled = self.parent.tag_states.get(index.row(), False) # Return False if key does not exist
if enabled:
painter.fillRect(option.rect, QColor('lime'))
else:
painter.fillRect(option.rect, QColor('grey'))
super().paint(painter, option, index)
class CustomListWidget(QListWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.setDragEnabled(True)
self.setAcceptDrops(True)
self.setDropIndicatorShown(True)
self.setDefaultDropAction(Qt.MoveAction)
self.setDragDropMode(QAbstractItemView.InternalMove)
self.setViewMode(QListView.IconMode)
self.setFlow(QListView.LeftToRight)
self.setWrapping(True)
self.setResizeMode(QListView.Adjust)
self.setFlow(QListView.LeftToRight)
self.setWrapping(True)
self.setSizePolicy(QSizePolicy.MinimumExpanding , QSizePolicy.MinimumExpanding)
#self.setFixedSize(400, 300)
#self.setLayoutMode(QListView.Flow)
self.setStyleSheet("""
QListWidget::item {
border-radius: 10px;
min-width: 50px;
min-height: 25px;
}
QListWidget::item:selected {
color: yellow;
}
""")
self.setToolTip("Left click to toggle enable/disable.\n"
"Middle click to delete.\n"
"Right click to add new.\n"
"Double click to edit.\n")
self.tag_states = {}
self.itemChanged.connect(self.handleItemChanged)
self.spacing = 7
self.setSpacing(self.spacing) # Added padding between labels
self.setItemDelegate(ItemDelegate(self))
self.setLayoutMode(QListView.SinglePass) # Update layout mode to fix drag issue
def calculateHeight(self):
return # self.setMinimumHeight(self.sizeHintForRow(0) * self.count())
def changed_add_callback(self, changed_callback_new):
print("changed")
self.changed_callback = changed_callback_new
changed_callback = None
tags_counter = 0
def dropEvent(self, event):
if event.source() == self:
# Get the original source index and item
source_item = self.currentItem()
source_index = self.row(source_item)
source_status = self.tag_states[source_index]
# Calculate the target index
pos = event.pos()
target_index = self.drop_on(pos)
print(f"Target Index: {target_index}") # Debugging print statement
# Handle the items
self.blockSignals(True)
if target_index > source_index and target_index != self.count() - 1: # dragged down, adjust target_index after remove
target_index -= 1
# Remove the original item from the list
removed_item = self.takeItem(source_index)
self.insertItem(target_index, removed_item)
self.blockSignals(False)
# Update the status for the moved item
self.tag_states.pop(source_index, None)
self.tag_states[target_index] = source_status
# Update the rest of the tag states
tag_states = {i: state for i, state in enumerate(self.tag_states.values())}
self.tag_states = tag_states
self.calculateHeight()
# super().dropEvent(event)
self.clearSelection() # Clear selection after drag and drop
def drop_on(self, pos):
"""
Determine the index of the item that is under the cursor.
"""
for i in range(self.count() - 1): # we exclude the last item because it has no next item
current_item = self.item(i)
next_item = self.item(i + 1)
current_item_left = self.visualItemRect(current_item).left()
next_item_left = self.visualItemRect(next_item).left()
center_pos = (current_item_left + next_item_left) // 2
if pos.x() < center_pos:
return i
# Special case for the last item
last_item = self.item(self.count() - 1)
last_item_left = self.visualItemRect(last_item).left()
last_item_right = self.visualItemRect(last_item).right()
last_item_center = (last_item_left + last_item_right) // 2
if pos.x() < last_item_center:
return self.count() - 2
else:
return self.count() - 1
def handleItemChanged(self, item):
# Estimate the size of the item based on the length of the text
width = len(item.text()) * 7
height = item.sizeHint().height()
item.setSizeHint(QSize(width, height))
# update tag states if the item text was changed
item_row = self.row(item)
if item_row in self.tag_states:
self.tag_states[item_row] = self.tag_states.pop(item_row)
# Rearrange the items to respect the new size
self.doItemsLayout()
if self.changed_callback:
self.changed_callback()
def mouseDoubleClickEvent(self, event):
if event.button() == Qt.LeftButton:
item = self.itemAt(event.pos())
if item:
self.editItem(item)
else:
super().mouseDoubleClickEvent(event)
def mousePressEvent(self, event):
changed = False
if event.button() == Qt.MiddleButton: # Item delete
item = self.itemAt(event.pos())
if item:
row = self.row(item)
self.takeItem(row)
if row in self.tag_states:
del self.tag_states[row]
changed = True
elif event.button() == Qt.RightButton: # Add new at end
item = QListWidgetItem(f"Edit me #{self.tags_counter:03d}")
self.tags_counter += 1
item.setFlags(item.flags() | Qt.ItemIsEditable)
self.addItem(item)
self.tag_states[self.row(item)] = False
changed = True
elif event.button() == Qt.LeftButton: # Toggle enabled
item = self.itemAt(event.pos())
if item:
row = self.row(item)
self.tag_states[row] = not self.tag_states.get(row, False)
changed = True
if changed:
if self.changed_callback:
self.changed_callback()
self.calculateHeight()
super().mousePressEvent(event)
def keyPressEvent(self, event):
if event.key() in [Qt.Key_Backspace, Qt.Key_Delete]:
for item in self.selectedItems():
row = self.row(item)
self.takeItem(row)
if row in self.tag_states:
del self.tag_states[row]
def startEditMode(self, pos):
item = self.itemAt(pos)
if item and not item.isSelected():
self.editItem(item)
def startDrag(self, supportedActions):
drag = QDrag(self)
mimeData = self.mimeData(self.selectedItems())
drag.setMimeData(mimeData)
result = drag.exec_(supportedActions, Qt.MoveAction)
def get_labels(self):
labels = []
for i in range(self.count()):
item = self.item(i)
enabled = self.tag_states.get(i, False) # returns False if key doesn't exist
labels.append((item.text(), enabled))
return labels
def set_labels(self, labels):
self.clear()
self.tag_states.clear()
for i, (label, enabled) in enumerate(labels):
item = QListWidgetItem(label)
item.setFlags(item.flags() | Qt.ItemIsEditable)
item.setData(Qt.UserRole, QPalette())
self.addItem(item)
self.tag_states[i] = enabled
class ListInputDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Add List")
self.layout = QVBoxLayout(self)
# Textbox for user input
self.text_box = QTextEdit(self)
self.layout.addWidget(self.text_box)
# Add button
self.add_button = QPushButton("Add", self)
self.layout.addWidget(self.add_button)
self.add_button.clicked.connect(self.on_add_button_clicked)
def on_add_button_clicked(self):
text = self.text_box.toPlainText()
self.parent().process_list_input(text)
self.close()
class ImageLabel(QLabel):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.path = None
self.setFrameShape(QFrame.Panel)
self.setLineWidth(3)
self.__set_default_frame_color()
self.__is_selected = False
self.__is_highlighted = False
def __set_default_frame_color(self):
# Set the default frame color to the background color
palette = self.palette()
palette.setColor(QPalette.WindowText, palette.color(QPalette.Background))
self.setPalette(palette)
def __set_selected_frame_color(self):
# Set the frame color to red
palette = self.palette()
palette.setColor(QPalette.WindowText, QColor(Qt.red))
self.setPalette(palette)
def __set_highlighted_frame_color(self):
# Set the frame color to yellow
palette = self.palette()
palette.setColor(QPalette.WindowText, QColor(Qt.yellow))
self.setPalette(palette)
def set_selected(self, is_selected):
if self.__is_selected != is_selected:
self.__is_selected = is_selected
if self.__is_selected:
self.__set_selected_frame_color()
else:
if self.__is_highlighted:
self.__set_highlighted_frame_color()
else:
self.__set_default_frame_color()
def set_highlighted(self, is_highlighted):
if self.__is_highlighted != is_highlighted:
self.__is_highlighted = is_highlighted
if self.__is_highlighted:
if not self.__is_selected:
self.__set_highlighted_frame_color()
else:
if not self.__is_selected:
self.__set_default_frame_color()
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.parent().parent().parent().parent().on_image_clicked(self)
if event.button() == Qt.RightButton:
# Right button was pressed, copy image to clipboard
clipboard = QApplication.clipboard()
pixmap = self.pixmap()
if pixmap:
clipboard.setPixmap(pixmap)
super().mousePressEvent(event)
def mouseDoubleClickEvent(self, event):
if self.path:
if sys.platform.startswith('linux'):
os.system(f"xdg-open '{self.path}'")
elif sys.platform.startswith('win'):
os.system(f"start '{self.path}'")
elif sys.platform.startswith('darwin'):
os.system(f"open '{self.path}'")
class ImageDropWidget(QWidget):
def __init__(self, args, parent=None):
super().__init__(parent)
self.current_image_index = 0
self.grid_item_width = 128
self.grid_item_height = 128
self.grid_spacing = 10
self.min_width = 800
self.min_height = 400
self.setAcceptDrops(True)
self.last_preview = None
self.resize_timer = QTimer()
self.resize_timer.timeout.connect(self.resize_done)
# Create horizontal layout
self.h_layout = QHBoxLayout(self)
# Main layout
self.main_layout = QVBoxLayout()
self.preview_layout = QVBoxLayout()
self.h_layout.addLayout(self.main_layout)
self.h_layout.addLayout(self.preview_layout)
self.setLayout(self.h_layout)
# Grid layout
self.grid_layout = QGridLayout()
self.grid_layout.setSpacing(self.grid_spacing)
self.grid_layout.setAlignment(Qt.AlignTop | Qt.AlignLeft)
# Grid Widget
self.grid_widget = QWidget()
self.grid_widget.setLayout(self.grid_layout)
self.grid_widget.setStyleSheet("background-color: #dddddd;") # Set the background color of the grid
# Scroll Area
self.scroll_area = QScrollArea(self)
self.scroll_area.setWidgetResizable(True)
self.scroll_area.setWidget(self.grid_widget)
self.scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
self.main_layout.addWidget(self.scroll_area, stretch=10)
# Bottom layout
self.bottom_layout = QHBoxLayout()
self.bottom_layout.setAlignment(Qt.AlignBottom | Qt.AlignLeft)
self.main_layout.addLayout(self.bottom_layout)
# Add caption label
self.caption_label = QLabel("Add caption for all:", self)
self.bottom_layout.addWidget(self.caption_label)
# Add caption text input
self.caption_input = QLineEdit(self)
self.caption_input.setPlaceholderText("Add caption to all shown images")
self.bottom_layout.addWidget(self.caption_input)
self.caption_label = QLabel("Comma position:", self)
self.bottom_layout.addWidget(self.caption_label)
# Add comma place input
self.comma_place_input = QSpinBox(self)
self.bottom_layout.addWidget(self.comma_place_input)
# Add captions button
self.add_captions_button = QPushButton("Add to all", self)
self.bottom_layout.addWidget(self.add_captions_button)
self.add_captions_button.clicked.connect(self.add_captions) # Connect the button to the add_captions method
# Bottom layout for Labels
self.bottom_layout_labels = QHBoxLayout()
self.bottom_layout_labels.setAlignment(Qt.AlignBottom | Qt.AlignLeft)
self.main_layout.addLayout(self.bottom_layout_labels)
self.labels_labels = QLabel("Labels:", self)
self.bottom_layout_labels.addWidget(self.labels_labels)
# self.layout = QVBoxLayout(self)
self.labels_list_widget = CustomListWidget(self)
self.bottom_layout_labels.addWidget(self.labels_list_widget)
self.checkboxes_layout = QVBoxLayout()
self.checkboxes_layout.setAlignment(Qt.AlignTop | Qt.AlignRight)
self.bottom_layout_labels.addLayout(self.checkboxes_layout)
self.add_labels_checkbox = QCheckBox("Add labels on load", self)
self.checkboxes_layout.addWidget(self.add_labels_checkbox)
self.add_labels_checkbox.stateChanged.connect(self.add_labels_checkbox_changed)
self.sync_labels_checkbox = QCheckBox("Sync labels", self)
self.checkboxes_layout.addWidget(self.sync_labels_checkbox)
self.sync_labels_checkbox.stateChanged.connect(self.sync_labels_checkbox_changed)
self.sync_labels_changes_checkbox = QCheckBox("Sync labels changes", self)
self.checkboxes_layout.addWidget(self.sync_labels_changes_checkbox)
#self.sync_labels_changes_checkbox.stateChanged.connect(self.sync_labels_checkbox_changes_changed)
self.labels_list_widget.changed_add_callback(self.labels_changed_callback)
# Horizontal line
self.line = QFrame(self)
self.line.setFrameShape(QFrame.HLine)
self.line.setFrameShadow(QFrame.Sunken)
self.main_layout.addWidget(self.line)
# Bottom layout for remove
self.bottom_layout_remove = QHBoxLayout()
self.bottom_layout_remove.setAlignment(Qt.AlignBottom | Qt.AlignLeft)
self.main_layout.addLayout(self.bottom_layout_remove)
# Remove caption label
self.remove_caption_label = QLabel("Remove caption for all:", self)
self.bottom_layout_remove.addWidget(self.remove_caption_label)
# Remove caption text input
self.remove_caption_input = QLineEdit(self)
self.remove_caption_input.setPlaceholderText("Remove caption to all shown images")
self.bottom_layout_remove.addWidget(self.remove_caption_input)
# Remove captions button
self.remove_captions_button = QPushButton("Remove from all", self)
self.bottom_layout_remove.addWidget(self.remove_captions_button)
self.remove_captions_button.clicked.connect(self.remove_captions) # Connect the button to the add_captions method
# Horizontal line
self.line = QFrame(self)
self.line.setFrameShape(QFrame.HLine)
self.line.setFrameShadow(QFrame.Sunken)
self.main_layout.addWidget(self.line)
# Bottom layout for search and replace
self.search_and_replace_layout = QHBoxLayout()
self.search_and_replace_layout.setAlignment(Qt.AlignBottom | Qt.AlignLeft)
self.main_layout.addLayout(self.search_and_replace_layout)
# Search field label
self.search_and_replace_search_label = QLabel("Search:", self)
self.search_and_replace_layout.addWidget(self.search_and_replace_search_label)
# Search text input
self.search_and_replace_search_input = QLineEdit(self)
self.search_and_replace_search_input.setPlaceholderText("Enter text to search")
self.search_and_replace_layout.addWidget(self.search_and_replace_search_input)
# Replace field label
self.search_and_replace_replace_label = QLabel("Replace:", self)
self.search_and_replace_layout.addWidget(self.search_and_replace_replace_label)
# Replace text input
self.search_and_replace_replace_input = QLineEdit(self)
self.search_and_replace_replace_input.setPlaceholderText("Enter replacement text")
self.search_and_replace_layout.addWidget(self.search_and_replace_replace_input)
self.search_and_replace_all_text = QCheckBox("All text", self)
self.search_and_replace_layout.addWidget(self.search_and_replace_all_text)
#self.search_and_replace_all_text.stateChanged.connect(self.search_and_replace_all_text_checkbox_changed)
self.search_and_replace_use_re = QCheckBox("RE", self)
self.search_and_replace_layout.addWidget(self.search_and_replace_use_re)
# Search and Replace button
self.search_and_replace_button = QPushButton("Search and Replace", self)
self.search_and_replace_layout.addWidget(self.search_and_replace_button)
self.search_and_replace_button.clicked.connect(
self.search_and_replace) # Connect the button to the search_and_replace method
# Horizontal line
self.line = QFrame(self)
self.line.setFrameShape(QFrame.HLine)
self.line.setFrameShadow(QFrame.Sunken)
self.main_layout.addWidget(self.line)
# Captions layout
self.captions_layout = QHBoxLayout()
self.captions_layout.setAlignment(Qt.AlignBottom | Qt.AlignLeft)
self.main_layout.addLayout(self.captions_layout)
# Add captions text input/output
self.caption_label = QLabel("Caption:", self)
self.captions_layout.addWidget(self.caption_label)
self.captions_io = QTextEdit(self)
self.captions_io.setPlaceholderText("Select image to edit captions")
self.captions_io.setLineWrapMode(QTextEdit.WidgetWidth)
self.captions_io.textChanged.connect(self.adjust_text_height)
self.captions_layout.addWidget(self.captions_io)
self.current_label = None
self.captions_io.textChanged.connect(self.on_captions_io_text_changed)
self.save_captions_button = QPushButton("Save caption", self)
self.captions_layout.addWidget(self.save_captions_button)
self.save_captions_button.clicked.connect(self.save_captions)
# Search layout
self.search_layout = QHBoxLayout()
self.search_layout.setAlignment(Qt.AlignBottom | Qt.AlignLeft)
self.main_layout.addLayout(self.search_layout)
# Add search label
self.search_label = QLabel("Search in caption:", self)
self.search_layout.addWidget(self.search_label)
# Add search input
self.search_input = QLineEdit(self)
self.search_input.setPlaceholderText("Enter search text")
self.search_layout.addWidget(self.search_input)
self.captions_io.textChanged.connect(self.highlight_search_results)
self.search_input.textChanged.connect(self.highlight_search_results)
self.clear_search_button = QPushButton("Clear search", self)
self.search_layout.addWidget(self.clear_search_button)
self.clear_search_button.clicked.connect(self.clear_search)
self.image_captions = {}
# Search in all caption, indicate with yellow grid
# Search all layout
self.search_all_layout = QHBoxLayout()
self.search_all_layout.setAlignment(Qt.AlignBottom | Qt.AlignLeft)
self.main_layout.addLayout(self.search_all_layout)
# Add search all label
self.search_all_label = QLabel("Search in all captions:", self)
self.search_all_layout.addWidget(self.search_all_label)
# Add search all input
self.search_all_input = QLineEdit(self)
self.search_all_input.setPlaceholderText("Enter search all text")
self.search_all_layout.addWidget(self.search_all_input)
self.search_all_now_button = QPushButton("Search all now", self)
self.search_all_layout.addWidget(self.search_all_now_button)
self.search_all_now_button.clicked.connect(self.search_all_now)
self.clear_search_all_button = QPushButton("Clear all search", self)
self.search_all_layout.addWidget(self.clear_search_all_button)
self.clear_search_all_button.clicked.connect(self.search_all_clear_search)
# Horizontal line
self.line = QFrame(self)
self.line.setFrameShape(QFrame.HLine)
self.line.setFrameShadow(QFrame.Sunken)
self.main_layout.addWidget(self.line)
# Clear Images
self.clear_button = QPushButton("Clear Images", self)
self.clear_button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
self.clear_button.setStyleSheet("QPushButton { color: red; }")
self.clear_button.setStyleSheet("QPushButton { background-color: red; }")
self.main_layout.addWidget(self.clear_button)
self.clear_button.clicked.connect(self.clear_all)
# Key help
self.key_help_label = QLabel(
"<span style='color: gray;'>Key controls: 'A' - left, 'D' - right, 'W' - top, 'S' - bottom, 'Backspace' - remove, 'F' - flip image horizontally</span>",
self
)
self.main_layout.addWidget(self.key_help_label)
# Preview label
self.preview_label = QLabel(self)
self.preview_label.setAlignment(Qt.AlignCenter)
self.preview_label.setMinimumSize(int(self.min_width // 3), int(self.min_height - 20))
self.preview_label.setFrameShape(QFrame.Box)
self.preview_label.setFrameShadow(QFrame.Sunken)
self.preview_label.setStyleSheet("background-color: #ffffff;")
self.preview_layout.addWidget(self.preview_label, stretch=2)
self.images = []
self.resize(self.min_width, self.min_height)
self.setMinimumSize(self.min_width, self.min_height)
self.adjust_text_height()
def add_labels_checkbox_changed(self):
if self.add_labels_checkbox.isChecked():
#print("add_labels_checkbox_changed")
self.sync_labels_on_change()
# def search_and_replace_all_text_checkbox_changed(self):
# if self.search_and_replace_all_text.isChecked():
# # print("search_and_replace_all_text_checkbox_changed")
# None
def sync_labels_checkbox_changed(self):
if self.sync_labels_checkbox.isChecked():
#print("sync_labels_checkbox_changed")
self.sync_labels_on_change()
def sync_labels_checkbox_changes_changed(self):
if self.sync_labels_changes_checkbox.isChecked():
#print("sync_labels_checkbox_changed")
self.sync_labels_on_change()
change_counter = 0
def labels_changed_callback(self):
print(f"labels_changed_callback, {self.change_counter}")
self.change_counter += 1
if self.sync_labels_checkbox.isChecked():
print("sync_labels_checkbox_changed")
self.sync_labels_on_change()
else:
if self.sync_labels_changes_checkbox.isChecked():
self.sync_labels_on_change(only_changes=True)
def sync_labels_on_change(self, only_changes:bool = False):
# When label toggled
# When loading image
label_and_state = self.labels_list_widget.get_labels()
enabled_tags = []
disabled_tags = []
for (label, status) in label_and_state:
print(f"{label}, {status}")
tags = self.caption_to_tag_list(label)
is_add = (False == only_changes) or \
(status and (label in self.disabled_tags_last)) or \
(not status and (label in self.enabled_tags_last)) or \
(not (label in self.enabled_tags_last) and not (label in self.disabled_tags_last))
if is_add:
if status:
enabled_tags.extend(tags)
else:
disabled_tags.extend(tags)
self.enabled_tags_last = [item for item in self.enabled_tags_last if item not in disabled_tags]
self.enabled_tags_last.extend(enabled_tags)
self.disabled_tags_last = [item for item in self.disabled_tags_last if item not in enabled_tags]
self.disabled_tags_last.extend(disabled_tags)
comma_place_desired = 0
if (enabled_tags != []) or (disabled_tags != []):
for label in self.images:
path = label.path
if (enabled_tags != []):
self.add_captions_to_path(enabled_tags, comma_place_desired, path)
if (disabled_tags != []):
self.remove_captions_from_path(disabled_tags, path)
def load_args(self, args):
self.args = args
self.load_settings(self.args.configurations_file)
def clossing_app(self):
self.save_settings(self.args.configurations_file)
def save_settings(self, filepath):
data = {
"add_labels_on_load": self.add_labels_checkbox.isChecked(),
"sync_labels": self.sync_labels_checkbox.isChecked(),
"sync_labels_changes": self.sync_labels_changes_checkbox.isChecked(),
"labels": self.labels_list_widget.get_labels()
}
with open(filepath, 'w') as file:
json.dump(data, file)
def init_last_labels(self, labels_info):
self.enabled_tags_last = []
self.disabled_tags_last = []
for i, (label, enabled) in enumerate(labels_info):
if enabled:
self.enabled_tags_last.append(label)
else:
self.disabled_tags_last.append(label)
def load_settings(self, filepath):
try:
if os.path.exists(filepath):
with open(filepath, 'r') as file:
data = json.load(file)
labels_info = data.get("labels", [])
self.labels_list_widget.set_labels(labels_info)
self.init_last_labels(labels_info)
self.add_labels_checkbox.setChecked(data.get("add_labels_on_load", False))
self.sync_labels_checkbox.setChecked(data.get("sync_labels", False))
self.sync_labels_changes_checkbox.setChecked(data.get("sync_labels_changes", False))
else:
print(f"File '{filepath}' does not exist. Could not load labels.")
except Exception as e:
print(f"Loading file '{filepath}' error: {e}.")
def keyPressEvent(self, event):
if event.key() == Qt.Key_A: # 'a' key for left
self.navigate_to_previous_image()
elif event.key() == Qt.Key_D: # 'd' key for right
self.navigate_to_next_image()
elif event.key() == Qt.Key_W: # 'w' key for up
self.navigate_to_previous_row_image()
elif event.key() == Qt.Key_S: # 's' key for down
self.navigate_to_next_row_image()
elif event.key() in {Qt.Key_Backspace, Qt.Key_Delete}:
if self.current_label is not None:
self.remove_item(self.current_label)
elif event.key() == Qt.Key_F:
self.flip_current_image()
import piexif
def flip_current_image(self):
if self.current_label is not None:
try:
# Open the image using PIL
img = Image.open(self.current_label.path)
# Flip the image horizontally
img = img.transpose(Image.FLIP_LEFT_RIGHT)
# Create new EXIF data with a normal orientation
exif_dict = {"0th": {piexif.ImageIFD.Orientation: 1}}
exif_bytes = piexif.dump(exif_dict)
# Save the image back to the same path with new EXIF data
img.save(self.current_label.path, exif=exif_bytes)
# Reload the image into QPixmap
pixmap = QPixmap(self.current_label.path)
# Scale the image to the appropriate size for the grid
pixmap = pixmap.scaled(self.grid_item_width, self.grid_item_height, aspectRatioMode=Qt.KeepAspectRatio)
# Update the label's pixmap and refresh the label
self.current_label.setPixmap(pixmap)
self.current_label.update()
# Replace the old label in the self.images list with the new one
self.images[self.images.index(self.current_label)] = self.current_label
# Update the preview with the new pixmap
self.update_preview_with_image_resize(self.current_label)
except Exception as e:
print(f"Error when flipping image: {e}")
def navigate_to_previous_image(self):
if self.current_image_index > 0: # prevent underflow
self.current_image_index -= 1
self.select_current_image()
def navigate_to_next_image(self):
if self.current_image_index < len(self.images) - 1: # prevent overflow
self.current_image_index += 1
self.select_current_image()
def navigate_to_previous_row_image(self):
items_in_grid_line = max(1, int((self.size().width() - self.preview_label.size().width()) / (self.grid_item_width + self.grid_spacing)))
if self.current_image_index >= items_in_grid_line: # if there's a row above
self.current_image_index -= items_in_grid_line
self.select_current_image()
def navigate_to_next_row_image(self):
items_in_grid_line = max(1, int((self.size().width() - self.preview_label.size().width()) / (self.grid_item_width + self.grid_spacing)))
if self.current_image_index < len(self.images) - items_in_grid_line: # if there's a row below
self.current_image_index += items_in_grid_line
self.select_current_image()
def select_current_image(self):
self.on_image_clicked(self.images[self.current_image_index])
def adjust_text_height(self):
document_height = self.captions_io.document().size().height()
scroll_bar_height = self.captions_io.verticalScrollBar().sizeHint().height()
widget_height = self.captions_io.sizeHint().height()
if self.captions_io.toPlainText() == "":
self.captions_io.setFixedHeight(min(100, widget_height))
elif document_height + scroll_bar_height > widget_height:
self.captions_io.setFixedHeight(int(document_height + scroll_bar_height))
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
event.ignore()
def add_images_to_preview_area(self, paths):
# Check if paths is a list
if not isinstance(paths, list):
raise TypeError("paths must be a list")
# Loop through the image paths and add them to the preview area
for path in paths:
self.process_image(path)
# You could reuse the logic in dropEvent here for adding images, or create another method
# if path.endswith('.jpg') or path.endswith('.png'):
# if path not in [label.path for label in self.images]:
# pixmap = image_basic.load_image_with_exif(path)
#
# # Check and flip the QPixmap image if it's not already flipped
# if pixmap.transformed(QTransform().scale(-1, 1), Qt.SmoothTransformation) == pixmap:
# pixmap = pixmap.transformed(QTransform().scale(-1, 1), Qt.SmoothTransformation)
#
# pixmap = pixmap.scaled(self.grid_item_width, self.grid_item_height,
# aspectRatioMode=Qt.KeepAspectRatio)
# label = ImageLabel(self)
# label.path = path
# label.setPixmap(pixmap)
#
# # Add close button to the label
# close_button = QPushButton("X", label)
# close_button.setStyleSheet("QPushButton { color: red; }")
# close_button.setFlat(True)
# close_button.setFixedSize(QSize(16, 16))
# close_button.clicked.connect(lambda checked, lbl=label: self.remove_item(lbl))
#
# self.images.append(label)
# self.update_grid_layout()
# else:
# print(f"{path} already exists in the widget!")
supported_formats_list = ['jpg', 'jpeg', 'png', 'bmp', 'tiff', 'webp']
def is_supported_image_format(self, file_name):
return any(file_name.lower().endswith(ext) for ext in self.supported_formats_list)
def dropEvent(self, event):
print(f"dropEvent, urls len: {len(event.mimeData().urls())}")
for url in event.mimeData().urls():
path = url.toLocalFile()
# If the path is a directory, iterate through all files in the directory
if os.path.isdir(path):
for root, dirs, files in os.walk(path):
for file in files:
if self.is_supported_image_format(file):
full_path = os.path.join(root, file)
self.process_image(full_path)
# If the path is a file, process the file directly
elif os.path.isfile(path) and self.is_supported_image_format(path):
self.process_image(path)
else:
event.ignore()
def process_image(self, path):
if path not in [label.path for label in self.images]:
if self.is_supported_image_format(path):
pixmap = image_basic.load_image_with_exif(path)
pixmap = pixmap.scaled(self.grid_item_width, self.grid_item_height,
aspectRatioMode=Qt.KeepAspectRatio)
label = ImageLabel(self)
label.path = path
label.setPixmap(pixmap)
# Add close button to the label
close_button = QPushButton("X", label)
close_button.setStyleSheet("QPushButton { color: red; }")
close_button.setFlat(True)
close_button.setFixedSize(QSize(16, 16))
close_button.clicked.connect(lambda checked, lbl=label: self.remove_item(lbl))
# Read captions from text file at this stage
txt_path = os.path.splitext(path)[0] + '.txt'
self.ensure_txt_file_exists(txt_path)
with open(txt_path, 'r') as txt_file:
content = txt_file.read()
# Store the caption in the map
self.image_captions[path] = content
self.images.append(label)
self.update_grid_layout()
if self.add_labels_checkbox.isChecked():
# print("add_labels_checkbox_changed")
self.sync_labels_on_change()
else:
print(f"{path} already exists in the widget!")
def caption_to_tag_list(self, captions: str) -> list[str]:
tags_list = [caption.strip() for caption in captions.split(',') if caption.strip()]
# Remove duplicates while preserving order
tag_list = list(dict.fromkeys(tags_list))
return tag_list
def tag_list_to_string(self, tags_list: list[str]):
return ', '.join(tags_list)
def add_captions(self):
tags_to_add_list = self.caption_to_tag_list(self.caption_input.text())
comma_place_desired = self.comma_place_input.value()
for label in self.images:
path = label.path
self.add_captions_to_path(tags_to_add_list, comma_place_desired, path)
def add_captions_to_path(self, tags_to_add_list, comma_place_desired, path):
txt_path = os.path.splitext(path)[0] + '.txt'
if not os.path.exists(txt_path):
with open(txt_path, 'w') as txt_file:
pass # Create an empty txt file if it doesn't exist
tags_list = self.caption_to_tag_list(self.image_captions[path])
tags_to_add = [tag for tag in tags_to_add_list if
tag not in tags_list] # Remove tags to add from captions to avoid duplicates
comma_place = comma_place_desired
if comma_place > len(tags_list):
comma_place = len(tags_list)
for tag in reversed(tags_to_add): # Loop over tags to add and insert each one
tags_list.insert(comma_place, tag)
final_captions = self.tag_list_to_string(tags_list)
# Update the caption in the map
self.image_captions[path] = final_captions
with open(txt_path, 'w') as txt_file:
txt_file.write(final_captions)
def remove_captions(self):
tags_to_remove = self.caption_to_tag_list(self.remove_caption_input.text())
for label in self.images:
path = label.path
self.remove_captions_from_path(tags_to_remove, path)
# Define the search_and_replace method
def search_and_replace(self):
search_text = self.search_and_replace_search_input.text()
replace_text = self.search_and_replace_replace_input.text()
search_tags = search_text.split(',')
replace_tags = replace_text.split(',')
is_search_all_text = self.search_and_replace_all_text.isChecked()
is_re = self.search_and_replace_use_re.isChecked()
# Add your search and replace logic here
print(f"search_and_replace, search: \"{search_text}\", replace: \"{replace_text}\".")