File size: 12,645 Bytes
fb0011a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
import os
import wave
import numpy as np
import subprocess
import tempfile


def filter_audio_list(

    input_path="train_list.txt",

    output_path="train_list_filtered.txt",

    min_duration_sec=1.25,

    max_duration_sec=10.0,

    min_amplitude_threshold=0.02,

    max_amplitude_threshold=0.94,

    ffmpeg_path="ffmpeg",

):
    """

    Filter lines in input_path according to duration and amplitude checks.

    Removes duplicate paths: if a given .wav path appears more than once in the

    input file, ALL occurrences are removed from the output.

    """
    if not os.path.exists(input_path):
        print(f"Error: Input file not found at '{input_path}'")
        return

    kept_lines = []
    removed_count = 0
    total_count = 0

    print(f"Starting to process '{input_path}'...")
    print(f" - Minimum duration: {min_duration_sec}s")
    print(f" - Maximum duration: {max_duration_sec}s")
    print(f" - Minimum amplitude: {min_amplitude_threshold}")
    print(f" - Maximum amplitude: {max_amplitude_threshold}")
    print(
        f" - Target format: 44.1kHz, 16-bit PCM, mono "
        f"(will convert using {ffmpeg_path})"
    )

    # Read input lines (preserve full line content for output)
    with open(input_path, "r", encoding="utf-8") as f:
        raw_lines = f.readlines()

    # Build canonical path for each non-empty line so we can detect duplicates
    base_dir = os.path.dirname(os.path.abspath(input_path)) or os.getcwd()
    canon_for_line = [None] * len(raw_lines)
    canon_to_indices = {}

    for idx, raw in enumerate(raw_lines):
        ln = raw.strip()
        if not ln:
            continue
        audio_rel = ln.split("|")[0].strip()
        # Match original behavior of prefixing "../" relative to the input file
        candidate = os.path.join(base_dir, "..", audio_rel)
        canonical = os.path.realpath(os.path.abspath(candidate))
        canon_for_line[idx] = canonical
        canon_to_indices.setdefault(canonical, []).append(idx)

    # Identify duplicate canonical paths (appear more than once)
    duplicates_canonical = {p for p, idxs in canon_to_indices.items() if len(idxs) > 1}
    if duplicates_canonical:
        print(
            f"  [Deduplication] Found {len(duplicates_canonical)} duplicate "
            "path(s). All occurrences will be removed."
        )
        for p in sorted(duplicates_canonical):
            print(f"    - {p} (occurrences={len(canon_to_indices[p])})")

    # Process lines, skipping duplicates early
    for idx, raw in enumerate(raw_lines):
        total_count += 1
        line = raw.strip()
        if not line:
            continue

        canonical = canon_for_line[idx]
        if canonical in duplicates_canonical:
            # remove duplicate occurrences (do not keep any of them)
            print(f"  [Removing] Duplicate entry: {line.split('|')[0].strip()}")
            removed_count += 1
            continue

        # Use the canonical absolute path for filesystem operations
        audio_path = canonical

        try:
            if not os.path.exists(audio_path):
                print(f"  [Warning] File not found, skipping: {audio_path}")
                removed_count += 1
                continue

            # Try to open as WAV; if not readable, convert with ffmpeg
            try:
                wav_file = wave.open(audio_path, "rb")
            except wave.Error:
                print(
                    f"  [Converting] Not a readable WAV: converting {audio_path} -> "
                    "44.1kHz 16-bit mono WAV"
                )
                tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
                tmp.close()
                cmd = [
                    ffmpeg_path,
                    "-y",
                    "-i",
                    audio_path,
                    "-ar",
                    "44100",
                    "-ac",
                    "1",
                    "-acodec",
                    "pcm_s16le",
                    tmp.name,
                ]
                proc = subprocess.run(
                    cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
                )
                if proc.returncode != 0:
                    stderr = proc.stderr.decode("utf-8", errors="replace")
                    print(
                        f"  [Error] ffmpeg conversion failed for {audio_path}: "
                        f"{stderr}"
                    )
                    removed_count += 1
                    try:
                        os.unlink(tmp.name)
                    except Exception:
                        pass
                    continue

                try:
                    os.replace(tmp.name, audio_path)
                except Exception as e:
                    print(
                        f"  [Error] Could not replace original with converted file: "
                        f"{e}"
                    )
                    removed_count += 1
                    try:
                        os.unlink(tmp.name)
                    except Exception:
                        pass
                    continue

                try:
                    wav_file = wave.open(audio_path, "rb")
                except wave.Error as e:
                    print(
                        f"  [Warning] Still cannot open after conversion: "
                        f"{audio_path} ({e})"
                    )
                    removed_count += 1
                    continue

            # Read header info then close
            try:
                num_frames = wav_file.getnframes()
                framerate = wav_file.getframerate()
                sampwidth = wav_file.getsampwidth()
                n_channels = wav_file.getnchannels()
            finally:
                try:
                    wav_file.close()
                except Exception:
                    pass

            # Convert to target format if needed
            needs_conversion = (
                framerate != 44100 or sampwidth != 2 or n_channels != 1
            )
            if needs_conversion:
                print(
                    f"  [Converting] {audio_path} (sr={framerate}, sw={sampwidth}, "
                    f"ch={n_channels}) -> 44.1kHz 16-bit mono"
                )
                tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
                tmp.close()
                cmd = [
                    ffmpeg_path,
                    "-y",
                    "-i",
                    audio_path,
                    "-ar",
                    "44100",
                    "-ac",
                    "1",
                    "-acodec",
                    "pcm_s16le",
                    tmp.name,
                ]
                proc = subprocess.run(
                    cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
                )
                if proc.returncode != 0:
                    stderr = proc.stderr.decode("utf-8", errors="replace")
                    print(
                        f"  [Error] ffmpeg conversion failed for {audio_path}: "
                        f"{stderr}"
                    )
                    removed_count += 1
                    try:
                        os.unlink(tmp.name)
                    except Exception:
                        pass
                    continue

                try:
                    os.replace(tmp.name, audio_path)
                except Exception as e:
                    print(
                        f"  [Error] Could not replace original with converted file: "
                        f"{e}"
                    )
                    removed_count += 1
                    try:
                        os.unlink(tmp.name)
                    except Exception:
                        pass
                    continue

            # Open the (possibly converted) WAV and perform checks
            try:
                with wave.open(audio_path, "rb") as wf:
                    num_frames = wf.getnframes()
                    framerate = wf.getframerate()
                    sampwidth = wf.getsampwidth()
                    n_channels = wf.getnchannels()

                    # Duration checks
                    duration = num_frames / float(framerate)
                    if duration < min_duration_sec:
                        print(
                            f"  [Removing] Short duration: {audio_path} "
                            f"({duration:.2f}s)"
                        )
                        removed_count += 1
                        continue

                    if duration > max_duration_sec:
                        print(
                            f"  [Removing] Too long: {audio_path} "
                            f"({duration:.2f}s > {max_duration_sec}s)"
                        )
                        removed_count += 1
                        continue

                    # Amplitude check (16-bit PCM)
                    if sampwidth == 2:
                        frames = wf.readframes(num_frames)
                        if not frames:
                            print(f"  [Removing] Empty audio: {audio_path}")
                            removed_count += 1
                            continue

                        samples = np.frombuffer(frames, dtype=np.int16)
                        if samples.size == 0:
                            print(f"  [Removing] Empty samples: {audio_path}")
                            removed_count += 1
                            continue

                        normalized_samples = samples.astype(np.float32) / 32768.0
                        max_abs_amplitude = float(
                            np.max(np.abs(normalized_samples))
                        )

                        if max_abs_amplitude > max_amplitude_threshold:
                            print(
                                f"  [Removing] High amplitude: {audio_path} "
                                f"(Peak: {max_abs_amplitude:.2f})"
                            )
                            removed_count += 1
                            continue

                        if max_abs_amplitude < min_amplitude_threshold:
                            print(
                                f"  [Removing] Low amplitude: {audio_path} "
                                f"(Peak: {max_abs_amplitude:.2f})"
                            )
                            removed_count += 1
                            continue
                    else:
                        print(
                            f"  [Info] Skipping amplitude check for {audio_path} "
                            f"(sample width: {sampwidth})"
                        )

            except wave.Error as e:
                print(
                    f"  [Warning] Could not read WAV after conversion/open: "
                    f"{audio_path} ({e})"
                )
                removed_count += 1
                continue

            # Passed all checks
            kept_lines.append(line + "\n")

        except wave.Error as e:
            print(
                f"  [Warning] Could not read WAV file, skipping: {audio_path} ({e})"
            )
            removed_count += 1
        except FileNotFoundError as e:
            print(f"  [Warning] File disappeared, skipping: {audio_path} ({e})")
            removed_count += 1
        except Exception as e:
            print(f"  [Error] An unexpected error occurred on line: {line}")
            print(f"          {e}")
            removed_count += 1

    with open(output_path, "w", encoding="utf-8") as f:
        f.writelines(kept_lines)

    print("\n--- Processing Complete ---")
    print(f"Total entries processed: {total_count}")
    print(f"Entries kept: {len(kept_lines)}")
    print(f"Entries removed (duration/amplitude/errors/dupes): {removed_count}")
    print(f"Filtered list saved to: '{output_path}'")


if __name__ == "__main__":
    # Ensure numpy and ffmpeg are available.
    filter_audio_list(
        input_path="train_3_filtered.txt",
        output_path="train_3_filtered_1.txt",
        min_duration_sec=1.25,
        max_duration_sec=10.0,
        min_amplitude_threshold=0.02,
        max_amplitude_threshold=0.93,
        ffmpeg_path="ffmpeg",
    )