File size: 13,443 Bytes
050271c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
import torch
# os.system("pip install git+https://github.com/openai/whisper.git")
import gradio as gr
import whisper
import librosa
import plotly.express as px
from threading import Thread
from statistics import mode, mean
import time


model = whisper.load_model("large", device='cpu')
print('loaded whisper')

vad, vad_utils = torch.hub.load(repo_or_dir='snakers4/silero-vad',
                                model='silero_vad',
                                force_reload=False,
                                onnx=False)
print('loaded silero')
(get_speech_timestamps,
 save_audio,
 read_audio,
 VADIterator,
 collect_chunks) = vad_utils
vad_iterator = VADIterator(vad)

global x, y, j, audio_vec, transcribe, STOP, languages, not_detected, main_lang, STARTED
x = []
y = []
j = 0
STOP = False
audio_vec = torch.tensor([])
transcribe = ''
languages = []
not_detected = True
main_lang = ''
STARTED = False

css = """
        .gradio-container {
            font-family: 'IBM Plex Sans', sans-serif;
        }
        .gr-button {
            color: white;
            border-color: black;
            background: black;
        }
        input[type='range'] {
            accent-color: black;
        }
        .dark input[type='range'] {
            accent-color: #dfdfdf;
        }
        .container {
            max-width: 730px;
            margin: auto;
            padding-top: 1.5rem;
        }
        .details:hover {
            text-decoration: underline;
        }
        .gr-button {
            white-space: nowrap;
        }
        .gr-button:focus {
            border-color: rgb(147 197 253 / var(--tw-border-opacity));
            outline: none;
            box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000);
            --tw-border-opacity: 1;
            --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);
            --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px var(--tw-ring-offset-width)) var(--tw-ring-color);
            --tw-ring-color: rgb(191 219 254 / var(--tw-ring-opacity));
            --tw-ring-opacity: .5;
        }
        .footer {
            margin-bottom: 45px;
            margin-top: 35px;
            text-align: center;
            border-bottom: 1px solid #e5e5e5;
        }
        .footer>p {
            font-size: .8rem;
            display: inline-block;
            padding: 0 10px;
            transform: translateY(10px);
            background: white;
        }
        .dark .footer {
            border-color: #303030;
        }
        .dark .footer>p {
            background: #0b0f19;
        }
        .prompt h4{
            margin: 1.25em 0 .25em 0;
            font-weight: bold;
            font-size: 115%;
        }
        .animate-spin {
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            from {
                transform: rotate(0deg);
            }
            to {
                transform: rotate(360deg);
            }
        }
        #share-btn-container {
            display: flex; margin-top: 1.5rem !important; padding-left: 0.5rem !important; padding-right: 0.5rem
            !important; background-color: #000000; justify-content: center; align-items: center; border-radius: 9999px
            !important; width: 13rem;
        }
        #share-btn {
            all: initial; color: #ffffff;font-weight: 600; cursor:pointer; font-family: 'IBM Plex Sans', sans-serif;
            margin-left: 0.5rem !important; padding-top: 0.25rem !important; padding-bottom: 0.25rem !important;
        }
        #share-btn * {
            all: unset;
        }
"""


# def transcribe_chunk():
#     print('********************************')
#     global audio_vec, transcribe, STOP
#     print('Enter trans chunk')
#     counter = 0
#     i = 0
#     while not STOP:
#         if audio_vec.size()[0] // 32000 > counter and audio_vec.size()[0] > 0:
#             print('audio_vec.size()[0] % 32000', audio_vec.size()[0] % 32000)
#             print('audio size', audio_vec.size()[0])
#             chunk = whisper.pad_or_trim(audio_vec[32000*counter: 32000*(counter + 1)])
#             mel_th = whisper.log_mel_spectrogram(chunk).to(model.device)
#             options = whisper.DecodingOptions(fp16=False)
#             result = whisper.decode(model, mel_th, options)
#             no_speech_prob = result.no_speech_prob
#             if no_speech_prob < 0.4:
#                 transcribe += result.text + ' '
#             counter += 1
def transcribe_chunk(audio, vad_prob):
    global languages
    trnscrb = ''
    audio = whisper.pad_or_trim(audio)
    mel = whisper.log_mel_spectrogram(audio).to(model.device)
    options = whisper.DecodingOptions(fp16= False, task='transcribe')
    result = whisper.decode(model, mel, options)
    no_speech_prob = result.no_speech_prob
    mel = whisper.log_mel_spectrogram(audio).to(model.device)

    _, probs = model.detect_language(mel)

    temp_lang = max(probs, key=probs.get)

    print(result.text, "no_speech_prob: ",no_speech_prob, 1 - vad_prob)
    if no_speech_prob < 0.6:
        trnscrb = result.text + ' '
        languages.append(temp_lang)
        if len(languages) > 3:
            languages.pop(0)
    return trnscrb


def inference(audio):
    global x, y, j, audio_vec, transcribe, languages, not_detected, main_lang, STARTED
    print('enter inference')
    if j == 0:
        thread.start()
        STARTED = True
    wav2 = whisper.load_audio(audio, sr=16000)
    wav = torch.from_numpy(librosa.load(audio, sr=16000)[0])
    audio_vec = torch.cat((audio_vec, wav))
    speech_probs = []
    window_size_samples = 1600
    for i in range(0, len(wav), window_size_samples):
        chunk = wav[i: i + window_size_samples]
        if len(chunk) < window_size_samples:
            break
        speech_prob = vad(chunk, 16000).item()
        speech_probs.append(speech_prob)
    vad_iterator.reset_states()
    sample_per_sec = 16000 / window_size_samples
    x.extend([j + i / sample_per_sec for i in range(len(speech_probs))])
    y.extend(speech_probs)
    j = max(x)
    fig = px.line(x=x, y=y)

    whisper_audio = whisper.pad_or_trim(wav2)
    mel = whisper.log_mel_spectrogram(whisper_audio).to(model.device)

    _, probs = model.detect_language(mel)


    temp_lang = max(probs, key=probs.get)
    print(temp_lang)

    languages.append(temp_lang)
    if len(languages) > 5:
        languages.pop(0)

    curr_lang = mode(languages)
    print(curr_lang, languages)

    if curr_lang == 'iw':
        return 'he', fig, gr.update(visible=True), transcribe, gr.update(visible=True), gr.update(visible=True)
    return curr_lang, fig, gr.update(visible=True), transcribe, gr.update(visible=True), gr.update(visible=True)


def clear():
    global x, y, j, audio_vec, transcribe, thread, STOP, languages, main_lang, not_detected ,STARTED
    STOP = True
    if STARTED:
        thread.join()
    STARTED = False
    x = []
    y = []
    j = 0
    audio_vec = torch.tensor([])
    transcribe = ''
    STOP = False
    languages = []
    main_lang = ''
    not_detected = True
    thread = Thread(target=transcribe_chunk)
    print('clean:', x, y, j, transcribe, audio_vec)
    return '', gr.update(visible=False), gr.update(visible=False), '', gr.update(visible=False), gr.update(visible=False),


def inference_file(audio):
    time.sleep(0.8)
    global x, y, j, audio_vec, transcribe, languages, not_detected, main_lang
    wav = torch.from_numpy(librosa.load(audio, sr=16000)[0])
    audio_vec = torch.cat((audio_vec, wav))
    speech_probs = []
    window_size_samples = 1600
    for i in range(0, len(wav), window_size_samples):
        chunk = wav[i: i + window_size_samples]
        if len(chunk) < window_size_samples:
            break
        speech_prob = vad(chunk, 16000).item()
        speech_probs.append(speech_prob)
    vad_iterator.reset_states()
    sample_per_sec = 16000 / window_size_samples
    x.extend([j + i / sample_per_sec for i in range(len(speech_probs))])
    y.extend(speech_probs)
    j = max(x)
    fig = px.line(x=x, y=y)

    mean_speech_probs = mean(speech_probs)

    if wav.shape[0] > 16000 * 30:
        start = 0
        end = 16000 * 30
        chunk = wav[start:end]
        chunk_idx = 0
        while end < wav.shape[0]:
            transcribe += transcribe_chunk(chunk)
            chunk_idx += 1
            start = chunk_idx * 30 * 16000
            if start >= wav.shape[0]:
                break
            end = (chunk_idx + 1) * 30 * 16000
            if end >= wav.shape[0]:
                end = wav.shape[0] - 1
                chunk = wav[start:end]
    else:
        transcribe += transcribe_chunk(wav, mean_speech_probs)

    curr_lang = ''
    if len(languages) > 0:
        curr_lang = mode(languages)
        print(curr_lang, languages)

    if curr_lang == 'iw':
        return 'he', fig, gr.update(visible=True), transcribe, gr.update(visible=True), gr.update(visible=True)
    return curr_lang, fig, gr.update(visible=True), transcribe, gr.update(visible=True), gr.update(visible=True)


block = gr.Blocks(css=css)


def play_sound():
    global audio_vec
    import soundfile as sf
    print(audio_vec)
    sf.write('uploaded.wav', data=audio_vec, samplerate=16000)
    from pygame import mixer
    mixer.init()
    mixer.music.load('uploaded.wav')
    mixer.music.play()


def change_audio(string):
    # if string == 'סטרימינג':
    #     return gr.Audio.update(source="microphone",), gr.update(visible=False),  gr.update(visible=False), gr.update(visible=False)
    # else:
    #     return gr.Audio.update(source='upload'), gr.update(visible=True),  gr.update(visible=False), gr.update(visible=False)
    if string == 'סטרימינג':
        return gr.update(visible=True),  gr.update(visible=False), gr.update(visible=False), \
            gr.update(visible=False), gr.update(visible=False)
    elif string == 'הקלטה':
        print('in mesholav')
        return gr.update(visible=False),  gr.update(visible=False), gr.update(visible=False), \
            gr.update(visible=True), gr.update(visible=True)
    else:
        return gr.update(visible=False),  gr.update(visible=True), gr.update(visible=True), \
            gr.update(visible=False), gr.update(visible=False)


with block:
    gr.HTML(
        """
            <div style="text-align: center; max-width: 650px; margin: 0 auto;">
              <div
                style="
                  display: inline-flex;
                  align-items: center;
                  gap: 0.8rem;
                  font-size: 1.75rem;
                "
              >
                <h1 style="font-weight: 900; margin-bottom: 7px;">
                  Whisper
                </h1>
              </div>
            </div>
        """
    )
    with gr.Group():
        plot = gr.Plot(show_label=False, visible=False)
        with gr.Row(equal_height=True):
            with gr.Box():
                radio = gr.Radio(["סטרימינג", "הקלטה", "קובץ"], label="?איך תרצה לספק את האודיו")
                with gr.Row().style(mobile_collapse=False, equal_height=True):
                    audio = gr.Audio(

                        show_label=False,
                        source="microphone",
                        type="filepath",
                        visible=True

                    )
                    audio2 = gr.Audio(

                        label="Input Audio",
                        show_label=False,
                        source="upload",
                        type="filepath",
                        visible=False

                    )
                    audio3 = gr.Audio(
                        label="Input Audio",
                        show_label=False,
                        source="microphone",
                        type="filepath",
                        visible=False
                    )

                    trans_btn = gr.Button("Transcribe", visible=False)
                    trans_btn3 = gr.Button("Transcribe", visible=False)

        text = gr.Textbox(show_label=False, elem_id="result-textarea")
        text2 = gr.Textbox(show_label=False, elem_id="result-textarea")
        with gr.Row():
            clear_btn = gr.Button("Clear", visible=False)
            play_btn = gr.Button('Play audio', visible=False)

        radio.change(fn=change_audio, inputs=radio, outputs=[audio, trans_btn, audio2, trans_btn3, audio3])
        trans_btn.click(inference_file, audio2, [text, plot, plot, text2, clear_btn, play_btn])
        trans_btn3.click(inference_file, audio3, [text, plot, plot, text2, clear_btn, play_btn])
        audio.stream(inference_file, audio, [text, plot, plot, text2, clear_btn, play_btn])
        play_btn.click(play_sound)
        clear_btn.click(clear, inputs=[], outputs=[text, plot, plot, text2, clear_btn, play_btn])

        gr.HTML('''
        <div class="footer">
                    <p>Model by Moses team - Whisper Demo
                    </p>
        </div>
        ''')
        gr.HTML('''
           <img style="text-align: center; max-width: 650px; margin: 0 auto;" src="https://geekflare.com/wp-content/uploads/2022/02/speechrecognitionapi.png", alt="Girl in a jacket" width="500" height="600">
        ''')

global thread
thread = Thread(target=transcribe_chunk)
block.queue().launch()