diff --git a/.gitea/workflows/ffmpeg_handling.yaml b/.gitea/workflows/ffmpeg_handling.yaml new file mode 100644 index 0000000..6ccaf23 --- /dev/null +++ b/.gitea/workflows/ffmpeg_handling.yaml @@ -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" diff --git a/ffmpeg_handling/.vscode/launch.json b/ffmpeg_handling/.vscode/launch.json new file mode 100644 index 0000000..19bdf85 --- /dev/null +++ b/ffmpeg_handling/.vscode/launch.json @@ -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 + } + ] +} diff --git a/ffmpeg_handling/.vscode/tasks.json b/ffmpeg_handling/.vscode/tasks.json new file mode 100644 index 0000000..695a7c8 --- /dev/null +++ b/ffmpeg_handling/.vscode/tasks.json @@ -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": [] + } + ] +} diff --git a/ffmpeg_handling/BUILDING.md b/ffmpeg_handling/BUILDING.md new file mode 100644 index 0000000..b93f636 --- /dev/null +++ b/ffmpeg_handling/BUILDING.md @@ -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. diff --git a/ffmpeg_handling/README.md b/ffmpeg_handling/README.md new file mode 100644 index 0000000..e69de29 diff --git a/ffmpeg_handling/ffmpeg_handling.py b/ffmpeg_handling/ffmpeg_handling.py deleted file mode 100755 index 1d7b1e5..0000000 --- a/ffmpeg_handling/ffmpeg_handling.py +++ /dev/null @@ -1,2375 +0,0 @@ -#!/home/lucas/scripts/.venv/bin/python3 -""" -FFmpeg Python CLI Tool - -A wrapper for ffmpeg-python to perform common media tasks. -Parameters are documented with their equivalent FFmpeg command-line flags. -""" - -import argparse -import json -import logging -import os -import re -import subprocess -import sys -import tempfile -from pathlib import Path - -import ffmpeg -from mutagen.easyid3 import EasyID3 -from serverlibrary import * - -logging.setLoggerClass(CustomLogger) -logger: CustomLogger = logging.getLogger(__name__) # type: ignore[assignment] - -# ---------------------------- -# OUTPUT ENFORCEMENT (clean + centralized) -# ---------------------------- -commands = { - "test": {"name": "test", "output": False}, - "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}, -} -# ------ Russian Dictonary --------------# -AUDIO_TRANSLATIONS = { - # Voice-over / dubbing - "Закадровый": "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", - # Languages - "русск": "Russian", - "Английски": "English", - "български": "Bulgarian", - "Български": "Bulgarian", - "Українська": "Ukrainian", - "українська": "Ukrainian", - "Македонски": "Macedonian", - "Српски": "Serbian", - "Немецкая": "German", - "Немецкое": "German", - "немецкие": "German", - "Английская": "English", - "Английское": "English", - "Французская": "French", - "Французское": "French", - # Studios / groups - "Кубик в кубе": "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", - # Voice actors - "Юрий Сербин": "Yuriy Serbin", - "Ю. Сербин": "Y. Serbin", - "П.Либергал": "P. Libergal", - "Визгунов": "Vizgunov", - # Misc - # Subtitles - "субтитры": "Russian Subtitles", - "Оригинален език": "Original language", - # ISO - "rus": "Russian", - "ru": "Russian", -} -IGNORE_WORDS = { - "English", - "German", - "French", -} - -RUSSIAN_RE = re.compile( - "|".join( - sorted( - ( - re.escape(key) - for key in AUDIO_TRANSLATIONS - if AUDIO_TRANSLATIONS[key] not in IGNORE_WORDS - ), - key=len, - reverse=True, - ) - ), - re.IGNORECASE, -) - - -def is_russian_track(track: dict) -> bool: - descr = bool(RUSSIAN_RE.search(track["description"])) - language = bool(RUSSIAN_RE.search(track["language"])) - lang = bool(RUSSIAN_RE.search(track["lang"])) - return descr or lang or language - - -def video_files(path: Path, recursive: bool): - iterator = path.rglob("*") if recursive else path.iterdir() - yield from ( - p for p in iterator if p.is_file() and p.suffix.lower() in VIDEO_SUFFIXES - ) - - -class ArgsBuffer: - input: Path | None = None - output: Path | None = None - kidflag: bool | None = False - loud: bool | None = False - key: str | None = None - value: str | None = None - audio_index: list | None = None - dry_run: bool | None = None - audio_codec: str | None = None - video_codec: str | None = None - preset: str | None = None - quality: int | None = None - width: int | None = None - height: int | None = None - crf: int | None = None - num: int | None = None - start: str | None = None - duration: str | None = None - suffix: str | None = None - new_suffix: str | None = None - - -CYRILLIC_RE = re.compile(r"[А-Яа-яЁё]") - - -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 src, dst in AUDIO_TRANSLATIONS.items(): - if re.search(rf"{re.escape(src)}", value, flags=re.IGNORECASE): - value = dst - break - 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 - - -# ---------- Utilities ---------- # - - -# ---------------------------- -# HELPERS -# ---------------------------- -def ask(prompt, default=None): - value = input(f"{prompt}" + (f" [{default}]" if default else "") + ": ").strip() - return value if value else default - - -def ensure(value, prompt): - if value is None: - return ask(prompt) - return value - - -def move_overwrite_file(files_move_from, files_move_to, args): - - backup_files = args.backup - silent = not args.loud - for file_to, file_from in zip(files_move_to, files_move_from): - if not file_to.is_file() and not hasattr(args, "new_suffix"): - logger.error(f"overwrite Target File does not exist: {file_to}") - return False - - if not file_from.is_file(): - logger.trace(f"overwrite File does not exist: {file_from}") - continue - backup = file_to.parent / f"{file_to.stem}_backup{file_from.suffix}" - - if backup_files: - # move original -> backup - logger.trace(f"Move original to backup: {backup}") - safe_rename(file_to, backup, silent=silent) - - # move overwrite -> original name - retstr, ret = safe_rename(file_from, file_to, silent=silent, overwrite=True) - logger.trace(retstr) - if not ret: - logger.error(f"Safe rename failed for: {file_from} -> {file_to}") - return False - return True - - -LOG_FILE = Path.home() / "ffmpeg_log.log" - - -def run_ffmpeg(stream, overwrite=True, loud=False, dry_run=False): - kwargs = { - "overwrite_output": overwrite, - } - - kwargs.update( - capture_stdout=True, - capture_stderr=True, - quiet=True, - ) - - if dry_run: - logger.debug(f"Dry run: {stream}") - return - try: - out, err = ffmpeg.run(stream, **kwargs) - logger.trace(out) - if err: - logger.error(err) - except ffmpeg.Error as e: - logger.error(e.stderr) - logger.error("FFmpeg failed.\n") - sys.exit(1) - - -def probe_audio_streams(file): - """ - Probes metadata to identify audio tracks. - - FFmpeg Equivalent: - ffprobe -v error -select_streams a -show_entries stream=index:tags=language -of json - """ - try: - probe = ffmpeg.probe(file) - except ffmpeg.Error as e: - logger.error(f"ffprobe failed:{e}") - sys.exit(1) - - return [ - (s.get("index"), s.get("tags", {}).get("language", "unknown")) - for s in probe.get("streams", []) - if s.get("codec_type") == "audio" - ] - - -def select_audio_stream(file, provided=None): - """ - Logical handler for stream selection. Ensures we target the correct - absolute stream index when building filter graphs. - """ - streams = probe_audio_streams(file) - - if not streams: - logger.info("No audio streams found.") - sys.exit(1) - - provided = int(provided) if provided else None - if provided is not None: - if any(s[0] == provided for s in streams): - return provided - logger.info(f"Provided index {provided} is not a valid audio stream.") - - if len(streams) == 1: - return streams[0][0] - - logger.info(f"Found {len(streams)} audio streams:") - for i, (idx, lang) in enumerate(streams): - logger.info(f"[{i}] Index: {idx}, Language: {lang}") - - try: - choice = int(input("Select stream number (the list index [x]): ")) - return streams[choice][0] - except (ValueError, IndexError): - logger.error("Invalid selection.") - sys.exit(1) - - -def parse_time_to_seconds(value: str) -> float: - """ - Convert human-readable time formats into seconds. - - Supported formats: - - "100s" → 100 - - "1m20s" → 80 - - "2h10m5s" → 7805 - - "0h1m5s" → 65 - - "0:1:5" → 65 (hh:mm:ss or mm:ss) - """ - - if value is None: - return None - - value = str(value).strip() - - # Case 1: pure seconds (e.g. 100s) - if value.endswith("s") and value[:-1].isdigit(): - return float(value[:-1]) - - # Case 2: h/m/s format (e.g. 1h2m3s) - pattern = re.compile(r"(?:(?P\d+)h)?(?:(?P\d+)m)?(?:(?P\d+)s)?") - match = pattern.fullmatch(value) - if match and any(match.groups()): - h = int(match.group("h") or 0) - m = int(match.group("m") or 0) - s = int(match.group("s") or 0) - return h * 3600 + m * 60 + s - - # Case 3: colon format (hh:mm:ss or mm:ss) - if ":" in value: - parts = list(map(int, value.split(":"))) - if len(parts) == 2: - m, s = parts - return m * 60 + s - elif len(parts) == 3: - h, m, s = parts - return h * 3600 + m * 60 + s - - # fallback: raw number - try: - return float(value) - except ValueError: - raise argparse.ArgumentTypeError(f"Invalid time format: {value}") - - -def get_scodec(output_path: Path): - ext = output_path.suffix - - if ext == "mp4": - return "mov_text" - - if ext == "mkv": - return "srt" - - return "copy" - - -def get_vcodec(output_path: Path): - ext = output_path.suffix - if ext == "mp4": - return "libx264" - - return "copy" - - -def get_chapter_lengths(file_path): - """ - Returns an array of chapter durations (in seconds). - """ - - cmd = [ - "ffprobe", - "-v", - "error", - "-print_format", - "json", - "-show_chapters", - file_path, - ] - - result = subprocess.run( - cmd, - capture_output=True, - text=True, - check=True, - ) - logger.trace(result.stdout) - if result.returncode != 0: - raise RuntimeError(result.stderr) - - data = json.loads(result.stdout) - - chapters = [] - for ch in data.get("chapters", []): - chapters.append( - {"start": float(ch["start_time"]), "end": float(ch["end_time"])} - ) - - return chapters - - -def natural_sort_key(path: Path): - s = str(path.name) # force string conversion - return [ - int(part) if part.isdigit() else part.lower() for part in re.split(r"(\d+)", s) - ] - - -# ---------- Commands ---------- # -def cmd_info(args): - """ - Retrieves and prints metadata. - - FFmpeg Equivalent: - ffprobe -show_format -show_streams -of json [input] - """ - try: - info = ffmpeg.probe(str(args.input)) - logger.info(json.dumps(info, indent=2)) - except ffmpeg.Error as e: - logger.error(f"Error probing file:{e}") - - return False, "nooutputneeded" - - -def cmd_convert_av_all_suffix(args): - """ - Re-encodes both video and audio for all files of suffix . - """ - if args.input.suffix != args.suffix: - return False, "nooutputneeded" - - return cmd_convert_av(args) - - -def cmd_convert_av(args): - """ - Re-encodes both video and audio. - - FFmpeg Equivalent: - ffmpeg -i input -c:v libx264 -c:a aac -preset medium -qp 23 output.mkv - """ - if args.new_suffix: - output = args.output.with_suffix(args.new_suffix) - else: - output = args.output - - logger.debug(f"Convert Audio/Video for {args.input} -> {output}") - cmd = [ - "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), - ] - - result = subprocess.run( - cmd, - check=False, - capture_output=True, - text=True, - encoding="utf-8", - errors="replace", - ) - - return result.returncode == 0, "nooutputneeded" - - -def cmd_convert_audio(args): - """ - Transcodes audio while keeping video intact. - - FFmpeg Equivalent: - ffmpeg -i [input] -map 0:v -map 0:a -c:v copy -c:a [audio_codec] [output] - - Parameters: - - vcodec='copy': Enables 'stream copy' mode, bypassing the video decoder/encoder. - """ - inp = ffmpeg.input(args.input) - out = ffmpeg.output( - inp, - str(args.output), - vcodec="copy", - acodec=args.audio_codec, - scodec=get_scodec(args.output), - map="0", - map_metadata=0, - ) - return True, out - - -def cmd_convert_video(args): - """ - Transcodes video while keeping audio intact. - - FFmpeg Equivalent: - ffmpeg -i [input] -map 0:v -map 0:a -c:v [video_codec] -c:a copy [output] - """ - inp = ffmpeg.input(args.input) - out = ffmpeg.output( - inp, - str(args.output), - vcodec=args.video_codec, - acodec="copy", - scodec=get_scodec(args.output), - map="0", - map_metadata=0, - ) - return True, out - - -from collections.abc import Callable - - -def remove_streams( - args, - remove_indices: set[int] | list[int], - *, - output_subtitle_codec: bool = False, -) -> tuple[bool, str]: - probe = ffmpeg.probe(str(args.input)) - remove_indices = set(remove_indices) - - remaining_audio = [ - s - for s in probe["streams"] - if s["codec_type"] == "audio" and s["index"] not in remove_indices - ] - - if not remaining_audio: - logger.warning("No audiotracks remaining") - return False, "nooutputneeded" - - removed_default_audio = any( - s["codec_type"] == "audio" - and s["index"] in remove_indices - and s.get("disposition", {}).get("default", 0) == 1 - for s in probe["streams"] - ) - - cmd = [ - "ffmpeg", - "-y", - "-i", - str(args.input), - ] - - for stream in probe["streams"]: - if stream["index"] not in remove_indices: - cmd.extend(["-map", f"0:{stream['index']}"]) - - cmd.extend( - [ - "-c:v", - "copy", - "-c:a", - "copy", - ] - ) - - if output_subtitle_codec: - cmd.extend(["-c:s", get_scodec(args.output)]) - else: - cmd.extend(["-c:s", "copy"]) - - cmd.extend( - [ - "-map_metadata", - "0", - ] - ) - - if removed_default_audio: - cmd.extend( - [ - "-disposition:a", - "0", - "-disposition:a:0", - "default", - ] - ) - - cmd.append(str(args.output)) - - logger.trace(" ".join(cmd)) - - if args.dry_run: - logger.debug("Dry run: %s", " ".join(cmd)) - return True, "nooutputneeded" - - try: - result = subprocess.run( - cmd, - capture_output=True, - text=True, - check=True, - ) - - logger.debug("FFmpeg subprocess successful") - logger.trace(result.stdout) - - return True, "nooutputneeded" - - except subprocess.CalledProcessError as e: - logger.error("Command: %s", " ".join(e.cmd)) - logger.error("Return code: %s", e.returncode) - logger.error("STDOUT:\n%s", e.stdout) - logger.error("STDERR:\n%s", e.stderr) - raise - - -def cmd_remove_subs(args): - probe = ffmpeg.probe(str(args.input)) - - if args.num is None: - remove_indices = { - s["index"] for s in probe["streams"] if s["codec_type"] == "subtitle" - } - else: - remove_indices = set(args.num) - - return remove_streams( - args=args, - remove_indices=remove_indices, - ) - - -def cmd_remove_audio_track(args): - remove_indices = { - select_audio_stream(args.input, audio_index) for audio_index in args.audio_index - } - - return remove_streams( - args=args, - remove_indices=remove_indices, - output_subtitle_codec=True, - ) - - -def cmd_extract_audio_track(args): - """ - 1. Saves that specific audio track as a standalone MP3 (Extra Output). - """ - inp = ffmpeg.input(args.input) - probe = ffmpeg.probe(str(args.input)) - - output_audio = Path(args.output) - output_audio = str(output_audio.with_name(f"{output_audio.stem}.mp3")) - - outputs = [] - for index in args.audio_index: - remove_idx = select_audio_stream(args.input, index) - - extracted_audio = None - - for s in probe["streams"]: - idx = s["index"] - if idx == remove_idx: - extracted_audio = inp[str(idx)] - - outputs.append( - ffmpeg.output( - extracted_audio, output_audio, acodec="libmp3lame", audio_bitrate="192k" - ) - ) - - return True, outputs - - -def cmd_downsize(args): - """ - Scales resolution and compresses. - - FFmpeg Equivalent: - ffmpeg -i [input] -vf scale=[w]:[h] -c:v libx264 -crf [crf] -c:a copy [output] - - Parameters: - - filter('scale'): Invokes the video filter (vf) for resizing. - - crf: Set to 23 (default) for balanced quality. - """ - inp = ffmpeg.input(args.input) - video = inp.video.filter("scale", args.width, args.height) - info = ffmpeg.probe(str(args.input)) - streams = info.get("streams", []) - subtitle_streams = [s for s in streams if s.get("codec_type") == "subtitle"] - - subs = {} - if len(subtitle_streams) > 0: - subs = {inp["s"]} - - out = ffmpeg.output( - video, - inp.audio, - *subs, - str(args.output), - vcodec="libx264", - crf=args.crf, - acodec="copy", - scodec=get_scodec(args.output), - ) - return True, out - - -def cmd_filter_audio(args): - """ - Multi-stage audio mastering chain. - - FFmpeg Equivalent: - ffmpeg -i [input] -filter_complex "[0:a:X]highpass...,acompressor...,equalizer...out" \ - -map 0:v -map out -c:v copy -c:a libvorbis [output] - - Filter Descriptions: - 1. highpass: Cuts frequencies below 100Hz (removes low-end rumble). - 2. acompressor: Reduces volume of loud peaks to increase overall clarity. - 3. equalizer: Adjusts specific frequency bands (2.5kHz and 4kHz for presence). - 4. deesser: Dampens harsh 'S' sounds. - 5. alimiter: Hard limit at 0.95 to prevent digital clipping (distortion). - 6. dynaudnorm: Smooths out loudness levels over time. - """ - if len(args.audio_index) > 1: - logger.warning( - f"Filter Audio only filters the first element of list audio_index: {args.audio_index}" - ) - - index = args.audio_index[0] - - idx_filt = select_audio_stream(args.input, index) - - inp = ffmpeg.input(args.input) - probe = ffmpeg.probe(str(args.input)) - - audio_streams = [] - audio_titles = {} - audio_languages = {} - - for s in probe["streams"]: - if s.get("codec_type") == "audio": - idx = s["index"] - audio_streams.append(idx) - - tags = s.get("tags", {}) - audio_titles[idx] = tags.get("title", f"Audio {idx}") - audio_languages[idx] = tags.get("language", "und") - - filtered_audios = [] - metadata_args = [] - - out_audio_idx = 0 - - for idx in audio_streams: - audio = inp[str(idx)] - - # ------------------- - # ORIGINAL STREAM - # ------------------- - filtered_audios.append(audio) - - metadata_args += [ - f"-metadata:s:a:{out_audio_idx}", - f"title={audio_titles[idx]}", - f"-metadata:s:a:{out_audio_idx}", - f"language={audio_languages[idx]}", - ] - - out_audio_idx += 1 - - # ------------------- - # FILTERED STREAM - # ------------------- - if idx == idx_filt: - audio_filtered = ( - audio.filter("highpass", f=100) - .filter( - "acompressor", threshold="-22dB", ratio=4, attack=10, release=150 - ) - .filter("equalizer", f=2500, t="q", w=1, g=5) - .filter("equalizer", f=4000, t="q", w=1, g=4) - .filter("deesser", i=0.4, f=0.25) - .filter("alimiter", limit=0.95) - .filter("dynaudnorm", f=200, g=15) - ) - - filtered_audios.append(audio_filtered) - - base_title = audio_titles[idx] - filtered_title = base_title + " + filtered" - lang = audio_languages[idx] - - metadata_args += [ - f"-metadata:s:a:{out_audio_idx}", - f"title={filtered_title}", - f"-metadata:s:a:{out_audio_idx}", - f"language={lang}", - f"-metadata:s:a:{out_audio_idx}", - f"handler_name={filtered_title}", - ] - - out_audio_idx += 1 - - # ------------------- - # SUBTITLES - # ------------------- - subs = [] - if any(s.get("codec_type") == "subtitle" for s in probe["streams"]): - subs.append(inp["s"]) - - # ------------------- - # OUTPUT (IMPORTANT FIX HERE) - # ------------------- - input_args = [ - inp.video, - *filtered_audios, - *subs, - ] - - out = ffmpeg.output( - *input_args, - str(args.output), - vcodec="copy", - acodec="libvorbis", - scodec=get_scodec(args.output), - ).global_args(*metadata_args) - - return True, out - - -def cmd_cut_segment(args): - """ - Cut a segment from a video or audio file. - - FFmpeg parameters: - ss (start time): where to begin cutting (seconds or timestamp) - t (duration): length of segment to extract - c=copy: stream copy (fast, no re-encoding) - - Notes: - - Using ss before input enables fast seek - - Copy mode is fast but may be less frame-accurate - """ - - start = parse_time_to_seconds(args.start) - duration = parse_time_to_seconds(args.duration) - - inp = ffmpeg.input(args.input, ss=start) - - out = ffmpeg.output( - inp, - str(args.output), - t=duration, - map="0", - vcodec=get_vcodec(args.output), - acodec="copy", - scodec=get_scodec(args.output), - ) - logger.trace(f"Command: {out}") - return True, out - - -def cmd_set_primary_audio(args): - """ - Set a chosen audio stream as the PRIMARY (first/default) audio track. - - Uses select_audio_stream() to ensure correct stream selection. - - FFmpeg behavior: - - We explicitly reorder audio streams - - Selected stream becomes first audio track - - All other audio streams are preserved - - Video and subtitles are kept - - Important: - FFmpeg does NOT support "set default audio track" directly in MP4. - So we simulate it by stream reordering. - """ - - inp = ffmpeg.input(args.input) - - if len(args.audio_index) > 1: - logger.warning( - f"Set primary can only set the first element of list audio_index: {args.audio_index}" - ) - index = args.audio_index[0] - - primary_audio = select_audio_stream(args.input, index) - probe = ffmpeg.probe(str(args.input)) - - audio_streams = [ - s["index"] for s in probe["streams"] if s.get("codec_type") == "audio" - ] - - reordered_audio = [primary_audio] + [a for a in audio_streams if a != primary_audio] - - audio_inputs = [inp[f"a:{i - 1}"] for i in reordered_audio] - - out_kwargs = {} - for i, stream in enumerate(reordered_audio): - if stream == primary_audio: - out_kwargs[f"disposition:a:{i}"] = "default" - else: - out_kwargs[f"disposition:a:{i}"] = "0" - - info = ffmpeg.probe(str(args.input)) - streams = info.get("streams", []) - subtitle_streams = [s for s in streams if s.get("codec_type") == "subtitle"] - - subs = {} - if len(subtitle_streams) > 0: - subs = {inp["s"]} - - out = ffmpeg.output( - inp.video, - *audio_inputs, - *subs, - str(args.output), - vcodec="copy", - acodec="copy", - scodec=get_scodec(args.output), - **out_kwargs, - ) - - return True, out - - -def cmd_show_metadata(args, show_metadata=False, return_tags=None): - probe = ffmpeg.probe(str(args.input)) - format_tags = probe.get("format", {}).get("tags", {}) - - if return_tags is not None: - return_tags.clear() - return_tags.update(format_tags) - - if show_metadata: - logger.info("=== FORMAT METADATA ===") - for k, v in format_tags.items(): - logger.info(f"{k}: {v}") - - # logger.info(f"\n=== STREAM METADATA ===") - # for i, stream in enumerate(probe.get("streams", [])): - # logger.info(f"\n--- Stream {i} ({stream.get('codec_type')}) ---") - - # tags = stream.get("tags", {}) - # if not tags: - # logger.info(f"No tags") - # else: - # for k, v in tags.items(): - # logger.info(f"{k}: {v}") - return False, "nooutputneeded" - - -def cmd_set_metadata(args): - """ - Set metadata for media files. - - - Default: uses ffmpeg (stream copy) - - If file is .opus: uses kid3-cli (Vorbis tags) - """ - - ext = args.input.suffix.lower() - - # ───────────────────────────────────────────── - # OPUS → use Kid3 CLI (Vorbis comments) - # ───────────────────────────────────────────── - if ext == ".opus" or args.kidflag: - cmd = ["kid3-cli", "-c", f"set {args.key} '{args.value}'", args.input] - if args.dry_run: - logger.debug(f"Dry run: {' '.join(cmd)}") - return True, "nooutputneeded" - result = subprocess.run( - cmd, - capture_output=True, - text=True, - check=True, - ) - logger.trace(result.stdout) - return False, "nooutputneeded" # Kid3 writes in-place - - # ───────────────────────────────────────────── - # Default → ffmpeg (copy stream) - # ───────────────────────────────────────────── - inp = ffmpeg.input(args.input) - - out = ffmpeg.output( - inp, str(args.output), c="copy", metadata=f"{args.key}={args.value}" - ) - return True, out - - -def cmd_apply_chapters(args): - """ - Apply chapter titles to an M4B using a simple title-only text file. - - Chapters file format: - One title per line: - Introduction - Acknowledgment - The War Begins - - Behavior: - - Evenly distributes chapters across media duration - - Generates ffmetadata internally - - Applies chapters using ffmpeg-python - """ - # ---------------------------- - # read chapter titles - # ---------------------------- - with open(args.chapter_file, "r", encoding="utf-8") as f: - titles = [line.strip() for line in f if line.strip()] - - if not titles: - raise ValueError("Chapter file is empty") - - if Path(args.input).suffix == ".m4b": - # ---------------------------- - # build ffmetadata chapters - # ---------------------------- - chapters = get_chapter_lengths(args.input) - - if len(chapters) != len(titles): - logger.error( - f"Chapter lengths do not match: {len(chapters)}, {len(titles)}" - ) - for idx, title in enumerate(titles): - chapters[idx].update({"title": title}) - - metadata_text = ";FFMETADATA1\n\n" - for ch in chapters: - start_ms = int(float(ch["start"]) * 1000) - end_ms = int(float(ch["end"]) * 1000) - metadata_text += ( - "[CHAPTER]\n" - "TIMEBASE=1/1000\n" - f"START={start_ms}\n" - f"END={end_ms}\n" - f"title={ch['title']}\n\n" - ) - - # ---------------------------- - # run ffmpeg - # ---------------------------- - with tempfile.NamedTemporaryFile("w+", suffix=".txt", delete=False) as f: - f.write(metadata_text) - meta_path = f.name - - cmd = [ - "ffmpeg", - "-y", - "-i", - args.input, - "-f", - "ffmetadata", - "-i", - meta_path, - "-map_chapters", - "1", - "-map_metadata", - "0", - "-c", - "copy", - args.output, - ] - if args.dry_run: - logger.debug(f"Dry run: {' '.join(cmd)}") - return True, "nooutputneeded" - result = subprocess.run( - cmd, - capture_output=True, - text=True, - check=True, - ) - logger.trace(result.stdout) - - elif Path(args.input).suffix == ".mp3": - filename = Path(args.input) - logger.info(f"{args.file_counter}:{filename}") - title = titles[args.file_counter] - safe_title = title.replace("/", "-").replace(":", "-") - new_name = f"{args.file_counter + 1:03d} - {safe_title}.mp3" - - new_path = filename.with_name(new_name) - - logger.info(f"{filename.name} -> {new_name}") - audio = EasyID3(filename) - audio["title"] = title - audio["tracknumber"] = str(args.file_counter + 1) - if args.dry_run: - logger.debug("Dry run") - return True, "nooutputneeded" - audio.save() - safe_rename(filename, new_path) - - return True, "nooutputneeded" - - -def cmd_remove_russian_from_db(args): - """ - Find all media with russian audio - remove russian audio tracks - """ - - file = args.input - - logger.trace("Run remove russian cmd") - - try: - audio_tracks = translate_audio_tracks(get_audio_tracks(file)) - subtitle_tracks = translate_audio_tracks(get_subtitle_tracks(file)) - except ValueError as error_msg: - logger.warning(f"File {file.name} {error_msg}") - return False, "nooutputneeded" - - logger.trace("Remove Russian from File: %s", file.name) - - remove_indices = { - track["number"] - for track in audio_tracks + subtitle_tracks - if is_russian_track(track) - } - - for track in audio_tracks: - if track["number"] in remove_indices: - logger.debug( - "Removing russian audio track %s from %s", - track["number"], - file, - ) - - for track in subtitle_tracks: - if track["number"] in remove_indices: - logger.debug( - "Removing russian subtitle track %s from %s", - track["number"], - file, - ) - - if not remove_indices: - return False, "nooutputneeded" - - return remove_streams( - args=args, - remove_indices=remove_indices, - ) - - -def cmd_test(args): - """ - TEST MODE: - Runs each command individually on test.mp4 and probes outputs. - """ - - test_file_dir = Path("/home/lucas/scripts/media_editing/testfiles") - test_files = [ - "test_auto.mkv", - "test_auto.mp4", - "test_auto.avi", - "test_auto_only_russian.mkv", - "test_auto_no_subs.mkv", - "test_auto_no_subs.mp4", - ] - test_files = [test_file_dir / file for file in test_files] - test_dir = Path(tempfile.mkdtemp(prefix="ffmpeg_test_")) - logger.info(f"Using test dir: {test_dir}") - - def run_and_probe(name, cmd_func, args_probe, _test_dict=None): - if _test_dict is None: - _test_dict = [] - logger.info(f"TEST: {name}") - # Run FFmpeg for this single command only - return_value, outputs = cmd_func(args_probe) - if not outputs: - logger.error("No outputs returned.") - return False - if outputs != "nooutputneeded": - try: - ffmpeg.run( - outputs, overwrite_output=True, quiet=True, capture_stderr=True - ) - except ffmpeg.Error as e: - logger.error("FFmpeg failed:") - if e.stderr: - logger.info(e.stderr.decode(errors="ignore")) - return False - logger.info("FFmpeg succeeded") - # Probe result file(s) - out_files = [] - - if hasattr(args_probe, "output") and args_probe.output and return_value: - out_files.append(args_probe.output) - - for idx, file in enumerate(out_files): - if not file.exists(): - logger.info(f"{red_tag('FAIL')} Missing output: {file}") - continue - try: - ret_va = validate_ffprobe(file, _test_dict[idx]) - return ret_va - except ffmpeg.Error as e: - logger.error(f"{red_tag('FAIL')} Probe error: {file}") - logger.error(e) - return False - return True - - def is_cover_art(stream): - if stream["codec_type"] != "video": - return False - - if stream.get("disposition", {}).get("attached_pic") == 1: - return True - - if stream.get("nb_frames") and int(stream.get("nb_frames")) <= 1: - return True - tags = stream.get("tags", {}) - if "DURATION" in tags: - h, m, s = tags["DURATION"].split(":") - if int(h) * 3600 + int(m) * 60 + float(s) < 1: - return True - if "MIMETYPE" in tags and tags["MIMETYPE"] == "image/jpg": - return True - if "FILENAME" in tags and tags["FILENAME"] == "cover.jpg": - return True - - return False - - def get_streams(_test_file): - info = ffmpeg.probe(_test_file) - streams = info.get("streams", []) - - _video_streams = [ - s for s in streams if s.get("codec_type") == "video" and not is_cover_art(s) - ] - _audio_streams = [s for s in streams if s.get("codec_type") == "audio"] - _subtitle_streams = [s for s in streams if s.get("codec_type") == "subtitle"] - _cover_image = [ - s for s in streams if s.get("codec_type") == "video" and is_cover_art(s) - ] - if not os.path.exists(_test_file): - logger.info("test file not found in script directory.") - sys.exit(1) - - return _video_streams, _audio_streams, _subtitle_streams, _cover_image - - def validate_ffprobe(file_path, expected: dict): - """ - Validate ffprobe output using a dictionary-based expectation. - - Expected dict format: - { - "video_count": int, - "audio_count": int, - "subtitle_count": int, - "audio_codecs": list[str], - "video_codecs": list[str] - } - """ - if not file_path.is_file(): - logger.error(f"Test file {file_path} is not a file") - result = subprocess.run( - [ - "ffprobe", - "-v", - "quiet", - "-print_format", - "json", - "-show_chapters", - "-show_format", - file_path, - ], - capture_output=True, - text=True, - check=True, - ) - - info = json.loads(result.stdout) - video_streams, audio_streams, subtitle_streams, cover_image = get_streams( - file_path - ) - args = ArgsBuffer() - args.input = file_path - tags = {} - cmd_show_metadata(args, return_tags=tags) - - return_value = True - - # ---------- COUNT CHECKS ---------- - if "video_count" in expected: - if len(video_streams) != expected["video_count"]: - logger.error( - f"{red_tag('VIDEO COUNT FAIL')} expected {expected['video_count']}, got {len(video_streams)}" - ) - return_value = return_value and False - - if "audio_count" in expected: - if len(audio_streams) != expected["audio_count"]: - logger.error( - f"{red_tag('AUDIO COUNT FAIL')} expected {expected['audio_count']}, got {len(audio_streams)}" - ) - return_value = return_value and False - - if "subtitle_count" in expected: - if len(subtitle_streams) != expected["subtitle_count"]: - logger.error( - f"{red_tag('SUBTITLE COUNT FAIL')} expected {expected['subtitle_count']}, got {len(subtitle_streams)}" - ) - return_value = return_value and False - - # ---------- CODEC CHECKS ---------- - if "audio_codecs" in expected: - actual = sorted([s.get("codec_name") for s in audio_streams]) - expected_codecs = sorted(expected["audio_codecs"]) - if len(expected_codecs) < len(actual): - last = expected_codecs[-1] if expected_codecs else None - expected_codecs = expected_codecs + [last] * ( - len(actual) - len(expected_codecs) - ) - - if actual != expected_codecs: - logger.error( - f"{red_tag('AUDIO CODEC FAIL')}\nExpected: {expected_codecs}\nGot: {actual}" - ) - return_value = return_value and False - - if "video_codecs" in expected: - actual = sorted([s.get("codec_name") for s in video_streams]) - expected_codecs = sorted(expected["video_codecs"]) - if len(expected_codecs) < len(actual): - last = expected_codecs[-1] if expected_codecs else None - expected_codecs = expected_codecs + [last] * ( - len(actual) - len(expected_codecs) - ) - if actual != expected_codecs: - logger.error( - f"{red_tag('VIDEO CODEC FAIL')}\nExpected: {expected_codecs}\nGot: {actual}" - ) - return_value = return_value and False - - # ---------- DURATION CHECKS ---------- - if "duration" in expected: - format_info = info.get("format", {}) - actual_duration = float(format_info.get("duration", 0)) - expected_duration = parse_time_to_seconds(expected["duration"]) - - # allow small ffmpeg timing variance (important!) - tolerance = expected.get("duration_tolerance", 0.2) - - if abs(actual_duration - expected_duration) <= tolerance: - logger.error( - f"{red_tag('DURATION FAIL')} expected ~{expected_duration} (±{tolerance}), got {actual_duration}s" - ) - return_value = return_value and False - - # ---------- CHAPTER CHECKS ---------- - if "chapter_name" in expected: - chapter_name = [ - chapter.get("tags", {}).get("title", "") - for chapter in info.get("chapters", []) - ] - expected_chapter_name = expected["chapter_name"] - if expected_chapter_name != chapter_name: - logger.error( - f"Expected chapter_name: {expected_chapter_name}, got {chapter_name}" - ) - return_value = return_value and False - - if "chapter_count" in expected: - chapter_num = len(info.get("chapters", [])) - expected_chapter_count = expected["chapter_count"] - if expected_chapter_count != chapter_num: - logger.error( - f"Expected chapters: {expected_chapter_count}, got {chapter_num}" - ) - return_value = return_value and False - - # ---------- METADATA CHECKS ---------- - - if "metadata" in expected: - keys = expected["metadata"].keys() - values = expected["metadata"].values() - for key, value in zip(keys, values): - if key in tags.keys() and tags[key] == value: - logger.debug(f"{key}: {value}") - else: - logger.error(f"Key {key}: {value} not in expected tags") - return_value = return_value and False - - if "no_russian_dir" in expected: - audio_tracks = translate_audio_tracks(get_audio_tracks(file_path)) - logger.debug(f"Audio tracks: {audio_tracks}") - for audio_track in audio_tracks: - if is_russian_track(audio_track): - logger.error( - f"Found russian track: {audio_track} in file {file_path}" - ) - return return_value and False - - subtitle_tracks = translate_audio_tracks(get_audio_tracks(file_path)) - logger.debug(f"Subtitle tracks: {subtitle_tracks}") - for subtitle_track in subtitle_tracks: - if is_russian_track(subtitle_track): - logger.error( - f"Found russian track: {subtitle_track} in file {file_path}" - ) - return return_value and False - - logger.info(f"{green_tag('PASS')} {file_path}") - return return_value - - # ---------- INFO ---------- - # args = ArgsBuffer() - # args.input = test_file_mp4 - # test_dict = {} - # run_and_probe(cmd_test["name"], cmd_info, args, test_dict) - # args.input = test_file_mkv - # ret = ret and run_and_probe(cmd_test["name"], cmd_info, args, test_dict) - - # ---------- DOWNSIZE ----------# - ret = True - args_test = ArgsBuffer() - - cmd_test = commands["downsize"] - if cmd_test["name"] in args.choices: - for test_file in test_files: - video_streams, audio_streams, subtitle_streams, cover_image = get_streams( - test_file - ) - args_test.input = test_file - args_test.output = ( - Path(test_dir) - / f"out_{str(cmd_test['name']).replace('-', '_')}_{Path(test_file).stem}{Path(test_file).suffix}" - ) - args_test.width = 640 - args_test.height = 360 - args_test.crf = 28 - test_dict = [ - { - "video_count": len(video_streams), - "audio_count": len(audio_streams), - "subtitle_count": len(subtitle_streams), - "video_codecs": ["h264"], - } - ] - ret = ret and run_and_probe( - cmd_test["name"], cmd_downsize, args_test, test_dict - ) - - # ---------- REMOVE AUDIO TRACK ---------- - cmd_test = commands["remove-audio"] - if cmd_test["name"] in args.choices: - args_test = ArgsBuffer() - args_test.audio_index = [1] - - for test_file in test_files: - video_streams, audio_streams, subtitle_streams, cover_image = get_streams( - test_file - ) - args_test.input = test_file - test_dict = [ - { - "video_count": len(video_streams), - "audio_count": 1, - "subtitle_count": len(subtitle_streams), - } - ] - args_test.output = ( - Path(test_dir) - / f"out_{str(cmd_test['name']).replace('-', '_')}_{Path(test_file).stem}{Path(test_file).suffix}" - ) - - ret = ret and run_and_probe( - cmd_test["name"], cmd_remove_audio_track, args_test, test_dict - ) - - # ---------- EXTRACT AUDIO TRACK ---------- - cmd_test = commands["extract-audio"] - if cmd_test["name"] in args.choices: - args_test = ArgsBuffer() - args_test.audio_index = [1] - - for test_file in test_files: - args_test.input = test_file - test_dict = [{"video_count": 0, "audio_count": 1, "subtitle_count": 0}] - args_test.output = ( - Path(test_dir) / f"extracted_audio_{Path(test_file).suffix[1:]}.mp3" - ) - ret = ret and run_and_probe( - cmd_test["name"], cmd_extract_audio_track, args_test, test_dict - ) - - # ---------- CONVERT AV ---------- - cmd_test = commands["convert-av"] - if cmd_test["name"] in args.choices: - args_test = ArgsBuffer() - for test_file in test_files: - video_streams, audio_streams, subtitle_streams, cover_image = get_streams( - test_file - ) - args_test.input = test_file - args_test.suffix = ".mkv" - args_test.output = ( - Path(test_dir) - / f"out_{str(cmd_test['name']).replace('-', '_')}_{Path(test_file).stem}_" - f"{Path(test_file).suffix.replace('.', '')}_{args_test.suffix}" - ) - args_test.video_codec = "libx264" - args_test.audio_codec = "aac" - args_test.preset = "fast" - args_test.quality = 23 - test_dict = [ - { - "video_count": len(video_streams), - "audio_count": len(audio_streams), - "subtitle_count": len(subtitle_streams), - "video_codecs": ["h264"], - "audio_codecs": ["aac"], - } - ] - logger.trace(f"Convert file {args_test.input}") - ret = ret and run_and_probe( - cmd_test["name"], cmd_convert_av, args_test, test_dict - ) - - # ---------- CONVERT AV ALL ---------- - cmd_test = commands["convert-av-all"] - if cmd_test["name"] in args.choices: - args_test = ArgsBuffer() - for test_file in test_files: - video_streams, audio_streams, subtitle_streams, cover_image = get_streams( - test_file - ) - args_test.input = test_file - args_test.suffix = ".avi" - args_test.new_suffix = ".mp4" - args_test.output = ( - Path(test_dir) - / f"out_{str(cmd_test['name']).replace('-', '_')}_{Path(test_file).stem}{args_test.new_suffix}" - ) - args_test.video_codec = "libx264" - args_test.audio_codec = "aac" - args_test.preset = "fast" - args_test.quality = 23 - test_dict = [ - { - "video_count": len(video_streams), - "audio_count": len(audio_streams), - "subtitle_count": len(subtitle_streams), - } - ] - if test_file.suffix == args_test.suffix: - test_dict[0]["video_codecs"] = ["h264"] - test_dict[0]["audio_codecs"] = ["aac"] - if test_file.suffix != args_test.suffix: - test_dict[0]["video_codecs"] = [ - s.get("codec_name") for s in video_streams - ] - test_dict[0]["audio_codecs"] = [ - s.get("codec_name") for s in video_streams - ] - - ret = ret and run_and_probe( - cmd_test["name"], cmd_convert_av_all_suffix, args_test, test_dict - ) - - # ---------- CONVERT AUDIO ---------- - cmd_test = commands["convert-audio"] - - if cmd_test["name"] in args.choices: - args_test = ArgsBuffer() - for test_file in test_files: - video_streams, audio_streams, subtitle_streams, cover_image = get_streams( - test_file - ) - args_test.input = test_file - args_test.output = ( - Path(test_dir) - / f"out_{str(cmd_test['name']).replace('-', '_')}_{Path(test_file).stem}{Path(test_file).suffix}" - ) - args_test.audio_codec = "aac" - test_dict = [ - { - "video_count": len(video_streams), - "audio_count": len(audio_streams), - "subtitle_count": len(subtitle_streams), - "audio_codecs": ["aac"], - } - ] - ret = ret and run_and_probe( - cmd_test["name"], cmd_convert_audio, args_test, test_dict - ) - - # ---------- CONVERT VIDEO ---------- - cmd_test = commands["convert-video"] - if cmd_test["name"] in args.choices: - args_test = ArgsBuffer() - for test_file in test_files: - video_streams, audio_streams, subtitle_streams, cover_image = get_streams( - test_file - ) - args_test.input = test_file - args_test.output = ( - Path(test_dir) - / f"out_{str(cmd_test['name']).replace('-', '_')}_{Path(test_file).stem}{Path(test_file).suffix}" - ) - args_test.video_codec = "libx264" - test_dict = [ - { - "video_count": len(video_streams), - "audio_count": len(audio_streams), - "subtitle_count": len(subtitle_streams), - "video_codecs": ["h264"], - } - ] - ret = ret and run_and_probe( - cmd_test["name"], cmd_convert_video, args_test, test_dict - ) - - # ---------- REMOVE SUBS ---------- - cmd_test = commands["remove-subs"] - if cmd_test["name"] in args.choices: - args_test = ArgsBuffer() - for test_file in test_files: - video_streams, audio_streams, subtitle_streams, cover_image = get_streams( - test_file - ) - args_test.input = test_file - args_test.num = None - test_dict = [ - { - "video_count": len(video_streams), - "audio_count": len(audio_streams), - "subtitle_count": 0, - } - ] - args_test.output = ( - Path(test_dir) - / f"out_{str(cmd_test['name']).replace('-', '_')}_{Path(test_file).stem}{Path(test_file).suffix}" - ) - ret = ret and run_and_probe( - cmd_test["name"], cmd_remove_subs, args_test, test_dict - ) - - # ---------- FILTER AUDIO ---------- - cmd_test = commands["filter-audio"] - if cmd_test["name"] in args.choices: - args_test = ArgsBuffer() - for test_file in test_files: - video_streams, audio_streams, subtitle_streams, cover_image = get_streams( - test_file - ) - args_test.input = test_file - args_test.output = ( - Path(test_dir) - / f"out_{str(cmd_test['name']).replace('-', '_')}_{Path(test_file).stem}{Path(test_file).suffix}" - ) - args_test.audio_index = [1] - test_dict = [ - { - "video_count": len(video_streams), - "audio_count": len(audio_streams) + 1, - "subtitle_count": len(subtitle_streams), - "audio_codecs": ["vorbis"], - } - ] - ret = ret and run_and_probe( - cmd_test["name"], cmd_filter_audio, args_test, test_dict - ) - - # ---------- CUT ---------- - cmd_test = commands["cut"] - if cmd_test["name"] in args.choices: - args_test = ArgsBuffer() - for test_file in test_files: - video_streams, audio_streams, subtitle_streams, cover_image = get_streams( - test_file - ) - args_test.input = test_file - args_test.output = ( - Path(test_dir) - / f"out_{str(cmd_test['name']).replace('-', '_')}_{Path(test_file).stem}{Path(test_file).suffix}" - ) - args_test.start = "0:0:5" - args_test.duration = "10s" - test_dict = [ - { - "video_count": len(video_streams), - "audio_count": len(audio_streams), - "subtitle_count": len(subtitle_streams), - "duration": "10s", - } - ] - ret = ret and run_and_probe( - cmd_test["name"], cmd_cut_segment, args_test, test_dict - ) - - # ---------- SET PRIMARY AUDIO ---------- - cmd_test = commands["set-primary-audio"] - if cmd_test["name"] in args.choices: - args_test = ArgsBuffer() - for test_file in test_files: - video_streams, audio_streams, subtitle_streams, cover_image = get_streams( - test_file - ) - args_test.input = test_file - args_test.output = ( - Path(test_dir) - / f"out_{str(cmd_test['name']).replace('-', '_')}_{Path(test_file).stem}{Path(test_file).suffix}" - ) - args_test.audio_index = [2] - test_dict = [ - { - "video_count": len(video_streams), - "audio_count": len(audio_streams), - "subtitle_count": len(subtitle_streams), - } - ] - ret = ret and run_and_probe( - cmd_test["name"], cmd_set_primary_audio, args_test, test_dict - ) - - # ---------- APPLY CHAPTERS----- - cmd_test = commands["chapters"] - if cmd_test["name"] in args.choices: - args_test = ArgsBuffer() - test_file = test_file_dir / "test_auto.m4b" - video_streams, audio_streams, subtitle_streams, cover_image = get_streams( - test_file - ) - args_test.input = test_file - args_test.output = ( - Path(test_dir) - / f"out_{str(cmd_test['name']).replace('-', '_')}_{Path(test_file).stem}{Path(test_file).suffix}" - ) - args_test.chapter_file = test_file_dir / "test_auto_chapters.txt" - lines = Path(args_test.chapter_file).read_text(encoding="utf-8").splitlines() - test_dict = [ - { - "video_count": len(video_streams), - "audio_count": len(audio_streams), - "chapter_name": lines, - "chapter_count": len(lines), - } - ] - ret = ret and run_and_probe( - cmd_test["name"], cmd_apply_chapters, args_test, test_dict - ) - - # ---------- WRITE METADATA----- - cmd_test = commands["metadata-set"] - if cmd_test["name"] in args.choices: - args_test = ArgsBuffer() - test_file = test_file_dir / "test_auto.m4b" - video_streams, audio_streams, subtitle_streams, cover_image = get_streams( - test_file - ) - args_test.input = test_file - args_test.output = ( - Path(test_dir) - / f"out_{str(cmd_test['name']).replace('-', '_')}_{Path(test_file).stem}{Path(test_file).suffix}" - ) - args_test.key = "artist" - args_test.value = "TEST" - args_test.kidflag = False - test_dict = [ - { - "video_count": len(video_streams), - "audio_count": len(audio_streams), - "metadata": {"artist": "TEST"}, - } - ] - ret = ret and run_and_probe( - cmd_test["name"], cmd_set_metadata, args_test, test_dict - ) - - # ---------- REMOVE RUSSIAN AUDIO ----- - cmd_test = commands["remove-russian-from-db"] - if cmd_test["name"] in args.choices: - for test_file in test_files: - args_test = ArgsBuffer() - args_test.input = test_file - args_test.output = ( - Path(test_dir) - / f"out_{str(cmd_test['name']).replace('-', '_')}_{Path(test_file).stem}{Path(test_file).suffix}" - ) - args_test.loud = False - test_dict = [{"no_russian_dir": test_dir}] - ret = ret and run_and_probe( - cmd_test["name"], cmd_remove_russian_from_db, args_test, test_dict - ) - - ## -----------FOLDER TEST--------------- - ## ---------- REMOVE RUSSIAN AUDIO ----- - # cmd = commands["remove-russian-from-db"] - # if cmd["name"] in args.choices: - # args_test = ArgsBuffer() - # args_test.input = test_file_dir - # args_test.output = ( - # Path(test_dir) - # / f"out_{str(cmd['name']).replace('-', '_')}_{Path(test_file).stem}{Path(test_file).suffix}" - # ) - # args_test.loud = False - # test_dict = [{"no_russian_dir": test_dir}] - # ret = ret and run_and_probe( - # cmd["name"], cmd_remove_russian_from_db, args_test, test_dict - # ) - - if ret: - logger.info(green_tag("ALL TESTS SUCCEEDED")) - else: - logger.info(red_tag("SOME TESTS FAILED")) - - -# ---------- CLI Setup ---------- # - - -def add_command( - subparsers, - name, - func, - help_text, - aliases=None, - parents=None, -): - parser = subparsers.add_parser( - name, - aliases=aliases or [], - parents=parents or [], - 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="Audio track index", - ) - - -def main(): - parser = argparse.ArgumentParser( - description="Media processing tool using ffmpeg-python", - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - ) - - # ========================================================= - # SHARED ARGS - # ========================================================= - - base_p = argparse.ArgumentParser(add_help=False) - - base_p.add_argument("input", nargs="?", type=Path, help="Input file or directory") - base_p.add_argument("-o", "--output", type=Path, help="Output file") - base_p.add_argument("--overwrite", action="store_true", help="Overwrite input") - base_p.add_argument("--backup", action="store_true", help="Backup original") - base_p.add_argument("--loud", action="store_true", help="Show ffmpeg output") - base_p.add_argument( - "--kidflag", action="store_true", help="Use kid3 instead of ffmpeg" - ) - base_p.add_argument( - "-r", "--recursive", action="store_true", help="Process recursively" - ) - - parser_add_loglevel(parser) - - base_p.add_argument( - "--dry-run", - action="store_true", - help="Do not execute actions", - ) - - sub = parser.add_subparsers( - dest="command", - required=True, - ) - - # ========================================================= - # INFO - # ========================================================= - - add_command( - sub, - "info", - cmd_info, - "Inspect media metadata", - aliases=["i"], - parents=[base_p], - ) - - # ========================================================= - # TEST - # ========================================================= - - p = add_command( - sub, - "test", - cmd_test, - "Run tests", - aliases=["t"], - parents=[base_p], - ) - - p.add_argument( - "--choices", - nargs="+", - choices=list(commands.keys()), - default=list(commands.keys()), - ) - - # ========================================================= - # CONVERT AV - # ========================================================= - - p = add_command( - sub, - "convert-av", - cmd_convert_av, - "Full video/audio re-encode", - aliases=["cav"], - parents=[base_p], - ) - - p.add_argument("--video-codec", default="libx264") - p.add_argument("--audio-codec", default="aac") - p.add_argument("--preset", default="slow") - p.add_argument("--quality", type=int) - p.add_argument("--new-suffix", type=str) - # ========================================================= - # CONVERT AV ALL - # ========================================================= - - p = add_command( - sub, - "convert-av-all", - cmd_convert_av_all_suffix, - "Full video/audio re-encode for all files of suffx ", - aliases=["call"], - parents=[base_p], - ) - - p.add_argument("suffix", type=str) - p.add_argument("--video-codec", default="libx264") - p.add_argument("--audio-codec", default="aac") - p.add_argument("--preset", default="slow") - p.add_argument("--quality", type=int) - p.add_argument("--new-suffix", type=str) - - # ========================================================= - # CONVERT AUDIO - # ========================================================= - - p = add_command( - sub, - "convert-audio", - cmd_convert_audio, - "Convert audio only", - aliases=["ca"], - parents=[base_p], - ) - - p.add_argument("--audio-codec", default="aac") - - # ========================================================= - # CONVERT VIDEO - # ========================================================= - - p = add_command( - sub, - "convert-video", - cmd_convert_video, - "Convert video only", - aliases=["cv"], - parents=[base_p], - ) - - p.add_argument("--video-codec", default="libx264") - - # ========================================================= - # REMOVE SUBS - # ========================================================= - - add_command( - sub, - "remove-subs", - cmd_remove_subs, - "Strip subtitle streams", - aliases=["rs"], - parents=[base_p], - ) - - # ========================================================= - # REMOVE AUDIO - # ========================================================= - - p = add_command( - sub, - "remove-audio", - cmd_remove_audio_track, - "Remove audio track", - aliases=["ra"], - parents=[base_p], - ) - add_audio_index(p) - - # ========================================================= - # EXTRACT AUDIO - # ========================================================= - - p = add_command( - sub, - "extract-audio", - cmd_extract_audio_track, - "Extract audio track", - aliases=["ea"], - parents=[base_p], - ) - add_audio_index(p) - - # ========================================================= - # DOWNSIZE - # ========================================================= - - p = add_command( - sub, - "downsize", - cmd_downsize, - "Scale video", - aliases=["d"], - parents=[base_p], - ) - - p.add_argument("-w", "--width", type=int) - p.add_argument("-he", "--height", type=int) - p.add_argument("-c", "--crf", type=int) - - # ========================================================= - # FILTER AUDIO - # ========================================================= - - p = add_command( - sub, - "filter-audio", - cmd_filter_audio, - "Apply audio filters", - aliases=["fa"], - parents=[base_p], - ) - add_audio_index(p) - - # ========================================================= - # CUT - # ========================================================= - - p = add_command( - sub, - "cut", - cmd_cut_segment, - "Cut media segment", - aliases=["c"], - parents=[base_p], - ) - - p.add_argument("--start") - p.add_argument("--duration") - - # ========================================================= - # SET PRIMARY AUDIO - # ========================================================= - - p = add_command( - sub, - "set-primary-audio", - cmd_set_primary_audio, - "Set default audio track", - aliases=["spa"], - parents=[base_p], - ) - add_audio_index(p) - - # ========================================================= - # REMOVE RUSSIAN AUDIO - # ========================================================= - - add_command( - sub, - "remove-russian-from-db", - cmd_remove_russian_from_db, - "Remove russian audio tracks", - aliases=["rrfd"], - parents=[base_p], - ) - - # ========================================================= - # CHAPTERS - # ========================================================= - - p = add_command( - sub, - "chapters", - cmd_apply_chapters, - "Apply chapter metadata", - aliases=["ch"], - parents=[base_p], - ) - - p.add_argument( - "-cf", - "--chapter-file", - help="ffmetadata chapter file", - ) - - # ========================================================= - # METADATA PRINT - # ========================================================= - - add_command( - sub, - "metadata-print", - cmd_show_metadata, - "Show metadata", - aliases=["mp"], - parents=[base_p], - ) - - # ========================================================= - # METADATA SET - # ========================================================= - - p = add_command( - sub, - "metadata-set", - cmd_set_metadata, - "Set metadata value", - aliases=["ms"], - parents=[base_p], - ) - - p.add_argument("-k", "--key") - p.add_argument("-v", "--value") - - # ========================================================= - # PARSE - # ========================================================= - - args = parser.parse_args() - - setup_logging(args.log_level, "ffmpeg_handling") - # ---------------------------- - # COMMAND VALIDATION - # ---------------------------- - if not hasattr(args, "func"): - logger.info("\nAvailable commands:") - - seen = set() - for name, parser in sub.choices.items(): - if id(parser) in seen: - continue - seen.add(id(parser)) - logger.info(f" - {name}") - - args.command = ensure(None, "Command") - - if args.command not in sub.choices: - parser.error("Unknown command") - - # re-parse subcommand properly - sub_args = sub.choices[args.command].parse_args([]) - args = argparse.Namespace(**vars(sub_args)) - - # ---------------------------- - # INTERACTIVE FALLBACK (ensure ALL missing values) - # ---------------------------- - if args.command != "test": - args.input = Path( - ensure(getattr(args, "input", None), f"Input file ({Path.cwd()})") - ) - args.input = Path(args.input).expanduser().resolve() - if not Path(args.input).exists(): - parser.error(f"Input file {args.input} does not exist!") - if commands[args.command]["output"] and not getattr(args, "output", None): - input_path = Path(args.input) - if args.overwrite: - args.output = input_path.with_name( - f"{input_path.stem}_overwrite{input_path.suffix}" - ) - else: - args.output = ensure( - getattr(args, "output", None), - "Output file (enter for default file)", - ) - if args.output == "" or args.output is None: - input_path = Path(args.input) - args.output = input_path.with_name( - f"{input_path.stem}_{args.command}{input_path.suffix}" - ) - else: - args.output = Path(args.output) - # ---------------------------- - # COMMAND-SPECIFIC REQUIRED FIELDS - # ---------------------------- - - if args.command == "convert-av": - args.preset = ensure( - getattr(args, "preset", None), - "Encoding speed/quality preset (default: medium, e.g. ultrafast, fast, slow, veryslow)", - ) - args.quality = ensure( - getattr(args, "quality", None), - "Output quality level (e.g. CRF value or bitrate depending on encoder)", - ) - if args.command == "convert-av" or args.command == "convert-audio": - args.audio_codec = ensure( - getattr(args, "audio_codec", None), - "Audio codec to use (default: aac, e.g. mp3, opus)", - ) - if args.command == "convert-av" or args.command == "convert-video": - args.video_codec = ensure( - getattr(args, "video_codec", None), - "Video codec to use (default: libx264, e.g. libx265, vp9)", - ) - - if args.command == "cut": - args.start = ensure(getattr(args, "start", None), "Start time (e.g. 10s, 1:00)") - args.duration = ensure(getattr(args, "duration", None), "Duration (e.g. 30s)") - - if args.command == "downsize": - args.width = ensure(getattr(args, "width", None), "width: eg 1080") - args.height = ensure(getattr(args, "height", None), "height: eg 720") - args.crf = ensure(getattr(args, "crf", None), "crf: eg 23") - - if args.command in [ - "filter-audio", - "remove-audio", - "extract-audio", - "set-primary-audio", - ]: - index = str(ensure(getattr(args, "audio_index", None), "Audio index")) - args.audio_index = [int(x) for x in re.split(r"[,\s]+", index.strip()) if x] - if args.audio_index is None: - args.audio_index = [1] - - if args.command == "chapters": - args.chapter_file = ensure( - getattr(args, "chapter_file", None), "File with chapternames" - ) - - if args.command == "metadata-set": - args.chapter_file = ensure(getattr(args, "key", None), "Key to change") - args.chapter_file = ensure(getattr(args, "value", None), "Key value") - - # ---------------------------- - # EXECUTE COMMAND - # ---------------------------- - try: - if args.command == "test": - args.func(args) - sys.exit(0) - outputs = [] - input_path = Path(args.input) - files_move_from = [] - files_move_to = [] - # ---- DIRECTORY ---- - if input_path.is_dir(): - counter = 0 - logger.info(f"Processing dir: {input_path}") - - sorted_files = sorted( - video_files(input_path, args.recursive), - key=natural_sort_key, - ) - - for file in sorted_files: - if ( - file.suffix.lower() not in VIDEO_SUFFIXES - and file.suffix.lower() not in AUDIO_SUFFIXES - ): - continue - logger.trace(f"Processing File: {file}") - args.input = Path(file) - if args.overwrite: - out_path = file.with_name(f"{file.stem}_overwrite{file.suffix}") - else: - out_path = file.with_name( - f"{file.stem}_{args.command}{file.suffix}" - ) - args.output = out_path - args.file_counter = counter - return_value, output_str = args.func(args) - if output_str != "nooutputneeded": - outputs.append(output_str) - if args.overwrite and return_value: - if hasattr(args, "new_suffix") and args.new_suffix: - out_path = file.with_name( - f"{file.stem}_overwrite{args.new_suffix}" - ) - safe_delete(file, logger) - file = file.with_suffix(args.new_suffix) - files_move_from.append(out_path) - files_move_to.append(file) - counter += 1 - # ---- SINGLE FILE ---- - elif input_path.is_file(): - return_value, output_str = args.func(args) - if output_str != "nooutputneeded": - outputs.append(output_str) - else: - raise ValueError(f"Invalid input path: {args.input}") - - if any(item is None for item in outputs) or len(outputs) == 0: - logger.info("Output is NONE") - else: - if not isinstance(outputs, list): - outputs = [outputs] - - if args.command != "test" and outputs is not None: - run_ffmpeg( - ffmpeg.merge_outputs(*outputs), overwrite=True, loud=args.loud - ) - if args.overwrite and not move_overwrite_file( - files_move_from, files_move_to, args - ): - logger.error("move_overwrite failed") - sys.exit(1) - except ffmpeg.Error as e: - logger.error("FFmpeg failed.\n") - if e.stderr: - logger.error(e.stderr.decode(errors="ignore")) - sys.exit(1) - - sys.exit(0) - - -if __name__ == "__main__": - main() diff --git a/ffmpeg_handling/ffmpeg_handling.spec b/ffmpeg_handling/ffmpeg_handling.spec new file mode 100644 index 0000000..6217b3e --- /dev/null +++ b/ffmpeg_handling/ffmpeg_handling.spec @@ -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, +) diff --git a/ffmpeg_handling/main.py b/ffmpeg_handling/main.py new file mode 100755 index 0000000..4eb3d7b --- /dev/null +++ b/ffmpeg_handling/main.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python3 + +import sys + +from ffmpeg_handling.cli import main + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ffmpeg_handling/pyproject.toml b/ffmpeg_handling/pyproject.toml new file mode 100644 index 0000000..73f3aac --- /dev/null +++ b/ffmpeg_handling/pyproject.toml @@ -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 } diff --git a/ffmpeg_handling/src/ffmpeg_handling/__init__.py b/ffmpeg_handling/src/ffmpeg_handling/__init__.py new file mode 100644 index 0000000..030ae36 --- /dev/null +++ b/ffmpeg_handling/src/ffmpeg_handling/__init__.py @@ -0,0 +1,6 @@ +"""FFmpeg media processing commands.""" + +from .argparse_builder import build_parser +from .cli import main + +__all__ = ["build_parser", "main"] diff --git a/ffmpeg_handling/src/ffmpeg_handling/__main__.py b/ffmpeg_handling/src/ffmpeg_handling/__main__.py new file mode 100644 index 0000000..e399d86 --- /dev/null +++ b/ffmpeg_handling/src/ffmpeg_handling/__main__.py @@ -0,0 +1,5 @@ +import sys + +from ffmpeg_handling.cli import main + +sys.exit(main()) diff --git a/ffmpeg_handling/src/ffmpeg_handling/argparse_builder.py b/ffmpeg_handling/src/ffmpeg_handling/argparse_builder.py new file mode 100644 index 0000000..2ee6f23 --- /dev/null +++ b/ffmpeg_handling/src/ffmpeg_handling/argparse_builder.py @@ -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 diff --git a/ffmpeg_handling/src/ffmpeg_handling/audio_commands.py b/ffmpeg_handling/src/ffmpeg_handling/audio_commands.py new file mode 100644 index 0000000..e1bdbdb --- /dev/null +++ b/ffmpeg_handling/src/ffmpeg_handling/audio_commands.py @@ -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) diff --git a/ffmpeg_handling/src/ffmpeg_handling/cli.py b/ffmpeg_handling/src/ffmpeg_handling/cli.py new file mode 100755 index 0000000..f7dc28a --- /dev/null +++ b/ffmpeg_handling/src/ffmpeg_handling/cli.py @@ -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()) diff --git a/ffmpeg_handling/src/ffmpeg_handling/helpers.py b/ffmpeg_handling/src/ffmpeg_handling/helpers.py new file mode 100644 index 0000000..563f5b5 --- /dev/null +++ b/ffmpeg_handling/src/ffmpeg_handling/helpers.py @@ -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\d+)h)?(?:(?P\d+)m)?(?:(?P\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", +] diff --git a/ffmpeg_handling/src/ffmpeg_handling/metadata_commands.py b/ffmpeg_handling/src/ffmpeg_handling/metadata_commands.py new file mode 100644 index 0000000..a541aa3 --- /dev/null +++ b/ffmpeg_handling/src/ffmpeg_handling/metadata_commands.py @@ -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" diff --git a/ffmpeg_handling/src/ffmpeg_handling/run_test.py b/ffmpeg_handling/src/ffmpeg_handling/run_test.py new file mode 100755 index 0000000..d856b8f --- /dev/null +++ b/ffmpeg_handling/src/ffmpeg_handling/run_test.py @@ -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) diff --git a/ffmpeg_handling/src/ffmpeg_handling/video_commands.py b/ffmpeg_handling/src/ffmpeg_handling/video_commands.py new file mode 100644 index 0000000..71739a0 --- /dev/null +++ b/ffmpeg_handling/src/ffmpeg_handling/video_commands.py @@ -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) diff --git a/ffmpeg_handling/tests/__init__.py b/ffmpeg_handling/tests/__init__.py new file mode 100644 index 0000000..e386396 --- /dev/null +++ b/ffmpeg_handling/tests/__init__.py @@ -0,0 +1 @@ +"""Tests for the ffmpeg_handling command-line tool.""" diff --git a/ffmpeg_handling/tests/test_cli.py b/ffmpeg_handling/tests/test_cli.py new file mode 100644 index 0000000..8ddffa7 --- /dev/null +++ b/ffmpeg_handling/tests/test_cli.py @@ -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() diff --git a/ffmpeg_handling/tests/test_helpers.py b/ffmpeg_handling/tests/test_helpers.py new file mode 100644 index 0000000..c47d794 --- /dev/null +++ b/ffmpeg_handling/tests/test_helpers.py @@ -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() diff --git a/ffmpeg_handling/tests/test_media_commands.py b/ffmpeg_handling/tests/test_media_commands.py new file mode 100644 index 0000000..4fb3fef --- /dev/null +++ b/ffmpeg_handling/tests/test_media_commands.py @@ -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() diff --git a/pyproject.toml b/pyproject.toml index d918f2b..1929901 100755 --- a/pyproject.toml +++ b/pyproject.toml @@ -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", +]