pygenutils 17.2.1__tar.gz → 18.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. {pygenutils-17.2.1 → pygenutils-18.0.0}/PKG-INFO +1 -1
  2. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/__init__.py +1 -1
  3. pygenutils-18.0.0/pygenutils/audio_and_video/audio_and_video_manipulation.py +666 -0
  4. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/audio_and_video/merge_audio_and_video.py +18 -7
  5. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/audio_and_video/merge_audio_or_video.py +26 -21
  6. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/audio_and_video/trim_media.py +5 -5
  7. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/number_bases/base_converters.py +13 -3
  8. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/strings/text_formatters.py +98 -56
  9. pygenutils-18.0.0/pygenutils/time_handling/program_snippet_exec_timers.py +288 -0
  10. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/time_handling/time_formatters.py +10 -6
  11. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils.egg-info/PKG-INFO +1 -1
  12. {pygenutils-17.2.1 → pygenutils-18.0.0}/pyproject.toml +1 -1
  13. pygenutils-17.2.1/pygenutils/audio_and_video/audio_and_video_manipulation.py +0 -896
  14. pygenutils-17.2.1/pygenutils/time_handling/program_snippet_exec_timers.py +0 -258
  15. {pygenutils-17.2.1 → pygenutils-18.0.0}/LICENSE +0 -0
  16. {pygenutils-17.2.1 → pygenutils-18.0.0}/README.md +0 -0
  17. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/arrays_and_lists/__init__.py +0 -0
  18. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/arrays_and_lists/conversions.py +0 -0
  19. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/arrays_and_lists/data_manipulation.py +0 -0
  20. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/arrays_and_lists/maths.py +0 -0
  21. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/arrays_and_lists/patterns.py +0 -0
  22. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/audio_and_video/__init__.py +0 -0
  23. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/dictionaries/__init__.py +0 -0
  24. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/dictionaries/dict_handler.py +0 -0
  25. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/dictionaries/dict_operators.py +0 -0
  26. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/number_bases/__init__.py +0 -0
  27. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/number_bases/binary_operations.py +0 -0
  28. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/number_bases/bitwise_operators.py +0 -0
  29. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/number_bases/mathematical_utils.py +0 -0
  30. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/operative_systems/__init__.py +0 -0
  31. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/operative_systems/os_operations.py +0 -0
  32. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/sets_and_intervals/__init__.py +0 -0
  33. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/sets_and_intervals/interval_handler.py +0 -0
  34. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/sets_and_intervals/sets_handler.py +0 -0
  35. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/strings/__init__.py +0 -0
  36. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/strings/string_handler.py +0 -0
  37. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/time_handling/__init__.py +0 -0
  38. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/time_handling/_optional_climate.py +0 -0
  39. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/time_handling/calendar_utils.py +0 -0
  40. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/time_handling/countdown.py +0 -0
  41. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/time_handling/date_and_time_maths.py +0 -0
  42. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/time_handling/date_and_time_utils.py +0 -0
  43. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils/time_handling/time_utils.py +0 -0
  44. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils.egg-info/SOURCES.txt +0 -0
  45. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils.egg-info/dependency_links.txt +0 -0
  46. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils.egg-info/requires.txt +0 -0
  47. {pygenutils-17.2.1 → pygenutils-18.0.0}/pygenutils.egg-info/top_level.txt +0 -0
  48. {pygenutils-17.2.1 → pygenutils-18.0.0}/setup.cfg +0 -0
  49. {pygenutils-17.2.1 → pygenutils-18.0.0}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pygenutils
3
- Version: 17.2.1
3
+ Version: 18.0.0
4
4
  Summary: A comprehensive Python utility library for general-purpose and specialised tasks
5
5
  Author-email: Jon Ander Gabantxo <jagabantxo@gmail.com>
6
6
  License-Expression: MIT
@@ -3,7 +3,7 @@
3
3
 
4
4
  # pygenutils/__init__.py
5
5
 
6
- __version__ = "17.2.1"
6
+ __version__ = "18.0.0"
7
7
 
8
8
  # Define what should be available when using 'from pygenutils import *'
9
9
  __all__ = [
@@ -0,0 +1,666 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ #----------------#
5
+ # Import modules #
6
+ #----------------#
7
+
8
+ import inspect
9
+ import os
10
+ import shlex
11
+ import tempfile
12
+
13
+ #------------------------#
14
+ # Import project modules #
15
+ #------------------------#
16
+
17
+ from pygenutils.arrays_and_lists.data_manipulation import flatten_list
18
+ from pygenutils.operative_systems.os_operations import run_system_command, exit_info
19
+ from pygenutils.time_handling.time_formatters import parse_dt_string
20
+
21
+ #--------------------------#
22
+ # Parameters and constants #
23
+ #--------------------------#
24
+
25
+ # Time format strings accepted by datetime.strptime. '%T' is not one of them.
26
+ TIME_FMT_STR_LIST = ['%H:%M:%S', '%H:%M:%S.%f']
27
+
28
+ # Common audio and video formats #
29
+ COMMON_AUDIO_FORMATS = ('.mp3', '.aac', '.wav')
30
+ COMMON_VIDEO_FORMATS = ('.mp4', '.avi', '.mkv')
31
+ COMMON_MEDIA_FORMATS = COMMON_AUDIO_FORMATS + COMMON_VIDEO_FORMATS
32
+
33
+ VALID_PRESETS = [
34
+ "ultrafast", "superfast", "veryfast", "faster", "fast",
35
+ "medium", "slow", "slower", "veryslow",
36
+ ]
37
+
38
+ #------------------#
39
+ # Define functions #
40
+ #------------------#
41
+
42
+ # Internal helpers #
43
+ #------------------#
44
+
45
+ def _load_file_list(files):
46
+ """
47
+ Load files from a path, a list of paths, or a text file of paths.
48
+
49
+ Parameters
50
+ ----------
51
+ files : str | list[str]
52
+ A media path, a text file listing paths, or a list of either.
53
+
54
+ Returns
55
+ -------
56
+ list[str]
57
+ A flattened list of file paths.
58
+
59
+ Raises
60
+ ------
61
+ ValueError
62
+ If a text file cannot be read.
63
+ TypeError
64
+ If the input is neither a string nor a list.
65
+ """
66
+ if isinstance(files, list):
67
+ if any(isinstance(item, list) for item in files):
68
+ files = flatten_list(files)
69
+ return files
70
+
71
+ if isinstance(files, str):
72
+ if os.path.exists(files) and files.endswith(COMMON_MEDIA_FORMATS):
73
+ return [files]
74
+ try:
75
+ with open(files) as file_obj:
76
+ return file_obj.read().splitlines()
77
+ except OSError as exc:
78
+ raise ValueError(f"Error reading file '{files}': {exc}") from exc
79
+
80
+ raise TypeError(f"Expected list or string, got {type(files)}")
81
+
82
+
83
+ def _validate_files(file_list, list_name):
84
+ """
85
+ Raise FileNotFoundError if any path in ``file_list`` is missing.
86
+ """
87
+ for file_path in file_list:
88
+ if not os.path.exists(file_path):
89
+ raise FileNotFoundError(f"{list_name}: '{file_path}' not found.")
90
+
91
+
92
+ def _is_audio_file(file_path):
93
+ """Return True when ``file_path`` ends with a known audio extension."""
94
+ return file_path.endswith(COMMON_AUDIO_FORMATS)
95
+
96
+
97
+ def _is_video_file(file_path):
98
+ """Return True when ``file_path`` ends with a known video extension."""
99
+ return file_path.endswith(COMMON_VIDEO_FORMATS)
100
+
101
+
102
+ def _escape_path(file_path):
103
+ """Quote a path for a shell command."""
104
+ return shlex.quote(file_path)
105
+
106
+
107
+ def _validate_positive_int_or_none(name, value):
108
+ if value is not None and (not isinstance(value, int) or value < 1):
109
+ raise ValueError(f"'{name}' must be a positive integer or None.")
110
+
111
+
112
+ def _validate_zero_padding(zero_padding):
113
+ if zero_padding is not None and (not isinstance(zero_padding, int) or zero_padding < 1):
114
+ caller_args = inspect.getargvalues(inspect.currentframe().f_back).args
115
+ zero_pad_pos = caller_args.index("zero_padding")
116
+ raise ValueError(
117
+ f"'zero_padding' (number {zero_pad_pos}) "
118
+ f"must be an integer >= 1 or None, got {zero_padding}."
119
+ )
120
+
121
+
122
+ def _validate_codec_options(audio_bitrate_fraction, video_bitrate_fraction,
123
+ video_codec, audio_codec, preset, overwrite):
124
+ """
125
+ Validate the shared bitrate, codec, preset, and overwrite arguments.
126
+ """
127
+ _validate_positive_int_or_none("audio_bitrate_fraction", audio_bitrate_fraction)
128
+ _validate_positive_int_or_none("video_bitrate_fraction", video_bitrate_fraction)
129
+ if not isinstance(video_codec, str) or not video_codec:
130
+ raise ValueError(
131
+ "'video_codec' must be a string. Use 'copy' to stream-copy the video."
132
+ )
133
+ if not isinstance(audio_codec, str) or not audio_codec:
134
+ raise ValueError(
135
+ "'audio_codec' must be a string. Use 'copy' to stream-copy the audio."
136
+ )
137
+ if preset not in VALID_PRESETS:
138
+ raise ValueError(f"'preset' must be one of {VALID_PRESETS}, got '{preset}'.")
139
+ if not isinstance(overwrite, bool):
140
+ raise ValueError("'overwrite' must be a boolean value.")
141
+
142
+
143
+ def _bitrate_kbps(fraction):
144
+ """Convert a bitrate fraction to kbps. ``None`` stays ``None``."""
145
+ if fraction is None:
146
+ return None
147
+ return fraction * 32
148
+
149
+
150
+ def _uses_stream_copy(codec):
151
+ """``"copy"`` stream-copies the stream. Any other name re-encodes it."""
152
+ return codec == "copy"
153
+
154
+
155
+ def _stream_codec_args(stream, codec, bitrate_kbps, preset=None):
156
+ """
157
+ Build the codec flags for one stream.
158
+
159
+ A bitrate and, for video, a preset are added only when the stream is
160
+ re-encoded. ``stream`` is ``"v"`` or ``"a"``.
161
+ """
162
+ if _uses_stream_copy(codec):
163
+ return f" -c:{stream} copy"
164
+ args = f" -c:{stream} {codec}"
165
+ if stream == "v" and preset is not None:
166
+ args += f" -preset {preset}"
167
+ if bitrate_kbps is not None:
168
+ args += f" -b:{stream} {bitrate_kbps}k"
169
+ return args
170
+
171
+
172
+ def _overwrite_flag(overwrite):
173
+ return "-y" if overwrite else "-n"
174
+
175
+
176
+ def _resolved_output_path(output_file_name, default_extension=".mp4"):
177
+ """
178
+ Keep a name that already has a media extension.
179
+
180
+ A bare name, including the default ``out_file``, gains ``default_extension``.
181
+ """
182
+ if not output_file_name:
183
+ output_file_name = "out_file"
184
+ extension = os.path.splitext(output_file_name)[1].lower()
185
+ if extension in COMMON_MEDIA_FORMATS:
186
+ return output_file_name
187
+ return f"{output_file_name}{default_extension}"
188
+
189
+
190
+ def _build_pair_merge_command(audio_file, video_file, output_file, overwrite,
191
+ video_codec, audio_codec,
192
+ audio_bitrate_fraction, video_bitrate_fraction,
193
+ preset):
194
+ """
195
+ Build one ffmpeg command that copies or encodes a separated pair.
196
+
197
+ Input 0 is the audio file and input 1 is the video file. The maps take
198
+ the video stream from input 1 and the audio stream from input 0, which
199
+ is what separate yt-dlp tracks need when both containers are ``.mp4``.
200
+ """
201
+ video_args = _stream_codec_args(
202
+ "v", video_codec, _bitrate_kbps(video_bitrate_fraction), preset
203
+ )
204
+ audio_args = _stream_codec_args(
205
+ "a", audio_codec, _bitrate_kbps(audio_bitrate_fraction)
206
+ )
207
+ return (
208
+ f"ffmpeg {_overwrite_flag(overwrite)} "
209
+ f"-i {_escape_path(audio_file)} -i {_escape_path(video_file)} "
210
+ f"-map 1:v:0 -map 0:a:0{video_args}{audio_args} "
211
+ f"{_escape_path(output_file)}"
212
+ )
213
+
214
+
215
+ def _build_concat_command(list_path, output_path, overwrite, has_video,
216
+ video_codec, audio_codec,
217
+ audio_bitrate_fraction, video_bitrate_fraction,
218
+ preset):
219
+ """
220
+ Build a concat-demuxer command for files of one kind.
221
+
222
+ ``-safe 0`` is required: this module is used with absolute paths and
223
+ with names that contain spaces, both of which ffmpeg's concat demuxer
224
+ rejects when ``-safe`` is 1.
225
+ """
226
+ command = (
227
+ f"ffmpeg {_overwrite_flag(overwrite)} -f concat -safe 0 "
228
+ f"-i {_escape_path(list_path)}"
229
+ )
230
+ if has_video:
231
+ command += _stream_codec_args(
232
+ "v", video_codec, _bitrate_kbps(video_bitrate_fraction), preset
233
+ )
234
+ command += _stream_codec_args(
235
+ "a", audio_codec, _bitrate_kbps(audio_bitrate_fraction)
236
+ )
237
+ command += f" {_escape_path(output_path)}"
238
+ return command
239
+
240
+
241
+ def _build_cut_command(input_file, output_file, start_time, end_time, overwrite,
242
+ video_codec, audio_codec,
243
+ audio_bitrate_fraction, video_bitrate_fraction, preset):
244
+ """Build one ffmpeg cut command for a single media file."""
245
+ start_arg = f" -ss {start_time}" if start_time != "start" else ""
246
+ end_arg = f" -to {end_time}" if end_time != "end" else ""
247
+ command = (
248
+ f"ffmpeg {_overwrite_flag(overwrite)} "
249
+ f"-i {_escape_path(input_file)}{start_arg}{end_arg}"
250
+ )
251
+ if _is_video_file(input_file):
252
+ command += _stream_codec_args(
253
+ "v", video_codec, _bitrate_kbps(video_bitrate_fraction), preset
254
+ )
255
+ command += _stream_codec_args(
256
+ "a", audio_codec, _bitrate_kbps(audio_bitrate_fraction)
257
+ )
258
+ command += f" {_escape_path(output_file)}"
259
+ return command
260
+
261
+
262
+ def _run_ffmpeg(command, capture_output, return_output_name, encoding, shell):
263
+ """
264
+ Run one ffmpeg command and raise RuntimeError when the exit code is not 0.
265
+
266
+ Captured stdout and stderr are not printed on success. ffmpeg writes its
267
+ banner to stderr even when the exit code is 0.
268
+ """
269
+ process_exit_info = run_system_command(
270
+ command,
271
+ capture_output=capture_output,
272
+ return_output_name=return_output_name,
273
+ encoding=encoding,
274
+ shell=shell,
275
+ )
276
+ exit_info(
277
+ process_exit_info,
278
+ check_stdout=False,
279
+ check_stderr=False,
280
+ check_return_code=True,
281
+ )
282
+ return process_exit_info
283
+
284
+
285
+ def _write_concat_list(file_list):
286
+ """
287
+ Write an ffmpeg concat list and return its path.
288
+
289
+ The caller deletes the file. Quotes and backslashes in a path are
290
+ escaped so the demuxer reads the path literally.
291
+ """
292
+ handle = tempfile.NamedTemporaryFile(
293
+ "w", suffix=".txt", delete=False, encoding="utf-8"
294
+ )
295
+ try:
296
+ for file_path in file_list:
297
+ escaped = file_path.replace("\\", "\\\\").replace("'", r"\'")
298
+ handle.write(f"file '{escaped}'\n")
299
+ except Exception:
300
+ handle.close()
301
+ os.remove(handle.name)
302
+ raise
303
+ handle.close()
304
+ return handle.name
305
+
306
+
307
+ def _validate_time_format(time_str):
308
+ """Accept the first format in TIME_FMT_STR_LIST that matches."""
309
+ last_error = None
310
+ for time_fmt in TIME_FMT_STR_LIST:
311
+ try:
312
+ parse_dt_string(time_str, time_fmt)
313
+ return
314
+ except ValueError as exc:
315
+ last_error = exc
316
+ raise ValueError(
317
+ f"Invalid time format: {time_str}. Expected one from {TIME_FMT_STR_LIST}."
318
+ ) from last_error
319
+
320
+
321
+ def _numbered_names(count, prefix, zero_padding, extension):
322
+ names = []
323
+ for index in range(1, count + 1):
324
+ number = str(index) if zero_padding is None else str(index).zfill(zero_padding)
325
+ names.append(f"{prefix}_{number}{extension}")
326
+ return names
327
+
328
+
329
+ def _raise_if_failures(action, failures):
330
+ if failures:
331
+ details = "\n".join(failures)
332
+ raise RuntimeError(f"Failed to {action}:\n{details}")
333
+
334
+
335
+ # Main functions #
336
+ #----------------#
337
+
338
+ def merge_media_files(audio_files,
339
+ video_files,
340
+ output_file_list=None,
341
+ zero_padding=1,
342
+ audio_bitrate_fraction=5,
343
+ video_bitrate_fraction=5,
344
+ video_codec="copy",
345
+ audio_codec="copy",
346
+ preset="medium",
347
+ overwrite=True,
348
+ capture_output=False,
349
+ return_output_name=False,
350
+ encoding="utf-8",
351
+ shell=True):
352
+ """
353
+ Merge each audio file with the video file at the same position.
354
+
355
+ Parameters
356
+ ----------
357
+ audio_files : str | list[str]
358
+ Audio paths, or a text file containing them. Argument 0.
359
+ video_files : str | list[str]
360
+ Video paths, or a text file containing them. Argument 1.
361
+ output_file_list : list[str] | None, optional
362
+ Output paths. Generated, with a ``.mp4`` suffix, when omitted.
363
+ zero_padding : int | None, optional
364
+ Width of the generated output numbers. ``None`` disables padding.
365
+ Used only when ``output_file_list`` is omitted.
366
+ audio_bitrate_fraction : int | None, optional
367
+ Multiplied by 32 to give kbps. Applied only when the audio stream
368
+ is re-encoded. ``None`` omits the bitrate.
369
+ video_bitrate_fraction : int | None, optional
370
+ Multiplied by 32 to give kbps. Applied only when the video stream
371
+ is re-encoded. ``None`` omits the bitrate.
372
+ video_codec : str, optional
373
+ ``"copy"`` stream-copies the video. Any other string, such as
374
+ ``"libx264"``, re-encodes it.
375
+ audio_codec : str, optional
376
+ ``"copy"`` stream-copies the audio. Any other string, such as
377
+ ``"aac"``, re-encodes it.
378
+ preset : str, optional
379
+ Video encoding preset. Used only when the video stream is re-encoded.
380
+ overwrite : bool, optional
381
+ ``True`` passes ``-y``. ``False`` passes ``-n``.
382
+ capture_output : bool, optional
383
+ Capture ffmpeg stdout and stderr. They are not printed on success.
384
+ return_output_name : bool, optional
385
+ Passed through to the command runner.
386
+ encoding : str, optional
387
+ Decoding used for captured output.
388
+ shell : bool, optional
389
+ Run the command through the shell.
390
+
391
+ Raises
392
+ ------
393
+ ValueError
394
+ If the lists differ in length or an argument is invalid.
395
+ FileNotFoundError
396
+ If an input path does not exist.
397
+ RuntimeError
398
+ If ffmpeg fails for one or more pairs. Every pair is still attempted.
399
+
400
+ Returns
401
+ -------
402
+ None
403
+ """
404
+ try:
405
+ audio_file_list = _load_file_list(audio_files)
406
+ video_file_list = _load_file_list(video_files)
407
+ except ValueError as exc:
408
+ raise ValueError(f"Error loading files: {exc}") from exc
409
+
410
+ if len(video_file_list) != len(audio_file_list):
411
+ raise ValueError("Input audio and video file lists must have the same length.")
412
+
413
+ if output_file_list is not None and len(output_file_list) != len(video_file_list):
414
+ raise ValueError("Output file name list must match the length of input lists.")
415
+
416
+ _validate_zero_padding(zero_padding)
417
+ _validate_codec_options(
418
+ audio_bitrate_fraction, video_bitrate_fraction,
419
+ video_codec, audio_codec, preset, overwrite,
420
+ )
421
+ _validate_files(audio_file_list, "Audio file list (argument 0)")
422
+ _validate_files(video_file_list, "Video file list (argument 1)")
423
+
424
+ if output_file_list is None:
425
+ output_file_list = _numbered_names(
426
+ len(video_file_list), "merged_video", zero_padding, ".mp4"
427
+ )
428
+
429
+ failures = []
430
+ pair_count = len(audio_file_list)
431
+ for index, (audio_file, video_file, output_file) in enumerate(
432
+ zip(audio_file_list, video_file_list, output_file_list), start=1
433
+ ):
434
+ print(
435
+ f"Creating merged file {index}/{pair_count}: {output_file} "
436
+ f"from audio '{audio_file}' and video '{video_file}'"
437
+ )
438
+ command = _build_pair_merge_command(
439
+ audio_file, video_file, output_file, overwrite,
440
+ video_codec, audio_codec,
441
+ audio_bitrate_fraction, video_bitrate_fraction, preset,
442
+ )
443
+ try:
444
+ _run_ffmpeg(command, capture_output, return_output_name, encoding, shell)
445
+ except RuntimeError as exc:
446
+ failures.append(f"{audio_file} + {video_file}: {exc}")
447
+
448
+ _raise_if_failures("merge media files", failures)
449
+
450
+
451
+ def merge_individual_media_files(media_inputs,
452
+ safe=True,
453
+ output_file_name=None,
454
+ audio_bitrate_fraction=5,
455
+ video_bitrate_fraction=5,
456
+ video_codec="copy",
457
+ audio_codec="copy",
458
+ preset="medium",
459
+ overwrite=True,
460
+ capture_output=False,
461
+ return_output_name=False,
462
+ encoding="utf-8",
463
+ shell=True):
464
+ """
465
+ Concatenate files that are all audio or all video.
466
+
467
+ Parameters
468
+ ----------
469
+ media_inputs : str | list[str]
470
+ Media paths, or a text file containing them.
471
+ safe : bool, optional
472
+ Accepted for existing callers. The concat list is always read with
473
+ ``-safe 0``, because absolute paths and spaces are normal here.
474
+ output_file_name : str | None, optional
475
+ Output path. An existing media extension is kept. A bare name
476
+ receives ``.mp4``.
477
+ audio_bitrate_fraction : int | None, optional
478
+ Multiplied by 32 to give kbps. Applied only when audio is re-encoded.
479
+ video_bitrate_fraction : int | None, optional
480
+ Multiplied by 32 to give kbps. Applied only when video is re-encoded.
481
+ video_codec : str, optional
482
+ ``"copy"`` stream-copies the video. Any other string re-encodes it.
483
+ audio_codec : str, optional
484
+ ``"copy"`` stream-copies the audio. Any other string re-encodes it.
485
+ preset : str, optional
486
+ Video encoding preset. Used only when the video stream is re-encoded.
487
+ overwrite : bool, optional
488
+ ``True`` passes ``-y``. ``False`` passes ``-n``.
489
+ capture_output : bool, optional
490
+ Capture ffmpeg stdout and stderr. They are not printed on success.
491
+ return_output_name : bool, optional
492
+ Passed through to the command runner.
493
+ encoding : str, optional
494
+ Decoding used for captured output.
495
+ shell : bool, optional
496
+ Run the command through the shell.
497
+
498
+ Raises
499
+ ------
500
+ ValueError
501
+ If the inputs mix audio and video, or an argument is invalid.
502
+ RuntimeError
503
+ If ffmpeg fails. The temporary concat list is still removed.
504
+
505
+ Returns
506
+ -------
507
+ None
508
+ """
509
+ if not isinstance(safe, bool):
510
+ raise ValueError("'safe' must be a boolean value.")
511
+ _validate_codec_options(
512
+ audio_bitrate_fraction, video_bitrate_fraction,
513
+ video_codec, audio_codec, preset, overwrite,
514
+ )
515
+
516
+ try:
517
+ file_list = _load_file_list(media_inputs)
518
+ except ValueError as exc:
519
+ raise ValueError(f"Error loading files: {exc}") from exc
520
+
521
+ audio_files = [file_path for file_path in file_list if _is_audio_file(file_path)]
522
+ video_files = [file_path for file_path in file_list if _is_video_file(file_path)]
523
+ if audio_files and video_files:
524
+ raise ValueError(
525
+ "Input list contains both audio and video files. Only one type is allowed."
526
+ )
527
+
528
+ output_path = _resolved_output_path(output_file_name)
529
+ file_type = "audio" if audio_files else "video"
530
+ source = (
531
+ f"{len(file_list)} {file_type} files"
532
+ if isinstance(media_inputs, list)
533
+ else f"files listed in '{media_inputs}'"
534
+ )
535
+ print(f"Creating merged file {output_path} from {source}")
536
+
537
+ list_path = _write_concat_list(file_list)
538
+ try:
539
+ command = _build_concat_command(
540
+ list_path, output_path, overwrite, bool(video_files),
541
+ video_codec, audio_codec,
542
+ audio_bitrate_fraction, video_bitrate_fraction, preset,
543
+ )
544
+ try:
545
+ _run_ffmpeg(command, capture_output, return_output_name, encoding, shell)
546
+ except RuntimeError as exc:
547
+ raise RuntimeError(f"Failed to merge files into {output_path}: {exc}") from exc
548
+ finally:
549
+ if os.path.exists(list_path):
550
+ os.remove(list_path)
551
+
552
+
553
+ def cut_media_files(media_inputs,
554
+ start_time_list,
555
+ end_time_list,
556
+ output_file_list=None,
557
+ zero_padding=1,
558
+ audio_bitrate_fraction=5,
559
+ video_bitrate_fraction=5,
560
+ video_codec="copy",
561
+ audio_codec="copy",
562
+ preset="medium",
563
+ overwrite=True,
564
+ capture_output=False,
565
+ return_output_name=False,
566
+ encoding="utf-8",
567
+ shell=True):
568
+ """
569
+ Cut each media file from a start time to an end time.
570
+
571
+ Parameters
572
+ ----------
573
+ media_inputs : str | list[str]
574
+ Media paths, or a text file containing them.
575
+ A single path must be a one-item list, or a real media file.
576
+ A plain string that is not a media file is read as a list of paths.
577
+ start_time_list : list[str]
578
+ Start times as ``%H:%M:%S`` or ``%H:%M:%S.%f``. ``"start"`` means
579
+ the beginning of the file.
580
+ end_time_list : list[str]
581
+ End times in the same formats. ``"end"`` means the end of the file.
582
+ output_file_list : list[str] | None, optional
583
+ Output paths. Generated when omitted.
584
+ zero_padding : int | None, optional
585
+ Width of the generated output numbers. ``None`` disables padding.
586
+ audio_bitrate_fraction : int | None, optional
587
+ Multiplied by 32 to give kbps. Applied only when audio is re-encoded.
588
+ video_bitrate_fraction : int | None, optional
589
+ Multiplied by 32 to give kbps. Applied only when video is re-encoded.
590
+ video_codec : str, optional
591
+ ``"copy"`` stream-copies the video. Any other string re-encodes it.
592
+ audio_codec : str, optional
593
+ ``"copy"`` stream-copies the audio. Any other string re-encodes it.
594
+ preset : str, optional
595
+ Video encoding preset. Used only when the video stream is re-encoded.
596
+ overwrite : bool, optional
597
+ ``True`` passes ``-y``. ``False`` passes ``-n``.
598
+ capture_output : bool, optional
599
+ Capture ffmpeg stdout and stderr. They are not printed on success.
600
+ return_output_name : bool, optional
601
+ Passed through to the command runner.
602
+ encoding : str, optional
603
+ Decoding used for captured output.
604
+ shell : bool, optional
605
+ Run the command through the shell.
606
+
607
+ Raises
608
+ ------
609
+ RuntimeError
610
+ If a path list cannot be read, or if ffmpeg fails for one or more files.
611
+ Every file is still attempted before the ffmpeg error is raised.
612
+ ValueError
613
+ If a time is invalid, the lists differ in length, or both ends of a
614
+ cut are the default ``"start"`` and ``"end"``.
615
+
616
+ Returns
617
+ -------
618
+ None
619
+ """
620
+ try:
621
+ file_list = _load_file_list(media_inputs)
622
+ except ValueError as exc:
623
+ raise RuntimeError(f"Error loading files: {exc}") from exc
624
+
625
+ if len(file_list) != len(start_time_list) or len(start_time_list) != len(end_time_list):
626
+ raise ValueError("Media, start time, and end time lists must have the same length.")
627
+
628
+ for start_time, end_time in zip(start_time_list, end_time_list):
629
+ if (start_time, end_time) == ("start", "end"):
630
+ raise ValueError("Both start and end cannot be default values.")
631
+ if start_time != "start":
632
+ _validate_time_format(start_time)
633
+ if end_time != "end":
634
+ _validate_time_format(end_time)
635
+
636
+ _validate_zero_padding(zero_padding)
637
+ _validate_codec_options(
638
+ audio_bitrate_fraction, video_bitrate_fraction,
639
+ video_codec, audio_codec, preset, overwrite,
640
+ )
641
+
642
+ if output_file_list is None:
643
+ output_file_list = _numbered_names(len(file_list), "cut_file", zero_padding, ".mp4")
644
+
645
+ failures = []
646
+ file_count = len(file_list)
647
+ for index, (input_file, output_file, start_time, end_time) in enumerate(
648
+ zip(file_list, output_file_list, start_time_list, end_time_list), start=1
649
+ ):
650
+ start_desc = start_time if start_time != "start" else "the beginning"
651
+ end_desc = end_time if end_time != "end" else "the end"
652
+ print(
653
+ f"Creating cut file {index}/{file_count}: {output_file} "
654
+ f"from '{input_file}' (from {start_desc} to {end_desc})"
655
+ )
656
+ command = _build_cut_command(
657
+ input_file, output_file, start_time, end_time, overwrite,
658
+ video_codec, audio_codec,
659
+ audio_bitrate_fraction, video_bitrate_fraction, preset,
660
+ )
661
+ try:
662
+ _run_ffmpeg(command, capture_output, return_output_name, encoding, shell)
663
+ except RuntimeError as exc:
664
+ failures.append(f"{input_file}: {exc}")
665
+
666
+ _raise_if_failures("cut media files", failures)