File size: 9,467 Bytes
b58079c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
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
"""

############ Custom parameter ##############
N_EXTRACT = 10   # number of extracted windows from video
WINDOW_LEN = 5   # frames of each window
MAX_SAMPLE = 0   # maximum number of videos to process (0 means no limit)
############################################

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:
        # Create output directory
        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)")
        
        # Limit number of samples if MAX_SAMPLE > 0
        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'):
                    # 提取视频文件名(去掉 _group.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]
            
            # Check if video file exists
            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
            
            # Load video
            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))
            
            # Skip if video is too short
            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
            
            # Select N_EXTRACT starting points from frames
            # Ensure we don't go beyond frame_count - WINDOW_LEN
            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()
            
            # Selected frames
            frame_sequence = [
                i for num in frame_idx for i in range(num, num + WINDOW_LEN)
            ]
            frame_list = []
            current_frame = 0
            
            # Read frames
            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()
            
            # Check if we got all frames
            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
            
            # Load audio
            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
            
            # Generate spectrogram
            if not get_spectrogram(audio_path):
                print(f"\nWarning: Could not generate spectrogram for {v}, skipping...")
                skip_count += 1
                continue
            
            # Load spectrogram
            mel = plt.imread("./temp/mel.png") * 255  # load spectrogram (int)
            mel = mel.astype(np.uint8)
            
            # Calculate mapping from video frames to spectrogram time axis
            mapping = mel.shape[1] / frame_count
            
            # Process each window
            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))
                    
                    # Ensure bounds are valid
                    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
                    
                    # Extract and resize spectrogram for this window
                    sub_mel = cv2.resize(
                        mel[:, begin:end], (500 * WINDOW_LEN, 500)
                    )
                    
                    # Concatenate frames horizontally
                    x = np.concatenate(frame_list[i:i + WINDOW_LEN], axis=1)
                    
                    # Concatenate spectrogram (top) and frames (bottom)
                    x = np.concatenate((sub_mel[:, :, :3], x[:, :, :3]), axis=0)
                    
                    # Save output image
                    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
            
            # Clean up temp file periodically
            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)
    
    # Create necessary directories
    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)