File size: 10,380 Bytes
2594d73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
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)