| import os |
| import cv2 |
| import numpy as np |
| import librosa |
| import matplotlib.pyplot as plt |
| from tqdm import tqdm |
| from librosa import feature as audio |
| import sys |
|
|
| """ |
| Structure of the AVLips dataset: |
| AVLips |
| ├── 0_real |
| ├── 1_fake |
| └── wav |
| ├── 0_real |
| └── 1_fake |
| """ |
|
|
| |
| N_EXTRACT = 10 |
| WINDOW_LEN = 5 |
| MAX_SAMPLE = 0 |
| |
|
|
| audio_root = "./AVLips/wav" |
| video_root = "./AVLips" |
| output_root = "./datasets/AVLips" |
|
|
| |
| os.makedirs("./temp", exist_ok=True) |
| os.makedirs(output_root, exist_ok=True) |
|
|
|
|
| def get_spectrogram(audio_file, output_path="./temp/mel.png"): |
| """ |
| Generate mel-spectrogram from audio file |
| |
| Args: |
| audio_file: path to audio file |
| output_path: path to save spectrogram image |
| """ |
| try: |
| data, sr = librosa.load(audio_file, sr=16000) |
| mel = librosa.power_to_db(audio.melspectrogram(y=data, sr=sr), ref=np.min) |
| plt.imsave(output_path, mel) |
| return True |
| except Exception as e: |
| print(f"Error generating spectrogram for {audio_file}: {str(e)}") |
| return False |
|
|
|
|
| def run(): |
| labels = [(0, "0_real"), (1, "1_fake")] |
| |
| for label, dataset_name in labels: |
| |
| os.makedirs(f"{output_root}/{dataset_name}", exist_ok=True) |
| |
| root = f"{video_root}/{dataset_name}" |
| if not os.path.exists(root): |
| print(f"Warning: {root} does not exist, skipping...") |
| continue |
| |
| video_list = os.listdir(root) |
| print(f"\nHandling {dataset_name}... (Total: {len(video_list)} videos)") |
| |
| |
| if MAX_SAMPLE > 0: |
| video_list = video_list[:MAX_SAMPLE] |
| print(f"Limiting to {MAX_SAMPLE} videos") |
| |
| |
| output_dir = f"{output_root}/{dataset_name}" |
| processed_files = set() |
| if os.path.exists(output_dir): |
| |
| for f in os.listdir(output_dir): |
| if f.endswith('.png'): |
| |
| parts = f.rsplit('_', 1) |
| if len(parts) == 2 and parts[1].startswith('0') and parts[1].endswith('.png'): |
| processed_files.add(parts[0] + '.mp4') |
| |
| print(f" - Already processed: {len(processed_files)} videos") |
| |
| |
| video_list = [v for v in video_list if v not in processed_files] |
| print(f" - Remaining to process: {len(video_list)} videos") |
| |
| processed_count = 0 |
| error_count = 0 |
| skip_count = 0 |
| |
| for j in tqdm(range(len(video_list)), desc=dataset_name): |
| v = video_list[j] |
| |
| |
| video_path = f"{root}/{v}" |
| if not os.path.exists(video_path): |
| print(f"\nWarning: Video file not found: {video_path}") |
| skip_count += 1 |
| continue |
| |
| |
| video_capture = cv2.VideoCapture(video_path) |
| if not video_capture.isOpened(): |
| print(f"\nError: Cannot open video {video_path}") |
| error_count += 1 |
| continue |
| |
| fps = video_capture.get(cv2.CAP_PROP_FPS) |
| frame_count = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT)) |
| |
| |
| if frame_count < WINDOW_LEN: |
| print(f"\nWarning: Video {v} has only {frame_count} frames (need {WINDOW_LEN}), skipping...") |
| video_capture.release() |
| skip_count += 1 |
| continue |
| |
| |
| |
| max_start = frame_count - WINDOW_LEN |
| if max_start <= 0: |
| print(f"\nWarning: Video {v} is too short, skipping...") |
| video_capture.release() |
| error_count += 1 |
| continue |
| |
| frame_idx = np.linspace( |
| 0, |
| max_start, |
| N_EXTRACT, |
| endpoint=True, |
| ).astype(int).tolist() |
| frame_idx.sort() |
| |
| |
| frame_sequence = [ |
| i for num in frame_idx for i in range(num, num + WINDOW_LEN) |
| ] |
| frame_list = [] |
| current_frame = 0 |
| |
| |
| while current_frame <= frame_sequence[-1]: |
| ret, frame = video_capture.read() |
| if not ret: |
| print(f"\nWarning: Error reading frame {current_frame} from {v}") |
| break |
| if current_frame in frame_sequence: |
| frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) |
| frame_list.append(cv2.resize(frame, (500, 500))) |
| current_frame += 1 |
| video_capture.release() |
| |
| |
| if len(frame_list) != len(frame_sequence): |
| print(f"\nWarning: Could not read all frames from {v} ({len(frame_list)}/{len(frame_sequence)}), skipping...") |
| skip_count += 1 |
| continue |
| |
| |
| name = os.path.splitext(v)[0] |
| audio_path = f"{audio_root}/{dataset_name}/{name}.wav" |
| |
| if not os.path.exists(audio_path): |
| print(f"\nWarning: Audio file not found for {v}: {audio_path}") |
| skip_count += 1 |
| continue |
| |
| |
| if not get_spectrogram(audio_path): |
| print(f"\nWarning: Could not generate spectrogram for {v}, skipping...") |
| skip_count += 1 |
| continue |
| |
| |
| mel = plt.imread("./temp/mel.png") * 255 |
| mel = mel.astype(np.uint8) |
| |
| |
| mapping = mel.shape[1] / frame_count |
| |
| |
| group = 0 |
| for i in range(0, len(frame_list), WINDOW_LEN): |
| idx = i // WINDOW_LEN |
| try: |
| begin = int(np.round(frame_sequence[i] * mapping)) |
| end = int(np.round((frame_sequence[i] + WINDOW_LEN) * mapping)) |
| |
| |
| begin = max(0, begin) |
| end = min(mel.shape[1], end) |
| |
| if end <= begin: |
| print(f"\nWarning: Invalid spectrogram bounds for {name}, skipping window {group}") |
| continue |
| |
| |
| sub_mel = cv2.resize( |
| mel[:, begin:end], (500 * WINDOW_LEN, 500) |
| ) |
| |
| |
| x = np.concatenate(frame_list[i:i + WINDOW_LEN], axis=1) |
| |
| |
| x = np.concatenate((sub_mel[:, :, :3], x[:, :, :3]), axis=0) |
| |
| |
| output_path = f"{output_root}/{dataset_name}/{name}_{group}.png" |
| plt.imsave(output_path, x) |
| group += 1 |
| |
| except Exception as e: |
| print(f"\nError processing window {group} for {name}: {str(e)}") |
| continue |
| |
| processed_count += 1 |
| |
| |
| if processed_count % 100 == 0: |
| if os.path.exists("./temp/mel.png"): |
| os.remove("./temp/mel.png") |
| |
| print(f"\n{dataset_name}:") |
| print(f" - Processed: {processed_count} videos") |
| print(f" - Skipped: {skip_count} videos") |
| print(f" - Errors: {error_count} videos") |
|
|
|
|
| if __name__ == "__main__": |
| print("="*50) |
| print("AVLips Preprocessing Script") |
| print("="*50) |
| print(f"Parameters:") |
| print(f" - N_EXTRACT: {N_EXTRACT} windows per video") |
| print(f" - WINDOW_LEN: {WINDOW_LEN} frames per window") |
| print(f" - MAX_SAMPLE: {MAX_SAMPLE} (0 = no limit)") |
| print(f" - Video root: {video_root}") |
| print(f" - Audio root: {audio_root}") |
| print(f" - Output root: {output_root}") |
| print("="*50) |
| |
| |
| if not os.path.exists(output_root): |
| os.makedirs(output_root, exist_ok=True) |
| if not os.path.exists("./temp"): |
| os.makedirs("./temp", exist_ok=True) |
| |
| run() |
| |
| print("\n" + "="*50) |
| print("Processing complete!") |
| print("="*50) |
|
|