File size: 4,674 Bytes
804301e | 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 | #!/usr/bin/python
#-*- coding: utf-8 -*-
# Example usage:
# python batch_syncnet_mp.py --video_dir /share/zhaohu_workspace/video_gen-hunyuanvideo1.5_tai2v_training/outputs/test_results_step_010400 --output_file results_10400.json --num_workers 4
# python batch_syncnet_mp.py --video_dir /path/to/videos --num_workers 8 --video_ext mp4,avi
import argparse
import os
import glob
import json
from multiprocessing import Pool, current_process
import torch
# ==================== LOAD PARAMS ====================
parser = argparse.ArgumentParser(description="SyncNet Batch Processing with Multiprocessing")
parser.add_argument('--initial_model', type=str, default="data/syncnet_v2.model", help='Path to SyncNet model')
parser.add_argument('--batch_size', type=int, default=20, help='Batch size for processing')
parser.add_argument('--vshift', type=int, default=15, help='Video shift for evaluation')
parser.add_argument('--video_dir', type=str, required=True, help='Directory containing video files')
parser.add_argument('--tmp_dir', type=str, default="data/work/pytmp", help='Temporary directory')
parser.add_argument('--output_file', type=str, default="syncnet_scores.json", help='Output JSON file for results')
parser.add_argument('--video_ext', type=str, default="mp4,avi,mov,mkv", help='Video extensions to process (comma-separated)')
parser.add_argument('--num_workers', type=int, default=4, help='Number of parallel workers')
args = parser.parse_args()
def process_single_video(task):
"""Process a single video file and return the result."""
idx, total, videofile, model_path, batch_size, vshift, tmp_dir = task
video_name = os.path.basename(videofile)
# Import here to avoid issues with multiprocessing
from SyncNetInstance import SyncNetInstance
# Create a unique reference for this process
process_id = current_process().name
reference = f"{os.path.splitext(video_name)[0]}_{process_id}"
# Create opt-like object
class Opt:
pass
opt = Opt()
opt.batch_size = batch_size
opt.vshift = vshift
opt.tmp_dir = tmp_dir
opt.reference = reference
print(f"[{idx+1}/{total}] [{process_id}] Processing: {video_name}")
try:
# Load model for this process
s = SyncNetInstance()
s.loadParameters(model_path)
offset, conf, dists = s.evaluate(opt, videofile=videofile)
result = {
'offset': int(offset),
'confidence': float(conf),
'min_dist': float(dists.min()) if dists is not None else None,
'status': 'success'
}
print(f" [{process_id}] {video_name} -> Offset: {offset}, Confidence: {conf:.3f}")
except Exception as e:
result = {
'offset': None,
'confidence': None,
'min_dist': None,
'status': 'error',
'error_message': str(e)
}
print(f" [{process_id}] {video_name} -> Error: {str(e)}")
return video_name, result
def main():
# ==================== FIND VIDEO FILES ====================
video_extensions = args.video_ext.split(',')
video_files = []
for ext in video_extensions:
video_files.extend(glob.glob(os.path.join(args.video_dir, f'*.{ext.strip()}')))
video_files.extend(glob.glob(os.path.join(args.video_dir, f'*.{ext.strip().upper()}')))
video_files = sorted(list(set(video_files)))
total = len(video_files)
print(f"Found {total} video files to process with {args.num_workers} workers.")
if total == 0:
print("No video files found. Exiting.")
return
# ==================== PREPARE TASKS ====================
tasks = [
(idx, total, vf, args.initial_model, args.batch_size, args.vshift, args.tmp_dir)
for idx, vf in enumerate(video_files)
]
# ==================== PROCESS WITH MULTIPROCESSING ====================
# Use spawn method for CUDA compatibility
torch.multiprocessing.set_start_method('spawn', force=True)
with Pool(processes=args.num_workers) as pool:
results_list = pool.map(process_single_video, tasks)
# ==================== COLLECT RESULTS ====================
results = {video_name: result for video_name, result in results_list}
# ==================== SAVE RESULTS ====================
with open(args.output_file, 'w') as f:
json.dump(results, f, indent=2)
print(f"\nResults saved to {args.output_file}")
# Print summary
successful = sum(1 for r in results.values() if r['status'] == 'success')
print(f"Processed {successful}/{total} videos successfully.")
if __name__ == '__main__':
main()
|