def tts_start(self, saytext, lang): appSecret = self.set['main_setting']['TTS']['youdao']['appkey'] appKey = self.set['main_setting']['TTS']['youdao']['appid'] data = {} salt = random.randint(1, 65536) sign = appKey + q + str(salt) + appSecret m1 = md5.new() m1.update(sign) sign = m1.hexdigest() data['appKey'] = appKey data['q'] = q data['salt'] = salt data['sign'] = sign data['langType'] = lang response = requests.post('http://openapi.youdao.com/ttsapi', data=data) contentType = response.headers['content-type'] if contentType == "audio/mp3": filePath = "/home/pi/xiaolan/memory_center/musiclib/" + 'say' + ".mp3" fo = open(filePath,'wb') fo.write(response.content) fo.close() return {'States': 'YoudaoTTSComplete'} else: self.tts('对不起,我的语言中枢出错了,我不能跟你说话了', self.set['main_setting']['TTS']['youdao']['lang']) speaker.speak() return {'States': 'Error:YoudaoTTSError'}
def learn_name(name): # build a response response = "Okay {}".format(name) # say it speaker.speak(response) # save the data config.save_config("name", name)
def speaker(self, mode): """ 播音器 :param mode: 模式 :return: """ if mode == 'ding': self.log('write', { 'log': 'XiaolanSpeakerEvent:StartRecording', 'level': 'info' }) speaker.ding() elif mode == 'dong': self.log('write', { 'log': 'XiaolanSpeakerEvent:RecordingComplete', 'level': 'info' }) speaker.dong() elif mode == 'speak': self.log('write', { 'log': 'XiaolanSpeakerEvent:Speak', 'level': 'info' }) speaker.speak() elif mode == 'TextEmpty': self.log('write', { 'log': 'XiaolanSpeakerEvent:TextNull', 'level': 'info' }) speaker.speacilrecorder() else: self.log('write', { 'log': 'Error:UnknowSpeakerCommands', 'level': 'warning' })
def result(reslt): if reslt: print("bot: Ok bye, I am on it!!") speak("Ok bye, I am on it!!") else: print("Bot: See you next Time :)")
def diy_tts(self, saytext, service, more): """ DIY_TTS语音合成 :param saytext: tts文本 :param service: tts服务 :param more: 更多 :return: """ from speech_center.tts import baidu_tts from speech_center.tts import youdao_tts if service == 'baidu': tts = baidu_tts() tok = tts.get_token() elif service == 'youdao': tts = youdao_tts() tok = more['lang'] else: tok = tts.get_token() tts = baidu_tts() self.log('write', {'log': 'StartTTS:' + saytext, 'level': 'info'}) states = tts.tts_start(saytext, tok) if 'Error' in states['States']: self.log('write', {'log': states['States'], 'level': 'error'}) else: speaker.speak()
def tts(self, saytext): """ TTS语音合成 :return: """ from speech_center.tts import baidu_tts from speech_center.tts import youdao_tts if self.set['main_setting']['TTS']['service'] == 'baidu': tts = baidu_tts() tok = tts.get_token() elif self.set['main_setting']['TTS']['service'] == 'youdao': tts = youdao_tts() tok = self.set['main_setting']['TTS']['youdao']['lang'] else: tts = baidu_tts() tok = tts.get_token() self.log('write', { 'log': 'Error:UnreadSettingForTTS', 'level': 'waring' }) self.log('write', {'log': 'StartTTS:' + saytext, 'level': 'info'}) states = tts.tts_start(saytext, tok) if 'Error' in states: self.log('write', {'log': states['States'], 'level': 'error'}) else: speaker.speak()
def main(tok): bt = baidu_tts() host = 'https://api.seniverse.com/v3/weather/now.json?key=' key = 'sxyi6ehxblxkqeto' APIURL = key + '&location=ip&language=zh-Hans&unit=c' url = host + APIURL r = requests.get(url) json = r.json() print json weather = json['results'][0]['now']['text'] temperature = json['results'][0]['now']['temperature'] ran = random.randint(0, 4) if ran == 0: saytext = "今天," + weather + ",温度是," + temperature + ",摄氏度" elif ran == 1: saytext = "你猜啊!算了,告诉你吧:今天" + weather + ",温度大概是" + temperature + "摄氏度" elif ran == 2: saytext = "我生气了,不想告诉你。但是看在你这么可爱的份上,告诉你咯:今天" + weather + ",温度" + temperature + "摄氏度" elif ran == 3: saytext = "我是你的可爱小蓝,天气这就来:今天" + weather + ",温度" + temperature + "摄氏度" else: saytext = "今天" + weather + ",温度" + temperature + "摄氏度,天气天天都有,但如果我没有就恐怖了" bt.tts(saytext, tok) speaker.speak()
def e_id(self, tok): bt = baidu_tts() setting = setting.setting() url = setting['smarthome']['url'] port = setting['smarthome']['port'] passwd = setting['smarthome']['passwd'] service = '/api/states' headers = {'x-ha-access': passwd, 'content-type': 'application/json'} r = requests.get(url + ':' + port + service, headers=headers) r_json = r.json() e_id = {} try: for r_jsons in r_json: entity_id = r_jsons['entity_id'] friendly_name = r_jsons['attributes']['friendly_name'] domain = entity_id.split(".")[0] e_id[friendly_name] = entity_id except TypeError: bt.tts('homeassistant设备实体码获取失败', tok) speaker.speak() else: return e_id
def main(text, tok): setting = setting.setting() ak = setting['tuling']['key'] ui = setting['tuling']['user_id'] url = 'http://openapi.tuling123.com/openapi/api/v2' dataf = { "reqType": 0, "perception": { "inputText": { "text": text }, }, "userInfo": { "apiKey": ak, "userId": ui } } data = json.dumps(dataf) talkback = requests.post(url, data=data) talkback_data = talkback.json() text = talkback_data["results"][-1]["values"]["text"] saytext = text.encode('utf-8', 'strict') bt = baidu_tts() bt.tts(saytext, tok) speaker.speak()
def main(tok): bt = baidu_tts() bs = baidu_stt(1, 2, 3, 4) r = recorder() m = hashlib.md5() host = 'http://api.fanyi.baidu.com/api/trans/vip/translate' appid = '20180425000150592' apikey = 'gN56Mdv4mh2KJ0Ko2p6v' asktext = '请问您要翻译什么?请在滴一声后说出内容,文言文也可以翻译哦!' bt.tts(asktext, tok) speaker.speak() speaker.ding() r.tsrecord() speaker.dong() tstext = bs.stt('./voice.wav', tok) signf = appid + tstext + '1435660288' + apikey m.update(signf) sign = m.hexdigest() data = 'q=' + tstext + '&from=auto&to=zh&appid=' + appid + '&salt=1435660288&sign=' + sign url = host + data r = requests(url) json = r.json() print json tsback = ['trans_result'][0]['dst'] saytext = tsback bt.tts(saytext, tok) speaker.speak()
def listen_for_input(r, mic): # listen to input print("Now listening...") beep() with mic as source: # this ambient noise adjustment is causing more problems than it's solving # r.adjust_for_ambient_noise(source) audio = r.listen(source) # try to recognize audio try: recognized_speech = r.recognize_google(audio) print(recognized_speech) decoder.decode(recognized_speech.lower()) listen_for_input(r, mic) except sr.RequestError: # API was unreachable or unresponsive print("There was an error: API unavailable") except sr.UnknownValueError: # speech was unintelligible print("There was an error: Unable to recognize speech") speaker.speak("Sorry, I didn't get that.") listen_for_input(r, mic)
def main(text, tok): ak = 'c380ed8f2880443c84892ace36ba6bad' ui = '167031' url = 'http://openapi.tuling123.com/openapi/api/v2' dataf = { "reqType":0, "perception": { "inputText": { "text": text }, }, "userInfo": { "apiKey": ak, "userId": ui } } data = json.dumps(dataf) talkback = requests.post(url, data=data) talkback_data = talkback.json() text = talkback_data["results"][-1]["values"]["text"] saytext = text.encode('utf-8','strict') bt = baidu_tts() bt.tts(saytext, tok) speaker.speak()
def main(self, tok): bt = baidu_tts() bs = baidu_stt(1, 2, 3, 4) r = recorder() e = email() mail_host = 'smtp.qq.com' #这里默认qq邮箱,可以更改 mail_user = '' #邮箱账户 mail_pass = '' #邮箱密码 mail_port = '465' #与邮箱服务商相通 sender = '*****@*****.**' receivers = [] bt.tts('欢迎使用小蓝邮件助手,请问您有什么需要吗', tok) speaker.speak() speaker.ding() r.record() speaker.dong() commands = bs.stt('./voice.wav', tok) command = e.command_choose(commands, tok) if command == 'send': e.send(mail_host, mail_user, mail_pass, mail_port, sender, tok) else: bt.tts('对不起,我们还暂时不支持该功能', tok) speaker.speak()
def main(text, tok): ak = '869429e05ea142ef9e3784f8e7965d1c' ui = '373523' url = 'http://openapi.tuling123.com/openapi/api/v2' dataf = { "reqType": 0, "perception": { "inputText": { "text": text }, }, "userInfo": { "apiKey": ak, "userId": ui } } data = json.dumps(dataf) talkback = requests.post(url, data=data) talkback_data = talkback.json() text = talkback_data["results"][-1]["values"]["text"] saytext = text.encode('utf-8', 'strict') bt = baidu_tts() bt.tts(saytext, tok) speaker.speak()
def getskills(self, intent, text, tok): if intent == 'clock': clock.start(tok) elif intent == 'camera': camera.start(tok) elif intent == 'smarthome': smarthome.start(tok) elif intent == 'weather': weather.start(tok) elif intent == 'music': music.start(tok) elif intent == 'mail': mail.start(tok) elif intent == 'joke': joke.start(tok) elif intent == 'news': news.start(tok) elif intent == 'tuling': tuling.start(text, tok) elif intent == 'snowboytrain': snowboytrain.start(tok) elif intent == 'raspberrypi-gpio': raspberrypigpio.start(tok) elif intent == 'respeaker': speaker.speak() elif intent == 'no': sconvenstation() elif intent == 'reintent': intent = nlp.do_intent(text, tok) s.getskills(intent, text, tok)
def readpage(pdfname): pdfFileObj = open(pdfname, 'rb') pdfReader = PyPDF2.PdfFileReader(pdfFileObj) pdfsize = pdfReader.numPages) for p in range(pdfsize-1): pageObj=pdfReader.getPage(p) speaker.speak(pageObj.extractText())) pdfFileObj.close()
def ip_loc(self, tok): r = requests.ger('http://restapi.amap.com/v3/ip?' + 'output=json&key=' + self.set['maps']['key']) try: bt.tts('你在' + r.json()['province'] + r.json()['city'], tok) speaker.speak() except KeyError: bt.tts('位置获取失败', tok) speaker.speak()
def read(): global queue, quit while not quit: sleep(1) if not queue.empty(): tweet = queue.get() message = config.MESSAGE % (tweet.user, tweet.tweet) print "Saying: "+message speaker.speak(message)
def readDth(self): bt = baidu_tts() bs = baidu_stt(1, 'a', '{', 3) humidity, temperature = Adafruit_DHT.read_retry( self.sensor, gpio.pdht11.value) if humidity is not None and temperature is not None: saytext = '湿度是,' + humidity + '温度是' + temperature tok = bt.get_token() bt.tts(saytext, tok) speaker.speak()
def sui_ji(self, services, tok): bt = baidu_tts() bs = baidu_stt(1, 2, 3, 4) r = recorder() m = xlMusic() url = 'http://tingapi.ting.baidu.com/v1/restserver/ting?' song_name_c = random.uniform(0, 12) song_name_s = [ '皮皮虾我们走', 'I hope you think of me', '小幸运', '全部都是你', '佛系少女', 'Something just like this', 'Feel this Moment', 'Welcome to NewYork', '洛天依投食歌', '带你去旅行', '死机之歌', 'Shape of You', 'Kiss Fight', 'Hot song' ] if song_name_s[random.uniform(0, 12)] != 'Hot song': get_song_id_rawj = requests.get(url + services['search'] + song_name_c) else: get_song_id_rawj = requests.get(url + services['hot']) get_song_id_j = get_song_id_rawj.json() try: if song_name_s[random.uniform(0, 12)] == 'Hot song': id = get_song_id_j['result']['list'][song_name_c]['song_id'] else: id = get_song_id_j['song'][song_name_c]['songid'] except KeyError: try: if song_name == 'Hot song': id = get_song_id_j['result']['list'][song_name_c][ 'song_id'] else: id = get_song_id_j['song'][song_name_c]['songid'] except KeyError: bt.tts('对不起,播放错误') speaker.speak() else: pass else: get_song_url_rawj = requests.get(url + services['musicurl_get'] + id) get_song_url_j = get_song_url_rawj.json() song_name = get_song_url_j['songinfo']['title'] song_url_f = get_song_url_j['bitrate']['file_link'] song_url = (song_url_f.replace('\', ' '')) download = requests.get(song_url) with open("/home/pi/xiaolan/musiclib/music.mp3", "wb") as code: code.write(download.content) m.play(song_name, tok)
def main(tok): bt = baidu_tts() bs = baidu_stt(1, 2, 3, 4) r = recorder() youdao = youdao_tts() appKey = selfset['ts']['appkey'] secretkey = selfset['ts']['secretkey'] httpClient = None myurl = '/api' q = 'good' bt.tts('请问您要翻译的是什么语言?', tok) speaker.speak() speaker.ding() r.record() speaker.dong() fromLang = lang_choose(bs.stt('./voice.wav', tok), tok) bt.tts('请问您要翻译为什么语言?', tok) speaker.speak() speaker.ding() r.record() speaker.dong() toLang = lang_choose(bs.stt('./voice.wav', tok), tok) bt.tts('请说出您要翻译的内容', tok) speaker.speak() speaker.ding() r.tsrecord() speaker.dong() tstext = bs.stt('./voice.wav', tok) salt = random.randint(1, 65536) sign = appKey+q+str(salt)+secretKey m1 = md5.new() m1.update(sign) sign = m1.hexdigest() myurl = myurl + '?appKey=' + appKey + '&q=' + urllib.quote(q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(salt) + '&sign=' + sign try: httpClient = httplib.HTTPConnection('openapi.youdao.com') httpClient.request('GET', myurl) #response是HTTPResponse对象 response = httpClient.getresponse() json = json.loads(response.read()) try: youdao.tts('第一种意思为,' + json['translation'][0] + ',第二种意思为,' + json['translation'][1], toLang) speaker.speak() except: youdao.tts('翻译结果为' + json['translation'][0], toLang) speaker.speak() except Exception, e: print e
def choose_mode(self, text, tok): if '打开' in text or '启动' in text: mode = 1 elif '关闭' in text or '低电平' in text: mode = 0 elif '高电平' in text: mode = 1 else: mode = 'none' bt.tts('对不起,暂时不支持该操作', tok) speaker.speak() return mode
def main(tok): url = 'http://api.avatardata.cn/Joke/QueryJokeByTime?key=' selfset = setting.setting() key = selfset['joke']['key'] bt = baidu_tts() r = requests.post(url + key + '&sort=asc&time=1418745237') json = r.json() bt.tts(json['result'][random.randint(0, 9)]['content'], tok) speaker.speak()
def decode(speech): # set config data config_data = config.get_config() if (speech == "stop listening"): speaker.speak("Goodbye") sys.exit(0) else: if "call me" in speech: # get name from text name = speech.split("all me ")[1] learn_name(name) if "my name is" in speech: # get name from text name = speech.split("name is ")[1] learn_name(name) elif "what's my name" in speech: try: # using a try/catch here to see if the data exists in the config name = config_data["name"] response = "Your name is {}".format(name) speaker.speak(response) except KeyError: speaker.speak("I don't know what to call you yet.") elif "what time is it" in speech: import time timeObj = time.gmtime() hour = int(time.strftime("%H")) minute = time.strftime("%M") spokenTime = spoken_datetime.getSpokenTime(hour, minute) response = "It's {}".format(spokenTime) print(response) speaker.speak(response) return
def start(text, token): """ 启动 :param text: 文本 :param token: token :return: """ r = recorder() bt = baidu_tts() bs = baidu_stt(1, 'a', 2, '{') song_list = ["冲鸭冲鸭.mp3", "招财进宝.mp3", "毒液前来.mp3", "跟着我一起.mp3"] ycy = "杨超越,1998年7月31日出生于江苏省盐城市,中国内地流行乐女歌手,女子演唱组合CH2、火箭少女101成员。 2017年,加入女子演唱组合CH2,从而正式出道,并签约了多家游戏平台,为高校电竞比赛做内容推广;同年,随CH2相继推出了《启航》、《听雪恋歌》等单曲。2018年,参加腾讯视频女团青春成长节目《创造101》,最终获得第3名,并加入女子演唱组合火箭少女101;8月18日,随火箭少女101推出组合首张EP专辑《撞》;9月23日,推出首支个人单曲《跟着我一起》;11月15日,推出第2支个人单曲《冲鸭冲鸭》;11月27日,推出第3支个人单曲《招财进宝》;12月15日,获得“影响中国”年度人物荣誉盛典年度演艺人物奖。2019年,她被评选为LikeTCCAsia亚太区最美100张面孔第3位、中国区最美100张面孔第1位呢!" bt.tts(ycy, token) speaker.speak() bt.tts("我这里还有杨超越姐姐唱的歌哦~要不要听一听呢?", token) speaker.speak() speaker.ding() r.record() speaker.dong() text = bs.stt("./voice.wav", token) if "不" in text: bt.tts("哦,那好吧~再见啦", token) speaker.speak() else: bt.tts("那你想要听什么呢?不知道的话,可以说随机哦~", token) speaker.speak() speaker.ding() r.record() speaker.dong() text = bs.stt("./voice.wav", token) if "随机" in text: speaker.play(song_list[random.randint(0, 4)]) else: kugou_request(text)
def main(tok): bt = baidu_tts() bs = baidu_stt(1, 2, 3, 4) r.recorder() asktext = '请问您要设定什么时候的闹钟?要重复请在开头说重复闹钟,默认单次,重复闹钟请说出重复日期哦!' bt.tts(asktext, tok) speaker.speak() speaker.ding() r.record() speaker.dong() settext = bs.stt('./voice.wav', tok) if settext[0:3] == '重复闹钟': clockmode = 'reclock' reclocktime = settext[4:6]
def study(self, tok): bt = baidu_tts() bs = baidu_stt(1, 2, 3, 4) r = recorder() h = hass() url = 'http://hassio.local' port = '8123' passwd = 'y20050801' headers = {'x-ha-access': passwd, 'content-type': 'application/json'} say = '该功能暂未开发完毕,sorry' bt.tts(say, tok) speaker.speak()
def paly(self, song_name, tok): bt = baidu_tts() bs = baidu_stt(1, 2, 3, 4) r = recorder() m = xlMusic() while song_name != None: speaker.play() bt.tts('请问还要听什么吗?可以输入指令,如,这首歌叫什么,或者,搜索歌曲', tok) speaker.speak() speaker.ding() r.record() speaker.dong() commands = bs.stt('./voice.wav', tok) command = m.command_choose(commands, tok) if command == 'sui_ji': m.sui_ji(services, tok) elif command == 'sou_suo': m.sou_suo(services, tok) elif command == 'exit': bt.tts('谢谢使用,下次再见', tok) speaker.speak() os.system('python /home/pi/xiaolan/xiaolan/xldo.py b') break elif command == 're': bt.tts('对不起,我没有听清楚您说了什么?', tok) speaker.speak() m.main(tok) else: bt.tts('对不起,发生了故障', tok) speaker.speak()
def main(tok): bt = baidu_tts() bs = baidu_stt(1, 2, 3, 4) r.recorder() bt.tts('请问您要设定什么时候的闹钟?', tok) speaker.speak() bt.tts('支持下午几点的说法', tok) speaker.speak() speaker.ding() r.exrecord() speaker.dong() text = bs.stt('./voice.wav', tok).replace(',', '') if '重复闹钟' in text: if '下午' in text or '上午' in text: text = text.choose_date(text, text.rfind('重复闹钟'), tok)
def main(self, tok): bt = baidu_tts() bs = baidu_stt(1, 2, 3, 4) r = recorder() m = xlMusic() welcome = '欢迎使用小蓝音乐播放器,云服务使用百度音乐' ask = '请问您要随机播放还是搜索播放?' url = 'http://tingapi.ting.baidu.com/v1/restserver/ting?' services = { 'musicurl_get': 'method=baidu.ting.song.play&songid=', 'search': 'method=baidu.ting.search.catalogSug&query=', 'hot': 'method=baidu.ting.song.getRecommandSongList&song_id=877578&num=12' } bt.tts(welcome, tok) speaker.speak() bt.tts(ask, tok) speaker.speak() speaker.ding() r.record() speaker.dong() try: commands = bs.stt('./voice.wav', tok) except TypeError: speaker.speak() speaker.ding() r.record() speaker.dong() command = m.command_choose(commands, tok) else: if command == 'sui_ji': m.sui_ji(services, tok) elif command == 'sou_suo': m.sou_suo(services, tok) elif command == 'exit': bt.tts('谢谢使用,下次再见', tok) speaker.speak() os.system('python /home/pi/xiaolan/xiaolan/xldo.py b') elif command == 're': bt.tts('对不起,我没有听清楚您说了什么?', tok) speaker.speak() m.main(tok)
def main(tok): bt = baidu_tts() bs = baidu_stt(1, 'a', 2, '{') r = recorder() selfset = setting.setting() host = 'https://api.seniverse.com/v3/weather/now.json?key=' key = selfset['weather']['key'] r = requests.get(host + key + '&location=ip&language=zh-Hans&unit=c') json = r.json() bt.tts( ',今天的天气是,' + json['results'][0]['now']['text'] + ',温度是,' + json['results'][0]['now']['temperature'] + ',摄氏度,', tok) speaker.speak()
from client import Client import speaker import config from Queue import Queue from time import sleep from threading import Thread client = Client() queue = Queue() quit = False if config.ANNOUNCE_ENABLED: speaker.speak(config.ANNOUNCE_MESSAGE) def gather(): global queue, quit lastId = client.getLatestTweetId() print "Last tweet = "+lastId while not quit: sleep(60 * config.POLL_INTERVAL) tweets = client.getTweets(lastId) if len(tweets)>0: lastId = tweets[0].id for tweet in reversed(tweets): print "Queueing "+str(tweet) queue.put(tweet) else: print "No tweets - I checked"