| | import os |
| | import subprocess |
| | import re |
| | from pathlib import Path |
| |
|
| | def get_video_dimensions(file_path: str) -> tuple[int, int] | None: |
| | """Extract original video width and height from HandBrakeCLI --scan output.""" |
| | try: |
| | |
| | result = subprocess.run( |
| | ["HandBrakeCLI", "-i", file_path, "--scan"], |
| | stderr=subprocess.PIPE, |
| | stdout=subprocess.PIPE, |
| | text=True |
| | ) |
| | output = result.stderr + result.stdout |
| |
|
| | |
| | match = re.search(r"\+ size:\s*(\d+)x(\d+)", output) |
| | if match: |
| | width = int(match.group(1)) |
| | height = int(match.group(2)) |
| | return width, height |
| | else: |
| | raise RuntimeError("Could not parse width and height from HandBrakeCLI output.") |
| | except Exception as e: |
| | print(f"[ERROR] Failed to get dimensions for {file_path}: {e}") |
| |
|
| | def process_video(file_path: str, qualities=range(40, 11, -2)): |
| | """Process a video at multiple quality levels, scaling to 0.25x width.""" |
| | width,height = get_video_dimensions(file_path) |
| | if width is None or height is None: |
| | return |
| |
|
| | new_width = width // 4 |
| | new_height = height // 4 |
| | print(f"Original width = {width}, new width = {new_width}") |
| | print(f"Original height = {height}, new width = {new_height}") |
| |
|
| | |
| | out_dir = Path("processed") |
| | out_dir.mkdir(exist_ok=True) |
| |
|
| | base_name = Path(file_path).stem |
| | for q in qualities: |
| | out_file = out_dir / f"{base_name}_{q}.mp4" |
| | print(f"Encoding {file_path} → {out_file} (quality={q})") |
| |
|
| | cmd = [ |
| | "HandBrakeCLI", |
| | "-i", file_path, |
| | "-o", str(out_file), |
| | "-q", str(q), |
| | "--width", str(new_width), |
| | "--height", str(new_height) |
| | ] |
| | subprocess.run(cmd, check=True) |
| |
|
| | def main(): |
| | |
| | for file in Path(".").glob("*.mp4"): |
| | print(f"\n=== Processing {file} ===") |
| | process_video(str(file)) |
| |
|
| | if __name__ == "__main__": |
| | main() |