File size: 7,224 Bytes
fdbda89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e17176
fdbda89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import argparse
import collections
from typing import List

import matplotlib.pyplot as plt
import numpy as np
from scipy.io import wavfile
import webrtcvad

from project_settings import project_path


class Frame(object):
    def __init__(self, signal: np.ndarray, timestamp, duration):
        self.signal = signal
        self.timestamp = timestamp
        self.duration = duration


class WebRTCVad(object):
    def __init__(self,
                 agg: int = 3,
                 frame_duration_ms: int = 30,
                 padding_duration_ms: int = 300,
                 silence_duration_threshold: float = 0.3,
                 sample_rate: int = 8000
                 ):
        self.agg = agg
        self.frame_duration_ms = frame_duration_ms
        self.padding_duration_ms = padding_duration_ms
        self.silence_duration_threshold = silence_duration_threshold
        self.sample_rate = sample_rate

        self._vad = webrtcvad.Vad(mode=agg)

        # frames
        self.frame_length = int(sample_rate * (frame_duration_ms / 1000.0))
        self.frame_timestamp = 0.0
        self.signal_cache = None

        # segments
        self.num_padding_frames = int(padding_duration_ms / frame_duration_ms)
        self.ring_buffer = collections.deque(maxlen=self.num_padding_frames)
        self.triggered = False
        self.voiced_frames: List[Frame] = list()
        self.segments = list()

        # vad segments
        self.is_first_segment = True
        self.timestamp_start = 0.0
        self.timestamp_end = 0.0

    def signal_to_frames(self, signal: np.ndarray):
        frames = list()

        l = len(signal)

        duration = (float(self.frame_length) / self.sample_rate)

        for offset in range(0, l, self.frame_length):
            sub_signal = signal[offset:offset+self.frame_length]

            frame = Frame(sub_signal, self.frame_timestamp, duration)
            self.frame_timestamp += duration

            frames.append(frame)
        return frames

    def segments_generator(self, signal: np.ndarray):
        # signal rounding
        if self.signal_cache is not None:
            signal = np.concatenate([self.signal_cache, signal])

        rest = len(signal) % self.frame_length

        if rest == 0:
            self.signal_cache = None
            signal_ = signal
        else:
            self.signal_cache = signal[-rest:]
            signal_ = signal[:-rest]

        # frames
        frames = self.signal_to_frames(signal_)

        for frame in frames:
            audio_bytes = bytes(frame.signal)
            is_speech = self._vad.is_speech(audio_bytes, self.sample_rate)

            if not self.triggered:
                self.ring_buffer.append((frame, is_speech))
                num_voiced = len([f for f, speech in self.ring_buffer if speech])

                if num_voiced > 0.9 * self.ring_buffer.maxlen:
                    self.triggered = True

                    for f, _ in self.ring_buffer:
                        self.voiced_frames.append(f)
                    self.ring_buffer.clear()
            else:
                self.voiced_frames.append(frame)
                self.ring_buffer.append((frame, is_speech))
                num_unvoiced = len([f for f, speech in self.ring_buffer if not speech])
                if num_unvoiced > 0.9 * self.ring_buffer.maxlen:
                    self.triggered = False
                    segment = [
                        np.concatenate([f.signal for f in self.voiced_frames]),
                        self.voiced_frames[0].timestamp,
                        self.voiced_frames[-1].timestamp
                    ]
                    yield segment
                    self.ring_buffer.clear()
                    self.voiced_frames = []

    def vad_segments_generator(self, segments_generator):
        segments = list(segments_generator)

        for i, segment in enumerate(segments):
            start = round(segment[1], 4)
            end = round(segment[2], 4)

            if self.is_first_segment:
                self.timestamp_start = start
                self.timestamp_end = end
                self.is_first_segment = False
                continue

            if self.timestamp_start:
                sil_duration = start - self.timestamp_end
                if sil_duration > self.silence_duration_threshold:
                    vad_segment = [self.timestamp_start, self.timestamp_end]
                    yield vad_segment

                    self.timestamp_start = start
                    self.timestamp_end = end
                else:
                    self.timestamp_end = end

    def vad(self, signal: np.ndarray) -> List[list]:
        segments = self.segments_generator(signal)
        vad_segments = self.vad_segments_generator(segments)
        vad_segments = list(vad_segments)
        return vad_segments

    def last_vad_segments(self) -> List[list]:
        # last segments
        if len(self.voiced_frames) == 0:
            segments = []
        else:
            segment = [
                np.concatenate([f.signal for f in self.voiced_frames]),
                self.voiced_frames[0].timestamp,
                self.voiced_frames[-1].timestamp
            ]
            segments = [segment]

        # last vad segments
        vad_segments = self.vad_segments_generator(segments)
        vad_segments = list(vad_segments)

        vad_segments = vad_segments + [[self.timestamp_start, self.timestamp_end]]
        return vad_segments


def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--wav_file",
        default=(project_path / "data/early_media/3300999628164249998.wav").as_posix(),
        type=str,
    )
    parser.add_argument(
        "--agg",
        default=3,
        type=int,
        help="The level of aggressiveness of the VAD: [0-3]'"
    )
    parser.add_argument(
        "--frame_duration_ms",
        default=30,
        type=int,
    )
    parser.add_argument(
        "--silence_duration_threshold",
        default=0.3,
        type=float,
        help="minimum silence duration, in seconds."
    )
    args = parser.parse_args()
    return args


SAMPLE_RATE = 8000


def main():
    args = get_args()

    w_vad = WebRTCVad(sample_rate=SAMPLE_RATE)

    sample_rate, signal = wavfile.read(args.wav_file)
    if SAMPLE_RATE != sample_rate:
        raise AssertionError

    vad_segments = list()

    segments = w_vad.vad(signal)
    vad_segments += segments
    for segment in segments:
        print(segment)

    # last vad segment
    segments = w_vad.last_vad_segments()
    vad_segments += segments
    for segment in segments:
        print(segment)

    # plot
    time = np.arange(0, len(signal)) / sample_rate
    plt.figure(figsize=(12, 5))
    plt.plot(time, signal / 32768, color='b')
    for start, end in vad_segments:
        plt.axvline(x=start, ymin=0.25, ymax=0.75, color='g', linestyle='--', label='开始端点')  # 标记开始端点
        plt.axvline(x=end, ymin=0.25, ymax=0.75, color='r', linestyle='--', label='结束端点')  # 标记结束端点

    plt.show()
    return


if __name__ == '__main__':
    main()