Persival123 commited on
Commit
bad0c4e
1 Parent(s): 4c25cef

Upload app (1).py

Browse files
Files changed (1) hide show
  1. app (1).py +421 -0
app (1).py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import whisper
2
+ from faster_whisper import WhisperModel
3
+ import datetime
4
+ import subprocess
5
+ import gradio as gr
6
+ from pathlib import Path
7
+ import pandas as pd
8
+ import re
9
+ import time
10
+ import os
11
+ import numpy as np
12
+ from sklearn.cluster import AgglomerativeClustering
13
+ from sklearn.metrics import silhouette_score
14
+
15
+ from pytube import YouTube
16
+ import yt_dlp
17
+ import torch
18
+ import pyannote.audio
19
+ from pyannote.audio.pipelines.speaker_verification import PretrainedSpeakerEmbedding
20
+ from pyannote.audio import Audio
21
+ from pyannote.core import Segment
22
+
23
+ from gpuinfo import GPUInfo
24
+
25
+ import wave
26
+ import contextlib
27
+ from transformers import pipeline
28
+ import psutil
29
+
30
+ whisper_models = ["tiny", "base", "small", "medium", "large-v1", "large-v2"]
31
+ source_languages = {
32
+ "en": "English",
33
+ "zh": "Chinese",
34
+ "de": "German",
35
+ "es": "Spanish",
36
+ "ru": "Russian",
37
+ "ko": "Korean",
38
+ "fr": "French",
39
+ "ja": "Japanese",
40
+ "pt": "Portuguese",
41
+ "tr": "Turkish",
42
+ "pl": "Polish",
43
+ "ca": "Catalan",
44
+ "nl": "Dutch",
45
+ "ar": "Arabic",
46
+ "sv": "Swedish",
47
+ "it": "Italian",
48
+ "id": "Indonesian",
49
+ "hi": "Hindi",
50
+ "fi": "Finnish",
51
+ "vi": "Vietnamese",
52
+ "he": "Hebrew",
53
+ "uk": "Ukrainian",
54
+ "el": "Greek",
55
+ "ms": "Malay",
56
+ "cs": "Czech",
57
+ "ro": "Romanian",
58
+ "da": "Danish",
59
+ "hu": "Hungarian",
60
+ "ta": "Tamil",
61
+ "no": "Norwegian",
62
+ "th": "Thai",
63
+ "ur": "Urdu",
64
+ "hr": "Croatian",
65
+ "bg": "Bulgarian",
66
+ "lt": "Lithuanian",
67
+ "la": "Latin",
68
+ "mi": "Maori",
69
+ "ml": "Malayalam",
70
+ "cy": "Welsh",
71
+ "sk": "Slovak",
72
+ "te": "Telugu",
73
+ "fa": "Persian",
74
+ "lv": "Latvian",
75
+ "bn": "Bengali",
76
+ "sr": "Serbian",
77
+ "az": "Azerbaijani",
78
+ "sl": "Slovenian",
79
+ "kn": "Kannada",
80
+ "et": "Estonian",
81
+ "mk": "Macedonian",
82
+ "br": "Breton",
83
+ "eu": "Basque",
84
+ "is": "Icelandic",
85
+ "hy": "Armenian",
86
+ "ne": "Nepali",
87
+ "mn": "Mongolian",
88
+ "bs": "Bosnian",
89
+ "kk": "Kazakh",
90
+ "sq": "Albanian",
91
+ "sw": "Swahili",
92
+ "gl": "Galician",
93
+ "mr": "Marathi",
94
+ "pa": "Punjabi",
95
+ "si": "Sinhala",
96
+ "km": "Khmer",
97
+ "sn": "Shona",
98
+ "yo": "Yoruba",
99
+ "so": "Somali",
100
+ "af": "Afrikaans",
101
+ "oc": "Occitan",
102
+ "ka": "Georgian",
103
+ "be": "Belarusian",
104
+ "tg": "Tajik",
105
+ "sd": "Sindhi",
106
+ "gu": "Gujarati",
107
+ "am": "Amharic",
108
+ "yi": "Yiddish",
109
+ "lo": "Lao",
110
+ "uz": "Uzbek",
111
+ "fo": "Faroese",
112
+ "ht": "Haitian creole",
113
+ "ps": "Pashto",
114
+ "tk": "Turkmen",
115
+ "nn": "Nynorsk",
116
+ "mt": "Maltese",
117
+ "sa": "Sanskrit",
118
+ "lb": "Luxembourgish",
119
+ "my": "Myanmar",
120
+ "bo": "Tibetan",
121
+ "tl": "Tagalog",
122
+ "mg": "Malagasy",
123
+ "as": "Assamese",
124
+ "tt": "Tatar",
125
+ "haw": "Hawaiian",
126
+ "ln": "Lingala",
127
+ "ha": "Hausa",
128
+ "ba": "Bashkir",
129
+ "jw": "Javanese",
130
+ "su": "Sundanese",
131
+ }
132
+
133
+ source_language_list = [key[0] for key in source_languages.items()]
134
+
135
+ MODEL_NAME = "vumichien/whisper-medium-jp"
136
+ lang = "ja"
137
+
138
+ device = 0 if torch.cuda.is_available() else "cpu"
139
+ pipe = pipeline(
140
+ task="automatic-speech-recognition",
141
+ model=MODEL_NAME,
142
+ chunk_length_s=30,
143
+ device=device,
144
+ )
145
+ os.makedirs('output', exist_ok=True)
146
+ pipe.model.config.forced_decoder_ids = pipe.tokenizer.get_decoder_prompt_ids(language=lang, task="transcribe")
147
+
148
+ embedding_model = PretrainedSpeakerEmbedding(
149
+ "speechbrain/spkrec-ecapa-voxceleb",
150
+ device=torch.device("cuda" if torch.cuda.is_available() else "cpu"))
151
+
152
+ def transcribe(microphone, file_upload):
153
+ warn_output = ""
154
+ if (microphone is not None) and (file_upload is not None):
155
+ warn_output = (
156
+ "WARNING: You've uploaded an audio file and used the microphone. "
157
+ "The recorded file from the microphone will be used and the uploaded audio will be discarded.\n"
158
+ )
159
+
160
+ elif (microphone is None) and (file_upload is None):
161
+ return "ERROR: You have to either use the microphone or upload an audio file"
162
+
163
+ file = microphone if microphone is not None else file_upload
164
+
165
+ text = pipe(file)["text"]
166
+
167
+ return warn_output + text
168
+
169
+ def _return_yt_html_embed(yt_url):
170
+ video_id = yt_url.split("?v=")[-1]
171
+ HTML_str = (
172
+ f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
173
+ " </center>"
174
+ )
175
+ return HTML_str
176
+
177
+ def yt_transcribe(yt_url):
178
+ # yt = YouTube(yt_url)
179
+ # html_embed_str = _return_yt_html_embed(yt_url)
180
+ # stream = yt.streams.filter(only_audio=True)[0]
181
+ # stream.download(filename="audio.mp3")
182
+
183
+ ydl_opts = {
184
+ 'format': 'bestvideo*+bestaudio/best',
185
+ 'postprocessors': [{
186
+ 'key': 'FFmpegExtractAudio',
187
+ 'preferredcodec': 'mp3',
188
+ 'preferredquality': '192',
189
+ }],
190
+ 'outtmpl':'audio.%(ext)s',
191
+ }
192
+
193
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
194
+ ydl.download([yt_url])
195
+
196
+ text = pipe("audio.mp3")["text"]
197
+ return html_embed_str, text
198
+
199
+ def convert_time(secs):
200
+ return datetime.timedelta(seconds=round(secs))
201
+
202
+ def get_youtube(video_url):
203
+ # yt = YouTube(video_url)
204
+ # abs_video_path = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first().download()
205
+
206
+ ydl_opts = {
207
+ 'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
208
+ }
209
+
210
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
211
+ info = ydl.extract_info(video_url, download=False)
212
+ abs_video_path = ydl.prepare_filename(info)
213
+ ydl.process_info(info)
214
+
215
+ print("Success download video")
216
+ print(abs_video_path)
217
+ return abs_video_path
218
+
219
+ def speech_to_text(video_file_path, selected_source_lang, whisper_model, num_speakers):
220
+ """
221
+ # Transcribe youtube link using OpenAI Whisper
222
+ 1. Using Open AI's Whisper model to seperate audio into segments and generate transcripts.
223
+ 2. Generating speaker embeddings for each segments.
224
+ 3. Applying agglomerative clustering on the embeddings to identify the speaker for each segment.
225
+
226
+ Speech Recognition is based on models from OpenAI Whisper https://github.com/openai/whisper
227
+ Speaker diarization model and pipeline from by https://github.com/pyannote/pyannote-audio
228
+ """
229
+
230
+ # model = whisper.load_model(whisper_model)
231
+ # model = WhisperModel(whisper_model, device="cuda", compute_type="int8_float16")
232
+ model = WhisperModel(whisper_model, compute_type="int8")
233
+ time_start = time.time()
234
+ if(video_file_path == None):
235
+ raise ValueError("Error no video input")
236
+ print(video_file_path)
237
+
238
+ try:
239
+ # Read and convert youtube video
240
+ _,file_ending = os.path.splitext(f'{video_file_path}')
241
+ print(f'file enging is {file_ending}')
242
+ audio_file = video_file_path.replace(file_ending, ".wav")
243
+ print("starting conversion to wav")
244
+ os.system(f'ffmpeg -i "{video_file_path}" -ar 16000 -ac 1 -c:a pcm_s16le "{audio_file}"')
245
+
246
+ # Get duration
247
+ with contextlib.closing(wave.open(audio_file,'r')) as f:
248
+ frames = f.getnframes()
249
+ rate = f.getframerate()
250
+ duration = frames / float(rate)
251
+ print(f"conversion to wav ready, duration of audio file: {duration}")
252
+
253
+ # Transcribe audio
254
+ options = dict(language=selected_source_lang, beam_size=5, best_of=5)
255
+ transcribe_options = dict(task="transcribe", **options)
256
+ segments_raw, info = model.transcribe(audio_file, **transcribe_options)
257
+
258
+ # Convert back to original openai format
259
+ segments = []
260
+ i = 0
261
+ for segment_chunk in segments_raw:
262
+ chunk = {}
263
+ chunk["start"] = segment_chunk.start
264
+ chunk["end"] = segment_chunk.end
265
+ chunk["text"] = segment_chunk.text
266
+ segments.append(chunk)
267
+ i += 1
268
+ print("transcribe audio done with fast whisper")
269
+ except Exception as e:
270
+ raise RuntimeError("Error converting video to audio")
271
+
272
+ try:
273
+ # Create embedding
274
+ def segment_embedding(segment):
275
+ audio = Audio()
276
+ start = segment["start"]
277
+ # Whisper overshoots the end timestamp in the last segment
278
+ end = min(duration, segment["end"])
279
+ clip = Segment(start, end)
280
+ waveform, sample_rate = audio.crop(audio_file, clip)
281
+ return embedding_model(waveform[None])
282
+
283
+ embeddings = np.zeros(shape=(len(segments), 192))
284
+ for i, segment in enumerate(segments):
285
+ embeddings[i] = segment_embedding(segment)
286
+ embeddings = np.nan_to_num(embeddings)
287
+ print(f'Embedding shape: {embeddings.shape}')
288
+
289
+ if num_speakers == 0:
290
+ # Find the best number of speakers
291
+ score_num_speakers = {}
292
+
293
+ for num_speakers in range(2, 10+1):
294
+ clustering = AgglomerativeClustering(num_speakers).fit(embeddings)
295
+ score = silhouette_score(embeddings, clustering.labels_, metric='euclidean')
296
+ score_num_speakers[num_speakers] = score
297
+ best_num_speaker = max(score_num_speakers, key=lambda x:score_num_speakers[x])
298
+ print(f"The best number of speakers: {best_num_speaker} with {score_num_speakers[best_num_speaker]} score")
299
+ else:
300
+ best_num_speaker = num_speakers
301
+
302
+ # Assign speaker label
303
+ clustering = AgglomerativeClustering(best_num_speaker).fit(embeddings)
304
+ labels = clustering.labels_
305
+ for i in range(len(segments)):
306
+ segments[i]["speaker"] = 'SPEAKER ' + str(labels[i] + 1)
307
+
308
+ # Make output
309
+ objects = {
310
+ 'Start' : [],
311
+ 'End': [],
312
+ 'Speaker': [],
313
+ 'Text': []
314
+ }
315
+ text = ''
316
+ for (i, segment) in enumerate(segments):
317
+ if i == 0 or segments[i - 1]["speaker"] != segment["speaker"]:
318
+ objects['Start'].append(str(convert_time(segment["start"])))
319
+ objects['Speaker'].append(segment["speaker"])
320
+ if i != 0:
321
+ objects['End'].append(str(convert_time(segments[i - 1]["end"])))
322
+ objects['Text'].append(text)
323
+ text = ''
324
+ text += segment["text"] + ' '
325
+ objects['End'].append(str(convert_time(segments[i - 1]["end"])))
326
+ objects['Text'].append(text)
327
+
328
+ time_end = time.time()
329
+ time_diff = time_end - time_start
330
+ memory = psutil.virtual_memory()
331
+ gpu_utilization, gpu_memory = GPUInfo.gpu_usage()
332
+ gpu_utilization = gpu_utilization[0] if len(gpu_utilization) > 0 else 0
333
+ gpu_memory = gpu_memory[0] if len(gpu_memory) > 0 else 0
334
+ system_info = f"""
335
+ *Memory: {memory.total / (1024 * 1024 * 1024):.2f}GB, used: {memory.percent}%, available: {memory.available / (1024 * 1024 * 1024):.2f}GB.*
336
+ *Processing time: {time_diff:.5} seconds.*
337
+ *GPU Utilization: {gpu_utilization}%, GPU Memory: {gpu_memory}MiB.*
338
+ """
339
+ save_path = "output/transcript_result.csv"
340
+ df_results = pd.DataFrame(objects)
341
+ df_results.to_csv(save_path)
342
+ return df_results, system_info, save_path
343
+
344
+ except Exception as e:
345
+ raise RuntimeError("Error Running inference with local model", e)
346
+
347
+
348
+ # ---- Gradio Layout -----
349
+ # Inspiration from https://huggingface.co/spaces/RASMUS/Whisper-youtube-crosslingual-subtitles
350
+ video_in = gr.Video(label="Video file", mirror_webcam=False)
351
+ youtube_url_in = gr.Textbox(label="Youtube url", lines=1, interactive=True)
352
+ df_init = pd.DataFrame(columns=['Start', 'End', 'Speaker', 'Text'])
353
+ memory = psutil.virtual_memory()
354
+ selected_source_lang = gr.Dropdown(choices=source_language_list, type="value", value="en", label="Spoken language in video", interactive=True)
355
+ selected_whisper_model = gr.Dropdown(choices=whisper_models, type="value", value="base", label="Selected Whisper model", interactive=True)
356
+ number_speakers = gr.Number(precision=0, value=0, label="Input number of speakers for better results. If value=0, model will automatic find the best number of speakers", interactive=True)
357
+ system_info = gr.Markdown(f"*Memory: {memory.total / (1024 * 1024 * 1024):.2f}GB, used: {memory.percent}%, available: {memory.available / (1024 * 1024 * 1024):.2f}GB*")
358
+ download_transcript = gr.File(label="Download transcript")
359
+ transcription_df = gr.DataFrame(value=df_init,label="Transcription dataframe", row_count=(0, "dynamic"), max_rows = 10, wrap=True, overflow_row_behaviour='paginate')
360
+ title = "Whisper speaker diarization"
361
+ demo = gr.Blocks(title=title)
362
+ demo.encrypt = False
363
+
364
+
365
+ with demo:
366
+ with gr.Tab("Consult AI"):
367
+ gr.Markdown('''
368
+ <div>
369
+ <h1 style='text-align: center'>Your very own AI Scribe</h1>
370
+ This model uses Open AI and a modified Whisper model to produce A SOAP note using only your patient conversations! So give it a try!
371
+ </div>
372
+ ''')
373
+
374
+ with gr.Row():
375
+ gr.Markdown('''
376
+ ### Transcribe youtube link using OpenAI Whisper
377
+ ##### 1. Using Open AI's Whisper model to seperate audio into segments and generate transcripts.
378
+ ##### 2. Using Open AI to analyse the transcript in terms of your chosen profession.
379
+ ##### 3. Finally ooutputting your generated SOAP note specilized for your profession and for the patient in just 5 minutes!( Give or take)
380
+ ''')
381
+
382
+ with gr.Row():
383
+ with gr.Column():
384
+ youtube_url_in.render()
385
+ download_youtube_btn = gr.Button("Download Youtube video")
386
+ download_youtube_btn.click(get_youtube, [youtube_url_in], [
387
+ video_in])
388
+ print(video_in)
389
+
390
+
391
+ with gr.Row():
392
+ with gr.Column():
393
+ video_in.render()
394
+ with gr.Column():
395
+ gr.Markdown('''
396
+ ##### Here you can start the transcription process.
397
+ ##### Please select the source language for transcription.
398
+ ##### You can select a range of assumed numbers of speakers.
399
+ ''')
400
+ selected_source_lang.render()
401
+ selected_whisper_model.render()
402
+ number_speakers.render()
403
+ transcribe_btn = gr.Button("Transcribe audio and diarization")
404
+ transcribe_btn.click(speech_to_text,
405
+ [video_in, selected_source_lang, selected_whisper_model, number_speakers],
406
+ [transcription_df, system_info, download_transcript]
407
+ )
408
+
409
+ with gr.Row():
410
+ gr.Markdown('''
411
+ ##### Here you will get transcription output
412
+ ##### ''')
413
+
414
+
415
+ with gr.Row():
416
+ with gr.Column():
417
+ download_transcript.render()
418
+ transcription_df.render()
419
+ system_info.render()
420
+ gr.Markdown('''<center><img src='https://visitor-badge.glitch.me/badge?page_id=WhisperDiarizationSpeakers' alt='visitor badge'><a href="https://opensource.org/licenses/Apache-2.0"><img src='https://img.shields.io/badge/License-Apache_2.0-blue.svg' alt='License: Apache 2.0'></center>''')
421
+ demo.launch(debug=True)