From 971df53803c66c6053ef5019d2accea90b53fc55 Mon Sep 17 00:00:00 2001 From: Jacky chung Date: Tue, 28 Feb 2023 07:31:18 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BD=BF=E7=94=A8=20Colaboratory=20=E5=BB=BA?= =?UTF-8?q?=E7=AB=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...345\255\227\345\271\225\346\252\224.ipynb" | 392 ++++++++++++++++++ 1 file changed, 392 insertions(+) create mode 100644 "\345\275\261\347\211\207\350\275\211\345\255\227\345\271\225@OpenAI(Whisper)\350\252\236\351\237\263\350\276\250\350\255\230/\350\243\275\344\275\234\345\255\227\345\271\225\346\252\224.ipynb" diff --git "a/\345\275\261\347\211\207\350\275\211\345\255\227\345\271\225@OpenAI(Whisper)\350\252\236\351\237\263\350\276\250\350\255\230/\350\243\275\344\275\234\345\255\227\345\271\225\346\252\224.ipynb" "b/\345\275\261\347\211\207\350\275\211\345\255\227\345\271\225@OpenAI(Whisper)\350\252\236\351\237\263\350\276\250\350\255\230/\350\243\275\344\275\234\345\255\227\345\271\225\346\252\224.ipynb" new file mode 100644 index 00000000..3493f558 --- /dev/null +++ "b/\345\275\261\347\211\207\350\275\211\345\255\227\345\271\225@OpenAI(Whisper)\350\252\236\351\237\263\350\276\250\350\255\230/\350\243\275\344\275\234\345\255\227\345\271\225\346\252\224.ipynb" @@ -0,0 +1,392 @@ +{ + "nbformat": 4, + "nbformat_minor": 0, + "metadata": { + "colab": { + "provenance": [], + "include_colab_link": true + }, + "kernelspec": { + "name": "python3", + "display_name": "Python 3" + }, + "language_info": { + "name": "python" + } + }, + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "view-in-github", + "colab_type": "text" + }, + "source": [ + "\"Open" + ] + }, + { + "cell_type": "markdown", + "source": [ + "【註】這是顏國雄老師寫的程式,可以直接「聽」在 YouTube 上的影片,並把做好字幕檔。這是專為在 Colab 上執行設計的, 使用 `pytube` 下載在 YouTube 上的影片 (到 Colab 的臨時雲端碟), 再用 OpenAI 的 `Whisper` 做語音辨識。\n", + "\n", + "使用方法只需找到 YouTube 影片分享網址, 執行後 Colab 就開始工作, 完成後預設會自動下載字幕檔到你的電腦上!\n", + "\n", + "唯一要提醒的是, `Whisper` 自己會判斷是繁體還是簡體, 所以你有可能得到的是簡體版。不過相信這是小事, 很容易自己轉成繁體的。" + ], + "metadata": { + "id": "L15YQPLnC89h" + } + }, + { + "cell_type": "markdown", + "source": [ + "#OpenAI 的 Whisper 語音辨識測試\n", + "\n", + "OpenaAI 的 Whisper 是一個自動語音辨識系統,而且有開源,可以在底下的網址中找到:\n", + "* https://github.com/openai/whisper\n", + "\n", + "結合 Whisper 和 pytube 或其它類似 yt-dlp 的工具,就可以將 Youtube 上的影片或播放清單擷取聲音、儲存語音檔後,進行語音辨識,並生成字幕檔。\n", + "\n", + "目前在後面程式設定區塊中,語音來源路徑的「url」欄位中,可以填入 Youtube 的影片或影片清單網址;如果想馬上錄一段做測試,也可以利用線上錄音的網站 [Vocaroo](https://voca.roo/) (https://voca.roo/) 來錄音,再將它給的網址貼在「url」欄位中;如果是在電腦本機中的影片或聲音檔,則可以上載在左側資料夾中後,在「url」欄位中填入完整的檔名名稱。\n", + "\n", + "接著將其它選項都設定好後,就可以在[程式區塊]中按「執行」的按鈕,開始進行語音辨識了。\n", + "\n", + "Whisper 也可以辨識臺語,不過記得設定時,語言代碼「lang」的欄位要選「Chinese」比較保險,如果用「自動判斷」,有時會被當成非中文,而無法辨識出文字。\n", + "\n", + "程式第一次執行時,因為要安裝及下載自動語音辨識所需要的資料,可能要稍等一下下。\n", + "\n" + ], + "metadata": { + "id": "mbnPkLAOhQ2v" + } + }, + { + "cell_type": "code", + "source": [ + "#@title OpenAI Whisper 語音辨識並輸出字幕檔案程式 { vertical-output: true }\n", + "\n", + "#@markdown 設定底下的自訂參數後,就可以按左側的執行鈕\n", + "\n", + "#@markdown 聲音檔的來源,可以是網址(Youtube影片、撥放清單、 [Vocaroo](https://voca.roo/) 網址),或是上載後的影片、聲音檔檔案名稱。\n", + "url = \"https://voca.ro/15HVH0YvIaa6\" #@param {type:\"string\"}\n", + "#@markdown 語音的語言代碼\n", + "lang = 'Chinese' #@param [\"Chinese\", \"English\", \"Japanese\", \"Korean\", \"自動判斷\"]\n", + "#@markdown 輸出為哪一種格式(.srt:字幕檔、.txt:純文字檔)\n", + "outputFormat = 'srt' #@param ['srt', 'txt']\n", + "#@markdown 使用哪一種辨識模型(small:快/普通,medium:慢/精準)\n", + "modelType = 'small' #@param [\"small\" , \"medium\"]\n", + "#@markdown 是否全部辨識完成,立即下載字幕檔\n", + "start_downloading_immediately = True #@param { type: 'boolean' }\n", + "#@markdown 是否即時顯示語音辨識結果\n", + "verbose = False #@param { type: 'boolean' }\n", + "#@markdown ---\n", + "\n", + "\n", + "\n", + "# Install + Import + Config\n", + "try: import whisper\n", + "except:\n", + " print('install whisper ...')\n", + " ! pip -q install git+https://github.com/openai/whisper.git\n", + "\n", + "#try: import yt_dlp\n", + "#except:\n", + "# print('install ;yt-dlp ...')\n", + "# ! pip -q install yt-dlp\n", + "\n", + "try: from pytube import YouTube\n", + "except:\n", + " print('install pytube ...')\n", + " ! pip -q install pytube\n", + "\n", + "import torch\n", + "import whisper\n", + "from whisper.utils import get_writer\n", + "from pytube import YouTube\n", + "from pytube import Playlist\n", + "import re\n", + "import os.path\n", + "import urllib.request\n", + "from slugify import slugify\n", + "\n", + "import google\n", + "\n", + "#import yt_dlp\n", + "\n", + "#url = \"https://voca.ro/15HVH0YvIaa6\"\n", + "#url = 'https://www.youtube.com/watch?v=I4DZn4z8aRQ&list=PLelNvYGEtsV8TpwxL4t7GTTG-7qALZqol'\n", + "#url = 'https://www.youtube.com/watch?v=I4DZn4z8aRQ'\n", + "#url = 'vocaroo-台語.mp3'\n", + "\n", + "#lang = 'Chinese' # '自動判斷'\n", + "#start_downloading_immediately = True\n", + "\n", + "#modelType = 'small' # 'small' 'medium'\n", + "#outputFormat = 'txt' # 'srt' 'txt'\n", + "\n", + "audioFile = 'source.mp3'\n", + "output_path = '.'\n", + "title = ''\n", + "\n", + "# GPU or CPU\n", + "DEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", + "\n", + "def getAudioFromYoutube(url, output_path, filename) :\n", + " video = YouTube(url)\n", + " video.streams.get_audio_only().download(output_path, filename)\n", + " return video.title\n", + "\n", + "#Get the MP3 URL from Vocaroo record share URL\n", + "def getVocarooMP3URL(url) :\n", + " vocarooMP3Base = 'https://media.vocaroo.com/mp3/'\n", + " regex = re.compile(r'(https\\:\\/\\/voca\\.ro|https\\:\\/\\/vocaroo\\.com)\\/(\\w{12})')\n", + " match = regex.search(url)\n", + " if match :\n", + " url = vocarooMP3Base+match.group(2)\n", + " return url\n", + "\n", + "def transcribe(filename, output_path, outputFilename, outputFormat) :\n", + " # load whisper model and get transcribe result\n", + " model = whisper.load_model(modelType, device=DEVICE)\n", + " if lang==\"自動判斷\" :\n", + " print('auto detect language')\n", + " result = model.transcribe(filename, fp16=False, verbose=verbose) \n", + " else :\n", + " result = model.transcribe(filename, fp16=False, verbose=verbose, language=lang)\n", + " # save result to outputFormat file\n", + " saveToFile(result, output_path, outputFilename, outputFormat)\n", + "\n", + "# save whisper result to a file\n", + "def saveToFile(result, output_path, filename, fileType='srt') :\n", + " # save SRT\n", + " file_writer = get_writer(fileType, output_path)\n", + " file_writer(result, filename)\n", + "\n", + "\n", + "# 建立 Playlist 物件\n", + "pList = Playlist(url)\n", + "\n", + "isPlayList = True\n", + "try : title = pList.title\n", + "except :\n", + " isPlayList = False\n", + "\n", + "if isPlayList :\n", + " for video in pList.videos :\n", + " title = video.title\n", + " #filename = title+'.mp3'\n", + " filename = audioFile\n", + " \n", + " print(title)\n", + "\n", + " #convert title to valid filename\n", + " outputFilename = slugify(title, allow_unicode=True, lowercase=False)\n", + " \n", + " #continue\n", + "\n", + " #download audio from video stream\n", + " video.streams.get_audio_only().download(output_path, filename)\n", + "\n", + " # load whisper model and get transcribe result\n", + " transcribe(filename, output_path, outputFilename, outputFormat)\n", + "else :\n", + " filename = audioFile\n", + " if re.search('https\\:\\/\\/', url) :\n", + " if re.search('youtube\\.|youtu\\.', url) :\n", + " # Youtube video\n", + " title = getAudioFromYoutube(url, output_path, audioFile) \n", + " elif re.search('voca\\.ro|vocaroo\\.com', url) :\n", + " # Vocaroo or other web audio\n", + " url = getVocarooMP3URL(url)\n", + " urllib.request.urlretrieve(url, audioFile)\n", + " title = 'vocaroo'\n", + " else :\n", + " # other website\n", + " ! rm {audioFile}\n", + " #! yt-dlp -q --force-overwrites -x --audio-format mp3 -o {audioFile} {url}\n", + " else :\n", + " # local audio file\n", + " title = url\n", + " filename = url\n", + "\n", + " print(title)\n", + " #convert title to valid filename\n", + " outputFilename = slugify(title, allow_unicode=True, lowercase=False)\n", + " \n", + " # load whisper model and get transcribe result\n", + " if os.path.exists(filename) :\n", + " transcribe(filename, output_path, outputFilename, outputFormat)\n", + " else :\n", + " print('找不到語音檔: '+filename)\n", + " start_downloading_immediately = False\n", + "\n", + "if start_downloading_immediately:\n", + " if isPlayList :\n", + " print('\\n壓縮並下載辨識結果')\n", + " title = pList.title\n", + " outputFilename = slugify(title, allow_unicode=True, lowercase=False)+'-'+outputFormat+'.zip'\n", + " #先將所有字幕檔的換行符號由 \\n 換成 \\r\\n,全部壓縮\n", + " ! zip -l {outputFilename} *.{outputFormat}\n", + " else :\n", + " print('\\n下載辨識結果')\n", + " outputFilename = outputFilename+'.'+outputFormat\n", + " #下載辨識結果\n", + " google.colab.files.download(outputFilename)\n", + "\n" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 104 + }, + "cellView": "form", + "id": "-U10L-FaUDPA", + "outputId": "1bf05c7d-d464-4665-a8c8-996cac0f0699" + }, + "execution_count": null, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "vocaroo\n" + ] + }, + { + "output_type": "stream", + "name": "stderr", + "text": [ + "100%|███████████████████████████████████████| 461M/461M [00:08<00:00, 55.2MiB/s]\n", + "100%|██████████| 4051/4051 [01:08<00:00, 59.35frames/s]" + ] + }, + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\n", + "下載辨識結果\n" + ] + }, + { + "output_type": "stream", + "name": "stderr", + "text": [ + "\n" + ] + }, + { + "output_type": "display_data", + "data": { + "text/plain": [ + "" + ], + "application/javascript": [ + "\n", + " async function download(id, filename, size) {\n", + " if (!google.colab.kernel.accessAllowed) {\n", + " return;\n", + " }\n", + " const div = document.createElement('div');\n", + " const label = document.createElement('label');\n", + " label.textContent = `Downloading \"${filename}\": `;\n", + " div.appendChild(label);\n", + " const progress = document.createElement('progress');\n", + " progress.max = size;\n", + " div.appendChild(progress);\n", + " document.body.appendChild(div);\n", + "\n", + " const buffers = [];\n", + " let downloaded = 0;\n", + "\n", + " const channel = await google.colab.kernel.comms.open(id);\n", + " // Send a message to notify the kernel that we're ready.\n", + " channel.send({})\n", + "\n", + " for await (const message of channel.messages) {\n", + " // Send a message to notify the kernel that we're ready.\n", + " channel.send({})\n", + " if (message.buffers) {\n", + " for (const buffer of message.buffers) {\n", + " buffers.push(buffer);\n", + " downloaded += buffer.byteLength;\n", + " progress.value = downloaded;\n", + " }\n", + " }\n", + " }\n", + " const blob = new Blob(buffers, {type: 'application/binary'});\n", + " const a = document.createElement('a');\n", + " a.href = window.URL.createObjectURL(blob);\n", + " a.download = filename;\n", + " div.appendChild(a);\n", + " a.click();\n", + " div.remove();\n", + " }\n", + " " + ] + }, + "metadata": {} + }, + { + "output_type": "display_data", + "data": { + "text/plain": [ + "" + ], + "application/javascript": [ + "download(\"download_e74a26a5-3033-44e7-8abc-c201c9749194\", \"vocaroo.srt\", 660)" + ] + }, + "metadata": {} + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "# 辨識結果比較\n", + "\n", + "以同一個音檔\n", + "* https://voca.ro/15HVH0YvIaa6\n", + "\n", + "用不同模型來進行辨識的結果\n", + "##Model small\n", + "
\n",
+        "[00:00.000 --> 00:02.500] 大家午安\n",
+        "[00:02.500 --> 00:07.500] 科技的進步實在讓人很驚訝\n",
+        "[00:07.500 --> 00:13.000] 我們現在不怕利用廣的賣力\n",
+        "[00:13.000 --> 00:16.000] 我們說台語\n",
+        "[00:16.000 --> 00:19.000] 電腦跟我們說的台語就變異\n",
+        "[00:19.000 --> 00:23.000] 連鍵盤都不變硬\n",
+        "[00:23.000 --> 00:26.000] 現在我們來砌這個\n",
+        "[00:26.000 --> 00:28.500] OpenAI的Whisper\n",
+        "[00:28.500 --> 00:33.500] 也是跟我們說的微變異\n",
+        "[00:33.500 --> 00:36.500] 好,我們現在就來試試看\n",
+        "[00:36.500 --> 00:58.500] 看它到底有多厲害\n",
+        "
\n", + "\n", + "##Model medium\n", + "
\n",
+        "[00:00.000 --> 00:03.000] 大家午安\n",
+        "[00:03.000 --> 00:08.000] 科技的進步實在讓人很驚險\n",
+        "[00:08.000 --> 00:11.000] 我們現在不用打字\n",
+        "[00:11.000 --> 00:14.000] 用講的也可以\n",
+        "[00:14.000 --> 00:16.000] 我們講台語\n",
+        "[00:16.000 --> 00:20.000] 電腦跟我們講的台語就變字\n",
+        "[00:20.000 --> 00:24.000] 連鍵盤都不用用\n",
+        "[00:24.000 --> 00:26.000] 現在我們來試這個\n",
+        "[00:26.000 --> 00:29.000] OpenAI的Whisper\n",
+        "[00:29.000 --> 00:33.000] 它可以跟我們講的話變字\n",
+        "[00:33.000 --> 00:37.000] 好,我們現在就來試看看\n",
+        "[00:37.000 --> 01:03.000] 看它到底多厲害\n",
+        "
\n", + "\n", + "基本上,精準度是用空間與時間換來的。" + ], + "metadata": { + "id": "kelIURvOPEQh" + } + } + ] +} \ No newline at end of file