-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathtab_review.py
More file actions
1817 lines (1483 loc) · 76.6 KB
/
tab_review.py
File metadata and controls
1817 lines (1483 loc) · 76.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
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 os
import glob
import re
import cv2
import json
import shutil
import numpy as np
from PIL import Image, ImageOps
from file_utils import find_media_files, get_display_name, ALL_MEDIA_EXTS
from PySide6.QtWidgets import (QWidget, QHBoxLayout, QVBoxLayout, QListWidget, QTextEdit, QSlider, QLabel, QSplitter, QGroupBox,
QLineEdit, QCheckBox, QPushButton, QMessageBox, QFormLayout, QFrame, QSizePolicy, QColorDialog, QButtonGroup, QProgressDialog, QComboBox, QScrollArea, QStyle)
from PySide6.QtCore import Qt, QTimer, Signal, QByteArray, QCoreApplication
from PySide6.QtGui import QImage, QPixmap, QFont, QColor, QShortcut, QKeySequence
from gui_widgets import ResizableImageLabel
class RefreshableComboBox(QComboBox):
def __init__(self, parent=None, preset_file="search_replace_presets.json"):
super().__init__(parent)
self.preset_file = preset_file
self.refresh_items()
def showPopup(self):
self.refresh_items()
super().showPopup()
def refresh_items(self):
current_text = self.currentText()
self.blockSignals(True)
self.clear()
self.addItem("Select a Preset...", None)
if os.path.exists(self.preset_file):
try:
with open(self.preset_file, 'r', encoding='utf-8') as f:
data = json.load(f)
for name, values in data.items():
self.addItem(name, values)
except Exception as e:
print(f"Error loading presets: {e}")
# Restore selection if it still exists
index = self.findText(current_text)
if index >= 0:
self.setCurrentIndex(index)
else:
self.setCurrentIndex(0)
self.blockSignals(False)
class ReviewTab(QWidget):
log_msg = Signal(str)
SAVE_BUTTON_STYLE_NORMAL = "background-color: #5d99c4; color: white; font-weight: bold;"
SAVE_BUTTON_STYLE_DIRTY = "background-color: #f1c40f; color: black; font-weight: bold;"
TOOL_BUTTON_STYLE = """
QPushButton { background-color: #3b3b3b; border: 1px solid #555; border-radius: 4px; }
QPushButton:checked { background-color: #5d99c4; border: 1px solid #fff; }
QPushButton:hover:!checked { background-color: #555; }
"""
def __init__(self):
super().__init__()
self.current_folder = ""
self.recursive = False
self.image_files = []
self.current_index = -1
self.last_selected_file = None
self.cv_img_original = None
self.cv_mask = None
self.mask_is_dirty = False
self.last_paint_pos = None
self.mask_overlay_color = QColor(0, 0, 50)
self.undo_snapshot = {}
self.mask_undo_stack = []
self.mask_redo_stack = []
self.cv_dimmed_cache = None
self.is_alpha_mask_mode = False # Track if we are editing an embedded alpha mask
# Undo Delete Stack: Stores dicts of {original_index, items: [(src, dst), ...]}
self.deleted_files_stack = []
# Persistent state for "Show Mask" toggle (to survive video switching)
self.show_mask_state = True
self.video_cap = None
self.total_frames = 0
self.save_timer = QTimer()
self.save_timer.setSingleShot(True)
self.save_timer.setInterval(1000)
self.save_timer.timeout.connect(self.save_current_caption)
self.setup_ui()
self.setup_shortcuts()
self.on_tool_changed()
def setup_ui(self):
layout = QHBoxLayout(self)
splitter = QSplitter(Qt.Horizontal)
self.main_splitter = splitter
# --- LEFT SIDE (Stats & List) ---
left_widget = QWidget()
left_layout = QVBoxLayout(left_widget)
left_layout.setContentsMargins(0, 0, 0, 0)
# Folder Stats
stats_group = QGroupBox("Folder Stats")
stats_layout = QHBoxLayout(stats_group)
stats_layout.setContentsMargins(5, 5, 5, 5)
self.lbl_stat_img = QLabel("Images: 0")
self.lbl_stat_img.setStyleSheet("color: #a3be8c; font-weight: bold;")
self.lbl_stat_txt = QLabel("Captions: 0")
self.lbl_stat_txt.setStyleSheet("color: #a3be8c; font-weight: bold;")
self.lbl_stat_mask = QLabel("Masks: 0")
self.lbl_stat_mask.setStyleSheet("color: #666666; font-weight: bold;")
stats_layout.addWidget(self.lbl_stat_img)
stats_layout.addWidget(self.lbl_stat_txt)
stats_layout.addWidget(self.lbl_stat_mask)
left_layout.addWidget(stats_group)
# File List
self.list_widget = QListWidget()
self.list_widget.currentRowChanged.connect(self.on_row_changed)
left_layout.addWidget(self.list_widget)
# Delete Button
self.btn_delete = QPushButton("🗑️ Move to 'unused' Folder [DEL]")
self.btn_delete.setToolTip("Move current image, text, and mask to /unused subfolder (Del)")
self.btn_delete.clicked.connect(lambda: self.delete_current_image())
left_layout.addWidget(self.btn_delete)
# Undo Delete Button
self.btn_undo_delete = QPushButton("↩️ Undo Delete")
self.btn_undo_delete.setToolTip("Restore the last deleted image.")
self.btn_undo_delete.clicked.connect(self.undo_delete)
self.btn_undo_delete.setEnabled(False)
left_layout.addWidget(self.btn_undo_delete)
# Batch Crop Button
self.btn_crop_all = QPushButton("✂️ Crop All Images to Masks")
self.btn_crop_all.setToolTip("Crop ALL images in the list to their corresponding masks.")
self.btn_crop_all.clicked.connect(self.crop_all_masks)
left_layout.addWidget(self.btn_crop_all)
# Batch Find & Replace
fr_group = QGroupBox("Batch Find && Replace")
fr_layout = QVBoxLayout(fr_group)
input_layout = QFormLayout()
self.txt_find = QLineEdit()
self.txt_find.setPlaceholderText("Find...")
self.txt_find.setToolTip("The text or pattern to search for in all caption files.")
self.txt_replace = QLineEdit()
self.txt_replace.setPlaceholderText("Replace with...")
self.txt_replace.setToolTip("The text to replace the found matches with.")
# Presets ComboBox
self.combo_presets = RefreshableComboBox(preset_file="search_replace_presets.json")
self.combo_presets.currentIndexChanged.connect(self.apply_preset)
self.combo_presets.setToolTip("Select a preset to automatically fill the Find and Replace fields.")
input_layout.addRow("Presets:", self.combo_presets)
input_layout.addRow("Find:", self.txt_find)
input_layout.addRow("Replace:", self.txt_replace)
fr_layout.addLayout(input_layout)
self.chk_case = QCheckBox("Match Case")
self.chk_whole = QCheckBox("Match Whole Word Only")
self.chk_whole.setChecked(True)
opts_layout = QHBoxLayout()
opts_layout.addWidget(self.chk_case)
opts_layout.addWidget(self.chk_whole)
fr_layout.addLayout(opts_layout)
self.btn_apply = QPushButton("Replace All")
self.btn_apply.clicked.connect(self.apply_replace)
self.btn_apply.setStyleSheet("background-color: #d73a49; color: white; font-weight: bold;")
self.btn_undo = QPushButton("Undo Last Replace")
self.btn_undo.clicked.connect(self.undo_last_replace)
self.btn_undo.setEnabled(False)
fr_layout.addWidget(self.btn_apply)
fr_layout.addWidget(self.btn_undo)
left_layout.addWidget(fr_group)
self.main_splitter.addWidget(left_widget)
# --- RIGHT SIDE (Image & Tools) ---
right_widget = QWidget()
right_layout = QVBoxLayout(right_widget)
# Toolbar — wrapped in a horizontal scroll area so the window can shrink below
# the toolbar's natural width on smaller screens. Scrollbar only appears when needed.
toolbar_container = QWidget()
toolbar = QHBoxLayout(toolbar_container)
toolbar.setContentsMargins(2, 2, 2, 2)
toolbar.setSpacing(3)
self.chk_show_mask = QCheckBox("Show Mask Overlay")
self.chk_show_mask.setChecked(True)
self.chk_show_mask.clicked.connect(self.on_show_mask_toggled)
self.chk_show_mask.toggled.connect(self.update_image_display)
self.chk_show_mask.setFixedWidth(155)
self.btn_color_picker = QPushButton()
self.btn_color_picker.setToolTip("Set overlay background color")
self.btn_color_picker.setFixedSize(28, 28)
self.btn_color_picker.clicked.connect(self.pick_overlay_color)
self._update_color_button_style()
self.slider_opacity = QSlider(Qt.Horizontal)
self.slider_opacity.setRange(0, 100)
self.slider_opacity.setValue(80)
self.slider_opacity.setFixedWidth(120)
self.slider_opacity.valueChanged.connect(self.on_opacity_changed)
self.slider_opacity.setToolTip("Adjust background dimming intensity.")
self.lbl_opacity_val = QLabel("80%")
self.lbl_opacity_val.setFixedWidth(35)
self.slider_opacity.valueChanged.connect(lambda v: self.lbl_opacity_val.setText(f"{v}%"))
toolbar.addWidget(self.chk_show_mask)
toolbar.addSpacing(2)
toolbar.addWidget(self.btn_color_picker)
toolbar.addWidget(self.slider_opacity)
toolbar.addWidget(self.lbl_opacity_val)
separator = QFrame()
separator.setFrameShape(QFrame.VLine)
separator.setFrameShadow(QFrame.Sunken)
toolbar.addWidget(separator)
emoji_font = QFont("Segoe UI Emoji", 12)
# Tool Selection
self.btn_tool_brush = QPushButton("🖌️")
self.btn_tool_brush.setFont(emoji_font)
self.btn_tool_brush.setCheckable(True)
self.btn_tool_brush.setChecked(True)
self.btn_tool_brush.setToolTip("Brush Tool (B)")
self.btn_tool_brush.setFixedSize(32, 30)
self.btn_tool_brush.setStyleSheet(self.TOOL_BUTTON_STYLE)
self.btn_tool_bucket = QPushButton("🪣")
self.btn_tool_bucket.setFont(emoji_font)
self.btn_tool_bucket.setCheckable(True)
self.btn_tool_bucket.setToolTip("Bucket Fill Tool (F)\nFills connected mask area.")
self.btn_tool_bucket.setFixedSize(32, 30)
self.btn_tool_bucket.setStyleSheet(self.TOOL_BUTTON_STYLE)
# Group to ensure only one is active at a time
self.tool_group = QButtonGroup(self)
self.tool_group.addButton(self.btn_tool_brush)
self.tool_group.addButton(self.btn_tool_bucket)
# signal connection to a new dedicated handler
self.tool_group.buttonClicked.connect(self.on_tool_changed)
toolbar.addWidget(self.btn_tool_bucket)
toolbar.addWidget(self.btn_tool_brush)
toolbar.addSpacing(4)
# Brush Controls
self.lbl_brush_size = QLabel("Brush:")
self.slider_brush = QSlider(Qt.Horizontal)
self.slider_brush.setRange(1, 30)
self.slider_brush.setValue(10)
self.slider_brush.setFixedWidth(100)
self.slider_brush.setToolTip("Adjust brush size. Shortcuts: [ and ]")
self.slider_brush.valueChanged.connect(self.on_brush_size_changed)
self.lbl_brush_val = QLabel("10%")
self.lbl_brush_val.setFixedWidth(35)
toolbar.addWidget(self.lbl_brush_size)
toolbar.addWidget(self.slider_brush)
toolbar.addWidget(self.lbl_brush_val)
# Mask Action Buttons
self.btn_fill_black = QPushButton("⬛ Fill")
self.btn_fill_black.setToolTip("Fill mask with black (background)")
self.btn_fill_black.setFixedSize(60, 30)
self.btn_fill_black.clicked.connect(lambda: self.fill_mask(0))
self.btn_fill_white = QPushButton("⬜ Fill")
self.btn_fill_white.setToolTip("Fill mask with white (foreground)")
self.btn_fill_white.setFixedSize(60, 30)
self.btn_fill_white.clicked.connect(lambda: self.fill_mask(255))
self.btn_save_mask = QPushButton("💾 Save")
self.btn_save_mask.setToolTip("Save current mask to disk (Ctrl+S)")
self.btn_save_mask.setFixedSize(60, 30)
self.btn_save_mask.clicked.connect(self.save_current_mask)
self.btn_discard_mask = QPushButton("↩️ Discard")
self.btn_discard_mask.setToolTip("Discard unsaved changes to mask (Reverts to last saved state)")
self.btn_discard_mask.setFixedSize(90, 30)
self.btn_discard_mask.clicked.connect(self.discard_mask_changes)
self.btn_crop_mask = QPushButton("✂️ Crop")
self.btn_crop_mask.setToolTip("Crop image and mask to the mask's bounding box (C).\nThis moves the original files to an 'uncropped' subfolder.")
self.btn_crop_mask.setFixedSize(70, 30)
self.btn_crop_mask.clicked.connect(self.crop_to_mask)
# Undo
self.btn_mask_undo = QPushButton("↩️ Undo")
self.btn_mask_undo.setToolTip("Undo mask change (Ctrl+Z)")
self.btn_mask_undo.setFixedSize(60, 30)
self.btn_mask_undo.clicked.connect(self.undo_mask_action)
self.btn_mask_undo.setEnabled(False)
# Redo
self.btn_mask_redo = QPushButton("↪️ Redo")
self.btn_mask_redo.setToolTip("Redo mask change (Ctrl+Y)")
self.btn_mask_redo.setFixedSize(60, 30)
self.btn_mask_redo.clicked.connect(self.redo_mask_action)
self.btn_mask_redo.setEnabled(False)
# Mask Expansion / Contraction
self.btn_mask_contract = QPushButton("➖ Contract")
self.btn_mask_contract.setToolTip("Contract Mask (Minus Key)")
self.btn_mask_contract.setFixedSize(80, 30)
self.btn_mask_contract.clicked.connect(lambda: self.modify_mask(-1))
self.btn_mask_expand = QPushButton("➕ Expand")
self.btn_mask_expand.setToolTip("Expand Mask (Plus Key)")
self.btn_mask_expand.setFixedSize(80, 30)
self.btn_mask_expand.clicked.connect(lambda: self.modify_mask(1))
# Add buttons to toolbar
toolbar.addWidget(self.btn_fill_black)
toolbar.addWidget(self.btn_fill_white)
toolbar.addWidget(self.btn_mask_contract)
toolbar.addWidget(self.btn_mask_expand)
toolbar.addWidget(self.btn_crop_mask)
toolbar.addWidget(self.btn_save_mask)
toolbar.addWidget(self.btn_discard_mask)
toolbar.addWidget(self.btn_mask_undo)
toolbar.addWidget(self.btn_mask_redo)
# Spacer
toolbar.addStretch()
# Confirm Toggle
self.chk_confirm_actions = QCheckBox("Confirm Actions")
self.chk_confirm_actions.setChecked(True)
self.chk_confirm_actions.setToolTip("Uncheck to disable confirmation popups for Fill, Crop, and Discard operations.")
toolbar.addWidget(self.chk_confirm_actions)
toolbar_scroll = QScrollArea()
toolbar_scroll.setWidget(toolbar_container)
toolbar_scroll.setWidgetResizable(True)
toolbar_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
toolbar_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
toolbar_scroll.setFrameShape(QFrame.NoFrame)
# Reserve enough height for the toolbar plus the horizontal scrollbar so widgets
# don't get clipped when the scrollbar appears on narrow windows.
scrollbar_extent = toolbar_scroll.style().pixelMetric(QStyle.PM_ScrollBarExtent)
toolbar_fixed_height = toolbar_container.sizeHint().height() + scrollbar_extent + 6
toolbar_scroll.setFixedHeight(toolbar_fixed_height)
toolbar_scroll.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
# Allow the scroll area itself to shrink well below the toolbar's natural width.
toolbar_scroll.setMinimumWidth(0)
right_layout.addWidget(toolbar_scroll)
# Mouse Help Label
self.lbl_mouse_help = QLabel("Left Mouse Button: Draw / Fill (mask foreground) | Right Mouse Button: Erase / Fill (mask background) | Middle Mouse Button: Switch Tool | Scroll Wheel: scroll through image list")
self.lbl_mouse_help.setAlignment(Qt.AlignCenter)
self.lbl_mouse_help.setStyleSheet("color: #888; font-size: 11px; margin-bottom: 2px;")
right_layout.addWidget(self.lbl_mouse_help)
# Image Display
self.lbl_image = ResizableImageLabel()
self.lbl_image.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
self.lbl_image.setFocusPolicy(Qt.StrongFocus)
self.lbl_image.wheelEvent = self.image_wheel_event
self.lbl_image.paint_start.connect(self.on_paint_start)
self.lbl_image.paint_move.connect(self.on_paint_move)
self.lbl_image.paint_end.connect(self.on_paint_end)
self.lbl_image.view_resized.connect(self._update_brush_cursor_size)
self.lbl_image.middle_click.connect(self.toggle_tool)
# Video Controls
self.video_controls_layout = QHBoxLayout()
self.lbl_frame_info = QLabel("Frame: 0 / 0")
self.lbl_frame_info.setStyleSheet("color: #888;")
self.slider_video = QSlider(Qt.Horizontal)
self.slider_video.setToolTip("Scrub video frames")
self.slider_video.valueChanged.connect(self.seek_video)
self.slider_video.setEnabled(False)
self.video_controls_layout.addWidget(QLabel("🎞️"))
self.video_controls_layout.addWidget(self.slider_video)
self.video_controls_layout.addWidget(self.lbl_frame_info)
# Container widget to easily hide/show
self.wid_video_controls = QWidget()
self.wid_video_controls.setLayout(self.video_controls_layout)
self.wid_video_controls.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
self.wid_video_controls.setVisible(False) # Hide by default
# Caption Edit
self.txt_caption = QTextEdit()
self.txt_caption.setPlaceholderText("Select an image to edit caption...")
self.txt_caption.textChanged.connect(self.on_text_changed)
self.txt_caption.setMaximumHeight(16777215)
# Info & Slider
self.lbl_info = QLabel("0 / 0")
self.lbl_info.setAlignment(Qt.AlignCenter)
self.slider = QSlider(Qt.Horizontal)
self.slider.valueChanged.connect(self.on_slider_changed)
# Vertical Splitter
self.vertical_splitter = QSplitter(Qt.Vertical)
self.vertical_splitter.setHandleWidth(2)
# Top Pane: Image + Video
top_pane = QWidget()
top_layout = QVBoxLayout(top_pane)
top_layout.setContentsMargins(0,0,0,0)
top_layout.addWidget(self.lbl_image, stretch=1)
top_layout.addWidget(self.wid_video_controls)
self.vertical_splitter.addWidget(top_pane)
self.vertical_splitter.addWidget(self.txt_caption)
self.vertical_splitter.setSizes([600, 150])
self.vertical_splitter.setCollapsible(0, False)
self.vertical_splitter.setCollapsible(1, False)
right_layout.addWidget(self.vertical_splitter, stretch=1)
right_layout.addWidget(self.lbl_info)
right_layout.addWidget(self.slider)
self.main_splitter.addWidget(right_widget)
self.main_splitter.setStretchFactor(1, 1)
layout.addWidget(self.main_splitter)
self._update_mask_button_states()
def set_focus_to_image(self):
"""Public method to allow the main window to set focus here."""
self.lbl_image.setFocus()
def setup_shortcuts(self):
QShortcut(QKeySequence("Ctrl+S"), self, self.save_current_mask)
QShortcut(QKeySequence("Ctrl+Z"), self, self.undo_mask_action)
QShortcut(QKeySequence("Ctrl+Y"), self, self.redo_mask_action)
QShortcut(QKeySequence("Ctrl+Shift+Z"), self, self.redo_mask_action)
QShortcut(QKeySequence("Del"), self, self.delete_current_image)
QShortcut(QKeySequence("["), self, lambda: self.slider_brush.setValue(self.slider_brush.value() - 1))
QShortcut(QKeySequence("]"), self, lambda: self.slider_brush.setValue(self.slider_brush.value() + 1))
QShortcut(QKeySequence("Left"), self, lambda: self.navigate(-1))
QShortcut(QKeySequence("Right"), self, lambda: self.navigate(1))
QShortcut(QKeySequence("B"), self, self.btn_tool_brush.click)
QShortcut(QKeySequence("F"), self, self.btn_tool_bucket.click)
QShortcut(QKeySequence("C"), self, self.crop_to_mask)
QShortcut(QKeySequence("+"), self, lambda: self.modify_mask(1))
QShortcut(QKeySequence("="), self, lambda: self.modify_mask(1)) # Support = as +
QShortcut(QKeySequence("-"), self, lambda: self.modify_mask(-1))
def get_settings(self):
# Get current filename safely
current_file = None
if 0 <= self.current_index < len(self.image_files):
current_file = get_display_name(self.image_files[self.current_index], self.current_folder, self.recursive)
return {
"find_text": self.txt_find.text(),
"replace_text": self.txt_replace.text(),
"match_case": self.chk_case.isChecked(),
"match_whole": self.chk_whole.isChecked(),
"show_mask": self.show_mask_state,
"confirm_actions": self.chk_confirm_actions.isChecked(),
"mask_opacity": self.slider_opacity.value(),
"brush_size": self.slider_brush.value(),
"mask_overlay_color": self.mask_overlay_color.name(),
"main_splitter_state": self.main_splitter.saveState().toHex().data().decode(),
"vertical_splitter_state": self.vertical_splitter.saveState().toHex().data().decode(),
"last_selected_file": current_file
}
def set_settings(self, settings):
if not settings: return
if "find_text" in settings: self.txt_find.setText(settings["find_text"])
if "replace_text" in settings: self.txt_replace.setText(settings["replace_text"])
if "match_case" in settings: self.chk_case.setChecked(settings["match_case"])
if "match_whole" in settings: self.chk_whole.setChecked(settings["match_whole"])
if "show_mask" in settings:
self.show_mask_state = settings["show_mask"]
self.chk_show_mask.setChecked(self.show_mask_state)
if "confirm_actions" in settings: self.chk_confirm_actions.setChecked(settings["confirm_actions"])
if "mask_opacity" in settings: self.slider_opacity.setValue(settings["mask_opacity"])
if "brush_size" in settings: self.slider_brush.setValue(settings["brush_size"])
if "mask_overlay_color" in settings:
self.mask_overlay_color = QColor(settings["mask_overlay_color"])
self._update_color_button_style()
if "last_selected_file" in settings:
self.last_selected_file = settings["last_selected_file"]
if "main_splitter_state" in settings:
try: self.main_splitter.restoreState(QByteArray.fromHex(settings["main_splitter_state"].encode()))
except: pass
elif "splitter_state" in settings:
# Migration for old settings
try: self.main_splitter.restoreState(QByteArray.fromHex(settings["splitter_state"].encode()))
except: pass
if "vertical_splitter_state" in settings:
try: self.vertical_splitter.restoreState(QByteArray.fromHex(settings["vertical_splitter_state"].encode()))
except: pass
def _refresh_dimmed_cache(self):
"""
Performance Optimization:
Pre-calculates the 'dimmed' background (Image + Color Overlay) so we don't
have to run cv2.addWeighted() on every single mouse movement.
"""
if self.cv_img_original is None:
self.cv_dimmed_cache = None
return
opacity = self.slider_opacity.value() / 100.0
brightness = 1.0 - opacity
r, g, b, _ = self.mask_overlay_color.getRgb()
# Create the solid color block (Allocating this 60fps is slow, so we do it here)
color_overlay = np.full(self.cv_img_original.shape, (r, g, b), dtype=np.uint8)
# Perform the heavy blending operation once
self.cv_dimmed_cache = cv2.addWeighted(
self.cv_img_original, brightness,
color_overlay, opacity,
0
)
def _update_mask_button_states(self):
has_image = self.cv_img_original is not None
has_mask = self.cv_mask is not None
is_video = self.video_cap is not None # Check if video
# Disable mask-specific items if it is a video
self.chk_show_mask.setEnabled(has_mask and not is_video)
self.slider_opacity.setEnabled(has_mask and not is_video)
self.btn_color_picker.setEnabled(has_mask and not is_video)
self.btn_fill_black.setEnabled(has_image and not is_video)
self.btn_fill_white.setEnabled(has_image and not is_video)
self.btn_mask_contract.setEnabled(has_mask and not is_video)
self.btn_mask_expand.setEnabled(has_mask and not is_video)
self.slider_brush.setEnabled(has_mask and not is_video)
# Crop logic
can_crop = has_mask and not is_video
self.btn_crop_mask.setEnabled(can_crop)
self.btn_save_mask.setEnabled(self.mask_is_dirty and not is_video)
self.btn_discard_mask.setEnabled(self.mask_is_dirty and not is_video)
# Styles
if self.mask_is_dirty:
self.btn_save_mask.setStyleSheet(self.SAVE_BUTTON_STYLE_DIRTY)
if has_mask: self.chk_show_mask.setText("Show Mask (* Unsaved)")
else:
self.btn_save_mask.setStyleSheet(self.SAVE_BUTTON_STYLE_NORMAL)
if has_mask and not is_video:
self.chk_show_mask.setText("Show Mask (Saved)")
elif is_video:
self.chk_show_mask.setText("Masks Disabled (Video)")
def _draw_on_mask(self, x, y, button):
if self.cv_mask is None or self.cv_img_original is None: return
brush_percentage = self.slider_brush.value() / 100.0
h, w = self.cv_img_original.shape[:2]
max_dimension = max(h, w)
brush_size_px = max(1, int(max_dimension * brush_percentage))
color = 255 if button == Qt.LeftButton else 0
if self.last_paint_pos:
cv2.line(self.cv_mask, self.last_paint_pos, (x, y), color, brush_size_px, cv2.FILLED)
else:
cv2.circle(self.cv_mask, (x, y), brush_size_px // 2, color, -1, cv2.FILLED)
self.last_paint_pos = (x, y)
if not self.mask_is_dirty:
self.mask_is_dirty = True
self._update_mask_button_states()
self.update_image_display()
def toggle_tool(self):
"""Swaps the active tool (Brush <-> Bucket) and triggers UI updates."""
if self.btn_tool_brush.isChecked():
self.btn_tool_bucket.click()
else:
self.btn_tool_brush.click()
def on_tool_changed(self, button=None):
"""
Handles switching between tools.
Updates the cursor and the brush overlay visibility.
"""
if self.btn_tool_bucket.isChecked():
# Bucket Mode:
# 1. Set cursor to a specific icon (Pointing Hand or Arrow)
self.lbl_image.setCursor(Qt.PointingHandCursor)
# 2. Hide the brush circle overlay
self.lbl_image.set_brush_outline_size(0)
else:
# Brush Mode:
# 1. Hide system cursor (so we only see the custom circle)
self.lbl_image.setCursor(Qt.BlankCursor)
# 2. Update/Show the brush circle overlay
self._update_brush_cursor_size()
def on_brush_size_changed(self, value):
self.lbl_brush_val.setText(f"{value}%")
self._update_brush_cursor_size()
def _update_brush_cursor_size(self, _=None):
# Safety check: If bucket is selected, force brush size to 0 and exit.
if self.btn_tool_bucket.isChecked():
self.lbl_image.set_brush_outline_size(0)
return
if self.cv_img_original is None or self.lbl_image.pixmap() is None or self.lbl_image.pixmap().isNull():
self.lbl_image.set_brush_outline_size(0)
# Restore standard cursor if no image is loaded
self.lbl_image.setCursor(Qt.ArrowCursor)
return
# Ensure we are using the Blank cursor when brush is active
# (in case it was switched elsewhere)
if self.lbl_image.cursor().shape() != Qt.BlankCursor:
self.lbl_image.setCursor(Qt.BlankCursor)
brush_percentage = self.slider_brush.value() / 100.0
h, w = self.cv_img_original.shape[:2]
max_dimension = max(h, w)
brush_size_image_px = max(1, int(max_dimension * brush_percentage))
scale_w = self.lbl_image.pixmap().width() / w
scale_h = self.lbl_image.pixmap().height() / h
scale = min(scale_w, scale_h)
widget_brush_size = brush_size_image_px * scale
self.lbl_image.set_brush_outline_size(widget_brush_size)
def _flood_fill_mask(self, x, y, button):
if self.cv_img_original is None: return
# Ensure mask exists
h, w = self.cv_img_original.shape[:2]
if self.cv_mask is None:
self.cv_mask = np.zeros((h, w), dtype=np.uint8)
# Determine fill color: Left Click = White (255), Right Click = Black (0)
fill_value = 255 if button == Qt.LeftButton else 0
# cv2.floodFill modifies the image in-place.
# It requires a mask slightly larger than the image (h+2, w+2) for processing
flood_mask = np.zeros((h + 2, w + 2), np.uint8)
# Perform fill
# loDiff and upDiff are 0 because we are filling a binary mask (0 or 255)
# flags=4 means 4-connected pixels (up/down/left/right)
try:
cv2.floodFill(self.cv_mask, flood_mask, (x, y), fill_value, 0, 0, flags=4)
self.mask_is_dirty = True
self._update_mask_button_states()
self.update_image_display()
except Exception as e:
# Click might be outside bounds or other CV error
print(f"Fill error: {e}")
def on_paint_start(self, x, y, button):
# Ensure mask exists before painting starts
if self.cv_img_original is not None:
h, w = self.cv_img_original.shape[:2]
if self.cv_mask is None:
self.cv_mask = np.zeros((h, w), dtype=np.uint8)
# Save state before drawing
self._push_undo_state()
if self.btn_tool_bucket.isChecked():
self._flood_fill_mask(x, y, button)
else:
self.last_paint_pos = None
self._draw_on_mask(x, y, button)
def on_paint_move(self, x, y, button):
if self.btn_tool_bucket.isChecked():
return
self._draw_on_mask(x, y, button)
def on_paint_end(self, button):
self.last_paint_pos = None
def _get_current_mask_path(self):
if self.current_index < 0 or self.current_index >= len(self.image_files): return None
f_path = self.image_files[self.current_index]
base, _ = os.path.splitext(f_path)
return f"{base}-masklabel.png"
def save_current_mask(self):
if self.cv_mask is None or not self.mask_is_dirty: return
try:
if self.is_alpha_mask_mode:
# Alpha Mode: Save back to the original image file
f_path = self.image_files[self.current_index]
# 1. Load original image (to get color channels)
# We can use self.cv_img_original, but need to be sure it's valid RGB
pil_img = Image.fromarray(self.cv_img_original)
# 2. Resize mask if needed
pil_mask = Image.fromarray(self.cv_mask)
if pil_mask.size != pil_img.size:
pil_mask = pil_mask.resize(pil_img.size, Image.NEAREST)
# 3. Merge
r, g, b = pil_img.split()
pil_final = Image.merge("RGBA", (r, g, b, pil_mask))
# 4. Save (Overwrite)
pil_final.save(f_path, compress_level=1)
self.log_msg.emit(f"✅ Mask saved to alpha channel: {os.path.basename(f_path)}")
elif getattr(self, 'mask_subfolder_mode', False):
# Subfolder Mode: masks/filename.png
f_path = self.image_files[self.current_index]
folder = os.path.dirname(f_path)
filename = os.path.basename(f_path)
base_name = os.path.splitext(filename)[0]
masks_dir = os.path.join(folder, "masks")
if not os.path.exists(masks_dir):
os.makedirs(masks_dir, exist_ok=True)
mask_path = os.path.join(masks_dir, f"{base_name}.png")
cv2.imwrite(mask_path, self.cv_mask, [cv2.IMWRITE_PNG_COMPRESSION, 1])
self.log_msg.emit(f"✅ Mask saved to subfolder: {os.path.basename(mask_path)}")
else:
# Separate File Mode
mask_path = self._get_current_mask_path()
if not mask_path: return
cv2.imwrite(mask_path, self.cv_mask, [cv2.IMWRITE_PNG_COMPRESSION, 1])
self.log_msg.emit(f"✅ Mask saved: {os.path.basename(mask_path)}")
self.mask_is_dirty = False
self._update_mask_button_states()
self.update_stats()
except Exception as e:
self.log_msg.emit(f"❌ Error saving mask: {e}")
QMessageBox.critical(self, "Save Error", f"Could not save mask.\n\nError: {e}")
def crop_all_masks(self):
"""Iterates through all files, checks for masks, and crops them."""
# 1. Check for unsaved changes on the current image first
if not self.check_unsaved_changes():
return
# 2. Confirm Action
msg = (
"⚠️ <b>Are you sure you want to crop ALL images?</b><br><br>"
"This will:<br>"
"1. Scan every image in the folder.<br>"
"2. If a matching mask exists, crop the image and mask to the content.<br>"
"3. Move original files to an 'uncropped' subfolder.<br><br>"
"This process might take a moment."
)
reply = QMessageBox.question(self, "Confirm Batch Crop", msg, QMessageBox.Yes | QMessageBox.No)
if reply == QMessageBox.No:
return
# 3. Setup
uncropped_dir = os.path.join(self.current_folder, "uncropped")
count_processed = 0
count_skipped = 0
errors = []
total_images = len(self.image_files)
# --- PROGRESS BAR SETUP ---
progress = QProgressDialog("Preparing to crop...", "Cancel", 0, total_images, self)
progress.setWindowTitle("Batch Crop Progress")
progress.setWindowModality(Qt.WindowModal)
progress.setMinimumDuration(0) # Force it to show immediately
# Apply stylesheet to enforce consistent dark theme and prevent "inactive" graying
progress.setStyleSheet("""
QDialog {
background-color: #2b2b2b;
color: #ffffff;
}
QLabel {
color: #e0e0e0;
font-size: 13px;
font-weight: bold;
}
QProgressBar {
border: 1px solid #555;
border-radius: 4px;
text-align: center;
background-color: #333;
color: white;
font-weight: bold;
}
QProgressBar::chunk {
background-color: #a15f13;
width: 20px;
}
QPushButton {
background-color: #d73a49;
color: white;
border: 1px solid #ab2636;
border-radius: 4px;
padding: 5px 15px;
font-weight: bold;
}
QPushButton:hover {
background-color: #cb2431;
}
""")
progress.setValue(0)
# --------------------------
# Change cursor to wait
self.setCursor(Qt.WaitCursor)
try:
# Ensure output directory exists if we are going to use it
if not os.path.exists(uncropped_dir):
os.makedirs(uncropped_dir, exist_ok=True)
file_pairs = []
for f_path in self.image_files:
base, _ = os.path.splitext(f_path)
filename = os.path.basename(f_path)
base_name = os.path.splitext(filename)[0]
mask_path_std = f"{base}-masklabel.png"
mask_path_sub = os.path.join(os.path.dirname(f_path), "masks", f"{base_name}.png")
# Check Priority: Subfolder > Separate File > Alpha
has_sub_mask = os.path.exists(mask_path_sub)
has_mask_file = False
has_alpha = False
final_source_type = None
final_mask_source = None
if has_sub_mask:
final_source_type = 'subfolder'
final_mask_source = mask_path_sub
else:
has_mask_file = os.path.exists(mask_path_std)
if has_mask_file:
final_source_type = 'file'
final_mask_source = mask_path_std
else:
# Simple check for alpha candidacy without opening file
final_source_type = 'alpha'
if final_source_type:
file_pairs.append((f_path, final_mask_source, final_source_type))
# -------------------------------
if not file_pairs:
self.log_msg.emit("⚠️ No masks (or candidates) found to crop.")
self.setCursor(Qt.ArrowCursor)
progress.close()
return
self.log_msg.emit(f"🚀 Starting batch crop on {len(file_pairs)} images...")
# --- LAUNCH WORKER ---
from gui_workers import CropWorker
self.crop_worker = CropWorker(file_pairs, uncropped_dir)
# Connect Signals
self.crop_worker.progress.connect(progress.setValue)
self.crop_worker.log.connect(lambda m: self.log_msg.emit(m))
def on_finished():
self.setCursor(Qt.ArrowCursor)
progress.close()
# Refresh file list / current view
self.refresh_file_list()
if self.current_index >= 0:
self.load_image_and_data(self.current_index) # Reload current
QMessageBox.information(self, "Batch Crop", f"Batch crop finished.\nOriginals saved to 'uncropped' folder.")
self.crop_worker = None # cleanup
self.crop_worker.finished.connect(on_finished)
# Handle Progress Cancel
progress.canceled.connect(self.crop_worker.stop)
# Adjust Progress Range
progress.setMaximum(len(file_pairs))
progress.setValue(0)
self.crop_worker.start()
# ---------------------
except Exception as e:
self.setCursor(Qt.ArrowCursor)
progress.close()
self.log_msg.emit(f"❌ Batch crop failed: {e}")
QMessageBox.critical(self, "Error", f"An error occurred: {e}")
def crop_to_mask(self):
if self.current_index < 0 or self.cv_mask is None:
return
# If mask has changes, save them first so the backup file
# created later contains the most recent edits.
if self.mask_is_dirty:
self.save_current_mask()
# Safety check: If save failed (still dirty), abort crop
if self.mask_is_dirty:
return
# 1. Get Bounding Box from current mask data
try:
pil_mask = Image.fromarray(self.cv_mask)
bbox = pil_mask.getbbox()
if not bbox:
# Mask is empty — cropping would produce nothing. Treat the image
# as unusable and offer to move it to the 'unused' folder.
reply = QMessageBox.question(
self,
"Empty Mask",
"The current mask is empty, so there is nothing to crop to.<br><br>"
"Do you want to move this image to the <b>'unused'</b> folder instead?",
QMessageBox.Yes | QMessageBox.No
)
if reply == QMessageBox.Yes:
self.delete_current_image(skip_confirm=True)
return
except Exception as e:
QMessageBox.critical(self, "Crop Error", f"Could not process mask for cropping:\n{e}")
return
# 2. Confirm with user (If enabled)
if self.chk_confirm_actions.isChecked():
reply = QMessageBox.question(self, "Confirm Crop",
"This will:\n"
"1. Crop the current image and its mask.\n"
"2. Overwrite the original files with the cropped versions.\n"
"3. Move the original full-size files to an 'uncropped' subfolder.\n\n"
"This action cannot be undone. Proceed?",
QMessageBox.Yes | QMessageBox.No)
if reply == QMessageBox.No:
return
# 3. Get paths
current_image_path = self.image_files[self.current_index]
current_mask_path = self._get_current_mask_path() # Default separate file path
uncropped_dir = os.path.join(self.current_folder, "uncropped")
os.makedirs(uncropped_dir, exist_ok=True)
uncropped_image_path = os.path.join(uncropped_dir, os.path.basename(current_image_path))
# Handle Subfolder Mask Mode
if getattr(self, 'mask_subfolder_mode', False):
folder = os.path.dirname(current_image_path)
base_name = os.path.splitext(os.path.basename(current_image_path))[0]
current_mask_path = os.path.join(folder, "masks", f"{base_name}.png")
uncropped_masks_dir = os.path.join(uncropped_dir, "masks")
if not os.path.exists(uncropped_masks_dir):
os.makedirs(uncropped_masks_dir, exist_ok=True)
uncropped_mask_path = os.path.join(uncropped_masks_dir, f"{base_name}.png")