#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 视频去重批处理工具 对输入视频做随机组合的二次处理(镜像/裁剪缩放/边框/调色/变速/帧率微调), 并重编码、清除原元数据,使输出在文件哈希、视觉指纹、音频指纹层面均与原片不同。 用法示例: python video_dedup.py # 处理当前目录 → ./去重输出 python video_dedup.py -i 素材 -o 成品 -p strong python video_dedup.py -i a.mp4 --hw # 单文件,NVENC 硬件编码 """ import argparse import csv import json import random import subprocess import sys from datetime import datetime, timedelta from pathlib import Path VIDEO_EXTS = {'.mp4', '.mov', '.mkv', '.avi', '.flv', '.wmv', '.ts', '.m4v', '.webm', '.mpg', '.mpeg'} # 各档位:各变换的启用概率与参数范围 PRESETS = { 'light': dict( p_hflip=0.5, p_crop=0.6, crop=(0.015, 0.03), p_eq=0.7, bright=0.015, contr=(0.98, 1.02), sat=(0.96, 1.04), gam=(0.98, 1.02), p_speed=0.6, speed=(0.96, 1.04), p_pad=0.0, p_fps=0.0, ), 'medium': dict( p_hflip=0.7, p_crop=0.8, crop=(0.03, 0.05), p_eq=0.9, bright=0.03, contr=(0.95, 1.05), sat=(0.92, 1.08), gam=(0.96, 1.04), p_speed=0.8, speed=(0.93, 1.07), p_pad=0.3, p_fps=0.0, ), 'strong': dict( p_hflip=0.9, p_crop=1.0, crop=(0.05, 0.09), p_eq=1.0, bright=0.05, contr=(0.92, 1.08), sat=(0.88, 1.12), gam=(0.94, 1.06), p_speed=1.0, speed=(0.90, 1.10), p_pad=0.5, p_fps=0.8, ), } def run(cmd, **kw): return subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='replace', **kw) def probe(path: Path) -> dict: r = run(['ffprobe', '-v', 'error', '-print_format', 'json', '-show_streams', '-show_format', str(path)]) if r.returncode != 0: raise RuntimeError(f'ffprobe 失败: {r.stderr.strip()[:200]}') info = json.loads(r.stdout) v = next((s for s in info['streams'] if s.get('codec_type') == 'video'), None) if v is None: raise RuntimeError('找不到视频流') has_audio = any(s.get('codec_type') == 'audio' for s in info['streams']) w, h = int(v['width']), int(v['height']) for sd in v.get('side_data_list') or []: if 'rotation' in sd: # 手机竖拍视频常见旋转元数据,实际显示尺寸要互换 if abs(int(sd['rotation'])) in (90, 270): w, h = h, w break fps = None num, _, den = (v.get('avg_frame_rate') or '0').partition('/') try: if int(den) > 0: fps = int(num) / int(den) except ValueError: pass dur = float(info['format'].get('duration', 0) or 0) return dict(w=w, h=h, has_audio=has_audio, fps=fps, dur=dur) def build_transform(rng: random.Random, cfg: dict, w: int, h: int, has_audio: bool, fps): """按档位概率随机组合滤镜,返回 (vf滤镜列表, af滤镜或None, 变换记录dict)""" t = {} vf = [] if rng.random() < cfg['p_hflip']: vf.append('hflip') t['镜像'] = '是' if rng.random() < cfg['p_crop']: f = rng.uniform(*cfg['crop']) cw, ch = int(w * (1 - f)), int(h * (1 - f)) x, y = rng.randint(0, w - cw), rng.randint(0, h - ch) vf.append(f'crop={cw}:{ch}:{x}:{y}') t['裁剪'] = f'{f * 100:.1f}%' if rng.random() < cfg['p_pad']: # 内容缩小后加黑边,再放回原尺寸 p = rng.uniform(0.01, 0.025) vf.append(f'scale={int(w * (1 - 2 * p))}:{int(h * (1 - 2 * p))}') vf.append(f'pad={w}:{h}:(ow-iw)/2:(oh-ih)/2:black') t['边框'] = f'{p * 100:.1f}%' vf.append(f'scale={w}:{h}') # 无论前面怎么变,统一回到原始尺寸 vf.append('setsar=1') if rng.random() < cfg['p_eq']: b = rng.uniform(-cfg['bright'], cfg['bright']) c = rng.uniform(*cfg['contr']) s = rng.uniform(*cfg['sat']) g = rng.uniform(*cfg['gam']) vf.append(f'eq=brightness={b:.3f}:contrast={c:.3f}:saturation={s:.3f}:gamma={g:.3f}') t['调色'] = f'亮度{b:+.3f} 对比{c:.2f} 饱和{s:.2f} γ{g:.2f}' af = None if rng.random() < cfg['p_speed']: sp = rng.uniform(*cfg['speed']) vf.append(f'setpts=PTS/{sp:.4f}') if has_audio: af = f'atempo={sp:.4f}' t['变速'] = f'{sp:.3f}x' if fps and rng.random() < cfg['p_fps']: nf = fps + rng.choice((-1, 1)) * rng.uniform(0.4, 1.2) vf.append(f'fps={nf:.2f}') t['帧率'] = f'{fps:.2f}→{nf:.2f}' return vf, af, t def main(): ap = argparse.ArgumentParser( description='视频去重批处理工具:随机组合二次处理,改变文件哈希与视听指纹', formatter_class=argparse.RawDescriptionHelpFormatter, epilog='示例:\n' ' python video_dedup.py -i 素材 -o 成品 -p strong\n' ' python video_dedup.py -i a.mp4 --hw --same-name') ap.add_argument('-i', '--input', default='.', help='输入文件或目录(默认当前目录)') ap.add_argument('-o', '--output', help='输出目录(默认 输入目录/去重输出)') ap.add_argument('-p', '--preset', choices=list(PRESETS), default='medium', help='处理强度: light/medium/strong(默认 medium)') ap.add_argument('--seed', type=int, help='随机种子(指定后可复现同一批参数)') ap.add_argument('--crf', type=int, default=19, help='CPU 编码质量,默认 19(越小越清晰、文件越大)') ap.add_argument('--enc-preset', default='veryfast', help='x264 速度档,默认 veryfast') ap.add_argument('--hw', action='store_true', help='用 NVIDIA NVENC 硬件编码(快很多,需 N 卡)') ap.add_argument('--overlay', help='叠加一张半透明图片覆盖全画面(可配合 --overlay-alpha)') ap.add_argument('--overlay-alpha', type=float, default=0.05, help='叠加图层不透明度 0~1,默认 0.05(即 5%% 混合,肉眼近无感)') ap.add_argument('--same-name', action='store_true', help='输出保持原文件名(默认追加随机后缀)') args = ap.parse_args() sys.stdout.reconfigure(encoding='utf-8', errors='replace') inp = Path(args.input) if inp.is_file(): files = [inp] in_dir = inp.parent else: in_dir = inp files = sorted(p for p in in_dir.iterdir() if p.is_file() and p.suffix.lower() in VIDEO_EXTS) out_dir = Path(args.output) if args.output else in_dir / '去重输出' out_dir_resolved = out_dir.resolve() files = [f for f in files if out_dir_resolved not in f.resolve().parents] if not files: print(f'输入中没有找到视频文件: {in_dir.resolve()}') sys.exit(1) out_dir.mkdir(parents=True, exist_ok=True) rng = random.Random(args.seed) cfg = PRESETS[args.preset] report_path = out_dir / '处理报告.csv' fields = ['文件名', '输出名', '状态', '原分辨率', '原时长(s)', '新时长(s)', '镜像', '裁剪', '边框', '调色', '变速', '帧率', '叠加图层'] rows, ok, fail = [], 0, 0 print(f'共 {len(files)} 个视频,档位 {args.preset},输出 → {out_dir.resolve()}\n') for f in files: row = dict.fromkeys(fields, '') row['文件名'] = f.name try: info = probe(f) w, h = info['w'] - info['w'] % 2, info['h'] - info['h'] % 2 vf, af, t = build_transform(rng, cfg, w, h, info['has_audio'], info['fps']) row['原分辨率'] = f"{info['w']}x{info['h']}" row['原时长(s)'] = f"{info['dur']:.1f}" row.update(t) token = '' if args.same_name else '_' + ''.join( rng.choices('abcdefghijkmnpqrstuvwxyz23456789', k=6)) dst = out_dir / (f.stem + token + '.mp4') n = 1 while dst.exists(): n += 1 dst = out_dir / (f.stem + token + f'_{n}.mp4') row['输出名'] = dst.name meta_time = (datetime(2021, 1, 1) + timedelta( seconds=rng.randint(0, 5 * 365 * 86400))).strftime('%Y-%m-%dT%H:%M:%S') cmd = ['ffmpeg', '-y', '-hide_banner', '-loglevel', 'error', '-i', str(f)] if args.overlay: ov = Path(args.overlay) if not ov.is_file(): raise RuntimeError(f'叠加图层不存在: {ov}') cmd += ['-i', str(ov), '-filter_complex', f'[0:v]{",".join(vf)}[base];' f'[1:v]scale={w}:{h},format=rgba,' f'colorchannelmixer=aa={args.overlay_alpha}[ov];' '[base][ov]overlay=0:0[v]', # 静态图,overlay 默认重复末帧铺满全程 '-map', '[v]'] t['叠加图层'] = f'{args.overlay_alpha * 100:.0f}%' else: cmd += ['-vf', ','.join(vf), '-map', '0:v:0'] cmd += ['-map_metadata', '-1', '-metadata', f'creation_time={meta_time}'] if args.hw: cmd += ['-c:v', 'h264_nvenc', '-preset', 'p5', '-rc', 'vbr', '-cq', str(args.crf + 2), '-spatial-aq', '1', '-b:v', '0'] else: cmd += ['-c:v', 'libx264', '-preset', args.enc_preset, '-crf', str(args.crf)] if info['has_audio']: cmd += ['-map', '0:a:0', '-c:a', 'aac', '-b:a', '160k'] if af is not None: cmd += ['-af', af] else: cmd += ['-an'] cmd += ['-pix_fmt', 'yuv420p', '-movflags', '+faststart', str(dst)] r = run(cmd) if r.returncode != 0 and args.hw: # NVENC 不可用时自动回落 CPU print(f' [硬件编码失败,改用 CPU] {r.stderr.strip()[:120]}') i_v = cmd.index('-c:v') cmd = cmd[:i_v] + ['-c:v', 'libx264', '-preset', args.enc_preset, '-crf', str(args.crf)] + cmd[i_v + 7:] r = run(cmd) if r.returncode != 0: raise RuntimeError(r.stderr.strip()[-300:]) new_info = probe(dst) row['新时长(s)'] = f"{new_info['dur']:.1f}" row['状态'] = '成功' ok += 1 desc = ' '.join(f'{k}:{v}' for k, v in t.items()) or '仅重编码+元数据' print(f' ✔ {f.name} → {dst.name} [{desc}]') except Exception as e: row['状态'] = f'失败:{e}' fail += 1 print(f' ✘ {f.name} 失败: {e}') rows.append(row) with open(report_path, 'w', newline='', encoding='utf-8-sig') as fp: writer = csv.DictWriter(fp, fieldnames=fields) writer.writeheader() writer.writerows(rows) print(f'\n完成: 成功 {ok} / 失败 {fail},处理报告 → {report_path.resolve()}') if __name__ == '__main__': main()