-
Notifications
You must be signed in to change notification settings - Fork 304
/
Copy pathfunctional.py
2447 lines (1849 loc) · 87.2 KB
/
functional.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
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# pyre-unsafe
import functools
import math
import os
import shutil
import tempfile
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
from augly import audio as audaugs, image as imaugs, utils
from augly.audio import utils as audutils
from augly.video import helpers, utils as vdutils
from augly.video.augmenters import cv2 as ac, ffmpeg as af
def add_noise(
video_path: str,
output_path: Optional[str] = None,
level: int = 25,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Adds noise to a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param level: noise strength for specific pixel component. Default value is
25. Allowed range is [0, 100], where 0 indicates no change
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
noise_aug = af.VideoAugmenterByNoise(level)
noise_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="add_noise", **func_kwargs
)
return output_path or video_path
def apply_lambda(
video_path: str,
output_path: Optional[str] = None,
aug_function: Callable[..., Any] = helpers.identity_function,
metadata: Optional[List[Dict[str, Any]]] = None,
**kwargs,
) -> str:
"""
Apply a user-defined lambda on a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param aug_function: the augmentation function to be applied onto the video
(should expect a video path and output path as input and output the augmented
video to the output path. Nothing needs to be returned)
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@param **kwargs: the input attributes to be passed into `aug_function`
@returns: the path to the augmented video
"""
assert callable(aug_function), (
repr(type(aug_function).__name__) + " object is not callable"
)
func_kwargs = helpers.get_func_kwargs(
metadata, locals(), video_path, aug_function=aug_function.__name__
)
aug_function(video_path, output_path or video_path, **kwargs)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="apply_lambda", **func_kwargs
)
return output_path or video_path
def audio_swap(
video_path: str,
audio_path: str,
output_path: Optional[str] = None,
offset: float = 0.0,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Swaps the video audio for the audio passed in provided an offset
@param video_path: the path to the video to be augmented
@param audio_path: the iopath uri to the audio you'd like to swap with the
video's audio
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param offset: starting point in seconds such that an audio clip of offset to
offset + video_duration is used in the audio swap. Default value is zero
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
audio_swap_aug = af.VideoAugmenterByAudioSwap(audio_path, offset)
audio_swap_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="audio_swap", **func_kwargs
)
return output_path or video_path
def augment_audio(
video_path: str,
output_path: Optional[str] = None,
audio_aug_function: Callable[..., Tuple[np.ndarray, int]] = audaugs.apply_lambda,
metadata: Optional[List[Dict[str, Any]]] = None,
**audio_aug_kwargs,
) -> str:
"""
Augments the audio track of the input video using a given AugLy audio augmentation
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param audio_aug_function: the augmentation function to be applied onto the video's
audio track. Should have the standard API of an AugLy audio augmentation, i.e.
expect input audio as a numpy array or path & output path as input, and output
the augmented audio to the output path
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@param audio_aug_kwargs: the input attributes to be passed into `audio_aug`
@returns: the path to the augmented video
"""
assert callable(audio_aug_function), (
repr(type(audio_aug_function).__name__) + " object is not callable"
)
func_kwargs = helpers.get_func_kwargs(
metadata, locals(), video_path, audio_aug_function=audio_aug_function
)
if audio_aug_function is not None:
try:
func_kwargs["audio_aug_function"] = audio_aug_function.__name__
except AttributeError:
func_kwargs["audio_aug_function"] = type(audio_aug_function).__name__
audio_metadata = []
with tempfile.NamedTemporaryFile(suffix=".wav") as tmpfile:
helpers.extract_audio_to_file(video_path, tmpfile.name)
audio, sr = audutils.validate_and_load_audio(tmpfile.name)
aug_audio, aug_sr = audio_aug_function(
audio, sample_rate=sr, metadata=audio_metadata, **audio_aug_kwargs
)
audutils.ret_and_save_audio(aug_audio, tmpfile.name, aug_sr)
audio_swap(video_path, tmpfile.name, output_path=output_path or video_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata,
audio_metadata=audio_metadata,
function_name="augment_audio",
**func_kwargs,
)
return output_path or video_path
def blend_videos(
video_path: str,
overlay_path: str,
output_path: Optional[str] = None,
opacity: float = 0.5,
overlay_size: float = 1.0,
x_pos: float = 0.0,
y_pos: float = 0.0,
use_second_audio: bool = True,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Overlays a video onto another video at position (width * x_pos, height * y_pos)
at a lower opacity
@param video_path: the path to the video to be augmented
@param overlay_path: the path to the video that will be overlaid onto the
background video
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param opacity: the lower the opacity, the more transparent the overlaid video
@param overlay_size: size of the overlaid video is overlay_size * height of
the background video
@param x_pos: position of overlaid video relative to the background video width
@param y_pos: position of overlaid video relative to the background video height
@param use_second_audio: use the audio of the overlaid video rather than the audio
of the background video
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
blend_func = functools.partial(
imaugs.overlay_image,
opacity=opacity,
overlay_size=overlay_size,
x_pos=x_pos,
y_pos=y_pos,
)
vdutils.apply_to_frames(
blend_func, video_path, overlay_path, output_path, use_second_audio
)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="blend_videos", **func_kwargs
)
return output_path or video_path
def blur(
video_path: str,
output_path: Optional[str] = None,
sigma: float = 1,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Blurs a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param sigma: horizontal sigma, standard deviation of Gaussian blur
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
blur_aug = af.VideoAugmenterByBlur(sigma)
blur_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="blur", **func_kwargs)
return output_path or video_path
def brightness(
video_path: str,
output_path: Optional[str] = None,
level: float = 0.15,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Brightens or darkens a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param level: the value must be a float value in range -1.0 to 1.0, where a
negative value darkens and positive brightens
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
brightness_aug = af.VideoAugmenterByBrightness(level)
brightness_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="brightness", **func_kwargs
)
return output_path or video_path
def change_aspect_ratio(
video_path: str,
output_path: Optional[str] = None,
ratio: Union[float, str] = 1.0,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Changes the sample aspect ratio attribute of the video, and resizes the
video to reflect the new aspect ratio
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param ratio: aspect ratio of the new video, either as a float i.e. width/height,
or as a string representing the ratio in the form "num:denom"
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
aspect_ratio_aug = af.VideoAugmenterByAspectRatio(ratio)
aspect_ratio_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="change_aspect_ratio", **func_kwargs
)
return output_path or video_path
def change_video_speed(
video_path: str,
output_path: Optional[str] = None,
factor: float = 1.0,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Changes the speed of the video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param factor: the factor by which to alter the speed of the video. A factor
less than one will slow down the video, a factor equal to one won't alter
the video, and a factor greater than one will speed up the video
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
speed_aug = af.VideoAugmenterBySpeed(factor)
speed_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="change_video_speed", **func_kwargs
)
return output_path or video_path
def color_jitter(
video_path: str,
output_path: Optional[str] = None,
brightness_factor: float = 0,
contrast_factor: float = 1.0,
saturation_factor: float = 1.0,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Color jitters the video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param brightness_factor: set the brightness expression. The value must be a
float value in range -1.0 to 1.0. The default value is 0
@param contrast_factor: set the contrast expression. The value must be a float
value in range -1000.0 to 1000.0. The default value is 1
@param saturation_factor: set the saturation expression. The value must be a float
in range 0.0 to 3.0. The default value is 1
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
color_jitter_aug = af.VideoAugmenterByColorJitter(
brightness_level=brightness_factor,
contrast_level=contrast_factor,
saturation_level=saturation_factor,
)
color_jitter_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="color_jitter", **func_kwargs
)
return output_path or video_path
def concat(
video_paths: List[str],
output_path: Optional[str] = None,
src_video_path_index: int = 0,
transition: Optional[af.TransitionConfig] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Concatenates videos together. Resizes all other videos to the size of the
`source` video (video_paths[src_video_path_index]), and modifies the sample
aspect ratios to match (ffmpeg will fail to concat if SARs don't match)
@param video_paths: a list of paths to all the videos to be concatenated (in order)
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param src_video_path_index: for metadata purposes, this indicates which video in
the list `video_paths` should be considered the `source` or original video
@param transition: optional transition configuration to apply between the clips
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(
metadata, locals(), video_paths[src_video_path_index]
)
concat_aug = af.VideoAugmenterByConcat(
video_paths,
src_video_path_index,
transition,
)
concat_aug.add_augmenter(video_paths[src_video_path_index], output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata,
function_name="concat",
video_path=video_paths[src_video_path_index],
**func_kwargs,
)
return output_path or video_paths[src_video_path_index]
def contrast(
video_path: str,
output_path: Optional[str] = None,
level: float = 1.0,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Alters the contrast of a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param level: the value must be a float value in range -1000.0 to 1000.0,
where a negative value removes contrast and a positive value adds contrast
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
contrast_aug = af.VideoAugmenterByContrast(level)
contrast_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="contrast", **func_kwargs)
return output_path or video_path
def crop(
video_path: str,
output_path: Optional[str] = None,
left: float = 0.25,
top: float = 0.25,
right: float = 0.75,
bottom: float = 0.75,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Crops the video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param left: left positioning of the crop; between 0 and 1, relative to
the video width
@param top: top positioning of the crop; between 0 and 1, relative to
the video height
@param right: right positioning of the crop; between 0 and 1, relative to
the video width
@param bottom: bottom positioning of the crop; between 0 and 1, relative to
the video height
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
crop_aug = af.VideoAugmenterByCrop(left, top, right, bottom)
crop_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="crop", **func_kwargs)
return output_path or video_path
def encoding_quality(
video_path: str,
output_path: Optional[str] = None,
quality: int = 23,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Alters the encoding quality of a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param quality: CRF scale is 0–51, where 0 is lossless, 23 is the default,
and 51 is worst quality possible. A lower value generally leads to higher
quality, and a subjectively sane range is 17–28
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
encoding_aug = af.VideoAugmenterByQuality(quality)
encoding_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="encoding_quality", **func_kwargs
)
return output_path or video_path
def fps(
video_path: str,
output_path: Optional[str] = None,
fps: int = 15,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Alters the FPS of a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param fps: the desired output frame rate. Note that a FPS value greater than
the original FPS of the video will result in an unaltered video
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
fps_aug = af.VideoAugmenterByFPSChange(fps)
fps_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="fps", **func_kwargs)
return output_path or video_path
def grayscale(
video_path: str,
output_path: Optional[str] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Changes a video to be grayscale
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
grayscale_aug = af.VideoAugmenterByGrayscale()
grayscale_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(
metadata=metadata, function_name="grayscale", **func_kwargs
)
return output_path or video_path
def hflip(
video_path: str,
output_path: Optional[str] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Horizontally flips a video
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
hflip_aug = af.VideoAugmenterByHFlip()
hflip_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="hflip", **func_kwargs)
return output_path or video_path
def hstack(
video_path: str,
second_video_path: str,
output_path: Optional[str] = None,
use_second_audio: bool = False,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Horizontally stacks two videos
@param video_path: the path to the video that will be stacked to the left
@param second_video_path: the path to the video that will be stacked to the right
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param use_second_audio: if set to True, the audio of the right video will be
used instead of the left's
@param metadata: if set to be a list, metadata about the function execution
including its name, the source & dest duration, fps, etc. will be appended
to the inputted list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
hstack_aug = af.VideoAugmenterByStack(second_video_path, use_second_audio, "hstack")
hstack_aug.add_augmenter(video_path, output_path)
if metadata is not None:
helpers.get_metadata(metadata=metadata, function_name="hstack", **func_kwargs)
return output_path or video_path
def insert_in_background(
video_path: str,
output_path: Optional[str] = None,
background_path: Optional[str] = None,
offset_factor: float = 0.0,
source_percentage: Optional[float] = None,
seed: Optional[int] = None,
transition: Optional[af.TransitionConfig] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Puts the video in the middle of the background video
(at offset_factor * background.duration)
@param video_path: the path to the video to be augmented
@param output_path: the path in which the resulting video will be stored.
If not passed in, the original video file will be overwritten
@param background_path: the path to the video in which to insert the main
video. If set to None, the main video will play in the middle of a silent
video with black frames
@param offset_factor: the point in the background video in which the main video
starts to play (this factor is multiplied by the background video duration to
determine the start point)
@param source_percentage: when set, source_percentage of the duration
of the final video (background + source) will be taken up by the
source video. Randomly crops the background video to the correct duration.
If the background video isn't long enough to get the desired source_percentage,
it will be looped.
@param seed: if provided, this will set the random seed to ensure consistency
between runs
@param transition: optional transition configuration to apply between the clips
@param metadata: if set to be a list, metadata about the function execution including
its name, the source & dest duration, fps, etc. will be appended to the inputted
list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
assert (
0.0 <= offset_factor <= 1.0
), "Offset factor must be a value in the range [0.0, 1.0]"
if source_percentage is not None:
assert (
0.0 <= source_percentage <= 1.0
), "Source percentage must be a value in the range [0.0, 1.0]"
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
local_path = utils.pathmgr.get_local_path(video_path)
utils.validate_video_path(local_path)
video_info = helpers.get_video_info(local_path)
video_duration = float(video_info["duration"])
width, height = video_info["width"], video_info["height"]
rng = np.random.RandomState(seed) if seed is not None else np.random
video_paths = []
with tempfile.TemporaryDirectory() as tmpdir:
tmp_video_path = os.path.join(tmpdir, "in.mp4")
resized_bg_path = os.path.join(tmpdir, "bg.mp4")
helpers.add_silent_audio(video_path, tmp_video_path)
if background_path is None:
helpers.create_color_video(resized_bg_path, video_duration, height, width)
else:
resize(background_path, resized_bg_path, height, width)
bg_video_info = helpers.get_video_info(resized_bg_path)
bg_video_duration = float(bg_video_info["duration"])
bg_start = 0
bg_end = bg_video_duration
desired_bg_duration = bg_video_duration
if source_percentage is not None:
# desired relationship: percent * (bg_len + s_len) = s_len
# solve for bg_len -> bg_len = s_len / percent - s_len
desired_bg_duration = video_duration / source_percentage - video_duration
# if background vid isn't long enough, loop
num_loops_needed = math.ceil(desired_bg_duration / bg_video_duration)
if num_loops_needed > 1:
loop(resized_bg_path, num_loops=num_loops_needed)
bg_video_duration *= num_loops_needed
bg_start = rng.uniform(0, bg_video_duration - desired_bg_duration)
bg_end = bg_start + desired_bg_duration
offset = desired_bg_duration * offset_factor
transition_before = False
if offset > 0:
before_path = os.path.join(tmpdir, "before.mp4")
trim(resized_bg_path, before_path, start=bg_start, end=bg_start + offset)
video_paths.append(before_path)
src_video_path_index = 1
transition_before = True
else:
src_video_path_index = 0
video_paths.append(tmp_video_path)
transition_after = False
if bg_start + offset < bg_end:
after_path = os.path.join(tmpdir, "after.mp4")
trim(resized_bg_path, after_path, start=bg_start + offset, end=bg_end)
video_paths.append(after_path)
transition_after = True
concat(
video_paths,
output_path or video_path,
src_video_path_index,
transition=transition,
)
if metadata is not None:
helpers.get_metadata(
metadata=metadata,
function_name="insert_in_background",
background_video_duration=desired_bg_duration,
transition_before=transition_before,
transition_after=transition_after,
**func_kwargs,
)
return output_path or video_path
def insert_in_background_multiple(
video_path: str,
output_path: str,
background_path: str,
src_ids: List[str],
additional_video_paths: List[str],
seed: Optional[int] = None,
min_source_segment_duration: float = 5.0,
max_source_segment_duration: float = 20.0,
min_background_segment_duration: float = 2.0,
min_result_video_duration: float = 30.0,
max_result_video_duration: float = 60.0,
transition: Optional[af.TransitionConfig] = None,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
"""
Places the video (and the additional videos) in the middle of the background video.
@param video_path: the path of the main video to be augmented.
@param output_path: the path in which the output video will be stored.
@param background_path: the path of the video in which to insert the main
(and additional) video.
@param src_ids: the list of identifiers for the main video and additional videos.
@param additional_video_paths: list of additional video paths to be
inserted alongside the main video; one clip from each of the input
videos will be inserted in order.
@param seed: if provided, this will set the random seed to ensure consistency
between runs.
@param min_source_segment_duration: minimum duration in seconds of the source
segments that will be inserted in the background video.
@param max_source_segment_duration: maximum duration in seconds of the source
segments that will be inserted in the background video.
@param min_background_segment_duration: minimum duration in seconds of a background segment.
@param min_result_video_duration: minimum duration in seconds of the output video.
@param max_result_video_duration: maximum duration in seconds of the output video.
@param transition: optional transition configuration to apply between the clips.
@param metadata: if set to be a list, metadata about the function execution including
its name, the source & dest duration, fps, etc. will be appended to the inputted
list. If set to None, no metadata will be appended or returned
@returns: the path to the augmented video
"""
if additional_video_paths:
assert len(additional_video_paths) + 1 == len(
src_ids
), "src_ids need to be specified for the main video and all additional videos."
func_kwargs = helpers.get_func_kwargs(metadata, locals(), video_path)
rng = np.random.RandomState(seed) if seed is not None else np.random
local_path = utils.pathmgr.get_local_path(video_path)
additional_local_paths = (
[utils.pathmgr.get_local_path(p) for p in additional_video_paths]
if additional_video_paths
else []
)
bkg_local_path = utils.pathmgr.get_local_path(background_path)
src_paths = [
local_path,
] + additional_local_paths
src_video_durations = np.array(
[float(helpers.get_video_info(v)["duration"]) for v in src_paths]
)
bkg_duration = float(helpers.get_video_info(bkg_local_path)["duration"])
src_segment_durations = (
rng.random_sample(len(src_video_durations))
* (max_source_segment_duration - min_source_segment_duration)
+ min_source_segment_duration
)
src_segment_durations = np.minimum(src_segment_durations, src_video_durations)
src_segment_starts = rng.random(len(src_video_durations)) * (
src_video_durations - src_segment_durations
)
src_segment_ends = src_segment_starts + src_segment_durations
sum_src_duration = np.sum(src_segment_durations)
required_result_duration = (
len(src_segment_durations) + 1
) * min_background_segment_duration + sum_src_duration
if required_result_duration > max_result_video_duration:
raise ValueError(
"Failed to generate config for source segments in insert_in_background_multiple."
)
duration_budget = max_result_video_duration - required_result_duration
bkg_budget = rng.random() * duration_budget
overall_bkg_needed_duration = (
len(src_segment_durations) + 1
) * min_background_segment_duration + bkg_budget