| import argparse |
| import torch |
| from tqdm import tqdm |
| import numpy as np |
| from sklearn.metrics import average_precision_score, roc_auc_score, accuracy_score, precision_recall_curve |
| import pandas as pd |
| import os |
| import json |
| from datetime import datetime |
|
|
| from model import FusionModel |
| from utils import seed_run |
|
|
| def convert_numpy_types(obj): |
| """Convert NumPy types to Python native types for JSON serialization""" |
| if isinstance(obj, (np.integer, np.int64)): |
| return int(obj) |
| elif isinstance(obj, (np.floating, np.float64)): |
| return float(obj) |
| elif isinstance(obj, np.ndarray): |
| return obj.tolist() |
| elif isinstance(obj, dict): |
| return {key: convert_numpy_types(value) for key, value in obj.items()} |
| elif isinstance(obj, list): |
| return [convert_numpy_types(item) for item in obj] |
| else: |
| return obj |
|
|
| def calculate_acc_at_eer(labels, scores): |
| """Calculate accuracy at Equal Error Rate (EER)""" |
| from sklearn.metrics import roc_curve |
| |
| fpr, tpr, thresholds = roc_curve(labels, scores) |
| fnr = 1 - tpr |
| |
| |
| eer_threshold_idx = np.nanargmin(np.abs(fpr - fnr)) |
| eer_threshold = thresholds[eer_threshold_idx] |
| |
| |
| binary_predictions = (scores >= eer_threshold).astype(int) |
| acc_at_eer = accuracy_score(labels, binary_predictions) |
| |
| return acc_at_eer, eer_threshold |
|
|
| def calculate_metrics_for_subset(labels, scores, subset_name): |
| """Calculate comprehensive metrics for a subset of data""" |
| if len(labels) == 0: |
| return None |
| |
| try: |
| auc = roc_auc_score(labels, scores) |
| ap = average_precision_score(labels, scores) |
| binary_predictions = (scores > 0).astype(int) |
| accuracy = accuracy_score(labels, binary_predictions) |
| acc_at_eer, eer_threshold = calculate_acc_at_eer(labels, scores) |
| |
| return { |
| 'subset': subset_name, |
| 'samples': len(labels), |
| 'real_samples': np.sum(labels == 0), |
| 'fake_samples': np.sum(labels == 1), |
| 'accuracy': accuracy, |
| 'auc': auc, |
| 'average_precision': ap, |
| 'acc_at_eer': acc_at_eer, |
| 'eer_threshold': eer_threshold |
| } |
| except Exception as e: |
| print(f"Error calculating metrics for {subset_name}: {e}") |
| return None |
|
|
| def extract_method_from_filename(filename): |
| """Extract method name from filename""" |
| |
| if 'Fake_' in filename: |
| |
| method_part = filename.split('Fake_')[1] |
| method_name = method_part.replace('.npz', '') |
| return method_name |
| elif 'Real' in filename: |
| return 'real' |
| else: |
| return 'unknown' |
|
|
| def classify_video_method(video_path): |
| """Classify video into diffusion or non-diffusion methods""" |
| |
| filename = os.path.basename(video_path) |
| |
| |
| method_name = extract_method_from_filename(filename) |
| |
| |
| diffusion_methods = ['AniPortrait', 'Ditto', 'Hallo', 'JoyVASA', 'Sonic'] |
| non_diffusion_methods = ['EDTalk', 'Float', 'SadTalk'] |
| |
| if method_name == 'real': |
| return 'real' |
| elif method_name in diffusion_methods: |
| return 'diffusion' |
| elif method_name in non_diffusion_methods: |
| return 'non_diffusion' |
| else: |
| return method_name |
|
|
| def process_video(data, fusion_model, device, invert_score=False): |
| visual_tensor = torch.from_numpy(data["visual"]).to(device) |
| audio_tensor = torch.from_numpy(data["audio"]).to(device) |
|
|
| |
| visual_tensor = visual_tensor / (torch.linalg.norm(visual_tensor, ord=2, dim=-1, keepdim=True)) |
| audio_tensor = audio_tensor / (torch.linalg.norm(audio_tensor, ord=2, dim=-1, keepdim=True)) |
|
|
| output = fusion_model(visual_tensor, audio_tensor) |
| score = torch.logsumexp(-output, dim=0).detach().cpu().squeeze() |
|
|
| |
| |
| |
| if invert_score: |
| score = -score |
|
|
| return score |
|
|
| def main(args): |
| seed_run() |
|
|
| print(f"Evaluating AVH-Align on {args.dataset} with pretrained weights saved at {args.checkpoint_path} ...") |
|
|
| |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| fusion_model_weights = torch.load(args.checkpoint_path, weights_only=False) |
|
|
| |
| fusion_model = FusionModel().to(device) |
|
|
| |
| state_dict = fusion_model_weights["state_dict"] |
| if list(state_dict.keys())[0].startswith('module.'): |
| |
| new_state_dict = {k.replace('module.', ''): v for k, v in state_dict.items()} |
| fusion_model.load_state_dict(new_state_dict) |
| else: |
| fusion_model.load_state_dict(state_dict) |
|
|
| fusion_model.eval() |
|
|
| |
| metadata = pd.read_csv(args.metadata) |
|
|
| |
| |
| |
| |
| methods_filter = None |
| if args.methods is not None and args.methods.strip().lower() not in ("", "all"): |
| methods_filter = [m.strip() for m in args.methods.split(",") if m.strip()] |
| original_n = len(metadata) |
| |
| def _row_keep(path): |
| fname = os.path.basename(path) |
| spec = extract_method_from_filename(fname) |
| return spec == 'real' or spec in methods_filter |
| keep_mask = metadata["path"].map(_row_keep) |
| metadata = metadata[keep_mask].reset_index(drop=True) |
| print(f"[INFO] --methods filter active: {methods_filter}") |
| print(f"[INFO] metadata filtered: {original_n} -> {len(metadata)} (kept all real + only listed fake methods)") |
|
|
| outputs = [] |
| ground_truths = [] |
| video_paths = [] |
| video_methods = [] |
| specific_methods = [] |
|
|
| print(f"Processing {len(metadata)} videos...") |
| for _, row in tqdm(metadata.iterrows()): |
| data = np.load(os.path.join(args.features_path, row["path"].replace(".mp4", ".npz")), allow_pickle=True) |
| label = row["label"] |
| score = process_video(data, fusion_model, device, invert_score=args.invert_score) |
| outputs.append(score) |
| ground_truths.append(label) |
| video_paths.append(row["path"]) |
|
|
| |
| filename = os.path.basename(row["path"]) |
| specific_method = extract_method_from_filename(filename) |
| category_method = classify_video_method(row["path"]) |
|
|
| video_methods.append(category_method) |
| specific_methods.append(specific_method) |
|
|
| outputs = np.array(outputs) |
| ground_truths = np.array(ground_truths) |
|
|
| |
| overall_metrics = calculate_metrics_for_subset(ground_truths, outputs, "Overall") |
| |
| |
| |
| |
| method_metrics = {} |
| |
| real_mask = ground_truths == 0 |
| fake_mask = ground_truths == 1 |
| |
| video_methods_arr = np.array(video_methods) |
| specific_methods_arr = np.array(specific_methods) |
| |
| |
| print(f"\n--- Sample Distribution ---") |
| print(f"Real samples: {np.sum(real_mask)}") |
| unique_methods, method_counts = np.unique(specific_methods_arr[fake_mask], return_counts=True) |
| for m, c in zip(unique_methods, method_counts): |
| print(f" {m} fake samples: {c}") |
| |
| |
| diffusion_fake_mask = (video_methods_arr == 'diffusion') & fake_mask |
| diffusion_subset_mask = real_mask | diffusion_fake_mask |
| if np.sum(diffusion_fake_mask) > 0 and np.sum(real_mask) > 0: |
| method_metrics['diffusion'] = calculate_metrics_for_subset( |
| ground_truths[diffusion_subset_mask], outputs[diffusion_subset_mask], |
| "Diffusion Methods (real + diffusion fakes)" |
| ) |
| |
| |
| non_diffusion_fake_mask = (video_methods_arr == 'non_diffusion') & fake_mask |
| non_diffusion_subset_mask = real_mask | non_diffusion_fake_mask |
| if np.sum(non_diffusion_fake_mask) > 0 and np.sum(real_mask) > 0: |
| method_metrics['non_diffusion'] = calculate_metrics_for_subset( |
| ground_truths[non_diffusion_subset_mask], outputs[non_diffusion_subset_mask], |
| "Non-Diffusion Methods (real + non-diffusion fakes)" |
| ) |
| |
| |
| all_specific_methods = sorted(set(specific_methods)) |
| for method in all_specific_methods: |
| if method == 'real' or method == 'unknown': |
| continue |
| method_fake_mask = (specific_methods_arr == method) & fake_mask |
| method_subset_mask = real_mask | method_fake_mask |
| if np.sum(method_fake_mask) > 0 and np.sum(real_mask) > 0: |
| method_metrics[method] = calculate_metrics_for_subset( |
| ground_truths[method_subset_mask], outputs[method_subset_mask], |
| f"{method} (real + {method} fakes)" |
| ) |
|
|
| |
| print("\n=== Evaluation Results ===") |
| print(f"Dataset: {args.dataset}") |
| print(f"Total videos: {len(outputs)}") |
| |
| |
| if overall_metrics: |
| print(f"\n--- Overall Performance ---") |
| print(f"ACC: {overall_metrics['accuracy']:.4f}") |
| print(f"AUC: {overall_metrics['auc']:.4f}") |
| print(f"AP: {overall_metrics['average_precision']:.4f}") |
| print(f"ACC@EER: {overall_metrics['acc_at_eer']:.4f}") |
| print(f"Real samples: {overall_metrics['real_samples']}, Fake samples: {overall_metrics['fake_samples']}") |
| |
| |
| print(f"\n--- Performance by Method Type ---") |
| for key, metrics in method_metrics.items(): |
| if metrics: |
| print(f"\n{metrics['subset']}:") |
| print(f" Samples: {metrics['samples']}") |
| print(f" ACC: {metrics['accuracy']:.4f}") |
| print(f" AUC: {metrics['auc']:.4f}") |
| print(f" AP: {metrics['average_precision']:.4f}") |
| print(f" ACC@EER: {metrics['acc_at_eer']:.4f}") |
|
|
| |
| results_dir = "results" |
| os.makedirs(results_dir, exist_ok=True) |
| |
| |
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") |
| checkpoint_name = os.path.basename(args.checkpoint_path).replace('.pt', '') |
| |
| |
| results_df = pd.DataFrame({ |
| 'video_path': video_paths, |
| 'method_category': video_methods, |
| 'specific_method': specific_methods, |
| 'predicted_score': outputs, |
| 'predicted_label': (outputs > 0).astype(int), |
| 'ground_truth': ground_truths, |
| 'correct': ((outputs > 0).astype(int) == ground_truths).astype(int) |
| }) |
| |
| predictions_file = os.path.join(results_dir, f"{args.dataset}_{checkpoint_name}_detailed_predictions_{timestamp}.csv") |
| results_df.to_csv(predictions_file, index=False) |
| print(f"\nDetailed predictions saved to: {predictions_file}") |
| |
| |
| eval_summary = { |
| 'dataset': args.dataset, |
| 'checkpoint_path': args.checkpoint_path, |
| 'features_path': args.features_path, |
| 'metadata': args.metadata, |
| 'methods_filter': methods_filter, |
| 'invert_score': bool(args.invert_score), |
| 'overall_metrics': overall_metrics, |
| 'method_metrics': method_metrics, |
| 'total_videos': int(len(outputs)), |
| 'predictions_file': predictions_file, |
| 'evaluation_time': datetime.now().isoformat() |
| } |
| |
| |
| eval_summary_converted = convert_numpy_types(eval_summary) |
| |
| summary_file = os.path.join(results_dir, f"{args.dataset}_{checkpoint_name}_detailed_summary_{timestamp}.json") |
| with open(summary_file, 'w') as f: |
| json.dump(eval_summary_converted, f, indent=2) |
| |
| print(f"Evaluation summary saved to: {summary_file}") |
| |
| print("\n=== Final Summary ===") |
| print(f"Dataset: {args.dataset}") |
| print(f"Total videos: {len(outputs)}") |
| if overall_metrics: |
| print(f"ACC: {overall_metrics['accuracy']:.4f}") |
| print(f"AUC: {overall_metrics['auc']:.4f}") |
| print(f"AP: {overall_metrics['average_precision']:.4f}") |
| print(f"ACC@EER: {overall_metrics['acc_at_eer']:.4f}") |
|
|
| if __name__ == "__main__": |
| parser = argparse.ArgumentParser(description="Evaluate Fusion Model on Deepfake Dataset") |
|
|
| parser.add_argument("--checkpoint_path", type=str, default="checkpoints/AVH-Align_AV1M.pt", |
| help="Path to the pretrained fusion model checkpoint.") |
| parser.add_argument("--features_path", type=str, |
| default=f"av1m_features/val/", |
| help="Path to the root folder of test data.") |
| parser.add_argument("--metadata", type=str, |
| default="av1m_metadata/test_metadata.csv", |
| help="CSV file containing ground truth labels.") |
| parser.add_argument("--dataset", type=str, default="AV1M", |
| help="Dataset name") |
| parser.add_argument("--methods", type=str, default=None, |
| help="Comma-separated subset of fake-generation methods to evaluate " |
| "(real samples are always kept). Example: 'SadTalk,EDTalk,Float'. " |
| "Default = None (use all methods).") |
| parser.add_argument("--invert_score", action="store_true", |
| help="Negate the per-video score before computing metrics. " |
| "Use this for in-house ckpts whose score direction is opposite " |
| "to the official AVH-Align_AV1M.pt convention.") |
|
|
| args = parser.parse_args() |
| main(args) |
|
|