Spaces:
Runtime error
Runtime error
Upload 6 files
Browse filesFiles changed (6)
- README.md+8-6
- app.pyAdded+147
- gitattributesAdded+34
- packages.txtAdded+1
- requirements.txtAdded+2
- whisper_notebook.ipynbAdded+192
12345234567789101112131214---title: Audio Textemoji: 🌍colorFrom: pinkcolorTo: greentitle: Whisper Turboemoji: 🤯colorFrom: indigocolorTo: redsdk: gradiosdk_version: 5.4.0sdk_version: 5.0.0app_file: app.pypinned: falsetags:- whisper-event---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-referenceCheck out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147import spacesimport torch
import gradio as grimport yt_dlp as youtube_dlfrom transformers import pipelinefrom transformers.pipelines.audio_utils import ffmpeg_read
import tempfileimport os
MODEL_NAME = "openai/whisper-large-v3-turbo"BATCH_SIZE = 8FILE_LIMIT_MB = 1000YT_LENGTH_LIMIT_S = 3600 # limit to 1 hour YouTube files
device = 0 if torch.cuda.is_available() else "cpu"
pipe = pipeline( task="automatic-speech-recognition", model=MODEL_NAME, chunk_length_s=30, device=device,)
@spaces.GPUdef transcribe(inputs, task): if inputs is None: raise gr.Error("No audio file submitted! Please upload or record an audio file before submitting your request.")
text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"] return text
def _return_yt_html_embed(yt_url): video_id = yt_url.split("?v=")[-1] HTML_str = ( f'<center> <iframe width="500" height="320" src="https://www.youtube.com/embed/{video_id}"> </iframe>' " </center>" ) return HTML_str
def download_yt_audio(yt_url, filename): info_loader = youtube_dl.YoutubeDL() try: info = info_loader.extract_info(yt_url, download=False) except youtube_dl.utils.DownloadError as err: raise gr.Error(str(err)) file_length = info["duration_string"] file_h_m_s = file_length.split(":") file_h_m_s = [int(sub_length) for sub_length in file_h_m_s] if len(file_h_m_s) == 1: file_h_m_s.insert(0, 0) if len(file_h_m_s) == 2: file_h_m_s.insert(0, 0) file_length_s = file_h_m_s[0] * 3600 + file_h_m_s[1] * 60 + file_h_m_s[2] if file_length_s > YT_LENGTH_LIMIT_S: yt_length_limit_hms = time.strftime("%HH:%MM:%SS", time.gmtime(YT_LENGTH_LIMIT_S)) file_length_hms = time.strftime("%HH:%MM:%SS", time.gmtime(file_length_s)) raise gr.Error(f"Maximum YouTube length is {yt_length_limit_hms}, got {file_length_hms} YouTube video.") ydl_opts = {"outtmpl": filename, "format": "worstvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"} with youtube_dl.YoutubeDL(ydl_opts) as ydl: try: ydl.download([yt_url]) except youtube_dl.utils.ExtractorError as err: raise gr.Error(str(err))
@spaces.GPUdef yt_transcribe(yt_url, task, max_filesize=75.0): html_embed_str = _return_yt_html_embed(yt_url)
with tempfile.TemporaryDirectory() as tmpdirname: filepath = os.path.join(tmpdirname, "video.mp4") download_yt_audio(yt_url, filepath) with open(filepath, "rb") as f: inputs = f.read()
inputs = ffmpeg_read(inputs, pipe.feature_extractor.sampling_rate) inputs = {"array": inputs, "sampling_rate": pipe.feature_extractor.sampling_rate}
text = pipe(inputs, batch_size=BATCH_SIZE, generate_kwargs={"task": task}, return_timestamps=True)["text"]
return html_embed_str, text
demo = gr.Blocks(theme=gr.themes.Ocean())
mf_transcribe = gr.Interface( fn=transcribe, inputs=[ gr.Audio(sources="microphone", type="filepath"), gr.Radio(["transcribe", "translate"], label="Task", value="transcribe"), ], outputs="text", title="Whisper Large V3 Turbo: Transcribe Audio", description=( "Transcribe long-form microphone or audio inputs with the click of a button! Demo uses the" f" checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe audio files" " of arbitrary length." ), allow_flagging="never",)
file_transcribe = gr.Interface( fn=transcribe, inputs=[ gr.Audio(sources="upload", type="filepath", label="Audio file"), gr.Radio(["transcribe", "translate"], label="Task", value="transcribe"), ], outputs="text", title="Whisper Large V3: Transcribe Audio", description=( "Transcribe long-form microphone or audio inputs with the click of a button! Demo uses the" f" checkpoint [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe audio files" " of arbitrary length." ), allow_flagging="never",)
yt_transcribe = gr.Interface( fn=yt_transcribe, inputs=[ gr.Textbox(lines=1, placeholder="Paste the URL to a YouTube video here", label="YouTube URL"), gr.Radio(["transcribe", "translate"], label="Task", value="transcribe") ], outputs=["html", "text"], title="Whisper Large V3: Transcribe YouTube", description=( "Transcribe long-form YouTube videos with the click of a button! Demo uses the checkpoint" f" [{MODEL_NAME}](https://huggingface.co/{MODEL_NAME}) and 🤗 Transformers to transcribe video files of" " arbitrary length." ), allow_flagging="never",)
with demo: gr.TabbedInterface([mf_transcribe, file_transcribe, yt_transcribe], ["Microphone", "Audio file", "YouTube"])
demo.queue().launch(ssr_mode=False)
12345678910111213141516171819202122232425262728293031323334*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text1ffmpeg12transformersyt-dlp123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "gpuType": "T4" }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" }, "accelerator": "GPU" }, "cells": [ { "cell_type": "markdown", "source": [ "# Whisper v3 is here!\n", "\n", "Whisper v3 is a new model open sourced by OpenAI. The model can do multilingual transcriptions and is quite impressive. For example, you can change from English to Spanish or Chinese in the middle of a sentence and it will work well!\n", "\n", "The model can be run in a free Google Colab instance and is integrated into `transformers` already, so switching can be a very smooth process if you already use the previous versions." ], "metadata": { "id": "OXaUqiE-eyXM" } }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "WFQeUT9EcIcK" }, "outputs": [], "source": [ "%%capture\n", "!pip install git+https://github.com/huggingface/transformers gradio" ] }, { "cell_type": "markdown", "source": [ "Let's use the high level `pipeline` from the `transformers` library to load the model." ], "metadata": { "id": "sZONes21fHTA" } }, { "cell_type": "code", "source": [ "import torch\n", "from transformers import pipeline\n", "\n", "pipe = pipeline(\"automatic-speech-recognition\",\n", " \"openai/whisper-large-v3\",\n", " torch_dtype=torch.float16,\n", " device=\"cuda:0\")" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "DvBdwMdPcr-Y", "outputId": "47f32218-fd85-49ea-d880-d31577bcf9b8" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stderr", "text": [ "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n", "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n" ] } ] }, { "cell_type": "code", "source": [ "pipe(\"https://cdn-media.huggingface.co/speech_samples/sample1.flac\")" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "GZFkIyhjc0Nc", "outputId": "f1463431-3e08-4438-815f-b71e5e7a1503" }, "execution_count": null, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "{'text': \" going along slushy country roads and speaking to damp audiences in draughty schoolrooms day after day for a fortnight he'll have to put in an appearance at some place of worship on sunday morning and he can come to us immediately afterwards\"}" ] }, "metadata": {}, "execution_count": 2 } ] }, { "cell_type": "markdown", "source": [ "Let's now build a quick Gradio demo where we can play with the model directly using our microphone! You can run this code in a Google Colab instance (or locally!) or just head to the <a href=\"https://huggingface.co/spaces/hf-audio/whisper-large-v3\" target=\"_blank\">Space</a> to play directly with it online." ], "metadata": { "id": "pt3YtM_PfTQY" } }, { "cell_type": "code", "source": [ "import gradio as gr\n", "\n", "def transcribe(inputs):\n", " if inputs is None:\n", " raise gr.Error(\"No audio file submitted! Please record an audio before submitting your request.\")\n", "\n", " text = pipe(inputs, generate_kwargs={\"task\": \"transcribe\"}, return_timestamps=True)[\"text\"]\n", " return text\n", "\n", "demo = gr.Interface(\n", " fn=transcribe,\n", " inputs=[\n", " gr.Audio(sources=[\"microphone\", \"upload\"], type=\"filepath\"),\n", " ],\n", " outputs=\"text\",\n", " title=\"Whisper Large V3: Transcribe Audio\",\n", " description=(\n", " \"Transcribe long-form microphone or audio inputs with the click of a button! Demo uses the\"\n", " \" checkpoint [openai/whisper-large-v3](https://huggingface.co/openai/whisper-large-v3) and 🤗 Transformers to transcribe audio files\"\n", " \" of arbitrary length.\"\n", " ),\n", " allow_flagging=\"never\",\n", ")\n", "\n", "demo.launch()\n" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 648 }, "id": "K0b2UZLVdIze", "outputId": "bcff00e0-4fc8-4883-9ba4-480f5a6665f0" }, "execution_count": null, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Setting queue=True in a Colab notebook requires sharing enabled. Setting `share=True` (you can turn this off by setting `share=False` in `launch()` explicitly).\n", "\n", "Colab notebook detected. To show errors in colab notebook, set debug=True in launch()\n", "Running on public URL: https://037dbdb04542aa1a29.gradio.live\n", "\n", "This share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from Terminal to deploy to Spaces (https://huggingface.co/spaces)\n" ] }, { "output_type": "display_data", "data": { "text/plain": [ "<IPython.core.display.HTML object>" ], "text/html": [ "<div><iframe src=\"https://037dbdb04542aa1a29.gradio.live\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>" ] }, "metadata": {} }, { "output_type": "execute_result", "data": { "text/plain": [] }, "metadata": {}, "execution_count": 4 } ] } ]}README.md+8-6
app.pyAdded+147
gitattributesAdded+34
packages.txtAdded+1
requirements.txtAdded+2
whisper_notebook.ipynbAdded+192