syncnet_compute / syncnet_claude /batch_syncnet_full.py
xingzhaohu's picture
Add files using upload-large-folder tool
d26d563 verified
#!/usr/bin/python
#-*- coding: utf-8 -*-
# Full SyncNet Pipeline: Face Detection -> Tracking -> Cropping -> SyncNet Evaluation
#
# Example usage:
# python batch_syncnet_full.py --video_dir /path/to/videos --output_file results.json
# python batch_syncnet_full.py --video_dir /share/zhaohu_workspace/benchmarks/outputs_benchmark_4/latent_sync --output_file results_latentsync.json
"""
python batch_syncnet_full.py --video_dir /share/zhaohu_workspace/benchmarks/outputs_benchmark_4/latent_sync --output_file results_latentsync.json 2>&1
python batch_syncnet_full.py \
--video_dir /share/zhaohu_workspace/video_gen-hunyuanvideo1.5_tai2v_training/outputs/test_results_step_010800 \
--output_file results_10800.json 2>&1
"""
#
# Prerequisites:
# sh download_model.sh # Download required models first
import sys
import time
import os
import argparse
import pickle
import subprocess
import glob
import cv2
import json
import numpy as np
from shutil import rmtree
import scenedetect
from scenedetect.video_manager import VideoManager
from scenedetect.scene_manager import SceneManager
from scenedetect.stats_manager import StatsManager
from scenedetect.detectors import ContentDetector
from scipy.interpolate import interp1d
from scipy.io import wavfile
from scipy import signal
from detectors import S3FD
from SyncNetInstance import SyncNetInstance
# ==================== PARSE ARGS ====================
parser = argparse.ArgumentParser(description="Full SyncNet Pipeline - Batch Processing")
# Input/Output
parser.add_argument('--video_dir', type=str, required=True, help='Directory containing video files')
parser.add_argument('--output_file', type=str, default='syncnet_results.json', help='Output JSON file')
parser.add_argument('--data_dir', type=str, default='data/work', help='Working directory for intermediate files')
parser.add_argument('--video_ext', type=str, default='mp4,avi,mov,mkv', help='Video extensions (comma-separated)')
# Model paths
parser.add_argument('--syncnet_model', type=str, default='data/syncnet_v2.model', help='SyncNet model path')
# Pipeline parameters
parser.add_argument('--facedet_scale', type=float, default=0.25, help='Scale factor for face detection')
parser.add_argument('--crop_scale', type=float, default=0.40, help='Scale bounding box')
parser.add_argument('--min_track', type=int, default=50, help='Minimum facetrack duration (frames)')
parser.add_argument('--frame_rate', type=int, default=25, help='Frame rate')
parser.add_argument('--num_failed_det', type=int, default=25, help='Missed detections allowed before stopping track')
parser.add_argument('--min_face_size', type=int, default=100, help='Minimum face size in pixels')
# SyncNet parameters
parser.add_argument('--batch_size', type=int, default=20, help='Batch size for SyncNet')
parser.add_argument('--vshift', type=int, default=15, help='Video shift for sync evaluation')
# Cleanup
parser.add_argument('--keep_intermediate', action='store_true', help='Keep intermediate files')
opt = parser.parse_args()
# Setup directories
opt.avi_dir = os.path.join(opt.data_dir, 'pyavi')
opt.tmp_dir = os.path.join(opt.data_dir, 'pytmp')
opt.work_dir = os.path.join(opt.data_dir, 'pywork')
opt.crop_dir = os.path.join(opt.data_dir, 'pycrop')
opt.frames_dir = os.path.join(opt.data_dir, 'pyframes')
# ==================== UTILITY FUNCTIONS ====================
def bb_intersection_over_union(boxA, boxB):
xA = max(boxA[0], boxB[0])
yA = max(boxA[1], boxB[1])
xB = min(boxA[2], boxB[2])
yB = min(boxA[3], boxB[3])
interArea = max(0, xB - xA) * max(0, yB - yA)
boxAArea = (boxA[2] - boxA[0]) * (boxA[3] - boxA[1])
boxBArea = (boxB[2] - boxB[0]) * (boxB[3] - boxB[1])
iou = interArea / float(boxAArea + boxBArea - interArea)
return iou
def track_shot(opt, scenefaces):
iouThres = 0.5
tracks = []
while True:
track = []
for framefaces in scenefaces:
for face in framefaces:
if track == []:
track.append(face)
framefaces.remove(face)
elif face['frame'] - track[-1]['frame'] <= opt.num_failed_det:
iou = bb_intersection_over_union(face['bbox'], track[-1]['bbox'])
if iou > iouThres:
track.append(face)
framefaces.remove(face)
continue
else:
break
if track == []:
break
elif len(track) > opt.min_track:
framenum = np.array([f['frame'] for f in track])
bboxes = np.array([np.array(f['bbox']) for f in track])
frame_i = np.arange(framenum[0], framenum[-1] + 1)
bboxes_i = []
for ij in range(0, 4):
interpfn = interp1d(framenum, bboxes[:, ij])
bboxes_i.append(interpfn(frame_i))
bboxes_i = np.stack(bboxes_i, axis=1)
if max(np.mean(bboxes_i[:, 2] - bboxes_i[:, 0]), np.mean(bboxes_i[:, 3] - bboxes_i[:, 1])) > opt.min_face_size:
tracks.append({'frame': frame_i, 'bbox': bboxes_i})
return tracks
def crop_video(opt, track, cropfile):
flist = glob.glob(os.path.join(opt.frames_dir, opt.reference, '*.jpg'))
flist.sort()
fourcc = cv2.VideoWriter_fourcc(*'XVID')
vOut = cv2.VideoWriter(cropfile + 't.avi', fourcc, opt.frame_rate, (224, 224))
dets = {'x': [], 'y': [], 's': []}
for det in track['bbox']:
dets['s'].append(max((det[3] - det[1]), (det[2] - det[0])) / 2)
dets['y'].append((det[1] + det[3]) / 2)
dets['x'].append((det[0] + det[2]) / 2)
# Smooth detections
dets['s'] = signal.medfilt(dets['s'], kernel_size=13)
dets['x'] = signal.medfilt(dets['x'], kernel_size=13)
dets['y'] = signal.medfilt(dets['y'], kernel_size=13)
for fidx, frame in enumerate(track['frame']):
cs = opt.crop_scale
bs = dets['s'][fidx]
bsi = int(bs * (1 + 2 * cs))
image = cv2.imread(flist[frame])
frame_padded = np.pad(image, ((bsi, bsi), (bsi, bsi), (0, 0)), 'constant', constant_values=(110, 110))
my = dets['y'][fidx] + bsi
mx = dets['x'][fidx] + bsi
face = frame_padded[int(my - bs):int(my + bs * (1 + 2 * cs)), int(mx - bs * (1 + cs)):int(mx + bs * (1 + cs))]
vOut.write(cv2.resize(face, (224, 224)))
audiotmp = os.path.join(opt.tmp_dir, opt.reference, 'audio.wav')
audiostart = (track['frame'][0]) / opt.frame_rate
audioend = (track['frame'][-1] + 1) / opt.frame_rate
vOut.release()
# Crop audio
command = "ffmpeg -y -i %s -ss %.3f -to %.3f %s" % (
os.path.join(opt.avi_dir, opt.reference, 'audio.wav'), audiostart, audioend, audiotmp)
subprocess.call(command, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# Combine audio and video
command = "ffmpeg -y -i %st.avi -i %s -c:v copy -c:a copy %s.avi" % (cropfile, audiotmp, cropfile)
subprocess.call(command, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
os.remove(cropfile + 't.avi')
return {'track': track, 'proc_track': dets}
def inference_video(opt, DET):
flist = glob.glob(os.path.join(opt.frames_dir, opt.reference, '*.jpg'))
flist.sort()
dets = []
for fidx, fname in enumerate(flist):
image = cv2.imread(fname)
image_np = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
bboxes = DET.detect_faces(image_np, conf_th=0.9, scales=[opt.facedet_scale])
dets.append([])
for bbox in bboxes:
dets[-1].append({'frame': fidx, 'bbox': (bbox[:-1]).tolist(), 'conf': bbox[-1]})
return dets
def scene_detect(opt):
video_path = os.path.join(opt.avi_dir, opt.reference, 'video.avi')
video_manager = VideoManager([video_path])
stats_manager = StatsManager()
scene_manager = SceneManager(stats_manager)
scene_manager.add_detector(ContentDetector())
base_timecode = video_manager.get_base_timecode()
video_manager.set_downscale_factor()
video_manager.start()
scene_manager.detect_scenes(frame_source=video_manager)
scene_list = scene_manager.get_scene_list(base_timecode)
if scene_list == []:
scene_list = [(video_manager.get_base_timecode(), video_manager.get_current_timecode())]
return scene_list
def process_single_video(opt, videofile, DET, syncnet):
"""Process a single video through the full pipeline."""
video_name = os.path.basename(videofile)
opt.reference = os.path.splitext(video_name)[0]
# Clean up previous runs
for d in [opt.work_dir, opt.crop_dir, opt.avi_dir, opt.frames_dir, opt.tmp_dir]:
path = os.path.join(d, opt.reference)
if os.path.exists(path):
rmtree(path)
os.makedirs(path, exist_ok=True)
# ========== STEP 1: Convert video and extract frames ==========
# Convert to standard format
command = "ffmpeg -y -i %s -qscale:v 2 -async 1 -r %d %s" % (
videofile, opt.frame_rate, os.path.join(opt.avi_dir, opt.reference, 'video.avi'))
subprocess.call(command, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# Extract frames
command = "ffmpeg -y -i %s -qscale:v 2 -threads 1 -f image2 %s" % (
os.path.join(opt.avi_dir, opt.reference, 'video.avi'),
os.path.join(opt.frames_dir, opt.reference, '%06d.jpg'))
subprocess.call(command, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# Extract audio
command = "ffmpeg -y -i %s -ac 1 -vn -acodec pcm_s16le -ar 16000 %s" % (
os.path.join(opt.avi_dir, opt.reference, 'video.avi'),
os.path.join(opt.avi_dir, opt.reference, 'audio.wav'))
subprocess.call(command, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# Check if frames were extracted
flist = glob.glob(os.path.join(opt.frames_dir, opt.reference, '*.jpg'))
if len(flist) == 0:
return {'status': 'error', 'error_message': 'No frames extracted from video'}
# ========== STEP 2: Face detection ==========
faces = inference_video(opt, DET)
# ========== STEP 3: Scene detection ==========
scene = scene_detect(opt)
# ========== STEP 4: Face tracking ==========
alltracks = []
for shot in scene:
if shot[1].frame_num - shot[0].frame_num >= opt.min_track:
alltracks.extend(track_shot(opt, faces[shot[0].frame_num:shot[1].frame_num]))
if len(alltracks) == 0:
return {'status': 'error', 'error_message': 'No face tracks found'}
# ========== STEP 5: Crop face tracks ==========
vidtracks = []
for ii, track in enumerate(alltracks):
cropfile = os.path.join(opt.crop_dir, opt.reference, '%05d' % ii)
vidtracks.append(crop_video(opt, track, cropfile))
# ========== STEP 6: Run SyncNet on cropped faces ==========
flist = glob.glob(os.path.join(opt.crop_dir, opt.reference, '0*.avi'))
flist.sort()
if len(flist) == 0:
return {'status': 'error', 'error_message': 'No cropped face videos created'}
all_offsets = []
all_confs = []
all_min_dists = []
for fname in flist:
try:
offset, conf, dist = syncnet.evaluate(opt, videofile=fname)
all_offsets.append(int(offset))
all_confs.append(float(conf))
all_min_dists.append(float(dist.min()) if dist is not None else None)
except Exception as e:
print(f" Warning: Failed to evaluate track {fname}: {e}")
if len(all_confs) == 0:
return {'status': 'error', 'error_message': 'SyncNet evaluation failed for all tracks'}
# Aggregate results (use the track with highest confidence)
best_idx = np.argmax(all_confs)
return {
'status': 'success',
'num_tracks': len(alltracks),
'offset': all_offsets[best_idx],
'confidence': all_confs[best_idx],
'min_dist': all_min_dists[best_idx],
'all_offsets': all_offsets,
'all_confidences': all_confs,
'avg_confidence': float(np.mean(all_confs))
}
def cleanup_video(opt):
"""Clean up intermediate files for a video."""
for d in [opt.work_dir, opt.crop_dir, opt.avi_dir, opt.frames_dir, opt.tmp_dir]:
path = os.path.join(d, opt.reference)
if os.path.exists(path):
rmtree(path)
# ==================== MAIN ====================
def main():
print("=" * 60)
print("Full SyncNet Pipeline - Batch Processing")
print("=" * 60)
# Find video files
video_extensions = opt.video_ext.split(',')
video_files = []
for ext in video_extensions:
video_files.extend(glob.glob(os.path.join(opt.video_dir, f'*.{ext.strip()}')))
video_files.extend(glob.glob(os.path.join(opt.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.")
if total == 0:
print("No video files found. Exiting.")
return
# Create working directories
for d in [opt.avi_dir, opt.tmp_dir, opt.work_dir, opt.crop_dir, opt.frames_dir]:
os.makedirs(d, exist_ok=True)
# Load models
print("\nLoading face detector (S3FD)...")
DET = S3FD(device='cuda')
print("Loading SyncNet model...")
syncnet = SyncNetInstance()
syncnet.loadParameters(opt.syncnet_model)
print(f"Model {opt.syncnet_model} loaded.\n")
# Process videos
results = {}
for idx, videofile in enumerate(video_files):
video_name = os.path.basename(videofile)
print(f"[{idx + 1}/{total}] Processing: {video_name}")
try:
result = process_single_video(opt, videofile, DET, syncnet)
results[video_name] = result
if result['status'] == 'success':
print(f" -> Tracks: {result['num_tracks']}, Offset: {result['offset']}, "
f"Confidence: {result['confidence']:.3f}, Avg Conf: {result['avg_confidence']:.3f}")
else:
print(f" -> Error: {result['error_message']}")
except Exception as e:
results[video_name] = {'status': 'error', 'error_message': str(e)}
print(f" -> Error: {str(e)}")
# Cleanup intermediate files
if not opt.keep_intermediate:
cleanup_video(opt)
# Summary statistics
successful = sum(1 for r in results.values() if r['status'] == 'success')
summary = {
'total_videos': total,
'successful': successful,
'failed': total - successful,
}
if successful > 0:
confs = [r['confidence'] for r in results.values() if r['status'] == 'success']
offsets = [r['offset'] for r in results.values() if r['status'] == 'success']
min_dists = [r['min_dist'] for r in results.values() if r['status'] == 'success' and r['min_dist'] is not None]
summary['avg_confidence'] = float(np.mean(confs))
summary['min_confidence'] = float(np.min(confs))
summary['max_confidence'] = float(np.max(confs))
summary['std_confidence'] = float(np.std(confs))
summary['avg_offset'] = float(np.mean(offsets))
summary['avg_min_dist'] = float(np.mean(min_dists)) if min_dists else None
# Save results with summary
output = {
'summary': summary,
'videos': results
}
with open(opt.output_file, 'w') as f:
json.dump(output, f, indent=2)
print("\n" + "=" * 60)
print(f"Results saved to {opt.output_file}")
print("=" * 60)
# Print summary
print(f"\n[SUMMARY]")
print(f"Processed {successful}/{total} videos successfully.")
if successful > 0:
print(f"\nConfidence scores:")
print(f" Average: {summary['avg_confidence']:.3f}")
print(f" Std: {summary['std_confidence']:.3f}")
print(f" Min: {summary['min_confidence']:.3f}")
print(f" Max: {summary['max_confidence']:.3f}")
print(f"\nAverage offset: {summary['avg_offset']:.2f}")
if summary['avg_min_dist'] is not None:
print(f"Average min_dist: {summary['avg_min_dist']:.3f}")
if __name__ == '__main__':
main()