nova-bavisbox-assets / encode_to_hapq.py
NilsJohannesson's picture
added python version for more stable 'newest file only' encoding
7ce6d3d
#!/usr/bin/env python3
"""
Batch-encode videos to the Hap family (hap / hap_q / hap_alpha / hap_q_alpha).
Only the newest non-Hap video per folder is encoded.
Outputs are written next to each source file with a Hap suffix in the filename.
"""
import os
import subprocess
import sys
from collections import defaultdict
from pathlib import Path
HAP_FORMAT = os.environ.get("HAP_FORMAT", "hap")
HAP_COMPRESSOR = os.environ.get("HAP_COMPRESSOR", "snappy")
FFMPEG_THREADS = os.environ.get("FFMPEG_THREADS", "0")
RED = "\033[0;31m"
GREEN = "\033[0;32m"
YELLOW = "\033[1;33m"
NC = "\033[0m"
VIDEO_EXTENSIONS = {".mp4", ".mov", ".avi", ".mkv", ".m4v", ".flv", ".wmv"}
HAP_SUFFIXES = ("_hap", "_hapq", "_hapalpha", "_hapqalpha")
FORMAT_TO_SUFFIX = {
"hap": "hap",
"hap_q": "hapq",
"hap_alpha": "hapalpha",
"hap_q_alpha": "hapqalpha",
}
def find_newest_per_folder(root: Path) -> list[Path]:
"""Group non-Hap video files by folder, return only the newest from each."""
folders: dict[Path, list[Path]] = defaultdict(list)
for path in root.rglob("*"):
if not path.is_file():
continue
if path.suffix.lower() not in VIDEO_EXTENSIONS:
continue
if path.stem.endswith(HAP_SUFFIXES):
continue
folders[path.parent].append(path)
newest = []
for folder, files in sorted(folders.items()):
files.sort(key=lambda f: f.stat().st_mtime, reverse=True)
newest.append(files[0])
if len(files) > 1:
skipped = [f.name for f in files[1:]]
print(
f"{YELLOW}[{folder}] Picking newest: {files[0].name}, "
f"skipping {len(skipped)} older: {', '.join(skipped)}{NC}"
)
return newest
def encode_video(input_file: Path, suffix: str) -> bool:
output_file = input_file.parent / f"{input_file.stem}_{suffix}.mov"
if output_file.exists():
print(f"{YELLOW}Skipping {input_file} - output already exists{NC}")
return True
print(f"{GREEN}Encoding: {input_file}{NC}")
print(f" Output: {output_file}")
result = subprocess.run(
[
"ffmpeg",
"-nostdin",
"-threads",
FFMPEG_THREADS,
"-i",
str(input_file),
"-vf",
"pad=ceil(iw/4)*4:ceil(ih/4)*4",
"-c:v",
"hap",
"-format",
HAP_FORMAT,
"-compressor",
HAP_COMPRESSOR,
"-an",
"-y",
str(output_file),
],
)
if result.returncode == 0:
print(f"{GREEN} Success{NC}")
return True
else:
print(f"{RED} Failed{NC}")
return False
def main():
if HAP_FORMAT not in FORMAT_TO_SUFFIX:
print(
f"{RED}Error: Unsupported HAP_FORMAT='{HAP_FORMAT}' "
f"(use hap|hap_q|hap_alpha|hap_q_alpha){NC}"
)
sys.exit(1)
if HAP_COMPRESSOR not in ("snappy", "none"):
print(
f"{RED}Error: Unsupported HAP_COMPRESSOR='{HAP_COMPRESSOR}' "
f"(use snappy|none){NC}"
)
sys.exit(1)
try:
subprocess.run(["ffmpeg", "-version"], capture_output=True, check=True)
except (FileNotFoundError, subprocess.CalledProcessError):
print(f"{RED}Error: ffmpeg is not installed or not in PATH{NC}")
sys.exit(1)
suffix = FORMAT_TO_SUFFIX[HAP_FORMAT]
root = Path(".")
print(f"{GREEN}Searching for video files (newest per folder)...{NC}")
print()
candidates = find_newest_per_folder(root)
if not candidates:
print(f"{YELLOW}No video files found.{NC}")
return
print()
success = 0
failed = 0
for file in candidates:
if encode_video(file, suffix):
success += 1
else:
failed += 1
print()
print(f"{GREEN}{'=' * 40}{NC}")
print(f"{GREEN}Encoding complete!{NC}")
print(f"Folders processed: {len(candidates)}")
print(f"{GREEN}Successfully encoded: {success}{NC}")
if failed > 0:
print(f"{RED}Failed: {failed}{NC}")
print(f"{GREEN}{'=' * 40}{NC}")
if __name__ == "__main__":
main()