vcmp exclude criteria
This commit is contained in:
1 parent
11f162c91a
commit
c66260ee69
1 file changed
+80
-12
@@ -5,6 +5,10 @@ import subprocess
|
|||||||
import shutil
|
import shutil
|
||||||
import sys
|
import sys
|
||||||
import argparse
|
import argparse
|
||||||
|
import fnmatch
|
||||||
|
import functools
|
||||||
|
import json
|
||||||
|
import re
|
||||||
import tempfile
|
import tempfile
|
||||||
import logging
|
import logging
|
||||||
from logging.handlers import RotatingFileHandler
|
from logging.handlers import RotatingFileHandler
|
||||||
@@ -14,6 +18,7 @@ from tqdm import tqdm
|
|||||||
|
|
||||||
video_extensions: list[str] = ["mp4", "mkv", "avi", "wmv", "mov", "m4v", "ts", "flv", "mpg", "webm"]
|
video_extensions: list[str] = ["mp4", "mkv", "avi", "wmv", "mov", "m4v", "ts", "flv", "mpg", "webm"]
|
||||||
embedded_sub_extensions: list[str] = ["mkv"]
|
embedded_sub_extensions: list[str] = ["mkv"]
|
||||||
|
vr_filename_token = re.compile(r"vr|vr180|vr360|180|360|180x180|360x180|lr|tb|sbs|3dh|3dv|eac360|mkx\d+|vrca\d+|fisheye\d*")
|
||||||
|
|
||||||
total_files: int = 0
|
total_files: int = 0
|
||||||
|
|
||||||
@@ -152,12 +157,59 @@ def clean_directory(directory_path: pathlib.Path) -> None:
|
|||||||
else:
|
else:
|
||||||
item.unlink() # Yeet the file
|
item.unlink() # Yeet the file
|
||||||
|
|
||||||
|
def is_excluded(path: pathlib.Path, root: pathlib.Path, patterns: list[str]) -> bool:
|
||||||
|
"""Match patterns against the name or the path relative to root."""
|
||||||
|
rel = path.relative_to(root).as_posix()
|
||||||
|
return any(fnmatch.fnmatch(path.name, p) or fnmatch.fnmatch(rel, p) for p in patterns)
|
||||||
|
|
||||||
|
def walk(root: pathlib.Path, exclude: list[str]):
|
||||||
|
for dirpath, dirnames, filenames in os.walk(root):
|
||||||
|
dirnames[:] = [d for d in dirnames if not is_excluded(pathlib.Path(dirpath) / d, root, exclude)]
|
||||||
|
for filename in filenames:
|
||||||
|
filepath = pathlib.Path(dirpath) / filename
|
||||||
|
if not is_excluded(filepath, root, exclude):
|
||||||
|
yield filepath
|
||||||
|
|
||||||
def is_video(path: pathlib.Path) -> bool:
|
def is_video(path: pathlib.Path) -> bool:
|
||||||
return path.suffix.lower()[1:] in video_extensions
|
return path.suffix.lower()[1:] in video_extensions
|
||||||
|
|
||||||
def is_video_with_embedded_subs(path: pathlib.Path) -> bool:
|
def is_video_with_embedded_subs(path: pathlib.Path) -> bool:
|
||||||
return path.suffix.lower()[1:] in embedded_sub_extensions
|
return path.suffix.lower()[1:] in embedded_sub_extensions
|
||||||
|
|
||||||
|
@functools.lru_cache(maxsize=None)
|
||||||
|
def vr_reason(path: pathlib.Path) -> str | None:
|
||||||
|
tokens = re.split(r"[^a-z0-9]+", path.stem.lower())
|
||||||
|
if any(vr_filename_token.fullmatch(t) for t in tokens):
|
||||||
|
return "filename"
|
||||||
|
|
||||||
|
cmd = [
|
||||||
|
"ffprobe",
|
||||||
|
"-v", "error",
|
||||||
|
"-select_streams", "v:0",
|
||||||
|
"-show_entries", "stream=width,height:stream_side_data",
|
||||||
|
"-of", "json",
|
||||||
|
str(path)
|
||||||
|
]
|
||||||
|
try:
|
||||||
|
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
|
||||||
|
stream = json.loads(result.stdout)["streams"][0]
|
||||||
|
except (subprocess.CalledProcessError, ValueError, KeyError, IndexError):
|
||||||
|
logging.error(f"Error probing {path} for VR")
|
||||||
|
return None
|
||||||
|
|
||||||
|
for side_data in stream.get("side_data_list", []):
|
||||||
|
if side_data.get("side_data_type") == "Spherical Mapping":
|
||||||
|
return "spherical metadata"
|
||||||
|
if side_data.get("side_data_type") == "Stereo 3D" and side_data.get("type") != "2D":
|
||||||
|
return "stereo metadata"
|
||||||
|
|
||||||
|
width, height = stream.get("width", 0), stream.get("height", 0)
|
||||||
|
if height >= 1920:
|
||||||
|
ratio = width / height
|
||||||
|
if abs(ratio - 2) < 0.02 or abs(ratio - 1) < 0.02:
|
||||||
|
return f"{width}x{height} frame"
|
||||||
|
return None
|
||||||
|
|
||||||
def get_video_duration(input_file: pathlib.Path) -> float:
|
def get_video_duration(input_file: pathlib.Path) -> float:
|
||||||
cmd = [
|
cmd = [
|
||||||
"ffprobe",
|
"ffprobe",
|
||||||
@@ -311,15 +363,14 @@ def process_directory(
|
|||||||
temp_dir: pathlib.Path,
|
temp_dir: pathlib.Path,
|
||||||
remove_source: bool = False,
|
remove_source: bool = False,
|
||||||
nice: int = 20,
|
nice: int = 20,
|
||||||
count_only: bool = False
|
count_only: bool = False,
|
||||||
|
exclude: list[str] = [],
|
||||||
|
include_vr: bool = False
|
||||||
) -> int:
|
) -> int:
|
||||||
"""Process all video files in source directory recursively."""
|
"""Process all video files in source directory recursively."""
|
||||||
count = 0
|
count = 0
|
||||||
successful = 0
|
successful = 0
|
||||||
for dirpath, _dirnames, filenames in os.walk(source_dir):
|
for filepath in walk(source_dir, exclude):
|
||||||
for filename in filenames:
|
|
||||||
filepath = pathlib.Path(dirpath) / filename
|
|
||||||
|
|
||||||
# File might have been deleted since starting script
|
# File might have been deleted since starting script
|
||||||
if not filepath.exists() or not is_video(filepath):
|
if not filepath.exists() or not is_video(filepath):
|
||||||
logging.debug(f"Skipping {filepath}: not a video file or doesn't exist")
|
logging.debug(f"Skipping {filepath}: not a video file or doesn't exist")
|
||||||
@@ -337,6 +388,10 @@ def process_directory(
|
|||||||
filepath.unlink()
|
filepath.unlink()
|
||||||
logging.debug(f"Skipping {filepath}: target already exists")
|
logging.debug(f"Skipping {filepath}: target already exists")
|
||||||
continue
|
continue
|
||||||
|
if not include_vr and (reason := vr_reason(filepath)):
|
||||||
|
if not count_only:
|
||||||
|
logging.info(f"Skipping {filepath}: VR video ({reason})")
|
||||||
|
continue
|
||||||
|
|
||||||
count += 1
|
count += 1
|
||||||
if count_only:
|
if count_only:
|
||||||
@@ -353,14 +408,17 @@ def process_subtitles(
|
|||||||
*,
|
*,
|
||||||
source_dir: pathlib.Path,
|
source_dir: pathlib.Path,
|
||||||
destination_dir: pathlib.Path,
|
destination_dir: pathlib.Path,
|
||||||
temp_dir: pathlib.Path):
|
temp_dir: pathlib.Path,
|
||||||
for dirpath, _dirnames, filenames in os.walk(source_dir):
|
exclude: list[str] = [],
|
||||||
for filename in filenames:
|
include_vr: bool = False):
|
||||||
filepath = pathlib.Path(dirpath) / filename
|
for filepath in walk(source_dir, exclude):
|
||||||
# File might have been deleted since starting script
|
# File might have been deleted since starting script
|
||||||
if not filepath.exists() or not is_video_with_embedded_subs(filepath):
|
if not filepath.exists() or not is_video_with_embedded_subs(filepath):
|
||||||
logging.debug(f"Skipping {filepath}: not a video file or doesn't exist")
|
logging.debug(f"Skipping {filepath}: not a video file or doesn't exist")
|
||||||
continue
|
continue
|
||||||
|
if not include_vr and (reason := vr_reason(filepath)):
|
||||||
|
logging.info(f"Skipping {filepath}: VR video ({reason})")
|
||||||
|
continue
|
||||||
if has_subs(filepath):
|
if has_subs(filepath):
|
||||||
target_path = destination_dir / filepath.relative_to(source_dir)
|
target_path = destination_dir / filepath.relative_to(source_dir)
|
||||||
target_path = target_path.with_suffix(".cmp.en.srt")
|
target_path = target_path.with_suffix(".cmp.en.srt")
|
||||||
@@ -394,6 +452,10 @@ def main():
|
|||||||
help='Nice value for process priority (default: 20). Valid values are 0 (highest priority) to 39 (lowest priority). Lower values use more system resources.')
|
help='Nice value for process priority (default: 20). Valid values are 0 (highest priority) to 39 (lowest priority). Lower values use more system resources.')
|
||||||
parser.add_argument('-i', '--ignore-busy', action='store_true',
|
parser.add_argument('-i', '--ignore-busy', action='store_true',
|
||||||
help='Ignore system busy check and run anyway')
|
help='Ignore system busy check and run anyway')
|
||||||
|
parser.add_argument('-x', '--exclude', action='append', default=[], metavar='PATTERN',
|
||||||
|
help='Skip files and directories whose name or path relative to the source matches this glob. Repeatable.')
|
||||||
|
parser.add_argument('--include-vr', action='store_true',
|
||||||
|
help='Also process VR videos, detected by spherical/stereo metadata, filename tags, or a 2:1 or 1:1 frame of at least 1920 high')
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
setup_logging(bool(args.verbose))
|
setup_logging(bool(args.verbose))
|
||||||
@@ -412,7 +474,9 @@ def main():
|
|||||||
if args.sub:
|
if args.sub:
|
||||||
process_subtitles(source_dir=source_dir,
|
process_subtitles(source_dir=source_dir,
|
||||||
destination_dir=destination_dir,
|
destination_dir=destination_dir,
|
||||||
temp_dir=temp_dir)
|
temp_dir=temp_dir,
|
||||||
|
exclude=args.exclude,
|
||||||
|
include_vr=args.include_vr)
|
||||||
else:
|
else:
|
||||||
logging.info(f"Starting video compression from {source_dir} to {destination_dir}")
|
logging.info(f"Starting video compression from {source_dir} to {destination_dir}")
|
||||||
|
|
||||||
@@ -421,7 +485,9 @@ def main():
|
|||||||
source_dir=source_dir,
|
source_dir=source_dir,
|
||||||
destination_dir=destination_dir,
|
destination_dir=destination_dir,
|
||||||
temp_dir=temp_dir,
|
temp_dir=temp_dir,
|
||||||
count_only=True
|
count_only=True,
|
||||||
|
exclude=args.exclude,
|
||||||
|
include_vr=args.include_vr
|
||||||
)
|
)
|
||||||
|
|
||||||
process_directory(
|
process_directory(
|
||||||
@@ -429,7 +495,9 @@ def main():
|
|||||||
destination_dir=destination_dir,
|
destination_dir=destination_dir,
|
||||||
temp_dir=temp_dir,
|
temp_dir=temp_dir,
|
||||||
remove_source=args.remove_source,
|
remove_source=args.remove_source,
|
||||||
nice=args.nice
|
nice=args.nice,
|
||||||
|
exclude=args.exclude,
|
||||||
|
include_vr=args.include_vr
|
||||||
)
|
)
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
Reference in new issue
Block a user