Porjaz commited on
Commit
786f240
·
verified ·
1 Parent(s): 5499946

Update custom_interface_app_backup.py

Browse files
Files changed (1) hide show
  1. custom_interface_app_backup.py +173 -0
custom_interface_app_backup.py CHANGED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_w2v2(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
+
37
+ def filter_repetitions(self, seq, max_repetition_length):
38
+ seq = list(seq)
39
+ output = []
40
+ max_n = len(seq) // 2
41
+ for n in range(max_n, 0, -1):
42
+ max_repetitions = max(max_repetition_length // n, 1)
43
+ # Don't need to iterate over impossible n values:
44
+ # len(seq) can change a lot during iteration
45
+ if (len(seq) <= n*2) or (len(seq) <= max_repetition_length):
46
+ continue
47
+ iterator = enumerate(seq)
48
+ # Fill first buffers:
49
+ buffers = [[next(iterator)[1]] for _ in range(n)]
50
+ for seq_index, token in iterator:
51
+ current_buffer = seq_index % n
52
+ if token != buffers[current_buffer][-1]:
53
+ # No repeat, we can flush some tokens
54
+ buf_len = sum(map(len, buffers))
55
+ flush_start = (current_buffer-buf_len) % n
56
+ # Keep n-1 tokens, but possibly mark some for removal
57
+ for flush_index in range(buf_len - buf_len%n):
58
+ if (buf_len - flush_index) > n-1:
59
+ to_flush = buffers[(flush_index + flush_start) % n].pop(0)
60
+ else:
61
+ to_flush = None
62
+ # Here, repetitions get removed:
63
+ if (flush_index // n < max_repetitions) and to_flush is not None:
64
+ output.append(to_flush)
65
+ elif (flush_index // n >= max_repetitions) and to_flush is None:
66
+ output.append(to_flush)
67
+ buffers[current_buffer].append(token)
68
+ # At the end, final flush
69
+ current_buffer += 1
70
+ buf_len = sum(map(len, buffers))
71
+ flush_start = (current_buffer-buf_len) % n
72
+ for flush_index in range(buf_len):
73
+ to_flush = buffers[(flush_index + flush_start) % n].pop(0)
74
+ # Here, repetitions just get removed:
75
+ if flush_index // n < max_repetitions:
76
+ output.append(to_flush)
77
+ seq = []
78
+ to_delete = 0
79
+ for token in output:
80
+ if token is None:
81
+ to_delete += 1
82
+ elif to_delete > 0:
83
+ to_delete -= 1
84
+ else:
85
+ seq.append(token)
86
+ output = []
87
+ return seq
88
+
89
+
90
+ def increase_volume(self, waveform, threshold_db=-25):
91
+ # Measure loudness using RMS
92
+ loudness_vector = librosa.feature.rms(y=waveform)
93
+ average_loudness = np.mean(loudness_vector)
94
+ average_loudness_db = librosa.amplitude_to_db(average_loudness)
95
+
96
+ print(f"Average Loudness: {average_loudness_db} dB")
97
+
98
+ # Check if loudness is below threshold and apply gain if needed
99
+ if average_loudness_db < threshold_db:
100
+ # Calculate gain needed
101
+ gain_db = threshold_db - average_loudness_db
102
+ gain = librosa.db_to_amplitude(gain_db) # Convert dB to amplitude factor
103
+
104
+ # Apply gain to the audio signal
105
+ waveform = waveform * gain
106
+ loudness_vector = librosa.feature.rms(y=waveform)
107
+ average_loudness = np.mean(loudness_vector)
108
+ average_loudness_db = librosa.amplitude_to_db(average_loudness)
109
+
110
+ print(f"Average Loudness: {average_loudness_db} dB")
111
+ return waveform
112
+
113
+
114
+ def classify_file_w2v2(self, waveform, device):
115
+ # Get audio length in seconds
116
+ sr = 16000
117
+ audio_length = len(waveform) / sr
118
+
119
+ if audio_length >= 30:
120
+ print(f"Audio is too long ({audio_length:.2f} seconds), splitting into segments")
121
+ # Detect non-silent segments
122
+
123
+ non_silent_intervals = librosa.effects.split(waveform, top_db=20) # Adjust top_db for sensitivity
124
+
125
+ segments = []
126
+ current_segment = []
127
+ current_length = 0
128
+ max_duration = 30 * sr # Maximum segment duration in samples (20 seconds)
129
+
130
+
131
+ for interval in non_silent_intervals:
132
+ start, end = interval
133
+ segment_part = waveform[start:end]
134
+
135
+ # If adding the next part exceeds max duration, store the segment and start a new one
136
+ if current_length + len(segment_part) > max_duration:
137
+ segments.append(np.concatenate(current_segment))
138
+ current_segment = []
139
+ current_length = 0
140
+
141
+ current_segment.append(segment_part)
142
+ current_length += len(segment_part)
143
+
144
+ # Append the last segment if it's not empty
145
+ if current_segment:
146
+ segments.append(np.concatenate(current_segment))
147
+
148
+ # Process each segment
149
+ outputs = []
150
+ for i, segment in enumerate(segments):
151
+ print(f"Processing segment {i + 1}/{len(segments)}, length: {len(segment) / sr:.2f} seconds")
152
+
153
+ # import soundfile as sf
154
+ # sf.write(f"outputs/segment_{i}.wav", segment, sr)
155
+
156
+ segment_tensor = torch.tensor(segment).to(device)
157
+
158
+ # Fake a batch for the segment
159
+ batch = segment_tensor.unsqueeze(0).to(device)
160
+ rel_length = torch.tensor([1.0]).to(device) # Adjust if necessary
161
+
162
+ # Pass the segment through the ASR model
163
+ result = " ".join(self.encode_batch_w2v2(device, batch, rel_length)[0])
164
+ # outputs.append(result)
165
+ yield result
166
+ else:
167
+ waveform = torch.tensor(waveform).to(device)
168
+ waveform = waveform.to(device)
169
+ # Fake a batch:
170
+ batch = waveform.unsqueeze(0)
171
+ rel_length = torch.tensor([1.0]).to(device)
172
+ outputs = " ".join(self.encode_batch_w2v2(device, batch, rel_length)[0])
173
+ yield outputs