Porjaz commited on
Commit
134a152
1 Parent(s): aefe5ec

Create custom_interface_app.py

Browse files
Files changed (1) hide show
  1. custom_interface_app.py +222 -0
custom_interface_app.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 classify_file(self, path):
90
+ # # waveform = self.load_audio(path)
91
+ # waveform, sr = librosa.load(path, sr=16000)
92
+ # waveform = torch.tensor(waveform)
93
+
94
+ # # Fake a batch:
95
+ # batch = waveform.unsqueeze(0)
96
+ # rel_length = torch.tensor([1.0])
97
+ # outputs = self.encode_batch(batch, rel_length)
98
+
99
+ # return outputs
100
+
101
+
102
+ def classify_file(self, path, device):
103
+ # Load the audio file
104
+ # path = "long_sample.wav"
105
+ waveform, sr = librosa.load(path, sr=16000)
106
+
107
+ # Get audio length in seconds
108
+ audio_length = len(waveform) / sr
109
+
110
+ if audio_length >= 20:
111
+ print(f"Audio is too long ({audio_length:.2f} seconds), splitting into segments")
112
+ # Detect non-silent segments
113
+ non_silent_intervals = librosa.effects.split(waveform, top_db=20) # Adjust top_db for sensitivity
114
+
115
+ segments = []
116
+ current_segment = []
117
+ current_length = 0
118
+ max_duration = 20 * sr # Maximum segment duration in samples (20 seconds)
119
+
120
+ for interval in non_silent_intervals:
121
+ start, end = interval
122
+ segment_part = waveform[start:end]
123
+
124
+ # If adding the next part exceeds max duration, store the segment and start a new one
125
+ if current_length + len(segment_part) > max_duration:
126
+ segments.append(np.concatenate(current_segment))
127
+ current_segment = []
128
+ current_length = 0
129
+
130
+ current_segment.append(segment_part)
131
+ current_length += len(segment_part)
132
+
133
+ # Append the last segment if it's not empty
134
+ if current_segment:
135
+ segments.append(np.concatenate(current_segment))
136
+
137
+ # Process each segment
138
+ outputs = []
139
+ for i, segment in enumerate(segments):
140
+ print(f"Processing segment {i + 1}/{len(segments)}, length: {len(segment) / sr:.2f} seconds")
141
+
142
+ segment_tensor = torch.tensor(segment).to(device)
143
+
144
+ # Fake a batch for the segment
145
+ batch = segment_tensor.unsqueeze(0).to(device)
146
+ rel_length = torch.tensor([1.0]).to(device) # Adjust if necessary
147
+
148
+ # Pass the segment through the ASR model
149
+ segment_output = self.encode_batch(device, batch, rel_length)
150
+ yield segment_output
151
+ else:
152
+ waveform = torch.tensor(waveform).to(device)
153
+ waveform = waveform.to(device)
154
+ # Fake a batch:
155
+ batch = waveform.unsqueeze(0)
156
+ rel_length = torch.tensor([1.0]).to(device)
157
+ outputs = self.encode_batch(device, batch, rel_length)
158
+ yield outputs
159
+
160
+
161
+ def classify_file_whisper(self, path, pipe, device):
162
+ waveform, sr = librosa.load(path, sr=16000)
163
+ transcription = pipe(waveform, generate_kwargs={"language": "macedonian"})["text"]
164
+ return transcription
165
+
166
+
167
+ def classify_file_mms(self, path, processor, model, device):
168
+ # Load the audio file
169
+ waveform, sr = librosa.load(path, sr=16000)
170
+
171
+ # Get audio length in seconds
172
+ audio_length = len(waveform) / sr
173
+
174
+ if audio_length >= 20:
175
+ print(f"MMS Audio is too long ({audio_length:.2f} seconds), splitting into segments")
176
+ # Detect non-silent segments
177
+ non_silent_intervals = librosa.effects.split(waveform, top_db=20) # Adjust top_db for sensitivity
178
+
179
+ segments = []
180
+ current_segment = []
181
+ current_length = 0
182
+ max_duration = 20 * sr # Maximum segment duration in samples (20 seconds)
183
+
184
+
185
+ for interval in non_silent_intervals:
186
+ start, end = interval
187
+ segment_part = waveform[start:end]
188
+
189
+ # If adding the next part exceeds max duration, store the segment and start a new one
190
+ if current_length + len(segment_part) > max_duration:
191
+ segments.append(np.concatenate(current_segment))
192
+ current_segment = []
193
+ current_length = 0
194
+
195
+ current_segment.append(segment_part)
196
+ current_length += len(segment_part)
197
+
198
+ # Append the last segment if it's not empty
199
+ if current_segment:
200
+ segments.append(np.concatenate(current_segment))
201
+
202
+ # Process each segment
203
+ outputs = []
204
+ for i, segment in enumerate(segments):
205
+ print(f"MMS Processing segment {i + 1}/{len(segments)}, length: {len(segment) / sr:.2f} seconds")
206
+
207
+ segment_tensor = torch.tensor(segment).to(device)
208
+
209
+ # Pass the segment through the ASR model
210
+ inputs = processor(segment_tensor, sampling_rate=16_000, return_tensors="pt").to(device)
211
+ outputs = model(**inputs).logits
212
+ ids = torch.argmax(outputs, dim=-1)[0]
213
+ segment_output = processor.decode(ids)
214
+ yield segment_output
215
+ else:
216
+ waveform = torch.tensor(waveform).to(device)
217
+ inputs = processor(waveform, sampling_rate=16_000, return_tensors="pt").to(device)
218
+ outputs = model(**inputs).logits
219
+ ids = torch.argmax(outputs, dim=-1)[0]
220
+ transcription = processor.decode(ids)
221
+ yield transcription
222
+