TaliDror commited on
Commit
4ea5904
·
1 Parent(s): 6240d8c

initial demo implementation

Browse files
app.py CHANGED
@@ -1,7 +1,532 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- demo = gr.Interface(fn=greet, inputs="text", outputs="text")
7
  demo.launch()
 
1
+ import os
2
+ import sys
3
+ os.environ["OMP_NUM_THREADS"] = "1"
4
+ os.environ["MKL_NUM_THREADS"] = "1"
5
+ os.environ["MKL_THREADING_LAYER"] = "GNU"
6
+
7
+ # ---------------------------------------------------------------------------
8
+ # Configuration — set CHECKPOINT_REPO as a HuggingFace Space secret to load
9
+ # fine-tuned models. If left empty, the demo uses base Arc2Face with a raw
10
+ # WavLM x-vector encoder (useful for testing that the Space works).
11
+ # ---------------------------------------------------------------------------
12
+ CHECKPOINT_REPO = os.environ.get("CHECKPOINT_REPO", "")
13
+ ENCODER_FILENAME = os.environ.get("ENCODER_FILENAME", "speaker_encoder.pt")
14
+ ARC2FACE_REPO = "FoivosPar/Arc2Face"
15
+ BASE_MODEL = "stable-diffusion-v1-5/stable-diffusion-v1-5"
16
+ SKIP_LORA = not bool(CHECKPOINT_REPO)
17
+ SKIP_SPEAKER_ENCODER = not bool(CHECKPOINT_REPO)
18
+
19
+ import numpy as np
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+ import torchaudio
24
+ from PIL import Image
25
+ from diffusers import StableDiffusionPipeline, UNet2DConditionModel, DPMSolverMultistepScheduler
26
+ from huggingface_hub import snapshot_download, hf_hub_download
27
  import gradio as gr
28
 
29
+ from external.arc2face import CLIPTextModelWrapper, project_face_embs
30
+ from core.models.encoder.speech_face_encoder import SpeechFaceXVectorEncoder
31
+
32
+ # ---------------------------------------------------------------------------
33
+ # Globals populated at startup
34
+ # ---------------------------------------------------------------------------
35
+ pipeline = None
36
+ speaker_encoder = None
37
+ facenet_model = None
38
+ facenet_classify_model = None
39
+ device = "cuda" if torch.cuda.is_available() else "cpu"
40
+
41
+
42
+ # ---------------------------------------------------------------------------
43
+ # PEFT-compatible attention processors (inlined from core/factories/lora_factory.py)
44
+ # These fix "Linear.forward() takes 2 positional arguments but 3 were given"
45
+ # when using LoRA-wrapped UNet attention layers.
46
+ # ---------------------------------------------------------------------------
47
+
48
+ class PeftCompatibleAttnProcessor:
49
+ def __call__(
50
+ self,
51
+ attn,
52
+ hidden_states: torch.Tensor,
53
+ encoder_hidden_states=None,
54
+ attention_mask=None,
55
+ temb=None,
56
+ *args,
57
+ **kwargs,
58
+ ) -> torch.Tensor:
59
+ residual = hidden_states
60
+
61
+ if attn.spatial_norm is not None:
62
+ hidden_states = attn.spatial_norm(hidden_states, temb)
63
+
64
+ input_ndim = hidden_states.ndim
65
+
66
+ if input_ndim == 4:
67
+ batch_size, channel, height, width = hidden_states.shape
68
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
69
+
70
+ batch_size, sequence_length, _ = (
71
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
72
+ )
73
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
74
+
75
+ if attn.group_norm is not None:
76
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
77
+
78
+ query = attn.to_q(hidden_states)
79
+
80
+ if encoder_hidden_states is None:
81
+ encoder_hidden_states = hidden_states
82
+ elif attn.norm_cross:
83
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
84
+
85
+ key = attn.to_k(encoder_hidden_states)
86
+ value = attn.to_v(encoder_hidden_states)
87
+
88
+ query = attn.head_to_batch_dim(query)
89
+ key = attn.head_to_batch_dim(key)
90
+ value = attn.head_to_batch_dim(value)
91
+
92
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
93
+ hidden_states = torch.bmm(attention_probs, value)
94
+ hidden_states = attn.batch_to_head_dim(hidden_states)
95
+
96
+ hidden_states = attn.to_out[0](hidden_states)
97
+ hidden_states = attn.to_out[1](hidden_states)
98
+
99
+ if input_ndim == 4:
100
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
101
+
102
+ if attn.residual_connection:
103
+ hidden_states = hidden_states + residual
104
+
105
+ hidden_states = hidden_states / attn.rescale_output_factor
106
+ return hidden_states
107
+
108
+
109
+ class PeftCompatibleAttnProcessor2_0:
110
+ def __init__(self):
111
+ if not hasattr(torch.nn.functional, "scaled_dot_product_attention"):
112
+ raise ImportError("PeftCompatibleAttnProcessor2_0 requires PyTorch 2.0+.")
113
+
114
+ def __call__(
115
+ self,
116
+ attn,
117
+ hidden_states: torch.Tensor,
118
+ encoder_hidden_states=None,
119
+ attention_mask=None,
120
+ temb=None,
121
+ *args,
122
+ **kwargs,
123
+ ) -> torch.Tensor:
124
+ residual = hidden_states
125
+
126
+ if attn.spatial_norm is not None:
127
+ hidden_states = attn.spatial_norm(hidden_states, temb)
128
+
129
+ input_ndim = hidden_states.ndim
130
+
131
+ if input_ndim == 4:
132
+ batch_size, channel, height, width = hidden_states.shape
133
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
134
+
135
+ batch_size, sequence_length, _ = (
136
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
137
+ )
138
+
139
+ if attention_mask is not None:
140
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
141
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
142
+
143
+ if attn.group_norm is not None:
144
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
145
+
146
+ query = attn.to_q(hidden_states)
147
+
148
+ if encoder_hidden_states is None:
149
+ encoder_hidden_states = hidden_states
150
+ elif attn.norm_cross:
151
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
152
+
153
+ key = attn.to_k(encoder_hidden_states)
154
+ value = attn.to_v(encoder_hidden_states)
155
+
156
+ inner_dim = key.shape[-1]
157
+ head_dim = inner_dim // attn.heads
158
+
159
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
160
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
161
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
162
+
163
+ hidden_states = torch.nn.functional.scaled_dot_product_attention(
164
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
165
+ )
166
+
167
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
168
+ hidden_states = hidden_states.to(query.dtype)
169
+
170
+ hidden_states = attn.to_out[0](hidden_states)
171
+ hidden_states = attn.to_out[1](hidden_states)
172
+
173
+ if input_ndim == 4:
174
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
175
+
176
+ if attn.residual_connection:
177
+ hidden_states = hidden_states + residual
178
+
179
+ hidden_states = hidden_states / attn.rescale_output_factor
180
+ return hidden_states
181
+
182
+
183
+ def _set_attn_processor_for_lora(unet: nn.Module) -> None:
184
+ try:
185
+ attn_procs = {}
186
+ for name in unet.attn_processors.keys():
187
+ if hasattr(torch.nn.functional, 'scaled_dot_product_attention'):
188
+ attn_procs[name] = PeftCompatibleAttnProcessor2_0()
189
+ else:
190
+ attn_procs[name] = PeftCompatibleAttnProcessor()
191
+ unet.set_attn_processor(attn_procs)
192
+ print(" Set PEFT-compatible attention processors")
193
+ except Exception as e:
194
+ print(f" Warning: Could not set attention processors for LoRA: {e}")
195
+
196
+
197
+ # ---------------------------------------------------------------------------
198
+ # Utilities
199
+ # ---------------------------------------------------------------------------
200
+
201
+ def load_and_process_audio(audio_file: str, dev: str, max_seconds: float = 6.0):
202
+ try:
203
+ waveform, sample_rate = torchaudio.load(audio_file)
204
+ except Exception:
205
+ import soundfile as sf
206
+ data, sample_rate = sf.read(audio_file, always_2d=True)
207
+ waveform = torch.from_numpy(data.T.astype(np.float32))
208
+ if sample_rate != 16000:
209
+ resampler = torchaudio.transforms.Resample(orig_freq=sample_rate, new_freq=16000)
210
+ waveform = resampler(waveform)
211
+ if waveform.shape[0] > 1:
212
+ waveform = waveform.mean(dim=0, keepdim=True)
213
+ max_samples = int(max_seconds * 16000)
214
+ if waveform.shape[1] > max_samples:
215
+ waveform = waveform[:, :max_samples]
216
+ elif waveform.shape[1] < max_samples:
217
+ waveform = F.pad(waveform, (0, max_samples - waveform.shape[1]))
218
+ return waveform.squeeze(0).unsqueeze(0).to(dev)
219
+
220
+
221
+ def is_lora_checkpoint(checkpoint_path: str, subfolder: str) -> bool:
222
+ return os.path.exists(os.path.join(checkpoint_path, subfolder, "adapter_config.json"))
223
+
224
+
225
+ def resolve_checkpoint_path(checkpoint_path: str) -> str:
226
+ checkpoint_path = os.path.expanduser(checkpoint_path)
227
+ if not os.path.exists(checkpoint_path):
228
+ raise FileNotFoundError(f"Checkpoint path does not exist: {checkpoint_path}")
229
+ expected_subs = {"encoder", "unet"}
230
+ if os.path.isdir(checkpoint_path):
231
+ children = set(os.listdir(checkpoint_path))
232
+ if expected_subs.issubset(children):
233
+ return checkpoint_path
234
+ ckpts = [d for d in os.listdir(checkpoint_path)
235
+ if d.startswith("checkpoint-") and os.path.isdir(os.path.join(checkpoint_path, d))]
236
+ if not ckpts:
237
+ return checkpoint_path
238
+
239
+ def ckpt_num(name):
240
+ try:
241
+ return int(name.split("checkpoint-")[-1])
242
+ except Exception:
243
+ return -1
244
+ return os.path.join(checkpoint_path, sorted(ckpts, key=ckpt_num)[-1])
245
+ return checkpoint_path
246
+
247
+
248
+ # ---------------------------------------------------------------------------
249
+ # LoRA checkpoint loading
250
+ # ---------------------------------------------------------------------------
251
+
252
+ def load_encoder_with_lora(checkpoint_path: str):
253
+ encoder_path = os.path.join(checkpoint_path, "lora", "encoder")
254
+ if is_lora_checkpoint(checkpoint_path, os.path.join("lora", "encoder")):
255
+ from peft import PeftModel
256
+ base_encoder = CLIPTextModelWrapper.from_pretrained(ARC2FACE_REPO, subfolder='encoder')
257
+ encoder = PeftModel.from_pretrained(base_encoder, encoder_path)
258
+ encoder = encoder.merge_and_unload()
259
+ encoder.forward = base_encoder.forward
260
+ return encoder
261
+ return CLIPTextModelWrapper.from_pretrained(checkpoint_path, subfolder="encoder")
262
+
263
+
264
+ def load_unet_with_lora(checkpoint_path: str):
265
+ unet_path = os.path.join(checkpoint_path, "lora", "unet")
266
+ if is_lora_checkpoint(checkpoint_path, os.path.join("lora", "unet")):
267
+ from peft import PeftModel
268
+ base_unet = UNet2DConditionModel.from_pretrained(ARC2FACE_REPO, subfolder='arc2face')
269
+ unet = PeftModel.from_pretrained(base_unet, unet_path)
270
+ unet = unet.merge_and_unload()
271
+ unet.forward = base_unet.forward
272
+ _set_attn_processor_for_lora(unet)
273
+ return unet
274
+ return UNet2DConditionModel.from_pretrained(checkpoint_path, subfolder="unet")
275
+
276
+
277
+ # ---------------------------------------------------------------------------
278
+ # Raw WavLM encoder (fallback when no fine-tuned checkpoint is provided)
279
+ # ---------------------------------------------------------------------------
280
+
281
+ class RawWavLMEncoder:
282
+ def __init__(self, pretrained_path: str, dev: str):
283
+ from transformers import WavLMForXVector
284
+ self.wavlm_xvector = WavLMForXVector.from_pretrained(pretrained_path).to(dev)
285
+ self.wavlm_xvector.eval()
286
+
287
+ def __call__(self, waveform, normalize=True, apply_shared_projection=False):
288
+ emb = self.wavlm_xvector(input_values=waveform, return_dict=True).embeddings
289
+ if normalize:
290
+ emb = F.normalize(emb, p=2, dim=1)
291
+ return emb
292
+
293
+ def eval(self):
294
+ self.wavlm_xvector.eval()
295
+ return self
296
+
297
+ def to(self, dev):
298
+ self.wavlm_xvector = self.wavlm_xvector.to(dev)
299
+ return self
300
+
301
+
302
+ # ---------------------------------------------------------------------------
303
+ # FaceNet best-sample selection
304
+ # ---------------------------------------------------------------------------
305
+
306
+ def _facenet_transform():
307
+ from torchvision import transforms
308
+ return transforms.Compose([
309
+ transforms.Resize((160, 160)),
310
+ transforms.ToTensor(),
311
+ transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]),
312
+ ])
313
+
314
+
315
+ def _extract_facenet_emb(img: Image.Image, model) -> torch.Tensor:
316
+ tensor = _facenet_transform()(img.convert("RGB")).unsqueeze(0)
317
+ with torch.no_grad():
318
+ emb = model(tensor)
319
+ return F.normalize(emb.squeeze(0), p=2, dim=0)
320
+
321
+
322
+ def _extract_facenet_logits(img: Image.Image, model) -> torch.Tensor:
323
+ tensor = _facenet_transform()(img.convert("RGB")).unsqueeze(0)
324
+ with torch.no_grad():
325
+ logits = model(tensor)
326
+ return logits.squeeze(0)
327
+
328
+
329
+ def select_best_image(images: list, method: str) -> Image.Image:
330
+ global facenet_model, facenet_classify_model
331
+
332
+ if method == "entropy":
333
+ logits_list = [_extract_facenet_logits(img, facenet_classify_model) for img in images]
334
+ logits_stack = torch.stack(logits_list)
335
+ probs = F.softmax(logits_stack, dim=1)
336
+ entropy = -(probs * (probs + 1e-10).log()).sum(dim=1)
337
+ best_idx = entropy.argmin().item()
338
+ print(f"[select_best:entropy] selected image {best_idx} (entropy={entropy[best_idx]:.3f})")
339
+
340
+ elif method == "pairwise":
341
+ embeddings = torch.stack([_extract_facenet_emb(img, facenet_model) for img in images])
342
+ sim_matrix = F.cosine_similarity(embeddings.unsqueeze(1), embeddings.unsqueeze(0), dim=2)
343
+ avg_sims = (sim_matrix.sum(dim=1) - 1) / (len(images) - 1)
344
+ best_idx = avg_sims.argmax().item()
345
+ print(f"[select_best:pairwise] selected image {best_idx} (avg_sim={avg_sims[best_idx]:.3f})")
346
+
347
+ else: # mean
348
+ embeddings = torch.stack([_extract_facenet_emb(img, facenet_model) for img in images])
349
+ mean_emb = F.normalize(embeddings.mean(dim=0), p=2, dim=0)
350
+ sims = F.cosine_similarity(embeddings, mean_emb.unsqueeze(0))
351
+ best_idx = sims.argmax().item()
352
+ print(f"[select_best:mean] selected image {best_idx} (sim={sims[best_idx]:.3f})")
353
+
354
+ return images[best_idx]
355
+
356
+
357
+ # ---------------------------------------------------------------------------
358
+ # Generation
359
+ # ---------------------------------------------------------------------------
360
+
361
+ def generate(audio_path, num_samples, guidance_scale, num_inference_steps, base_seed, select_best, best_selection="pairwise"):
362
+ global pipeline, speaker_encoder, facenet_model, facenet_classify_model, device
363
+
364
+ if pipeline is None:
365
+ return None, "Model not loaded. Check Space configuration."
366
+ if audio_path is None:
367
+ return None, "Please provide an audio file."
368
+
369
+ try:
370
+ waveform = load_and_process_audio(audio_path, device, max_seconds=5.0)
371
+ except Exception as e:
372
+ return None, f"Audio loading failed: {e}"
373
+
374
+ with torch.no_grad():
375
+ speech_z = speaker_encoder(waveform, normalize=True, apply_shared_projection=False)
376
+ id_emb = speech_z.to(torch.float16)
377
+ id_emb_projected = project_face_embs(pipeline, id_emb)
378
+
379
+ images = []
380
+ for i in range(int(num_samples)):
381
+ seed = int(base_seed) + i
382
+ generator = torch.Generator(device=device).manual_seed(seed)
383
+ img = pipeline(
384
+ prompt_embeds=id_emb_projected,
385
+ num_inference_steps=int(num_inference_steps),
386
+ guidance_scale=float(guidance_scale),
387
+ num_images_per_prompt=1,
388
+ generator=generator,
389
+ ).images[0]
390
+ images.append(img)
391
+
392
+ if select_best:
393
+ model_ready = facenet_model is not None if best_selection in ("mean", "pairwise") else facenet_classify_model is not None
394
+ if model_ready:
395
+ best = select_best_image(images, best_selection)
396
+ else:
397
+ best = images[0]
398
+ return [best], ""
399
+
400
+ return images, ""
401
+
402
+
403
+ # ---------------------------------------------------------------------------
404
+ # Model loading
405
+ # ---------------------------------------------------------------------------
406
+
407
+ def load_models():
408
+ global pipeline, speaker_encoder, facenet_model, facenet_classify_model, device
409
+
410
+ device = "cuda" if torch.cuda.is_available() else "cpu"
411
+ print(f"Using device: {device}")
412
+
413
+ # Speaker encoder
414
+ print("Loading speaker encoder...")
415
+ if SKIP_SPEAKER_ENCODER:
416
+ speaker_encoder = RawWavLMEncoder("microsoft/wavlm-base-sv", device)
417
+ print(" Using raw WavLM x-vector encoder (no fine-tuned checkpoint)")
418
+ else:
419
+ enc = SpeechFaceXVectorEncoder(
420
+ pretrained_path="microsoft/wavlm-base-sv",
421
+ face_emb_dim=512,
422
+ dropout=0.0,
423
+ use_projection=True,
424
+ freeze_feature_encoder=True,
425
+ )
426
+ encoder_pt = hf_hub_download(CHECKPOINT_REPO, ENCODER_FILENAME)
427
+ ckpt = torch.load(encoder_pt, map_location=device, weights_only=False)
428
+ enc.load_state_dict(ckpt["model"], strict=False)
429
+ speaker_encoder = enc.to(device).eval()
430
+ print(f" Loaded from {CHECKPOINT_REPO}/{ENCODER_FILENAME}")
431
+
432
+ # Diffusion pipeline
433
+ print("Loading diffusion pipeline...")
434
+ if SKIP_LORA:
435
+ encoder = CLIPTextModelWrapper.from_pretrained(ARC2FACE_REPO, subfolder='encoder', torch_dtype=torch.float16)
436
+ unet = UNet2DConditionModel.from_pretrained(ARC2FACE_REPO, subfolder='arc2face', torch_dtype=torch.float16)
437
+ print(" Using base Arc2Face (no LoRA)")
438
+ else:
439
+ checkpoint_dir = snapshot_download(CHECKPOINT_REPO)
440
+ checkpoint = resolve_checkpoint_path(checkpoint_dir)
441
+ print(f" Checkpoint: {checkpoint}")
442
+ encoder = load_encoder_with_lora(checkpoint).to(dtype=torch.float16)
443
+ unet = load_unet_with_lora(checkpoint).to(dtype=torch.float16)
444
+
445
+ pipeline = StableDiffusionPipeline.from_pretrained(
446
+ BASE_MODEL,
447
+ text_encoder=encoder,
448
+ unet=unet,
449
+ torch_dtype=torch.float16,
450
+ safety_checker=None,
451
+ )
452
+ pipeline.scheduler = DPMSolverMultistepScheduler.from_config(pipeline.scheduler.config)
453
+ pipeline = pipeline.to(device)
454
+ print(" Pipeline ready")
455
+
456
+ # FaceNet for best-sample selection
457
+ print("Loading FaceNet for best-sample selection...")
458
+ try:
459
+ from facenet_pytorch import InceptionResnetV1
460
+ facenet_model = InceptionResnetV1(pretrained='vggface2', classify=False).eval()
461
+ facenet_classify_model = InceptionResnetV1(pretrained='vggface2', classify=True).eval()
462
+ print(" FaceNet ready")
463
+ except Exception as e:
464
+ print(f" FaceNet unavailable ({e}); select-best will fall back to first image")
465
+ facenet_model = None
466
+ facenet_classify_model = None
467
+
468
+
469
+ # ---------------------------------------------------------------------------
470
+ # Gradio UI
471
+ # ---------------------------------------------------------------------------
472
+
473
+ def build_demo():
474
+ facenet_available = facenet_model is not None and facenet_classify_model is not None
475
+
476
+ with gr.Blocks(title="Speech-to-Face Generation") as demo:
477
+ gr.Markdown("# Speech-to-Face Generation")
478
+ gr.Markdown("Upload or record a speech audio clip and generate face images conditioned on the speaker's voice.")
479
+
480
+ with gr.Row():
481
+ with gr.Column():
482
+ audio_input = gr.Audio(
483
+ sources=["upload", "microphone"],
484
+ type="filepath",
485
+ label="Audio Input",
486
+ )
487
+ num_samples = gr.Slider(1, 16, value=4, step=1, label="Number of samples")
488
+ guidance_scale = gr.Slider(1.0, 10.0, value=4.5, step=0.5, label="Guidance scale")
489
+ num_steps = gr.Slider(10, 50, value=25, step=5, label="Inference steps")
490
+ base_seed = gr.Slider(0, 9999, value=42, step=1, label="Base seed")
491
+ select_best = gr.Checkbox(
492
+ value=facenet_available,
493
+ label="Select best image",
494
+ interactive=facenet_available,
495
+ )
496
+ best_selection = gr.Radio(
497
+ choices=["pairwise", "mean", "entropy"],
498
+ value="pairwise",
499
+ label="Selection method",
500
+ info="pairwise: most consistent with others | mean: closest to average | entropy: most confident face prediction",
501
+ interactive=facenet_available,
502
+ )
503
+ if not facenet_available:
504
+ gr.Markdown("_FaceNet not available — select-best disabled._")
505
+ generate_btn = gr.Button("Generate", variant="primary")
506
+
507
+ with gr.Column():
508
+ gallery = gr.Gallery(label="Generated Images", columns=4, rows=1, object_fit="contain")
509
+ status = gr.Markdown(visible=False)
510
+
511
+ def _generate(audio, n, gs, steps, seed, best, selection):
512
+ imgs, msg = generate(audio, n, gs, steps, seed, best, selection)
513
+ visible = bool(msg)
514
+ return imgs, gr.update(value=msg, visible=visible)
515
+
516
+ generate_btn.click(
517
+ fn=_generate,
518
+ inputs=[audio_input, num_samples, guidance_scale, num_steps, base_seed, select_best, best_selection],
519
+ outputs=[gallery, status],
520
+ )
521
+
522
+ return demo
523
+
524
+
525
+ # ---------------------------------------------------------------------------
526
+ # Entry point
527
+ # ---------------------------------------------------------------------------
528
+
529
+ load_models()
530
 
531
+ demo = build_demo()
532
  demo.launch()
core/__init__.py ADDED
File without changes
core/models/__init__.py ADDED
File without changes
core/models/encoder/__init__.py ADDED
File without changes
core/models/encoder/speech_face_encoder.py ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Speech-Face Encoder Wrapper for WavLMForXVector
3
+
4
+ Wraps HuggingFace's WavLMForXVector for speech-to-face embedding alignment task.
5
+ Uses CLIP-style InfoNCE loss for cross-modal alignment.
6
+ """
7
+
8
+ import logging
9
+ import types
10
+ from typing import Dict, List, Optional, Union
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+ from transformers import WavLMForXVector, WavLMModel, WavLMConfig, AutoFeatureExtractor
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class _TDNNLayer(nn.Module):
21
+ """TDNN layer matching HuggingFace WavLMTDNNLayer implementation exactly."""
22
+
23
+ def __init__(self, in_conv_dim: int, out_conv_dim: int, kernel_size: int, dilation: int):
24
+ super().__init__()
25
+ self.in_conv_dim = in_conv_dim
26
+ self.out_conv_dim = out_conv_dim
27
+ self.kernel_size = kernel_size
28
+ self.dilation = dilation
29
+ self.kernel = nn.Linear(in_conv_dim * kernel_size, out_conv_dim)
30
+ self.activation = nn.ReLU()
31
+
32
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
33
+ # hidden_states: (B, T, C)
34
+ hidden_states = hidden_states.unsqueeze(1) # (B, 1, T, C)
35
+ hidden_states = F.unfold(
36
+ hidden_states,
37
+ (self.kernel_size, self.in_conv_dim),
38
+ stride=(1, self.in_conv_dim),
39
+ dilation=(self.dilation, 1),
40
+ ) # (B, kernel_size * in_conv_dim, T_out)
41
+ hidden_states = hidden_states.transpose(1, 2) # (B, T_out, kernel_size * in_conv_dim)
42
+ hidden_states = self.kernel(hidden_states)
43
+ hidden_states = self.activation(hidden_states)
44
+ return hidden_states
45
+
46
+
47
+ class WavLMBaseWithXVectorHead(nn.Module):
48
+ """
49
+ WavLM-base-plus backbone with a freshly-initialized x-vector head.
50
+ """
51
+
52
+ _TDNN_DIM = [512, 512, 512, 512, 1500]
53
+ _TDNN_KERNEL = [5, 3, 3, 1, 1]
54
+ _TDNN_DILATION = [1, 2, 3, 1, 1]
55
+ _XVECTOR_DIM = 512
56
+
57
+ def __init__(self, pretrained_path: str, use_weighted_layer_sum: bool = True):
58
+ super().__init__()
59
+
60
+ logger.info(f"Loading WavLMModel (base backbone) from {pretrained_path}")
61
+ self.wavlm = WavLMModel.from_pretrained(pretrained_path)
62
+ hidden_size = self.wavlm.config.hidden_size
63
+ num_layers = self.wavlm.config.num_hidden_layers
64
+
65
+ self._use_weighted_layer_sum = use_weighted_layer_sum
66
+ if use_weighted_layer_sum:
67
+ self.layer_weights = nn.Parameter(torch.ones(num_layers + 1))
68
+
69
+ self.projector = nn.Linear(hidden_size, self._TDNN_DIM[0])
70
+
71
+ in_dims = [self._TDNN_DIM[0]] + self._TDNN_DIM[:-1]
72
+ self.tdnn = nn.ModuleList([
73
+ _TDNNLayer(in_dims[i], self._TDNN_DIM[i], self._TDNN_KERNEL[i], self._TDNN_DILATION[i])
74
+ for i in range(len(self._TDNN_DIM))
75
+ ])
76
+
77
+ self.feature_extractor = nn.Linear(2 * self._TDNN_DIM[-1], self._XVECTOR_DIM)
78
+ self.classifier = nn.Linear(self._XVECTOR_DIM, self._XVECTOR_DIM)
79
+
80
+ @property
81
+ def config(self):
82
+ cfg = self.wavlm.config
83
+ cfg.xvector_output_dim = self._XVECTOR_DIM
84
+ cfg.use_weighted_layer_sum = self._use_weighted_layer_sum
85
+ return cfg
86
+
87
+ def freeze_base_model(self):
88
+ for param in self.wavlm.parameters():
89
+ param.requires_grad = False
90
+
91
+ def freeze_feature_encoder(self):
92
+ for param in self.wavlm.feature_extractor.parameters():
93
+ param.requires_grad = False
94
+
95
+ def _get_tdnn_output_lengths(self, feat_lengths: torch.Tensor) -> torch.Tensor:
96
+ for kernel, dilation in zip(self._TDNN_KERNEL, self._TDNN_DILATION):
97
+ feat_lengths = feat_lengths - dilation * (kernel - 1)
98
+ return feat_lengths
99
+
100
+ def forward(
101
+ self,
102
+ input_values: Optional[torch.Tensor],
103
+ attention_mask: Optional[torch.Tensor] = None,
104
+ return_dict: bool = True,
105
+ ):
106
+ wavlm_out = self.wavlm(
107
+ input_values,
108
+ attention_mask=attention_mask,
109
+ output_hidden_states=self._use_weighted_layer_sum,
110
+ return_dict=True,
111
+ )
112
+
113
+ if self._use_weighted_layer_sum:
114
+ hidden_states = torch.stack(wavlm_out.hidden_states, dim=1)
115
+ norm_weights = F.softmax(self.layer_weights, dim=0)
116
+ hidden_states = (hidden_states * norm_weights.view(1, -1, 1, 1)).sum(dim=1)
117
+ else:
118
+ hidden_states = wavlm_out.last_hidden_state
119
+
120
+ hidden_states = self.projector(hidden_states)
121
+ for tdnn_layer in self.tdnn:
122
+ hidden_states = tdnn_layer(hidden_states)
123
+
124
+ if attention_mask is None:
125
+ mean_features = hidden_states.mean(dim=1)
126
+ std_features = hidden_states.std(dim=1)
127
+ else:
128
+ feat_lengths = self.wavlm._get_feat_extract_output_lengths(
129
+ attention_mask.sum(-1).long()
130
+ )
131
+ tdnn_lengths = self._get_tdnn_output_lengths(feat_lengths).clamp(
132
+ min=1, max=hidden_states.size(1)
133
+ )
134
+ T_out = hidden_states.size(1)
135
+ seq_mask = (
136
+ torch.arange(T_out, device=hidden_states.device).unsqueeze(0)
137
+ < tdnn_lengths.unsqueeze(1)
138
+ ).unsqueeze(-1).float()
139
+ counts = tdnn_lengths.float().unsqueeze(-1)
140
+ mean_features = (hidden_states * seq_mask).sum(dim=1) / counts
141
+ diff = (hidden_states - mean_features.unsqueeze(1)) * seq_mask
142
+ std_features = (diff.pow(2).sum(dim=1) / counts).sqrt()
143
+
144
+ statistic_pooling = torch.cat([mean_features, std_features], dim=-1)
145
+ output_embeddings = self.feature_extractor(statistic_pooling)
146
+ logits = self.classifier(output_embeddings)
147
+
148
+ return types.SimpleNamespace(embeddings=output_embeddings, logits=logits)
149
+
150
+
151
+ class SpeechFaceXVectorEncoder(nn.Module):
152
+ """
153
+ Speech encoder for face embedding alignment using WavLMForXVector.
154
+ """
155
+
156
+ def __init__(
157
+ self,
158
+ pretrained_path: str = "microsoft/wavlm-base-sv",
159
+ face_emb_dim: int = 512,
160
+ dropout: float = 0.1,
161
+ use_projection: bool = False,
162
+ projection_hidden_dim: int = None,
163
+ freeze_feature_encoder: bool = True,
164
+ reinit_tdnn_projector: bool = False,
165
+ use_base_wavlm: bool = False,
166
+ use_weighted_layer_sum: bool = True,
167
+ shared_projection_config: dict = None,
168
+ attention_gate_config: dict = None,
169
+ attribute_disentangled_config: dict = None,
170
+ attribute_heads_config: dict = None,
171
+ probabilistic_config: dict = None,
172
+ ):
173
+ super().__init__()
174
+ self.shared_projection_config = shared_projection_config
175
+
176
+ if use_base_wavlm:
177
+ self.wavlm_xvector = WavLMBaseWithXVectorHead(
178
+ pretrained_path=pretrained_path,
179
+ use_weighted_layer_sum=use_weighted_layer_sum,
180
+ )
181
+ else:
182
+ logger.info(f"Loading WavLMForXVector from {pretrained_path}")
183
+ self.wavlm_xvector, loading_info = WavLMForXVector.from_pretrained(
184
+ pretrained_path, output_loading_info=True
185
+ )
186
+ missing = loading_info["missing_keys"]
187
+ unexpected = loading_info["unexpected_keys"]
188
+ mismatched = loading_info["mismatched_keys"]
189
+ if not missing and not unexpected and not mismatched:
190
+ logger.info("Checkpoint loaded: all keys matched")
191
+ else:
192
+ if missing:
193
+ logger.warning(f" Missing keys ({len(missing)}): {missing}")
194
+ if unexpected:
195
+ logger.warning(f" Unexpected keys ({len(unexpected)}): {unexpected}")
196
+ if mismatched:
197
+ logger.warning(f" Mismatched shapes ({len(mismatched)}): {mismatched}")
198
+
199
+ if reinit_tdnn_projector and not use_base_wavlm:
200
+ for layer in self.wavlm_xvector.tdnn:
201
+ layer.kernel.reset_parameters()
202
+ if hasattr(layer, 'norm'):
203
+ layer.norm.reset_parameters()
204
+ self.wavlm_xvector.projector.reset_parameters()
205
+
206
+ self.xvector_dim = self.wavlm_xvector.config.xvector_output_dim
207
+ self.face_emb_dim = face_emb_dim
208
+
209
+ if freeze_feature_encoder:
210
+ self.wavlm_xvector.freeze_feature_encoder()
211
+
212
+ self.use_projection = use_projection or (projection_hidden_dim is not None)
213
+ self.projection_hidden_dim = projection_hidden_dim
214
+ if projection_hidden_dim is not None:
215
+ self.projection = nn.Sequential(
216
+ nn.Linear(self.xvector_dim, projection_hidden_dim),
217
+ nn.ReLU(),
218
+ nn.Linear(projection_hidden_dim, face_emb_dim),
219
+ nn.BatchNorm1d(face_emb_dim),
220
+ )
221
+ elif use_projection and self.xvector_dim != face_emb_dim:
222
+ self.projection = nn.Sequential(
223
+ nn.Linear(self.xvector_dim, face_emb_dim),
224
+ nn.BatchNorm1d(face_emb_dim),
225
+ )
226
+ else:
227
+ self.projection = nn.Identity()
228
+
229
+ self.dropout = nn.Dropout(p=dropout) if dropout > 0 else nn.Identity()
230
+
231
+ self.attention_gate = None
232
+ if attention_gate_config and attention_gate_config.get('enabled'):
233
+ from core.models.encoder.speech_attention_gate import SpeechAttentionGate
234
+ self.attention_gate = SpeechAttentionGate(
235
+ embedding_dim=face_emb_dim,
236
+ hidden_dim=attention_gate_config.get('hidden_dim'),
237
+ dropout=attention_gate_config.get('dropout', 0.1),
238
+ )
239
+
240
+ self.attribute_disentangled = None
241
+ self._attr_disent_output = None
242
+ if attribute_disentangled_config and attribute_disentangled_config.get('enabled'):
243
+ if self.attention_gate is not None:
244
+ raise ValueError("attention_gate and attribute_disentangled are mutually exclusive.")
245
+ from core.models.encoder.attribute_disentangled_encoder import AttributeDisentangledEncoder
246
+ self.attribute_disentangled = AttributeDisentangledEncoder(
247
+ embedding_dim=face_emb_dim,
248
+ num_directions=attribute_disentangled_config.get('num_directions', 16),
249
+ hidden_dim=attribute_disentangled_config.get('hidden_dim'),
250
+ dropout=attribute_disentangled_config.get('dropout', 0.1),
251
+ use_uncertainty=attribute_disentangled_config.get('use_uncertainty', True),
252
+ use_residual=attribute_disentangled_config.get('use_residual', True),
253
+ )
254
+
255
+ self.attribute_heads = None
256
+ self._attr_heads_output = None
257
+ if attribute_heads_config and attribute_heads_config.get('enabled'):
258
+ from core.models.encoder.attribute_prediction_heads import AttributePredictionHeads
259
+ self.attribute_heads = AttributePredictionHeads(
260
+ embedding_dim=face_emb_dim,
261
+ hidden_dim=attribute_heads_config.get('hidden_dim'),
262
+ dropout=attribute_heads_config.get('dropout', 0.1),
263
+ )
264
+
265
+ self.probabilistic = False
266
+ self._probabilistic_output = None
267
+ if probabilistic_config and probabilistic_config.get('enabled'):
268
+ self.probabilistic = True
269
+ self.log_sigma_head = nn.Linear(face_emb_dim, face_emb_dim)
270
+ self.sigma_min_log = probabilistic_config.get('min_log_sigma', -10.0)
271
+ self.sigma_max_log = probabilistic_config.get('max_log_sigma', 0.0)
272
+ nn.init.zeros_(self.log_sigma_head.weight)
273
+ nn.init.constant_(self.log_sigma_head.bias, self.sigma_min_log)
274
+
275
+ self.shared_projection = None
276
+ if shared_projection_config and shared_projection_config.get('enabled'):
277
+ from core.models.encoder.projection_head import ProjectionHead
278
+ self.shared_projection = ProjectionHead(
279
+ input_dim=face_emb_dim,
280
+ output_dim=shared_projection_config['shared_dim'],
281
+ hidden_dim=shared_projection_config.get('hidden_dim'),
282
+ use_batchnorm=shared_projection_config.get('use_batchnorm', True),
283
+ dropout=shared_projection_config.get('dropout', 0.1),
284
+ )
285
+
286
+ def freeze_base_model(self):
287
+ self.wavlm_xvector.freeze_base_model()
288
+
289
+ def unfreeze_base_model(self):
290
+ for param in self.wavlm_xvector.wavlm.parameters():
291
+ param.requires_grad = True
292
+
293
+ def freeze_feature_encoder(self):
294
+ self.wavlm_xvector.freeze_feature_encoder()
295
+
296
+ def get_base_model_params(self) -> List[nn.Parameter]:
297
+ return [p for p in self.wavlm_xvector.wavlm.parameters() if p.requires_grad]
298
+
299
+ def get_head_params(self) -> List[nn.Parameter]:
300
+ params = []
301
+ params.extend(self.wavlm_xvector.projector.parameters())
302
+ for tdnn_layer in self.wavlm_xvector.tdnn:
303
+ params.extend(tdnn_layer.parameters())
304
+ params.extend(self.wavlm_xvector.feature_extractor.parameters())
305
+ if hasattr(self.wavlm_xvector, 'layer_weights'):
306
+ params.append(self.wavlm_xvector.layer_weights)
307
+ if self.use_projection:
308
+ params.extend(self.projection.parameters())
309
+ if self.attention_gate is not None:
310
+ params.extend(self.attention_gate.parameters())
311
+ if self.attribute_disentangled is not None:
312
+ params.extend(self.attribute_disentangled.parameters())
313
+ if self.attribute_heads is not None:
314
+ params.extend(self.attribute_heads.parameters())
315
+ if self.probabilistic:
316
+ params.extend(self.log_sigma_head.parameters())
317
+ if self.shared_projection is not None:
318
+ params.extend(self.shared_projection.parameters())
319
+ return [p for p in params if p.requires_grad]
320
+
321
+ def get_attr_heads_output(self) -> Optional[Dict[str, torch.Tensor]]:
322
+ return self._attr_heads_output
323
+
324
+ def get_probabilistic_output(self) -> Optional[Dict[str, torch.Tensor]]:
325
+ return self._probabilistic_output
326
+
327
+ def get_kl_loss(self) -> torch.Tensor:
328
+ if self.attribute_disentangled is None or self._attr_disent_output is None:
329
+ return torch.tensor(0.0)
330
+ return self.attribute_disentangled.compute_kl_loss(
331
+ self._attr_disent_output['alphas'],
332
+ self._attr_disent_output['log_vars']
333
+ )
334
+
335
+ def get_decorrelation_loss(self) -> torch.Tensor:
336
+ if self.attribute_disentangled is None or self._attr_disent_output is None:
337
+ return torch.tensor(0.0)
338
+ return self.attribute_disentangled.compute_decorrelation_loss(
339
+ self._attr_disent_output['alphas']
340
+ )
341
+
342
+ def forward(
343
+ self,
344
+ audio: torch.Tensor,
345
+ attention_mask: Optional[torch.Tensor] = None,
346
+ normalize: bool = True,
347
+ apply_shared_projection: bool = True,
348
+ ) -> torch.Tensor:
349
+ outputs = self.wavlm_xvector(
350
+ input_values=audio,
351
+ attention_mask=attention_mask,
352
+ return_dict=True,
353
+ )
354
+
355
+ embeddings = outputs.embeddings
356
+ embeddings = self.projection(embeddings)
357
+ embeddings = self.dropout(embeddings)
358
+
359
+ if self.attribute_heads is not None:
360
+ self._attr_heads_output = self.attribute_heads(embeddings)
361
+
362
+ if self.probabilistic:
363
+ log_sigma = self.log_sigma_head(embeddings)
364
+ log_sigma = log_sigma.clamp(self.sigma_min_log, self.sigma_max_log)
365
+ self._probabilistic_output = {'mu': embeddings, 'log_sigma': log_sigma}
366
+
367
+ if self.attention_gate is not None:
368
+ embeddings = self.attention_gate(embeddings)
369
+ embeddings = F.normalize(embeddings, p=2, dim=1)
370
+
371
+ if self.attribute_disentangled is not None:
372
+ attr_out = self.attribute_disentangled(embeddings)
373
+ embeddings = attr_out['embedding']
374
+ self._attr_disent_output = attr_out
375
+ embeddings = F.normalize(embeddings, p=2, dim=1)
376
+
377
+ if self.shared_projection is not None and apply_shared_projection:
378
+ embeddings = self.shared_projection(embeddings)
379
+
380
+ if normalize:
381
+ embeddings = F.normalize(embeddings, p=2, dim=1)
382
+
383
+ return embeddings
384
+
385
+ def forward_with_loss(
386
+ self,
387
+ audio: torch.Tensor,
388
+ face_embeddings: torch.Tensor,
389
+ loss_fn: nn.Module,
390
+ attention_mask: Optional[torch.Tensor] = None,
391
+ normalize: bool = True,
392
+ ) -> Dict[str, torch.Tensor]:
393
+ speech_embeddings = self.forward(audio, attention_mask, normalize)
394
+ if normalize:
395
+ face_embeddings = F.normalize(face_embeddings, p=2, dim=1)
396
+ loss_dict = loss_fn(speech_embeddings, face_embeddings)
397
+ loss_dict["speech_embeddings"] = speech_embeddings
398
+ return loss_dict
399
+
400
+ @property
401
+ def output_dim(self) -> int:
402
+ if self.shared_projection is not None:
403
+ return self.shared_projection_config['shared_dim']
404
+ return self.face_emb_dim
405
+
406
+
407
+ def build_speech_face_encoder(
408
+ pretrained_path: str = "microsoft/wavlm-base-sv",
409
+ face_emb_dim: int = 512,
410
+ dropout: float = 0.1,
411
+ use_projection: bool = True,
412
+ projection_hidden_dim: int = None,
413
+ freeze_feature_encoder: bool = True,
414
+ reinit_tdnn_projector: bool = False,
415
+ use_base_wavlm: bool = False,
416
+ use_weighted_layer_sum: bool = True,
417
+ shared_projection_config: dict = None,
418
+ attention_gate_config: dict = None,
419
+ attribute_disentangled_config: dict = None,
420
+ attribute_heads_config: dict = None,
421
+ probabilistic_config: dict = None,
422
+ ) -> SpeechFaceXVectorEncoder:
423
+ return SpeechFaceXVectorEncoder(
424
+ pretrained_path=pretrained_path,
425
+ face_emb_dim=face_emb_dim,
426
+ dropout=dropout,
427
+ use_projection=use_projection,
428
+ projection_hidden_dim=projection_hidden_dim,
429
+ freeze_feature_encoder=freeze_feature_encoder,
430
+ reinit_tdnn_projector=reinit_tdnn_projector,
431
+ use_base_wavlm=use_base_wavlm,
432
+ use_weighted_layer_sum=use_weighted_layer_sum,
433
+ shared_projection_config=shared_projection_config,
434
+ attention_gate_config=attention_gate_config,
435
+ attribute_disentangled_config=attribute_disentangled_config,
436
+ attribute_heads_config=attribute_heads_config,
437
+ probabilistic_config=probabilistic_config,
438
+ )
external/__init__.py ADDED
File without changes
external/arc2face/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .models import CLIPTextModelWrapper
2
+ from .utils import project_face_embs, project_face_embs_with_grad, image_align
external/arc2face/models.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from transformers import CLIPTextModel
3
+ from typing import Any, Callable, Dict, Optional, Tuple, Union, List
4
+ from transformers.modeling_outputs import BaseModelOutputWithPooling
5
+ from transformers.models.clip.modeling_clip import _make_causal_mask, _expand_mask
6
+
7
+
8
+ class CLIPTextModelWrapper(CLIPTextModel):
9
+ # Adapted from https://github.com/huggingface/transformers/blob/v4.34.1/src/transformers/models/clip/modeling_clip.py#L812
10
+ # Modified to accept precomputed token embeddings "input_token_embs" as input or calculate them from input_ids and return them.
11
+ def forward(
12
+ self,
13
+ input_ids: Optional[torch.Tensor] = None,
14
+ attention_mask: Optional[torch.Tensor] = None,
15
+ position_ids: Optional[torch.Tensor] = None,
16
+ output_attentions: Optional[bool] = None,
17
+ output_hidden_states: Optional[bool] = None,
18
+ return_dict: Optional[bool] = None,
19
+ input_token_embs: Optional[torch.Tensor] = None,
20
+ return_token_embs: Optional[bool] = False,
21
+ ) -> Union[Tuple, torch.Tensor, BaseModelOutputWithPooling]:
22
+
23
+ if return_token_embs:
24
+ return self.text_model.embeddings.token_embedding(input_ids)
25
+
26
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
27
+
28
+ output_attentions = output_attentions if output_attentions is not None else self.text_model.config.output_attentions
29
+ output_hidden_states = (
30
+ output_hidden_states if output_hidden_states is not None else self.text_model.config.output_hidden_states
31
+ )
32
+ return_dict = return_dict if return_dict is not None else self.text_model.config.use_return_dict
33
+
34
+ if input_ids is None:
35
+ raise ValueError("You have to specify input_ids")
36
+
37
+ input_shape = input_ids.size()
38
+ input_ids = input_ids.view(-1, input_shape[-1])
39
+
40
+ hidden_states = self.text_model.embeddings(input_ids=input_ids, position_ids=position_ids, inputs_embeds=input_token_embs)
41
+
42
+ # CLIP's text model uses causal mask, prepare it here.
43
+ # https://github.com/openai/CLIP/blob/cfcffb90e69f37bf2ff1e988237a0fbe41f33c04/clip/model.py#L324
44
+ causal_attention_mask = _make_causal_mask(input_shape, hidden_states.dtype, device=hidden_states.device)
45
+ # expand attention_mask
46
+ if attention_mask is not None:
47
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
48
+ attention_mask = _expand_mask(attention_mask, hidden_states.dtype)
49
+
50
+ encoder_outputs = self.text_model.encoder(
51
+ inputs_embeds=hidden_states,
52
+ attention_mask=attention_mask,
53
+ causal_attention_mask=causal_attention_mask,
54
+ output_attentions=output_attentions,
55
+ output_hidden_states=output_hidden_states,
56
+ return_dict=return_dict,
57
+ )
58
+
59
+ last_hidden_state = encoder_outputs[0]
60
+ last_hidden_state = self.text_model.final_layer_norm(last_hidden_state)
61
+
62
+ if self.text_model.eos_token_id == 2:
63
+ pooled_output = last_hidden_state[
64
+ torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device),
65
+ input_ids.to(dtype=torch.int, device=last_hidden_state.device).argmax(dim=-1),
66
+ ]
67
+ else:
68
+ pooled_output = last_hidden_state[
69
+ torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device),
70
+ (input_ids.to(dtype=torch.int, device=last_hidden_state.device) == self.text_model.eos_token_id)
71
+ .int()
72
+ .argmax(dim=-1),
73
+ ]
74
+
75
+ if not return_dict:
76
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
77
+
78
+ return BaseModelOutputWithPooling(
79
+ last_hidden_state=last_hidden_state,
80
+ pooler_output=pooled_output,
81
+ hidden_states=encoder_outputs.hidden_states,
82
+ attentions=encoder_outputs.attentions,
83
+ )
external/arc2face/utils.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import scipy
2
+ import PIL
3
+ import numpy as np
4
+ import torch
5
+ import torch.nn.functional as F
6
+
7
+ @torch.no_grad()
8
+ def project_face_embs(pipeline, face_embs):
9
+
10
+ '''
11
+ face_embs: (N, 512) normalized ArcFace embeddings
12
+ '''
13
+
14
+ arcface_token_id = pipeline.tokenizer.encode("id", add_special_tokens=False)[0]
15
+
16
+ input_ids = pipeline.tokenizer(
17
+ "photo of a id person",
18
+ truncation=True,
19
+ padding="max_length",
20
+ max_length=pipeline.tokenizer.model_max_length,
21
+ return_tensors="pt",
22
+ ).input_ids.to(pipeline.device)
23
+
24
+ face_embs_padded = F.pad(face_embs, (0, pipeline.text_encoder.config.hidden_size-512), "constant", 0)
25
+ token_embs = pipeline.text_encoder(input_ids=input_ids.repeat(len(face_embs), 1), return_token_embs=True)
26
+ token_embs[input_ids==arcface_token_id] = face_embs_padded
27
+
28
+ prompt_embeds = pipeline.text_encoder(
29
+ input_ids=input_ids,
30
+ input_token_embs=token_embs
31
+ )[0]
32
+
33
+ return prompt_embeds
34
+
35
+
36
+ def project_face_embs_with_grad(encoder, tokenizer, face_embs):
37
+ """
38
+ Same as project_face_embs but allows gradients for training.
39
+ """
40
+ arcface_token_id = tokenizer.encode("id", add_special_tokens=False)[0]
41
+
42
+ input_ids = tokenizer(
43
+ "photo of a id person",
44
+ truncation=True,
45
+ padding="max_length",
46
+ max_length=tokenizer.model_max_length,
47
+ return_tensors="pt",
48
+ ).input_ids.to(encoder.device)
49
+
50
+ face_embs_padded = F.pad(face_embs, (0, encoder.config.hidden_size - 512), "constant", 0)
51
+
52
+ input_ids_batch = input_ids.repeat(len(face_embs), 1)
53
+ token_embs = encoder(input_ids=input_ids_batch, return_token_embs=True)
54
+
55
+ face_embs_padded = face_embs_padded.to(token_embs.dtype)
56
+ token_embs[input_ids_batch == arcface_token_id] = face_embs_padded
57
+
58
+ prompt_embeds = encoder(
59
+ input_ids=input_ids_batch,
60
+ input_token_embs=token_embs
61
+ )[0]
62
+
63
+ return prompt_embeds
64
+
65
+
66
+ def image_align(img,
67
+ face_landmarks,
68
+ output_size=1024,
69
+ transform_size=4096,
70
+ enable_padding=True):
71
+ # Align function from FFHQ dataset pre-processing step
72
+ # https://github.com/NVlabs/ffhq-dataset/blob/master/download_ffhq.py
73
+
74
+ lm = face_landmarks
75
+ lm_eye_left = lm[36:42]
76
+ lm_eye_right = lm[42:48]
77
+ lm_mouth_outer = lm[48:60]
78
+
79
+ eye_left = np.mean(lm_eye_left, axis=0)
80
+ eye_right = np.mean(lm_eye_right, axis=0)
81
+ eye_avg = (eye_left + eye_right) * 0.5
82
+ eye_to_eye = eye_right - eye_left
83
+ mouth_left = lm_mouth_outer[0]
84
+ mouth_right = lm_mouth_outer[6]
85
+ mouth_avg = (mouth_left + mouth_right) * 0.5
86
+ eye_to_mouth = mouth_avg - eye_avg
87
+
88
+ x = eye_to_eye - np.flipud(eye_to_mouth) * [-1, 1]
89
+ x /= np.hypot(*x)
90
+ x *= max(np.hypot(*eye_to_eye) * 2.0, np.hypot(*eye_to_mouth) * 1.8)
91
+ y = np.flipud(x) * [-1, 1]
92
+ c = eye_avg + eye_to_mouth * 0.1
93
+ quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y])
94
+ qsize = np.hypot(*x) * 2
95
+
96
+ img = img.convert('RGB')
97
+
98
+ shrink = int(np.floor(qsize / output_size * 0.5))
99
+ if shrink > 1:
100
+ rsize = (int(np.rint(float(img.size[0]) / shrink)),
101
+ int(np.rint(float(img.size[1]) / shrink)))
102
+ img = img.resize(rsize, PIL.Image.LANCZOS)
103
+ quad /= shrink
104
+ qsize /= shrink
105
+
106
+ border = max(int(np.rint(qsize * 0.1)), 3)
107
+ crop = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))),
108
+ int(np.ceil(max(quad[:, 0]))), int(np.ceil(max(quad[:, 1]))))
109
+ crop = (max(crop[0] - border, 0), max(crop[1] - border, 0),
110
+ min(crop[2] + border, img.size[0]), min(crop[3] + border, img.size[1]))
111
+ if crop[2] - crop[0] < img.size[0] or crop[3] - crop[1] < img.size[1]:
112
+ img = img.crop(crop)
113
+ quad -= crop[0:2]
114
+
115
+ pad = (int(np.floor(min(quad[:, 0]))), int(np.floor(min(quad[:, 1]))),
116
+ int(np.ceil(max(quad[:, 0]))), int(np.ceil(max(quad[:, 1]))))
117
+ pad = (max(-pad[0] + border, 0), max(-pad[1] + border, 0),
118
+ max(pad[2] - img.size[0] + border, 0), max(pad[3] - img.size[1] + border, 0))
119
+ if enable_padding and max(pad) > border - 4:
120
+ pad = np.maximum(pad, int(np.rint(qsize * 0.3)))
121
+ img = np.pad(np.float32(img),
122
+ ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)), 'reflect')
123
+ h, w, _ = img.shape
124
+ y, x, _ = np.ogrid[:h, :w, :1]
125
+ mask = np.maximum(
126
+ 1.0 - np.minimum(np.float32(x) / pad[0], np.float32(w - 1 - x) / pad[2]),
127
+ 1.0 - np.minimum(np.float32(y) / pad[1], np.float32(h - 1 - y) / pad[3]))
128
+ blur = qsize * 0.02
129
+ img += (scipy.ndimage.gaussian_filter(img, [blur, blur, 0]) - img) * np.clip(mask * 3.0 + 1.0, 0.0, 1.0)
130
+ img += (np.median(img, axis=(0, 1)) - img) * np.clip(mask, 0.0, 1.0)
131
+ img = PIL.Image.fromarray(np.uint8(np.clip(np.rint(img), 0, 255)), 'RGB')
132
+ quad += pad[:2]
133
+
134
+ img = img.transform((transform_size, transform_size), PIL.Image.QUAD,
135
+ (quad + 0.5).flatten(), PIL.Image.BILINEAR)
136
+ if output_size < transform_size:
137
+ img = img.resize((output_size, output_size), PIL.Image.LANCZOS)
138
+
139
+ return img
requirements.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ torch
3
+ torchvision
4
+ torchaudio
5
+ diffusers==0.21.4
6
+ transformers==4.34.1
7
+ accelerate==0.23.0
8
+ peft==0.6.2
9
+ huggingface-hub==0.16.4
10
+ safetensors
11
+ einops
12
+ numpy
13
+ scipy
14
+ pillow
15
+ opencv-python-headless
16
+ facenet-pytorch
17
+ soundfile