Spaces:
Build error
Build error
yama
commited on
Commit
•
f88322e
1
Parent(s):
9e020be
Update app.py
Browse files
app.py
CHANGED
@@ -1,288 +1,295 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
-
import wave
|
3 |
import numpy as np
|
4 |
-
import
|
5 |
-
from
|
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 |
-
|
106 |
-
|
107 |
-
|
|
|
|
|
|
|
|
|
108 |
|
109 |
-
|
110 |
-
frames = f.getnframes()
|
111 |
-
rate = f.getframerate()
|
112 |
-
duration = frames / float(rate)
|
113 |
|
114 |
-
|
115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
116 |
|
117 |
-
|
118 |
-
|
|
|
119 |
|
120 |
|
121 |
-
|
122 |
-
|
123 |
-
|
|
|
|
|
|
|
|
|
124 |
|
|
|
|
|
125 |
|
126 |
-
|
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 |
-
|
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 |
-
|
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 |
-
|
|
|
|
|
189 |
|
190 |
|
191 |
-
def
|
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 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
if distance < min_distance:
|
210 |
-
min_distance = distance
|
211 |
-
closest_speaker = name
|
212 |
|
213 |
-
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
"ja": "Japanese",
|
34 |
+
}
|
35 |
+
|
36 |
+
source_language_list = [key[0] for key in source_languages.items()]
|
37 |
+
|
38 |
+
MODEL_NAME = "vumichien/whisper-medium-jp"
|
39 |
+
lang = "ja"
|
40 |
+
|
41 |
+
device = 0 if torch.cuda.is_available() else "cpu"
|
42 |
+
pipe = pipeline(
|
43 |
+
task="automatic-speech-recognition",
|
44 |
+
model=MODEL_NAME,
|
45 |
+
chunk_length_s=30,
|
46 |
+
device=device,
|
47 |
+
)
|
48 |
+
os.makedirs('output', exist_ok=True)
|
49 |
+
pipe.model.config.forced_decoder_ids = pipe.tokenizer.get_decoder_prompt_ids(language=lang, task="transcribe")
|
50 |
|
51 |
+
embedding_model = PretrainedSpeakerEmbedding(
|
52 |
+
"speechbrain/spkrec-ecapa-voxceleb",
|
53 |
+
device=torch.device("cuda" if torch.cuda.is_available() else "cpu"))
|
54 |
|
55 |
|
56 |
+
def transcribe(microphone, file_upload):
|
57 |
+
warn_output = ""
|
58 |
+
if (microphone is not None) and (file_upload is not None):
|
59 |
+
warn_output = (
|
60 |
+
"WARNING: You've uploaded an audio file and used the microphone. "
|
61 |
+
"The recorded file from the microphone will be used and the uploaded audio will be discarded.\n"
|
62 |
+
)
|
63 |
|
64 |
+
elif (microphone is None) and (file_upload is None):
|
65 |
+
return "ERROR: You have to either use the microphone or upload an audio file"
|
66 |
|
67 |
+
file = microphone if microphone is not None else file_upload
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
|
69 |
+
text = pipe(file)["text"]
|
70 |
|
71 |
+
return warn_output + text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
72 |
|
|
|
|
|
|
|
|
|
73 |
|
74 |
+
def convert_time(secs):
|
75 |
+
return datetime.timedelta(seconds=round(secs))
|
76 |
|
|
|
|
|
77 |
|
78 |
+
def get_youtube(video_url):
|
79 |
+
# yt = YouTube(video_url)
|
80 |
+
# abs_video_path = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first().download()
|
81 |
|
82 |
+
ydl_opts = {
|
83 |
+
'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
|
84 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
|
86 |
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
87 |
+
info = ydl.extract_info(video_url, download=False)
|
88 |
+
abs_video_path = ydl.prepare_filename(info)
|
89 |
+
ydl.process_info(info)
|
90 |
|
91 |
+
print("Success download video")
|
92 |
+
print(abs_video_path)
|
93 |
+
return abs_video_path
|
94 |
|
95 |
|
96 |
+
def speech_to_text(video_file_path, selected_source_lang, whisper_model, num_speakers):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
97 |
"""
|
98 |
+
# Transcribe youtube link using OpenAI Whisper
|
99 |
+
1. Using Open AI's Whisper model to seperate audio into segments and generate transcripts.
|
100 |
+
2. Generating speaker embeddings for each segments.
|
101 |
+
3. Applying agglomerative clustering on the embeddings to identify the speaker for each segment.
|
|
|
|
|
|
|
102 |
|
103 |
+
Speech Recognition is based on models from OpenAI Whisper https://github.com/openai/whisper
|
104 |
+
Speaker diarization model and pipeline from by https://github.com/pyannote/pyannote-audio
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
105 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
106 |
|
107 |
+
# model = whisper.load_model(whisper_model)
|
108 |
+
# model = WhisperModel(whisper_model, device="cuda", compute_type="int8_float16")
|
109 |
+
model = WhisperModel(whisper_model, compute_type="int8")
|
110 |
+
time_start = time.time()
|
111 |
+
if (video_file_path == None):
|
112 |
+
raise ValueError("Error no video input")
|
113 |
+
print(video_file_path)
|
114 |
+
|
115 |
+
try:
|
116 |
+
# Read and convert youtube video
|
117 |
+
_, file_ending = os.path.splitext(f'{video_file_path}')
|
118 |
+
print(f'file enging is {file_ending}')
|
119 |
+
audio_file = video_file_path.replace(file_ending, ".wav")
|
120 |
+
print("starting conversion to wav")
|
121 |
+
os.system(f'ffmpeg -i "{video_file_path}" -ar 16000 -ac 1 -c:a pcm_s16le "{audio_file}"')
|
122 |
+
|
123 |
+
# Get duration
|
124 |
+
with contextlib.closing(wave.open(audio_file, 'r')) as f:
|
125 |
+
frames = f.getnframes()
|
126 |
+
rate = f.getframerate()
|
127 |
+
duration = frames / float(rate)
|
128 |
+
print(f"conversion to wav ready, duration of audio file: {duration}")
|
129 |
+
|
130 |
+
# Transcribe audio
|
131 |
+
options = dict(language=selected_source_lang, beam_size=5, best_of=5)
|
132 |
+
transcribe_options = dict(task="transcribe", **options)
|
133 |
+
segments_raw, info = model.transcribe(audio_file, **transcribe_options)
|
134 |
+
|
135 |
+
# Convert back to original openai format
|
136 |
+
segments = []
|
137 |
+
i = 0
|
138 |
+
for segment_chunk in segments_raw:
|
139 |
+
chunk = {}
|
140 |
+
chunk["start"] = segment_chunk.start
|
141 |
+
chunk["end"] = segment_chunk.end
|
142 |
+
chunk["text"] = segment_chunk.text
|
143 |
+
segments.append(chunk)
|
144 |
+
i += 1
|
145 |
+
print("transcribe audio done with fast whisper")
|
146 |
+
except Exception as e:
|
147 |
+
raise RuntimeError("Error converting video to audio")
|
148 |
+
|
149 |
+
try:
|
150 |
+
# Create embedding
|
151 |
+
def segment_embedding(segment):
|
152 |
+
audio = Audio()
|
153 |
+
start = segment["start"]
|
154 |
+
# Whisper overshoots the end timestamp in the last segment
|
155 |
+
end = min(duration, segment["end"])
|
156 |
+
clip = Segment(start, end)
|
157 |
+
waveform, sample_rate = audio.crop(audio_file, clip)
|
158 |
+
return embedding_model(waveform[None])
|
159 |
+
|
160 |
+
embeddings = np.zeros(shape=(len(segments), 192))
|
161 |
+
for i, segment in enumerate(segments):
|
162 |
+
embeddings[i] = segment_embedding(segment)
|
163 |
+
embeddings = np.nan_to_num(embeddings)
|
164 |
+
print(f'Embedding shape: {embeddings.shape}')
|
165 |
+
|
166 |
+
if num_speakers == 0:
|
167 |
+
# Find the best number of speakers
|
168 |
+
score_num_speakers = {}
|
169 |
+
|
170 |
+
for num_speakers in range(2, 10 + 1):
|
171 |
+
clustering = AgglomerativeClustering(num_speakers).fit(embeddings)
|
172 |
+
score = silhouette_score(embeddings, clustering.labels_, metric='euclidean')
|
173 |
+
score_num_speakers[num_speakers] = score
|
174 |
+
best_num_speaker = max(score_num_speakers, key=lambda x: score_num_speakers[x])
|
175 |
+
print(f"The best number of speakers: {best_num_speaker} with {score_num_speakers[best_num_speaker]} score")
|
176 |
+
else:
|
177 |
+
best_num_speaker = num_speakers
|
178 |
+
|
179 |
+
# Assign speaker label
|
180 |
+
clustering = AgglomerativeClustering(best_num_speaker).fit(embeddings)
|
181 |
+
labels = clustering.labels_
|
182 |
+
for i in range(len(segments)):
|
183 |
+
segments[i]["speaker"] = 'SPEAKER ' + str(labels[i] + 1)
|
184 |
+
|
185 |
+
# Make output
|
186 |
+
objects = {
|
187 |
+
'Start': [],
|
188 |
+
'End': [],
|
189 |
+
'Speaker': [],
|
190 |
+
'Text': []
|
191 |
+
}
|
192 |
+
text = ''
|
193 |
+
for (i, segment) in enumerate(segments):
|
194 |
+
if i == 0 or segments[i - 1]["speaker"] != segment["speaker"]:
|
195 |
+
objects['Start'].append(str(convert_time(segment["start"])))
|
196 |
+
objects['Speaker'].append(segment["speaker"])
|
197 |
+
if i != 0:
|
198 |
+
objects['End'].append(str(convert_time(segments[i - 1]["end"])))
|
199 |
+
objects['Text'].append(text)
|
200 |
+
text = ''
|
201 |
+
text += segment["text"] + ' '
|
202 |
+
objects['End'].append(str(convert_time(segments[i - 1]["end"])))
|
203 |
+
objects['Text'].append(text)
|
204 |
+
|
205 |
+
time_end = time.time()
|
206 |
+
time_diff = time_end - time_start
|
207 |
+
memory = psutil.virtual_memory()
|
208 |
+
gpu_utilization, gpu_memory = GPUInfo.gpu_usage()
|
209 |
+
gpu_utilization = gpu_utilization[0] if len(gpu_utilization) > 0 else 0
|
210 |
+
gpu_memory = gpu_memory[0] if len(gpu_memory) > 0 else 0
|
211 |
+
system_info = f"""
|
212 |
+
*Memory: {memory.total / (1024 * 1024 * 1024):.2f}GB, used: {memory.percent}%, available: {memory.available / (1024 * 1024 * 1024):.2f}GB.*
|
213 |
+
*Processing time: {time_diff:.5} seconds.*
|
214 |
+
*GPU Utilization: {gpu_utilization}%, GPU Memory: {gpu_memory}MiB.*
|
215 |
+
"""
|
216 |
+
save_path = "output/transcript_result.csv"
|
217 |
+
df_results = pd.DataFrame(objects)
|
218 |
+
df_results.to_csv(save_path)
|
219 |
+
return df_results, system_info, save_path
|
220 |
+
|
221 |
+
except Exception as e:
|
222 |
+
raise RuntimeError("Error Running inference with local model", e)
|
223 |
+
|
224 |
+
|
225 |
+
# ---- Gradio Layout -----
|
226 |
+
# Inspiration from https://huggingface.co/spaces/RASMUS/Whisper-youtube-crosslingual-subtitles
|
227 |
+
video_in = gr.Video(label="Video file", mirror_webcam=False)
|
228 |
+
youtube_url_in = gr.Textbox(label="Youtube url", lines=1, interactive=True)
|
229 |
+
df_init = pd.DataFrame(columns=['Start', 'End', 'Speaker', 'Text'])
|
230 |
+
memory = psutil.virtual_memory()
|
231 |
+
selected_source_lang = gr.Dropdown(choices=source_language_list, type="value", value="ja",
|
232 |
+
label="Spoken language in video", interactive=True)
|
233 |
+
selected_whisper_model = gr.Dropdown(choices=whisper_models, type="value", value="base", label="Selected Whisper model",
|
234 |
+
interactive=True)
|
235 |
+
number_speakers = gr.Number(precision=0, value=0,
|
236 |
+
label="Input number of speakers for better results. If value=0, model will automatic find the best number of speakers",
|
237 |
+
interactive=True)
|
238 |
+
system_info = gr.Markdown(
|
239 |
+
f"*Memory: {memory.total / (1024 * 1024 * 1024):.2f}GB, used: {memory.percent}%, available: {memory.available / (1024 * 1024 * 1024):.2f}GB*")
|
240 |
+
download_transcript = gr.File(label="Download transcript")
|
241 |
+
transcription_df = gr.DataFrame(value=df_init, label="Transcription dataframe", row_count=(0, "dynamic"), max_rows=10,
|
242 |
+
wrap=True, overflow_row_behaviour='paginate')
|
243 |
+
title = "Whisper speaker diarization"
|
244 |
+
demo = gr.Blocks(title=title)
|
245 |
+
demo.encrypt = False
|
246 |
+
|
247 |
+
with demo:
|
248 |
+
with gr.Row():
|
249 |
+
gr.Markdown('''
|
250 |
+
### You can test by following examples:
|
251 |
+
''')
|
252 |
+
examples = gr.Examples(examples=
|
253 |
+
["https://www.youtube.com/watch?v=j7BfEzAFuYc&t=32s",
|
254 |
+
"https://www.youtube.com/watch?v=-UX0X45sYe4",
|
255 |
+
"https://www.youtube.com/watch?v=7minSgqi-Gw"],
|
256 |
+
label="Examples", inputs=[youtube_url_in])
|
257 |
+
|
258 |
+
with gr.Row():
|
259 |
+
with gr.Column():
|
260 |
+
youtube_url_in.render()
|
261 |
+
download_youtube_btn = gr.Button("Download Youtube video")
|
262 |
+
download_youtube_btn.click(get_youtube, [youtube_url_in], [video_in])
|
263 |
+
print(video_in)
|
264 |
+
|
265 |
+
with gr.Row():
|
266 |
+
with gr.Column():
|
267 |
+
video_in.render()
|
268 |
+
with gr.Column():
|
269 |
+
gr.Markdown('''
|
270 |
+
##### Here you can start the transcription process.
|
271 |
+
##### Please select the source language for transcription.
|
272 |
+
##### You can select a range of assumed numbers of speakers.
|
273 |
+
''')
|
274 |
+
selected_source_lang.render()
|
275 |
+
selected_whisper_model.render()
|
276 |
+
number_speakers.render()
|
277 |
+
transcribe_btn = gr.Button("Transcribe audio and diarization")
|
278 |
+
transcribe_btn.click(speech_to_text,
|
279 |
+
[video_in, selected_source_lang, selected_whisper_model, number_speakers],
|
280 |
+
[transcription_df, system_info, download_transcript]
|
281 |
+
)
|
282 |
+
|
283 |
+
with gr.Row():
|
284 |
+
gr.Markdown('''
|
285 |
+
##### Here you will get transcription output
|
286 |
+
##### ''')
|
287 |
+
|
288 |
+
with gr.Row():
|
289 |
+
with gr.Column():
|
290 |
+
download_transcript.render()
|
291 |
+
transcription_df.render()
|
292 |
+
# system_info.render()
|
293 |
+
|
294 |
+
|
295 |
+
demo.launch(debug=True)
|