溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

使用python如何開發(fā)翻譯工具

發(fā)布時間:2020-10-28 16:53:15 來源:億速云 閱讀:190 作者:Leah 欄目:開發(fā)技術

本篇文章為大家展示了使用python如何開發(fā)翻譯工具,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。

效果展示

先看看界面和結果哈:

可以選擇多種語音,這里只寫了四種常見的:

使用python如何開發(fā)翻譯工具

偶分別測試的中文、韓文、英文??粗€不錯哦~

使用python如何開發(fā)翻譯工具

調用API接口的準備工作

首先,是需要在有道智云的個人頁面上創(chuàng)建實例、創(chuàng)建應用、綁定應用和實例,獲取調用接口用到的應用的id和密鑰。具體個人注冊的過程和應用創(chuàng)建過程詳見文章分享一次批量文件翻譯的開發(fā)過程

使用python如何開發(fā)翻譯工具

開發(fā)過程詳細介紹

下面介紹具體的代碼開發(fā)過程。

首先是根據實時語音識別文檔來分析接口的輸入輸出。接口設計的目的是對連續(xù)音頻流的實時識別,轉換成文本信息并返對應文字流,因此通信采用websocket,調用過程分為認證、實時通信兩階段。

在認證階段,需發(fā)送以下參數(shù):

參數(shù)類型必填說明示例
appKeyString已申請的應用IDID
saltStringUUIDUUID
curtimeString時間戳(秒)TimeStamp
signString加密數(shù)字簽名。sha256
signTypeString數(shù)字簽名類型v4
langTypeString語言選擇,參考支持語言列表zh-CHS
formatString音頻格式,支持wavwav
channelString聲道,支持1(單聲道)1
versionStringapi版本v1
rateString采樣率16000

簽名sign生成方法如下:
signType=v4;
sign=sha256(應用ID+salt+curtime+應用密鑰)。

認證之后,就進入了實時通信階段,發(fā)送音頻流,獲取識別結果,最后發(fā)送結束標志結束通信,這里需要注意的是,發(fā)送的音頻最好是16bit位深的單聲道、16k采樣率的清晰的wav音頻文件,這里我開發(fā)時最開始因為音頻錄制設備有問題,導致音頻效果極差,接口一直返回錯誤碼304(手動捂臉)。

Demo開發(fā):

這個demo使用python3開發(fā),包括maindow.py,audioandprocess.py,recobynetease.py三個文件。界面部分,使用python自帶的tkinter庫,來進行語言選擇、錄音開始、錄音停止并識別的操作。audioandprocess.py實現(xiàn)了錄音、音頻處理的邏輯,最后通過recobynetease.py中的方法來調用實時語音識別API。

1.界面部分:

主要元素:

root=tk.Tk()
root.title("netease youdao translation test")
frm = tk.Frame(root)
frm.grid(padx='80', pady='80')
# label1=tk.Label(frm,text="選擇待翻譯文件:")
# label1.grid(row=0,column=0)
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()

2.音頻錄制部分,引入pyaudio庫(需通過pip安裝)來調用音頻設備,錄制接口要求的wav文件,并通過wave庫存儲文件:

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=language_dict[language_type]
  print(language_dict[language_type])
  self.is_recording=is_recording
  self.audio_chunk_size=1600
  self.audio_channels=1
  self.audio_format=pyaudio.paInt16
  self.audio_rate=16000

def record_and_save(self):
  self.is_recording = True
  # self.audio_file_name=self.audio_path+'/recordtmp.wav'
  self.audio_file_name='/recordtmp.wav'

  threading.Thread(target=self.record,args=(self.audio_file_name,)).start()

def record(self,file_name):
  print(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)

  # 讀取數(shù)據寫入文件
  while self.is_recording:
    data = stream.read(self.audio_chunk_size)
    wf.writeframes(data)
  wf.close()
  stream.stop_stream()
  stream.close()
  p.terminate()

3.翻譯接口調用部分:

def recognise(filepath,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&#63;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)


def encrypt(signStr):
  hash = hashlib.sha256()
  hash.update(signStr.encode('utf-8'))
  return hash.hexdigest()



def on_message(ws, message):
  result=json.loads(message)
  try:
    resultmessage1 = result['result'][0]
    resultmessage2 = resultmessage1["st"]['sentence']
    print(resultmessage2)
  except Exception as e:
    print('')

def on_error(ws, error):
  print(error)


def on_close(ws):
  print("### closed ###")


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 start(uri,step):

  websocket.enableTrace(True)

  ws = websocket.WebSocketApp(uri,
                on_message=on_message,
                on_error=on_error,
                on_close=on_close)

  ws.on_open = on_open
  ws.run_forever()

上述內容就是使用python如何開發(fā)翻譯工具,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI