Spaces:
Build error
Build error
yama
commited on
Commit
•
9e020be
1
Parent(s):
631631a
Update app.py
Browse files
app.py
CHANGED
@@ -1,443 +1,288 @@
|
|
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 |
-
|
13 |
-
from
|
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 |
-
|
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 |
-
# "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 |
|
153 |
-
def transcribe(microphone, file_upload):
|
154 |
-
warn_output = ""
|
155 |
-
if (microphone is not None) and (file_upload is not None):
|
156 |
-
warn_output = (
|
157 |
-
"WARNING: You've uploaded an audio file and used the microphone. "
|
158 |
-
"The recorded file from the microphone will be used and the uploaded audio will be discarded.\n"
|
159 |
-
)
|
160 |
|
161 |
-
|
162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
163 |
|
164 |
-
|
|
|
|
|
165 |
|
166 |
-
|
|
|
|
|
|
|
167 |
|
168 |
-
|
|
|
169 |
|
|
|
|
|
170 |
|
171 |
-
def _return_yt_html_embed(yt_url):
|
172 |
-
video_id = yt_url.split("?v=")[-1]
|
173 |
-
HTML_str = (
|
174 |
-
f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>'
|
175 |
-
" </center>"
|
176 |
-
)
|
177 |
-
return HTML_str
|
178 |
|
|
|
|
|
|
|
179 |
|
180 |
-
def yt_transcribe(yt_url):
|
181 |
-
# yt = YouTube(yt_url)
|
182 |
-
# html_embed_str = _return_yt_html_embed(yt_url)
|
183 |
-
# stream = yt.streams.filter(only_audio=True)[0]
|
184 |
-
# stream.download(filename="audio.mp3")
|
185 |
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
|
|
|
|
|
|
|
|
|
|
195 |
|
196 |
-
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
197 |
-
ydl.download([yt_url])
|
198 |
|
199 |
-
|
200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
201 |
|
|
|
|
|
|
|
|
|
202 |
|
203 |
-
def convert_time(secs):
|
204 |
-
return datetime.timedelta(seconds=round(secs))
|
205 |
|
|
|
|
|
206 |
|
207 |
-
def get_youtube(video_url):
|
208 |
-
# yt = YouTube(video_url)
|
209 |
-
# abs_video_path = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first().download()
|
210 |
|
211 |
-
|
212 |
-
|
213 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
214 |
|
215 |
-
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
216 |
-
info = ydl.extract_info(video_url, download=False)
|
217 |
-
abs_video_path = ydl.prepare_filename(info)
|
218 |
-
ydl.process_info(info)
|
219 |
|
220 |
-
|
221 |
-
print(abs_video_path)
|
222 |
-
return abs_video_path
|
223 |
|
224 |
|
225 |
-
def
|
226 |
"""
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
231 |
|
232 |
-
|
233 |
-
|
234 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
235 |
|
236 |
-
|
237 |
-
# model = WhisperModel(whisper_model, device="cuda", compute_type="int8_float16")
|
238 |
-
model = WhisperModel(whisper_model, compute_type="int8")
|
239 |
-
time_start = time.time()
|
240 |
-
if (video_file_path == None):
|
241 |
-
raise ValueError("Error no video input")
|
242 |
-
print(video_file_path)
|
243 |
-
|
244 |
-
try:
|
245 |
-
# Read and convert youtube video
|
246 |
-
_, file_ending = os.path.splitext(f'{video_file_path}')
|
247 |
-
print(f'file enging is {file_ending}')
|
248 |
-
audio_file = video_file_path.replace(file_ending, ".wav")
|
249 |
-
print("starting conversion to wav")
|
250 |
-
os.system(f'ffmpeg -i "{video_file_path}" -ar 16000 -ac 1 -c:a pcm_s16le "{audio_file}"')
|
251 |
-
|
252 |
-
# Get duration
|
253 |
-
with contextlib.closing(wave.open(audio_file, 'r')) as f:
|
254 |
-
frames = f.getnframes()
|
255 |
-
rate = f.getframerate()
|
256 |
-
duration = frames / float(rate)
|
257 |
-
print(f"conversion to wav ready, duration of audio file: {duration}")
|
258 |
-
|
259 |
-
# Transcribe audio
|
260 |
-
options = dict(language=selected_source_lang, beam_size=5, best_of=5)
|
261 |
-
transcribe_options = dict(task="transcribe", **options)
|
262 |
-
segments_raw, info = model.transcribe(audio_file, **transcribe_options)
|
263 |
-
|
264 |
-
# Convert back to original openai format
|
265 |
-
segments = []
|
266 |
-
i = 0
|
267 |
-
for segment_chunk in segments_raw:
|
268 |
-
chunk = {}
|
269 |
-
chunk["start"] = segment_chunk.start
|
270 |
-
chunk["end"] = segment_chunk.end
|
271 |
-
chunk["text"] = segment_chunk.text
|
272 |
-
segments.append(chunk)
|
273 |
-
i += 1
|
274 |
-
print("transcribe audio done with fast whisper")
|
275 |
-
except Exception as e:
|
276 |
-
raise RuntimeError("Error converting video to audio")
|
277 |
-
|
278 |
-
try:
|
279 |
-
# Create embedding
|
280 |
-
def segment_embedding(segment):
|
281 |
-
audio = Audio()
|
282 |
-
start = segment["start"]
|
283 |
-
# Whisper overshoots the end timestamp in the last segment
|
284 |
-
end = min(duration, segment["end"])
|
285 |
-
clip = Segment(start, end)
|
286 |
-
waveform, sample_rate = audio.crop(audio_file, clip)
|
287 |
-
return embedding_model(waveform[None])
|
288 |
-
|
289 |
-
embeddings = np.zeros(shape=(len(segments), 192))
|
290 |
-
for i, segment in enumerate(segments):
|
291 |
-
embeddings[i] = segment_embedding(segment)
|
292 |
-
embeddings = np.nan_to_num(embeddings)
|
293 |
-
print(f'Embedding shape: {embeddings.shape}')
|
294 |
-
|
295 |
-
if num_speakers == 0:
|
296 |
-
# Find the best number of speakers
|
297 |
-
score_num_speakers = {}
|
298 |
-
|
299 |
-
for num_speakers in range(2, 10 + 1):
|
300 |
-
clustering = AgglomerativeClustering(num_speakers).fit(embeddings)
|
301 |
-
score = silhouette_score(embeddings, clustering.labels_, metric='euclidean')
|
302 |
-
score_num_speakers[num_speakers] = score
|
303 |
-
best_num_speaker = max(score_num_speakers, key=lambda x: score_num_speakers[x])
|
304 |
-
print(f"The best number of speakers: {best_num_speaker} with {score_num_speakers[best_num_speaker]} score")
|
305 |
-
else:
|
306 |
-
best_num_speaker = num_speakers
|
307 |
-
|
308 |
-
# Assign speaker label
|
309 |
-
clustering = AgglomerativeClustering(best_num_speaker).fit(embeddings)
|
310 |
-
labels = clustering.labels_
|
311 |
-
for i in range(len(segments)):
|
312 |
-
segments[i]["speaker"] = 'SPEAKER ' + str(labels[i] + 1)
|
313 |
-
|
314 |
-
# Make output
|
315 |
-
objects = {
|
316 |
-
'Start': [],
|
317 |
-
'End': [],
|
318 |
-
'Speaker': [],
|
319 |
-
'Text': []
|
320 |
-
}
|
321 |
-
text = ''
|
322 |
-
for (i, segment) in enumerate(segments):
|
323 |
-
if i == 0 or segments[i - 1]["speaker"] != segment["speaker"]:
|
324 |
-
objects['Start'].append(str(convert_time(segment["start"])))
|
325 |
-
objects['Speaker'].append(segment["speaker"])
|
326 |
-
if i != 0:
|
327 |
-
objects['End'].append(str(convert_time(segments[i - 1]["end"])))
|
328 |
-
objects['Text'].append(text)
|
329 |
-
text = ''
|
330 |
-
text += segment["text"] + ' '
|
331 |
-
objects['End'].append(str(convert_time(segments[i - 1]["end"])))
|
332 |
-
objects['Text'].append(text)
|
333 |
-
|
334 |
-
time_end = time.time()
|
335 |
-
time_diff = time_end - time_start
|
336 |
-
memory = psutil.virtual_memory()
|
337 |
-
gpu_utilization, gpu_memory = GPUInfo.gpu_usage()
|
338 |
-
gpu_utilization = gpu_utilization[0] if len(gpu_utilization) > 0 else 0
|
339 |
-
gpu_memory = gpu_memory[0] if len(gpu_memory) > 0 else 0
|
340 |
-
system_info = f"""
|
341 |
-
*Memory: {memory.total / (1024 * 1024 * 1024):.2f}GB, used: {memory.percent}%, available: {memory.available / (1024 * 1024 * 1024):.2f}GB.*
|
342 |
-
*Processing time: {time_diff:.5} seconds.*
|
343 |
-
*GPU Utilization: {gpu_utilization}%, GPU Memory: {gpu_memory}MiB.*
|
344 |
-
"""
|
345 |
-
save_path = "output/transcript_result.csv"
|
346 |
-
df_results = pd.DataFrame(objects)
|
347 |
-
df_results.to_csv(save_path)
|
348 |
-
return df_results, system_info, save_path
|
349 |
-
|
350 |
-
except Exception as e:
|
351 |
-
raise RuntimeError("Error Running inference with local model", e)
|
352 |
-
|
353 |
-
|
354 |
-
# ---- Gradio Layout -----
|
355 |
-
# Inspiration from https://huggingface.co/spaces/RASMUS/Whisper-youtube-crosslingual-subtitles
|
356 |
-
video_in = gr.Video(label="Video file", mirror_webcam=False)
|
357 |
-
youtube_url_in = gr.Textbox(label="Youtube url", lines=1, interactive=True)
|
358 |
-
df_init = pd.DataFrame(columns=['Start', 'End', 'Speaker', 'Text'])
|
359 |
-
memory = psutil.virtual_memory()
|
360 |
-
selected_source_lang = gr.Dropdown(choices=source_language_list, type="value", value="ja",
|
361 |
-
label="Spoken language in video", interactive=True)
|
362 |
-
selected_whisper_model = gr.Dropdown(choices=whisper_models, type="value", value="base", label="Selected Whisper model",
|
363 |
-
interactive=True)
|
364 |
-
number_speakers = gr.Number(precision=0, value=0,
|
365 |
-
label="Input number of speakers for better results. If value=0, model will automatic find the best number of speakers",
|
366 |
-
interactive=True)
|
367 |
-
system_info = gr.Markdown(
|
368 |
-
f"*Memory: {memory.total / (1024 * 1024 * 1024):.2f}GB, used: {memory.percent}%, available: {memory.available / (1024 * 1024 * 1024):.2f}GB*")
|
369 |
-
download_transcript = gr.File(label="Download transcript")
|
370 |
-
transcription_df = gr.DataFrame(value=df_init, label="Transcription dataframe", row_count=(0, "dynamic"), max_rows=10,
|
371 |
-
wrap=True, overflow_row_behaviour='paginate')
|
372 |
-
title = "Whisper speaker diarization"
|
373 |
-
demo = gr.Blocks(title=title)
|
374 |
-
demo.encrypt = False
|
375 |
-
|
376 |
-
with demo:
|
377 |
-
with gr.Tab("Whisper speaker diarization"):
|
378 |
-
gr.Markdown('''
|
379 |
-
<div>
|
380 |
-
<h1 style='text-align: center'>Whisper speaker diarization</h1>
|
381 |
-
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)
|
382 |
-
and ECAPA-TDNN model from <a href='https://github.com/speechbrain/speechbrain' target='_blank'><b>SpeechBrain</b></a> to encode and clasify speakers
|
383 |
-
</div>
|
384 |
-
''')
|
385 |
-
|
386 |
-
with gr.Row():
|
387 |
-
gr.Markdown('''
|
388 |
-
### Transcribe youtube link using OpenAI Whisper
|
389 |
-
##### 1. Using Open AI's Whisper model to seperate audio into segments and generate transcripts.
|
390 |
-
##### 2. Generating speaker embeddings for each segments.
|
391 |
-
##### 3. Applying agglomerative clustering on the embeddings to identify the speaker for each segment.
|
392 |
-
''')
|
393 |
-
|
394 |
-
with gr.Row():
|
395 |
-
gr.Markdown('''
|
396 |
-
### You can test by following examples:
|
397 |
-
''')
|
398 |
-
examples = gr.Examples(examples=
|
399 |
-
["https://www.youtube.com/watch?v=j7BfEzAFuYc&t=32s",
|
400 |
-
"https://www.youtube.com/watch?v=-UX0X45sYe4",
|
401 |
-
"https://www.youtube.com/watch?v=7minSgqi-Gw"],
|
402 |
-
label="Examples", inputs=[youtube_url_in])
|
403 |
-
|
404 |
-
with gr.Row():
|
405 |
-
with gr.Column():
|
406 |
-
youtube_url_in.render()
|
407 |
-
download_youtube_btn = gr.Button("Download Youtube video")
|
408 |
-
download_youtube_btn.click(get_youtube, [youtube_url_in], [
|
409 |
-
video_in])
|
410 |
-
print(video_in)
|
411 |
-
|
412 |
-
with gr.Row():
|
413 |
-
with gr.Column():
|
414 |
-
video_in.render()
|
415 |
-
with gr.Column():
|
416 |
-
gr.Markdown('''
|
417 |
-
##### Here you can start the transcription process.
|
418 |
-
##### Please select the source language for transcription.
|
419 |
-
##### You can select a range of assumed numbers of speakers.
|
420 |
-
''')
|
421 |
-
selected_source_lang.render()
|
422 |
-
selected_whisper_model.render()
|
423 |
-
number_speakers.render()
|
424 |
-
transcribe_btn = gr.Button("Transcribe audio and diarization")
|
425 |
-
transcribe_btn.click(speech_to_text,
|
426 |
-
[video_in, selected_source_lang, selected_whisper_model, number_speakers],
|
427 |
-
[transcription_df, system_info, download_transcript]
|
428 |
-
)
|
429 |
-
|
430 |
-
with gr.Row():
|
431 |
-
gr.Markdown('''
|
432 |
-
##### Here you will get transcription output
|
433 |
-
##### ''')
|
434 |
-
|
435 |
-
with gr.Row():
|
436 |
-
with gr.Column():
|
437 |
-
download_transcript.render()
|
438 |
-
transcription_df.render()
|
439 |
-
system_info.render()
|
440 |
-
gr.Markdown(
|
441 |
-
'''<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>''')
|
442 |
-
|
443 |
-
demo.launch(debug=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
+
import wave
|
3 |
import numpy as np
|
4 |
+
import contextlib
|
5 |
+
from pydub import AudioSegment
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
from pyannote.core import Segment
|
7 |
+
from pyannote.audio import Audio
|
8 |
+
from pyannote.audio.pipelines.speaker_verification import PretrainedSpeakerEmbedding
|
9 |
+
import torch
|
10 |
+
from typing import Dict, List, Tuple
|
11 |
|
|
|
12 |
|
13 |
+
def convert_to_wav(input_file: str, output_file: str = "output_file.wav") -> str:
|
14 |
+
"""
|
15 |
+
音声ファイルをWAV形式に変換します。
|
16 |
+
|
17 |
+
Parameters
|
18 |
+
----------
|
19 |
+
input_file: str
|
20 |
+
変換する音声ファイルのパス
|
21 |
+
output_file: str
|
22 |
+
変換後のWAVファイルの出力先パス(デフォルトは"output_file.wav")
|
23 |
+
Returns
|
24 |
+
-------
|
25 |
+
str
|
26 |
+
変換後のWAVファイルのパス
|
27 |
+
"""
|
28 |
+
file_format = os.path.splitext(input_file)[1][1:]
|
29 |
+
audio = AudioSegment.from_file(input_file, format=file_format)
|
30 |
+
audio.export(output_file, format="wav")
|
31 |
+
return output_file
|
32 |
+
|
33 |
+
|
34 |
+
def segment_embedding(
|
35 |
+
file_name: str,
|
36 |
+
duration: float,
|
37 |
+
segment,
|
38 |
+
embedding_model: PretrainedSpeakerEmbedding
|
39 |
+
) -> np.ndarray:
|
40 |
+
"""
|
41 |
+
音声ファイルから指定されたセグメントの埋め込みを計算します。
|
42 |
+
|
43 |
+
Parameters
|
44 |
+
----------
|
45 |
+
file_name: str
|
46 |
+
音声ファイルのパス
|
47 |
+
duration: float
|
48 |
+
音声ファイルの継続時間
|
49 |
+
segment: whisperのtranscribeのsegment
|
50 |
+
embedding_model: PretrainedSpeakerEmbedding
|
51 |
+
埋め込みモデル
|
52 |
+
Returns
|
53 |
+
-------
|
54 |
+
np.ndarray
|
55 |
+
計算された埋め込みベクトル
|
56 |
+
"""
|
57 |
+
audio = Audio()
|
58 |
+
start = segment["start"]
|
59 |
+
end = min(duration, segment["end"])
|
60 |
+
clip = Segment(start, end)
|
61 |
+
waveform, sample_rate = audio.crop(file_name, clip)
|
62 |
+
return embedding_model(waveform[None])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
|
|
|
|
|
|
|
64 |
|
65 |
+
def reference_audio_embedding(
|
66 |
+
file_name: str
|
67 |
+
) -> np.ndarray:
|
68 |
+
"""
|
69 |
+
参考音声の埋め込みを出力します。
|
70 |
+
|
71 |
+
Parameters
|
72 |
+
----------
|
73 |
+
file_name: str
|
74 |
+
音声ファイルのパス
|
75 |
+
Returns
|
76 |
+
-------
|
77 |
+
np.ndarray
|
78 |
+
計算された埋め込みベクトル
|
79 |
+
"""
|
80 |
+
audio = Audio()
|
81 |
+
waveform, sample_rate = audio(file_name)
|
82 |
+
embedding_model = embedding_model = PretrainedSpeakerEmbedding("speechbrain/spkrec-ecapa-voxceleb", device='cpu')
|
83 |
+
return embedding_model(waveform[None])[0]
|
84 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
|
86 |
+
def generate_speaker_embeddings(
|
87 |
+
meeting_file_path: str,
|
88 |
+
transcript
|
89 |
+
) -> np.ndarray:
|
90 |
+
"""
|
91 |
+
音声ファイルから話者の埋め込みを計算します。
|
92 |
+
|
93 |
+
Parameters
|
94 |
+
----------
|
95 |
+
meeting_file_path: str
|
96 |
+
音声ファイルのパス
|
97 |
+
transcript: Whisper API の transcribe メソッドの出力結果
|
98 |
+
Returns
|
99 |
+
-------
|
100 |
+
np.ndarray
|
101 |
+
計算された話者の埋め込み群
|
102 |
+
"""
|
103 |
+
output_file = convert_to_wav(meeting_file_path)
|
104 |
|
105 |
+
segments = transcript['segments']
|
106 |
+
embedding_model = PretrainedSpeakerEmbedding("speechbrain/spkrec-ecapa-voxceleb", device='cpu')
|
107 |
+
embeddings = np.zeros(shape=(len(segments), 192))
|
108 |
|
109 |
+
with contextlib.closing(wave.open(output_file, 'r')) as f:
|
110 |
+
frames = f.getnframes()
|
111 |
+
rate = f.getframerate()
|
112 |
+
duration = frames / float(rate)
|
113 |
|
114 |
+
for i, segment in enumerate(segments):
|
115 |
+
embeddings[i] = segment_embedding(output_file, duration, segment, embedding_model)
|
116 |
|
117 |
+
embeddings = np.nan_to_num(embeddings)
|
118 |
+
return embeddings
|
119 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
120 |
|
121 |
+
import numpy as np
|
122 |
+
from sklearn.cluster import AgglomerativeClustering
|
123 |
+
from typing import List, Tuple
|
124 |
|
|
|
|
|
|
|
|
|
|
|
125 |
|
126 |
+
def clustering_embeddings(speaker_count: int, embeddings: np.ndarray) -> AgglomerativeClustering:
|
127 |
+
"""
|
128 |
+
埋め込みデータをクラスタリングして、クラスタリングオブジェクトを返します。
|
129 |
+
Parameters
|
130 |
+
----------
|
131 |
+
embeddings: np.ndarray
|
132 |
+
分散表現(埋め込み)のリスト。
|
133 |
+
Returns
|
134 |
+
-------
|
135 |
+
AgglomerativeClustering
|
136 |
+
クラスタリングオブジェクト。
|
137 |
+
"""
|
138 |
+
clustering = AgglomerativeClustering(speaker_count).fit(embeddings)
|
139 |
+
return clustering
|
140 |
|
|
|
|
|
141 |
|
142 |
+
def format_speaker_output_by_segment(clustering: AgglomerativeClustering, transcript: dict) -> str:
|
143 |
+
"""
|
144 |
+
クラスタリングの結果をもとに、各発話者ごとにセグメントを整形して出力します
|
145 |
+
Parameters
|
146 |
+
----------
|
147 |
+
clustering: AgglomerativeClustering
|
148 |
+
クラスタリングオブジェクト。
|
149 |
+
transcript: dict
|
150 |
+
Whisper API の transcribe メソッドの出力結果
|
151 |
+
Returns
|
152 |
+
-------
|
153 |
+
str
|
154 |
+
発話者ごとに整形されたセグメントの文字列
|
155 |
+
"""
|
156 |
+
labeled_segments = []
|
157 |
+
for label, segment in zip(clustering.labels_, transcript["segments"]):
|
158 |
+
labeled_segments.append((label, segment["start"], segment["text"]))
|
159 |
|
160 |
+
output = ""
|
161 |
+
for speaker, _, text in labeled_segments:
|
162 |
+
output += f"話者{speaker + 1}: 「{text}」\n"
|
163 |
+
return output
|
164 |
|
|
|
|
|
165 |
|
166 |
+
from sklearn.cluster import KMeans
|
167 |
+
from sklearn.metrics.pairwise import pairwise_distances
|
168 |
|
|
|
|
|
|
|
169 |
|
170 |
+
def clustering_embeddings2(speaker_count: int, embeddings: np.ndarray) -> KMeans:
|
171 |
+
"""
|
172 |
+
埋め込みデータをクラスタリングして、クラスタリングオブジェクトを返します。
|
173 |
+
Parameters
|
174 |
+
----------
|
175 |
+
embeddings: np.ndarray
|
176 |
+
分散表現(埋め込み)のリスト。
|
177 |
+
Returns
|
178 |
+
-------
|
179 |
+
KMeans
|
180 |
+
クラスタリングオブジェクト。
|
181 |
+
"""
|
182 |
+
# コサイン類似度行列を計算
|
183 |
+
cosine_distances = pairwise_distances(embeddings, metric='cosine')
|
184 |
+
clustering = KMeans(n_clusters=speaker_count).fit(cosine_distances)
|
185 |
+
return clustering
|
186 |
|
|
|
|
|
|
|
|
|
187 |
|
188 |
+
from scipy.spatial.distance import cosine
|
|
|
|
|
189 |
|
190 |
|
191 |
+
def closest_reference_speaker(embedding: np.ndarray, references: List[Tuple[str, np.ndarray]]) -> str:
|
192 |
"""
|
193 |
+
与えられた埋め込みに最も近い参照話者を返します。
|
194 |
+
Parameters
|
195 |
+
----------
|
196 |
+
embedding: np.ndarray
|
197 |
+
話者の埋め込み
|
198 |
+
references: List[Tuple[str, np.ndarray]]
|
199 |
+
参照話者の名前と埋め込みのリスト
|
200 |
+
Returns
|
201 |
+
-------
|
202 |
+
str
|
203 |
+
最も近い参照話者の名前
|
204 |
+
"""
|
205 |
+
min_distance = float('inf')
|
206 |
+
closest_speaker = None
|
207 |
+
for name, reference_embedding in references:
|
208 |
+
distance = cosine(embedding, reference_embedding)
|
209 |
+
if distance < min_distance:
|
210 |
+
min_distance = distance
|
211 |
+
closest_speaker = name
|
212 |
+
|
213 |
+
return closest_speaker
|
214 |
+
|
215 |
|
216 |
+
def format_speaker_output_by_segment2(embeddings: np.ndarray, transcript: dict,
|
217 |
+
reference_embeddings: List[Tuple[str, np.ndarray]]) -> str:
|
218 |
"""
|
219 |
+
各発話者の埋め込みに基づいて、セグメントを整形して出力します。
|
220 |
+
Parameters
|
221 |
+
----------
|
222 |
+
embeddings: np.ndarray
|
223 |
+
話者の埋め込みのリスト
|
224 |
+
transcript: dict
|
225 |
+
Whisper API の transcribe メソッドの出力結果
|
226 |
+
reference_embeddings: List[Tuple[str, np.ndarray]]
|
227 |
+
参照話者の名前と埋め込みのリスト
|
228 |
+
Returns
|
229 |
+
-------
|
230 |
+
str
|
231 |
+
発話者ごとに整形されたセグメントの文字列。
|
232 |
+
"""
|
233 |
+
labeled_segments = []
|
234 |
+
for embedding, segment in zip(embeddings, transcript["segments"]):
|
235 |
+
speaker_name = closest_reference_speaker(embedding, reference_embeddings)
|
236 |
+
labeled_segments.append((speaker_name, segment["start"], segment["text"]))
|
237 |
+
|
238 |
+
output = ""
|
239 |
+
for speaker, _, text in labeled_segments:
|
240 |
+
output += f"{speaker}: 「{text}」\n"
|
241 |
+
return output
|
242 |
+
|
243 |
+
|
244 |
+
import gradio as gr
|
245 |
+
import openai
|
246 |
+
|
247 |
+
|
248 |
+
def create_transcription_with_speaker(openai_key, main_audio, reference_audio_1, reference1_name,
|
249 |
+
reference_audio_2, reference2_name, speaker_count=2):
|
250 |
+
openai.api_key = openai_key
|
251 |
+
# 文字起こし
|
252 |
+
transcript = openai.Audio.transcribe("whisper-1", open(main_audio, "rb"), response_format="verbose_json")
|
253 |
+
# 各発話をembeddingsに変換
|
254 |
+
embeddings = generate_speaker_embeddings(main_audio, transcript)
|
255 |
+
# 各発話のembeddingsをクラスタリング
|
256 |
+
clustering = clustering_embeddings(speaker_count, embeddings)
|
257 |
+
# クラスタリングで作られた仮のラベルで各セグメントに名前付け
|
258 |
+
output_by_segment1 = format_speaker_output_by_segment(clustering, transcript)
|
259 |
+
reference1 = reference_audio_embedding(reference_audio_1)
|
260 |
+
reference2 = reference_audio_embedding(reference_audio_2)
|
261 |
+
reference_embeddings = [(reference1_name, reference1), (reference2_name, reference2)]
|
262 |
+
output_by_segment2 = format_speaker_output_by_segment2(embeddings, transcript, reference_embeddings)
|
263 |
+
return output_by_segment1, output_by_segment2
|
264 |
+
|
265 |
+
|
266 |
+
inputs = [
|
267 |
+
gr.Textbox(lines=1, label="openai_key", type="password"),
|
268 |
+
gr.Audio(type="filepath", label="メイン音声ファイル"),
|
269 |
+
gr.Audio(type="filepath", label="話者 (1) 参考音声ファイル"),
|
270 |
+
gr.Textbox(lines=1, label="話者 (1) の名前"),
|
271 |
+
gr.Audio(type="filepath", label="話者 (2) 参考音声ファイル"),
|
272 |
+
gr.Textbox(lines=1, label="話者 (2) の名前")
|
273 |
+
]
|
274 |
+
|
275 |
+
outputs = [
|
276 |
+
gr.Textbox(label="話者クラスタリング文字起こし"),
|
277 |
+
gr.Textbox(label="話者アサイン文字起こし"),
|
278 |
+
]
|
279 |
+
|
280 |
+
app = gr.Interface(
|
281 |
+
fn=create_transcription_with_speaker,
|
282 |
+
inputs=inputs,
|
283 |
+
outputs=outputs,
|
284 |
+
title="話者アサイン機能付き書き起こしアプリ",
|
285 |
+
description="音声ファイルをアップロードすると、話者分離した文字起こしが作成されます。"
|
286 |
+
)
|
287 |
|
288 |
+
app.launch(debug=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|