aneela-pervez commited on
Commit
cfef955
·
verified ·
1 Parent(s): 9a40160

Update final_lipsync.py

Browse files
Files changed (1) hide show
  1. final_lipsync.py +69 -18
final_lipsync.py CHANGED
@@ -1,6 +1,7 @@
1
  # -*- coding: utf-8 -*-
2
  import os
3
  import gc
 
4
  import cv2
5
  import torch
6
  import torch.nn as nn
@@ -25,18 +26,18 @@ from huggingface_hub import hf_hub_download
25
  import torch.serialization
26
  try:
27
  torch.serialization.add_safe_globals([np.core.multiarray.scalar])
28
- except:
29
  pass
30
 
 
31
  _original_load = torch.load
32
  def _patched_load(*args, **kwargs):
33
- kwargs['weights_only'] = False
34
  return _original_load(*args, **kwargs)
35
  torch.load = _patched_load
36
  # ----------------------------------------------
37
 
38
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
39
- # Secrets se API Key uthane ke liye
40
  OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY")
41
 
42
  # ==========================================
@@ -152,8 +153,48 @@ class MyFakeImageModel(nn.Module):
152
  self.fc = nn.Linear(512, 2)
153
  def forward(self, x): return torch.softmax(self.fc(x.view(x.size(0), -1)), dim=1)
154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  # ==========================================
156
- # 3. LOAD ALL MODELS (REDIRECTION TO HUB)
157
  # ==========================================
158
  def load_all_models():
159
  print("Loading Models...")
@@ -165,35 +206,45 @@ def load_all_models():
165
  m["ast_ext"] = AutoFeatureExtractor.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593")
166
  m["ast_mod"] = AutoModelForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593").to(DEVICE).eval()
167
 
 
168
  m["clap"] = laion_clap.CLAP_Module(enable_fusion=False, amodel='HTSAT-tiny').to(DEVICE)
169
- m["clap"].load_ckpt(model_id=1)
170
 
171
  sync_m = SyncNet_color().to(DEVICE)
172
- try: sync_m.load_state_dict(torch.load(hf_hub_download(repo_id="camenduru/Wav2Lip", filename="syncnet_v2.pth"), map_location=DEVICE)['state_dict'], strict=False)
173
- except: pass
 
 
174
  m["hf_sync"] = sync_m.eval()
175
 
176
  # Step 8 Models - Downloading from your HuggingFace Repo
177
  img_m = MyFakeImageModel().to(DEVICE)
178
  try:
179
- # Aapka FAKE-IMAGE model repo link use karein
180
  img_path = hf_hub_download(repo_id="aneela-pervez/My-Deepfake-Models", filename="checkpoint_step000080000.pth")
181
  img_m.load_state_dict(torch.load(img_path, map_location=DEVICE), strict=False)
182
- except: pass
 
183
  m["custom_img"] = img_m.eval()
184
 
185
  fusion_m = FusionLipSyncModel().to(DEVICE)
186
  try:
187
  fusion_path = hf_hub_download(repo_id="aneela-pervez/My-Deepfake-Models", filename="best_model.pth")
188
- fusion_m.load_state_dict(torch.load(fusion_path, map_location=DEVICE).get('model_state_dict'), strict=False)
189
- except: pass
 
 
 
 
190
  m["custom_fusion"] = fusion_m.eval()
191
 
192
  return m
193
 
194
  models = load_all_models()
195
 
196
- # (Analysis logic remains same as per your snippet)
 
 
 
197
  def extract_mouth(frame_np):
198
  try: faces = RetinaFace.detect_faces(frame_np)
199
  except: return None
@@ -207,18 +258,18 @@ def full_analysis(video_path):
207
  cap = cv2.VideoCapture(video_path)
208
  fps = cap.get(cv2.CAP_PROP_FPS) or 25.0
209
  frames = []
210
-
211
  # Fast Processing Logic (Har 5th frame use karega taake GPU pe time bache)
212
  frame_count = 0
213
  while cap.isOpened():
214
  ret, frame = cap.read()
215
  if not ret: break
216
-
217
  if frame_count % 5 == 0:
218
  temp_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
219
  small_frame = cv2.resize(temp_frame, (640, 360))
220
  frames.append(small_frame)
221
-
222
  frame_count += 1
223
  if len(frames) > 150: break
224
  cap.release()
@@ -240,7 +291,7 @@ def full_analysis(video_path):
240
  # Fast Audio Loading Logic
241
  y, sr = librosa.load(video_path, sr=48000, duration=10)
242
  y_16, _ = librosa.load(video_path, sr=16000, duration=10)
243
-
244
  with torch.no_grad():
245
  a_emb = torch.from_numpy(models["clap"].get_audio_embedding_from_data(x=[y])).to(DEVICE)
246
  r_a_emb = torch.from_numpy(models["clap"].get_text_embedding(PROMPTS["REAL_AUDIO"])).to(DEVICE)
@@ -279,9 +330,9 @@ def master_pipeline(video_path):
279
  res = full_analysis(video_path)
280
  if res is None or res[0] is None:
281
  return None, "Analysis failed to process video.", "Error"
282
-
283
  img, v_score, a_score, sync_score, clip_v, cust_v, clap_a, ast_a, hf_s, cust_s = res
284
-
285
  is_v_fake, is_a_fake, is_sync_bad = v_score >= 50, a_score >= 50, sync_score >= 60
286
  if is_v_fake and is_a_fake: case = "CASE 1: Full Deep Fake"
287
  elif is_v_fake: case = "CASE 2: Fake Video + Real Audio"
 
1
  # -*- coding: utf-8 -*-
2
  import os
3
  import gc
4
+ import urllib.request
5
  import cv2
6
  import torch
7
  import torch.nn as nn
 
26
  import torch.serialization
27
  try:
28
  torch.serialization.add_safe_globals([np.core.multiarray.scalar])
29
+ except Exception:
30
  pass
31
 
32
+ # Robust torch.load patch — handles both positional and keyword args
33
  _original_load = torch.load
34
  def _patched_load(*args, **kwargs):
35
+ kwargs['weights_only'] = False # Always force weights_only=False
36
  return _original_load(*args, **kwargs)
37
  torch.load = _patched_load
38
  # ----------------------------------------------
39
 
40
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
 
41
  OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY")
42
 
43
  # ==========================================
 
153
  self.fc = nn.Linear(512, 2)
154
  def forward(self, x): return torch.softmax(self.fc(x.view(x.size(0), -1)), dim=1)
155
 
156
+
157
+ # ==========================================
158
+ # 3. CLAP CHECKPOINT — DOWNLOAD HELPER
159
+ # ==========================================
160
+ def load_clap_safely(clap_module, device):
161
+ """
162
+ Load CLAP checkpoint with PyTorch 2.6+ compatibility.
163
+ Downloads checkpoint locally and uses strict=False to handle key mismatches.
164
+ """
165
+ CLAP_CKPT_URL = "https://huggingface.co/lukewys/laion_clap/resolve/main/music_audioset_epoch_15_esc_90.14.pt"
166
+ CLAP_CKPT_PATH = "/tmp/clap_music_audioset.pt"
167
+
168
+ # Step 1: Download checkpoint locally if not cached
169
+ if not os.path.exists(CLAP_CKPT_PATH):
170
+ print("⬇️ Downloading CLAP checkpoint to local disk...")
171
+ urllib.request.urlretrieve(CLAP_CKPT_URL, CLAP_CKPT_PATH)
172
+ print("✅ CLAP checkpoint downloaded!")
173
+ else:
174
+ print("✅ CLAP checkpoint already cached.")
175
+
176
+ # Step 2: Load checkpoint with weights_only=False
177
+ print("🔄 Loading CLAP checkpoint (strict=False)...")
178
+ ckpt = torch.load(CLAP_CKPT_PATH, map_location=device)
179
+
180
+ # Step 3: Extract state_dict from checkpoint
181
+ if isinstance(ckpt, dict):
182
+ if "state_dict" in ckpt:
183
+ state_dict = ckpt["state_dict"]
184
+ elif "model" in ckpt:
185
+ state_dict = ckpt["model"]
186
+ else:
187
+ state_dict = ckpt
188
+ else:
189
+ state_dict = ckpt
190
+
191
+ # Step 4: Load with strict=False to ignore unexpected/missing keys
192
+ clap_module.model.load_state_dict(state_dict, strict=False)
193
+ print("✅ CLAP model loaded successfully in lipsync!")
194
+
195
+
196
  # ==========================================
197
+ # 4. LOAD ALL MODELS (REDIRECTION TO HUB)
198
  # ==========================================
199
  def load_all_models():
200
  print("Loading Models...")
 
206
  m["ast_ext"] = AutoFeatureExtractor.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593")
207
  m["ast_mod"] = AutoModelForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593").to(DEVICE).eval()
208
 
209
+ # CLAP loading with PyTorch 2.6+ fix
210
  m["clap"] = laion_clap.CLAP_Module(enable_fusion=False, amodel='HTSAT-tiny').to(DEVICE)
211
+ load_clap_safely(m["clap"], DEVICE)
212
 
213
  sync_m = SyncNet_color().to(DEVICE)
214
+ try:
215
+ sync_m.load_state_dict(torch.load(hf_hub_download(repo_id="camenduru/Wav2Lip", filename="syncnet_v2.pth"), map_location=DEVICE)['state_dict'], strict=False)
216
+ except Exception as e:
217
+ print(f"⚠️ SyncNet load issue: {e}")
218
  m["hf_sync"] = sync_m.eval()
219
 
220
  # Step 8 Models - Downloading from your HuggingFace Repo
221
  img_m = MyFakeImageModel().to(DEVICE)
222
  try:
 
223
  img_path = hf_hub_download(repo_id="aneela-pervez/My-Deepfake-Models", filename="checkpoint_step000080000.pth")
224
  img_m.load_state_dict(torch.load(img_path, map_location=DEVICE), strict=False)
225
+ except Exception as e:
226
+ print(f"⚠️ Custom image model load issue: {e}")
227
  m["custom_img"] = img_m.eval()
228
 
229
  fusion_m = FusionLipSyncModel().to(DEVICE)
230
  try:
231
  fusion_path = hf_hub_download(repo_id="aneela-pervez/My-Deepfake-Models", filename="best_model.pth")
232
+ fusion_state = torch.load(fusion_path, map_location=DEVICE)
233
+ if isinstance(fusion_state, dict) and 'model_state_dict' in fusion_state:
234
+ fusion_state = fusion_state['model_state_dict']
235
+ fusion_m.load_state_dict(fusion_state, strict=False)
236
+ except Exception as e:
237
+ print(f"⚠️ Fusion model load issue: {e}")
238
  m["custom_fusion"] = fusion_m.eval()
239
 
240
  return m
241
 
242
  models = load_all_models()
243
 
244
+
245
+ # ==========================================
246
+ # 5. ANALYSIS LOGIC (UNCHANGED)
247
+ # ==========================================
248
  def extract_mouth(frame_np):
249
  try: faces = RetinaFace.detect_faces(frame_np)
250
  except: return None
 
258
  cap = cv2.VideoCapture(video_path)
259
  fps = cap.get(cv2.CAP_PROP_FPS) or 25.0
260
  frames = []
261
+
262
  # Fast Processing Logic (Har 5th frame use karega taake GPU pe time bache)
263
  frame_count = 0
264
  while cap.isOpened():
265
  ret, frame = cap.read()
266
  if not ret: break
267
+
268
  if frame_count % 5 == 0:
269
  temp_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
270
  small_frame = cv2.resize(temp_frame, (640, 360))
271
  frames.append(small_frame)
272
+
273
  frame_count += 1
274
  if len(frames) > 150: break
275
  cap.release()
 
291
  # Fast Audio Loading Logic
292
  y, sr = librosa.load(video_path, sr=48000, duration=10)
293
  y_16, _ = librosa.load(video_path, sr=16000, duration=10)
294
+
295
  with torch.no_grad():
296
  a_emb = torch.from_numpy(models["clap"].get_audio_embedding_from_data(x=[y])).to(DEVICE)
297
  r_a_emb = torch.from_numpy(models["clap"].get_text_embedding(PROMPTS["REAL_AUDIO"])).to(DEVICE)
 
330
  res = full_analysis(video_path)
331
  if res is None or res[0] is None:
332
  return None, "Analysis failed to process video.", "Error"
333
+
334
  img, v_score, a_score, sync_score, clip_v, cust_v, clap_a, ast_a, hf_s, cust_s = res
335
+
336
  is_v_fake, is_a_fake, is_sync_bad = v_score >= 50, a_score >= 50, sync_score >= 60
337
  if is_v_fake and is_a_fake: case = "CASE 1: Full Deep Fake"
338
  elif is_v_fake: case = "CASE 2: Fake Video + Real Audio"