ci(ffmpeg_handling): add main restriction for build task #2
No files matched your search
@@ -0,0 +1,111 @@
|
||||
name: FFmpeg Handling CI
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- dev
|
||||
- main
|
||||
paths:
|
||||
- "ffmpeg_handling/**"
|
||||
- "serverlibrary/**"
|
||||
- ".gitea/workflows/ffmpeg_handling.yaml"
|
||||
pull_request:
|
||||
branches:
|
||||
- dev
|
||||
paths:
|
||||
- "ffmpeg_handling/**"
|
||||
- "serverlibrary/**"
|
||||
- ".gitea/workflows/ffmpeg_handling.yaml"
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: nikolaik/python-nodejs:python3.12-nodejs20
|
||||
|
||||
steps:
|
||||
- name: Check out the tested commit
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install FFmpeg
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install --yes --no-install-recommends ffmpeg
|
||||
|
||||
- name: Install ffmpeg_handling
|
||||
working-directory: ffmpeg_handling
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install ../serverlibrary .
|
||||
|
||||
- name: Run tests
|
||||
working-directory: ffmpeg_handling
|
||||
run: python src/ffmpeg_handling/run_test.py
|
||||
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: nikolaik/python-nodejs:python3.12-nodejs20
|
||||
|
||||
steps:
|
||||
- name: Check out the tested commit
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install Ruff
|
||||
run: python -m pip install ruff
|
||||
|
||||
- name: Lint ffmpeg_handling
|
||||
run: ruff check ffmpeg_handling/src ffmpeg_handling/tests ffmpeg_handling/main.py
|
||||
|
||||
build:
|
||||
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }}
|
||||
needs: [test, lint]
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: nikolaik/python-nodejs:python3.12-nodejs20
|
||||
|
||||
steps:
|
||||
- name: Check out the tested commit
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install build dependencies
|
||||
working-directory: ffmpeg_handling
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install ../serverlibrary .
|
||||
python -m pip install pyinstaller
|
||||
|
||||
- name: Build one-file executable
|
||||
working-directory: ffmpeg_handling
|
||||
run: python -m PyInstaller --clean --noconfirm ffmpeg_handling.spec
|
||||
|
||||
- name: Verify executable
|
||||
run: test -x ffmpeg_handling/dist/ffmpeg_handling
|
||||
|
||||
- name: Upload executable
|
||||
uses: https://github.com/christopherHX/gitea-upload-artifact@v4
|
||||
with:
|
||||
name: ffmpeg-handling-build
|
||||
path: ffmpeg_handling/dist/ffmpeg_handling
|
||||
if-no-files-found: error
|
||||
|
||||
install:
|
||||
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }}
|
||||
needs: build
|
||||
runs-on: [self-hosted, linux, x64]
|
||||
|
||||
steps:
|
||||
- name: Download executable
|
||||
uses: https://github.com/christopherHX/gitea-download-artifact@v4
|
||||
with:
|
||||
name: ffmpeg-handling-build
|
||||
path: dist/
|
||||
|
||||
- name: Install ffmpeg_handling
|
||||
run: |
|
||||
set -euo pipefail
|
||||
install -d -m 755 "$HOME/tools"
|
||||
install -m 755 dist/ffmpeg_handling "$HOME/tools/ffmpeg_handling"
|
||||
Vendored
+29
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "ffmpeg_handling: Run sample command",
|
||||
"type": "debugpy",
|
||||
"request": "launch",
|
||||
"program": "${workspaceFolder}/main.py",
|
||||
"args": [
|
||||
"info",
|
||||
"${workspaceFolder}/testfiles/test_auto.mkv"
|
||||
],
|
||||
"cwd": "${workspaceFolder}",
|
||||
"python": "${workspaceFolder}/.venv/bin/python3",
|
||||
"console": "integratedTerminal",
|
||||
"justMyCode": true
|
||||
},
|
||||
{
|
||||
"name": "ffmpeg_handling: Run tests",
|
||||
"type": "debugpy",
|
||||
"request": "launch",
|
||||
"program": "${workspaceFolder}/src/ffmpeg_handling/run_test.py",
|
||||
"cwd": "${workspaceFolder}",
|
||||
"python": "${workspaceFolder}/.venv/bin/python3",
|
||||
"console": "integratedTerminal",
|
||||
"justMyCode": true
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
+38
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"label": "ffmpeg_handling: Run tests",
|
||||
"type": "process",
|
||||
"command": "${workspaceFolder}/.venv/bin/python3",
|
||||
"args": [
|
||||
"src/ffmpeg_handling/run_test.py"
|
||||
],
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}"
|
||||
},
|
||||
"group": "test",
|
||||
"problemMatcher": []
|
||||
},
|
||||
{
|
||||
"label": "ffmpeg_handling: Build one-file binary",
|
||||
"type": "process",
|
||||
"command": "${workspaceFolder}/.venv/bin/python3",
|
||||
"args": [
|
||||
"-m",
|
||||
"PyInstaller",
|
||||
"--clean",
|
||||
"--noconfirm",
|
||||
"ffmpeg_handling.spec"
|
||||
],
|
||||
"options": {
|
||||
"cwd": "${workspaceFolder}"
|
||||
},
|
||||
"group": {
|
||||
"kind": "build",
|
||||
"isDefault": false
|
||||
},
|
||||
"problemMatcher": []
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
# Running, testing, and building
|
||||
|
||||
From the repository root, install the build extra and run the test suite:
|
||||
|
||||
```sh
|
||||
uv sync --group build
|
||||
.venv/bin/python3 ffmpeg_handling/src/ffmpeg_handling/run_test.py
|
||||
```
|
||||
|
||||
In VS Code, use **ffmpeg_handling: Run sample command** or
|
||||
**ffmpeg_handling: Run tests** from Run and Debug. The corresponding test task
|
||||
and **ffmpeg_handling: Build one-file binary** are available from the task
|
||||
picker.
|
||||
|
||||
The one-file build is configured by `ffmpeg_handling/ffmpeg_handling.spec`.
|
||||
Build with:
|
||||
|
||||
```sh
|
||||
.venv/bin/python3 -m PyInstaller --clean --noconfirm \
|
||||
ffmpeg_handling/ffmpeg_handling.spec
|
||||
```
|
||||
|
||||
The executable is written to `ffmpeg_handling/dist/ffmpeg_handling`. It is a
|
||||
single-file Python application; `ffmpeg` and `ffprobe` must still be installed
|
||||
and available on `PATH`. Build separately on each target OS and architecture;
|
||||
PyInstaller does not cross-compile.
|
||||
|
||||
The Gitea workflow in `.gitea/workflows/ffmpeg_handling.yaml` runs tests,
|
||||
Ruff, and the executable build for changes to this project. A successful push
|
||||
to `main` installs the executable as `~/tools/ffmpeg_handling` on the
|
||||
self-hosted Linux x64 runner.
|
||||
Whitespace-only changes.
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,45 @@
|
||||
# -*- mode: python ; coding: utf-8 -*-
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
project_dir = Path(SPECPATH).resolve()
|
||||
repository_dir = project_dir.parent
|
||||
|
||||
analysis = Analysis(
|
||||
[str(project_dir / "src" / "ffmpeg_handling" / "__main__.py")],
|
||||
pathex=[
|
||||
str(project_dir),
|
||||
str(project_dir / "src"),
|
||||
str(repository_dir / "serverlibrary" / "src"),
|
||||
],
|
||||
binaries=[],
|
||||
datas=[],
|
||||
hiddenimports=[],
|
||||
hookspath=[],
|
||||
hooksconfig={},
|
||||
runtime_hooks=[],
|
||||
excludes=[],
|
||||
noarchive=False,
|
||||
optimize=0,
|
||||
)
|
||||
pyz = PYZ(analysis.pure)
|
||||
|
||||
exe = EXE(
|
||||
pyz,
|
||||
analysis.scripts,
|
||||
analysis.binaries,
|
||||
analysis.datas,
|
||||
[],
|
||||
name="ffmpeg_handling",
|
||||
debug=False,
|
||||
bootloader_ignore_signals=False,
|
||||
strip=False,
|
||||
upx=False,
|
||||
runtime_tmpdir=None,
|
||||
console=True,
|
||||
disable_windowed_traceback=False,
|
||||
argv_emulation=False,
|
||||
target_arch=None,
|
||||
codesign_identity=None,
|
||||
entitlements_file=None,
|
||||
)
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import sys
|
||||
|
||||
from ffmpeg_handling.cli import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,22 @@
|
||||
[project]
|
||||
name = "ffmpeg-handling"
|
||||
version = "0.1.0"
|
||||
description = "Add your description here"
|
||||
readme = "README.md"
|
||||
authors = [
|
||||
{ name = "Lucas Vivo", email = "lucas@mediahost" }
|
||||
]
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"serverlibrary",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
ffmpeg-handling = "ffmpeg_handling:main"
|
||||
|
||||
[build-system]
|
||||
requires = ["uv_build>=0.12.19,<0.13.0"]
|
||||
build-backend = "uv_build"
|
||||
|
||||
[tool.uv.sources]
|
||||
serverlibrary = { workspace = true }
|
||||
@@ -0,0 +1,6 @@
|
||||
"""FFmpeg media processing commands."""
|
||||
|
||||
from .argparse_builder import build_parser
|
||||
from .cli import main
|
||||
|
||||
__all__ = ["build_parser", "main"]
|
||||
@@ -0,0 +1,5 @@
|
||||
import sys
|
||||
|
||||
from ffmpeg_handling.cli import main
|
||||
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,150 @@
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
from serverlibrary import parser_add_loglevel
|
||||
|
||||
from .audio_commands import (
|
||||
cmd_extract_audio_track,
|
||||
cmd_filter_audio,
|
||||
cmd_remove_audio_track,
|
||||
cmd_remove_russian_from_db,
|
||||
cmd_set_primary_audio,
|
||||
)
|
||||
from .metadata_commands import cmd_apply_chapters, cmd_set_metadata, cmd_show_metadata
|
||||
from .video_commands import (
|
||||
cmd_convert_audio,
|
||||
cmd_convert_av,
|
||||
cmd_convert_av_all_suffix,
|
||||
cmd_convert_video,
|
||||
cmd_cut_segment,
|
||||
cmd_downsize,
|
||||
cmd_info,
|
||||
cmd_remove_subs,
|
||||
)
|
||||
|
||||
|
||||
def add_command(subparsers, name, func, help_text, *, aliases=(), parents=()):
|
||||
parser = subparsers.add_parser(
|
||||
name, aliases=list(aliases), parents=list(parents), help=help_text
|
||||
)
|
||||
parser.set_defaults(func=func, command=name)
|
||||
return parser
|
||||
|
||||
|
||||
def add_audio_index(parser):
|
||||
parser.add_argument(
|
||||
"-a", "--audio-index", type=int, nargs="+", help="Absolute audio stream index"
|
||||
)
|
||||
|
||||
|
||||
def build_parser():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Media processing tool using ffmpeg/ffprobe subprocesses",
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
)
|
||||
parser_add_loglevel(parser)
|
||||
base = argparse.ArgumentParser(add_help=False)
|
||||
base.add_argument("input", nargs="?", type=Path, help="Input file or directory")
|
||||
base.add_argument("-o", "--output", type=Path)
|
||||
base.add_argument("--overwrite", action="store_true")
|
||||
base.add_argument("--backup", action="store_true")
|
||||
base.add_argument("--loud", action="store_true")
|
||||
base.add_argument("--kidflag", action="store_true")
|
||||
base.add_argument("-r", "--recursive", action="store_true")
|
||||
base.add_argument("--dry-run", action="store_true")
|
||||
subparsers = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
add_command(
|
||||
subparsers, "info", cmd_info, "Inspect media metadata",
|
||||
aliases=("i",), parents=(base,),
|
||||
)
|
||||
|
||||
command = add_command(
|
||||
subparsers, "convert-av", cmd_convert_av, "Full video/audio re-encode",
|
||||
aliases=("cav",), parents=(base,),
|
||||
)
|
||||
command.add_argument("--video-codec", default="libx264")
|
||||
command.add_argument("--audio-codec", default="aac")
|
||||
command.add_argument("--preset", default="slow")
|
||||
command.add_argument("--quality", type=int)
|
||||
command.add_argument("--new-suffix")
|
||||
|
||||
command = add_command(
|
||||
subparsers, "convert-av-all", cmd_convert_av_all_suffix,
|
||||
"Re-encode files matching a suffix", aliases=("call",), parents=(base,),
|
||||
)
|
||||
command.add_argument("suffix")
|
||||
command.add_argument("--video-codec", default="libx264")
|
||||
command.add_argument("--audio-codec", default="aac")
|
||||
command.add_argument("--preset", default="slow")
|
||||
command.add_argument("--quality", type=int)
|
||||
command.add_argument("--new-suffix")
|
||||
|
||||
command = add_command(
|
||||
subparsers, "convert-audio", cmd_convert_audio, "Convert audio only",
|
||||
aliases=("ca",), parents=(base,),
|
||||
)
|
||||
command.add_argument("--audio-codec", default="aac")
|
||||
command = add_command(
|
||||
subparsers, "convert-video", cmd_convert_video, "Convert video only",
|
||||
aliases=("cv",), parents=(base,),
|
||||
)
|
||||
command.add_argument("--video-codec", default="libx264")
|
||||
add_command(
|
||||
subparsers, "remove-subs", cmd_remove_subs, "Strip subtitle streams",
|
||||
aliases=("rs",), parents=(base,),
|
||||
)
|
||||
command = add_command(
|
||||
subparsers, "remove-audio", cmd_remove_audio_track, "Remove audio streams",
|
||||
aliases=("ra",), parents=(base,),
|
||||
)
|
||||
add_audio_index(command)
|
||||
command = add_command(
|
||||
subparsers, "extract-audio", cmd_extract_audio_track,
|
||||
"Extract audio streams as MP3", aliases=("ea",), parents=(base,),
|
||||
)
|
||||
add_audio_index(command)
|
||||
|
||||
command = add_command(
|
||||
subparsers, "downsize", cmd_downsize, "Scale and compress video",
|
||||
aliases=("d",), parents=(base,),
|
||||
)
|
||||
command.add_argument("-w", "--width", type=int)
|
||||
command.add_argument("-he", "--height", type=int)
|
||||
command.add_argument("-c", "--crf", type=int)
|
||||
command = add_command(
|
||||
subparsers, "filter-audio", cmd_filter_audio, "Apply audio filters",
|
||||
aliases=("fa",), parents=(base,),
|
||||
)
|
||||
add_audio_index(command)
|
||||
command = add_command(
|
||||
subparsers, "cut", cmd_cut_segment, "Cut a media segment",
|
||||
aliases=("c",), parents=(base,),
|
||||
)
|
||||
command.add_argument("--start")
|
||||
command.add_argument("--duration")
|
||||
command = add_command(
|
||||
subparsers, "set-primary-audio", cmd_set_primary_audio,
|
||||
"Set the primary audio stream", aliases=("spa",), parents=(base,),
|
||||
)
|
||||
add_audio_index(command)
|
||||
add_command(
|
||||
subparsers, "remove-russian-from-db", cmd_remove_russian_from_db,
|
||||
"Remove Russian audio and subtitles", aliases=("rrfd",), parents=(base,),
|
||||
)
|
||||
command = add_command(
|
||||
subparsers, "chapters", cmd_apply_chapters, "Apply chapter metadata",
|
||||
aliases=("ch",), parents=(base,),
|
||||
)
|
||||
command.add_argument("-cf", "--chapter-file")
|
||||
add_command(
|
||||
subparsers, "metadata-print", cmd_show_metadata, "Show metadata",
|
||||
aliases=("mp",), parents=(base,),
|
||||
)
|
||||
command = add_command(
|
||||
subparsers, "metadata-set", cmd_set_metadata, "Set metadata",
|
||||
aliases=("ms",), parents=(base,),
|
||||
)
|
||||
command.add_argument("-k", "--key")
|
||||
command.add_argument("-v", "--value")
|
||||
return parser
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Audio stream editing and filtering commands."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from .helpers import (
|
||||
get_audio_tracks,
|
||||
get_scodec,
|
||||
get_subtitle_tracks,
|
||||
is_russian_track,
|
||||
logger,
|
||||
probe_media,
|
||||
run_ffmpeg_for_args,
|
||||
select_audio_stream,
|
||||
translate_audio_tracks,
|
||||
)
|
||||
from .video_commands import remove_streams
|
||||
|
||||
|
||||
def cmd_remove_audio_track(args):
|
||||
remove_indices = {
|
||||
select_audio_stream(args.input, index) for index in args.audio_index
|
||||
}
|
||||
return remove_streams(args, remove_indices, output_subtitle_codec=True)
|
||||
|
||||
|
||||
def cmd_extract_audio_track(args):
|
||||
outputs = []
|
||||
for index in args.audio_index:
|
||||
stream_index = select_audio_stream(args.input, index)
|
||||
output = Path(args.output).with_suffix(".mp3")
|
||||
if len(args.audio_index) > 1:
|
||||
output = output.with_name(f"{output.stem}_stream_{stream_index}{output.suffix}")
|
||||
command = [
|
||||
"ffmpeg", "-y", "-i", str(args.input),
|
||||
"-map", f"0:{stream_index}", "-vn", "-c:a", "libmp3lame",
|
||||
"-b:a", "192k", str(output),
|
||||
]
|
||||
run_ffmpeg_for_args(args, command)
|
||||
outputs.append(output)
|
||||
return bool(outputs), "nooutputneeded"
|
||||
|
||||
|
||||
def cmd_filter_audio(args):
|
||||
if not args.audio_index:
|
||||
raise ValueError("At least one audio stream index is required")
|
||||
if len(args.audio_index) > 1:
|
||||
logger.warning("Only the first requested audio stream will be filtered")
|
||||
selected_index = select_audio_stream(args.input, args.audio_index[0])
|
||||
streams = probe_media(args.input).get("streams", [])
|
||||
audio_streams = [
|
||||
stream for stream in streams if stream.get("codec_type") == "audio"
|
||||
]
|
||||
selected = next(stream for stream in audio_streams if stream["index"] == selected_index)
|
||||
title = selected.get("tags", {}).get("title", f"Audio {selected_index}")
|
||||
language = selected.get("tags", {}).get("language", "und")
|
||||
filter_graph = (
|
||||
f"[0:{selected_index}]highpass=f=100,"
|
||||
"acompressor=threshold=-22dB:ratio=4:attack=10:release=150,"
|
||||
"equalizer=f=2500:t=q:w=1:g=5,"
|
||||
"equalizer=f=4000:t=q:w=1:g=4,"
|
||||
"deesser=i=0.4:f=0.25,alimiter=limit=0.95,dynaudnorm=f=200:g=15"
|
||||
"[filtered]"
|
||||
)
|
||||
command = [
|
||||
"ffmpeg", "-y", "-i", str(args.input),
|
||||
"-filter_complex", filter_graph,
|
||||
"-map", "0:v?", "-map", "0:a?", "-map", "[filtered]", "-map", "0:s?",
|
||||
"-map_metadata", "0", "-c:v", "copy", "-c:a", "libvorbis",
|
||||
"-c:s", get_scodec(args.output),
|
||||
f"-metadata:s:a:{len(audio_streams)}", f"title={title} + filtered",
|
||||
f"-metadata:s:a:{len(audio_streams)}", f"language={language}",
|
||||
str(args.output),
|
||||
]
|
||||
return run_ffmpeg_for_args(args, command)
|
||||
|
||||
|
||||
def cmd_set_primary_audio(args):
|
||||
if not args.audio_index:
|
||||
raise ValueError("At least one audio stream index is required")
|
||||
if len(args.audio_index) > 1:
|
||||
logger.warning("Only the first requested audio stream will be selected")
|
||||
primary = select_audio_stream(args.input, args.audio_index[0])
|
||||
streams = probe_media(args.input).get("streams", [])
|
||||
audio_streams = [
|
||||
stream for stream in streams if stream.get("codec_type") == "audio"
|
||||
]
|
||||
ordered_audio = [primary] + [
|
||||
stream["index"] for stream in audio_streams if stream["index"] != primary
|
||||
]
|
||||
audio_indices = {stream["index"] for stream in audio_streams}
|
||||
command = ["ffmpeg", "-y", "-i", str(args.input)]
|
||||
for stream in streams:
|
||||
if stream["index"] not in audio_indices:
|
||||
command.extend(["-map", f"0:{stream['index']}"])
|
||||
for index in ordered_audio:
|
||||
command.extend(["-map", f"0:{index}"])
|
||||
command.extend(["-map_metadata", "0", "-c", "copy"])
|
||||
for audio_index in range(len(ordered_audio)):
|
||||
disposition = "default" if ordered_audio[audio_index] == primary else "0"
|
||||
command.extend([f"-disposition:a:{audio_index}", disposition])
|
||||
command.extend(["-c:s", get_scodec(args.output), str(args.output)])
|
||||
return run_ffmpeg_for_args(args, command)
|
||||
|
||||
|
||||
def cmd_remove_russian_from_db(args):
|
||||
try:
|
||||
tracks = translate_audio_tracks(
|
||||
get_audio_tracks(args.input) + get_subtitle_tracks(args.input)
|
||||
)
|
||||
except ValueError as error:
|
||||
logger.warning("File %s: %s", args.input.name, error)
|
||||
return False, "nooutputneeded"
|
||||
|
||||
remove_indices = {
|
||||
track["number"] for track in tracks if is_russian_track(track)
|
||||
}
|
||||
if not remove_indices:
|
||||
return False, "nooutputneeded"
|
||||
return remove_streams(args, remove_indices)
|
||||
Executable
+151
@@ -0,0 +1,151 @@
|
||||
#!/home/lucas/scripts/.venv/bin/python3
|
||||
"""Command-line media utility backed by the ffmpeg and ffprobe executables."""
|
||||
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from serverlibrary import setup_logging
|
||||
|
||||
from .argparse_builder import build_parser
|
||||
from .helpers import (
|
||||
ask,
|
||||
ensure,
|
||||
logger,
|
||||
move_overwrite_file,
|
||||
natural_sort_key,
|
||||
video_files,
|
||||
)
|
||||
|
||||
COMMANDS = {
|
||||
"info": {"name": "info", "output": False},
|
||||
"convert-av": {"name": "convert-av", "output": True},
|
||||
"convert-av-all": {"name": "convert-av-all", "output": True},
|
||||
"convert-audio": {"name": "convert-audio", "output": True},
|
||||
"convert-video": {"name": "convert-video", "output": True},
|
||||
"remove-subs": {"name": "remove-subs", "output": True},
|
||||
"remove-audio": {"name": "remove-audio", "output": True},
|
||||
"extract-audio": {"name": "extract-audio", "output": True},
|
||||
"downsize": {"name": "downsize", "output": True},
|
||||
"filter-audio": {"name": "filter-audio", "output": True},
|
||||
"cut": {"name": "cut", "output": True},
|
||||
"set-primary-audio": {"name": "set-primary-audio", "output": True},
|
||||
"chapters": {"name": "chapters", "output": True},
|
||||
"metadata-print": {"name": "metadata-print", "output": False},
|
||||
"metadata-set": {"name": "metadata-set", "output": True},
|
||||
"remove-russian-from-db": {"name": "remove-russian-from-db", "output": True},
|
||||
}
|
||||
|
||||
|
||||
def _fill_required_options(args):
|
||||
if args.command in {"convert-av", "convert-av-all"}:
|
||||
args.quality = ensure(args.quality, "Output quality (e.g. 23)")
|
||||
if args.command == "cut":
|
||||
args.start = ensure(args.start, "Start time (e.g. 10s, 1:00)")
|
||||
args.duration = ensure(args.duration, "Duration (e.g. 30s)")
|
||||
if args.command == "downsize":
|
||||
args.width = ensure(args.width, "Width (e.g. 1080)")
|
||||
args.height = ensure(args.height, "Height (e.g. 720)")
|
||||
args.crf = ensure(args.crf, "CRF (e.g. 23)")
|
||||
if args.command in {"filter-audio", "remove-audio", "extract-audio", "set-primary-audio"}:
|
||||
indices = ensure(args.audio_index, "Audio stream index")
|
||||
if isinstance(indices, str):
|
||||
args.audio_index = [
|
||||
int(value)
|
||||
for value in re.split(r"[,\s]+", indices.strip())
|
||||
if value
|
||||
]
|
||||
if args.command == "chapters":
|
||||
args.chapter_file = Path(ensure(args.chapter_file, "Chapter title file"))
|
||||
if args.command == "metadata-set":
|
||||
args.key = ensure(args.key, "Metadata key")
|
||||
args.value = ensure(args.value, "Metadata value")
|
||||
|
||||
|
||||
def _process_input(args, parser) -> int:
|
||||
if args.input is None:
|
||||
input_value = ensure(None, f"Input file ({Path.cwd()})")
|
||||
else:
|
||||
input_value = args.input
|
||||
input_path = Path(input_value).expanduser().resolve()
|
||||
args.input = input_path
|
||||
if not input_path.exists():
|
||||
parser.error(f"Input path does not exist: {input_path}")
|
||||
|
||||
if COMMANDS[args.command]["output"] and args.output is None:
|
||||
default_output = (
|
||||
input_path.with_name(f"{input_path.stem}_overwrite{input_path.suffix}")
|
||||
if args.overwrite
|
||||
else input_path.with_name(
|
||||
f"{input_path.stem}_{args.command}{input_path.suffix}"
|
||||
)
|
||||
)
|
||||
if args.overwrite:
|
||||
args.output = default_output
|
||||
else:
|
||||
selected_output = ask("Output file (enter for default file)")
|
||||
args.output = (
|
||||
Path(selected_output).expanduser() if selected_output else default_output
|
||||
)
|
||||
|
||||
_fill_required_options(args)
|
||||
|
||||
files_move_from = []
|
||||
files_move_to = []
|
||||
if input_path.is_dir():
|
||||
files = sorted(video_files(input_path, args.recursive), key=natural_sort_key)
|
||||
if not files:
|
||||
parser.error(f"No supported media files found in {input_path}")
|
||||
else:
|
||||
files = [input_path]
|
||||
|
||||
overall_success = True
|
||||
for counter, media_file in enumerate(files):
|
||||
args.input = media_file
|
||||
args.file_counter = counter
|
||||
if args.overwrite:
|
||||
args.output = media_file.with_name(
|
||||
f"{media_file.stem}_overwrite{media_file.suffix}"
|
||||
)
|
||||
elif input_path.is_dir():
|
||||
args.output = media_file.with_name(
|
||||
f"{media_file.stem}_{args.command}{media_file.suffix}"
|
||||
)
|
||||
if args.command in {"convert-av", "convert-av-all"} and args.new_suffix:
|
||||
output_path = args.output.with_suffix(args.new_suffix)
|
||||
elif args.command == "extract-audio":
|
||||
output_path = args.output.with_suffix(".mp3")
|
||||
else:
|
||||
output_path = args.output
|
||||
|
||||
logger.info("Processing %s", media_file)
|
||||
succeeded, _ = args.func(args)
|
||||
if args.overwrite and succeeded and not args.dry_run:
|
||||
files_move_from.append(output_path)
|
||||
files_move_to.append(media_file)
|
||||
|
||||
if args.overwrite and not args.dry_run:
|
||||
overall_success = move_overwrite_file(
|
||||
files_move_from, files_move_to, args
|
||||
) and overall_success
|
||||
return 0 if overall_success else 1
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
parser = build_parser()
|
||||
args = parser.parse_args(argv)
|
||||
setup_logging(args.log_level, "ffmpeg_handling")
|
||||
if shutil.which("ffmpeg") is None:
|
||||
logger.error("FFmpeg is not installed or not available on PATH")
|
||||
return 1
|
||||
try:
|
||||
return _process_input(args, parser)
|
||||
except (OSError, ValueError, subprocess.CalledProcessError) as error:
|
||||
logger.error("%s", error)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,313 @@
|
||||
"""Shared process, media-probing, and file helpers."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from serverlibrary import (
|
||||
AUDIO_SUFFIXES,
|
||||
VIDEO_SUFFIXES,
|
||||
CustomLogger,
|
||||
get_audio_tracks,
|
||||
get_subtitle_tracks,
|
||||
safe_rename,
|
||||
)
|
||||
|
||||
logging.setLoggerClass(CustomLogger)
|
||||
logger: CustomLogger = logging.getLogger("ffmpeg_handling") # type: ignore[assignment]
|
||||
|
||||
AUDIO_TRANSLATIONS = {
|
||||
"Закадровый": "Voice-over",
|
||||
"Закадровое озвучивание": "Voice-over",
|
||||
"закадровый": "Voice-over",
|
||||
"Многоголосый закадровый": "Voice-over",
|
||||
"Многоголосное закадровое озвучивание": "Voice-over",
|
||||
"Многоголосное озвучивание": "Voice-over",
|
||||
"Многоголосый": "Voice-over",
|
||||
"Одноголосый": "Voice-over",
|
||||
"Двухголосый": "Voice-over",
|
||||
"Авторский": "Voice-over",
|
||||
"Любительский": "Voice-over",
|
||||
"Профессиональный": "Professional",
|
||||
"Оригинал": "Original",
|
||||
"Дубляж": "Dubbed",
|
||||
"русск": "Russian",
|
||||
"Английски": "English",
|
||||
"български": "Bulgarian",
|
||||
"Български": "Bulgarian",
|
||||
"Українська": "Ukrainian",
|
||||
"українська": "Ukrainian",
|
||||
"Македонски": "Macedonian",
|
||||
"Српски": "Serbian",
|
||||
"Немецкая": "German",
|
||||
"Немецкое": "German",
|
||||
"немецкие": "German",
|
||||
"Английская": "English",
|
||||
"Английское": "English",
|
||||
"Французская": "French",
|
||||
"Французское": "French",
|
||||
"Кубик в кубе": "Kubik v Kube",
|
||||
"Синема УС": "Cinema US",
|
||||
"Озвучка Rumble": "Rumble",
|
||||
"LostFilm": "LostFilm",
|
||||
"AlexFilm": "AlexFilm",
|
||||
"Baibako": "Baibako",
|
||||
"NewStudio": "NewStudio",
|
||||
"Jaskier": "Jaskier",
|
||||
"Kerob": "Kerob",
|
||||
"TVShows": "TVShows",
|
||||
"HDRezka": "HDRezka",
|
||||
"KinoPub": "KinoPub",
|
||||
"Rumble": "Rumble",
|
||||
"супербит": "Superbit",
|
||||
"Видеосервис": "Videoservice",
|
||||
"Семён Гальцев": "Semyon Galtsev",
|
||||
"Юрий Сербин": "Yuriy Serbin",
|
||||
"Ю. Сербин": "Y. Serbin",
|
||||
"П.Либергал": "P. Libergal",
|
||||
"Визгунов": "Vizgunov",
|
||||
"субтитры": "Russian Subtitles",
|
||||
"Оригинален език": "Original language",
|
||||
"rus": "Russian",
|
||||
"ru": "Russian",
|
||||
}
|
||||
_IGNORED_RUSSIAN_WORDS = {"English", "German", "French"}
|
||||
_RUSSIAN_RE = re.compile(
|
||||
"|".join(
|
||||
re.escape(key)
|
||||
for key in sorted(
|
||||
(key for key, value in AUDIO_TRANSLATIONS.items()
|
||||
if value not in _IGNORED_RUSSIAN_WORDS),
|
||||
key=len,
|
||||
reverse=True,
|
||||
)
|
||||
),
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_CYRILLIC_RE = re.compile(r"[А-Яа-яЁё]")
|
||||
_TIME_RE = re.compile(
|
||||
r"(?:(?P<h>\d+)h)?(?:(?P<m>\d+)m)?(?:(?P<s>\d+)s)?"
|
||||
)
|
||||
|
||||
|
||||
def probe_media(file_path: str | Path, *, entries: str | None = None) -> dict:
|
||||
"""Return ffprobe JSON for a media file."""
|
||||
command = [
|
||||
"ffprobe",
|
||||
"-v",
|
||||
"error",
|
||||
"-print_format",
|
||||
"json",
|
||||
]
|
||||
if entries:
|
||||
command.extend(["-show_entries", entries])
|
||||
else:
|
||||
command.extend(["-show_format", "-show_streams", "-show_chapters"])
|
||||
command.append(str(file_path))
|
||||
result = subprocess.run(command, capture_output=True, text=True, check=True)
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def run_ffmpeg(
|
||||
command: list[str], *, dry_run: bool = False, loud: bool = False
|
||||
) -> bool:
|
||||
"""Run an ffmpeg command, raising an error with captured diagnostics on failure."""
|
||||
if dry_run:
|
||||
logger.debug("Dry run: %s", subprocess.list2cmdline(command))
|
||||
return True
|
||||
|
||||
result = subprocess.run(
|
||||
command,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
check=False,
|
||||
)
|
||||
if result.returncode:
|
||||
logger.error("FFmpeg failed with exit code %s", result.returncode)
|
||||
if result.stderr:
|
||||
logger.error("%s", result.stderr.strip())
|
||||
raise subprocess.CalledProcessError(
|
||||
result.returncode, command, output=result.stdout, stderr=result.stderr
|
||||
)
|
||||
if loud and result.stderr:
|
||||
logger.info("%s", result.stderr.strip())
|
||||
elif result.stderr:
|
||||
logger.debug("%s", result.stderr.strip())
|
||||
return True
|
||||
|
||||
|
||||
def run_ffmpeg_for_args(args, command: list[str]) -> tuple[bool, str]:
|
||||
run_ffmpeg(command, dry_run=args.dry_run, loud=args.loud)
|
||||
return True, "nooutputneeded"
|
||||
|
||||
|
||||
def parse_time_to_seconds(value: str | float | None) -> float | None:
|
||||
"""Parse seconds, compact h/m/s notation, or mm:ss/hh:mm:ss."""
|
||||
if value is None:
|
||||
return None
|
||||
value = str(value).strip()
|
||||
if not value:
|
||||
raise argparse.ArgumentTypeError("Time value cannot be empty")
|
||||
|
||||
match = _TIME_RE.fullmatch(value)
|
||||
if match and any(match.groups()):
|
||||
return (
|
||||
int(match.group("h") or 0) * 3600
|
||||
+ int(match.group("m") or 0) * 60
|
||||
+ int(match.group("s") or 0)
|
||||
)
|
||||
if ":" in value:
|
||||
parts = value.split(":")
|
||||
if len(parts) in (2, 3) and all(part.isdigit() for part in parts):
|
||||
values = [int(part) for part in parts]
|
||||
if len(values) == 2:
|
||||
minutes, seconds = values
|
||||
return float(minutes * 60 + seconds)
|
||||
hours, minutes, seconds = values
|
||||
return float(hours * 3600 + minutes * 60 + seconds)
|
||||
try:
|
||||
return float(value)
|
||||
except ValueError as error:
|
||||
raise argparse.ArgumentTypeError(f"Invalid time format: {value}") from error
|
||||
|
||||
|
||||
def get_scodec(output_path: str | Path) -> str:
|
||||
return "mov_text" if Path(output_path).suffix.lower() == ".mp4" else "copy"
|
||||
|
||||
|
||||
def get_vcodec(output_path: str | Path) -> str:
|
||||
return "libx264" if Path(output_path).suffix.lower() == ".mp4" else "copy"
|
||||
|
||||
|
||||
def natural_sort_key(path: Path) -> list[int | str]:
|
||||
return [
|
||||
int(part) if part.isdigit() else part.lower()
|
||||
for part in re.split(r"(\d+)", path.name)
|
||||
]
|
||||
|
||||
|
||||
def video_files(path: Path, recursive: bool):
|
||||
iterator = path.rglob("*") if recursive else path.iterdir()
|
||||
yield from (
|
||||
file for file in iterator
|
||||
if file.is_file() and file.suffix.lower() in VIDEO_SUFFIXES | AUDIO_SUFFIXES
|
||||
)
|
||||
|
||||
|
||||
def is_russian_track(track: dict) -> bool:
|
||||
return any(
|
||||
_RUSSIAN_RE.search(str(track.get(key, "")))
|
||||
for key in ("description", "language", "lang")
|
||||
)
|
||||
|
||||
|
||||
def translate_audio_tracks(tracks: list[dict]) -> list[dict]:
|
||||
translated = []
|
||||
for track in tracks:
|
||||
new_track = track.copy()
|
||||
for key, value in new_track.items():
|
||||
if not isinstance(value, str):
|
||||
continue
|
||||
for source, target in AUDIO_TRANSLATIONS.items():
|
||||
value = re.sub(
|
||||
re.escape(source), target, value, count=1, flags=re.IGNORECASE
|
||||
)
|
||||
if _CYRILLIC_RE.search(value):
|
||||
raise ValueError(
|
||||
f"Track contains unidentified Cyrillic characters in {key}: {value}"
|
||||
)
|
||||
new_track[key] = value
|
||||
translated.append(new_track)
|
||||
return translated
|
||||
|
||||
|
||||
def select_audio_stream(file_path: str | Path, provided: int | None = None) -> int:
|
||||
streams = [
|
||||
stream for stream in probe_media(file_path).get("streams", [])
|
||||
if stream.get("codec_type") == "audio"
|
||||
]
|
||||
if not streams:
|
||||
raise ValueError(f"No audio streams found in {file_path}")
|
||||
if provided is not None:
|
||||
selected = next(
|
||||
(stream for stream in streams if stream["index"] == int(provided)), None
|
||||
)
|
||||
if selected is None:
|
||||
raise ValueError(f"Audio stream index {provided} is not present")
|
||||
return int(selected["index"])
|
||||
if len(streams) == 1:
|
||||
return int(streams[0]["index"])
|
||||
|
||||
logger.info("Found audio streams:")
|
||||
for index, stream in enumerate(streams):
|
||||
language = stream.get("tags", {}).get("language", "unknown")
|
||||
logger.info("[%s] Index: %s, Language: %s", index, stream["index"], language)
|
||||
try:
|
||||
choice = int(input("Select stream number (the list index [x]): "))
|
||||
return int(streams[choice]["index"])
|
||||
except (ValueError, IndexError) as error:
|
||||
raise ValueError("Invalid audio stream selection") from error
|
||||
|
||||
|
||||
def get_chapter_lengths(file_path: str | Path) -> list[dict[str, float]]:
|
||||
info = probe_media(file_path, entries="chapter=start_time,end_time")
|
||||
return [
|
||||
{"start": float(chapter["start_time"]), "end": float(chapter["end_time"])}
|
||||
for chapter in info.get("chapters", [])
|
||||
]
|
||||
|
||||
|
||||
def ask(prompt: str, default="") -> str:
|
||||
value = input(f"{prompt}" + (f" [{default}]" if default else "") + ": ").strip()
|
||||
return value if value else default
|
||||
|
||||
|
||||
def ensure(value, prompt: str) -> str:
|
||||
return ask(prompt) if value is None else value
|
||||
|
||||
|
||||
def move_overwrite_file(files_move_from, files_move_to, args) -> bool:
|
||||
for source, target in zip(files_move_from, files_move_to):
|
||||
if not source.is_file():
|
||||
logger.error("Overwrite output does not exist: %s", source)
|
||||
return False
|
||||
backup = target.parent / f"{target.stem}_backup{target.suffix}"
|
||||
if args.backup and target.exists():
|
||||
target.replace(backup)
|
||||
_, renamed = safe_rename(
|
||||
source, target, silent=not args.loud, overwrite=True
|
||||
)
|
||||
if not renamed:
|
||||
logger.error("Could not move %s to %s", source, target)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AUDIO_SUFFIXES",
|
||||
"VIDEO_SUFFIXES",
|
||||
"ask",
|
||||
"ensure",
|
||||
"get_audio_tracks",
|
||||
"get_chapter_lengths",
|
||||
"get_scodec",
|
||||
"get_subtitle_tracks",
|
||||
"get_vcodec",
|
||||
"is_russian_track",
|
||||
"logger",
|
||||
"move_overwrite_file",
|
||||
"natural_sort_key",
|
||||
"parse_time_to_seconds",
|
||||
"probe_media",
|
||||
"run_ffmpeg",
|
||||
"run_ffmpeg_for_args",
|
||||
"safe_rename",
|
||||
"select_audio_stream",
|
||||
"translate_audio_tracks",
|
||||
"video_files",
|
||||
]
|
||||
@@ -0,0 +1,163 @@
|
||||
"""Metadata and chapter commands."""
|
||||
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from .helpers import (
|
||||
get_chapter_lengths,
|
||||
logger,
|
||||
probe_media,
|
||||
run_ffmpeg_for_args,
|
||||
safe_rename,
|
||||
)
|
||||
|
||||
|
||||
def cmd_show_metadata(args, show_metadata=True, return_tags=None):
|
||||
tags = probe_media(args.input).get("format", {}).get("tags", {})
|
||||
if return_tags is not None:
|
||||
return_tags.clear()
|
||||
return_tags.update(tags)
|
||||
if show_metadata:
|
||||
for key, value in tags.items():
|
||||
logger.info("%s: %s", key, value)
|
||||
return False, "nooutputneeded"
|
||||
|
||||
|
||||
def cmd_set_metadata(args):
|
||||
if args.input.suffix.lower() == ".opus" or args.kidflag:
|
||||
command = ["kid3-cli", "-c", f"set {args.key} {args.value}", str(args.input)]
|
||||
if args.dry_run:
|
||||
logger.debug("Dry run: %s", command)
|
||||
return True, "nooutputneeded"
|
||||
subprocess.run(command, capture_output=True, text=True, check=True)
|
||||
return False, "nooutputneeded"
|
||||
command = [
|
||||
"ffmpeg",
|
||||
"-y",
|
||||
"-i",
|
||||
str(args.input),
|
||||
"-map",
|
||||
"0:v?",
|
||||
"-map",
|
||||
"0:a?",
|
||||
"-map",
|
||||
"0:s?",
|
||||
"-map_metadata",
|
||||
"0",
|
||||
"-c",
|
||||
"copy",
|
||||
"-metadata",
|
||||
f"{args.key}={args.value}",
|
||||
str(args.output),
|
||||
]
|
||||
return run_ffmpeg_for_args(args, command)
|
||||
|
||||
|
||||
def _escape_ffmetadata(value: str) -> str:
|
||||
for char in ("\\", "=", ";", "#"):
|
||||
value = value.replace(char, f"\\{char}")
|
||||
return value
|
||||
|
||||
|
||||
def cmd_apply_chapters(args):
|
||||
titles = [
|
||||
line.strip()
|
||||
for line in Path(args.chapter_file).read_text(encoding="utf-8").splitlines()
|
||||
if line.strip()
|
||||
]
|
||||
if not titles:
|
||||
raise ValueError("Chapter file is empty")
|
||||
|
||||
if args.input.suffix.lower() == ".m4b":
|
||||
chapters = get_chapter_lengths(args.input)
|
||||
if len(chapters) != len(titles):
|
||||
raise ValueError(
|
||||
f"Chapter count mismatch: {len(chapters)} chapters, {len(titles)} titles"
|
||||
)
|
||||
metadata = [";FFMETADATA1", ""]
|
||||
for chapter, title in zip(chapters, titles):
|
||||
metadata.extend(
|
||||
[
|
||||
"[CHAPTER]",
|
||||
"TIMEBASE=1/1000",
|
||||
f"START={int(chapter['start'] * 1000)}",
|
||||
f"END={int(chapter['end'] * 1000)}",
|
||||
f"title={_escape_ffmetadata(title)}",
|
||||
"",
|
||||
]
|
||||
)
|
||||
if args.dry_run:
|
||||
logger.debug("Dry run: would write chapter metadata to %s", args.output)
|
||||
return True, "nooutputneeded"
|
||||
temporary_path = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(
|
||||
"w", encoding="utf-8", suffix=".txt", delete=False
|
||||
) as metadata_file:
|
||||
metadata_file.write("\n".join(metadata))
|
||||
temporary_path = Path(metadata_file.name)
|
||||
command = [
|
||||
"ffmpeg",
|
||||
"-y",
|
||||
"-i",
|
||||
str(args.input),
|
||||
"-f",
|
||||
"ffmetadata",
|
||||
"-i",
|
||||
str(temporary_path),
|
||||
"-map",
|
||||
"0:v?",
|
||||
"-map",
|
||||
"0:a?",
|
||||
"-map",
|
||||
"0:s?",
|
||||
"-map_chapters",
|
||||
"1",
|
||||
"-map_metadata",
|
||||
"0",
|
||||
"-c",
|
||||
"copy",
|
||||
str(args.output),
|
||||
]
|
||||
return run_ffmpeg_for_args(args, command)
|
||||
finally:
|
||||
if temporary_path is not None:
|
||||
temporary_path.unlink(missing_ok=True)
|
||||
|
||||
if args.input.suffix.lower() == ".mp3":
|
||||
counter = getattr(args, "file_counter", 0)
|
||||
if counter >= len(titles):
|
||||
raise ValueError(f"No chapter title available for track {counter + 1}")
|
||||
title = titles[counter]
|
||||
safe_title = title.replace("/", "-").replace(":", "-")
|
||||
new_name = f"{counter + 1:03d} - {safe_title}.mp3"
|
||||
new_path = args.input.with_name(new_name)
|
||||
if args.dry_run:
|
||||
logger.debug(
|
||||
"Dry run: would update and rename %s to %s", args.input, new_path
|
||||
)
|
||||
return True, "nooutputneeded"
|
||||
temporary_path = args.input.with_name(f".{args.input.stem}.metadata.mp3")
|
||||
try:
|
||||
command = [
|
||||
"ffmpeg",
|
||||
"-y",
|
||||
"-i",
|
||||
str(args.input),
|
||||
"-map",
|
||||
"0",
|
||||
"-c",
|
||||
"copy",
|
||||
"-metadata",
|
||||
f"title={title}",
|
||||
"-metadata",
|
||||
f"track={counter + 1}",
|
||||
str(temporary_path),
|
||||
]
|
||||
run_ffmpeg_for_args(args, command)
|
||||
temporary_path.replace(args.input)
|
||||
safe_rename(args.input, new_path, overwrite=True)
|
||||
finally:
|
||||
temporary_path.unlink(missing_ok=True)
|
||||
return True, "nooutputneeded"
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
#!/home/lucas/scripts/ffmpeg_handling/.venv/bin/python
|
||||
# """Discover and run the ffmpeg_handling unittest suite."""
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
PROJECT_DIR = Path(__file__).resolve().parents[2]
|
||||
TEST_DIR = PROJECT_DIR / "tests"
|
||||
sys.path.insert(0, str(PROJECT_DIR))
|
||||
|
||||
|
||||
def run_tests(verbosity: int = 2) -> bool:
|
||||
suite = unittest.defaultTestLoader.discover(
|
||||
str(TEST_DIR), pattern="test_*.py", top_level_dir=str(PROJECT_DIR)
|
||||
)
|
||||
result = unittest.TextTestRunner(verbosity=verbosity).run(suite)
|
||||
return result.wasSuccessful()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(0 if run_tests() else 1)
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Video-focused media commands."""
|
||||
|
||||
import json
|
||||
|
||||
from .helpers import (
|
||||
get_scodec,
|
||||
get_vcodec,
|
||||
logger,
|
||||
parse_time_to_seconds,
|
||||
probe_media,
|
||||
run_ffmpeg_for_args,
|
||||
)
|
||||
|
||||
|
||||
def cmd_info(args):
|
||||
logger.info("%s", json.dumps(probe_media(args.input), indent=2))
|
||||
return False, "nooutputneeded"
|
||||
|
||||
|
||||
def cmd_convert_av(args):
|
||||
output = args.output.with_suffix(args.new_suffix) if args.new_suffix else args.output
|
||||
command = [
|
||||
"ffmpeg", "-y", "-i", str(args.input),
|
||||
"-map", "0", "-map_metadata", "0",
|
||||
"-c:v", args.video_codec, "-c:a", args.audio_codec,
|
||||
"-c:s", get_scodec(output), "-preset", args.preset,
|
||||
"-qp", str(args.quality), str(output),
|
||||
]
|
||||
return run_ffmpeg_for_args(args, command)
|
||||
|
||||
|
||||
def cmd_convert_av_all_suffix(args):
|
||||
if args.input.suffix.lower() != args.suffix.lower():
|
||||
return False, "nooutputneeded"
|
||||
return cmd_convert_av(args)
|
||||
|
||||
|
||||
def cmd_convert_audio(args):
|
||||
command = [
|
||||
"ffmpeg", "-y", "-i", str(args.input), "-map", "0",
|
||||
"-map_metadata", "0", "-c:v", "copy", "-c:a", args.audio_codec,
|
||||
"-c:s", get_scodec(args.output), str(args.output),
|
||||
]
|
||||
return run_ffmpeg_for_args(args, command)
|
||||
|
||||
|
||||
def cmd_convert_video(args):
|
||||
command = [
|
||||
"ffmpeg", "-y", "-i", str(args.input), "-map", "0",
|
||||
"-map_metadata", "0", "-c:v", args.video_codec, "-c:a", "copy",
|
||||
"-c:s", get_scodec(args.output), str(args.output),
|
||||
]
|
||||
return run_ffmpeg_for_args(args, command)
|
||||
|
||||
|
||||
def cmd_downsize(args):
|
||||
command = [
|
||||
"ffmpeg", "-y", "-i", str(args.input),
|
||||
"-map", "0:v:0", "-map", "0:a?", "-map", "0:s?",
|
||||
"-vf", f"scale={args.width}:{args.height}",
|
||||
"-c:v", "libx264", "-crf", str(args.crf),
|
||||
"-c:a", "copy", "-c:s", get_scodec(args.output),
|
||||
str(args.output),
|
||||
]
|
||||
return run_ffmpeg_for_args(args, command)
|
||||
|
||||
|
||||
def cmd_cut_segment(args):
|
||||
start = parse_time_to_seconds(args.start)
|
||||
duration = parse_time_to_seconds(args.duration)
|
||||
command = ["ffmpeg", "-y", "-ss", str(start), "-i", str(args.input)]
|
||||
if duration is not None:
|
||||
command.extend(["-t", str(duration)])
|
||||
command.extend([
|
||||
"-map", "0", "-c:v", get_vcodec(args.output),
|
||||
"-c:a", "copy", "-c:s", get_scodec(args.output), str(args.output),
|
||||
])
|
||||
return run_ffmpeg_for_args(args, command)
|
||||
|
||||
|
||||
def cmd_remove_subs(args):
|
||||
streams = probe_media(args.input).get("streams", [])
|
||||
remove_indices = (
|
||||
set(args.num)
|
||||
if getattr(args, "num", None) is not None
|
||||
else {
|
||||
stream["index"] for stream in streams
|
||||
if stream.get("codec_type") == "subtitle"
|
||||
}
|
||||
)
|
||||
return remove_streams(args, remove_indices)
|
||||
|
||||
|
||||
def remove_streams(args, remove_indices: set[int], *, output_subtitle_codec=False):
|
||||
streams = probe_media(args.input).get("streams", [])
|
||||
remaining_audio = [
|
||||
stream for stream in streams
|
||||
if stream.get("codec_type") == "audio"
|
||||
and stream["index"] not in remove_indices
|
||||
]
|
||||
removing_audio = any(
|
||||
stream.get("codec_type") == "audio" and stream["index"] in remove_indices
|
||||
for stream in streams
|
||||
)
|
||||
if removing_audio and not remaining_audio:
|
||||
logger.warning("No audio tracks would remain; refusing to remove them all")
|
||||
return False, "nooutputneeded"
|
||||
|
||||
command = ["ffmpeg", "-y", "-i", str(args.input)]
|
||||
for stream in streams:
|
||||
if stream["index"] not in remove_indices:
|
||||
command.extend(["-map", f"0:{stream['index']}"])
|
||||
command.extend(["-c", "copy", "-map_metadata", "0"])
|
||||
command.extend([
|
||||
"-c:s", get_scodec(args.output) if output_subtitle_codec else "copy",
|
||||
str(args.output),
|
||||
])
|
||||
return run_ffmpeg_for_args(args, command)
|
||||
@@ -0,0 +1 @@
|
||||
"""Tests for the ffmpeg_handling command-line tool."""
|
||||
@@ -0,0 +1,60 @@
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from ffmpeg_handling import build_parser, main
|
||||
|
||||
ASSET_DIR = Path(__file__).resolve().parents[1] / "testfiles"
|
||||
|
||||
|
||||
class CliTests(unittest.TestCase):
|
||||
def test_test_command_is_not_registered(self):
|
||||
with self.assertRaises(SystemExit) as error:
|
||||
build_parser().parse_args(["test"])
|
||||
self.assertEqual(error.exception.code, 2)
|
||||
|
||||
def test_short_command_alias_resolves_to_canonical_name(self):
|
||||
args = build_parser().parse_args(["i", str(ASSET_DIR / "test_auto.mp4")])
|
||||
self.assertEqual(args.command, "info")
|
||||
|
||||
def test_missing_ffmpeg_logs_error_and_returns_failure(self):
|
||||
with patch("ffmpeg_handling.cli.shutil.which", return_value=None), \
|
||||
patch("ffmpeg_handling.cli.setup_logging"), \
|
||||
self.assertLogs("ffmpeg_handling", level="ERROR") as captured:
|
||||
result = main(["info", str(ASSET_DIR / "test_auto_no_subs.mkv")])
|
||||
|
||||
self.assertEqual(result, 1)
|
||||
self.assertIn("FFmpeg is not installed", captured.output[0])
|
||||
|
||||
def test_non_output_command_returns_success(self):
|
||||
with patch("ffmpeg_handling.cli.setup_logging"), \
|
||||
self.assertLogs("ffmpeg_handling", level="INFO"):
|
||||
self.assertEqual(
|
||||
main(["info", str(ASSET_DIR / "test_auto_no_subs.mkv")]), 0
|
||||
)
|
||||
|
||||
def test_cli_dry_run_uses_requested_output_and_creates_nothing(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
output = Path(temp_dir) / "dry_run.mkv"
|
||||
with patch("ffmpeg_handling.cli.setup_logging"), \
|
||||
self.assertLogs("ffmpeg_handling", level="INFO"):
|
||||
result = main([
|
||||
"downsize",
|
||||
str(ASSET_DIR / "test_auto_no_subs.mkv"),
|
||||
"-o",
|
||||
str(output),
|
||||
"--dry-run",
|
||||
"-w",
|
||||
"320",
|
||||
"-he",
|
||||
"180",
|
||||
"-c",
|
||||
"30",
|
||||
])
|
||||
self.assertEqual(result, 0)
|
||||
self.assertFalse(output.exists())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,122 @@
|
||||
import argparse
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from ffmpeg_handling.helpers import (
|
||||
get_scodec,
|
||||
get_vcodec,
|
||||
is_russian_track,
|
||||
move_overwrite_file,
|
||||
natural_sort_key,
|
||||
parse_time_to_seconds,
|
||||
run_ffmpeg,
|
||||
translate_audio_tracks,
|
||||
video_files,
|
||||
)
|
||||
|
||||
|
||||
class TimeParsingTests(unittest.TestCase):
|
||||
def test_seconds_and_compact_time_formats(self):
|
||||
cases = {
|
||||
"100s": 100,
|
||||
"1m20s": 80,
|
||||
"2h10m5s": 7805,
|
||||
"0:1:5": 65,
|
||||
"01:20": 80,
|
||||
"12.5": 12.5,
|
||||
}
|
||||
for value, expected in cases.items():
|
||||
with self.subTest(value=value):
|
||||
self.assertEqual(parse_time_to_seconds(value), expected)
|
||||
|
||||
def test_invalid_time_is_rejected(self):
|
||||
for value in ("", "abc", "1x", "1:2:3:4"):
|
||||
with self.subTest(value=value), self.assertRaises(
|
||||
argparse.ArgumentTypeError
|
||||
):
|
||||
parse_time_to_seconds(value)
|
||||
|
||||
def test_none_is_preserved(self):
|
||||
self.assertIsNone(parse_time_to_seconds(None))
|
||||
|
||||
|
||||
class MediaHelperTests(unittest.TestCase):
|
||||
def test_codec_selection_is_case_insensitive(self):
|
||||
self.assertEqual(get_scodec(Path("movie.MP4")), "mov_text")
|
||||
self.assertEqual(get_scodec(Path("movie.mkv")), "copy")
|
||||
self.assertEqual(get_vcodec(Path("movie.MP4")), "libx264")
|
||||
self.assertEqual(get_vcodec(Path("movie.mkv")), "copy")
|
||||
|
||||
def test_natural_sort_orders_numeric_segments(self):
|
||||
files = [Path("part10.mkv"), Path("part2.mkv"), Path("part1.mkv")]
|
||||
self.assertEqual(
|
||||
sorted(files, key=natural_sort_key),
|
||||
[Path("part1.mkv"), Path("part2.mkv"), Path("part10.mkv")],
|
||||
)
|
||||
|
||||
def test_russian_detection_and_translation(self):
|
||||
self.assertTrue(is_russian_track({"language": "rus"}))
|
||||
self.assertFalse(is_russian_track({"language": "eng"}))
|
||||
translated = translate_audio_tracks(
|
||||
[{"description": "Дубляж (AlexFilm)", "number": 1}]
|
||||
)
|
||||
self.assertEqual(translated[0]["description"], "Dubbed (AlexFilm)")
|
||||
|
||||
def test_unknown_cyrillic_translation_is_reported(self):
|
||||
with self.assertRaisesRegex(ValueError, "unidentified Cyrillic"):
|
||||
translate_audio_tracks([{"description": "Неизвестный перевод"}])
|
||||
|
||||
def test_video_files_filters_supported_extensions_and_recurses_on_request(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
root = Path(temp_dir)
|
||||
nested = root / "nested"
|
||||
nested.mkdir()
|
||||
(root / "video.mkv").touch()
|
||||
(root / "audio.mp3").touch()
|
||||
(root / "readme.txt").touch()
|
||||
(nested / "nested.mp4").touch()
|
||||
self.assertEqual(
|
||||
{path.name for path in video_files(root, recursive=False)},
|
||||
{"video.mkv", "audio.mp3"},
|
||||
)
|
||||
self.assertEqual(
|
||||
{path.name for path in video_files(root, recursive=True)},
|
||||
{"video.mkv", "audio.mp3", "nested.mp4"},
|
||||
)
|
||||
|
||||
def test_overwrite_moves_old_content_to_backup(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
target = Path(temp_dir) / "media.mkv"
|
||||
output = Path(temp_dir) / "media_overwrite.mkv"
|
||||
target.write_text("original", encoding="utf-8")
|
||||
output.write_text("converted", encoding="utf-8")
|
||||
args = SimpleNamespace(backup=True, loud=False)
|
||||
self.assertTrue(move_overwrite_file([output], [target], args))
|
||||
self.assertEqual(target.read_text(encoding="utf-8"), "converted")
|
||||
backup = Path(temp_dir) / "media_backup.mkv"
|
||||
self.assertEqual(backup.read_text(encoding="utf-8"), "original")
|
||||
|
||||
|
||||
class FfmpegRunnerTests(unittest.TestCase):
|
||||
@patch("ffmpeg_handling.helpers.subprocess.run")
|
||||
def test_dry_run_does_not_start_a_process(self, run):
|
||||
self.assertTrue(run_ffmpeg(["ffmpeg", "-version"], dry_run=True))
|
||||
run.assert_not_called()
|
||||
|
||||
@patch("ffmpeg_handling.helpers.subprocess.run")
|
||||
def test_process_failure_keeps_stderr_and_exit_code(self, run):
|
||||
run.return_value.returncode = 2
|
||||
run.return_value.stdout = ""
|
||||
run.return_value.stderr = "encoder failed"
|
||||
with self.assertRaises(subprocess.CalledProcessError) as error:
|
||||
run_ffmpeg(["ffmpeg", "-i", "bad.mkv"])
|
||||
self.assertEqual(error.exception.returncode, 2)
|
||||
self.assertIn("encoder failed", error.exception.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,315 @@
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from ffmpeg_handling.audio_commands import (
|
||||
cmd_extract_audio_track,
|
||||
cmd_filter_audio,
|
||||
cmd_remove_audio_track,
|
||||
cmd_remove_russian_from_db,
|
||||
cmd_set_primary_audio,
|
||||
)
|
||||
from ffmpeg_handling.helpers import probe_media
|
||||
from ffmpeg_handling.metadata_commands import cmd_apply_chapters, cmd_set_metadata
|
||||
from ffmpeg_handling.video_commands import (
|
||||
cmd_convert_audio,
|
||||
cmd_convert_av,
|
||||
cmd_convert_av_all_suffix,
|
||||
cmd_convert_video,
|
||||
cmd_cut_segment,
|
||||
cmd_downsize,
|
||||
cmd_info,
|
||||
cmd_remove_subs,
|
||||
)
|
||||
|
||||
ASSET_DIR = Path(__file__).resolve().parents[1] / "testfiles"
|
||||
|
||||
|
||||
def command_args(input_path: Path, output_path: Path, **values):
|
||||
defaults = {
|
||||
"input": input_path,
|
||||
"output": output_path,
|
||||
"dry_run": False,
|
||||
"loud": False,
|
||||
"audio_index": [],
|
||||
"kidflag": False,
|
||||
"backup": False,
|
||||
}
|
||||
defaults.update(values)
|
||||
return SimpleNamespace(**defaults)
|
||||
|
||||
|
||||
class MediaCommandIntegrationTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp_dir = tempfile.TemporaryDirectory(prefix="ffmpeg_handling_test_")
|
||||
self.output_dir = Path(self.temp_dir.name)
|
||||
|
||||
def tearDown(self):
|
||||
self.temp_dir.cleanup()
|
||||
|
||||
def output(self, name):
|
||||
return self.output_dir / name
|
||||
|
||||
def assert_stream_counts(self, path, *, audio=None, subtitles=None, video=None):
|
||||
streams = probe_media(path).get("streams", [])
|
||||
counts = {
|
||||
kind: sum(stream.get("codec_type") == kind for stream in streams)
|
||||
for kind in ("video", "audio", "subtitle")
|
||||
}
|
||||
if audio is not None:
|
||||
self.assertEqual(counts["audio"], audio)
|
||||
if subtitles is not None:
|
||||
self.assertEqual(counts["subtitle"], subtitles)
|
||||
if video is not None:
|
||||
self.assertEqual(counts["video"], video)
|
||||
|
||||
def test_info_and_all_supported_fixture_assets_probe(self):
|
||||
fixtures = sorted(
|
||||
path for path in ASSET_DIR.glob("test_auto*")
|
||||
if path.suffix.lower() in {".avi", ".m4b", ".mkv", ".mp4"}
|
||||
)
|
||||
self.assertGreaterEqual(len(fixtures), 7)
|
||||
for fixture in fixtures:
|
||||
with self.subTest(fixture=fixture.name):
|
||||
self.assertTrue(probe_media(fixture).get("streams"))
|
||||
self.assertEqual(
|
||||
cmd_info(command_args(ASSET_DIR / "test_auto.mp4", self.output("unused"))),
|
||||
(False, "nooutputneeded"),
|
||||
)
|
||||
|
||||
def test_remove_subtitles_and_audio_preserves_other_streams(self):
|
||||
source = ASSET_DIR / "test_auto.mkv"
|
||||
no_subtitles = self.output("no_subtitles.mkv")
|
||||
self.assertTrue(cmd_remove_subs(command_args(source, no_subtitles))[0])
|
||||
self.assert_stream_counts(no_subtitles, audio=2, subtitles=0)
|
||||
|
||||
source_without_subtitles = ASSET_DIR / "test_auto_no_subs.mkv"
|
||||
copied_without_subtitles = self.output("still_no_subtitles.mkv")
|
||||
self.assertTrue(
|
||||
cmd_remove_subs(
|
||||
command_args(source_without_subtitles, copied_without_subtitles)
|
||||
)[0]
|
||||
)
|
||||
self.assert_stream_counts(copied_without_subtitles, audio=2, subtitles=0)
|
||||
|
||||
one_subtitle_removed = self.output("one_subtitle_removed.mkv")
|
||||
args = command_args(source, one_subtitle_removed, num=[3])
|
||||
self.assertTrue(cmd_remove_subs(args)[0])
|
||||
self.assert_stream_counts(one_subtitle_removed, subtitles=2)
|
||||
|
||||
one_audio = self.output("one_audio.mkv")
|
||||
args = command_args(source, one_audio, audio_index=[1])
|
||||
self.assertTrue(cmd_remove_audio_track(args)[0])
|
||||
self.assert_stream_counts(one_audio, audio=1, subtitles=3)
|
||||
|
||||
def test_refusing_to_remove_the_last_audio_and_invalid_index(self):
|
||||
source = ASSET_DIR / "test_auto_only_russian.mkv"
|
||||
args = command_args(source, self.output("empty_audio.mkv"), audio_index=[1])
|
||||
self.assertFalse(cmd_remove_audio_track(args)[0])
|
||||
|
||||
args.audio_index = [99]
|
||||
with self.assertRaisesRegex(ValueError, "not present"):
|
||||
cmd_remove_audio_track(args)
|
||||
|
||||
def test_audio_extraction_and_segment_cut(self):
|
||||
source = ASSET_DIR / "test_auto.mkv"
|
||||
extracted = self.output("extracted.mp3")
|
||||
self.assertTrue(
|
||||
cmd_extract_audio_track(
|
||||
command_args(source, extracted, audio_index=[1])
|
||||
)[0]
|
||||
)
|
||||
self.assertEqual(probe_media(extracted)["streams"][0]["codec_type"], "audio")
|
||||
chapter_titles = self.output("audio_chapters.txt")
|
||||
chapter_titles.write_text("Extracted track\n", encoding="utf-8")
|
||||
chapter_args = command_args(
|
||||
extracted,
|
||||
self.output("renamed.mp3"),
|
||||
chapter_file=chapter_titles,
|
||||
file_counter=0,
|
||||
)
|
||||
self.assertTrue(cmd_apply_chapters(chapter_args)[0])
|
||||
tagged_audio = self.output("001 - Extracted track.mp3")
|
||||
self.assertEqual(
|
||||
probe_media(tagged_audio)["format"]["tags"]["title"], "Extracted track"
|
||||
)
|
||||
multiple_args = command_args(
|
||||
source, self.output("multiple.mp3"), audio_index=[1, 2]
|
||||
)
|
||||
self.assertTrue(cmd_extract_audio_track(multiple_args)[0])
|
||||
for index in (1, 2):
|
||||
output = self.output(f"multiple_stream_{index}.mp3")
|
||||
self.assertTrue(output.is_file())
|
||||
self.assertEqual(
|
||||
probe_media(output)["streams"][0]["codec_type"], "audio"
|
||||
)
|
||||
|
||||
cut = self.output("cut.mkv")
|
||||
args = command_args(source, cut, start="1s", duration="3s")
|
||||
self.assertTrue(cmd_cut_segment(args)[0])
|
||||
self.assertLess(float(probe_media(cut)["format"]["duration"]), 8)
|
||||
self.assertGreater(float(probe_media(cut)["format"]["duration"]), 2)
|
||||
|
||||
def test_audio_video_transcodes_and_downsize(self):
|
||||
source = ASSET_DIR / "test_auto.mkv"
|
||||
audio = self.output("audio_aac.mkv")
|
||||
self.assertTrue(
|
||||
cmd_convert_audio(
|
||||
command_args(source, audio, audio_codec="aac")
|
||||
)[0]
|
||||
)
|
||||
self.assertTrue(
|
||||
all(
|
||||
stream["codec_name"] == "aac"
|
||||
for stream in probe_media(audio)["streams"]
|
||||
if stream.get("codec_type") == "audio"
|
||||
)
|
||||
)
|
||||
|
||||
video = self.output("video_h264.mkv")
|
||||
self.assertTrue(
|
||||
cmd_convert_video(
|
||||
command_args(source, video, video_codec="libx264")
|
||||
)[0]
|
||||
)
|
||||
self.assert_stream_counts(video, audio=2, subtitles=3)
|
||||
self.assertTrue(
|
||||
all(
|
||||
stream["codec_name"] == "h264"
|
||||
for stream in probe_media(video)["streams"]
|
||||
if stream.get("codec_type") == "video"
|
||||
)
|
||||
)
|
||||
|
||||
smaller = self.output("smaller.mkv")
|
||||
args = command_args(source, smaller, width=320, height=180, crf=32)
|
||||
self.assertTrue(cmd_downsize(args)[0])
|
||||
first_video = next(
|
||||
stream for stream in probe_media(smaller)["streams"]
|
||||
if stream.get("codec_type") == "video"
|
||||
)
|
||||
self.assertEqual((first_video["width"], first_video["height"]), (320, 180))
|
||||
|
||||
def test_full_reencode_and_suffix_filter(self):
|
||||
source = ASSET_DIR / "test_auto.mkv"
|
||||
output = self.output("full.mp4")
|
||||
args = command_args(
|
||||
source, output, video_codec="libx264", audio_codec="aac",
|
||||
preset="ultrafast", quality=30, new_suffix=None,
|
||||
)
|
||||
self.assertTrue(cmd_convert_av(args)[0])
|
||||
converted_streams = probe_media(output)["streams"]
|
||||
self.assertTrue(converted_streams)
|
||||
self.assertTrue(
|
||||
all(
|
||||
stream["codec_name"] == "h264"
|
||||
for stream in converted_streams
|
||||
if stream.get("codec_type") == "video"
|
||||
)
|
||||
)
|
||||
self.assertTrue(
|
||||
all(
|
||||
stream["codec_name"] == "aac"
|
||||
for stream in converted_streams
|
||||
if stream.get("codec_type") == "audio"
|
||||
)
|
||||
)
|
||||
|
||||
args.suffix = ".mp4"
|
||||
self.assertFalse(cmd_convert_av_all_suffix(args)[0])
|
||||
args.suffix = ".mkv"
|
||||
args.new_suffix = ".mp4"
|
||||
args.output = self.output("filtered.mkv")
|
||||
self.assertTrue(cmd_convert_av_all_suffix(args)[0])
|
||||
self.assertTrue(self.output("filtered.mp4").is_file())
|
||||
|
||||
def test_audio_filter_and_primary_stream_order(self):
|
||||
source = ASSET_DIR / "test_auto.mkv"
|
||||
filtered = self.output("filtered_audio.mkv")
|
||||
args = command_args(source, filtered, audio_index=[2])
|
||||
self.assertTrue(cmd_filter_audio(args)[0])
|
||||
self.assert_stream_counts(filtered, audio=3)
|
||||
self.assertTrue(
|
||||
all(
|
||||
stream["codec_name"] == "vorbis"
|
||||
for stream in probe_media(filtered)["streams"]
|
||||
if stream.get("codec_type") == "audio"
|
||||
)
|
||||
)
|
||||
|
||||
primary = self.output("primary.mkv")
|
||||
args.output = primary
|
||||
self.assertTrue(cmd_set_primary_audio(args)[0])
|
||||
audio_streams = [
|
||||
stream for stream in probe_media(primary)["streams"]
|
||||
if stream.get("codec_type") == "audio"
|
||||
]
|
||||
self.assertEqual(audio_streams[0].get("tags", {}).get("language"), "ger")
|
||||
self.assertEqual(audio_streams[0].get("disposition", {}).get("default"), 1)
|
||||
|
||||
def test_metadata_and_chapter_operations(self):
|
||||
source = ASSET_DIR / "test_auto.m4b"
|
||||
metadata = self.output("metadata.m4b")
|
||||
args = command_args(
|
||||
source, metadata, key="artist", value="Unit Test", chapter_file=None
|
||||
)
|
||||
self.assertTrue(cmd_set_metadata(args)[0])
|
||||
self.assertEqual(
|
||||
probe_media(metadata)["format"]["tags"]["artist"], "Unit Test"
|
||||
)
|
||||
|
||||
chapter_output = self.output("chapters.m4b")
|
||||
args.output = chapter_output
|
||||
args.chapter_file = ASSET_DIR / "test_auto_chapters.txt"
|
||||
self.assertTrue(cmd_apply_chapters(args)[0])
|
||||
chapter_info = probe_media(chapter_output)
|
||||
expected_titles = [
|
||||
line for line in args.chapter_file.read_text(encoding="utf-8").splitlines()
|
||||
if line
|
||||
]
|
||||
self.assertEqual(
|
||||
[chapter["tags"]["title"] for chapter in chapter_info["chapters"]],
|
||||
expected_titles,
|
||||
)
|
||||
|
||||
def test_chapter_count_mismatch_fails_clearly(self):
|
||||
source = ASSET_DIR / "test_auto.m4b"
|
||||
titles = self.output("too_many_chapters.txt")
|
||||
titles.write_text("Only one title\n", encoding="utf-8")
|
||||
args = command_args(
|
||||
source, self.output("bad_chapters.m4b"), chapter_file=titles
|
||||
)
|
||||
with self.assertRaisesRegex(ValueError, "Chapter count mismatch"):
|
||||
cmd_apply_chapters(args)
|
||||
|
||||
def test_russian_track_removal_leaves_non_russian_streams(self):
|
||||
source = ASSET_DIR / "test_auto.mkv"
|
||||
output = self.output("no_russian.mkv")
|
||||
args = command_args(source, output)
|
||||
self.assertTrue(cmd_remove_russian_from_db(args)[0])
|
||||
media = probe_media(output)
|
||||
self.assertEqual(
|
||||
sum(stream.get("codec_type") == "audio" for stream in media["streams"]),
|
||||
1,
|
||||
)
|
||||
self.assertFalse(
|
||||
any(
|
||||
stream.get("tags", {}).get("language") == "rus"
|
||||
for stream in media["streams"]
|
||||
if stream.get("codec_type") in {"audio", "subtitle"}
|
||||
)
|
||||
)
|
||||
|
||||
def test_dry_run_does_not_create_output(self):
|
||||
output = self.output("dry_run.mkv")
|
||||
args = command_args(
|
||||
ASSET_DIR / "test_auto.mkv", output, dry_run=True, width=320,
|
||||
height=180, crf=30,
|
||||
)
|
||||
self.assertTrue(cmd_downsize(args)[0])
|
||||
self.assertFalse(output.exists())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+6
-1
@@ -17,7 +17,6 @@ dependencies = [
|
||||
"cryptography==46.0.7",
|
||||
"cycler==0.12.1",
|
||||
"distro==1.9.0",
|
||||
"ffmpeg-python>=0.2.0",
|
||||
"filelock==3.25.2",
|
||||
"fonttools==4.62.1",
|
||||
"fsspec==2026.3.0",
|
||||
@@ -75,7 +74,13 @@ members = [
|
||||
"serverlibrary",
|
||||
"wallpaper_changer/python",
|
||||
"immich-scripts",
|
||||
"ffmpeg_handling",
|
||||
]
|
||||
|
||||
[tool.uv.sources]
|
||||
serverlibrary = { workspace = true }
|
||||
|
||||
[dependency-groups]
|
||||
build = [
|
||||
"pyinstaller>=6.22.3",
|
||||
]
|
||||
Reference in new issue
Block a user