import numpy as np import torch from PIL import Image SYNCNET_HF_REPO = "lithiumice/syncnet" SYNCNET_HF_FILENAME = "syncnet_v2.model" SYNCNET_T = 5 SYNCNET_IMG_SIZE = 224 SYNCNET_MFCC = 13 # MFCC cepstra; the v2 audio CNN collapses 13 freq bins to 1 SYNCNET_MFCC_HOP = 160 # 10ms @ 16kHz (100 fps) SYNCNET_MFCC_WIN = 20 # 100fps mfcc frames per 5-frame window (0.2s), joonson convention SYNCNET_AUDIO_SR = 16000 SYNCNET_SAMPLES_PER_FRAME = 640 # 16000 / 25fps _SYNCNET_MODEL = None _FACE_CASCADE = None def _resolve_device(device=None): if device is not None: return device return "cuda" if torch.cuda.is_available() else "cpu" class SyncNetV2(torch.nn.Module): """Audio-visual SyncNet v2 (joonson/syncnet_python architecture, 1024-d embeddings). The published `syncnet_v2.model` checkpoint (HF: lithiumice/syncnet) uses this layout: an MFCC audio CNN (`netcnnaud` + `netfcaud`) and a 3D-convolutional lip/video encoder (`netcnnlip` + `netfclip`). """ def __init__(self, num_layers_in_fc_layers=1024): super().__init__() self.netcnnaud = torch.nn.Sequential( torch.nn.Conv2d(1, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)), torch.nn.BatchNorm2d(64), torch.nn.ReLU(inplace=True), torch.nn.MaxPool2d(kernel_size=(1, 1), stride=(1, 1)), torch.nn.Conv2d(64, 192, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)), torch.nn.BatchNorm2d(192), torch.nn.ReLU(inplace=True), torch.nn.MaxPool2d(kernel_size=(3, 3), stride=(1, 2)), torch.nn.Conv2d(192, 384, kernel_size=(3, 3), padding=(1, 1)), torch.nn.BatchNorm2d(384), torch.nn.ReLU(inplace=True), torch.nn.Conv2d(384, 256, kernel_size=(3, 3), padding=(1, 1)), torch.nn.BatchNorm2d(256), torch.nn.ReLU(inplace=True), torch.nn.Conv2d(256, 256, kernel_size=(3, 3), padding=(1, 1)), torch.nn.BatchNorm2d(256), torch.nn.ReLU(inplace=True), torch.nn.MaxPool2d(kernel_size=(3, 3), stride=(2, 2)), torch.nn.Conv2d(256, 512, kernel_size=(5, 4), padding=(0, 0)), torch.nn.BatchNorm2d(512), torch.nn.ReLU(inplace=True), ) self.netfcaud = torch.nn.Sequential( torch.nn.Linear(512, 512), torch.nn.BatchNorm1d(512), torch.nn.ReLU(inplace=True), torch.nn.Linear(512, num_layers_in_fc_layers), ) self.netfclip = torch.nn.Sequential( torch.nn.Linear(512, 512), torch.nn.BatchNorm1d(512), torch.nn.ReLU(inplace=True), torch.nn.Linear(512, num_layers_in_fc_layers), ) self.netcnnlip = torch.nn.Sequential( torch.nn.Conv3d(3, 96, kernel_size=(5, 7, 7), stride=(1, 2, 2), padding=0), torch.nn.BatchNorm3d(96), torch.nn.ReLU(inplace=True), torch.nn.MaxPool3d(kernel_size=(1, 3, 3), stride=(1, 2, 2)), torch.nn.Conv3d(96, 256, kernel_size=(1, 5, 5), stride=(1, 2, 2), padding=(0, 1, 1)), torch.nn.BatchNorm3d(256), torch.nn.ReLU(inplace=True), torch.nn.MaxPool3d(kernel_size=(1, 3, 3), stride=(1, 2, 2), padding=(0, 1, 1)), torch.nn.Conv3d(256, 256, kernel_size=(1, 3, 3), padding=(0, 1, 1)), torch.nn.BatchNorm3d(256), torch.nn.ReLU(inplace=True), torch.nn.Conv3d(256, 256, kernel_size=(1, 3, 3), padding=(0, 1, 1)), torch.nn.BatchNorm3d(256), torch.nn.ReLU(inplace=True), torch.nn.Conv3d(256, 256, kernel_size=(1, 3, 3), padding=(0, 1, 1)), torch.nn.BatchNorm3d(256), torch.nn.ReLU(inplace=True), torch.nn.MaxPool3d(kernel_size=(1, 3, 3), stride=(1, 2, 2)), torch.nn.Conv3d(256, 512, kernel_size=(1, 6, 6), padding=0), torch.nn.BatchNorm3d(512), torch.nn.ReLU(inplace=True), ) def forward_aud(self, x): mid = self.netcnnaud(x) mid = mid.view(mid.size(0), -1) return self.netfcaud(mid) def forward_lip(self, x): mid = self.netcnnlip(x) mid = mid.view(mid.size(0), -1) return self.netfclip(mid) # Backward-compatible alias (originally planned as the Wav2Lip SyncNet_color class; # the lithiumice/syncnet checkpoint ships the SyncNet v2 architecture above). SyncNetColor = SyncNetV2 def _download_syncnet_weights(): from huggingface_hub import hf_hub_download return hf_hub_download(repo_id=SYNCNET_HF_REPO, filename=SYNCNET_HF_FILENAME) def _load_syncnet(device=None): global _SYNCNET_MODEL if _SYNCNET_MODEL is None: device = _resolve_device(device) weights_path = _download_syncnet_weights() model = SyncNetV2() state_dict = torch.load(weights_path, map_location="cpu") state_dict = {k.replace("module.", "", 1) if k.startswith("module.") else k: v for k, v in state_dict.items()} model.load_state_dict(state_dict) model = model.eval().to(device) _SYNCNET_MODEL = model return _SYNCNET_MODEL def _get_face_cascade(): global _FACE_CASCADE if _FACE_CASCADE is None: import cv2 _FACE_CASCADE = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml") return _FACE_CASCADE def _resample_audio(audio, sample_rate): import torchaudio if isinstance(audio, np.ndarray): audio = torch.from_numpy(audio) if audio.ndim == 1: audio = audio.unsqueeze(0) if audio.ndim > 2: audio = audio.reshape(-1, audio.shape[-1]) audio = audio.float() if sample_rate != SYNCNET_AUDIO_SR: audio = torchaudio.functional.resample(audio, sample_rate, SYNCNET_AUDIO_SR) return audio.mean(dim=0) def compute_mfcc_features(audio, sample_rate=SYNCNET_AUDIO_SR): """MFCC front-end for SyncNet v2: 16kHz, 13 cepstra, win=400, hop=160, preemphasis 0.97 (python_speech_features conventions).""" import torchaudio wav = _resample_audio(audio, sample_rate).numpy() wav = np.append(wav[0], wav[1:] - 0.97 * wav[:-1]).astype(np.float32) wav = torch.from_numpy(wav) mfcc = torchaudio.transforms.MFCC( sample_rate=SYNCNET_AUDIO_SR, n_mfcc=SYNCNET_MFCC, melkwargs={ "n_fft": 400, "hop_length": SYNCNET_MFCC_HOP, "win_length": 400, "n_mels": 26, "power": 2.0, "center": False, }, ) return mfcc(wav.unsqueeze(0))[0] # (13, T) at 100fps def _extract_face_crops(frames, input_fps=24): """Detect faces in 24fps frames, realign to 25fps, return 224x224 face crops.""" import cv2 cascade = _get_face_cascade() # Realign 24fps frames onto a 25fps grid: output frame i takes input frame round(i*24/25). num_25fps = max(0, int(round(len(frames) * 25.0 / input_fps))) aligned_indices = [min(len(frames) - 1, int(round(i * input_fps / 25.0))) for i in range(num_25fps)] crops = [] for idx in aligned_indices: frame = np.asarray(frames[idx].convert("RGB"))[:, :, ::-1] # RGB -> BGR (cv2 convention) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(64, 64)) if len(faces) == 0: crops.append(None) continue x, y, w, h = max(faces, key=lambda f: f[2] * f[3]) face = frame[y:y + h, x:x + w] face = cv2.resize(face, (SYNCNET_IMG_SIZE, SYNCNET_IMG_SIZE)) face = (face.astype(np.float32) / 255.0 - 0.5) / 0.5 crops.append(face) return crops def compute_syncnet_lse(frames: list, audio, audio_sample_rate, device=None) -> dict: """Compute SyncNet LSE-C / LSE-D for a generated talking video. Args: frames: list of PIL.Image frames at 24fps. audio: torch.Tensor or numpy waveform, shape (..., T). audio_sample_rate: sample rate of `audio`. device: torch device override. Returns: dict with "lse_c" and "lse_d" floats, or None values if no valid face windows were found (e.g. no faces detected). """ device = _resolve_device(device) model = _load_syncnet(device) crops = _extract_face_crops(frames) mfcc = compute_mfcc_features(audio, audio_sample_rate).numpy() # (16, T) valid_starts = [] for start in range(0, len(crops) - SYNCNET_T + 1): if all(c is not None for c in crops[start:start + SYNCNET_T]): valid_starts.append(start) # Keep windows whose audio slice (including ±2 frame offsets) is in bounds. mfcc_per_frame = SYNCNET_SAMPLES_PER_FRAME / SYNCNET_MFCC_HOP # 4 mfcc frames per 25fps video frame valid_starts = [ s for s in valid_starts if int(round((s - 2) * mfcc_per_frame)) >= 0 and int(round((s + 2) * mfcc_per_frame)) + SYNCNET_MFCC_WIN <= mfcc.shape[1] ] if len(valid_starts) == 0: return {"lse_c": None, "lse_d": None} lip_batch = torch.from_numpy(np.stack([ np.stack(crops[s:s + SYNCNET_T], axis=3).transpose(2, 3, 0, 1) for s in valid_starts ])).float().to(device) with torch.no_grad(): lip_embeddings = torch.nn.functional.normalize(model.forward_lip(lip_batch), p=2, dim=1) sims_per_offset = {} for offset in (-2, -1, 0, 1, 2): aud_batch = np.stack([ mfcc[:, int(round((s + offset) * mfcc_per_frame)): int(round((s + offset) * mfcc_per_frame)) + SYNCNET_MFCC_WIN] for s in valid_starts ]) aud_batch = torch.from_numpy(aud_batch).unsqueeze(1).float().to(device) aud_embeddings = torch.nn.functional.normalize(model.forward_aud(aud_batch), p=2, dim=1) sims_per_offset[offset] = (aud_embeddings * lip_embeddings).sum(dim=1).cpu().numpy() sims = np.stack([sims_per_offset[o] for o in (-2, -1, 0, 1, 2)], axis=0) # (5, N) lse_c = float(np.mean(sims.max(axis=0))) lse_d = float(np.mean(1.0 - sims.max(axis=0))) return {"lse_c": lse_c, "lse_d": lse_d} class SyncNetLSEMetric: """Wrapper class with a Metric-like callable interface.""" def __call__(self, frames: list, audio, audio_sample_rate) -> dict: return compute_syncnet_lse(frames, audio, audio_sample_rate)