fairtalking-second-work / integrate_thb_test.py
huahua123313's picture
Add files using upload-large-folder tool
a17b394 verified
Raw
History Blame Contribute Delete
5.53 kB
#!/usr/bin/env python3
"""
Integration example for using TalkingHeadBench fake test dataset with FairTalking project.
This script shows how to:
1. Load THB fake test dataset
2. Create a compatible dataset class
3. Integrate with existing FairTalking data module
"""
import os
import pandas as pd
from pathlib import Path
class THBFakeTestDataset:
"""Dataset class for TalkingHeadBench fake test videos."""
def __init__(self, csv_file: str, transform=None, target_transform=None):
"""
Initialize the dataset.
Args:
csv_file: Path to CSV file with video paths
transform: Optional transform to be applied on video
target_transform: Optional transform to be applied on label
"""
self.data = pd.read_csv(csv_file)
self.transform = transform
self.target_transform = target_transform
def __len__(self):
"""Return the number of samples in dataset."""
return len(self.data)
def __getitem__(self, idx):
"""Get a sample from the dataset."""
row = self.data.iloc[idx]
# Video path
video_path = row['video_path']
# Label (all fake videos have label 1)
label = row['label']
# Generator information
generator = row['generator']
# In a real implementation, you would load the video here
# For demonstration, we'll just return the path and metadata
sample = {
'video_path': video_path,
'label': label,
'generator': generator,
'filename': row['filename']
}
# Apply transforms if specified
if self.transform:
sample = self.transform(sample)
if self.target_transform:
sample['label'] = self.target_transform(sample['label'])
return sample
def create_thb_test_config():
"""Create configuration for THB test dataset integration."""
config = {
'thb_root': '/apdcephfs_gy4/share_303628665/joywu/dataset/TalkingHeadBench',
'fake_test_csv': '/apdcephfs_gy4/share_303628665/joywu/dataset/TalkingHeadBench/fake_test_dataset.csv',
'batch_size': 8,
'num_workers': 4,
'video_params': {
'num_frames': 16,
'frame_size': 224,
'audio_seconds': 2.56
}
}
return config
def integrate_with_fairtalking():
"""Show how to integrate THB dataset with existing FairTalking code."""
print("=" * 60)
print("THB Fake Test Dataset Integration with FairTalking")
print("=" * 60)
# Configuration
config = create_thb_test_config()
# Check if CSV file exists
if not os.path.exists(config['fake_test_csv']):
print(f"Error: CSV file not found: {config['fake_test_csv']}")
return
# Load dataset
dataset = THBFakeTestDataset(config['fake_test_csv'])
print(f"Dataset loaded successfully!")
print(f" Total samples: {len(dataset)}")
print(f" CSV file: {config['fake_test_csv']}")
# Show sample data
print(f"\nSample data from dataset:")
for i in range(3):
sample = dataset[i]
print(f" Sample {i+1}:")
print(f" Video: {Path(sample['video_path']).name}")
print(f" Generator: {sample['generator']}")
print(f" Label: {sample['label']}")
# Integration with existing FairTalking datamodule
print(f"\nIntegration with FairTalking DataModule:")
print("1. Modify your datamodule.py to support THB dataset")
print("2. Add a new method for THB test dataset loading")
print("3. Update configuration to use THB test set")
# Example modification to datamodule
print(f"\nExample datamodule modification:")
print("""
# In your datamodule.py, add this method:
def thb_fake_test_loader(self):
'''Create DataLoader for THB fake test dataset.'''
from .thb_dataset import THBFakeTestDataset
dataset = THBFakeTestDataset(
csv_file=self.config.thb_fake_test_csv,
transform=self.test_transform
)
return DataLoader(
dataset,
batch_size=self.config.batch_size,
num_workers=self.config.num_workers,
shuffle=False
)
""")
def main():
"""Main function to demonstrate THB dataset integration."""
# Check dataset statistics
csv_path = '/apdcephfs_gy4/share_303628665/joywu/dataset/TalkingHeadBench/fake_test_dataset.csv'
if os.path.exists(csv_path):
df = pd.read_csv(csv_path)
print("Dataset Statistics:")
print(f" Total videos: {len(df)}")
print(f" Generators: {df['generator'].unique().tolist()}")
print(f" Label distribution: {df['label'].value_counts().to_dict()}")
# Show generator distribution
print(f"\nGenerator distribution:")
for generator, count in df['generator'].value_counts().items():
print(f" {generator}: {count} videos")
# Show integration example
integrate_with_fairtalking()
print(f"\nNext steps:")
print("1. Create a THBFakeTestDataset class in your project")
print("2. Modify your datamodule to support THB dataset")
print("3. Update your training/testing scripts to use THB test set")
print("4. Remember: All videos are fake (label=1), so you'll need real videos for binary classification")
if __name__ == "__main__":
main()