yama commited on
Commit
2c631bc
1 Parent(s): b2d6296

Update app.py

Browse files
Files changed (2) hide show
  1. app.py +366 -54
  2. requirements.txt +2 -3
app.py CHANGED
@@ -1,69 +1,381 @@
 
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import openai
3
  import os
4
- from io import BytesIO
5
  import tempfile
6
  from pydub import AudioSegment
7
- import shutil
8
 
9
- def create_meeting_summary(openai_key, prompt, uploaded_audio, max_transcribe_seconds):
10
- openai.api_key = openai_key
11
 
12
- # 音声ファイルを開く
13
- audio = AudioSegment.from_file(uploaded_audio)
 
 
 
 
 
 
 
 
14
 
15
- # 文字起こしする音声データの上限を設定する
16
- if len(audio) > int(max_transcribe_seconds) * 1000:
17
- audio = audio[:int(max_transcribe_seconds) * 1000]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
- # ファイルサイズを削減するために音声ファイルを圧縮する
20
- compressed_audio = audio.set_frame_rate(16000).set_channels(1)
21
 
22
- # 圧縮した音声ファイルをmp3形式で一時ファイルに保存する
23
- with tempfile.NamedTemporaryFile(delete=True, suffix=".mp3") as tmp:
24
- compressed_audio.export(tmp.name, format="mp3")
25
 
26
- transcript = openai.Audio.transcribe("whisper-1", open(tmp.name, "rb"), response_format="verbose_json")
27
- transcript_text = ""
28
- for segment in transcript.segments:
29
- transcript_text += f"{segment['text']}\n"
30
 
31
- system_template = prompt
32
 
33
- completion = openai.ChatCompletion.create(
34
- model="gpt-3.5-turbo",
35
- messages=[
36
- {"role": "system", "content": system_template},
37
- {"role": "user", "content": transcript_text}
38
- ]
39
  )
40
- summary = completion.choices[0].message.content
41
- return summary, transcript_text
42
-
43
-
44
- inputs = [
45
- gr.Textbox(lines=1, label="openai_key", type="password"),
46
- gr.TextArea(label="プロンプト", value="""会議の文字起こしが渡されます。
47
-
48
- この会議のサマリーをMarkdown形式で作成してください。サマリーは、以下のような形式で書いてください。
49
- - 会議の目的
50
- - 会議の内容
51
- - 会議の結果"""),
52
- gr.Audio(type="filepath", label="音声ファイルをアップロード"),
53
- gr.Textbox(lines=1, label="最大文字起こし時間(秒)", type="text"),
54
- ]
55
-
56
- outputs = [
57
- gr.Textbox(label="会議サマリー"),
58
- gr.Textbox(label="文字起こし")
59
- ]
60
-
61
- app = gr.Interface(
62
- fn=create_meeting_summary,
63
- inputs=inputs,
64
- outputs=outputs,
65
- title="会議サマリー生成アプリ",
66
- description="音声ファイルをアップロードして、会議のサマリーをMarkdown形式で作成します。"
67
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
- app.launch(debug=True)
 
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
  import openai
31
  import os
 
32
  import tempfile
33
  from pydub import AudioSegment
 
34
 
 
 
35
 
36
+ whisper_models = ["tiny", "base", "small", "medium", "large-v1", "large-v2"]
37
+ source_languages = {
38
+ "en": "English",
39
+ "ja": "Japanese",
40
+ }
41
+
42
+ source_language_list = [key[0] for key in source_languages.items()]
43
+
44
+ MODEL_NAME = "vumichien/whisper-medium-jp"
45
+ lang = "ja"
46
 
47
+ device = 0 if torch.cuda.is_available() else "cpu"
48
+ pipe = pipeline(
49
+ task="automatic-speech-recognition",
50
+ model=MODEL_NAME,
51
+ chunk_length_s=30,
52
+ device=device,
53
+ )
54
+ os.makedirs('output', exist_ok=True)
55
+ pipe.model.config.forced_decoder_ids = pipe.tokenizer.get_decoder_prompt_ids(language=lang, task="transcribe")
56
+
57
+ embedding_model = PretrainedSpeakerEmbedding(
58
+ "speechbrain/spkrec-ecapa-voxceleb",
59
+ device=torch.device("cuda" if torch.cuda.is_available() else "cpu"))
60
+
61
+
62
+ def transcribe(microphone, file_upload):
63
+ warn_output = ""
64
+ if (microphone is not None) and (file_upload is not None):
65
+ warn_output = (
66
+ "WARNING: You've uploaded an audio file and used the microphone. "
67
+ "The recorded file from the microphone will be used and the uploaded audio will be discarded.\n"
68
+ )
69
 
70
+ elif (microphone is None) and (file_upload is None):
71
+ return "ERROR: You have to either use the microphone or upload an audio file"
72
 
73
+ file = microphone if microphone is not None else file_upload
 
 
74
 
75
+ text = pipe(file)["text"]
 
 
 
76
 
77
+ return warn_output + text
78
 
79
+
80
+ def _return_yt_html_embed(yt_url):
81
+ video_id = yt_url.split("?v=")[-1]
82
+ HTML_str = (
83
+ f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
84
+ " </center>"
85
  )
86
+ return HTML_str
87
+
88
+
89
+ def yt_transcribe(yt_url):
90
+ # yt = YouTube(yt_url)
91
+ # html_embed_str = _return_yt_html_embed(yt_url)
92
+ # stream = yt.streams.filter(only_audio=True)[0]
93
+ # stream.download(filename="audio.mp3")
94
+
95
+ ydl_opts = {
96
+ 'format': 'bestvideo*+bestaudio/best',
97
+ 'postprocessors': [{
98
+ 'key': 'FFmpegExtractAudio',
99
+ 'preferredcodec': 'mp3',
100
+ 'preferredquality': '192',
101
+ }],
102
+ 'outtmpl': 'audio.%(ext)s',
103
+ }
104
+
105
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
106
+ ydl.download([yt_url])
107
+
108
+ text = pipe("audio.mp3")["text"]
109
+ return html_embed_str, text
110
+
111
+
112
+ def convert_time(secs):
113
+ return datetime.timedelta(seconds=round(secs))
114
+
115
+
116
+ def get_youtube(video_url):
117
+ # yt = YouTube(video_url)
118
+ # abs_video_path = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first().download()
119
+
120
+ ydl_opts = {
121
+ 'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
122
+ }
123
+
124
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
125
+ info = ydl.extract_info(video_url, download=False)
126
+ abs_video_path = ydl.prepare_filename(info)
127
+ ydl.process_info(info)
128
+
129
+ print("Success download video")
130
+ print(abs_video_path)
131
+ return abs_video_path
132
+
133
+
134
+ def speech_to_text(video_file_path, selected_source_lang, whisper_model, num_speakers):
135
+ """
136
+ # Transcribe youtube link using OpenAI Whisper
137
+ 1. Using Open AI's Whisper model to seperate audio into segments and generate transcripts.
138
+ 2. Generating speaker embeddings for each segments.
139
+ 3. Applying agglomerative clustering on the embeddings to identify the speaker for each segment.
140
+
141
+ Speech Recognition is based on models from OpenAI Whisper https://github.com/openai/whisper
142
+ Speaker diarization model and pipeline from by https://github.com/pyannote/pyannote-audio
143
+ """
144
+
145
+ # model = whisper.load_model(whisper_model)
146
+ # model = WhisperModel(whisper_model, device="cuda", compute_type="int8_float16")
147
+ model = WhisperModel(whisper_model, compute_type="int8")
148
+ time_start = time.time()
149
+ if (video_file_path == None):
150
+ raise ValueError("Error no video input")
151
+ print(video_file_path)
152
+
153
+ try:
154
+ # Read and convert youtube video
155
+ _, file_ending = os.path.splitext(f'{video_file_path}')
156
+ print(f'file enging is {file_ending}')
157
+ audio_file = video_file_path.replace(file_ending, ".wav")
158
+ print("starting conversion to wav")
159
+ os.system(f'ffmpeg -i "{video_file_path}" -ar 16000 -ac 1 -c:a pcm_s16le "{audio_file}"')
160
+
161
+ # Get duration
162
+ with contextlib.closing(wave.open(audio_file, 'r')) as f:
163
+ frames = f.getnframes()
164
+ rate = f.getframerate()
165
+ duration = frames / float(rate)
166
+ print(f"conversion to wav ready, duration of audio file: {duration}")
167
+
168
+ # Transcribe audio
169
+ options = dict(language=selected_source_lang, beam_size=5, best_of=5)
170
+ transcribe_options = dict(task="transcribe", **options)
171
+ segments_raw, info = model.transcribe(audio_file, **transcribe_options)
172
+
173
+ # Convert back to original openai format
174
+ segments = []
175
+ i = 0
176
+ for segment_chunk in segments_raw:
177
+ chunk = {}
178
+ chunk["start"] = segment_chunk.start
179
+ chunk["end"] = segment_chunk.end
180
+ chunk["text"] = segment_chunk.text
181
+ segments.append(chunk)
182
+ i += 1
183
+ print("transcribe audio done with fast whisper")
184
+ except Exception as e:
185
+ raise RuntimeError("Error converting video to audio")
186
+
187
+ try:
188
+ # Create embedding
189
+ def segment_embedding(segment):
190
+ audio = Audio()
191
+ start = segment["start"]
192
+ # Whisper overshoots the end timestamp in the last segment
193
+ end = min(duration, segment["end"])
194
+ clip = Segment(start, end)
195
+ waveform, sample_rate = audio.crop(audio_file, clip)
196
+ return embedding_model(waveform[None])
197
+
198
+ embeddings = np.zeros(shape=(len(segments), 192))
199
+ for i, segment in enumerate(segments):
200
+ embeddings[i] = segment_embedding(segment)
201
+ embeddings = np.nan_to_num(embeddings)
202
+ print(f'Embedding shape: {embeddings.shape}')
203
+
204
+ if num_speakers == 0:
205
+ # Find the best number of speakers
206
+ score_num_speakers = {}
207
+
208
+ for num_speakers in range(2, 10 + 1):
209
+ clustering = AgglomerativeClustering(num_speakers).fit(embeddings)
210
+ score = silhouette_score(embeddings, clustering.labels_, metric='euclidean')
211
+ score_num_speakers[num_speakers] = score
212
+ best_num_speaker = max(score_num_speakers, key=lambda x: score_num_speakers[x])
213
+ print(f"The best number of speakers: {best_num_speaker} with {score_num_speakers[best_num_speaker]} score")
214
+ else:
215
+ best_num_speaker = num_speakers
216
+
217
+ # Assign speaker label
218
+ clustering = AgglomerativeClustering(best_num_speaker).fit(embeddings)
219
+ labels = clustering.labels_
220
+ for i in range(len(segments)):
221
+ segments[i]["speaker"] = 'SPEAKER ' + str(labels[i] + 1)
222
+
223
+ # Make output
224
+ objects = {
225
+ 'Start': [],
226
+ 'End': [],
227
+ 'Speaker': [],
228
+ 'Text': []
229
+ }
230
+ text = ''
231
+ for (i, segment) in enumerate(segments):
232
+ if i == 0 or segments[i - 1]["speaker"] != segment["speaker"]:
233
+ objects['Start'].append(str(convert_time(segment["start"])))
234
+ objects['Speaker'].append(segment["speaker"])
235
+ if i != 0:
236
+ objects['End'].append(str(convert_time(segments[i - 1]["end"])))
237
+ objects['Text'].append(text)
238
+ text = ''
239
+ text += segment["text"] + ' '
240
+ objects['End'].append(str(convert_time(segments[i - 1]["end"])))
241
+ objects['Text'].append(text)
242
+
243
+ time_end = time.time()
244
+ time_diff = time_end - time_start
245
+ memory = psutil.virtual_memory()
246
+ gpu_utilization, gpu_memory = GPUInfo.gpu_usage()
247
+ gpu_utilization = gpu_utilization[0] if len(gpu_utilization) > 0 else 0
248
+ gpu_memory = gpu_memory[0] if len(gpu_memory) > 0 else 0
249
+ system_info = f"""
250
+ *Memory: {memory.total / (1024 * 1024 * 1024):.2f}GB, used: {memory.percent}%, available: {memory.available / (1024 * 1024 * 1024):.2f}GB.*
251
+ *Processing time: {time_diff:.5} seconds.*
252
+ *GPU Utilization: {gpu_utilization}%, GPU Memory: {gpu_memory}MiB.*
253
+ """
254
+ save_path = "output/transcript_result.csv"
255
+ df_results = pd.DataFrame(objects)
256
+ df_results.to_csv(save_path)
257
+ return df_results, system_info, save_path
258
+
259
+ except Exception as e:
260
+ raise RuntimeError("Error Running inference with local model", e)
261
+
262
+
263
+ # def create_meeting_summary(openai_key, prompt):
264
+ # openai.api_key = openai_key
265
+ #
266
+ # # 文字起こししたテキストを取得
267
+ # system_template = prompt
268
+ #
269
+ # completion = openai.ChatCompletion.create(
270
+ # model="gpt-3.5-turbo",
271
+ # messages=[
272
+ # {"role": "system", "content": system_template},
273
+ # {"role": "user", "content": transcript_text}
274
+ # ]
275
+ # )
276
+ # summary = completion.choices[0].message.content
277
+ # return summary
278
+
279
+
280
+ # ---- Gradio Layout -----
281
+ # Inspiration from https://huggingface.co/spaces/RASMUS/Whisper-youtube-crosslingual-subtitles
282
+ video_in = gr.Video(label="Video file", mirror_webcam=False)
283
+ youtube_url_in = gr.Textbox(label="Youtube url", lines=1, interactive=True)
284
+ df_init = pd.DataFrame(columns=['Start', 'End', 'Speaker', 'Text'])
285
+ memory = psutil.virtual_memory()
286
+ selected_source_lang = gr.Dropdown(choices=source_language_list, type="value", value="ja",
287
+ label="Spoken language in video", interactive=True)
288
+ selected_whisper_model = gr.Dropdown(choices=whisper_models, type="value", value="base", label="Selected Whisper model",
289
+ interactive=True)
290
+ number_speakers = gr.Number(precision=0, value=0,
291
+ label="Input number of speakers for better results. If value=0, model will automatic find the best number of speakers",
292
+ interactive=True)
293
+ system_info = gr.Markdown(
294
+ f"*Memory: {memory.total / (1024 * 1024 * 1024):.2f}GB, used: {memory.percent}%, available: {memory.available / (1024 * 1024 * 1024):.2f}GB*")
295
+ download_transcript = gr.File(label="Download transcript")
296
+ transcription_df = gr.DataFrame(value=df_init, label="Transcription dataframe", row_count=(0, "dynamic"), max_rows=10,
297
+ wrap=True, overflow_row_behaviour='paginate')
298
+ title = "Whisper speaker diarization"
299
+ demo = gr.Blocks(title=title)
300
+ demo.encrypt = False
301
+
302
+ with demo:
303
+ with gr.Tab("Whisper speaker diarization"):
304
+ gr.Markdown('''
305
+ <div>
306
+ <h1 style='text-align: center'>Whisper speaker diarization</h1>
307
+ This space uses Whisper models from <a href='https://github.com/openai/whisper' target='_blank'><b>OpenAI</b></a> with <a href='https://github.com/guillaumekln/faster-whisper' target='_blank'><b>CTranslate2</b></a> which is a fast inference engine for Transformer models to recognize the speech (4 times faster than original openai model with same accuracy)
308
+ and ECAPA-TDNN model from <a href='https://github.com/speechbrain/speechbrain' target='_blank'><b>SpeechBrain</b></a> to encode and clasify speakers
309
+ </div>
310
+ ''')
311
+
312
+ with gr.Row():
313
+ gr.Markdown('''
314
+ ### Transcribe youtube link using OpenAI Whisper
315
+ ##### 1. Using Open AI's Whisper model to seperate audio into segments and generate transcripts.
316
+ ##### 2. Generating speaker embeddings for each segments.
317
+ ##### 3. Applying agglomerative clustering on the embeddings to identify the speaker for each segment.
318
+ ''')
319
+
320
+ with gr.Row():
321
+ gr.Markdown('''
322
+ ### You can test by following examples:
323
+ ''')
324
+ examples = gr.Examples(examples=
325
+ ["https://www.youtube.com/watch?v=j7BfEzAFuYc&t=32s",
326
+ "https://www.youtube.com/watch?v=-UX0X45sYe4",
327
+ "https://www.youtube.com/watch?v=7minSgqi-Gw"],
328
+ label="Examples", inputs=[youtube_url_in])
329
+
330
+ with gr.Row():
331
+ with gr.Column():
332
+ youtube_url_in.render()
333
+ download_youtube_btn = gr.Button("Download Youtube video")
334
+ download_youtube_btn.click(get_youtube, [youtube_url_in], [
335
+ video_in])
336
+ print(video_in)
337
+
338
+ with gr.Row():
339
+ with gr.Column():
340
+ video_in.render()
341
+ with gr.Column():
342
+ gr.Markdown('''
343
+ ##### Here you can start the transcription process.
344
+ ##### Please select the source language for transcription.
345
+ ##### You can select a range of assumed numbers of speakers.
346
+ ''')
347
+ selected_source_lang.render()
348
+ selected_whisper_model.render()
349
+ number_speakers.render()
350
+ transcribe_btn = gr.Button("Transcribe audio and diarization")
351
+ transcribe_btn.click(speech_to_text,
352
+ [video_in, selected_source_lang, selected_whisper_model, number_speakers],
353
+ [transcription_df, system_info, download_transcript]
354
+ )
355
+
356
+ with gr.Row():
357
+ gr.Markdown('''
358
+ ##### Here you will get transcription output
359
+ ##### ''')
360
+
361
+ with gr.Row():
362
+ with gr.Column():
363
+ download_transcript.render()
364
+ transcription_df.render()
365
+ # system_info.render()
366
+ # gr.Markdown(
367
+ # '''<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>''')
368
+
369
+ # with gr.Row():
370
+ # with gr.Column():
371
+ # gr.Textbox(lines=1, label="openai_key", type="password")
372
+ # gr.TextArea(label="prompt", value="""会議の文字起こしが渡されます。
373
+ #
374
+ # この会議のサマリーをMarkdown形式で作成してください。サマリーは、以下のような形式で書いてください。
375
+ # - 会議の目的
376
+ # - 会議の内容
377
+ # - 会議の結果""")
378
+ # gr.Textbox(label="transcription_summary")
379
+
380
 
381
+ demo.launch(debug=True)
requirements.txt CHANGED
@@ -1,5 +1,3 @@
1
- openai==0.27.2
2
- pydub==0.25.1
3
  git+https://github.com/huggingface/transformers
4
  git+https://github.com/pyannote/pyannote-audio
5
  git+https://github.com/openai/whisper.git
@@ -21,4 +19,5 @@ psutil==5.9.2
21
  requests
22
  gpuinfo
23
  faster-whisper
24
- yt-dlp
 
 
 
 
1
  git+https://github.com/huggingface/transformers
2
  git+https://github.com/pyannote/pyannote-audio
3
  git+https://github.com/openai/whisper.git
 
19
  requests
20
  gpuinfo
21
  faster-whisper
22
+ yt-dlp
23
+ openai==0.27.2