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
|
|
1 |
+
import torch
|
2 |
+
from speechbrain.inference.interfaces import Pretrained
|
3 |
+
import librosa
|
4 |
+
import numpy as np
|
5 |
+
|
6 |
+
|
7 |
+
class ASR(Pretrained):
|
8 |
+
def __init__(self, *args, **kwargs):
|
9 |
+
super().__init__(*args, **kwargs)
|
10 |
+
|
11 |
+
def encode_batch(self, device, wavs, wav_lens=None, normalize=False):
|
12 |
+
wavs = wavs.to(device)
|
13 |
+
wav_lens = wav_lens.to(device)
|
14 |
+
|
15 |
+
# Forward pass
|
16 |
+
encoded_outputs = self.mods.encoder_w2v2(wavs.detach())
|
17 |
+
# append
|
18 |
+
tokens_bos = torch.zeros((wavs.size(0), 1), dtype=torch.long).to(device)
|
19 |
+
embedded_tokens = self.mods.embedding(tokens_bos)
|
20 |
+
decoder_outputs, _ = self.mods.decoder(embedded_tokens, encoded_outputs, wav_lens)
|
21 |
+
|
22 |
+
# Output layer for seq2seq log-probabilities
|
23 |
+
predictions = self.hparams.test_search(encoded_outputs, wav_lens)[0]
|
24 |
+
# predicted_words = [self.hparams.tokenizer.decode_ids(prediction).split(" ") for prediction in predictions]
|
25 |
+
predicted_words = []
|
26 |
+
for prediction in predictions:
|
27 |
+
prediction = [token for token in prediction if token != 0]
|
28 |
+
predicted_words.append(self.hparams.tokenizer.decode_ids(prediction).split(" "))
|
29 |
+
prediction = []
|
30 |
+
for sent in predicted_words:
|
31 |
+
sent = self.filter_repetitions(sent, 3)
|
32 |
+
prediction.append(sent)
|
33 |
+
predicted_words = prediction
|
34 |
+
return predicted_words
|
35 |
+
|
36 |
+
def filter_repetitions(self, seq, max_repetition_length):
|
37 |
+
seq = list(seq)
|
38 |
+
output = []
|
39 |
+
max_n = len(seq) // 2
|
40 |
+
for n in range(max_n, 0, -1):
|
41 |
+
max_repetitions = max(max_repetition_length // n, 1)
|
42 |
+
# Don't need to iterate over impossible n values:
|
43 |
+
# len(seq) can change a lot during iteration
|
44 |
+
if (len(seq) <= n*2) or (len(seq) <= max_repetition_length):
|
45 |
+
continue
|
46 |
+
iterator = enumerate(seq)
|
47 |
+
# Fill first buffers:
|
48 |
+
buffers = [[next(iterator)[1]] for _ in range(n)]
|
49 |
+
for seq_index, token in iterator:
|
50 |
+
current_buffer = seq_index % n
|
51 |
+
if token != buffers[current_buffer][-1]:
|
52 |
+
# No repeat, we can flush some tokens
|
53 |
+
buf_len = sum(map(len, buffers))
|
54 |
+
flush_start = (current_buffer-buf_len) % n
|
55 |
+
# Keep n-1 tokens, but possibly mark some for removal
|
56 |
+
for flush_index in range(buf_len - buf_len%n):
|
57 |
+
if (buf_len - flush_index) > n-1:
|
58 |
+
to_flush = buffers[(flush_index + flush_start) % n].pop(0)
|
59 |
+
else:
|
60 |
+
to_flush = None
|
61 |
+
# Here, repetitions get removed:
|
62 |
+
if (flush_index // n < max_repetitions) and to_flush is not None:
|
63 |
+
output.append(to_flush)
|
64 |
+
elif (flush_index // n >= max_repetitions) and to_flush is None:
|
65 |
+
output.append(to_flush)
|
66 |
+
buffers[current_buffer].append(token)
|
67 |
+
# At the end, final flush
|
68 |
+
current_buffer += 1
|
69 |
+
buf_len = sum(map(len, buffers))
|
70 |
+
flush_start = (current_buffer-buf_len) % n
|
71 |
+
for flush_index in range(buf_len):
|
72 |
+
to_flush = buffers[(flush_index + flush_start) % n].pop(0)
|
73 |
+
# Here, repetitions just get removed:
|
74 |
+
if flush_index // n < max_repetitions:
|
75 |
+
output.append(to_flush)
|
76 |
+
seq = []
|
77 |
+
to_delete = 0
|
78 |
+
for token in output:
|
79 |
+
if token is None:
|
80 |
+
to_delete += 1
|
81 |
+
elif to_delete > 0:
|
82 |
+
to_delete -= 1
|
83 |
+
else:
|
84 |
+
seq.append(token)
|
85 |
+
output = []
|
86 |
+
return seq
|
87 |
+
|
88 |
+
|
89 |
+
def increase_volume(self, waveform, threshold_db=-25):
|
90 |
+
# Measure loudness using RMS
|
91 |
+
loudness_vector = librosa.feature.rms(y=waveform)
|
92 |
+
average_loudness = np.mean(loudness_vector)
|
93 |
+
average_loudness_db = librosa.amplitude_to_db(average_loudness)
|
94 |
+
|
95 |
+
print(f"Average Loudness: {average_loudness_db} dB")
|
96 |
+
|
97 |
+
# Check if loudness is below threshold and apply gain if needed
|
98 |
+
if average_loudness_db < threshold_db:
|
99 |
+
# Calculate gain needed
|
100 |
+
gain_db = threshold_db - average_loudness_db
|
101 |
+
gain = librosa.db_to_amplitude(gain_db) # Convert dB to amplitude factor
|
102 |
+
|
103 |
+
# Apply gain to the audio signal
|
104 |
+
waveform = waveform * gain
|
105 |
+
loudness_vector = librosa.feature.rms(y=waveform)
|
106 |
+
average_loudness = np.mean(loudness_vector)
|
107 |
+
average_loudness_db = librosa.amplitude_to_db(average_loudness)
|
108 |
+
|
109 |
+
print(f"Average Loudness: {average_loudness_db} dB")
|
110 |
+
return waveform
|
111 |
+
|
112 |
+
|
113 |
+
def classify_file(self, path, device):
|
114 |
+
# Load the audio file
|
115 |
+
# path = "long_sample.wav"
|
116 |
+
waveform, sr = librosa.load(path, sr=16000)
|
117 |
+
|
118 |
+
# increase the volume if needed
|
119 |
+
# waveform = self.increase_volume(waveform)
|
120 |
+
|
121 |
+
# Get audio length in seconds
|
122 |
+
audio_length = len(waveform) / sr
|
123 |
+
|
124 |
+
if audio_length >= 20:
|
125 |
+
print(f"Audio is too long ({audio_length:.2f} seconds), splitting into segments")
|
126 |
+
# Detect non-silent segments
|
127 |
+
|
128 |
+
non_silent_intervals = librosa.effects.split(waveform, top_db=20) # Adjust top_db for sensitivity
|
129 |
+
|
130 |
+
segments = []
|
131 |
+
current_segment = []
|
132 |
+
current_length = 0
|
133 |
+
max_duration = 20 * sr # Maximum segment duration in samples (20 seconds)
|
134 |
+
|
135 |
+
|
136 |
+
for interval in non_silent_intervals:
|
137 |
+
start, end = interval
|
138 |
+
segment_part = waveform[start:end]
|
139 |
+
|
140 |
+
# If adding the next part exceeds max duration, store the segment and start a new one
|
141 |
+
if current_length + len(segment_part) > max_duration:
|
142 |
+
segments.append(np.concatenate(current_segment))
|
143 |
+
current_segment = []
|
144 |
+
current_length = 0
|
145 |
+
|
146 |
+
current_segment.append(segment_part)
|
147 |
+
current_length += len(segment_part)
|
148 |
+
|
149 |
+
# Append the last segment if it's not empty
|
150 |
+
if current_segment:
|
151 |
+
segments.append(np.concatenate(current_segment))
|
152 |
+
|
153 |
+
# Process each segment
|
154 |
+
outputs = []
|
155 |
+
for i, segment in enumerate(segments):
|
156 |
+
print(f"Processing segment {i + 1}/{len(segments)}, length: {len(segment) / sr:.2f} seconds")
|
157 |
+
|
158 |
+
# import soundfile as sf
|
159 |
+
# sf.write(f"outputs/segment_{i}.wav", segment, sr)
|
160 |
+
|
161 |
+
segment_tensor = torch.tensor(segment).to(device)
|
162 |
+
|
163 |
+
# Fake a batch for the segment
|
164 |
+
batch = segment_tensor.unsqueeze(0).to(device)
|
165 |
+
rel_length = torch.tensor([1.0]).to(device) # Adjust if necessary
|
166 |
+
|
167 |
+
# Pass the segment through the ASR model
|
168 |
+
segment_output = self.encode_batch(device, batch, rel_length)
|
169 |
+
yield segment_output
|
170 |
+
else:
|
171 |
+
waveform = torch.tensor(waveform).to(device)
|
172 |
+
waveform = waveform.to(device)
|
173 |
+
# Fake a batch:
|
174 |
+
batch = waveform.unsqueeze(0)
|
175 |
+
rel_length = torch.tensor([1.0]).to(device)
|
176 |
+
outputs = self.encode_batch(device, batch, rel_length)
|
177 |
+
yield outputs
|
178 |
+
|
179 |
+
|
180 |
+
def classify_file_whisper(self, path, pipe, device):
|
181 |
+
waveform, sr = librosa.load(path, sr=16000)
|
182 |
+
transcription = pipe(waveform, generate_kwargs={"language": "macedonian"})["text"]
|
183 |
+
return transcription
|
184 |
+
|
185 |
+
|
186 |
+
def classify_file_mms(self, path, processor, model, device):
|
187 |
+
# Load the audio file
|
188 |
+
waveform, sr = librosa.load(path, sr=16000)
|
189 |
+
|
190 |
+
# Get audio length in seconds
|
191 |
+
audio_length = len(waveform) / sr
|
192 |
+
|
193 |
+
if audio_length >= 20:
|
194 |
+
print(f"MMS Audio is too long ({audio_length:.2f} seconds), splitting into segments")
|
195 |
+
# Detect non-silent segments
|
196 |
+
non_silent_intervals = librosa.effects.split(waveform, top_db=20) # Adjust top_db for sensitivity
|
197 |
+
|
198 |
+
segments = []
|
199 |
+
current_segment = []
|
200 |
+
current_length = 0
|
201 |
+
max_duration = 20 * sr # Maximum segment duration in samples (20 seconds)
|
202 |
+
|
203 |
+
|
204 |
+
for interval in non_silent_intervals:
|
205 |
+
start, end = interval
|
206 |
+
segment_part = waveform[start:end]
|
207 |
+
|
208 |
+
# If adding the next part exceeds max duration, store the segment and start a new one
|
209 |
+
if current_length + len(segment_part) > max_duration:
|
210 |
+
segments.append(np.concatenate(current_segment))
|
211 |
+
current_segment = []
|
212 |
+
current_length = 0
|
213 |
+
|
214 |
+
current_segment.append(segment_part)
|
215 |
+
current_length += len(segment_part)
|
216 |
+
|
217 |
+
# Append the last segment if it's not empty
|
218 |
+
if current_segment:
|
219 |
+
segments.append(np.concatenate(current_segment))
|
220 |
+
|
221 |
+
# Process each segment
|
222 |
+
outputs = []
|
223 |
+
for i, segment in enumerate(segments):
|
224 |
+
print(f"MMS Processing segment {i + 1}/{len(segments)}, length: {len(segment) / sr:.2f} seconds")
|
225 |
+
|
226 |
+
segment_tensor = torch.tensor(segment).to(device)
|
227 |
+
|
228 |
+
# Pass the segment through the ASR model
|
229 |
+
inputs = processor(segment_tensor, sampling_rate=16_000, return_tensors="pt").to(device)
|
230 |
+
outputs = model(**inputs).logits
|
231 |
+
ids = torch.argmax(outputs, dim=-1)[0]
|
232 |
+
segment_output = processor.decode(ids)
|
233 |
+
yield segment_output
|
234 |
+
else:
|
235 |
+
waveform = torch.tensor(waveform).to(device)
|
236 |
+
inputs = processor(waveform, sampling_rate=16_000, return_tensors="pt").to(device)
|
237 |
+
outputs = model(**inputs).logits
|
238 |
+
ids = torch.argmax(outputs, dim=-1)[0]
|
239 |
+
transcription = processor.decode(ids)
|
240 |
+
yield transcription
|