-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshotboard.py
1810 lines (1405 loc) · 68 KB
/
shotboard.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
# ShotBoard
# By Jean-Yves 'madjyc' Chasle
# SPDX-License-Identifier: MIT
# ShotBoard: Visualize movies shot by shot
# Research
# https://python.hotexamples.com/fr/examples/PyQt5.QtMultimedia/QMediaPlayer/setMedia/python-qmediaplayer-setmedia-method-examples.html
# https://stackoverflow.com/questions/52359924/pyqt5-access-frames-with-qmediaplayer
# https://stackoverflow.com/questions/27006902/force-qmediaplayer-to-update-position-accurately-for-video-scrubbing-application
# https://stackoverflow.com/questions/57889211/pyqt-qmediaplayer-setposition-rounds-the-position-value
from shotboard_db import *
from shotboard_ui import *
from shotboard_cmd import *
import ffmpeg
import cv2
import numpy as np
from skimage.metrics import structural_similarity as ssim
import matplotlib.pyplot as plt
import os
import sys
import subprocess
import datetime
from functools import wraps
from PyQt5.QtCore import Qt, pyqtSignal, QRect, QTimer, QTime, QElapsedTimer
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QShortcut, QMessageBox, QDialog, QFileDialog, QProgressDialog
from PyQt5.QtWidgets import QSplitter, QHBoxLayout, QVBoxLayout, QGridLayout, QScrollArea, QSlider, QSpinBox
from PyQt5.QtWidgets import QLabel, QPushButton, QToolButton, QCheckBox
from PyQt5.QtWidgets import QAction, QStyle
from PyQt5.QtGui import QKeySequence, QIcon, QPalette, QColor
from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent
from PyQt5.QtMultimediaWidgets import QVideoWidget
APP_VERSION = "0.6.8"
# Main UI
DEFAULT_TITLE = "ShotBoard"
SPLITTER_HANDLE_WIDTH = 2
UPDATE_TIMER_INTERVAL = 1000 # 1 s
# Detection
MIN_SSIM_DROP_THRESHOLD = 0.05
MAX_SSIM_DROP_THRESHOLD = 0.30
DEFAULT_SSIM_DROP_THRESHOLD = 0.10
HISTOGRAM_BINS = 256
HISTOGRAM_THRESHOLD = 0.5
PIXEL_DIFF_THRESHOLD = 0.01
PIXEL_BINARY_THRESHOLD = 48
# Detection slider
DETECTION_SLIDER_STEPS = int((MAX_SSIM_DROP_THRESHOLD - MIN_SSIM_DROP_THRESHOLD) / 0.01)
DEFAULT_DETECTION_SLIDER_VALUE = int(((0.25 - MIN_SSIM_DROP_THRESHOLD) / (MAX_SSIM_DROP_THRESHOLD - MIN_SSIM_DROP_THRESHOLD)) * DETECTION_SLIDER_STEPS)
# UI colors
VIDEO_BACKGROUND_COLOR = "#000000" # Black
BOARD_BACKGROUND_COLOR = "#2e2e2e" # Dark gray
# Debug
PRINT_DEFAULT_COLOR = '\033[0m'
PRINT_GRAY_COLOR = '\033[90m'
PRINT_RED_COLOR = '\033[91m' # red
PRINT_GREEN_COLOR = '\033[92m' # green
PRINT_YELLOW_COLOR = '\033[93m' # yellow
PRINT_CYAN_COLOR = '\033[96m' # cyan
# Auto-save
RCLICK_SAVE = True
##
## DECORATORS
##
LOG_FUNCTION_NAMES = False
def log_function_name(has_params=False, color=PRINT_DEFAULT_COLOR):
def decorator(func):
def wrapper(self, *args, **kwargs):
if LOG_FUNCTION_NAMES:
class_name = self.__class__.__name__
function_name = func.__name__
print(f"Calling function: {class_name}.{color}{function_name}{PRINT_DEFAULT_COLOR}")
return func(self, *args, **kwargs) if has_params else func(self)
return wrapper
return decorator
# Undo/redo command wrapper (selection context)
def command_selection_context(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
# Store context before action execution
old_first_index, old_last_index = self._selection_first_index, self._selection_last_index
# Execute action
func(self, *args, **kwargs)
# Store context after action execution
new_first_index, new_last_index = self._selection_first_index, self._selection_last_index
# Push undo/redo command in history
cmd = Command()
cmd.set_undo(func=self.restore_selection, data={'first_index': old_first_index, 'last_index': old_last_index})
cmd.set_redo(func=self.restore_selection, data={'first_index': new_first_index, 'last_index': new_last_index})
self._history.push(cmd)
return wrapper
# Undo/redo command wrapper (full context)
def command_full_context(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
# Store context before action execution
old_frame_indexes = self._db.get_shots()
old_first_index, old_last_index = self._selection_first_index, self._selection_last_index
# Execute action
result = func(self, *args, **kwargs)
if result is None:
return # Stop execution if action was unsuccessful
# Store context after action execution
new_frame_indexes = self._db.get_shots()
new_first_index, new_last_index = self._selection_first_index, self._selection_last_index
# Push undo/redo command in history
cmd = Command()
cmd.set_undo(func=self.restore_context, data={'frame_indexes': old_frame_indexes, 'first_index': old_first_index, 'last_index': old_last_index})
cmd.set_redo(func=self.restore_context, data={'frame_indexes': new_frame_indexes, 'first_index': new_first_index, 'last_index': new_last_index})
self._history.push(cmd)
return result
return wrapper
##
## MAIN WINDOW
##
class ShotBoard(QMainWindow):
class ClickableScrollArea(QScrollArea):
clicked = pyqtSignal() # Signal to emit when the scroll area is clicked
def mousePressEvent(self, event):
self.clicked.emit()
# Call the base class implementation to ensure normal behavior
super().mousePressEvent(event)
@log_function_name(has_params=True, color=PRINT_GREEN_COLOR)
def __init__(self, geom=QRect(100, 100, 800, 600)):
super().__init__()
self._db = ShotBoardDb()
self._db_path = None
self._history = CommandHistory()
self._shot_widgets = []
self._selection_first_index = None
self._selection_last_index = None
self._video_path = None
self._fps = 0
self._frame_count = None
self._frame_width = 0
self._frame_height = 0
self._duration = 0
self._ui_enabled = True
self.update_window_title()
self.setGeometry(geom)
self.setMinimumSize(1024, 768)
self.create_menu()
# Create the top and bottom widgets
top_widget = self.create_top_widget()
bottom_widget = self.create_bottom_widget()
# Create a central widget to hold the splitter
central_widget = QWidget()
central_layout = QVBoxLayout(central_widget)
central_layout.setContentsMargins(10, 0, 10, 0)
# Create a QSplitter to host the top and bottom widgets
splitter = QSplitter(Qt.Vertical)
splitter.splitterMoved.connect(self.on_handle_splitter_moved)
splitter.addWidget(top_widget)
splitter.addWidget(bottom_widget)
splitter.setSizes([50, 50])
splitter.setHandleWidth(SPLITTER_HANDLE_WIDTH)
splitter.setStyleSheet(f"""
QSplitter::handle {{
background-color: darkgray;
}}
QSplitter::handle:vertical {{
height: {SPLITTER_HANDLE_WIDTH}px;
}}
QSplitter::handle:horizontal {{
width: {SPLITTER_HANDLE_WIDTH}px;
}}
""")
# Add the splitter to the central layout
central_layout.addWidget(splitter)
# Set the central widget
self.setCentralWidget(central_widget)
QApplication.instance().installEventFilter(self) # Install global event filter
self.create_status_bar()
self.statusBar().showMessage("Load a video.")
self.update_ui_state()
# Timer to update the slide bar
self._update_timer = QTimer(self)
self._update_timer.timeout.connect(self.on_timer_timeout)
##
## MENU, STATUS BAR
##
@log_function_name()
def create_status_bar(self):
# Get the default status bar
self._status_bar = self.statusBar()
# Add another QLabel aligned to the bottom right
self._info_label = QLabel()
self._status_bar.addPermanentWidget(self._info_label) # Aligns to the right
self.update_status_bar()
@log_function_name()
def create_menu(self):
# Create a menu bar
menubar = self.menuBar()
#
# Create a 'File' menu
#
file_menu = menubar.addMenu('File')
# Create 'New' action
action = QAction('New', self)
action.triggered.connect(self.on_menu_new)
action.setShortcut(QKeySequence.New)
file_menu.addAction(action)
file_menu.addSeparator()
# Create 'Open' action
action = QAction('Open Video', self)
action.triggered.connect(self.on_menu_open_video)
action.setShortcut(QKeySequence.Open)
file_menu.addAction(action)
# Create 'Open' action
action = QAction('Open Shot List', self)
action.triggered.connect(self.on_menu_open_shotlist)
action.setShortcut(QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.Key_O))
file_menu.addAction(action)
file_menu.addSeparator()
# Create 'Save' action
action = QAction('Save', self)
action.triggered.connect(self.on_menu_save)
action.setShortcut(QKeySequence.Save)
file_menu.addAction(action)
# Create 'Save As' action
action = QAction('Save as', self)
action.triggered.connect(self.on_menu_save_as)
action.setShortcut(QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.Key_S))
file_menu.addAction(action)
file_menu.addSeparator()
# Create 'Export...' submenu
export_menu = file_menu.addMenu('Export...')
# Create 'Export Selection' action
action = QAction('Export Selection', self)
action.triggered.connect(self.on_menu_export_selection)
action.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_E))
export_menu.addAction(action)
# Create 'Export Frame' action
action = QAction('Export Frame', self)
action.triggered.connect(self.on_menu_export_current_frame)
action.setShortcut(QKeySequence(Qt.CTRL + Qt.ALT + Qt.Key_E))
export_menu.addAction(action)
# Create 'Export As...' submenu
export_as_menu = file_menu.addMenu('Export As...')
# Create 'Export Selection As' action
action = QAction('Export Selection As', self)
action.triggered.connect(self.on_menu_export_selection_as)
action.setShortcut(QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.Key_E))
export_as_menu.addAction(action)
# Create 'Export Frame As' action
action = QAction('Export Frame As', self)
action.triggered.connect(self.on_menu_export_current_frame_as)
action.setShortcut(QKeySequence(Qt.SHIFT + Qt.CTRL + Qt.ALT + Qt.Key_E))
export_as_menu.addAction(action)
file_menu.addSeparator()
# Create 'Exit' action
action = QAction('Exit', self)
action.triggered.connect(self.on_menu_exit)
action.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Q))
file_menu.addAction(action)
#
# Create an 'Edit' menu
#
edit_menu = menubar.addMenu('Edit')
# Create an "Undo" action with Ctrl + Z shortcut
action = QAction("Undo", self)
action.triggered.connect(self._history.undo)
action.setShortcuts([QKeySequence.Undo]) # QKeySequence("Ctrl+Z")
edit_menu.addAction(action)
#action.setDisabled(True)
# Create an "Redo" action with Ctrl + Z shortcut
action = QAction("Redo", self)
action.triggered.connect(self._history.redo)
action.setShortcuts([QKeySequence.Redo]) # QKeySequence("Ctrl+Y"), QKeySequence("Shift+Ctrl+Z")
edit_menu.addAction(action)
#action.setDisabled(True)
edit_menu.addSeparator()
# Create an "Redo" action with Ctrl + Z shortcut
action = QAction("Select All", self)
action.triggered.connect(self.cmd_select_all)
action.setShortcuts([QKeySequence.SelectAll]) # Ctrl+A
edit_menu.addAction(action)
#action.setDisabled(True)
# Create an "Redo" action with Ctrl + Z shortcut
action = QAction("Deselect All", self)
action.triggered.connect(self.cmd_deselect_all)
action.setShortcuts([QKeySequence("Ctrl+D")])
edit_menu.addAction(action)
#action.setDisabled(True)
##
## MAIN WIDGETS
##
@log_function_name()
def create_top_widget(self):
top_widget = QWidget()
# Create a vertical layout for the top part
top_layout = QVBoxLayout()
top_widget.setLayout(top_layout)
margins = top_layout.contentsMargins()
top_layout.setContentsMargins(0, margins.top(), 0, margins.bottom())
# Create a media player object
self._media_player = QMediaPlayer(None, QMediaPlayer.VideoSurface)
#self._media_player.positionChanged.connect(self.on_mediaplayer_position_changed)
#self._media_player.durationChanged.connect(self.on_mediaplayer_duration_changed)
self._media_player.stateChanged.connect(self.on_mediaplayer_state_changed)
self._media_player.error.connect(self.on_media_player_error)
# Create a video widget for displaying video output
self._video_widget = QVideoWidget()
self._video_widget.setStyleSheet(f"background-color: {VIDEO_BACKGROUND_COLOR};")
self._media_player.setVideoOutput(self._video_widget)
self._video_widget.mousePressEvent = self.on_video_widget_clicked
top_layout.addWidget(self._video_widget)
# Create a horizontal layout for the slider
slider_layout = QHBoxLayout()
top_layout.addLayout(slider_layout)
self._seek_slider = QSlider(Qt.Horizontal)
self._seek_slider.setRange(0, 0)
self._seek_slider.mousePressEvent = self.on_seek_slider_click
self._seek_slider.sliderMoved.connect(self.on_seek_slider_moved)
slider_layout.addWidget(self._seek_slider)
# Create a spinbox
self._seek_spinbox = QSpinBox()
self._seek_spinbox.valueChanged.connect(self.on_seek_spinbox_changed)
self._seek_spinbox.setStatusTip("Directly set the position.")
slider_layout.addWidget(self._seek_spinbox)
# Create a horizontal layout for the buttons
button_layout = QHBoxLayout()
top_layout.addLayout(button_layout)
# Create a play button
self._play_button = QToolButton()
self._play_button.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
self._play_button.clicked.connect(self.on_play_button_clicked)
self._play_button.setStatusTip("Click to start playing.")
button_layout.addWidget(self._play_button)
# Create a stop button
self._stop_button = QToolButton()
self._stop_button.setIcon(self.style().standardIcon(QStyle.SP_MediaStop))
self._stop_button.clicked.connect(self.on_stop_button_clicked)
self._stop_button.setStatusTip("Click to stop playing.")
button_layout.addWidget(self._stop_button)
# Create an edge detection checkbox with a label
self._edgedetect_checkbox = QCheckBox("Lines")
self._edgedetect_checkbox.toggled.connect(self.on_edge_detection_toggled)
self._edgedetect_checkbox.setStatusTip("Check to apply 'Sobel' edge detection to the thumbnails.")
self._edgedetect_checkbox.setChecked(False)
ShotWidget.detect_edges = False
button_layout.addWidget(self._edgedetect_checkbox)
# Create an edge factor spinbox
self._edgefactor_spinbox = QSpinBox()
self._edgefactor_spinbox.setRange(1, 10)
self._edgefactor_spinbox.valueChanged.connect(self.on_edge_factor_changed)
self._edgefactor_spinbox.setStatusTip("Set the contrast factor of the 'Sobel' edge detection algorhythm.")
self._edgefactor_spinbox.setValue(1)
button_layout.addWidget(self._edgefactor_spinbox)
# Create a split button
self._split_button = QPushButton('Mark current frame as new shot')
self._split_button.clicked.connect(self.on_split_button_clicked)
self._split_button.setStyleSheet(f"background-color: {SHOT_WIDGET_PROGRESSBAR_COLOR};")
self._split_button.setStatusTip("Add a new shot to the list starting at current position (in case it has not already been detected as the beginning of a shot).")
button_layout.addStretch()
button_layout.addWidget(self._split_button)
# Create a scan button
self._scan_button = QPushButton('Scan selected shots')
self._scan_button.clicked.connect(self.on_scan_button_clicked)
self._scan_button.setStyleSheet(f"background-color: {SHOT_WIDGET_RESCAN_COLOR};")
self._scan_button.setStatusTip("Scan (or re-scan) the selected shots using the current similarity tolerance value.")
# Create a plot checkbox with a label
self._plot_checkbox = QCheckBox("Monitor")
self._plot_checkbox.setChecked(False)
self._plot_checkbox.setStatusTip("Check to display a real-time plot of SSIM values during frame analysis. Close the graph when done.")
# Detection level slider
self._detection_slider = QSlider(Qt.Horizontal)
self._detection_slider.setRange(0, DETECTION_SLIDER_STEPS)
self._detection_slider.setValue(DEFAULT_DETECTION_SLIDER_VALUE)
#self._detection_slider.mousePressEvent = self.on_detection_slider_click
self._detection_slider.sliderMoved.connect(self.on_detection_slider_moved)
self._detection_slider.setFixedWidth(100)
# Detection label
self._detection_label = QLabel(f"{self.convert_detection_slider_value_to_ssim_drop_threshold(self._detection_slider.value()):.2f}")
self._detection_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
# Create a downscale spinbox
self._downscale_spinbox = QSpinBox()
self._downscale_spinbox.setStatusTip("Set the width of the downscaled image size to ease shot detection.")
self._downscale_spinbox.setRange(64, 1280)
self._downscale_spinbox.setSingleStep(64)
self._downscale_spinbox.setValue(128)
# Create a layout for the detection widgets
detection_layout = QHBoxLayout()
detection_layout.addStretch() # Add stretch to push elements to the right
detection_layout.addWidget(self._scan_button)
detection_layout.addWidget(self._plot_checkbox)
detection_layout.addWidget(self._detection_slider)
detection_layout.addWidget(self._detection_label)
detection_layout.addWidget(self._downscale_spinbox)
detection_layout.setSpacing(5) # Adjust spacing between label and slider
button_layout.addStretch()
button_layout.addLayout(detection_layout)
# Create a merge button
self._merge_button = QPushButton('Merge selected shots')
self._merge_button.clicked.connect(self.on_merge_button_clicked)
self._merge_button.setStyleSheet(f"background-color: {SHOT_WIDGET_SELECT_COLOR};")
self._merge_button.setStatusTip("Merge the selected shots as one shot (in case they were incorrectly detected as separate shots).")
button_layout.addStretch()
button_layout.addWidget(self._merge_button)
# Volume label
volume_label = QLabel("Volume")
volume_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
# Volume slider
self._volume_slider = QSlider(Qt.Horizontal)
self._volume_slider.setRange(0, 100)
self._volume_slider.setValue(75)
self._volume_slider.mousePressEvent = self.on_volume_slider_click
self._volume_slider.sliderMoved.connect(self.on_volume_slider_moved)
self._volume_slider.setFixedWidth(150)
ShotWidget.volume = self._volume_slider.value() / 100
# Create a layout for the volume slider and label
volume_layout = QHBoxLayout()
volume_layout.addStretch() # Add stretch to push elements to the right
volume_layout.addWidget(volume_label)
volume_layout.addWidget(self._volume_slider)
volume_layout.setSpacing(5) # Adjust spacing between label and slider
button_layout.addStretch()
button_layout.addLayout(volume_layout)
return top_widget
@log_function_name()
def create_bottom_widget(self):
bottom_widget = QWidget()
bottom_layout = QVBoxLayout()
bottom_widget.setLayout(bottom_layout)
margins = bottom_layout.contentsMargins()
bottom_layout.setContentsMargins(0, margins.top(), 0, margins.bottom())
scrollarea_layout = QHBoxLayout()
bottom_layout.addLayout(scrollarea_layout)
# Wrap the grid layout in a scroll area
self._scroll_area = self.ClickableScrollArea()
self._scroll_area.setWidgetResizable(True)
self._scroll_area.setStatusTip("Click on a shot to play.")
self._scroll_area.setStyleSheet(f"background-color: {BOARD_BACKGROUND_COLOR};")
self._scroll_area.clicked.connect(self.cmd_deselect_all)
self._scroll_area.verticalScrollBar().valueChanged.connect(self.on_scroll)
scrollarea_layout.addWidget(self._scroll_area)
# Create a container widget to hold the grid layout
grid_widget = QWidget()
self._grid_layout = QGridLayout()
self._grid_layout.setAlignment(Qt.AlignTop | Qt.AlignLeft)
grid_widget.setLayout(self._grid_layout)
self._scroll_area.setWidget(grid_widget)
return bottom_widget
##
## SLOTS
##
@log_function_name(color=PRINT_GREEN_COLOR)
def on_menu_new(self):
self.reset_all()
@log_function_name(color=PRINT_GREEN_COLOR)
def on_menu_open_video(self):
file_dialog = QFileDialog()
file_dialog.setAcceptMode(QFileDialog.AcceptOpen)
file_dialog.setNameFilter("Video files (*.mp4 *.avi)")
if file_dialog.exec_() == QFileDialog.Accepted:
url = file_dialog.selectedUrls()[0]
self.set_video(url)
# Check for a matching JSON file
if self._video_path:
json_path = os.path.splitext(self._video_path)[0] + ".json"
if os.path.exists(json_path):
json_filename = os.path.basename(json_path) # Extract filename only
reply = QMessageBox.question(
self,
"Load Shotlist?",
f"A matching shot list was found:\n{json_filename}\nDo you want to load it?",
QMessageBox.Yes | QMessageBox.No,
QMessageBox.Yes
)
if reply == QMessageBox.Yes:
self.open_shot_list(json_path)
@log_function_name(color=PRINT_GREEN_COLOR)
def on_menu_open_shotlist(self):
if not self._video_path:
QMessageBox.warning(self, "Warning", "Please load a video first.")
return
options = QFileDialog.Options()
json_path, _ = QFileDialog.getOpenFileName(self, "Open Shot File", None, "Shot Files (*.json);;All Files (*)", options=options)
self.open_shot_list(json_path)
@log_function_name(color=PRINT_GREEN_COLOR)
def on_menu_save(self):
if self._db_path:
self.save_shot_list(self._db_path)
else:
self.on_menu_save_as()
self.update_window_title()
@log_function_name(color=PRINT_GREEN_COLOR)
def on_menu_save_as(self):
options = QFileDialog.Options()
path, _ = QFileDialog.getSaveFileName(self, "Save Shot File", self._db_path, "Shot Files (*.json);;All Files (*)", options=options)
if path:
#if os.path.exists(path) and not QMessageBox.question(self, 'File Exists', f"The file {path} already exists. Do you want to overwrite it?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) == QMessageBox.Yes:
# return
self.save_shot_list(path)
@log_function_name(color=PRINT_GREEN_COLOR)
def on_menu_export_selection(self):
self.export_selection(False)
@log_function_name(color=PRINT_GREEN_COLOR)
def on_menu_export_selection_as(self):
self.export_selection(True)
@log_function_name(color=PRINT_GREEN_COLOR)
def on_menu_export_current_frame(self):
self.export_single_frame(self._seek_spinbox.value(), False)
@log_function_name(color=PRINT_GREEN_COLOR)
def on_menu_export_current_frame_as(self):
self.export_single_frame(self._seek_spinbox.value(), True)
@log_function_name(color=PRINT_GREEN_COLOR)
def on_menu_exit(self):
reply = QMessageBox.question(self, 'Confirm Exit', 'Exit?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
self.close()
@log_function_name(has_params=True, color=PRINT_GREEN_COLOR)
def resizeEvent(self, event):
super().resizeEvent(event)
self.update_grid_layout()
#@log_function_name(has_params=True)
def eventFilter(self, obj, event):
if self._ui_enabled:
if event.type() == QEvent.MouseButtonPress:
if event.button() == Qt.RightButton:
if RCLICK_SAVE:
self.on_menu_save()
return True
elif event.type() == QEvent.KeyPress:
if event.key() == Qt.Key_Space:
self._play_button.click() # Play / pause
return True
modifiers = event.modifiers()
if modifiers & Qt.ShiftModifier:
frame_inc = 4 # 4 frames
elif modifiers & Qt.ControlModifier:
frame_inc = self._fps # 1 second
elif modifiers & Qt.AltModifier:
frame_inc = 4 * self._fps # 4 seconds
else:
frame_inc = 1
frame_index = self.qtvid_pos_to_frame_index()
if event.key() == Qt.Key_Right:
self.set_qtvid_pos_to_mid_frame(frame_index + frame_inc)
return True
elif event.key() == Qt.Key_Left:
self.set_qtvid_pos_to_mid_frame(frame_index - frame_inc)
return True
# Unprocessed events propagate as usual
return super().eventFilter(obj, event)
@log_function_name(has_params=True, color=PRINT_GREEN_COLOR)
def on_handle_splitter_moved(self, pos, index):
pass
@log_function_name(color=PRINT_GREEN_COLOR)
def on_video_widget_clicked(self):
if not self._video_path or not self._ui_enabled:
return
self.on_play_button_clicked()
@log_function_name(color=PRINT_GREEN_COLOR)
def on_play_button_clicked(self):
if not self._video_path:
return
player_state = self._media_player.state()
if player_state == QMediaPlayer.StoppedState:
self.play_video()
elif player_state == QMediaPlayer.PlayingState:
self.pause_video()
elif player_state == QMediaPlayer.PausedState:
self.resume_video()
@log_function_name(color=PRINT_GREEN_COLOR)
def on_stop_button_clicked(self):
self.stop_video()
@log_function_name(has_params=True, color=PRINT_GREEN_COLOR)
def on_edge_detection_toggled(self, checked):
ShotWidget.detect_edges = checked
@log_function_name(has_params=True, color=PRINT_GREEN_COLOR)
def on_edge_factor_changed(self, value):
ShotWidget.edge_factor = value
@log_function_name(color=PRINT_GREEN_COLOR)
def on_split_button_clicked(self):
self.cmd_split_video()
@log_function_name(color=PRINT_GREEN_COLOR)
def on_scan_button_clicked(self):
self.cmd_scan_selected_shots()
@log_function_name(color=PRINT_GREEN_COLOR)
def on_merge_button_clicked(self):
self.cmd_merge_selected_shots()
@log_function_name(has_params=True, color=PRINT_GREEN_COLOR)
def on_detection_slider_moved(self, value):
ssim_drop_threshold = self.convert_detection_slider_value_to_ssim_drop_threshold(value)
self._detection_label.setText(f"{ssim_drop_threshold:.2f}")
@log_function_name(has_params=True, color=PRINT_GREEN_COLOR)
def on_volume_slider_click(self, event):
if event.button() == Qt.LeftButton:
volume = int(self._volume_slider.minimum() + ((self._volume_slider.maximum() - self._volume_slider.minimum()) * event.x()) / self._volume_slider.width())
ShotWidget.volume = volume / 100
self._media_player.setVolume(volume)
event.accept()
QSlider.mousePressEvent(self._volume_slider, event)
@log_function_name(has_params=True, color=PRINT_GREEN_COLOR)
def on_volume_slider_moved(self, volume):
ShotWidget.volume = volume / 100
self._media_player.setVolume(volume)
@log_function_name(has_params=True, color=PRINT_GREEN_COLOR)
def on_seek_slider_click(self, event):
if event.button() == Qt.LeftButton:
frame_index = int(self._seek_slider.minimum() + ((self._seek_slider.maximum() - self._seek_slider.minimum()) * event.x()) / self._seek_slider.width())
self.set_qtvid_pos_to_mid_frame(frame_index)
# frame_index = round(self._seek_slider.minimum() + ((self._seek_slider.maximum() - self._seek_slider.minimum()) * event.x()) / self._seek_slider.width())
# self.update_slider_and_spinbox(frame_index)
# self.pause_video()
event.accept()
QSlider.mousePressEvent(self._seek_slider, event)
@log_function_name(has_params=True, color=PRINT_GREEN_COLOR)
def on_seek_slider_moved(self, frame_index):
self.set_qtvid_pos_to_mid_frame(frame_index)
# self.update_slider_and_spinbox(frame_index)
# self.pause_video()
@log_function_name(has_params=True, color=PRINT_GREEN_COLOR)
def on_seek_spinbox_changed(self, frame_index):
self.set_qtvid_pos_to_mid_frame(frame_index)
@log_function_name(has_params=True)
def on_mediaplayer_state_changed(self, state):
if state == QMediaPlayer.PlayingState:
self._play_button.setIcon(self.style().standardIcon(QStyle.SP_MediaPause))
else:
self._play_button.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
@log_function_name(color=PRINT_RED_COLOR)
def on_media_player_error(self):
print(f"{PRINT_RED_COLOR}{self._media_player.errorString()}{PRINT_DEFAULT_COLOR}")
@log_function_name(color=PRINT_GREEN_COLOR)
def on_scroll(self):
"""Detect which ShotWidgets are visible in the scroll area."""
viewport = self._scroll_area.viewport()
scroll_pos = self._scroll_area.verticalScrollBar().value()
viewport_rect = QRect(0, scroll_pos, viewport.width(), viewport.height())
# visible_shot_widgets = []
# for shot_widget in self._shot_widgets:
# if viewport_rect.intersects(shot_widget.geometry()):
# visible_shot_widgets.append(shot_widget)
@log_function_name(has_params=True, color=PRINT_GREEN_COLOR)
def on_shot_widget_clicked(self, shift_pressed):
if not self._ui_enabled:
return
if self._update_timer.isActive():
self._update_timer.stop()
self._media_player.pause()
# Fetch the shot widget emitting the signal
shot_widget = self.sender()
assert shot_widget
shot_index = self._shot_widgets.index(shot_widget)
if shift_pressed:
self.cmd_extend_shot_selection(shot_index)
else:
self.cmd_select_shot(shot_index)
start_frame_index = shot_widget.get_start_frame_index() # integer
qtvid_pos = round(self.convert_frame_index_to_qtvid_pos(start_frame_index))
self._media_player.setPosition(qtvid_pos)
self.update_slider_and_spinbox(start_frame_index)
@log_function_name(color=PRINT_YELLOW_COLOR)
def on_timer_timeout(self):
frame_index = self.qtvid_pos_to_frame_index() # float
self.update_slider_and_spinbox(frame_index)
##
## UPDATES
##
@log_function_name()
def update_window_title(self):
title = DEFAULT_TITLE
if self._db_path:
title += f" - {os.path.basename(self._db_path)}"
else:
title += " - (undefined)"
# Add '*' if database has unsaved changes
if self._db.is_dirty():
title += " *"
self.setWindowTitle(title)
@log_function_name()
def update_status_bar(self):
duration_hms = str(datetime.timedelta(seconds=int(self._duration)))
duration_h = self._duration / 3600 if self._duration > 0 else 1 # Prevent division by zero
shots_per_hour = round(len(self._db) / duration_h)
self._info_label.setText(
f"FPS: {self._fps:.3f} | "
f"Resolution: {self._frame_width}x{self._frame_height} | "
f"Duration: {duration_hms} | "
f"Shots: {len(self._db)} | "
f"Shots/hour: {shots_per_hour}"
)
def update_ui_state(self):
enabled = (self._video_path != None and self._ui_enabled)
self._seek_slider.setEnabled(enabled)
self._seek_spinbox.setEnabled(enabled)
self._play_button.setEnabled(enabled)
self._stop_button.setEnabled(enabled)
self._split_button.setEnabled(enabled)
self._scan_button.setEnabled(enabled and not self.is_selection_empty())
self._merge_button.setEnabled(enabled and not self.is_selection_empty())
#self._detection_slider.setEnabled(enabled and not self.is_selection_empty())
def update_slider_and_spinbox(self, frame_index):
self._seek_slider.blockSignals(True)
self._seek_spinbox.blockSignals(True)
self._seek_slider.setValue(int(frame_index))
self._seek_spinbox.setValue(int(frame_index))
self._seek_slider.blockSignals(False)
self._seek_spinbox.blockSignals(False)
def reset_all(self):
self.stop_video()
self._media_player.setPosition(0)
self.update_slider_and_spinbox(0)
self._history.clear()
self.clear_shot_widgets()
self._db.clear_shots()
self._db_path = None
self._video_path = None
self._fps = 0
self.update_ui_state()
self.update_window_title()
self.statusBar().showMessage("Load a video.")
def clear_shot_widgets(self):
self.deselect_all()
for widget in self._shot_widgets:
self._grid_layout.removeWidget(widget)
widget.hide()
widget.deleteLater()
self._shot_widgets = []
def create_shot_widget(self, widget_index, start_frame_index):
shot_widget = ShotWidget(self._video_path, self._fps, *self._db.get_start_end_frame_indexes(start_frame_index))
shot_widget.clicked.connect(self.on_shot_widget_clicked)
self._shot_widgets.insert(widget_index, shot_widget)
if widget_index > 0:
prev_widget = self._shot_widgets[widget_index - 1]
prev_widget.set_end_frame_index(start_frame_index, False)
return shot_widget
def delete_shot_widget(self, widget_index):
del self._shot_widgets[widget_index]
if widget_index > 0:
prev_shot_widget = self._shot_widgets[widget_index - 1]
if widget_index < len(self._shot_widgets):
next_shot_widget = self._shot_widgets[widget_index]
prev_shot_widget.set_end_frame_index(next_shot_widget.get_start_frame_index(), False)
else:
prev_shot_widget.set_end_frame_index(self._frame_count, False)
@log_function_name()
def update_grid_layout(self):
progress_dialog = None
if len(self._db) > 0:
if len(self._db) > 3:
# Create a progress dialog
progress_dialog = QProgressDialog("Updating shots...", "Cancel", 0, len(self._db), self)
progress_dialog.setWindowModality(Qt.WindowModal)
progress_dialog.setWindowTitle("Shot creation")
progress_dialog.setWindowFlags(progress_dialog.windowFlags() & ~Qt.WindowContextHelpButtonHint)
progress_dialog.setMinimumDuration(0)
progress_dialog.setValue(0)
i, j = 0, 0
while i < len(self._shot_widgets) and j < len(self._db):
widget_start_frame_index = self._shot_widgets[i].get_start_frame_index()
db_start_frame_index = self._db[j]
if widget_start_frame_index == db_start_frame_index:
# This widget is OK, move on to the next one
i += 1
j += 1
elif widget_start_frame_index < db_start_frame_index:
# This widget is no longer needed, remove it
self.delete_shot_widget(i)
else:
# Start frame index in _db is missing from _shot_widgets, insert it
self.create_shot_widget(i, db_start_frame_index)
i += 1
j += 1
if progress_dialog:
progress_dialog.setValue(j)
if progress_dialog.wasCanceled():
progress_dialog.close()
progress_dialog = None
break
# If any widget remain in _shot_widgets, remove them
if not progress_dialog or not progress_dialog.wasCanceled():
while i < len(self._shot_widgets):
self.delete_shot_widget(i)
# If any shot remain in _db, add them at the end
while j < len(self._db):
self.create_shot_widget(len(self._shot_widgets), self._db[j])
j += 1
if progress_dialog:
progress_dialog.setValue(j)