Pepper/Nao中級教程:第五章 如何在Choregraphe中呼叫百度翻譯API
阿新 • • 發佈:2018-12-20
目標
我希望讓機器人做翻譯,但是Naoqi自身是沒有翻譯API的。 那麼我可以呼叫百度翻譯API來實現翻譯功能。
原理
百度API是RESTfulAPI,直接向百度API的URL發出請求, 返回值中就有翻譯結果。
我們在Choregraphe中建立一個Python指令盒子,來呼叫百度API即可。
動手實踐
1.申請百度開發者,獲取百度翻譯APPID和金鑰。 開啟http://api.fanyi.baidu.com/api/trans/product/desktop,註冊百度開發者。 申請一個通用翻譯許可權。
-
在Choregraphe中做出如下流程 說明,TextEdit盒子中是等待被翻譯的英文,Translate是翻譯Python指令盒。 Translate指令盒上有兩個引數,一個是APPID一個是金鑰。
-
編寫Python程式碼
程式碼如下
# -*- coding:utf-8 -*-
import httplib
import md5
import urllib
import random
import json
class MyClass(GeneratedClass):
def __init__(self):
GeneratedClass.__init__(self)
def onLoad(self):
#put initialization code here
pass
def onUnload(self) :
#put clean-up code here
pass
def onInput_onStart(self, text):
# 從指令盒面板獲取appid和secretKey
appid = self.getParameter("appid")
secretKey = self.getParameter("password")
# 填寫BAIDU翻譯API的引數
httpClient = None
myurl = '/api/trans/vip/translate'
q = text
fromLang = 'en'
toLang = 'zh'
salt = random.randint(32768, 65536)
sign = appid+q+str(salt)+secretKey
m1 = md5.new()
m1.update(sign)
sign = m1.hexdigest()
myurl = myurl+'?appid='+appid+'&q='+urllib.quote(q)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign
try:
# 訪問BAIDU翻譯API的URL
httpClient = httplib.HTTPConnection('api.fanyi.baidu.com')
httpClient.request('GET', myurl)
response = httpClient.getresponse()
# 從返回中獲取翻譯結果
translated = response.read()
obj = json.loads(translated)
results = obj.get('trans_result')
if results and len(results) > 0:
words = results[0].get('dst').encode("utf-8")
# 輸出翻譯結果
self.logger.info(words)
self.onStopped(words)
except Exception, e:
print e
finally:
if httpClient:
httpClient.close()
def onInput_onStop(self):
self.onUnload() #it is recommended to reuse the clean-up as the box is stopped
self.onStopped() #activate the output of the box
- 見證奇蹟 我把翻譯結果列印到了日誌上。