DEV Community

Cover image for 免費開源的語音辨識功能:Google Colab + Faster Whisper
Let's Write
Let's Write

Posted on • Edited on • Originally published at letswrite.tw

免費開源的語音辨識功能:Google Colab + Faster Whisper

本篇要解決的問題

上一篇,我們用了 Google Colab,加上 OpenAI 的 Whisper,製作出了一個語音辨識功能,結果筆記文寫完沒過幾天,就看到有人改良了 Whisper,製作出了 Faster Whisper,辨識速度更快也更精準。

一開始研究時,因為是改到 Google Colab,所以跟著官方說明文件一直失敗,後來是爬了一下文後才找到解法。

確實,Faster Whisper 真的更快更準,測試了一個 70 分鐘的音檔,原本 OpenAI Whisper 要 14 分鐘,換用 Faster Whisper 後,只需要 7 分鐘。

不得不說,現在語音辨識模型已經到這程度,到年底時不知道又會有什麼樣子的進步。

Google Colab 的使用方式,在前一篇幾乎都寫到了,本篇不會再重寫,請先閱讀上一篇筆記文囉:

免費開源的語音辨識功能:Google Colab + Whisper large v3


安裝 Faster Whisper

官方說明文件:GitHub

文件一開始有說,要使用 GPU,要先安裝 NVIDIA 函式庫,一開始就是卡在這邊卡很久,因為找不到 Colab 的安裝方式。

後來爬了一下文後,才找到只要安裝「libcublas11」就可以了。

安裝 Faster Whisper 的程式碼如下:

!apt-get install -y libcublas11
!pip install ctranslate2==4.4.0
!pip install numpy==1.24.0
Enter fullscreen mode Exit fullscreen mode

複製貼上程式碼,點擊執行後就會進行安裝。

第一次執行時,會出現「要重啟工作階段」的提示,請按下重啟後,再重新執行一次程式碼,因為套件版本有不同,所以需要重啟一次。


使用 Faster Whisper

這篇來點跟前一篇不一樣的,因為官方提供的 Demo,產出的內容會加上時間軸,所以這邊 August 也試著做出三種格:一般、時間軸、字幕檔。

完整程式碼如下,可以直接貼上 Colab:

!apt-get install -y libcublas11
!pip install ctranslate2==4.4.0
!pip install numpy==1.24.0
!pip install faster-whisper ipywidgets

from google.colab import drive
from ipywidgets import widgets, VBox, Dropdown
from IPython.display import display, clear_output
from faster_whisper import WhisperModel
import os

# 掛載 Google Drive
drive.mount('/content/drive')

# 初始化 WhisperModel
model_size = "large-v2"  # 可以根據需求調整模型大小:tiny, base, small, medium, large, large-v2, large-v3
model = WhisperModel(model_size, device="cuda", compute_type="float16")

def transcribe(audio_path, mode):
    transcription = ""
    with output:
        clear_output()
        print("正在進行語音辨識,請稍候...")
        segments, info = model.transcribe(audio_path, beam_size=5, initial_prompt="繁體")

        if mode == "normal":
            transcription_segments = [segment.text for segment in segments]
            transcription = "".join(transcription_segments)
        elif mode == "timeline":
            for segment in segments:
                transcription += "[%.2fs -> %.2fs] %s\n" % (segment.start, segment.end, segment.text)
        elif mode == "subtitle":
          for i, segment in enumerate(segments, 1):
              start_hours, start_remainder = divmod(segment.start, 3600)
              start_minutes, start_seconds = divmod(start_remainder, 60)
              start_milliseconds = (segment.start - int(segment.start)) * 1000
              end_hours, end_remainder = divmod(segment.end, 3600)
              end_minutes, end_seconds = divmod(end_remainder, 60)
              end_milliseconds = (segment.end - int(segment.end)) * 1000
              transcription += "%d\n%02d:%02d:%02d,%03d --> %02d:%02d:%02d,%03d\n%s\n\n" % (
                  i,
                  start_hours, start_minutes, int(start_seconds), start_milliseconds,
                  end_hours, end_minutes, int(end_seconds), end_milliseconds,
                  segment.text
              )

        print("辨識完成!結果如下:")
        print(transcription)

        file_name = os.path.splitext(os.path.basename(audio_path))[0]
        with open(f"{file_name}_transcription.txt", "w") as file:
            file.write(transcription)
        print(f"辨識結果已保存為 {file_name}_transcription.txt")

        try:
            from google.colab import files
            files.download(f"{file_name}_transcription.txt")
        except ImportError:
            print("自動下載功能只在 Colab 環境中有效。")

mode_selector = Dropdown(
    options=[('一般版本', 'normal'), ('加入時間軸版本', 'timeline'), ('產生字幕檔的版本', 'subtitle')],
    value='normal',
    description='模式:',
)

file_path_input = widgets.Text(
    value='',
    placeholder='請輸入檔案路徑',
    description='檔案路徑:',
    disabled=False
)
transcribe_button = widgets.Button(
    description='進行語音辨識',
    disabled=False,
    button_style='info',
    tooltip='Click me',
    icon='check'
)
output = widgets.Output()

def on_transcribe_button_clicked(b):
    audio_path = file_path_input.value
    mode = mode_selector.value
    if os.path.exists(audio_path):
        transcribe(audio_path, mode)
    else:
        with output:
            clear_output()
            print("指定的檔案路徑不存在,請檢查!")

transcribe_button.on_click(on_transcribe_button_clicked)

clear_output()

ui = VBox([file_path_input, mode_selector, transcribe_button, output])
display(ui)
Enter fullscreen mode Exit fullscreen mode

貼上後,要修改的部份有:model_size。

意思是想要用哪種 model 來進行辨識。

目前 OpenAI 提供的 Whisper API 是 Large-V2,也確實 V2 就很好用了。

如果改用最新的 Large-V3,辨識時間會再久一點。

執行完後,頁面最下方會出現一個 UI,如下:

執行完出現的 UI

檔案路徑,要填的是 Colab 左側雲端硬碟中,音檔的路徑。

模式可以選擇最後要輸出的格式。


結論

這篇算是上一篇的…外傳?就是一個補充寫法。

網路上如果搜尋一下 Google Golab Faster Whisper,就還蠻多人有做出厲害的範例。

這篇就分享給需要的棒油囉~

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more