Commit
·
9eb42b2
1
Parent(s):
5179d0a
いったんセーブ
Browse files- app.py +152 -16
- app_space.py +498 -0
- requirements.txt +3 -1
app.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
from nemo.collections.asr.models import ASRModel
|
| 2 |
import torch
|
| 3 |
import gradio as gr
|
| 4 |
-
import spaces
|
| 5 |
import gc
|
| 6 |
import shutil
|
| 7 |
from pathlib import Path
|
|
@@ -10,6 +10,7 @@ import numpy as np
|
|
| 10 |
import os
|
| 11 |
import gradio.themes as gr_themes
|
| 12 |
import csv
|
|
|
|
| 13 |
|
| 14 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 15 |
MODEL_NAME="nvidia/parakeet-tdt-0.6b-v2"
|
|
@@ -72,7 +73,7 @@ def get_audio_segment(audio_path, start_second, end_second):
|
|
| 72 |
print(f"Error clipping audio {audio_path} from {start_second}s to {end_second}s: {e}")
|
| 73 |
return None
|
| 74 |
|
| 75 |
-
@spaces.GPU
|
| 76 |
def get_transcripts_and_raw_times(audio_path, session_dir):
|
| 77 |
if not audio_path:
|
| 78 |
gr.Error("No audio file path provided for transcription.", duration=None)
|
|
@@ -172,21 +173,57 @@ def get_transcripts_and_raw_times(audio_path, session_dir):
|
|
| 172 |
for c in char_timestamps_raw if isinstance(c, dict) and 'start' in c and 'end' in c and 'char' in c
|
| 173 |
]
|
| 174 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
button_update = gr.DownloadButton(visible=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
try:
|
| 177 |
csv_file_path = Path(session_dir, f"transcription_{audio_name}.csv")
|
| 178 |
-
with open(csv_file_path, 'w', newline='', encoding='utf-8') as f:
|
| 179 |
writer = csv.writer(f)
|
| 180 |
writer.writerow(csv_headers)
|
| 181 |
writer.writerows(vis_data)
|
| 182 |
print(f"CSV transcript saved to temporary file: {csv_file_path}")
|
| 183 |
-
button_update = gr.DownloadButton(value=csv_file_path.as_posix(), visible=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
except Exception as csv_e:
|
| 185 |
-
gr.Error(f"Failed to create transcript
|
| 186 |
-
print(f"Error writing
|
| 187 |
|
| 188 |
gr.Info("Transcription complete.", duration=2)
|
| 189 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
except torch.cuda.OutOfMemoryError as e:
|
| 192 |
error_msg = 'CUDA out of memory. Please try a shorter audio or reduce GPU load.'
|
|
@@ -266,6 +303,102 @@ def play_segment(evt: gr.SelectData, raw_ts_list, current_audio_path):
|
|
| 266 |
print("Failed to get audio segment data.")
|
| 267 |
return gr.Audio(value=None, label="Selected Segment")
|
| 268 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 269 |
article = (
|
| 270 |
"<p style='font-size: 1.1em;'>"
|
| 271 |
"This demo showcases <code><a href='https://huggingface.co/nvidia/parakeet-tdt-0.6b-v2'>parakeet-tdt-0.6b-v2</a></code>, a 600-million-parameter model designed for high-quality English speech recognition."
|
|
@@ -328,6 +461,10 @@ with gr.Blocks(theme=nvidia_theme) as demo:
|
|
| 328 |
gr.Markdown("<p><strong style='color: #FF0000; font-size: 1.2em;'>Transcription Results</strong></p>")
|
| 329 |
|
| 330 |
download_btn = gr.DownloadButton(label="Download Segment Transcript (CSV)", visible=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
|
| 332 |
with gr.Tabs(): # Tabs for result views
|
| 333 |
with gr.TabItem("Segment View (Click row to play segment)"):
|
|
@@ -339,30 +476,30 @@ with gr.Blocks(theme=nvidia_theme) as demo:
|
|
| 339 |
)
|
| 340 |
selected_segment_player = gr.Audio(label="Selected Segment", interactive=False)
|
| 341 |
|
| 342 |
-
with gr.TabItem("
|
| 343 |
-
|
| 344 |
-
headers=["Start (s)", "End (s)", "
|
| 345 |
datatype=["number", "number", "str"],
|
| 346 |
wrap=False, # As specified in diff
|
| 347 |
-
# label="
|
| 348 |
)
|
| 349 |
|
| 350 |
# Ensure outputs list matches the return order of get_transcripts_and_raw_times:
|
| 351 |
# vis_data, raw_times_data, char_vis_data, audio_path, button_update
|
| 352 |
# maps to:
|
| 353 |
-
# vis_timestamps_df, raw_timestamps_list_state,
|
| 354 |
|
| 355 |
mic_transcribe_btn.click(
|
| 356 |
fn=get_transcripts_and_raw_times,
|
| 357 |
inputs=[mic_input, session_dir_state],
|
| 358 |
-
outputs=[vis_timestamps_df, raw_timestamps_list_state,
|
| 359 |
api_name="transcribe_mic"
|
| 360 |
)
|
| 361 |
|
| 362 |
file_transcribe_btn.click(
|
| 363 |
fn=get_transcripts_and_raw_times,
|
| 364 |
inputs=[file_input, session_dir_state],
|
| 365 |
-
outputs=[vis_timestamps_df, raw_timestamps_list_state,
|
| 366 |
api_name="transcribe_file"
|
| 367 |
)
|
| 368 |
|
|
@@ -372,8 +509,7 @@ with gr.Blocks(theme=nvidia_theme) as demo:
|
|
| 372 |
outputs=[selected_segment_player],
|
| 373 |
)
|
| 374 |
|
| 375 |
-
demo.unload(end_session
|
| 376 |
-
# Corrected: end_session takes no inputs from gr.State directly from unload signature based on original code.
|
| 377 |
|
| 378 |
if __name__ == "__main__":
|
| 379 |
print("Launching Gradio Demo...")
|
|
|
|
| 1 |
from nemo.collections.asr.models import ASRModel
|
| 2 |
import torch
|
| 3 |
import gradio as gr
|
| 4 |
+
# import spaces
|
| 5 |
import gc
|
| 6 |
import shutil
|
| 7 |
from pathlib import Path
|
|
|
|
| 10 |
import os
|
| 11 |
import gradio.themes as gr_themes
|
| 12 |
import csv
|
| 13 |
+
import json
|
| 14 |
|
| 15 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 16 |
MODEL_NAME="nvidia/parakeet-tdt-0.6b-v2"
|
|
|
|
| 73 |
print(f"Error clipping audio {audio_path} from {start_second}s to {end_second}s: {e}")
|
| 74 |
return None
|
| 75 |
|
| 76 |
+
# @spaces.GPU
|
| 77 |
def get_transcripts_and_raw_times(audio_path, session_dir):
|
| 78 |
if not audio_path:
|
| 79 |
gr.Error("No audio file path provided for transcription.", duration=None)
|
|
|
|
| 173 |
for c in char_timestamps_raw if isinstance(c, dict) and 'start' in c and 'end' in c and 'char' in c
|
| 174 |
]
|
| 175 |
|
| 176 |
+
# 単語タイムスタンプ(word)を追加で抽出
|
| 177 |
+
word_timestamps_raw = output[0].timestamp.get("word", [])
|
| 178 |
+
word_vis_data = [
|
| 179 |
+
[f"{w['start']:.2f}", f"{w['end']:.2f}", w["word"]]
|
| 180 |
+
for w in word_timestamps_raw if isinstance(w, dict) and 'start' in w and 'end' in w and 'word' in w
|
| 181 |
+
]
|
| 182 |
+
|
| 183 |
button_update = gr.DownloadButton(visible=False)
|
| 184 |
+
srt_file_path = None
|
| 185 |
+
vtt_file_path = None
|
| 186 |
+
json_file_path = None
|
| 187 |
+
lrc_file_path = None
|
| 188 |
try:
|
| 189 |
csv_file_path = Path(session_dir, f"transcription_{audio_name}.csv")
|
| 190 |
+
with open(csv_file_path, 'w', newline='', encoding='utf-8') as f:
|
| 191 |
writer = csv.writer(f)
|
| 192 |
writer.writerow(csv_headers)
|
| 193 |
writer.writerows(vis_data)
|
| 194 |
print(f"CSV transcript saved to temporary file: {csv_file_path}")
|
| 195 |
+
button_update = gr.DownloadButton(value=csv_file_path.as_posix(), visible=True)
|
| 196 |
+
|
| 197 |
+
# SRT, VTT, JSON も保存
|
| 198 |
+
srt_file_path = Path(session_dir, f"transcription_{audio_name}.srt")
|
| 199 |
+
vtt_file_path = Path(session_dir, f"transcription_{audio_name}.vtt")
|
| 200 |
+
json_file_path = Path(session_dir, f"transcription_{audio_name}.json")
|
| 201 |
+
write_srt(vis_data, srt_file_path)
|
| 202 |
+
write_vtt(vis_data, word_vis_data, vtt_file_path)
|
| 203 |
+
write_json(vis_data, word_vis_data, json_file_path)
|
| 204 |
+
print(f"SRT, VTT, JSON transcript saved to temporary files: {srt_file_path}, {vtt_file_path}, {json_file_path}")
|
| 205 |
+
|
| 206 |
+
# LRC も保存
|
| 207 |
+
lrc_file_path = Path(session_dir, f"transcription_{audio_name}.lrc")
|
| 208 |
+
write_lrc(vis_data, lrc_file_path)
|
| 209 |
+
print(f"LRC transcript saved to temporary file: {lrc_file_path}")
|
| 210 |
except Exception as csv_e:
|
| 211 |
+
gr.Error(f"Failed to create transcript files: {csv_e}", duration=None)
|
| 212 |
+
print(f"Error writing transcript files: {csv_e}")
|
| 213 |
|
| 214 |
gr.Info("Transcription complete.", duration=2)
|
| 215 |
+
# 4つのファイルパスを返す
|
| 216 |
+
return (
|
| 217 |
+
vis_data,
|
| 218 |
+
raw_times_data,
|
| 219 |
+
word_vis_data,
|
| 220 |
+
audio_path,
|
| 221 |
+
gr.DownloadButton(value=csv_file_path.as_posix(), visible=True),
|
| 222 |
+
gr.DownloadButton(value=srt_file_path.as_posix(), visible=True),
|
| 223 |
+
gr.DownloadButton(value=vtt_file_path.as_posix(), visible=True),
|
| 224 |
+
gr.DownloadButton(value=json_file_path.as_posix(), visible=True),
|
| 225 |
+
gr.DownloadButton(value=lrc_file_path.as_posix(), visible=True)
|
| 226 |
+
)
|
| 227 |
|
| 228 |
except torch.cuda.OutOfMemoryError as e:
|
| 229 |
error_msg = 'CUDA out of memory. Please try a shorter audio or reduce GPU load.'
|
|
|
|
| 303 |
print("Failed to get audio segment data.")
|
| 304 |
return gr.Audio(value=None, label="Selected Segment")
|
| 305 |
|
| 306 |
+
def write_srt(segments, path):
|
| 307 |
+
def sec2srt(t):
|
| 308 |
+
h, rem = divmod(int(float(t)), 3600)
|
| 309 |
+
m, s = divmod(rem, 60)
|
| 310 |
+
ms = int((float(t) - int(float(t))) * 1000)
|
| 311 |
+
return f"{h:02}:{m:02}:{s:02},{ms:03}"
|
| 312 |
+
with open(path, "w", encoding="utf-8") as f:
|
| 313 |
+
for i, seg in enumerate(segments, 1):
|
| 314 |
+
f.write(f"{i}\n{sec2srt(seg[0])} --> {sec2srt(seg[1])}\n{seg[2]}\n\n")
|
| 315 |
+
|
| 316 |
+
def write_vtt(segments, words, path):
|
| 317 |
+
def sec2vtt(t):
|
| 318 |
+
h, rem = divmod(int(float(t)), 3600)
|
| 319 |
+
m, s = divmod(rem, 60)
|
| 320 |
+
ms = int((float(t) - int(float(t))) * 1000)
|
| 321 |
+
return f"{h:02}:{m:02}:{s:02}.{ms:03}"
|
| 322 |
+
|
| 323 |
+
with open(path, "w", encoding="utf-8") as f:
|
| 324 |
+
f.write("WEBVTT\n\n")
|
| 325 |
+
|
| 326 |
+
word_idx = 0
|
| 327 |
+
for seg in segments:
|
| 328 |
+
s_start = float(seg[0])
|
| 329 |
+
s_end = float(seg[1])
|
| 330 |
+
s_text = seg[2]
|
| 331 |
+
|
| 332 |
+
# このセグメントに含まれる単語を抽出
|
| 333 |
+
segment_words = []
|
| 334 |
+
while word_idx < len(words):
|
| 335 |
+
w = words[word_idx]
|
| 336 |
+
w_start = float(w[0])
|
| 337 |
+
w_end = float(w[1])
|
| 338 |
+
if w_start >= s_start and w_end <= s_end:
|
| 339 |
+
segment_words.append(w)
|
| 340 |
+
word_idx += 1
|
| 341 |
+
elif w_end < s_start:
|
| 342 |
+
word_idx += 1
|
| 343 |
+
else:
|
| 344 |
+
break
|
| 345 |
+
|
| 346 |
+
# 各単語ごとにタイムスタンプを生成
|
| 347 |
+
for i, w in enumerate(segment_words):
|
| 348 |
+
w_start = float(w[0])
|
| 349 |
+
w_end = float(w[1])
|
| 350 |
+
w_text = w[2]
|
| 351 |
+
|
| 352 |
+
# 現在の単語を強調表示し、他の単語は通常表示
|
| 353 |
+
colored_text = ""
|
| 354 |
+
for j, other_w in enumerate(segment_words):
|
| 355 |
+
if j == i:
|
| 356 |
+
colored_text += f"<c.yellow><b>{other_w[2]}</b></c> "
|
| 357 |
+
else:
|
| 358 |
+
colored_text += f"{other_w[2]} "
|
| 359 |
+
|
| 360 |
+
f.write(f"{sec2vtt(w_start)} --> {sec2vtt(w_end)}\n{colored_text.strip()}\n\n")
|
| 361 |
+
|
| 362 |
+
def write_json(segments, words, path):
|
| 363 |
+
# segments: [[start, end, text], ...]
|
| 364 |
+
# words: [[start, end, word], ...]
|
| 365 |
+
result = {"segments": []}
|
| 366 |
+
word_idx = 0
|
| 367 |
+
for s in segments:
|
| 368 |
+
s_start = float(s[0])
|
| 369 |
+
s_end = float(s[1])
|
| 370 |
+
s_text = s[2]
|
| 371 |
+
word_list = []
|
| 372 |
+
# wordのstartがこのsegmentの範囲内のものを抽出
|
| 373 |
+
while word_idx < len(words):
|
| 374 |
+
w = words[word_idx]
|
| 375 |
+
w_start = float(w[0])
|
| 376 |
+
w_end = float(w[1])
|
| 377 |
+
if w_start >= s_start and w_end <= s_end:
|
| 378 |
+
word_list.append({"start": w_start, "end": w_end, "word": w[2]})
|
| 379 |
+
word_idx += 1
|
| 380 |
+
elif w_end < s_start:
|
| 381 |
+
word_idx += 1
|
| 382 |
+
else:
|
| 383 |
+
break
|
| 384 |
+
result["segments"].append({
|
| 385 |
+
"start": s_start,
|
| 386 |
+
"end": s_end,
|
| 387 |
+
"text": s_text,
|
| 388 |
+
"words": word_list
|
| 389 |
+
})
|
| 390 |
+
with open(path, "w", encoding="utf-8") as f:
|
| 391 |
+
json.dump(result, f, ensure_ascii=False, indent=2)
|
| 392 |
+
|
| 393 |
+
def write_lrc(segments, path):
|
| 394 |
+
# segments: [[start, end, text], ...]
|
| 395 |
+
def sec2lrc(t):
|
| 396 |
+
m, s = divmod(float(t), 60)
|
| 397 |
+
return f"[{int(m):02}:{s:05.2f}]"
|
| 398 |
+
with open(path, "w", encoding="utf-8") as f:
|
| 399 |
+
for seg in segments:
|
| 400 |
+
f.write(f"{sec2lrc(seg[0])}{seg[2]}\n")
|
| 401 |
+
|
| 402 |
article = (
|
| 403 |
"<p style='font-size: 1.1em;'>"
|
| 404 |
"This demo showcases <code><a href='https://huggingface.co/nvidia/parakeet-tdt-0.6b-v2'>parakeet-tdt-0.6b-v2</a></code>, a 600-million-parameter model designed for high-quality English speech recognition."
|
|
|
|
| 461 |
gr.Markdown("<p><strong style='color: #FF0000; font-size: 1.2em;'>Transcription Results</strong></p>")
|
| 462 |
|
| 463 |
download_btn = gr.DownloadButton(label="Download Segment Transcript (CSV)", visible=False)
|
| 464 |
+
srt_btn = gr.DownloadButton(label="Download SRT", visible=False)
|
| 465 |
+
vtt_btn = gr.DownloadButton(label="Download VTT", visible=False)
|
| 466 |
+
json_btn = gr.DownloadButton(label="Download JSON", visible=False)
|
| 467 |
+
lrc_btn = gr.DownloadButton(label="Download LRC", visible=False)
|
| 468 |
|
| 469 |
with gr.Tabs(): # Tabs for result views
|
| 470 |
with gr.TabItem("Segment View (Click row to play segment)"):
|
|
|
|
| 476 |
)
|
| 477 |
selected_segment_player = gr.Audio(label="Selected Segment", interactive=False)
|
| 478 |
|
| 479 |
+
with gr.TabItem("Word View"):
|
| 480 |
+
word_vis_df = gr.DataFrame( # Define word_vis_df here
|
| 481 |
+
headers=["Start (s)", "End (s)", "Word"],
|
| 482 |
datatype=["number", "number", "str"],
|
| 483 |
wrap=False, # As specified in diff
|
| 484 |
+
# label="Word Timestamps" # Label provided by tab
|
| 485 |
)
|
| 486 |
|
| 487 |
# Ensure outputs list matches the return order of get_transcripts_and_raw_times:
|
| 488 |
# vis_data, raw_times_data, char_vis_data, audio_path, button_update
|
| 489 |
# maps to:
|
| 490 |
+
# vis_timestamps_df, raw_timestamps_list_state, word_vis_df, current_audio_path_state, download_btn
|
| 491 |
|
| 492 |
mic_transcribe_btn.click(
|
| 493 |
fn=get_transcripts_and_raw_times,
|
| 494 |
inputs=[mic_input, session_dir_state],
|
| 495 |
+
outputs=[vis_timestamps_df, raw_timestamps_list_state, word_vis_df, current_audio_path_state, download_btn, srt_btn, vtt_btn, json_btn, lrc_btn],
|
| 496 |
api_name="transcribe_mic"
|
| 497 |
)
|
| 498 |
|
| 499 |
file_transcribe_btn.click(
|
| 500 |
fn=get_transcripts_and_raw_times,
|
| 501 |
inputs=[file_input, session_dir_state],
|
| 502 |
+
outputs=[vis_timestamps_df, raw_timestamps_list_state, word_vis_df, current_audio_path_state, download_btn, srt_btn, vtt_btn, json_btn, lrc_btn],
|
| 503 |
api_name="transcribe_file"
|
| 504 |
)
|
| 505 |
|
|
|
|
| 509 |
outputs=[selected_segment_player],
|
| 510 |
)
|
| 511 |
|
| 512 |
+
demo.unload(end_session)
|
|
|
|
| 513 |
|
| 514 |
if __name__ == "__main__":
|
| 515 |
print("Launching Gradio Demo...")
|
app_space.py
ADDED
|
@@ -0,0 +1,498 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from nemo.collections.asr.models import ASRModel
|
| 2 |
+
import torch
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import spaces
|
| 5 |
+
import gc
|
| 6 |
+
import shutil
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from pydub import AudioSegment
|
| 9 |
+
import numpy as np
|
| 10 |
+
import os
|
| 11 |
+
import gradio.themes as gr_themes
|
| 12 |
+
import csv
|
| 13 |
+
import json
|
| 14 |
+
|
| 15 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 16 |
+
MODEL_NAME="nvidia/parakeet-tdt-0.6b-v2"
|
| 17 |
+
|
| 18 |
+
model = ASRModel.from_pretrained(model_name=MODEL_NAME)
|
| 19 |
+
model.eval()
|
| 20 |
+
|
| 21 |
+
def start_session(request: gr.Request):
|
| 22 |
+
session_hash = request.session_hash
|
| 23 |
+
session_dir = Path(f'/tmp/{session_hash}')
|
| 24 |
+
session_dir.mkdir(parents=True, exist_ok=True)
|
| 25 |
+
print(f"Session with hash {session_hash} started.")
|
| 26 |
+
return session_dir.as_posix()
|
| 27 |
+
|
| 28 |
+
def end_session(request: gr.Request):
|
| 29 |
+
session_hash = request.session_hash
|
| 30 |
+
session_dir = Path(f'/tmp/{session_hash}')
|
| 31 |
+
if session_dir.exists():
|
| 32 |
+
shutil.rmtree(session_dir)
|
| 33 |
+
print(f"Session with hash {session_hash} ended.")
|
| 34 |
+
|
| 35 |
+
def get_audio_segment(audio_path, start_second, end_second):
|
| 36 |
+
if not audio_path or not Path(audio_path).exists():
|
| 37 |
+
print(f"Warning: Audio path '{audio_path}' not found or invalid for clipping.")
|
| 38 |
+
return None
|
| 39 |
+
try:
|
| 40 |
+
start_ms = int(start_second * 1000)
|
| 41 |
+
end_ms = int(end_second * 1000)
|
| 42 |
+
|
| 43 |
+
start_ms = max(0, start_ms)
|
| 44 |
+
if end_ms <= start_ms:
|
| 45 |
+
print(f"Warning: End time ({end_second}s) is not after start time ({start_second}s). Adjusting end time.")
|
| 46 |
+
end_ms = start_ms + 100
|
| 47 |
+
|
| 48 |
+
audio = AudioSegment.from_file(audio_path)
|
| 49 |
+
clipped_audio = audio[start_ms:end_ms]
|
| 50 |
+
|
| 51 |
+
samples = np.array(clipped_audio.get_array_of_samples())
|
| 52 |
+
if clipped_audio.channels == 2:
|
| 53 |
+
samples = samples.reshape((-1, 2)).mean(axis=1).astype(samples.dtype)
|
| 54 |
+
|
| 55 |
+
frame_rate = clipped_audio.frame_rate
|
| 56 |
+
if frame_rate <= 0:
|
| 57 |
+
print(f"Warning: Invalid frame rate ({frame_rate}) detected for clipped audio.")
|
| 58 |
+
frame_rate = audio.frame_rate
|
| 59 |
+
|
| 60 |
+
if samples.size == 0:
|
| 61 |
+
print(f"Warning: Clipped audio resulted in empty samples array ({start_second}s to {end_second}s).")
|
| 62 |
+
return None
|
| 63 |
+
|
| 64 |
+
return (frame_rate, samples)
|
| 65 |
+
except FileNotFoundError:
|
| 66 |
+
print(f"Error: Audio file not found at path: {audio_path}")
|
| 67 |
+
return None
|
| 68 |
+
except Exception as e:
|
| 69 |
+
print(f"Error clipping audio {audio_path} from {start_second}s to {end_second}s: {e}")
|
| 70 |
+
return None
|
| 71 |
+
|
| 72 |
+
@spaces.GPU
|
| 73 |
+
def get_transcripts_and_raw_times(audio_path, session_dir):
|
| 74 |
+
if not audio_path:
|
| 75 |
+
gr.Error("No audio file path provided for transcription.", duration=None)
|
| 76 |
+
return [], [], [], None, gr.DownloadButton(visible=False)
|
| 77 |
+
|
| 78 |
+
vis_data = [["N/A", "N/A", "Processing failed"]]
|
| 79 |
+
raw_times_data = [[0.0, 0.0]]
|
| 80 |
+
char_vis_data = []
|
| 81 |
+
processed_audio_path = None
|
| 82 |
+
original_path_name = Path(audio_path).name
|
| 83 |
+
audio_name = Path(audio_path).stem
|
| 84 |
+
|
| 85 |
+
try:
|
| 86 |
+
try:
|
| 87 |
+
gr.Info(f"Loading audio: {original_path_name}", duration=2)
|
| 88 |
+
audio = AudioSegment.from_file(audio_path)
|
| 89 |
+
duration_sec = audio.duration_seconds
|
| 90 |
+
except Exception as load_e:
|
| 91 |
+
gr.Error(f"Failed to load audio file {original_path_name}: {load_e}", duration=None)
|
| 92 |
+
return [["Error", "Error", "Load failed"]], [[0.0, 0.0]], [], audio_path, gr.DownloadButton(visible=False)
|
| 93 |
+
|
| 94 |
+
resampled = False
|
| 95 |
+
mono = False
|
| 96 |
+
target_sr = 16000
|
| 97 |
+
|
| 98 |
+
if audio.frame_rate != target_sr:
|
| 99 |
+
try:
|
| 100 |
+
audio = audio.set_frame_rate(target_sr)
|
| 101 |
+
resampled = True
|
| 102 |
+
except Exception as resample_e:
|
| 103 |
+
gr.Error(f"Failed to resample audio: {resample_e}", duration=None)
|
| 104 |
+
return [["Error", "Error", "Resample failed"]], [[0.0, 0.0]], [], audio_path, gr.DownloadButton(visible=False)
|
| 105 |
+
|
| 106 |
+
if audio.channels == 2:
|
| 107 |
+
try:
|
| 108 |
+
audio = audio.set_channels(1)
|
| 109 |
+
mono = True
|
| 110 |
+
except Exception as mono_e:
|
| 111 |
+
gr.Error(f"Failed to convert audio to mono: {mono_e}", duration=None)
|
| 112 |
+
return [["Error", "Error", "Mono conversion failed"]], [[0.0, 0.0]], [], audio_path, gr.DownloadButton(visible=False)
|
| 113 |
+
elif audio.channels > 2:
|
| 114 |
+
gr.Error(f"Audio has {audio.channels} channels. Only mono (1) or stereo (2) supported.", duration=None)
|
| 115 |
+
return [["Error", "Error", f"{audio.channels}-channel audio not supported"]], [[0.0, 0.0]], [], audio_path, gr.DownloadButton(visible=False)
|
| 116 |
+
|
| 117 |
+
if resampled or mono:
|
| 118 |
+
try:
|
| 119 |
+
processed_audio_path = Path(session_dir, f"{audio_name}_resampled.wav")
|
| 120 |
+
audio.export(processed_audio_path, format="wav")
|
| 121 |
+
transcribe_path = processed_audio_path.as_posix()
|
| 122 |
+
info_path_name = f"{original_path_name} (processed)"
|
| 123 |
+
except Exception as export_e:
|
| 124 |
+
gr.Error(f"Failed to export processed audio: {export_e}", duration=None)
|
| 125 |
+
if processed_audio_path and os.path.exists(processed_audio_path):
|
| 126 |
+
os.remove(processed_audio_path)
|
| 127 |
+
return [["Error", "Error", "Export failed"]], [[0.0, 0.0]], [], audio_path, gr.DownloadButton(visible=False)
|
| 128 |
+
else:
|
| 129 |
+
transcribe_path = audio_path
|
| 130 |
+
info_path_name = original_path_name
|
| 131 |
+
|
| 132 |
+
long_audio_settings_applied = False
|
| 133 |
+
try:
|
| 134 |
+
model.to(device)
|
| 135 |
+
model.to(torch.float32)
|
| 136 |
+
gr.Info(f"Transcribing {info_path_name} on {device}...", duration=2)
|
| 137 |
+
|
| 138 |
+
if duration_sec > 480:
|
| 139 |
+
try:
|
| 140 |
+
gr.Info("Audio longer than 8 minutes. Applying optimized settings for long transcription.", duration=3)
|
| 141 |
+
print("Applying long audio settings: Local Attention and Chunking.")
|
| 142 |
+
model.change_attention_model("rel_pos_local_attn", [256,256])
|
| 143 |
+
model.change_subsampling_conv_chunking_factor(1)
|
| 144 |
+
long_audio_settings_applied = True
|
| 145 |
+
except Exception as setting_e:
|
| 146 |
+
gr.Warning(f"Could not apply long audio settings: {setting_e}", duration=5)
|
| 147 |
+
print(f"Warning: Failed to apply long audio settings: {setting_e}")
|
| 148 |
+
|
| 149 |
+
model.to(torch.bfloat16)
|
| 150 |
+
output = model.transcribe([transcribe_path], timestamps=True)
|
| 151 |
+
|
| 152 |
+
if not output or not isinstance(output, list) or not output[0] or not hasattr(output[0], 'timestamp') or not output[0].timestamp or 'segment' not in output[0].timestamp:
|
| 153 |
+
gr.Error("Transcription failed or produced unexpected output format.", duration=None)
|
| 154 |
+
return [["Error", "Error", "Transcription Format Issue"]], [[0.0, 0.0]], [], audio_path, gr.DownloadButton(visible=False)
|
| 155 |
+
|
| 156 |
+
segment_timestamps = output[0].timestamp['segment']
|
| 157 |
+
csv_headers = ["Start (s)", "End (s)", "Segment"]
|
| 158 |
+
vis_data = [[f"{ts['start']:.2f}", f"{ts['end']:.2f}", ts['segment']] for ts in segment_timestamps]
|
| 159 |
+
raw_times_data = [[ts['start'], ts['end']] for ts in segment_timestamps]
|
| 160 |
+
|
| 161 |
+
char_timestamps_raw = output[0].timestamp.get("char", [])
|
| 162 |
+
if not isinstance(char_timestamps_raw, list):
|
| 163 |
+
print(f"Warning: char_timestamps_raw is not a list, but {type(char_timestamps_raw)}. Defaulting to empty.")
|
| 164 |
+
char_timestamps_raw = []
|
| 165 |
+
char_vis_data = [
|
| 166 |
+
[f"{c['start']:.2f}", f"{c['end']:.2f}", c["char"]]
|
| 167 |
+
for c in char_timestamps_raw if isinstance(c, dict) and 'start' in c and 'end' in c and 'char' in c
|
| 168 |
+
]
|
| 169 |
+
|
| 170 |
+
word_timestamps_raw = output[0].timestamp.get("word", [])
|
| 171 |
+
word_vis_data = [
|
| 172 |
+
[f"{w['start']:.2f}", f"{w['end']:.2f}", w["word"]]
|
| 173 |
+
for w in word_timestamps_raw if isinstance(w, dict) and 'start' in w and 'end' in w and 'word' in w
|
| 174 |
+
]
|
| 175 |
+
|
| 176 |
+
button_update = gr.DownloadButton(visible=False)
|
| 177 |
+
srt_file_path = None
|
| 178 |
+
vtt_file_path = None
|
| 179 |
+
json_file_path = None
|
| 180 |
+
lrc_file_path = None
|
| 181 |
+
try:
|
| 182 |
+
csv_file_path = Path(session_dir, f"transcription_{audio_name}.csv")
|
| 183 |
+
with open(csv_file_path, 'w', newline='', encoding='utf-8') as f:
|
| 184 |
+
writer = csv.writer(f)
|
| 185 |
+
writer.writerow(csv_headers)
|
| 186 |
+
writer.writerows(vis_data)
|
| 187 |
+
print(f"CSV transcript saved to temporary file: {csv_file_path}")
|
| 188 |
+
button_update = gr.DownloadButton(value=csv_file_path.as_posix(), visible=True)
|
| 189 |
+
|
| 190 |
+
srt_file_path = Path(session_dir, f"transcription_{audio_name}.srt")
|
| 191 |
+
vtt_file_path = Path(session_dir, f"transcription_{audio_name}.vtt")
|
| 192 |
+
json_file_path = Path(session_dir, f"transcription_{audio_name}.json")
|
| 193 |
+
write_srt(vis_data, srt_file_path)
|
| 194 |
+
write_vtt(vis_data, word_vis_data, vtt_file_path)
|
| 195 |
+
write_json(vis_data, word_vis_data, json_file_path)
|
| 196 |
+
print(f"SRT, VTT, JSON transcript saved to temporary files: {srt_file_path}, {vtt_file_path}, {json_file_path}")
|
| 197 |
+
|
| 198 |
+
lrc_file_path = Path(session_dir, f"transcription_{audio_name}.lrc")
|
| 199 |
+
write_lrc(vis_data, word_vis_data, lrc_file_path)
|
| 200 |
+
print(f"LRC transcript saved to temporary file: {lrc_file_path}")
|
| 201 |
+
except Exception as csv_e:
|
| 202 |
+
gr.Error(f"Failed to create transcript files: {csv_e}", duration=None)
|
| 203 |
+
print(f"Error writing transcript files: {csv_e}")
|
| 204 |
+
|
| 205 |
+
gr.Info("Transcription complete.", duration=2)
|
| 206 |
+
return (
|
| 207 |
+
vis_data,
|
| 208 |
+
raw_times_data,
|
| 209 |
+
word_vis_data,
|
| 210 |
+
audio_path,
|
| 211 |
+
gr.DownloadButton(value=csv_file_path.as_posix(), visible=True),
|
| 212 |
+
gr.DownloadButton(value=srt_file_path.as_posix(), visible=True),
|
| 213 |
+
gr.DownloadButton(value=vtt_file_path.as_posix(), visible=True),
|
| 214 |
+
gr.DownloadButton(value=json_file_path.as_posix(), visible=True),
|
| 215 |
+
gr.DownloadButton(value=lrc_file_path.as_posix(), visible=True)
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
except torch.cuda.OutOfMemoryError as e:
|
| 219 |
+
error_msg = 'CUDA out of memory. Please try a shorter audio or reduce GPU load.'
|
| 220 |
+
print(f"CUDA OutOfMemoryError: {e}")
|
| 221 |
+
gr.Error(error_msg, duration=None)
|
| 222 |
+
return [["OOM", "OOM", error_msg]], [[0.0, 0.0]], [], audio_path, gr.DownloadButton(visible=False)
|
| 223 |
+
|
| 224 |
+
except FileNotFoundError:
|
| 225 |
+
error_msg = f"Audio file for transcription not found: {Path(transcribe_path).name}."
|
| 226 |
+
print(f"Error: Transcribe audio file not found at path: {transcribe_path}")
|
| 227 |
+
gr.Error(error_msg, duration=None)
|
| 228 |
+
return [["Error", "Error", "File not found for transcription"]], [[0.0, 0.0]], [], audio_path, gr.DownloadButton(visible=False)
|
| 229 |
+
|
| 230 |
+
except Exception as e:
|
| 231 |
+
error_msg = f"Transcription failed: {e}"
|
| 232 |
+
print(f"Error during transcription processing: {e}")
|
| 233 |
+
gr.Error(error_msg, duration=None)
|
| 234 |
+
return [["Error", "Error", error_msg]], [[0.0, 0.0]], [], audio_path, gr.DownloadButton(visible=False)
|
| 235 |
+
finally:
|
| 236 |
+
try:
|
| 237 |
+
if long_audio_settings_applied:
|
| 238 |
+
try:
|
| 239 |
+
print("Reverting long audio settings.")
|
| 240 |
+
model.change_attention_model("rel_pos")
|
| 241 |
+
model.change_subsampling_conv_chunking_factor(-1)
|
| 242 |
+
except Exception as revert_e:
|
| 243 |
+
print(f"Warning: Failed to revert long audio settings: {revert_e}")
|
| 244 |
+
gr.Warning(f"Issue reverting model settings after long transcription: {revert_e}", duration=5)
|
| 245 |
+
|
| 246 |
+
if 'model' in locals() and hasattr(model, 'cpu'):
|
| 247 |
+
if device == 'cuda':
|
| 248 |
+
model.cpu()
|
| 249 |
+
gc.collect()
|
| 250 |
+
if device == 'cuda':
|
| 251 |
+
torch.cuda.empty_cache()
|
| 252 |
+
except Exception as cleanup_e:
|
| 253 |
+
print(f"Error during model cleanup: {cleanup_e}")
|
| 254 |
+
gr.Warning(f"Issue during model cleanup: {cleanup_e}", duration=5)
|
| 255 |
+
finally:
|
| 256 |
+
if processed_audio_path and os.path.exists(processed_audio_path):
|
| 257 |
+
try:
|
| 258 |
+
os.remove(processed_audio_path)
|
| 259 |
+
print(f"Temporary audio file {processed_audio_path} removed.")
|
| 260 |
+
except Exception as e:
|
| 261 |
+
print(f"Error removing temporary audio file {processed_audio_path}: {e}")
|
| 262 |
+
|
| 263 |
+
def play_segment(evt: gr.SelectData, raw_ts_list, current_audio_path):
|
| 264 |
+
if not isinstance(raw_ts_list, list):
|
| 265 |
+
print(f"Warning: raw_ts_list is not a list ({type(raw_ts_list)}). Cannot play segment.")
|
| 266 |
+
return gr.Audio(value=None, label="Selected Segment")
|
| 267 |
+
|
| 268 |
+
if not current_audio_path:
|
| 269 |
+
print("No audio path available to play segment from.")
|
| 270 |
+
return gr.Audio(value=None, label="Selected Segment")
|
| 271 |
+
|
| 272 |
+
selected_index = evt.index[0]
|
| 273 |
+
|
| 274 |
+
if selected_index < 0 or selected_index >= len(raw_ts_list):
|
| 275 |
+
print(f"Invalid index {selected_index} selected for list of length {len(raw_ts_list)}.")
|
| 276 |
+
return gr.Audio(value=None, label="Selected Segment")
|
| 277 |
+
|
| 278 |
+
if not isinstance(raw_ts_list[selected_index], (list, tuple)) or len(raw_ts_list[selected_index]) != 2:
|
| 279 |
+
print(f"Warning: Data at index {selected_index} is not in the expected format [start, end].")
|
| 280 |
+
return gr.Audio(value=None, label="Selected Segment")
|
| 281 |
+
|
| 282 |
+
start_time_s, end_time_s = raw_ts_list[selected_index]
|
| 283 |
+
print(f"Attempting to play segment: {current_audio_path} from {start_time_s:.2f}s to {end_time_s:.2f}s")
|
| 284 |
+
segment_data = get_audio_segment(current_audio_path, start_time_s, end_time_s)
|
| 285 |
+
|
| 286 |
+
if segment_data:
|
| 287 |
+
print("Segment data retrieved successfully.")
|
| 288 |
+
return gr.Audio(value=segment_data, autoplay=True, label=f"Segment: {start_time_s:.2f}s - {end_time_s:.2f}s", interactive=False)
|
| 289 |
+
else:
|
| 290 |
+
print("Failed to get audio segment data.")
|
| 291 |
+
return gr.Audio(value=None, label="Selected Segment")
|
| 292 |
+
|
| 293 |
+
def write_srt(segments, path):
|
| 294 |
+
def sec2srt(t):
|
| 295 |
+
h, rem = divmod(int(float(t)), 3600)
|
| 296 |
+
m, s = divmod(rem, 60)
|
| 297 |
+
ms = int((float(t) - int(float(t))) * 1000)
|
| 298 |
+
return f"{h:02}:{m:02}:{s:02},{ms:03}"
|
| 299 |
+
with open(path, "w", encoding="utf-8") as f:
|
| 300 |
+
for i, seg in enumerate(segments, 1):
|
| 301 |
+
f.write(f"{i}\n{sec2srt(seg[0])} --> {sec2srt(seg[1])}\n{seg[2]}\n\n")
|
| 302 |
+
|
| 303 |
+
def write_vtt(segments, words, path):
|
| 304 |
+
def sec2vtt(t):
|
| 305 |
+
h, rem = divmod(int(float(t)), 3600)
|
| 306 |
+
m, s = divmod(rem, 60)
|
| 307 |
+
ms = int((float(t) - int(float(t))) * 1000)
|
| 308 |
+
return f"{h:02}:{m:02}:{s:02}.{ms:03}"
|
| 309 |
+
with open(path, "w", encoding="utf-8") as f:
|
| 310 |
+
f.write("WEBVTT\n\n")
|
| 311 |
+
word_idx = 0
|
| 312 |
+
for seg in segments:
|
| 313 |
+
s_start = float(seg[0])
|
| 314 |
+
s_end = float(seg[1])
|
| 315 |
+
s_text = seg[2]
|
| 316 |
+
# このセグメントに含まれる単語を抽出
|
| 317 |
+
segment_words = []
|
| 318 |
+
while word_idx < len(words):
|
| 319 |
+
w = words[word_idx]
|
| 320 |
+
w_start = float(w[0])
|
| 321 |
+
w_end = float(w[1])
|
| 322 |
+
if w_start >= s_start and w_end <= s_end:
|
| 323 |
+
segment_words.append(w)
|
| 324 |
+
word_idx += 1
|
| 325 |
+
elif w_end < s_start:
|
| 326 |
+
word_idx += 1
|
| 327 |
+
else:
|
| 328 |
+
break
|
| 329 |
+
prev_end = s_start
|
| 330 |
+
for i, w in enumerate(segment_words):
|
| 331 |
+
w_start = float(w[0])
|
| 332 |
+
w_end = float(w[1])
|
| 333 |
+
# 空白区間(前の単語のend~今の単語のstart)
|
| 334 |
+
if prev_end < w_start:
|
| 335 |
+
f.write(f"{sec2vtt(prev_end)} --> {sec2vtt(w_start)}\n{s_text}\n\n")
|
| 336 |
+
# 今の単語をハイライト
|
| 337 |
+
colored_text = ""
|
| 338 |
+
for j, other_w in enumerate(segment_words):
|
| 339 |
+
if j == i:
|
| 340 |
+
colored_text += f"<c.yellow><b>{other_w[2]}</b></c> "
|
| 341 |
+
else:
|
| 342 |
+
colored_text += f"{other_w[2]} "
|
| 343 |
+
f.write(f"{sec2vtt(w_start)} --> {sec2vtt(w_end)}\n{colored_text.strip()}\n\n")
|
| 344 |
+
prev_end = w_end
|
| 345 |
+
# 次の単語の開始まで空白があれば埋める
|
| 346 |
+
if i+1 < len(segment_words):
|
| 347 |
+
next_start = float(segment_words[i+1][0])
|
| 348 |
+
if prev_end < next_start:
|
| 349 |
+
f.write(f"{sec2vtt(prev_end)} --> {sec2vtt(next_start)}\n{s_text}\n\n")
|
| 350 |
+
prev_end = next_start
|
| 351 |
+
# 最後の単語のend~セグメントのendまで
|
| 352 |
+
if prev_end < s_end:
|
| 353 |
+
f.write(f"{sec2vtt(prev_end)} --> {sec2vtt(s_end)}\n{s_text}\n\n")
|
| 354 |
+
|
| 355 |
+
def write_json(segments, words, path):
|
| 356 |
+
result = {"segments": []}
|
| 357 |
+
word_idx = 0
|
| 358 |
+
for s in segments:
|
| 359 |
+
s_start = float(s[0])
|
| 360 |
+
s_end = float(s[1])
|
| 361 |
+
s_text = s[2]
|
| 362 |
+
word_list = []
|
| 363 |
+
while word_idx < len(words):
|
| 364 |
+
w = words[word_idx]
|
| 365 |
+
w_start = float(w[0])
|
| 366 |
+
w_end = float(w[1])
|
| 367 |
+
if w_start >= s_start and w_end <= s_end:
|
| 368 |
+
word_list.append({"start": w_start, "end": w_end, "word": w[2]})
|
| 369 |
+
word_idx += 1
|
| 370 |
+
elif w_end < s_start:
|
| 371 |
+
word_idx += 1
|
| 372 |
+
else:
|
| 373 |
+
break
|
| 374 |
+
result["segments"].append({
|
| 375 |
+
"start": s_start,
|
| 376 |
+
"end": s_end,
|
| 377 |
+
"text": s_text,
|
| 378 |
+
"words": word_list
|
| 379 |
+
})
|
| 380 |
+
with open(path, "w", encoding="utf-8") as f:
|
| 381 |
+
json.dump(result, f, ensure_ascii=False, indent=2)
|
| 382 |
+
|
| 383 |
+
def write_lrc(segments, words, path):
|
| 384 |
+
def sec2lrc(t):
|
| 385 |
+
m, s = divmod(float(t), 60)
|
| 386 |
+
return f"[{int(m):02}:{s:05.2f}]"
|
| 387 |
+
with open(path, "w", encoding="utf-8") as f:
|
| 388 |
+
for w in words:
|
| 389 |
+
f.write(f"{sec2lrc(w[0])}{w[2]}\n")
|
| 390 |
+
|
| 391 |
+
article = (
|
| 392 |
+
"<p style='font-size: 1.1em;'>"
|
| 393 |
+
"This demo showcases <code><a href='https://huggingface.co/nvidia/parakeet-tdt-0.6b-v2'>parakeet-tdt-0.6b-v2</a></code>, a 600-million-parameter model designed for high-quality English speech recognition."
|
| 394 |
+
"</p>"
|
| 395 |
+
"<p><strong style='color: red; font-size: 1.2em;'>Key Features:</strong></p>"
|
| 396 |
+
"<ul style='font-size: 1.1em;'>"
|
| 397 |
+
" <li>Automatic punctuation and capitalization</li>"
|
| 398 |
+
" <li>Accurate word-level timestamps (click on a segment in the table below to play it!)</li>"
|
| 399 |
+
" <li>Character-level timestamps now available in the 'Character View' tab.</li>"
|
| 400 |
+
" <li>Efficiently transcribes long audio segments (<strong>updated to support upto 3 hours</strong>) <small>(For even longer audios, see <a href='https://github.com/NVIDIA/NeMo/blob/main/examples/asr/asr_chunked_inference/rnnt/speech_to_text_buffered_infer_rnnt.py' target='_blank'>this script</a>)</small></li>"
|
| 401 |
+
" <li>Robust performance on spoken numbers, and song lyrics transcription </li>"
|
| 402 |
+
"</ul>"
|
| 403 |
+
"<p style='font-size: 1.1em;'>"
|
| 404 |
+
"This model is <strong>available for commercial and non-commercial use</strong>."
|
| 405 |
+
"</p>"
|
| 406 |
+
"<p style='text-align: center;'>"
|
| 407 |
+
"<a href='https://huggingface.co/nvidia/parakeet-tdt-0.6b-v2' target='_blank'>🎙️ Learn more about the Model</a> | "
|
| 408 |
+
"<a href='https://arxiv.org/abs/2305.05084' target='_blank'>📄 Fast Conformer paper</a> | "
|
| 409 |
+
"<a href='https://arxiv.org/abs/2304.06795' target='_blank'>📚 TDT paper</a> | "
|
| 410 |
+
"<a href='https://github.com/NVIDIA/NeMo' target='_blank'>🧑💻 NeMo Repository</a>"
|
| 411 |
+
"</p>"
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
examples = [
|
| 415 |
+
["data/example-yt_saTD1u8PorI.mp3"],
|
| 416 |
+
]
|
| 417 |
+
|
| 418 |
+
nvidia_theme = gr_themes.Default(
|
| 419 |
+
primary_hue=gr_themes.Color(
|
| 420 |
+
c50="#E6F1D9", c100="#CEE3B3", c200="#B5D58C", c300="#9CC766",
|
| 421 |
+
c400="#84B940", c500="#76B900", c600="#68A600", c700="#5A9200",
|
| 422 |
+
c800="#4C7E00", c900="#3E6A00", c950="#2F5600"
|
| 423 |
+
),
|
| 424 |
+
neutral_hue="gray",
|
| 425 |
+
font=[gr_themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"],
|
| 426 |
+
).set()
|
| 427 |
+
|
| 428 |
+
with gr.Blocks(theme=nvidia_theme) as demo:
|
| 429 |
+
model_display_name = MODEL_NAME.split('/')[-1] if '/' in MODEL_NAME else MODEL_NAME
|
| 430 |
+
gr.Markdown(f"<h1 style='text-align: center; margin: 0 auto;'>Speech Transcription with {model_display_name}</h1>")
|
| 431 |
+
gr.HTML(article)
|
| 432 |
+
|
| 433 |
+
current_audio_path_state = gr.State(None)
|
| 434 |
+
raw_timestamps_list_state = gr.State([])
|
| 435 |
+
session_dir_state = gr.State()
|
| 436 |
+
demo.load(start_session, outputs=[session_dir_state])
|
| 437 |
+
|
| 438 |
+
with gr.Tabs():
|
| 439 |
+
with gr.TabItem("Audio File"):
|
| 440 |
+
file_input = gr.Audio(sources=["upload"], type="filepath", label="Upload Audio File")
|
| 441 |
+
gr.Examples(examples=examples, inputs=[file_input], label="Example Audio Files (Click to Load)")
|
| 442 |
+
file_transcribe_btn = gr.Button("Transcribe Uploaded File", variant="primary")
|
| 443 |
+
|
| 444 |
+
with gr.TabItem("Microphone"):
|
| 445 |
+
mic_input = gr.Audio(sources=["microphone"], type="filepath", label="Record Audio")
|
| 446 |
+
mic_transcribe_btn = gr.Button("Transcribe Microphone Input", variant="primary")
|
| 447 |
+
|
| 448 |
+
gr.Markdown("---")
|
| 449 |
+
gr.Markdown("<p><strong style='color: #FF0000; font-size: 1.2em;'>Transcription Results</strong></p>")
|
| 450 |
+
|
| 451 |
+
download_btn = gr.DownloadButton(label="Download Segment Transcript (CSV)", visible=False)
|
| 452 |
+
srt_btn = gr.DownloadButton(label="Download SRT", visible=False)
|
| 453 |
+
vtt_btn = gr.DownloadButton(label="Download VTT", visible=False)
|
| 454 |
+
json_btn = gr.DownloadButton(label="Download JSON", visible=False)
|
| 455 |
+
lrc_btn = gr.DownloadButton(label="Download LRC", visible=False)
|
| 456 |
+
|
| 457 |
+
with gr.Tabs():
|
| 458 |
+
with gr.TabItem("Segment View (Click row to play segment)"):
|
| 459 |
+
vis_timestamps_df = gr.DataFrame(
|
| 460 |
+
headers=["Start (s)", "End (s)", "Segment"],
|
| 461 |
+
datatype=["number", "number", "str"],
|
| 462 |
+
wrap=True,
|
| 463 |
+
)
|
| 464 |
+
selected_segment_player = gr.Audio(label="Selected Segment", interactive=False)
|
| 465 |
+
|
| 466 |
+
with gr.TabItem("Word View"):
|
| 467 |
+
word_vis_df = gr.DataFrame(
|
| 468 |
+
headers=["Start (s)", "End (s)", "Word"],
|
| 469 |
+
datatype=["number", "number", "str"],
|
| 470 |
+
wrap=False,
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
mic_transcribe_btn.click(
|
| 474 |
+
fn=get_transcripts_and_raw_times,
|
| 475 |
+
inputs=[mic_input, session_dir_state],
|
| 476 |
+
outputs=[vis_timestamps_df, raw_timestamps_list_state, word_vis_df, current_audio_path_state, download_btn, srt_btn, vtt_btn, json_btn, lrc_btn],
|
| 477 |
+
api_name="transcribe_mic"
|
| 478 |
+
)
|
| 479 |
+
|
| 480 |
+
file_transcribe_btn.click(
|
| 481 |
+
fn=get_transcripts_and_raw_times,
|
| 482 |
+
inputs=[file_input, session_dir_state],
|
| 483 |
+
outputs=[vis_timestamps_df, raw_timestamps_list_state, word_vis_df, current_audio_path_state, download_btn, srt_btn, vtt_btn, json_btn, lrc_btn],
|
| 484 |
+
api_name="transcribe_file"
|
| 485 |
+
)
|
| 486 |
+
|
| 487 |
+
vis_timestamps_df.select(
|
| 488 |
+
fn=play_segment,
|
| 489 |
+
inputs=[raw_timestamps_list_state, current_audio_path_state],
|
| 490 |
+
outputs=[selected_segment_player],
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
demo.unload(end_session)
|
| 494 |
+
|
| 495 |
+
if __name__ == "__main__":
|
| 496 |
+
print("Launching Gradio Demo...")
|
| 497 |
+
demo.queue()
|
| 498 |
+
demo.launch()
|
requirements.txt
CHANGED
|
@@ -1,4 +1,6 @@
|
|
| 1 |
Cython
|
| 2 |
git+https://github.com/NVIDIA/NeMo.git@main#egg=nemo_toolkit[asr]
|
| 3 |
numpy<2.0
|
| 4 |
-
pydub
|
|
|
|
|
|
|
|
|
| 1 |
Cython
|
| 2 |
git+https://github.com/NVIDIA/NeMo.git@main#egg=nemo_toolkit[asr]
|
| 3 |
numpy<2.0
|
| 4 |
+
pydub
|
| 5 |
+
gradio
|
| 6 |
+
spaces
|