File size: 6,372 Bytes
b9f67de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from io import BytesIO
import multiprocessing as mp
from dataclasses import dataclass
import os
from pathlib import Path
import queue

import pydub
# import noisereduce as nr
import soundfile as sf
from tqdm import tqdm

from metadata import MetadataItem, LockedMetadata
from vad import remove_silence, get_vad_model_and_utils


@dataclass
class ProcessedFile:
    output: Path
    transcription: str
    speaker_id: str
    mic_id: str


@dataclass
class FileToProcess:
    input: Path
    input_txt: Path


# def noise_reduce(
#     input: Path,
# ) -> Path:
#     waveform, sample_rate = sf.read(input)
#     reduced_noise = nr.reduce_noise(y=waveform, sr=sample_rate, stationary=True, prop_decrease=0.8)

#     sf.write(input, reduced_noise, sample_rate)
#     return input


def pad_silence(
    input: Path | BytesIO,
    pad_length: int,
    format: str = 'wav',
) -> Path | BytesIO:
    audio = pydub.AudioSegment.from_file(input, format=format)

    # Add silence padding to the start and end
    padded: pydub.AudioSegment = pydub.AudioSegment.silent(duration=pad_length) + audio + pydub.AudioSegment.silent(duration=pad_length)
    padded.export(input, format=format)

    return input


def process_worker(
    work: mp.Queue,
    output: mp.Queue,
) -> None:
    vad_models_and_utils = get_vad_model_and_utils(use_cuda=False, use_onnx=False)

    while work.qsize() > 0:
        try:
            nitem = work.get(timeout=1)
        except queue.Empty:
            break

        result = process_file(
            vad_models_and_utils=vad_models_and_utils,
            inp=nitem.input,
            inp_txt=nitem.input_txt,
            output_directory=Path('dataset'),
            pad_length=25,
        )

        output.put(result)

    print(f"Worker {mp.current_process().name} finished processing.")


def process_file(
    vad_models_and_utils: tuple,
    inp: Path,
    inp_txt: Path,
    output_directory: Path,
    pad_length: int = 25,
) -> ProcessedFile | None:
    output_fpath = output_directory / f"{inp.stem}.wav"

    if not inp.exists():
        return None

    if not inp_txt.exists():
        return None

    transcription = (
        inp_txt
            .read_text()
            .strip()
    )

    speaker_id = inp.parent.name
    mic_id = inp.stem.split('_')[-1]  # Assuming the mic_id is the last part of the stem

    audio_mem = BytesIO()

    # Convert file to wav
    audio: pydub.AudioSegment = pydub.AudioSegment.from_file(inp)
    audio.export(audio_mem, format='wav')
    audio_mem.seek(0)

    silent_audio_mem = BytesIO()

    # Noise Reduction
    # output_fpath = noise_reduce(output_fpath)

    # Trim silence and remove leading/trailing silence
    _, _ = remove_silence(
        vad_models_and_utils,
        audio_path=audio_mem,
        out_path=silent_audio_mem,
        trim_just_beginning_and_end=True,
        format='wav',
    )

    silent_audio_mem.seek(0)

    # Pad silence
    output_audio = pad_silence(silent_audio_mem, pad_length)
    assert isinstance(output_audio, BytesIO), "Output audio should be a BytesIO object"

    # Actually save the processed audio to the output path
    with open(output_fpath, 'wb') as f:
        f.write(output_audio.getbuffer())

    return ProcessedFile(
        output=output_fpath,
        transcription=transcription,
        speaker_id=speaker_id,
        mic_id=mic_id,
    )


def main() -> None:
    txt = Path('txt')
    wav = Path('wav48_silence_trimmed')
    output_directory = Path('dataset')
    metadata_fpath = output_directory / 'metadata.csv'
    num_workers = os.cpu_count() or 1
    # num_workers = int(num_workers * 1.5)  # Use 75% of available CPU cores

    mp.set_start_method("spawn", force=True)

    print(f"Using {num_workers} workers for processing")

    if not txt.exists() or not wav.exists():
        raise ValueError("Input directories do not exist")

    if not output_directory.exists():
        output_directory.mkdir(parents=True, exist_ok=True)

    # file_name,text,mic_id
    metadata = LockedMetadata(key_field='id')

    if metadata_fpath.exists():
        metadata = LockedMetadata.load(metadata_fpath, key_field='id')

    files_to_process: list[FileToProcess] = []
    files = list(wav.glob('**/*.flac'))

    # stem maps to id
    # if the stem of the
    for file in files:
        stem = file.stem

        if stem in metadata:
            continue

        text = stem

        # Remove the _mic1 or _mic2 suffix from the stem
        if stem.endswith('_mic1') or stem.endswith('_mic2'):
            text = stem[:-5]

        # get the directory of the file
        directory = file.parent.name
        input_txt = txt / directory / f"{text}.txt"

        files_to_process.append(
            FileToProcess(
                input=file,
                input_txt=input_txt,
            )
        )

    work_queue: mp.Queue[FileToProcess] = mp.Queue()
    output_queue: mp.Queue[ProcessedFile | None] = mp.Queue()

    # fill the work queue with files to process
    for file in files_to_process:
        work_queue.put(file)


    # Before processing the files, ensure that the VAD model is downloaded.
    # This will ensure that the model is available for processing.
    get_vad_model_and_utils(use_cuda=False, use_onnx=False)

    processes = [
        mp.Process(
            target=process_worker,
            args=(work_queue, output_queue),
        )
        for _ in range(num_workers)
    ]

    # Process each file.
    results: list[ProcessedFile] = []

    try:
        results: list[ProcessedFile] = []

        for w in processes:
            w.start()

        for _ in tqdm(range(len(files_to_process)), desc="Processing files", unit="file"):
            result = output_queue.get()

            if result is None:
                continue

            results.append(result)

        # Wait for workers to finish
        for w in processes:
            w.join()
    finally:
        for result in results:
            metadata.add(
                MetadataItem(
                    id=result.output.stem,
                    text=result.transcription,
                    speaker_id=result.speaker_id,
                    file_name=result.output.name,
                    mic_id=result.mic_id,
                )
            )

        metadata.save(metadata_fpath)


if __name__ == '__main__':
    main()