| import os |
| import argparse |
| import torch |
| from torch.utils.data import DataLoader |
| import pandas as pd |
| import numpy as np |
| from sklearn.metrics import accuracy_score, roc_auc_score, average_precision_score, precision_recall_curve |
| import json |
| from datetime import datetime |
|
|
| from dataset import FeatureDataset |
| from model import FusionModel |
|
|
| def filter_metadata_for_diffusion_testing(metadata_path, diffusion_methods=['AniPortrait', 'Hallo', 'Sonic', 'Joyvasa', 'Ditto']): |
| """Filter metadata to include only diffusion methods and real data for testing""" |
| metadata = pd.read_csv(metadata_path) |
| |
| |
| filtered_metadata = metadata[ |
| metadata['path'].str.contains('real', case=False) | |
| metadata['path'].str.contains('|'.join(diffusion_methods)) |
| ] |
| |
| return filtered_metadata |
|
|
| def get_eval_args(): |
| parser = argparse.ArgumentParser(description='Evaluate Diffusion Methods Model') |
| |
| |
| parser.add_argument('--checkpoint_path', type=str, required=True, |
| help='Path to the trained model checkpoint (.pt file)') |
| |
| |
| parser.add_argument('--features_path', type=str, required=True, |
| help='Path to feature data directory') |
| parser.add_argument('--metadata', type=str, required=True, |
| help='Path to test metadata file') |
| |
| |
| parser.add_argument('--batch_size', type=int, default=1024, |
| help='Batch size for evaluation') |
| parser.add_argument('--tau', type=int, default=15, |
| help='Temporal window size') |
| |
| return parser.parse_args() |
|
|
| 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 save_predictions_to_csv(video_names, predictions, labels, output_path): |
| """Save individual video predictions to CSV file""" |
| results_df = pd.DataFrame({ |
| 'video_name': video_names, |
| 'prediction_score': predictions, |
| 'predicted_label': (predictions > 0).astype(int), |
| 'true_label': labels, |
| 'correct': ((predictions > 0).astype(int) == labels).astype(int) |
| }) |
| |
| results_df.to_csv(output_path, index=False) |
| print(f"Predictions saved to: {output_path}") |
|
|
| def main(): |
| args = get_eval_args() |
| print("Evaluating Diffusion Methods Model") |
| print(f"Checkpoint: {args.checkpoint_path}") |
| print(f"Features: {args.features_path}") |
| print(f"Metadata: {args.metadata}") |
| print(f"Batch size: {args.batch_size}") |
| |
| |
| device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') |
| |
| |
| diffusion_methods = ['AniPortrait', 'Hallo', 'Sonic', 'Joyvasa', 'Ditto'] |
| print(f"Testing on diffusion methods: {diffusion_methods}") |
| |
| |
| test_metadata = filter_metadata_for_diffusion_testing(args.metadata, diffusion_methods) |
| |
| print(f"Test dataset size (filtered): {len(test_metadata)}") |
| |
| |
| |
| temp_metadata_path = "/tmp/test_metadata_diffusion.csv" |
| test_metadata.to_csv(temp_metadata_path, index=False) |
| |
| test_dataset = FeatureDataset( |
| temp_metadata_path, args.features_path, tau=args.tau |
| ) |
| |
| |
| test_loader = DataLoader( |
| test_dataset, batch_size=args.batch_size, shuffle=False, num_workers=4 |
| ) |
| |
| |
| model = FusionModel().to(device) |
| |
| |
| if os.path.exists(args.checkpoint_path): |
| checkpoint = torch.load(args.checkpoint_path, map_location=device) |
| model.load_state_dict(checkpoint['state_dict']) |
| print(f"Loaded model from {args.checkpoint_path}") |
| if 'best_val_loss' in checkpoint: |
| print(f"Best validation loss: {checkpoint['best_val_loss']:.6f}") |
| else: |
| print(f"Checkpoint not found at {args.checkpoint_path}") |
| return |
| |
| print(f"Using single GPU for evaluation") |
| |
| model.eval() |
| |
| |
| total_loss = 0 |
| total_samples = 0 |
| logsoftmax = torch.nn.LogSoftmax(dim=1) |
| |
| |
| all_predictions = [] |
| all_labels = [] |
| all_video_names = [] |
| |
| with torch.no_grad(): |
| for batch in test_loader: |
| visual_frame, audio_window, video_name, video_frames, labels = batch |
| current_batch_size = visual_frame.size()[0] |
|
|
| visual_frame = visual_frame.to(device) |
| audio_window = audio_window.to(device) |
|
|
| |
| visual_central_frame = visual_frame.unsqueeze(1).repeat(1, 2 * args.tau + 1, 1) |
|
|
| outputs = model(visual_central_frame, audio_window) |
| outputs = outputs.squeeze() |
| |
| synchronization_scores = logsoftmax(outputs)[:, args.tau] |
| loss = -torch.sum(synchronization_scores) |
|
|
| total_loss += loss.item() |
| total_samples += current_batch_size |
| |
| |
| predictions = synchronization_scores.detach().cpu().numpy() |
| all_predictions.extend(predictions) |
| |
| batch_labels = labels.detach().cpu().numpy() |
| all_labels.extend(batch_labels) |
| |
| |
| all_video_names.extend(video_name) |
| |
| avg_loss = total_loss / total_samples |
| print(f"Test Loss: {avg_loss:.6f}") |
| |
| |
| if len(all_predictions) > 0 and len(all_labels) > 0: |
| all_predictions = np.array(all_predictions) |
| all_labels = np.array(all_labels) |
| |
| |
| binary_predictions = (all_predictions > 0).astype(int) |
| |
| |
| accuracy = accuracy_score(all_labels, binary_predictions) |
| print(f"Accuracy (ACC): {accuracy:.4f}") |
| |
| |
| try: |
| auc = roc_auc_score(all_labels, all_predictions) |
| print(f"AUC Score: {auc:.4f}") |
| except ValueError as e: |
| print(f"AUC calculation failed: {e}") |
| auc = 0.0 |
| |
| |
| try: |
| ap = average_precision_score(all_labels, all_predictions) |
| print(f"Average Precision (AP): {ap:.4f}") |
| except ValueError as e: |
| print(f"AP calculation failed: {e}") |
| ap = 0.0 |
| |
| |
| try: |
| acc_at_eer, eer_threshold = calculate_acc_at_eer(all_labels, all_predictions) |
| print(f"Accuracy at EER: {acc_at_eer:.4f} (Threshold: {eer_threshold:.4f})") |
| except Exception as e: |
| print(f"ACC@EER calculation failed: {e}") |
| acc_at_eer = 0.0 |
| eer_threshold = 0.0 |
| |
| |
| unique, counts = np.unique(all_labels, return_counts=True) |
| print(f"Class distribution: {dict(zip(unique, counts))}") |
| print(f"Real samples: {counts[0] if 0 in unique else 0}, Fake samples: {counts[1] if 1 in unique else 0}") |
| |
| |
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") |
| checkpoint_name = os.path.basename(args.checkpoint_path).replace('.pt', '') |
| predictions_csv_path = f"predictions_{checkpoint_name}_diffusion_{timestamp}.csv" |
| save_predictions_to_csv(all_video_names, all_predictions, all_labels, predictions_csv_path) |
| |
| |
| eval_summary = { |
| 'checkpoint_path': args.checkpoint_path, |
| 'test_metadata': args.metadata, |
| 'test_samples': int(len(all_predictions)), |
| 'real_samples': int(counts[0] if 0 in unique else 0), |
| 'fake_samples': int(counts[1] if 1 in unique else 0), |
| 'test_loss': float(avg_loss), |
| 'accuracy': float(accuracy), |
| 'auc': float(auc), |
| 'average_precision': float(ap), |
| 'acc_at_eer': float(acc_at_eer), |
| 'eer_threshold': float(eer_threshold), |
| 'predictions_file': predictions_csv_path, |
| 'evaluation_time': datetime.now().isoformat(), |
| 'diffusion_methods': diffusion_methods |
| } |
| |
| summary_json_path = f"eval_summary_{checkpoint_name}_diffusion_{timestamp}.json" |
| with open(summary_json_path, 'w') as f: |
| json.dump(eval_summary, f, indent=2) |
| |
| print(f"Evaluation summary saved to: {summary_json_path}") |
| print("\n=== Evaluation Summary ===") |
| print(f"Test Loss: {avg_loss:.6f}") |
| print(f"ACC: {accuracy:.4f}") |
| print(f"AUC: {auc:.4f}") |
| print(f"AP: {ap:.4f}") |
| print(f"ACC@EER: {acc_at_eer:.4f}") |
| print(f"Total samples: {len(all_predictions)}") |
|
|
| if __name__ == "__main__": |
| main() |