This repository was archived by the owner on Nov 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpixelate_video.py
executable file
·1625 lines (1493 loc) · 54.7 KB
/
pixelate_video.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
pixelate_video.py
Partially pixelate selected frames of a (short) video clip
(Tkinter-based GUI assistant)
"""
import argparse
import logging
import mimetypes
import os
import pathlib
import subprocess
import sys
import tempfile
import tkinter
from fractions import Fraction
from tkinter import filedialog
from tkinter import messagebox
# local modules
from pyxelate import core
from pyxelate import ffmpegwrappers as ffmw
from pyxelate import gui
from pyxelate import pixelations
#
# Constants
#
SCRIPT_NAME = "Partially pixelate a video clip"
HOMEPAGE = "https://github.com/blackstream-x/pyxelate"
SCRIPT_PATH = pathlib.Path(os.path.realpath(sys.argv[0]))
# Follow symlinks
if SCRIPT_PATH.is_symlink():
SCRIPT_PATH = SCRIPT_PATH.readlink()
#
LICENSE_PATH = SCRIPT_PATH.parent / "LICENSE"
COPYRIGHT_NOTICE = """Copyright (C) 2021 Rainer Schwarzbach
This file is part of pyxelate.
pyxelate is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
pyxelate is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with pyxelate (see LICENSE).
If not, see <http://www.gnu.org/licenses/>."""
VERSION_PATH = SCRIPT_PATH.parent / "version.txt"
try:
VERSION = VERSION_PATH.read_text().strip()
except OSError as os_error:
VERSION = f"(Version file is missing: {os_error})"
#
# Phases
OPEN_FILE = core.UserInterface.phase_open_file
FIRST_FRAME = "first_frame"
LAST_FRAME = "last_frame"
START_AREA = "start_area"
STOP_AREA = "stop_area"
PREVIEW = "preview"
PHASES = (
OPEN_FILE,
FIRST_FRAME,
LAST_FRAME,
START_AREA,
STOP_AREA,
PREVIEW,
)
PANEL_NAMES = {
FIRST_FRAME: "Cut your video: select the beginning of the desired clip",
LAST_FRAME: "Cut your video: select the end of the desired clip",
START_AREA: "Pixelate a segment: select a start frame and area",
STOP_AREA: "Pixelate a segment: select an end frame and area",
PREVIEW: "Preview the modified video frame by frame",
}
EMPTY_SELECTION = dict(
frame=None,
shape=None,
center_x=None,
center_y=None,
width=None,
height=None,
)
MAX_NB_FRAMES = 10000
ONE_MILLION = 1000000
# DEFAULT_EXPORT_CRF = 18
# DEFAULT_EXPORT_PRESET = "ultrafast"
EXPORT_PRESETS = (
"ultrafast",
"superfast",
"veryfast",
"faster",
"fast",
"medium",
"slow",
"slower",
"veryslow",
)
CANVAS_WIDTH = 720
CANVAS_HEIGHT = 540
# DEFAULT_TILESIZE = 10
#
# Classes
#
class TemporaryFramesPath(core.InterfacePlugin):
"""Context manager for a temporary directory with files from
the modified_frames and original_frames directory
"""
def __init__(self, application):
"""Store the provided information and provide
a storage for files source
"""
super().__init__(application)
self.source_file = {}
self.temporary_storage = None
def __enter__(self):
"""Create the temporary directory.
Move files here (from the primary or, if not found,
from the secondary directory
store the original name for each file
Return the name of the current tempdir as a Path instance
"""
source_paths = []
for source_tempdir in (
self.vars.modified_frames,
self.vars.original_frames,
):
try:
source_paths.append(pathlib.Path(source_tempdir.name))
except AttributeError:
pass
#
#
self.temporary_storage = tempfile.TemporaryDirectory()
logging.debug("Created tempdir %r", self.temporary_storage.name)
temporary_path = pathlib.Path(self.temporary_storage.name)
new_number = 1
for old_number in range(
self.vars.kept_frames.start, self.vars.kept_frames.end + 1
):
old_file_name = pixelations.FRAME_PATTERN % old_number
new_file_name = pixelations.FRAME_PATTERN % new_number
for single_source_path in source_paths:
old_path = single_source_path / old_file_name
if old_path.is_file():
self.source_file[new_file_name] = str(old_path)
old_path.rename(temporary_path / new_file_name)
break
#
else:
raise ValueError(
f"File {old_file_name!r} found neither in modified"
" nor in original frames!"
)
#
new_number += 1
#
logging.debug("Moved %r files", new_number - 1)
return temporary_path
def __exit__(self, exc_type, exc_value, traceback):
"""Move the files back
Cleanup the temporary directory
"""
temporary_path = pathlib.Path(self.temporary_storage.name)
for file_path in temporary_path.glob("*"):
original_name = self.source_file[file_path.name]
file_path.rename(original_name)
#
logging.debug("Moved files back to the original directories")
self.temporary_storage.cleanup()
logging.debug(
"Deleted temporary directory %s", self.temporary_storage.name
)
class Actions(core.InterfacePlugin):
"""Pre-panel actions for the video GUI in sequential order"""
def first_frame(self):
"""Actions before showing "first frame" selection"""
self.application.adjust_frame_limits()
self.vars.update(
image=pixelations.BaseImage(
pathlib.Path(self.vars.original_frames.name)
/ self.vars.frame_file,
canvas_size=(self.vars.canvas_width, self.vars.canvas_height),
),
frame_position="Select first video",
)
# set the show_preview variable to the user setting
self.tkvars.show_preview.set(self.vars.user_settings.show_preview)
self.application.set_default_selection(
tilesize=self.vars.user_settings.tilesize
)
def last_frame(self):
"""Actions before showing "first frame" selection"""
self.application.adjust_frame_limits()
self.vars.update(
image=pixelations.BaseImage(
pathlib.Path(self.vars.original_frames.name)
/ self.vars.frame_file,
canvas_size=(self.vars.canvas_width, self.vars.canvas_height),
),
frame_position="Select last video",
)
def start_area(self):
"""Actions before showing the start area selection panel:
Load the frame and set the variables
"""
self.application.adjust_frame_limits()
self.vars.update(
image=pixelations.FramePixelation(
pathlib.Path(self.vars.original_frames.name)
/ self.vars.frame_file,
canvas_size=(self.vars.canvas_width, self.vars.canvas_height),
),
frame_position="Pixelation start",
)
if self.tkvars.crop.get():
self.vars.image.set_crop_area(self.vars.crop_area)
#
try:
self.application.apply_coordinates(self.vars.later_stations.pop())
except IndexError:
self.application.adjust_current_frame(self.vars.kept_frames.start)
#
self.tkvars.drag_action.set(self.vars.previous_drag_action)
def stop_area(self):
"""Actions before showing the stop area selection panel:
Save the coordinates
Fix the currently selected frame as start frame.
Load the frame for area selection
"""
self.application.adjust_frame_limits(
minimum=self.tkvars.current_frame.get()
)
try:
self.application.apply_coordinates(self.vars.later_stations.pop())
except IndexError:
pass
#
self.vars.update(
image=pixelations.FramePixelation(
pathlib.Path(self.vars.original_frames.name)
/ self.vars.frame_file,
canvas_size=(self.vars.canvas_width, self.vars.canvas_height),
),
frame_position="Pixelation stop",
)
if self.tkvars.crop.get():
self.vars.image.set_crop_area(self.vars.crop_area)
#
def preview(self):
"""Actions before showing the preview panel:
Fix the selected end coordinates
Apply the pixelations to all images
"""
self.application.adjust_frame_limits()
try:
self.application.apply_coordinates(self.vars.later_stations.pop())
except IndexError:
pass
#
self.vars.update(
previous_drag_action=self.tkvars.drag_action.get(),
frame_position="Current",
)
self.tkvars.drag_action.set(core.NEW_CROP_AREA)
class Callbacks(core.Callbacks):
"""Callback functions for the video UI"""
def change_frame(self, *unused_arguments):
"""Trigger a change of the frame"""
if not self.vars.trace:
return
#
try:
self.widgets.canvas.delete(core.TAG_IMAGE)
except AttributeError as error:
logging.warning("%s", error)
except tkinter.TclError as error:
logging.warning("%s", error)
return
#
# Adjust to current limits
self.application.adjust_current_frame()
image_type = pixelations.BaseImage
frame_path = (
pathlib.Path(self.vars.original_frames.name) / self.vars.frame_file
)
if self.vars.current_panel == PREVIEW:
try:
modified_frames_dir = self.vars.modified_frames.name
except AttributeError:
pass
else:
modified_path = (
pathlib.Path(modified_frames_dir) / self.vars.frame_file
)
if modified_path.is_file():
frame_path = modified_path
#
#
elif self.vars.current_panel in (START_AREA, STOP_AREA):
image_type = pixelations.FramePixelation
#
self.vars.update(
image=image_type(
frame_path,
canvas_size=(self.vars.canvas_width, self.vars.canvas_height),
)
)
if self.tkvars.crop.get():
self.vars.image.set_crop_area(self.vars.crop_area)
#
self.vars.update(tk_image=self.vars.image.tk_original)
self.widgets.canvas.create_image(
0,
0,
image=self.vars.tk_image,
anchor=tkinter.NW,
tags=core.TAG_IMAGE,
)
if self.vars.current_panel in (START_AREA, STOP_AREA):
self.application.draw_indicator()
self.application.pixelate_selection()
#
def change_frame_from_text(self, *unused_arguments):
"""Trigger a change of the frame"""
if not self.vars.trace:
return
#
self.tkvars.current_frame.set(
int(self.tkvars.current_frame_text.get())
)
def frame_decrement(self, *unused_event):
"""Decrement frame number"""
current_frame = self.tkvars.current_frame.get()
self.application.adjust_current_frame(current_frame - 1)
self.change_frame()
def frame_increment(self, *unused_event):
"""increment frame number"""
current_frame = self.tkvars.current_frame.get()
self.application.adjust_current_frame(current_frame + 1)
self.change_frame()
def set_export_preferences(self, *unused_arguments):
"""Set the export_crf and export_preset user preferences
from the tkvars"""
self.vars.user_settings.update(
export_crf=self.tkvars.export.crf.get(),
export_preset=self.tkvars.export.preset.get(),
)
def set_include_audio_preference(self):
"""Set the prefer_include_audio user preference
from the tkvar
"""
self.vars.user_settings.update(
prefer_include_audio=bool(self.tkvars.export.include_audio.get())
)
def toggle_crop_display(self, *unused_arguments):
"""Toggle crop area preview update"""
if not self.vars.trace:
return
#
if self.vars.current_panel in (PREVIEW, FIRST_FRAME, LAST_FRAME):
self.change_frame()
return
#
super().toggle_crop_display(*unused_arguments)
def update_buttons(self, *unused_arguments):
"""Trigger previous, next and save button states changes"""
...
class Panels(core.Panels):
"""Panels and panel components"""
# Components
def component_image_on_canvas(self):
"""Show the image on a canvas, with a slider"""
image_frame = tkinter.Frame(
self.widgets.action_area, **core.WITH_BORDER
)
prev_button = tkinter.Button(
image_frame,
text="\u2190",
command=self.application.callbacks.frame_decrement,
)
label = tkinter.Label(
image_frame,
text=f"{self.vars.frame_position} frame fine-tune:",
)
next_button = tkinter.Button(
image_frame,
text="\u2192",
command=self.application.callbacks.frame_increment,
)
label.grid(row=0, column=1, padx=5, pady=5)
prev_button.grid(row=0, column=2, padx=5, pady=5)
next_button.grid(row=0, column=3, padx=5, pady=5)
logging.debug("Destroying pre-existing slider")
# Destroy a pre-existing widget to remove variable limits set before
try:
self.widgets.frames_slider.destroy()
except AttributeError:
pass
#
logging.debug("Showing slider")
self.widgets.frames_slider = tkinter.Scale(
image_frame,
from_=self.vars.frame_limits.minimum,
to=self.vars.frame_limits.maximum,
length=self.vars.canvas_width,
# label=f"{self.vars.frame_position} frame:",
orient=tkinter.HORIZONTAL,
variable=self.tkvars.current_frame,
)
self.widgets.frames_slider.grid(columnspan=5)
logging.debug("Showing canvas")
self.widgets.canvas = tkinter.Canvas(
image_frame,
width=self.vars.canvas_width,
height=self.vars.canvas_height,
)
self.widgets.canvas.grid(columnspan=5)
image_frame.columnconfigure(0, weight=100)
image_frame.columnconfigure(4, weight=100)
self.vars.update(trace=True)
if self.vars.current_panel in (START_AREA, STOP_AREA, PREVIEW):
if self.vars.current_panel in (START_AREA, STOP_AREA):
self.application.draw_indicator()
self.application.pixelate_selection()
#
# add bindings
self.widgets.canvas.bind(
"<ButtonPress-1>", self.application.callbacks.drag_start
)
self.widgets.canvas.bind(
"<ButtonRelease-1>", self.application.callbacks.drag_stop
)
self.widgets.canvas.bind(
"<B1-Motion>", self.application.callbacks.drag_move
)
# Set the canvas cursor
self.application.callbacks.set_canvas_cursor()
#
self.application.callbacks.change_frame()
image_frame.grid(row=1, column=0, rowspan=3, **core.GRID_FULLWIDTH)
def component_frameselection(self):
"""Select the start or end frame using a slider
and show that frame on a canvas
"""
self.component_image_on_canvas()
self.sidebar_frameselection()
def component_export_settings(self, sidebar_frame, parent_window=None):
"""Section with the export settings"""
# Disable "include audio" if the original video
# has no audio stream
if self.vars.has_audio:
include_audio_state = tkinter.NORMAL
else:
self.tkvars.export.include_audio.set(0)
include_audio_state = tkinter.DISABLED
#
self.application.heading_with_help_button(
sidebar_frame, "Export settings", parent_window=parent_window
)
label = tkinter.Label(sidebar_frame, text="CRF:")
crf = tkinter.Spinbox(
sidebar_frame,
from_=0,
to=51,
justify=tkinter.RIGHT,
state="readonly",
width=4,
textvariable=self.tkvars.export.crf,
)
label.grid(sticky=tkinter.W, column=0)
crf.grid(
sticky=tkinter.W,
row=gui.grid_row_of(label),
column=1,
columnspan=3,
)
label = tkinter.Label(sidebar_frame, text="Preset:")
preset_opts = tkinter.OptionMenu(
sidebar_frame, self.tkvars.export.preset, *EXPORT_PRESETS
)
label.grid(sticky=tkinter.W, column=0)
preset_opts.grid(
sticky=tkinter.W,
row=gui.grid_row_of(label),
column=1,
columnspan=4,
)
include_audio = tkinter.Checkbutton(
sidebar_frame,
anchor=tkinter.W,
command=self.application.callbacks.set_include_audio_preference,
text="Include original audio",
variable=self.tkvars.export.include_audio,
indicatoron=1,
state=include_audio_state,
)
include_audio.grid(
sticky=tkinter.W,
column=0,
columnspan=5,
)
def component_image_info(self, parent_frame):
"""Show information about the current video frame"""
self.application.heading_with_help_button(
parent_frame, f"{self.vars.frame_position} frame"
)
label = tkinter.Label(parent_frame, text="Number:")
# Destroy a pre-existing widget to remove variable limits set before
try:
self.widgets.frame_number.destroy()
except AttributeError:
pass
#
self.widgets.update(
frame_number=tkinter.Spinbox(
parent_frame,
from_=self.vars.frame_limits.minimum,
to=self.vars.frame_limits.maximum,
textvariable=self.tkvars.current_frame_text,
state="readonly",
width=4,
)
)
label.grid(sticky=tkinter.W)
self.widgets.frame_number.grid(
sticky=tkinter.W,
columnspan=3,
column=1,
row=gui.grid_row_of(label),
)
self.component_zoom_factor(parent_frame)
if self.vars.current_panel in (START_AREA, STOP_AREA, PREVIEW):
crop_active = tkinter.Checkbutton(
parent_frame,
anchor=tkinter.W,
text="Crop video",
variable=self.tkvars.crop,
indicatoron=1,
)
crop_active.grid(
sticky=tkinter.W,
column=0,
columnspan=5,
)
#
def sidebar_frameselection(self):
"""Show the frame selection sidebar"""
sidebar_frame = tkinter.Frame(
self.widgets.action_area, **core.WITH_BORDER
)
self.component_file_info(sidebar_frame)
self.component_image_info(sidebar_frame)
self.component_show_preview(sidebar_frame, subject="before saving")
sidebar_frame.columnconfigure(4, weight=100)
sidebar_frame.grid(row=0, column=1, rowspan=2, **core.GRID_FULLWIDTH)
def sidebar_preview(self):
"""Show the preview sidebar"""
sidebar_frame = tkinter.Frame(
self.widgets.action_area, **core.WITH_BORDER
)
self.component_file_info(sidebar_frame)
self.component_image_info(sidebar_frame)
self.component_select_drag_action(
sidebar_frame, supported_actions=[core.NEW_CROP_AREA]
)
sidebar_frame.columnconfigure(4, weight=100)
sidebar_frame.grid(row=0, column=1, rowspan=2, **core.GRID_FULLWIDTH)
def sidebar_export(self):
"""Show the export sidebar"""
sidebar_frame = tkinter.Frame(
self.widgets.action_area, **core.WITH_BORDER
)
self.component_export_settings(sidebar_frame)
sidebar_frame.columnconfigure(4, weight=100)
sidebar_frame.grid(
row=2,
column=1,
padx=4,
pady=2,
sticky=tkinter.E + tkinter.W + tkinter.S,
)
# Panels in order of appearance
def first_frame(self):
"""Select the first frame using a slider
and show that frame on a canvas
"""
self.component_image_on_canvas()
self.sidebar_frameselection()
last_frame = first_frame
def start_area(self):
"""Show the image on a canvas and let
the user select the area to be pixelated
"""
self.component_image_on_canvas()
self.sidebar_settings(preview_subject="pixelation / before saving")
def stop_area(self):
"""Show the image on a canvas and let
the user select the area to be pixelated
"""
if self.vars.stations[-1]["shape"] in core.ELLIPTIC_SHAPES:
allowed_shapes = core.ELLIPTIC_SHAPES
else:
allowed_shapes = core.RECTANGULAR_SHAPES
#
self.component_image_on_canvas()
self.sidebar_settings(
allowed_shapes=allowed_shapes,
preview_subject="pixelation / before saving",
)
def preview(self):
"""Show a slider allowing to preview the modified video"""
self.component_image_on_canvas()
self.sidebar_preview()
self.sidebar_export()
class PostPanelActions(core.InterfacePlugin):
"""Pre-panel actions for the video GUI in sequential order"""
def first_frame(self):
"""Cut before the first frame if required"""
self.vars.kept_frames.update(start=self.tkvars.current_frame.get())
self.application.cut_video(
to_=self.vars.kept_frames.start - 1,
)
def last_frame(self):
"""Cut after the last frame if required,
and if the last frame is greater than the first frame
"""
current_frame = self.tkvars.current_frame.get()
if current_frame > self.vars.kept_frames.start:
self.vars.kept_frames.update(end=self.tkvars.current_frame.get())
self.application.cut_video(
from_=self.vars.kept_frames.end + 1,
)
#
def start_area(self):
"""Append coordinates (current frame and selection)
to the stations list
"""
logging.debug("Saving coordinates ...")
self.vars.stations.append(self.application.get_coordinates())
self.vars.update(
modified_frames=tempfile.TemporaryDirectory(),
)
logging.debug("Created tempdir %r", self.vars.modified_frames.name)
def stop_area(self):
"""Append coordinates (current frame and selection)
to the stations list
"""
logging.debug("Saving coordinates ...")
self.vars.stations.append(self.application.get_coordinates())
# Set pixelations shape
logging.debug("Pixelating the segment...")
[segment_start, segment_end] = self.vars.stations[-2:]
px_shape = core.SHAPES[segment_start["shape"]]
if core.SHAPES[segment_end["shape"]] != px_shape:
raise ValueError(
"Shapes at both ends of the segment must be the same!"
)
#
pixelator = pixelations.MultiFramePixelation(
pathlib.Path(self.vars.original_frames.name),
pathlib.Path(self.vars.modified_frames.name),
quality="maximum",
)
progress = gui.TransientProgressDisplay(
self.main_window,
title="Pixelating segment",
label="Applying pixelation to all frames in the segment…",
maximum=100,
)
for percentage in pixelator.pixelate_segment(
px_shape,
segment_start,
segment_end,
):
progress.set_current_value(percentage)
#
progress.action_cancel()
self.vars.update(unsaved_changes=True)
class Rollbacks(core.InterfacePlugin):
"""Rollback action in order of appearance"""
def stop_area(self):
"""Actions when clicking the "previous" button
in the end area selection panel:
Set frame range for the previous panel.
Reset frame and position to the ones from the previous panel.
"""
self.vars.later_stations.append(self.application.get_coordinates())
self.application.adjust_frame_limits()
segment_end = self.vars.stations.pop()
self.application.apply_coordinates(segment_end)
# Set minimum frame to before-previous panel frame if possible.
# Clean up the modified_frames temporary directory.
try:
segment_start = self.vars.stations[-1]
except IndexError:
frame_position = "Pixelation start"
else:
start_frame = segment_start["frame"]
frame_position = "Pixelation stop"
self.application.adjust_frame_limits(minimum=start_frame)
# Remove modified frames of the last segment.
# If that was the only one, remove the modified
# first frame of that segment as well.
if len(self.vars.stations) > 1:
start_frame += 1
#
modified_frames_path = pathlib.Path(self.vars.modified_frames.name)
for frame_number in range(start_frame, segment_end["frame"] + 1):
frame_file = modified_frames_path / (
pixelations.FRAME_PATTERN % frame_number
)
try:
frame_file.unlink()
except FileNotFoundError:
logging.warning("Frame# %s not found", frame_number)
#
#
#
logging.debug("Frame position: {frame_position}")
self.vars.update(
frame_file=self.vars.frame_file,
image=pixelations.FramePixelation(
pathlib.Path(self.vars.original_frames.name)
/ self.vars.frame_file,
canvas_size=(self.vars.canvas_width, self.vars.canvas_height),
),
frame_position=frame_position,
trace=True,
)
def preview(self):
"""Actions when clicking the "previous" button
in the preview panel:
same as in stop_area,
and reset of the drag action
"""
if self.vars.panel_stack[-1] in (START_AREA, STOP_AREA):
self.stop_area()
#
self.tkvars.drag_action.set(self.vars.previous_drag_action)
class Validator(core.Validator):
"""Validate user settings"""
@staticmethod
def checked_export_crf(export_crf):
"""Check if export_crf is inside the allowd range"""
minimum_crf = 0
maximum_crf = 51
if not isinstance(export_crf, int):
raise ValueError("Wrong type, must be an integer")
#
if export_crf < minimum_crf:
logging.warning("Adjusted export_crf to minimum (%s)", minimum_crf)
return minimum_crf
#
if export_crf > maximum_crf:
logging.warning("Adjusted export_crf to maximum (%s)", maximum_crf)
return maximum_crf
#
return export_crf
def checked_export_preset(self, export_preset):
"""Check if export_preset is supported"""
self.must_be_in_collection(
export_preset, EXPORT_PRESETS, "Unsupported preset"
)
return export_preset
@staticmethod
def checked_prefer_include_audio(prefer_include_audio):
"""Check for True or False"""
if prefer_include_audio not in (True, False):
raise ValueError("Unsupported value")
#
return prefer_include_audio
class VideoUI(core.UserInterface):
"""Modular user interface for video pixelation"""
phases = PHASES
panel_names = PANEL_NAMES
looped_panels = {STOP_AREA}
script_name = SCRIPT_NAME
version = VERSION
copyright_notice = COPYRIGHT_NOTICE
action_class = Actions
callback_class = Callbacks
panel_class = Panels
post_panel_action_class = PostPanelActions
rollback_class = Rollbacks
validator_class = Validator
default_settings = dict(
tilesize=10,
export_crf=18,
export_preset="ultrafast",
prefer_include_audio=True,
**core.DEFAULT_SETTINGS,
)
def __init__(self, file_path, options):
"""Initialize the super class"""
super().__init__(
file_path,
options,
SCRIPT_PATH,
canvas_width=CANVAS_WIDTH,
canvas_height=CANVAS_HEIGHT,
)
def additional_variables(self):
"""Subclass-specific post-initialization
(additional variables)
"""
self.vars.update(
original_frames=None,
modified_frames=None,
nb_frames=None,
has_audio=False,
previous_drag_action=core.MOVE_SELECTION,
frame_position=None,
frame_file=None,
frame_rate=None,
frames_cache=None,
ffmpeg_loglevel="quiet",
stations=[],
later_stations=[],
duration_usec=None,
unsaved_changes=False,
frame_limits=core.Namespace(minimum=1, maximum=1),
kept_frames=core.Namespace(start=1, end=1),
)
if self.options.loglevel == logging.DEBUG:
self.vars.update(ffmpeg_loglevel="error")
#
self.tkvars.update(
current_frame=self.callbacks.get_traced_intvar("change_frame"),
current_frame_text=self.callbacks.get_traced_stringvar(
"change_frame_from_text"
),
end_frame=tkinter.IntVar(),
export=core.Namespace(
crf=self.callbacks.get_traced_intvar(
"set_export_preferences",
value=self.vars.user_settings.export_crf,
),
preset=self.callbacks.get_traced_stringvar(
"set_export_preferences",
value=self.vars.user_settings.export_preset,
),
include_audio=tkinter.IntVar(),
),
)
def additional_widgets(self):
"""Subclass-specific post-initialization
(additional widgets)
"""
self.widgets.update(
frame_canvas=None,
frames_slider=None,
frame_number=None,
)
def adjust_current_frame(self, new_frame_number=None):
"""Adjust current frame without calling triggers:
set to frame number if given,
and fix it if it is outside the allowed range
"""
previous_trace_setting = self.vars.trace
self.vars.update(trace=False)
old_frame_number = self.tkvars.current_frame.get()
if new_frame_number is None:
new_frame_number = old_frame_number
#
if new_frame_number < self.vars.frame_limits.minimum:
logging.warning(
"Raising frame# to minimum (%r)",
self.vars.frame_limits.minimum,
)
new_frame_number = self.vars.frame_limits.minimum
elif new_frame_number > self.vars.frame_limits.maximum:
new_frame_number = self.vars.frame_limits.maximum
logging.warning(
"Lowering frame# to maximum (%r)",
self.vars.frame_limits.maximum,
)
new_frame_number = self.vars.frame_limits.maximum
#
if new_frame_number != old_frame_number:
logging.debug("Setting frame# to %r", new_frame_number)
self.tkvars.current_frame.set(new_frame_number)
#
# set current_frame_text unconditionally
self.tkvars.current_frame_text.set(str(new_frame_number))
self.vars.update(
frame_file=pixelations.FRAME_PATTERN % new_frame_number,
trace=previous_trace_setting,
)
def adjust_frame_limits(self, minimum=None, maximum=None):
"""Adjust frame limits without being restricted by
connections of the current_frame and current_frame_text
control variables to their widgets
"""