File size: 4,102 Bytes
c22b544
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Zero out the speech channel (channel 0) from all WAV files in audio_mixtures_old_both
and strip speech from all JSON command variant targets.

Usage:
    python scripts/zero_out_speech.py \
        --src  data/audio_mixtures_old_both \
        --dst  data/audio_mixtures_no_speech \
        --splits train test test_700
"""

import argparse
import json
import os
import glob
from pathlib import Path

import torch
import torchaudio


def process_json(metadata):
    """Strip speech from all command variant targets. Returns count of empty-target variants."""
    empty_count = 0

    # List format (train/test)
    if "command_variants" in metadata:
        for variant in metadata["command_variants"]:
            variant["target_sources"] = [s for s in variant["target_sources"] if s != "speech"]
            variant["target_channels"] = [c for c in variant["target_channels"] if c != 0]
            if len(variant["target_sources"]) == 0:
                empty_count += 1

    # Singular dict format (test_700 pre-computed)
    if "command_variant" in metadata and isinstance(metadata["command_variant"], dict):
        cv = metadata["command_variant"]
        cv["target_sources"] = [s for s in cv["target_sources"] if s != "speech"]
        cv["target_channels"] = [c for c in cv["target_channels"] if c != 0]
        if len(cv["target_sources"]) == 0:
            empty_count += 1

    return empty_count


def process_split(src_dir, dst_dir):
    """Process all WAV/JSON pairs in a split directory."""
    os.makedirs(dst_dir, exist_ok=True)

    wav_files = sorted(glob.glob(os.path.join(src_dir, "*.wav")))
    total_files = 0
    total_empty_variants = 0

    for wav_path in wav_files:
        basename = os.path.splitext(os.path.basename(wav_path))[0]
        json_path = os.path.join(src_dir, basename + ".json")
        dst_wav = os.path.join(dst_dir, basename + ".wav")
        dst_json = os.path.join(dst_dir, basename + ".json")

        # --- WAV: zero out channel 0 (speech) ---
        audio, sr = torchaudio.load(wav_path)  # (5, T)
        audio[0, :] = 0.0
        torchaudio.save(dst_wav, audio, sr)

        # --- JSON: strip speech from targets ---
        if os.path.exists(json_path):
            with open(json_path, "r") as f:
                metadata = json.load(f)

            empty_count = process_json(metadata)
            total_empty_variants += empty_count

            with open(dst_json, "w") as f:
                json.dump(metadata, f, indent=2)

        total_files += 1
        if total_files % 500 == 0:
            print(f"  Processed {total_files}/{len(wav_files)} files...")

    return total_files, total_empty_variants


def main():
    parser = argparse.ArgumentParser(description="Zero out speech channel from audio_mixtures dataset")
    parser.add_argument("--src", required=True, help="Source audio_mixtures directory")
    parser.add_argument("--dst", required=True, help="Destination directory")
    parser.add_argument("--splits", nargs="+", default=["train", "test", "test_700"],
                        help="Split directories to process")
    args = parser.parse_args()

    print(f"Source: {args.src}")
    print(f"Destination: {args.dst}")
    print(f"Splits: {args.splits}")
    print()

    os.makedirs(args.dst, exist_ok=True)

    grand_total_files = 0
    grand_total_empty = 0

    for split in args.splits:
        src_split = os.path.join(args.src, split)
        dst_split = os.path.join(args.dst, split)

        if not os.path.isdir(src_split):
            print(f"Skipping {split}/ (not found)")
            continue

        print(f"Processing {split}/...")
        n_files, n_empty = process_split(src_split, dst_split)
        grand_total_files += n_files
        grand_total_empty += n_empty
        print(f"  Done: {n_files} files, {n_empty} empty-target variants (noise-cancelling)")
        print()

    print("=" * 50)
    print(f"Total files processed: {grand_total_files}")
    print(f"Total empty-target variants: {grand_total_empty}")
    print(f"Output at: {args.dst}")


if __name__ == "__main__":
    main()