File size: 5,502 Bytes
0a4deb9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | #!/usr/bin/env python3
import argparse
import os
import subprocess
from pathlib import Path
VIDEO_EXTS = {".mp4", ".mov", ".mkv", ".avi", ".webm", ".m4v"}
def run_cmd(cmd):
return subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
def get_duration_seconds(video_path: Path) -> float:
cmd = [
"ffprobe",
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"default=noprint_wrappers=1:nokey=1",
str(video_path),
]
out = run_cmd(cmd).stdout.strip()
return float(out)
def has_audio_stream(video_path: Path) -> bool:
cmd = [
"ffprobe",
"-v",
"error",
"-select_streams",
"a:0",
"-show_entries",
"stream=index",
"-of",
"csv=p=0",
str(video_path),
]
out = run_cmd(cmd).stdout.strip()
return bool(out)
def make_delay_plus_2s(src: Path, dst: Path, duration: float):
# Delay audio by 2s; keep final duration unchanged.
cmd = [
"ffmpeg",
"-y",
"-i",
str(src),
"-map",
"0:v:0",
"-map",
"0:a:0",
"-c:v",
"copy",
"-af",
f"adelay=2000:all=1,atrim=0:{duration}",
"-c:a",
"aac",
str(dst),
]
run_cmd(cmd)
def make_advance_minus_2s(src: Path, dst: Path, duration: float):
# Advance audio by 2s; the last 2s become silence.
cmd = [
"ffmpeg",
"-y",
"-i",
str(src),
"-map",
"0:v:0",
"-map",
"0:a:0",
"-c:v",
"copy",
"-af",
f"atrim=start=2,asetpts=PTS-STARTPTS,apad=pad_dur=2,atrim=0:{duration}",
"-c:a",
"aac",
str(dst),
]
run_cmd(cmd)
def iter_videos(root: Path):
for dirpath, _, filenames in os.walk(root):
for name in filenames:
p = Path(dirpath) / name
if p.suffix.lower() in VIDEO_EXTS:
yield p
def purge_directory(root: Path):
if not root.exists():
return
for dirpath, _, filenames in os.walk(root):
for name in filenames:
(Path(dirpath) / name).unlink()
def main():
parser = argparse.ArgumentParser(
description="Generate +2s delay and -2s advance audio versions for all videos."
)
parser.add_argument(
"--input-dir",
default="/home/ubuntu/uag_oops_data/uag_oops",
help="Source video directory.",
)
parser.add_argument(
"--out-delay-dir",
default="/home/ubuntu/uag_oops_data/delay",
help="Output directory for +2s delay versions.",
)
parser.add_argument(
"--out-advance-dir",
default="/home/ubuntu/uag_oops_data/early",
help="Output directory for -2s advance versions.",
)
parser.add_argument(
"--overwrite",
action="store_true",
help="Overwrite output if file exists.",
)
parser.add_argument(
"--no-purge-output",
action="store_true",
help="Do not purge output directories before generation.",
)
args = parser.parse_args()
input_dir = Path(args.input_dir)
out_delay_dir = Path(args.out_delay_dir)
out_advance_dir = Path(args.out_advance_dir)
if not input_dir.exists():
raise FileNotFoundError(f"Input directory not found: {input_dir}")
videos = sorted(iter_videos(input_dir))
if not videos:
print(f"No videos found in: {input_dir}")
return
out_delay_dir.mkdir(parents=True, exist_ok=True)
out_advance_dir.mkdir(parents=True, exist_ok=True)
purge_output = not args.no_purge_output
if purge_output:
print("Purging output directories first...")
purge_directory(out_delay_dir)
purge_directory(out_advance_dir)
print(f"Found {len(videos)} videos.")
skipped_no_audio = 0
processed = 0
for idx, src in enumerate(videos, start=1):
rel = src.relative_to(input_dir)
delay_name = f"{rel.stem}_delay2s{rel.suffix}"
advance_name = f"{rel.stem}_early2s{rel.suffix}"
dst_delay = out_delay_dir / rel.parent / delay_name
dst_advance = out_advance_dir / rel.parent / advance_name
dst_delay.parent.mkdir(parents=True, exist_ok=True)
dst_advance.parent.mkdir(parents=True, exist_ok=True)
if (not args.overwrite) and dst_delay.exists() and dst_advance.exists():
print(f"[{idx}/{len(videos)}] Skip existing: {rel}")
continue
if not has_audio_stream(src):
skipped_no_audio += 1
print(f"[{idx}/{len(videos)}] Skip no-audio: {rel}")
continue
duration = get_duration_seconds(src)
print(f"[{idx}/{len(videos)}] Processing: {rel}")
try:
if args.overwrite or not dst_delay.exists():
make_delay_plus_2s(src, dst_delay, duration)
if args.overwrite or not dst_advance.exists():
make_advance_minus_2s(src, dst_advance, duration)
processed += 1
except subprocess.CalledProcessError as exc:
print(f" Failed: {rel}")
print(exc.stderr[-500:])
print("\nDone.")
print(f"Processed videos: {processed}")
print(f"Skipped no-audio: {skipped_no_audio}")
print(f"Delay output dir: {out_delay_dir}")
print(f"Advance output dir: {out_advance_dir}")
if __name__ == "__main__":
main()
|