聞其聲而知雅意,基于Pytorch(mps/cpu/cuda)的人工智能AI本地語音識別庫Whisper(Python3.10)

前文回溯,之前一篇:含辭未吐,聲若幽蘭,史上最強(qiáng)免費人工智能AI語音合成TTS服務(wù)微軟Azure(Python3.10接入),利用AI技術(shù)將文本合成語音,現(xiàn)在反過來,利用開源庫Whisper再將語音轉(zhuǎn)回文字,所謂聞其聲而知雅意。

Whisper 是一個開源的語音識別庫,它是由Facebook AI Research (FAIR)開發(fā)的,支持多種語言的語音識別。它使用了雙向循環(huán)神經(jīng)網(wǎng)絡(luò)(bi-directional RNNs)來識別語音并將其轉(zhuǎn)換為文本。 Whisper支持自定義模型,可以用于實現(xiàn)在線語音識別,并且具有高級的語音識別功能,支持語音識別中的語音活動檢測和語音識別中的語音轉(zhuǎn)文本。它是使用PyTorch進(jìn)行開發(fā),可以使用Python API來調(diào)用語音識別,并且提供了一系列的預(yù)訓(xùn)練模型和數(shù)據(jù)集來幫助用戶開始使用。

PyTorch基于MPS的安裝

我們知道PyTorch一直以來在M芯片的MacOs系統(tǒng)中都不支持cuda模式,而現(xiàn)在,新的MPS后端擴(kuò)展了PyTorch生態(tài)系統(tǒng)并提供了現(xiàn)有的腳本功能來在 GPU上設(shè)置和運行操作。

截止本文發(fā)布,PyTorch與Python 3.11不兼容,所以我們將使用最新的 3.10.x 版本。

確保安裝Python3.10最新版:

?  transformers git:(stable) python3  
Python 3.10.9 (main, Dec 15 2022, 17:11:09) [Clang 14.0.0 (clang-1400.0.29.202)] on darwin  
Type "help", "copyright", "credits" or "license" for more information.  
>>>

隨后運行安裝命令:

pip3 install --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cpu

安裝成功后,在終端里驗證PyTorch-MPS的狀態(tài):

?  transformers git:(stable) python3  
Python 3.10.9 (main, Dec 15 2022, 17:11:09) [Clang 14.0.0 (clang-1400.0.29.202)] on darwin  
Type "help", "copyright", "credits" or "license" for more information.  
>>> import torch  
>>> torch.backends.mps.is_available()  
True  
>>>

返回True即可。

PyTorch MPS (Multi-Process Service)性能測試

PyTorch MPS (Multi-Process Service)是 PyTorch 中的一種分布式訓(xùn)練方式。它是基于Apple的MPS(Metal Performance Shaders) 框架開發(fā)的。MPS可以在多核的蘋果設(shè)備上加速tensor的運算。MPS使用了多個設(shè)備上的多個核心來加速模型的訓(xùn)練。它可以將模型的計算過程分配到多個核心上,并且可以在多個設(shè)備上進(jìn)行訓(xùn)練,從而提高訓(xùn)練速度。

PyTorch MPS 可以在 Apple 的設(shè)備(如 iPhone 和 iPad)上加速模型訓(xùn)練,也可以在 Mac 上使用。可以使用MPS來加速卷積神經(jīng)網(wǎng)絡(luò)(CNNs)、循環(huán)神經(jīng)網(wǎng)絡(luò)(RNNs)和其他類型的神經(jīng)網(wǎng)絡(luò)。使用MPS可以在不改變模型結(jié)構(gòu)的情況下,通過分布式訓(xùn)練來加速模型的訓(xùn)練速度。

現(xiàn)在我們來做一個簡單測試:

import torch  
import timeit  
import random  
  
x = torch.ones(50000000,device='cpu')  
print(timeit.timeit(lambda:x*random.randint(0,100),number=1))

首先創(chuàng)建一個大小為 50000000 的全為1的張量 x,并將其設(shè)置為在cpu上運算。最后使用 timeit.timeit 函數(shù)來測量在 CPU 上執(zhí)行 x 乘以一個隨機(jī)整數(shù)的時間。 number=1表示只運行一次。這段代碼的作用是在cpu上測量運算一個張量的時間。

運行結(jié)果:

?  nlp_chinese /opt/homebrew/bin/python3.10 "/Users/liuyue/wodfan/work/nlp_chinese/mps_test.py"  
0.020812375005334616

在10核M1pro的cpu芯片加持下,運行時間為:0.020812375005334616

隨后換成MPS模式:

import torch  
import timeit  
import random  
  
x = torch.ones(50000000,device='mps')  
print(timeit.timeit(lambda:x*random.randint(0,100),number=1))

程序返回:

?  nlp_chinese /opt/homebrew/bin/python3.10 "/Users/liuyue/wodfan/work/nlp_chinese/mps_test.py"  
0.003058041911572218

16核的GPU僅用時:0.003058041911572218

也就是說MPS的運行速度比CPU提升了7倍左右。

Whisper語音識別

安裝好了PyTorch,我們安裝Whisper:

pip install --upgrade --no-deps --force-reinstall git+https://github.com/openai/whisper.git

安裝好之后進(jìn)行驗證:

?  transformers git:(stable) whisper     
usage: whisper [-h] [--model {tiny.en,tiny,base.en,base,small.en,small,medium.en,medium,large}] [--model_dir MODEL_DIR]  
               [--device DEVICE] [--output_dir OUTPUT_DIR] [--verbose VERBOSE] [--task {transcribe,translate}]  
               [--language {af,am,ar,as,az,ba,be,bg,bn,bo,br,bs,ca,cs,cy,da,de,el,en,es,et,eu,fa,fi,fo,fr,gl,gu,ha,haw,hi,hr,ht,hu,hy,id,is,it,iw,ja,jw,ka,kk,km,kn,ko,la,lb,ln,lo,lt,lv,mg,mi,mk,ml,mn,mr,ms,mt,my,ne,nl,nn,no,oc,pa,pl,ps,pt,ro,ru,sa,sd,si,sk,sl,sn,so,sq,sr,su,sv,sw,ta,te,tg,th,tk,tl,tr,tt,uk,ur,uz,vi,yi,yo,zh,Afrikaans,Albanian,Amharic,Arabic,Armenian,Assamese,Azerbaijani,Bashkir,Basque,Belarusian,Bengali,Bosnian,Breton,Bulgarian,Burmese,Castilian,Catalan,Chinese,Croatian,Czech,Danish,Dutch,English,Estonian,Faroese,Finnish,Flemish,French,Galician,Georgian,German,Greek,Gujarati,Haitian,Haitian Creole,Hausa,Hawaiian,Hebrew,Hindi,Hungarian,Icelandic,Indonesian,Italian,Japanese,Javanese,Kannada,Kazakh,Khmer,Korean,Lao,Latin,Latvian,Letzeburgesch,Lingala,Lithuanian,Luxembourgish,Macedonian,Malagasy,Malay,Malayalam,Maltese,Maori,Marathi,Moldavian,Moldovan,Mongolian,Myanmar,Nepali,Norwegian,Nynorsk,Occitan,Panjabi,Pashto,Persian,Polish,Portuguese,Punjabi,Pushto,Romanian,Russian,Sanskrit,Serbian,Shona,Sindhi,Sinhala,Sinhalese,Slovak,Slovenian,Somali,Spanish,Sundanese,Swahili,Swedish,Tagalog,Tajik,Tamil,Tatar,Telugu,Thai,Tibetan,Turkish,Turkmen,Ukrainian,Urdu,Uzbek,Valencian,Vietnamese,Welsh,Yiddish,Yoruba}]

隨后安裝ffmpeg:

brew install ffmpeg

然后編寫語音識別代碼:

import whisper  
  
model = whisper.load_model("small")  
  
# load audio and pad/trim it to fit 30 seconds  
audio = whisper.load_audio("/Users/liuyue/wodfan/work/mydemo/b1.wav")  
audio = whisper.pad_or_trim(audio)  
  
# make log-Mel spectrogram and move to the same device as the model  
  
mel = whisper.log_mel_spectrogram(audio).to("cpu")  
  
# detect the spoken language  
_, probs = model.detect_language(mel)  
print(f"Detected language: {max(probs, key=probs.get)}")  
  
# decode the audio  
options = whisper.DecodingOptions(fp16 = False)  
result = whisper.decode(model, mel, options)  
  
# print the recognized text  
print(result.text)

這里導(dǎo)入音頻后,通過whisper.log_mel_spectrogram方法自動檢測語言,然后輸出文本:

?  minGPT git:(master) ? /opt/homebrew/bin/python3.10 "/Users/liuyue/wodfan/work/minGPT/wisper_test.py"  
Detected language: zh  
Hello大家好,這里是劉悅的技術(shù)博客,眾神殿內(nèi),高朋滿座,圣有如云,VMware,Virtual Box,UPM等虛擬機(jī)大神群英匯翠,指見位于C位王座上的Parallels唱網(wǎng)抬頭,緩緩群尋,屁膩群小,目光到處,無人敢抬頭對視。是的,如果說虛擬機(jī)領(lǐng)域有一位王者,非Parallels不能領(lǐng)袖群倫,畢竟大廠背書,功能滿格,美中不足之處就是價格略高,

這里使用的small模型,也可以用更大的模型比如:medium、large。模型越大,效果越好。

如果想使用MPS的方式,需要改寫一下Whisper源碼,將load_model方法的參數(shù)改為mps即可:

def load_model(name: str, device: Optional[Union[str, torch.device]] = None, download_root: str = None, in_memory: bool = False) -> Whisper:  
    """  
    Load a Whisper ASR model  
  
    Parameters  
    ----------  
    name : str  
        one of the official model names listed by `whisper.available_models()`, or  
        path to a model checkpoint containing the model dimensions and the model state_dict.  
    device : Union[str, torch.device]  
        the PyTorch device to put the model into  
    download_root: str  
        path to download the model files; by default, it uses "~/.cache/whisper"  
    in_memory: bool  
        whether to preload the model weights into host memory  
  
    Returns  
    -------  
    model : Whisper  
        The Whisper ASR model instance  
    """  
  
    if device is None:  
        device = "cuda" if torch.cuda.is_available() else "mps"

代碼在第18行。

隨后運行腳本也改成mps:

import whisper  
  
model = whisper.load_model("medium")  
  
# load audio and pad/trim it to fit 30 seconds  
audio = whisper.load_audio("/Users/liuyue/wodfan/work/mydemo/b1.wav")  
audio = whisper.pad_or_trim(audio)  
  
# make log-Mel spectrogram and move to the same device as the model  
  
mel = whisper.log_mel_spectrogram(audio).to("mps")  
  
# detect the spoken language  
_, probs = model.detect_language(mel)  
print(f"Detected language: {max(probs, key=probs.get)}")  
  
# decode the audio  
options = whisper.DecodingOptions(fp16 = False)  
result = whisper.decode(model, mel, options)  
  
# print the recognized text  
print(result.text)

這回切換為medium模型,程序返回:

?  minGPT git:(master) ? /opt/homebrew/bin/python3.10 "/Users/liuyue/wodfan/work/minGPT/wisper_test.py"  
100%|█████████████████████████████████████| 1.42G/1.42G [02:34<00:00, 9.90MiB/s]  
Detected language: zh  
Hello 大家好,這里是劉悅的技術(shù)博客,眾神殿內(nèi),高朋滿座,圣有如云,VMware,Virtualbox,UTM等虛擬機(jī)大神群音惠翠,只見位于C位王座上的Parallels唱往抬頭,緩緩輕尋,屁逆群小,目光到處,無人敢抬頭對視。

效率和精準(zhǔn)度提升了不少,但medium模型的體積也更大,達(dá)到了1.42g。

結(jié)語

Whisper作為一個開源的語音識別庫,支持多種語言,并且使用雙向循環(huán)神經(jīng)網(wǎng)絡(luò)(bi-directional RNNs)來識別語音并將其轉(zhuǎn)換為文本,支持自定義模型,可以用于實現(xiàn)在線語音識別,并且具有高級的語音識別功能,支持語音識別中的語音活動檢測和語音識別中的語音轉(zhuǎn)文本,在PyTorch的MPS加成下,更是猛虎添翼,絕世好庫,值得擁有。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,406評論 6 538
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,034評論 3 423
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,413評論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,449評論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 72,165評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,559評論 1 325
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,606評論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,781評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,327評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 41,084評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,278評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,849評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,495評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,927評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,172評論 1 291
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,010評論 3 396
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 48,241評論 2 375

推薦閱讀更多精彩內(nèi)容