很多人學習python,不知道從何學起。
很多人學習python,掌握了基本語法過後,不知道在哪裡尋找案例上手。
很多已經做案例的人,卻不知道如何去學習更加高深的知識。
那麼針對這三類人,我給大家提供一個好的學習平臺,免費領取視頻教程,電子書籍,以及課程的原始碼!??¤
QQ群:961562169
有了它,實現實時翻譯還遠嗎?一、還有3秒到達戰場最近,某水果手機廠在萬眾期待中開了一場沒有發布萬眾期待的手機產品的發布會,發布了除手機外的其他一些產品,也包括最新的水果14系統。幾天後,更新了系統的吃瓜群眾經過把玩突然發現新系統裡一個超有意思的功能——翻譯
奇怪的翻譯知識增加了!
相比常見的翻譯工具,同聲翻譯工具更具有實用價值,想想不精通其他語言就能和歪果朋友無障礙交流的場景,真是一件美事,不如自己動手實現個工具備用!一個同聲翻譯工具,邏輯大概可以是先識別,而後翻譯,翻譯能否成功,識別的準確率是個關鍵因素。為了降低難度,我決定分兩次完成工具開發。首先來實現試試語音識別的部分。
輕車熟路,本次的demo繼續調用有道智雲API,實現實時語音識別。
二、效果展示先看看界面和結果哈:
可以選擇多種語音,這裡只寫了四種常見的:
我分別測試的中文、韓文、英文。看著還不錯哦~
這裡翻譯結果,是根據音頻一個字、一個字這樣實時識別的,由於識別速度比較快,所以看起來木有時間差。
四、調用API接口的準備工作首先,是需要在有道智雲的個人頁面上創建實例、創建應用、綁定應用和實例,獲取調用接口用到的應用的id和密鑰。具體個人註冊的過程和應用創建過程詳見文章分享一次批量文件翻譯的開發過程
五、開發過程詳細介紹(一)準備工作下面介紹具體的代碼開發過程。
首先是根據實時語音識別文檔來分析接口的輸入輸出。接口設計的目的是對連續音頻流的實時識別,轉換成文本信息並返對應文字流,因此通信採用websocket,調用過程分為認證、實時通信兩階段。
在認證階段,需發送以下參數:
參數類型必填說明示例appKeyString是已申請的應用IDIDsaltString是UUIDUUIDcurtimeString是時間戳(秒)TimeStampsignString是加密數字籤名。sha256signTypeString是數字籤名類型v4langTypeString是語言選擇,參考支持語言列表zh-CHSformatString是音頻格式,支持wavwavchannelString是聲道,支持1(單聲道)1versionString是api版本v1rateString是採樣率16000
籤名sign生成方法如下:
signType=v4;
sign=sha256(應用ID+salt+curtime+應用密鑰)。
認證之後,就進入了實時通信階段,發送音頻流,獲取識別結果,最後發送結束標誌結束通信,這裡需要注意的是,發送的音頻最好是16bit位深的單聲道、16k採樣率的清晰的wav音頻文件,這裡我開發時最開始因為音頻錄製設備有問題,導致音頻效果極差,接口一直返回錯誤碼304(手動捂臉)。
(二)開發這個demo使用python3開發,包括maindow.py,audioandprocess.py,recobynetease.py三個文件。界面部分,使用python自帶的tkinter庫,來進行語言選擇、錄音開始、錄音停止並識別的操作。audioandprocess.py實現了錄音、音頻處理的邏輯,最後通過recobynetease.py中的方法來調用實時語音識別API。
1、界面部分主要元素:
root=tk.Tk()
root.title("netease youdao translation test")
frm = tk.Frame(root)
frm.grid(padx='80', pady='80')
label=tk.Label(frm,text='選擇語言類型:')
label.grid(row=0,column=0)
combox=ttk.Combobox(frm,textvariable=tk.StringVar(),width=38)
combox["value"]=lang_type_dict
combox.current(0)
combox.bind("<<ComboboxSelected>>",get_lang_type)
combox.grid(row=0,column=1)
btn_start_rec = tk.Button(frm, text='開始錄音', command=start_rec)
btn_start_rec.grid(row=2, column=0)
lb_Status = tk.Label(frm, text='Ready', anchor='w', fg='green')
lb_Status.grid(row=2,column=1)
btn_sure=tk.Button(frm,text="結束並識別",command=get_result)
btn_sure.grid(row=3,column=0)
root.mainloop()
選擇語言類型之後,開始錄音,錄音結束後,通過get_result()方法調用接口進行識別。
def get_result():
lb_Status['text']='Ready'
sr_result=au_model.stop_and_recognise()
音頻錄製部分引入pyaudio庫(需通過pip安裝)來調用音頻設備並錄製接口要求的wav文件,並調用wave庫存儲音頻文件。
Audio_model類的構造:
def __init__(self, audio_path, language_type,is_recording):
self.audio_path = audio_path, # 錄音存儲路徑
self.audio_file_name='' # 錄音文件名
self.language_type = language_type, # 錄音語言類型
self.language_dict=["zh-CHS","en","ja","ko"] # 支持的語言,用於從UI出的類型轉為接口所需類型
self.language=''
self.is_recording=is_recording # 錄音狀態
self.audio_chunk_size=1600 # 以下為一些接口所要求的錄音參數,採樣率、編碼、通道等
self.audio_channels=1
self.audio_format=pyaudio.paInt16
self.audio_rate=16000
record()方法中實現了錄音的邏輯,調用pyaudio庫,讀取音頻流,寫入文件。
def record(self,file_name):
p=pyaudio.PyAudio()
stream=p.open(
format=self.audio_format,
channels=self.audio_channels,
rate=self.audio_rate,
input=True,
frames_per_buffer=self.audio_chunk_size
)
wf = wave.open(file_name, 'wb')
wf.setnchannels(self.audio_channels)
wf.setsampwidth(p.get_sample_size(self.audio_format))
wf.setframerate(self.audio_rate)
# 讀取數據寫入文件
while self.is_recording:
data = stream.read(self.audio_chunk_size)
wf.writeframes(data)
wf.close()
stream.stop_stream()
stream.close()
p.terminate()
stop_and_recognise()方法將Audio_model的錄音狀態標記為false,並啟動調用有道智雲API的方法。
def stop_and_recognise(self):
self.is_recording=False
recognise(self.audio_file_name,self.language_dict[self.language_type])
有道智雲實時語音識別接口使用socket通信,為簡化展示邏輯,因此在此處發開了展示識別結果的界面,使用tkinter顯示:
#輸出結果的窗口
root = tk.Tk()
root.title("result")
frm = tk.Frame(root)
frm.grid(padx='80', pady='80')
text_result = tk.Text(frm, width='40', height='20')
text_result.grid(row=0, column=1)
recognise()方法根據接口文檔,將所需參數拼接到uri,傳給start()方法請求接口:
def recognise(filepath,language_type):
print('l:'+language_type)
global file_path
file_path=filepath
nonce = str(uuid.uuid1())
curtime = str(int(time.time()))
signStr = app_key + nonce + curtime + app_secret
print(signStr)
sign = encrypt(signStr)
uri = "wss://openapi.youdao.com/stream_asropenapi?appKey=" + app_key + "&salt=" + nonce + "&curtime=" + curtime + \
"&sign=" + sign + "&version=v1&channel=1&format=wav&signType=v4&rate=16000&langType=" + language_type
print(uri)
start(uri, 1600)
start()方法是實時識別部分的核心方法,通過websocket調用識別接口。
def start(uri):
websocket.enableTrace(True)
ws = websocket.WebSocketApp(uri,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.on_open = on_opend
ws.run_forever()
在請求接口時,首先讀取先前錄製的音頻文件,並發送:
def on_open(ws):
count = 0
file_object = open(file_path, 'rb') #打開錄製的音頻
while True:
chunk_data = file_object.read(1600)
ws.send(chunk_data, websocket.ABNF.OPCODE_BINARY) #發送
time.sleep(0.05)
count = count + 1
if not chunk_data:
break
print(count)
ws.send('{\"end\": \"true\"}', websocket.ABNF.OPCODE_BINARY)
而後在通信過程中處理接口返回的消息,收集接口返回的識別結果:
def on_message(ws, message):
result=json.loads(message)
resultmessage= result['result'] #解析調用接口的返回結果
if resultmessage:
resultmessage1 = result['result'][0]
resultmessage2 = resultmessage1["st"]['sentence']
print(resultmessage2)
#text_result.insert(tk.END, resultmessage2+'\n')
result_arr.append(resultmessage2)
最後在通信結束後展示識別結果:
def on_close(ws):
print_resule(result_arr)
print("### closed ###")
def print_resule(arr):
text_result.delete('1.0',tk.END)
for n in arr:
text_result.insert("insert", n + '\n')
有道智雲提供的接口一如既往的好用,這次開發主要的精力全都浪費在了由於我自己錄製的音頻質量差而識別失敗的問題上,音頻質量ok後,識別結果準確無誤,下一步就是拿去翻譯了,有了有道智雲API,實現實時翻譯也可以如此簡單