|
import torch |
|
import gradio as gr |
|
from pytube import YouTube |
|
from transformers import pipeline |
|
|
|
MODEL_NAME = "yuweiiizz/whisper-small-taiwanese" |
|
lang = "chinese" |
|
|
|
|
|
device = 0 if torch.cuda.is_available() else "cpu" |
|
|
|
|
|
pipe = pipeline( |
|
task="automatic-speech-recognition", |
|
chunk_length_s=15, |
|
model=MODEL_NAME, |
|
device=device, |
|
) |
|
|
|
|
|
pipe.model.config.forced_decoder_ids = pipe.tokenizer.get_decoder_prompt_ids(language=lang, task="transcribe") |
|
|
|
|
|
def transcribe(microphone=None, file_upload=None): |
|
warn_output = "" |
|
if microphone is not None and file_upload is not None: |
|
warn_output = "警告:您同時使用了麥克風與上傳音訊檔案,將只會使用麥克風錄製的檔案。\n" |
|
elif microphone is None and file_upload is None: |
|
return "錯誤:您必須至少使用麥克風或上傳一個音頻檔案。" |
|
|
|
file = microphone if microphone is not None else file_upload |
|
text = pipe(file)["text"] |
|
return warn_output + text |
|
|
|
|
|
def yt_transcribe(yt_url): |
|
yt = YouTube(yt_url) |
|
stream = yt.streams.filter(only_audio=True).first() |
|
stream.download(filename="audio.mp3") |
|
text = pipe("audio.mp3")["text"] |
|
|
|
video_id = yt_url.split("?v=")[-1] |
|
html_embed = f'<center><iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"></iframe></center>' |
|
|
|
return html_embed, text |
|
|
|
|
|
demo = gr.Blocks() |
|
|
|
|
|
mf_transcribe = gr.Interface( |
|
fn=transcribe, |
|
inputs=gr.Audio(label="audio",type="filepath"), |
|
outputs="text", |
|
title="Whisper 演示: 語音轉錄", |
|
description=f"演示使用 fine-tuned checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME} 以及 🤗 Transformers 轉錄任意長度的音訊檔案", |
|
allow_flagging="manual", |
|
) |
|
|
|
yt_transcribe = gr.Interface( |
|
fn=yt_transcribe, |
|
inputs=[gr.Textbox(lines=1, placeholder="在此處貼上 YouTube 影片的 URL", label="YouTube URL")], |
|
outputs=["html", "text"], |
|
title="Whisper 演示: Youtube轉錄", |
|
description=f"演示使用 fine-tuned checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME} 以及 🤗 Transformers 轉錄任意長度的Youtube影片", |
|
allow_flagging="manual", |
|
) |
|
|
|
|
|
with demo: |
|
gr.TabbedInterface([mf_transcribe, yt_transcribe], ["語音轉錄", "Youtube轉錄"]) |
|
|
|
|
|
demo.launch(share=True) |
|
|