-
Notifications
You must be signed in to change notification settings - Fork 486
Expand file tree
/
Copy path__init__.py
More file actions
1783 lines (1589 loc) · 60.9 KB
/
__init__.py
File metadata and controls
1783 lines (1589 loc) · 60.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# PySceneDetect: Python-Based Video Scene Detector
# -------------------------------------------------------------------
# [ Site: https://scenedetect.com ]
# [ Docs: https://scenedetect.com/docs/ ]
# [ Github: https://github.com/Breakthrough/PySceneDetect/ ]
#
# Copyright (C) 2014-2024 Brandon Castellano <http://www.bcastell.com>.
# PySceneDetect is licensed under the BSD 3-Clause License; see the
# included LICENSE file, or visit one of the above pages for details.
#
"""Implementation of the PySceneDetect application itself (the `scenedetect` command). The main CLI
entry-point function is :func:scenedetect_cli, which is a chained command group.
Commands are first parsed into a context (`CliContext`), which is then passed to a controller which
performs scene detection and other required actions (`run_scenedetect`).
"""
# Some parts of this file need word wrap to be displayed.
import inspect
import logging
import os
import os.path
import typing as ty
from copy import deepcopy
import click
import scenedetect
import scenedetect._cli.commands as cli_commands
from scenedetect._cli.config import (
CHOICE_MAP,
CONFIG_FILE_PATH,
CONFIG_MAP,
DEFAULT_JPG_QUALITY,
DEFAULT_WEBP_QUALITY,
)
from scenedetect._cli.context import USER_CONFIG, CliContext, check_split_video_requirements
from scenedetect.backends import AVAILABLE_BACKENDS
from scenedetect.common import FrameTimecode
from scenedetect.detectors import (
AdaptiveDetector,
ContentDetector,
HashDetector,
HistogramDetector,
ThresholdDetector,
)
from scenedetect.platform import get_cv2_imwrite_params, get_system_version_info
PROGRAM_VERSION = scenedetect.__version__
"""Used to avoid name conflict with named `scenedetect` command below."""
logger = logging.getLogger("pyscenedetect")
LINE_SEPARATOR = "-" * 72
# About & copyright message string shown for the 'about' CLI command (scenedetect about).
ABOUT_STRING = """
Site: http://scenedetect.com/
Docs: https://www.scenedetect.com/docs/
Code: https://github.com/Breakthrough/PySceneDetect/
Copyright (C) 2014-2024 Brandon Castellano. All rights reserved.
PySceneDetect is released under the BSD 3-Clause license. See the
LICENSE file or visit [ https://www.scenedetect.com/copyright/ ].
This software uses the following third-party components:
> NumPy [Copyright (C) 2018, Numpy Developers]
> OpenCV [Copyright (C) 2018, OpenCV Team]
> click [Copyright (C) 2018, Armin Ronacher]
> simpletable [Copyright (C) 2014 Matheus Vieira Portela]
> PyAV [Copyright (C) 2017, Mike Boers and others]
> MoviePy [Copyright (C) 2015 Zulko]
This software may also invoke the following third-party executables:
> FFmpeg [Copyright (C) 2018, Fabrice Bellard]
> mkvmerge [Copyright (C) 2005-2016, Matroska]
Certain distributions of PySceneDetect may include ffmpeg. See
the included LICENSE-FFMPEG or visit [ https://ffmpeg.org ].
Binary distributions of PySceneDetect include a compiled Python
distribution. See the included LICENSE-PYTHON file, or visit
[ https://docs.python.org/3/license.html ].
THE SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED.
"""
class Command(click.Command):
"""Custom formatting for commands."""
def format_help(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
"""Writes the help into the formatter if it exists."""
if ctx.parent:
formatter.write(click.style("`%s` Command" % ctx.command.name, fg="cyan"))
formatter.write_paragraph()
formatter.write(click.style(LINE_SEPARATOR, fg="cyan"))
formatter.write_paragraph()
else:
formatter.write(click.style(LINE_SEPARATOR, fg="yellow"))
formatter.write_paragraph()
formatter.write(click.style("PySceneDetect Help", fg="yellow"))
formatter.write_paragraph()
formatter.write(click.style(LINE_SEPARATOR, fg="yellow"))
formatter.write_paragraph()
self.format_usage(ctx, formatter)
self.format_help_text(ctx, formatter)
self.format_options(ctx, formatter)
self.format_epilog(ctx, formatter)
def format_help_text(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
"""Writes the help text to the formatter if it exists."""
if self.help:
base_command = ctx.parent.info_name if ctx.parent is not None else ctx.info_name
formatted_help = self.help.format(
scenedetect=base_command, scenedetect_with_video="%s -i video.mp4" % base_command
)
text = inspect.cleandoc(formatted_help).partition("\f")[0]
formatter.write_paragraph()
formatter.write_text(text)
def format_epilog(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
"""Writes the epilog into the formatter if it exists."""
if self.epilog:
epilog = inspect.cleandoc(self.epilog)
formatter.write_paragraph()
formatter.write_text(epilog)
class CommandGroup(Command, click.Group):
"""Custom formatting for command groups."""
pass
def print_command_help(ctx: click.Context, command: click.Command):
"""Print help/usage for a given command. Modifies `ctx` in-place."""
ctx.info_name = command.name
ctx.command = command
click.echo("")
click.echo(command.get_help(ctx))
SCENEDETECT_COMMAND_HELP = """PySceneDetect is a scene cut/transition detection program. PySceneDetect takes an input video, runs detection on it, and uses the resulting scene information to generate output. The syntax for using PySceneDetect is:
{scenedetect_with_video} [detector] [commands]
For [detector] use `detect-adaptive` or `detect-content` to find fast cuts, and `detect-threshold` for fades in/out. If [detector] is not specified, a default detector will be used.
Examples:
Split video wherever a new scene is detected:
{scenedetect_with_video} split-video
Save scene list in CSV format with images at the start, middle, and end of each scene:
{scenedetect_with_video} list-scenes save-images
Skip the first 10 seconds of the input video:
{scenedetect_with_video} time --start 10s detect-content
Show summary of all options and commands:
{scenedetect} --help
Global options (e.g. -i/--input, -c/--config) must be specified before any commands and their options. The order of commands is not strict, but each command must only be specified once."""
@click.group(
cls=CommandGroup,
chain=True,
context_settings=dict(help_option_names=["-h", "--help"]),
invoke_without_command=True,
epilog="""Type "scenedetect [command] --help" for command usage. See https://scenedetect.com/docs/ for online docs.""",
help=SCENEDETECT_COMMAND_HELP,
)
# *NOTE*: Although input is required, we cannot mark it as `required=True`, otherwise we will reject
# commands of the form `scenedetect detect-content --help`.
@click.option(
"--input",
"-i",
multiple=False,
required=False,
metavar="VIDEO",
type=click.STRING,
help="[REQUIRED] Input video file. Image sequences and URLs are supported.",
)
@click.option(
"--output",
"-o",
multiple=False,
required=False,
metavar="DIR",
type=click.Path(exists=False, dir_okay=True, writable=True, resolve_path=True),
help="Output directory for created files. If unset, working directory will be used. May be overridden by command options.%s"
% (USER_CONFIG.get_help_string("global", "output", show_default=False)),
)
@click.option(
"--config",
"-c",
metavar="FILE",
type=click.Path(exists=True, file_okay=True, readable=True, resolve_path=False),
help="Path to config file. If unset, tries to load config from %s" % (CONFIG_FILE_PATH),
)
@click.option(
"--stats",
"-s",
metavar="CSV",
type=click.Path(exists=False, file_okay=True, writable=True, resolve_path=False),
help="Stats file (.csv) to write frame metrics. Existing files will be overwritten. Used for tuning detection parameters and data analysis.",
)
@click.option(
"--framerate",
"-f",
metavar="FPS",
type=click.FLOAT,
default=None,
help="Override framerate with value as frames/sec.",
)
@click.option(
"--min-scene-len",
"-m",
metavar="TIMECODE",
type=click.STRING,
default=None,
help="Minimum length of any scene. TIMECODE can be specified as number of frames (-m 10), time in seconds (-m 2.5), or timecode (-m 00:02:53.633).%s"
% USER_CONFIG.get_help_string("global", "min-scene-len"),
)
@click.option(
"--drop-short-scenes",
is_flag=True,
flag_value=True,
default=None,
help="Drop scenes shorter than -m/--min-scene-len, instead of combining with neighbors.%s"
% (USER_CONFIG.get_help_string("global", "drop-short-scenes")),
)
@click.option(
"--merge-last-scene",
is_flag=True,
flag_value=True,
default=None,
help="Merge last scene with previous if shorter than -m/--min-scene-len.%s"
% (USER_CONFIG.get_help_string("global", "merge-last-scene")),
)
@click.option(
"--backend",
"-b",
metavar="BACKEND",
type=click.Choice(CHOICE_MAP["global"]["backend"]),
default=None,
help="Backend to use for video input. Backend options can be set using a config file (-c/--config). [available: %s]%s"
% (", ".join(AVAILABLE_BACKENDS.keys()), USER_CONFIG.get_help_string("global", "backend")),
)
@click.option(
"--crop",
metavar="X0 Y0 X1 Y1",
type=(int, int, int, int),
default=None,
help="Crop input video. Specified as two points representing top left and bottom right corner of crop region. 0 0 is top-left of the video frame. Bounds are inclusive (e.g. for a 100x100 video, the region covering the whole frame is 0 0 99 99).%s"
% (USER_CONFIG.get_help_string("global", "crop", show_default=False)),
)
@click.option(
"--downscale",
"-d",
metavar="N",
type=click.INT,
default=None,
help="Integer factor to downscale video by before processing. If unset, value is selected based on resolution. Set -d 1 to disable downscaling.%s"
% (USER_CONFIG.get_help_string("global", "downscale", show_default=False)),
)
@click.option(
"--frame-skip",
"-fs",
metavar="N",
type=click.INT,
default=None,
help="Skip N frames during processing. Reduces processing speed at expense of accuracy. -fs 1 skips every other frame processing 50%% of the video, -fs 2 processes 33%% of the video frames, -fs 3 processes 25%%, etc... %s"
% USER_CONFIG.get_help_string("global", "frame-skip"),
)
@click.option(
"--verbosity",
"-v",
metavar="LEVEL",
type=click.Choice(CHOICE_MAP["global"]["verbosity"], False),
default=None,
help="Amount of information to show. LEVEL must be one of: %s. Overrides -q/--quiet.%s"
% (
", ".join(CHOICE_MAP["global"]["verbosity"]),
USER_CONFIG.get_help_string("global", "verbosity"),
),
)
@click.option(
"--logfile",
"-l",
metavar="FILE",
type=click.Path(exists=False, file_okay=True, writable=True, resolve_path=False),
help="Save debug log to FILE. Appends to existing file if present.",
)
@click.option(
"--quiet",
"-q",
is_flag=True,
flag_value=True,
help="Suppress output to terminal/stdout. Equivalent to setting --verbosity=none.",
)
@click.pass_context
def scenedetect(
ctx: click.Context,
input: ty.Optional[ty.AnyStr],
output: ty.Optional[ty.AnyStr],
stats: ty.Optional[ty.AnyStr],
config: ty.Optional[ty.AnyStr],
framerate: ty.Optional[float],
min_scene_len: ty.Optional[str],
drop_short_scenes: ty.Optional[bool],
merge_last_scene: ty.Optional[bool],
backend: ty.Optional[str],
crop: ty.Optional[ty.Tuple[int, int, int, int]],
downscale: ty.Optional[int],
frame_skip: ty.Optional[int],
verbosity: ty.Optional[str],
logfile: ty.Optional[ty.AnyStr],
quiet: bool,
):
ctx = ctx.obj
assert isinstance(ctx, CliContext)
ctx.handle_options(
input_path=input,
output=output,
framerate=framerate,
stats_file=stats,
frame_skip=frame_skip,
min_scene_len=min_scene_len,
drop_short_scenes=drop_short_scenes,
merge_last_scene=merge_last_scene,
backend=backend,
crop=crop,
downscale=downscale,
quiet=quiet,
logfile=logfile,
config=config,
stats=stats,
verbosity=verbosity,
)
def add_hidden_alias(command: click.Command, alias: str):
"""Adds a copy of `command` that can be invoked under the name `alias`."""
hidden_command = deepcopy(command)
hidden_command.hidden = True
scenedetect.add_command(hidden_command, alias)
@click.command("help", cls=Command)
@click.argument(
"command_name",
required=False,
type=click.STRING,
)
@click.pass_context
def help_command(ctx: click.Context, command_name: str):
"""Print full help reference."""
# TODO: Other commands still seem to run if this is specified.
assert isinstance(ctx.parent.command, click.MultiCommand)
parent_command = ctx.parent.command
all_commands = set(parent_command.list_commands(ctx))
if command_name is not None:
if command_name not in all_commands:
error_strs = [
"unknown command. List of valid commands:",
" %s" % ", ".join(sorted(all_commands)),
]
raise click.BadParameter("\n".join(error_strs), param_hint="command")
click.echo("")
print_command_help(ctx, parent_command.get_command(ctx, command_name))
else:
click.echo(ctx.parent.get_help())
for command in sorted(all_commands):
print_command_help(ctx, parent_command.get_command(ctx, command))
ctx.exit()
@click.command("about", cls=Command, add_help_option=False)
@click.pass_context
def about_command(ctx: click.Context):
"""Print license/copyright info."""
click.echo("")
click.echo(click.style(LINE_SEPARATOR, fg="cyan"))
click.echo(click.style(" About PySceneDetect %s" % PROGRAM_VERSION, fg="yellow"))
click.echo(click.style(LINE_SEPARATOR, fg="cyan"))
click.echo(ABOUT_STRING)
ctx.exit()
@click.command("version", cls=Command, add_help_option=False)
@click.pass_context
def version_command(ctx: click.Context):
"""Print PySceneDetect version."""
click.echo("")
click.echo(get_system_version_info())
ctx.exit()
TIME_COMMAND_HELP = """Set start/end/duration of input video.
Values can be specified as seconds (SSSS.nn), frames (NNNN), or timecode (HH:MM:SS.nnn). For example, to process only the first minute of a video:
{scenedetect_with_video} time --end 00:01:00
{scenedetect_with_video} time --duration 60.0
Note that --end and --duration are mutually exclusive (i.e. only one of the two can be set). Lastly, the following is an example using absolute frame numbers to process frames 0 through 1000:
{scenedetect_with_video} time --start 0 --end 1000
"""
@click.command("time", cls=Command, help=TIME_COMMAND_HELP)
@click.option(
"--start",
"-s",
metavar="TIMECODE",
type=click.STRING,
default=None,
help="Time in video to start detection. TIMECODE can be specified as seconds (--start=100.0), frames (--start=100), or timecode (--start=00:01:40.000).",
)
@click.option(
"--duration",
"-d",
metavar="TIMECODE",
type=click.STRING,
default=None,
help="Maximum time in video to process. TIMECODE format is the same as other arguments. Mutually exclusive with -e/--end.",
)
@click.option(
"--end",
"-e",
metavar="TIMECODE",
type=click.STRING,
default=None,
help="Time in video to end detecting scenes. TIMECODE format is the same as other arguments. Mutually exclusive with -d/--duration",
)
@click.pass_context
def time_command(
ctx: click.Context,
start: ty.Optional[str],
duration: ty.Optional[str],
end: ty.Optional[str],
):
ctx = ctx.obj
assert isinstance(ctx, CliContext)
if duration is not None and end is not None:
raise click.BadParameter(
"Only one of --duration/-d or --end/-e can be specified, not both.",
param_hint="time",
)
logger.debug("Setting video time:\n start: %s, duration: %s, end: %s", start, duration, end)
# *NOTE*: The Python API uses 0-based frame indices, but the CLI uses 1-based indices to
# match the default start number used by `ffmpeg` when saving frames as images. As such,
# we must correct start time if set as frames. See the test_cli_time* tests for for details.
ctx.start_time = ctx.parse_timecode(start, correct_pts=True)
ctx.end_time = ctx.parse_timecode(end)
ctx.duration = ctx.parse_timecode(duration)
if ctx.start_time and ctx.end_time and (ctx.start_time + 1) > ctx.end_time:
raise click.BadParameter("-e/--end time must be greater than -s/--start")
DETECT_CONTENT_HELP = """Find fast cuts using differences in HSL (filtered).
For each frame, a score from 0 to 255.0 is calculated which represents the difference in content between the current and previous frame (higher = more different). A cut is generated when a frame score exceeds -t/--threshold. Frame scores are saved under the "content_val" column in a statsfile.
Scores are calculated from several components which are also recorded in the statsfile:
- *delta_hue*: Difference between pixel hue values of adjacent frames.
- *delta_sat*: Difference between pixel saturation values of adjacent frames.
- *delta_lum*: Difference between pixel luma (brightness) values of adjacent frames.
- *delta_edges*: Difference between calculated edges of adjacent frames. Typically larger than other components, so threshold may need to be increased to compensate.
Once calculated, these components are multiplied by the specified -w/--weights to calculate the final frame score ("content_val"). Weights are set as a set of 4 numbers in the form (*delta_hue*, *delta_sat*, *delta_lum*, *delta_edges*). For example, "--weights 1.0 0.5 1.0 0.2 --threshold 32" is a good starting point for trying edge detection. The final sum is normalized by the weight of all components, so they need not equal 100%. Edge detection is disabled by default to improve performance.
Examples:
{scenedetect_with_video} detect-content
{scenedetect_with_video} detect-content --threshold 27.5
"""
@click.command("detect-content", cls=Command, help=DETECT_CONTENT_HELP)
@click.option(
"--threshold",
"-t",
metavar="VAL",
type=click.FloatRange(
CONFIG_MAP["detect-content"]["threshold"].min_val,
CONFIG_MAP["detect-content"]["threshold"].max_val,
),
default=None,
help='The max difference (0.0 to 255.0) that adjacent frames score must exceed to trigger a cut. Lower values are more sensitive to shot changes. Refers to "content_val" in stats file.%s'
% (USER_CONFIG.get_help_string("detect-content", "threshold")),
)
@click.option(
"--weights",
"-w",
type=(float, float, float, float),
default=None,
metavar="HUE SAT LUM EDGE",
help="Weights of 4 components used to calculate frame score from (delta_hue, delta_sat, delta_lum, delta_edges).%s"
% (USER_CONFIG.get_help_string("detect-content", "weights")),
)
@click.option(
"--luma-only",
"-l",
is_flag=True,
flag_value=True,
help="Only use luma (brightness) channel. Useful for greyscale videos. Equivalent to setting -w 0 0 1 0.%s"
% (USER_CONFIG.get_help_string("detect-content", "luma-only")),
)
@click.option(
"--kernel-size",
"-k",
metavar="N",
type=click.INT,
default=None,
help="Size of kernel for expanding detected edges. Must be odd integer greater than or equal to 3. If unset, kernel size is estimated using video resolution.%s"
% (USER_CONFIG.get_help_string("detect-content", "kernel-size")),
)
@click.option(
"--min-scene-len",
"-m",
metavar="TIMECODE",
type=click.STRING,
default=None,
help="Minimum length of any scene. Overrides global option -m/--min-scene-len. %s"
% (
""
if USER_CONFIG.is_default("detect-content", "min-scene-len")
else USER_CONFIG.get_help_string("detect-content", "min-scene-len")
),
)
@click.option(
"--filter-mode",
"-f",
metavar="MODE",
type=click.Choice(CHOICE_MAP["detect-content"]["filter-mode"], False),
default=None,
help="Mode used to enforce -m/--min-scene-len option. Can be one of: %s. %s"
% (
", ".join(CHOICE_MAP["detect-content"]["filter-mode"]),
USER_CONFIG.get_help_string("detect-content", "filter-mode"),
),
)
@click.pass_context
def detect_content_command(
ctx: click.Context,
threshold: ty.Optional[float],
weights: ty.Optional[ty.Tuple[float, float, float, float]],
luma_only: bool,
kernel_size: ty.Optional[int],
min_scene_len: ty.Optional[str],
filter_mode: ty.Optional[str],
):
ctx = ctx.obj
assert isinstance(ctx, CliContext)
detector_args = ctx.get_detect_content_params(
threshold=threshold,
luma_only=luma_only,
min_scene_len=min_scene_len,
weights=weights,
kernel_size=kernel_size,
filter_mode=filter_mode,
)
ctx.add_detector(ContentDetector, detector_args)
DETECT_ADAPTIVE_HELP = """Find fast cuts using diffs in HSL colorspace (rolling average).
Two-pass algorithm that first calculates frame scores with `detect-content`, and then applies a rolling average when processing the result. This can help mitigate false detections in situations such as camera movement.
Examples:
{scenedetect_with_video} detect-adaptive
{scenedetect_with_video} detect-adaptive --threshold 3.2
"""
@click.command("detect-adaptive", cls=Command, help=DETECT_ADAPTIVE_HELP)
@click.option(
"--threshold",
"-t",
metavar="VAL",
type=click.FLOAT,
default=None,
help='Threshold (float) that frame score must exceed to trigger a cut. Refers to "adaptive_ratio" in stats file.%s'
% (USER_CONFIG.get_help_string("detect-adaptive", "threshold")),
)
@click.option(
"--min-content-val",
"-c",
metavar="VAL",
type=click.FLOAT,
default=None,
help='Minimum threshold (float) that "content_val" must exceed to trigger a cut.%s'
% (USER_CONFIG.get_help_string("detect-adaptive", "min-content-val")),
)
@click.option(
"--frame-window",
"-f",
metavar="VAL",
type=click.INT,
default=None,
help="Size of window to detect deviations from mean. Represents how many frames before/after the current one to use for mean.%s"
% (USER_CONFIG.get_help_string("detect-adaptive", "frame-window")),
)
@click.option(
"--weights",
"-w",
type=(float, float, float, float),
default=None,
help='Weights of 4 components ("delta_hue", "delta_sat", "delta_lum", "delta_edges") used to calculate "content_val".%s'
% (USER_CONFIG.get_help_string("detect-content", "weights")),
)
@click.option(
"--luma-only",
"-l",
is_flag=True,
flag_value=True,
help='Only use luma (brightness) channel. Useful for greyscale videos. Equivalent to "--weights 0 0 1 0".%s'
% (USER_CONFIG.get_help_string("detect-content", "luma-only")),
)
@click.option(
"--kernel-size",
"-k",
metavar="N",
type=click.INT,
default=None,
help="Size of kernel for expanding detected edges. Must be odd number >= 3. If unset, size is estimated using video resolution.%s"
% (USER_CONFIG.get_help_string("detect-content", "kernel-size")),
)
@click.option(
"--min-scene-len",
"-m",
metavar="TIMECODE",
type=click.STRING,
default=None,
help="Minimum length of any scene. Overrides global option -m/--min-scene-len. TIMECODE can be specified in frames (-m 100), in seconds with `s` suffix (-m 3.5s), or timecode (-m 00:01:52.778).%s"
% (
""
if USER_CONFIG.is_default("detect-adaptive", "min-scene-len")
else USER_CONFIG.get_help_string("detect-adaptive", "min-scene-len")
),
)
@click.pass_context
def detect_adaptive_command(
ctx: click.Context,
threshold: ty.Optional[float],
min_content_val: ty.Optional[float],
frame_window: ty.Optional[int],
weights: ty.Optional[ty.Tuple[float, float, float, float]],
luma_only: bool,
kernel_size: ty.Optional[int],
min_scene_len: ty.Optional[str],
):
ctx = ctx.obj
assert isinstance(ctx, CliContext)
detector_args = ctx.get_detect_adaptive_params(
threshold=threshold,
min_content_val=min_content_val,
frame_window=frame_window,
luma_only=luma_only,
min_scene_len=min_scene_len,
weights=weights,
kernel_size=kernel_size,
)
ctx.add_detector(AdaptiveDetector, detector_args)
DETECT_THRESHOLD_HELP = """Find fade in/out using averaging.
Detects fade-in and fade-out events using average pixel values. Resulting cuts are placed between adjacent fade-out and fade-in events.
Examples:
{scenedetect_with_video} detect-threshold
{scenedetect_with_video} detect-threshold --threshold 15
"""
@click.command("detect-threshold", cls=Command, help=DETECT_THRESHOLD_HELP)
@click.option(
"--threshold",
"-t",
metavar="VAL",
type=click.FloatRange(
CONFIG_MAP["detect-threshold"]["threshold"].min_val,
CONFIG_MAP["detect-threshold"]["threshold"].max_val,
),
default=None,
help='Threshold (integer) that frame score must exceed to start a new scene. Refers to "delta_rgb" in stats file.%s'
% (USER_CONFIG.get_help_string("detect-threshold", "threshold")),
)
@click.option(
"--fade-bias",
"-f",
metavar="PERCENT",
type=click.FloatRange(
CONFIG_MAP["detect-threshold"]["fade-bias"].min_val,
CONFIG_MAP["detect-threshold"]["fade-bias"].max_val,
),
default=None,
help="Percent (%%) from -100 to 100 of timecode skew of cut placement. -100 indicates the start frame, +100 indicates the end frame, and 0 is the middle of both.%s"
% (USER_CONFIG.get_help_string("detect-threshold", "fade-bias")),
)
@click.option(
"--add-last-scene",
"-l",
is_flag=True,
flag_value=True,
help="If set and video ends after a fade-out event, generate a final cut at the last fade-out position.%s"
% (USER_CONFIG.get_help_string("detect-threshold", "add-last-scene")),
)
@click.option(
"--min-scene-len",
"-m",
metavar="TIMECODE",
type=click.STRING,
default=None,
help="Minimum length of any scene. Overrides global option -m/--min-scene-len. TIMECODE can be specified in frames (-m 100), in seconds with `s` suffix (-m 3.5s), or timecode (-m 00:01:52.778).%s"
% (
""
if USER_CONFIG.is_default("detect-threshold", "min-scene-len")
else USER_CONFIG.get_help_string("detect-threshold", "min-scene-len")
),
)
@click.pass_context
def detect_threshold_command(
ctx: click.Context,
threshold: ty.Optional[float],
fade_bias: ty.Optional[float],
add_last_scene: bool,
min_scene_len: ty.Optional[str],
):
ctx = ctx.obj
assert isinstance(ctx, CliContext)
detector_args = ctx.get_detect_threshold_params(
threshold=threshold,
fade_bias=fade_bias,
add_last_scene=add_last_scene,
min_scene_len=min_scene_len,
)
ctx.add_detector(ThresholdDetector, detector_args)
DETECT_HIST_HELP = """Find fast cuts by differencing YUV histograms.
Uses Y channel after converting each frame to YUV to create a histogram of each frame. Histograms between frames are compared to determine a score for how similar they are.
Saved as the `hist_diff` metric in a statsfile.
Examples:
{scenedetect_with_video} detect-hist
{scenedetect_with_video} detect-hist --threshold 0.1 --bins 240
"""
@click.command("detect-hist", cls=Command, help=DETECT_HIST_HELP)
@click.option(
"--threshold",
"-t",
metavar="VAL",
type=click.FloatRange(
CONFIG_MAP["detect-hist"]["threshold"].min_val,
CONFIG_MAP["detect-hist"]["threshold"].max_val,
),
default=None,
help="Max difference (0.0 to 1.0) between histograms of adjacent frames. Lower "
"values are more sensitive to changes.%s"
% (USER_CONFIG.get_help_string("detect-hist", "threshold")),
)
@click.option(
"--bins",
"-b",
metavar="NUM",
type=click.IntRange(
CONFIG_MAP["detect-hist"]["bins"].min_val, CONFIG_MAP["detect-hist"]["bins"].max_val
),
default=None,
help="The number of bins to use for the histogram calculation.%s"
% (USER_CONFIG.get_help_string("detect-hist", "bins")),
)
@click.option(
"--min-scene-len",
"-m",
metavar="TIMECODE",
type=click.STRING,
default=None,
help="Minimum length of any scene. Overrides global min-scene-len (-m) setting."
" TIMECODE can be specified as exact number of frames, a time in seconds followed by s,"
" or a timecode in the format HH:MM:SS or HH:MM:SS.nnn.%s"
% (
""
if USER_CONFIG.is_default("detect-hist", "min-scene-len")
else USER_CONFIG.get_help_string("detect-hist", "min-scene-len")
),
)
@click.pass_context
def detect_hist_command(
ctx: click.Context,
threshold: ty.Optional[float],
bins: ty.Optional[int],
min_scene_len: ty.Optional[str],
):
ctx = ctx.obj
assert isinstance(ctx, CliContext)
detector_args = ctx.get_detect_hist_params(
threshold=threshold, bins=bins, min_scene_len=min_scene_len
)
ctx.add_detector(HistogramDetector, detector_args)
DETECT_HASH_HELP = """Find fast cuts using perceptual hashing.
The perceptual hash is taken of adjacent frames, and used to calculate the hamming distance between them. The distance is then normalized by the squared size of the hash, and compared to the threshold.
Saved as the `hash_dist` metric in a statsfile.
Examples:
{scenedetect_with_video} detect-hash
{scenedetect_with_video} detect-hash --size 32 --lowpass 3
"""
@click.command("detect-hash", cls=Command, help=DETECT_HASH_HELP)
@click.option(
"--threshold",
"-t",
metavar="VAL",
type=click.FloatRange(
CONFIG_MAP["detect-hash"]["threshold"].min_val,
CONFIG_MAP["detect-hash"]["threshold"].max_val,
),
default=None,
help=(
"Max distance between hash values (0.0 to 1.0) of adjacent frames. Lower values are "
"more sensitive to changes.%s" % (USER_CONFIG.get_help_string("detect-hash", "threshold"))
),
)
@click.option(
"--size",
"-s",
metavar="SIZE",
type=click.IntRange(
CONFIG_MAP["detect-hash"]["size"].min_val, CONFIG_MAP["detect-hash"]["size"].max_val
),
default=None,
help="Size of square of low frequency data to include from the discrete cosine transform.%s"
% (USER_CONFIG.get_help_string("detect-hash", "size")),
)
@click.option(
"--lowpass",
"-l",
metavar="FRAC",
type=click.IntRange(
CONFIG_MAP["detect-hash"]["lowpass"].min_val, CONFIG_MAP["detect-hash"]["lowpass"].max_val
),
default=None,
help=(
"How much high frequency information to filter from the DCT. 2 means keep lower 1/2 of "
"the frequency data, 4 means only keep 1/4, etc...%s"
% (USER_CONFIG.get_help_string("detect-hash", "lowpass"))
),
)
@click.option(
"--min-scene-len",
"-m",
metavar="TIMECODE",
type=click.STRING,
default=None,
help="Minimum length of any scene. Overrides global min-scene-len (-m) setting."
" TIMECODE can be specified as exact number of frames, a time in seconds followed by s,"
" or a timecode in the format HH:MM:SS or HH:MM:SS.nnn.%s"
% (
""
if USER_CONFIG.is_default("detect-hash", "min-scene-len")
else USER_CONFIG.get_help_string("detect-hash", "min-scene-len")
),
)
@click.pass_context
def detect_hash_command(
ctx: click.Context,
threshold: ty.Optional[float],
size: ty.Optional[int],
lowpass: ty.Optional[int],
min_scene_len: ty.Optional[str],
):
ctx = ctx.obj
assert isinstance(ctx, CliContext)
detector_args = ctx.get_detect_hash_params(
threshold=threshold, size=size, lowpass=lowpass, min_scene_len=min_scene_len
)
ctx.add_detector(HashDetector, detector_args)
LOAD_SCENES_HELP = """Load scenes from CSV instead of detecting. Can be used with CSV generated by `list-scenes`. Scenes are loaded using the specified column as cut locations (frame number or timecode).
Examples:
{scenedetect_with_video} load-scenes -i scenes.csv
{scenedetect_with_video} load-scenes -i scenes.csv --start-col-name "Start Timecode"
"""
@click.command("load-scenes", cls=Command, help=LOAD_SCENES_HELP)
@click.option(
"--input",
"-i",
multiple=False,
metavar="FILE",
required=True,
type=click.Path(exists=True, file_okay=True, readable=True, resolve_path=True),
help="Scene list to read cut information from.",
)
@click.option(
"--start-col-name",
"-c",
metavar="STRING",
type=click.STRING,
default=None,
help="Name of column used to mark scene cuts.%s"
% (USER_CONFIG.get_help_string("load-scenes", "start-col-name")),
)
@click.pass_context
def load_scenes_command(
ctx: click.Context, input: ty.Optional[str], start_col_name: ty.Optional[str]
):
ctx = ctx.obj
assert isinstance(ctx, CliContext)
logger.debug("Will load scenes from %s (start_col_name = %s)", input, start_col_name)
if ctx.scene_manager.get_num_detectors() > 0:
raise click.ClickException("The load-scenes command cannot be used with detectors.")
if ctx.load_scenes_input:
raise click.ClickException("The load-scenes command must only be specified once.")
input = os.path.abspath(input)
if not os.path.exists(input):
raise click.BadParameter(
f"Could not load scenes, file does not exist: {input}", param_hint="-i/--input"
)
ctx.load_scenes_input = input
ctx.load_scenes_column_name = ctx.config.get_value(
"load-scenes", "start-col-name", start_col_name
)
SAVE_HTML_HELP = """Save scene list to HTML file.
To customize image generation, specify the `save-images` command before `save-html`. This command always uses the result of the preceeding `save-images` command, or runs it with the default config values unless `--no-images` is set.
"""
@click.command("save-html", cls=Command, help=SAVE_HTML_HELP)
@click.option(
"--filename",
"-f",
metavar="NAME",
default="$VIDEO_NAME-Scenes.html",
type=click.STRING,
help="Filename format to use for the scene list HTML file. You can use the $VIDEO_NAME macro in the file name. Note that you may have to wrap the format name using single quotes.%s"
% (USER_CONFIG.get_help_string("save-html", "filename")),
)
@click.option(
"--no-images",
"-n",
is_flag=True,
flag_value=True,
help="Do not include images with the result.%s"
% (USER_CONFIG.get_help_string("save-html", "no-images")),
)
@click.option(
"--image-width",
"-w",