Amazing-Python-Scripts

Форк
0
150 строк · 4.0 Кб
1
from pydub import AudioSegment
2
from pydub.silence import split_on_silence
3
import os
4
import collections
5
import contextlib
6
import sys
7
import wave
8
import os
9
import webrtcvad
10

11

12
def read_wave(path):
13

14
    with contextlib.closing(wave.open(path, 'rb')) as wf:
15
        num_channels = wf.getnchannels()
16
        assert num_channels == 1
17
        sample_width = wf.getsampwidth()
18
        assert sample_width == 2
19
        sample_rate = wf.getframerate()
20
        assert sample_rate in (8000, 16000, 32000, 48000)
21
        pcm_data = wf.readframes(wf.getnframes())
22
        return pcm_data, sample_rate
23

24

25
def write_wave(path, audio, sample_rate):
26

27
    with contextlib.closing(wave.open(path, 'wb')) as wf:
28
        wf.setnchannels(1)
29
        wf.setsampwidth(2)
30
        wf.setframerate(sample_rate)
31
        wf.writeframes(audio)
32
        frames = wf.getnframes()
33
        return frames / float(sample_rate)
34

35

36
class Frame(object):
37

38
    def __init__(self, bytes, timestamp, duration):
39
        self.bytes = bytes
40
        self.timestamp = timestamp
41
        self.duration = duration
42

43

44
def frame_generator(frame_duration_ms, audio, sample_rate):
45

46
    n = int(sample_rate * (frame_duration_ms / 1000.0) * 2)
47
    offset = 0
48
    timestamp = 0.0
49
    duration = (float(n) / sample_rate) / 2.0
50
    while offset + n < len(audio):
51
        yield Frame(audio[offset:offset + n], timestamp, duration)
52
        timestamp += duration
53
        offset += n
54

55

56
def vad_collector(sample_rate, frame_duration_ms,
57
                  padding_duration_ms, vad, frames):
58

59
    num_padding_frames = int(padding_duration_ms / frame_duration_ms)
60
    ring_buffer = collections.deque(maxlen=num_padding_frames)
61
    triggered = False
62

63
    voiced_frames = []
64
    for frame in frames:
65
        is_speech = vad.is_speech(frame.bytes, sample_rate)
66

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

71
            if num_voiced > 0.9 * ring_buffer.maxlen:
72
                triggered = True
73

74
                for f, s in ring_buffer:
75
                    voiced_frames.append(f)
76
                ring_buffer.clear()
77
        else:
78

79
            voiced_frames.append(frame)
80
            ring_buffer.append((frame, is_speech))
81
            num_unvoiced = len([f for f, speech in ring_buffer if not speech])
82

83
            if num_unvoiced > 0.9 * ring_buffer.maxlen:
84

85
                triggered = False
86
                yield b''.join([f.bytes for f in voiced_frames])
87
                ring_buffer.clear()
88
                voiced_frames = []
89
    if triggered:
90
        pass
91

92
    if voiced_frames:
93
        yield b''.join([f.bytes for f in voiced_frames])
94

95

96
path = "./frontend/speech-transcription-app/public/Original data"
97
if not os.path.exists(path):
98
    os.makedirs(path)
99
    print("Output folder created")
100
else:
101
    print("Output folder already present")
102
    sys.exit()
103

104

105
def folder(path):
106
    if not os.path.exists(path):
107
        os.makedirs(path)
108
        print("Output folder created")
109
    else:
110
        print("Output folder already present")
111

112

113
path = "./frontend/speech-transcription-app/public/Original data"
114
folder(path)
115
path = "./main/save"
116
folder(path)
117
path = "./main/discard"
118
folder(path)
119

120
file_name = "./main/mod_1.wav"
121
op_path = "./frontend/speech-transcription-app/public/Original data/audio_chunks"
122

123

124
def main(file_name, op_path):
125

126
    if os.path.isdir(op_path):
127
        print("Output folder already present")
128
    else:
129
        os.mkdir(op_path)
130
        print("Output folder created")
131

132
    audio, sample_rate = read_wave(file_name)
133
    vad = webrtcvad.Vad(2)
134
    frames = frame_generator(30, audio, sample_rate)
135
    segments = vad_collector(sample_rate, 30, 300, vad, frames)
136

137
    for i, segment in enumerate(segments):
138
        path = op_path+'/'+'chunk%004d.wav' % (i+1,)
139
        print(' Writing %s' % (path,))
140
        write_wave(path, segment, sample_rate)
141

142

143
# sys.argv[1]
144

145
# sys.argv[2]
146
file_name = "./main/mod_1.wav"
147
op_path = "./frontend/speech-transcription-app/public/Original data/audio_chunks"
148
main(file_name, op_path)
149

150
print("Audio Splitting Done")
151

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.