Datasets:

Modalities:
Video
Languages:
English
Tags:
video
License:
File size: 9,626 Bytes
7f322ac
 
 
 
 
 
 
7450c6c
7f322ac
 
 
 
 
 
 
 
 
7450c6c
7f322ac
7450c6c
 
7f322ac
 
 
7450c6c
 
7f322ac
 
 
 
7450c6c
 
7f322ac
 
 
 
 
 
7450c6c
7f322ac
 
7450c6c
7f322ac
 
 
 
 
 
 
 
 
 
7450c6c
7f322ac
7450c6c
7f322ac
7450c6c
7f322ac
 
 
 
 
 
7450c6c
 
 
 
7f322ac
 
 
 
 
7450c6c
7f322ac
 
 
 
 
7450c6c
7f322ac
 
7450c6c
7f322ac
 
7450c6c
7f322ac
 
 
 
 
 
 
 
 
 
 
 
7450c6c
7f322ac
 
7450c6c
 
7f322ac
 
 
 
7450c6c
7f322ac
 
7450c6c
7f322ac
 
7450c6c
7f322ac
 
 
7450c6c
7f322ac
 
7450c6c
7f322ac
 
7450c6c
7f322ac
 
 
7450c6c
7f322ac
 
 
7450c6c
7f322ac
 
 
 
 
 
 
 
 
 
 
7450c6c
7f322ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7450c6c
7f322ac
 
 
 
 
 
 
 
 
 
 
 
7450c6c
 
7f322ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7450c6c
7f322ac
 
 
 
 
 
7450c6c
7f322ac
 
7450c6c
7f322ac
7450c6c
7f322ac
 
 
 
 
7450c6c
7f322ac
 
7450c6c
 
7f322ac
7450c6c
7f322ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7450c6c
7f322ac
 
7450c6c
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
import os
import subprocess
import json
from fractions import Fraction
import sys
import concurrent.futures
import time
import threading

def get_video_info(video_path):
    cmd = [
        "ffprobe", "-v", "error", "-show_entries",
        "format=duration:stream=codec_type,r_frame_rate",
        "-of", "json", "-i", video_path
    ]
    try:
        result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                text=True, timeout=45, check=False)
    except subprocess.TimeoutExpired:
        print(f"Probe timed out: {os.path.basename(video_path)}", file=sys.stderr)
        return None

    if result.returncode != 0:
        error_msg = result.stderr.strip()
        print(f"Probe error ({result.returncode}): {os.path.basename(video_path)} - {error_msg}", file=sys.stderr)
        return None

    try:
        data = json.loads(result.stdout)
    except json.JSONDecodeError:
        print(f"JSON decode error: {os.path.basename(video_path)}", file=sys.stderr)
        return None

    duration = None
    if "format" in data and "duration" in data["format"]:
        try:
            duration = float(data["format"]["duration"])
        except (ValueError, TypeError):
            print(f"Invalid duration format: {os.path.basename(video_path)}", file=sys.stderr)
            return None
    else:
        print(f"No duration found: {os.path.basename(video_path)}", file=sys.stderr)
        return None

    fps = None
    if "streams" in data:
        for stream in data["streams"]:
            if stream.get("codec_type") == "video" and "r_frame_rate" in stream:
                fps_str = stream["r_frame_rate"]
                if fps_str and fps_str != "0/0":
                    try:
                        fps = float(Fraction(*map(int, fps_str.split("/"))))
                        break
                    except (ValueError, ZeroDivisionError, TypeError):
                        print(f"Invalid FPS format '{fps_str}': {os.path.basename(video_path)}", file=sys.stderr)
                else:
                    print(f"Invalid FPS value '{fps_str}': {os.path.basename(video_path)}", file=sys.stderr)

    if duration is not None and fps is not None:
        return {
            "duration": duration,
            "fps": fps
        }
    elif duration is not None:
        print(f"No valid FPS found (duration was {duration:.2f}s): {os.path.basename(video_path)}", file=sys.stderr)
        return None
    else:
        return None

def process_video(video_path, log_file_path, log_lock):
    absolute_path = os.path.abspath(video_path)
    base_name = os.path.basename(video_path)
    status = "error"

    try:
        info = get_video_info(video_path)

        if not info:
            print(f"Skipping (probe error/missing info): {base_name}")
            try:
                os.remove(video_path)
                print(f"Removed (probe error/missing info): {base_name}")
                status = "removed"
            except OSError as e:
                print(f"Error removing {base_name}: {e}", file=sys.stderr)
                status = "error"
        else:
            duration, fps = info["duration"], info["fps"]
            remove_reason = None
            if duration < 9.5 or duration > 10.5:
                remove_reason = f"Duration {duration:.2f}s"
            elif abs(fps-30) > 1:
                remove_reason = f"FPS {fps:.2f}"

            if remove_reason:
                try:
                    os.remove(video_path)
                    print(f"Removed ({remove_reason}): {base_name}")
                    status = "removed"
                except OSError as e:
                    print(f"Error removing {base_name}: {e}", file=sys.stderr)
                    status = "error"
            else:
                status = "kept"

    except subprocess.TimeoutExpired:
        print(f"Timeout processing: {base_name}", file=sys.stderr)
        try:
            os.remove(video_path)
            print(f"Removed (timeout): {base_name}")
            status = "removed"
        except OSError as e:
            print(f"Error removing {base_name}: {e}", file=sys.stderr)
            status = "error"

    except Exception as e:
        print(f"Unexpected error processing {base_name}: {e}", file=sys.stderr)
        try:
            os.remove(video_path)
            print(f"Removed (unexpected error): {base_name}")
            status = "removed"
        except OSError as e:
            print(f"Error removing {base_name}: {e}", file=sys.stderr)
            status = "error"

    try:
        with log_lock:
            with open(log_file_path, 'a', encoding='utf-8') as log_f:
                log_f.write(absolute_path + '\n')
    except IOError as e:
        print(f"CRITICAL: Failed to write to log file {log_file_path}: {e}", file=sys.stderr)

    return status, absolute_path

def load_processed_files(log_file_path):
    processed = set()
    if os.path.exists(log_file_path):
        try:
            with open(log_file_path, 'r', encoding='utf-8') as f:
                for line in f:
                    processed.add(line.strip())
        except IOError as e:
            print(f"Warning: Could not read log file {log_file_path}: {e}", file=sys.stderr)
    return processed

def filter_videos_parallel(root_dir, log_file_path=".processed_videos.log", max_workers=None):
    if max_workers is None:
        max_workers = min(os.cpu_count() * 2, 16)

    print(f"--- Starting resumable parallel video filtering in {root_dir} ---")
    print(f"Using log file: {log_file_path}")
    print(f"Max workers: {max_workers}")
    start_time = time.time()

    processed_files_set = load_processed_files(log_file_path)
    print(f"Loaded {len(processed_files_set)} paths from log file.")

    video_paths_to_process = []
    total_files_found = 0
    for dirpath, _, files in os.walk(root_dir):
        for file in files:
            if file.lower().endswith(".mp4"):
                total_files_found += 1
                absolute_path = os.path.abspath(os.path.join(dirpath, file))
                if absolute_path not in processed_files_set:
                    video_paths_to_process.append(absolute_path)

    skipped_count = total_files_found - len(video_paths_to_process)
    total_to_process_this_run = len(video_paths_to_process)
    print(f"Found {total_files_found} total MP4 files.")
    if skipped_count > 0:
        print(f"Skipping {skipped_count} files already processed (found in log).")

    if not video_paths_to_process:
        print("No new videos to process.")
        return

    print(f"Processing {total_to_process_this_run} new files...")

    results = {"kept": 0, "removed": 0, "error": 0}
    log_lock = threading.Lock()
    completed_count = 0
    progress_update_interval = 50

    with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
        future_to_path = {
            executor.submit(process_video, path, log_file_path, log_lock): path
            for path in video_paths_to_process
        }

        try:
            for future in concurrent.futures.as_completed(future_to_path):
                original_path = future_to_path[future]
                try:
                    status, _ = future.result()
                    if status in results:
                        results[status] += 1
                    else:
                        print(f"Unknown status '{status}' received for {os.path.basename(original_path)}", file=sys.stderr)
                        results["error"] += 1

                    completed_count += 1
                    if completed_count % progress_update_interval == 0 or completed_count == total_to_process_this_run:
                        percent = (completed_count / total_to_process_this_run) * 100
                        progress_line = f"\rProgress: {completed_count} / {total_to_process_this_run} ({percent:.1f}%) completed. "
                        print(progress_line, end='', flush=True)

                except Exception as exc:
                    print(f"\nException for {os.path.basename(original_path)} during result retrieval: {exc}", file=sys.stderr)
                    results["error"] += 1
                    completed_count += 1
                    try:
                        with log_lock:
                            with open(log_file_path, 'a', encoding='utf-8') as log_f:
                                log_f.write(os.path.abspath(original_path) + '\n')
                    except IOError as e:
                        print(f"CRITICAL: Failed to write to log file after exception for {original_path}: {e}", file=sys.stderr)

        except KeyboardInterrupt:
            print("\nUser interrupted. Shutting down workers...")
            sys.exit(1)

    print()

    end_time = time.time()
    print("\n--- Filtering Complete ---")
    print(f"Files processed in this run: {total_to_process_this_run}")
    print(f"  Kept:     {results['kept']}")
    print(f"  Removed:  {results['removed']}")
    print(f"  Errors:   {results['error']}")
    print(f"Total files skipped (already processed): {skipped_count}")
    print(f"Total time for this run: {end_time - start_time:.2f} seconds")

if __name__ == "__main__":
    target_directory = "./train/train/"
    script_dir = os.path.dirname(os.path.abspath(__file__))
    log_file = os.path.join(script_dir, ".processed_videos.log")

    if not os.path.isdir(target_directory):
        print(f"Error: Target directory not found: {target_directory}", file=sys.stderr)
        sys.exit(1)

    filter_videos_parallel(target_directory, log_file_path=log_file)