范文健康探索娱乐情感热点
投稿投诉
热点动态
科技财经
情感日志
励志美文
娱乐时尚
游戏搞笑
探索旅游
历史星座
健康养生
美丽育儿
范文作文
教案论文

快速上手Dialogflow交互机器人

  作者:MeshCloud脉时云公有云架构师陈博文简介:
  Dialogflow 是Google 提供的一款人机交互平台,通过该平台可以轻松地设计出属于自己的交互机器人,比如常见的网页聊天机器人,电话智能客服等。借助Dialogflow甚至可以用于扫地机器人交互系统或者更高级的使用。
  Dialogflow 通过客户输入的语音或者文字甚至情感分析,来识别客户的意图(Intens),结合实体(Entities),来进行相应的回复。
  Dialogflow的几个优点:识别准确率高,响应速度快支持 30 多种语言和语言变体上手简单:图形界面配置;官方文档丰富、详细;网络上有案例可供参考有问题易解决:开发者社区超过150万名开发者
  Dialogflow经典案例:
  一、马航的订票查票机器人:
  使用 Google Cloud 上的 Dialogflow,马来西亚航空公司和 Amadeus 创建了一个聊天机器人,使客户能够搜索、预订和支付航班 ,从而使航空公司能够满足未来的需求并增加数字渠道的收入。
  二、达美乐披萨的订餐机器人:
  三、KLM预定、打包机器人:
  KLM 于 2016 年开始探索为客户提供体验的方法。他们在测试多个平台后选择了 Dialogflow。
  常用工具
  一、内置 Small Talk
  Small Talk 用于为闲聊对话提供响应。 此功能可以解答代理范围之外的常见问题,极大地提升最终用户体验。
  Small Talk 有两种版本:内置 Small Talk:为代理启用 Small Talk 后,它会自动处理闲聊对话,无需向代理添加意图。预建 Small Talk:导入预建 Small Talk 代理时,它会提供处理闲聊对话的意图。
  二、prebuilt agent
  由 Dialogflow 提供的一组代理,适用于常见的使用场景。 您可以这些代理为基础,构建涵盖特定场景(如外出就餐、酒店预订和导航)的对话。
  由 Dialogflow 提供的一组代理,适用于常见的使用场景。 您可以这些代理为基础,构建涵盖特定场景(如外出就餐、酒店预订和导航)的对话。
  如何制作一个自己的天气&新闻语音问答机器人
  使用了文字输入Dialogflow 的方式
  通过speech-to-text将音频麦克风流到Dialogflow 的文本意图检测API
  案例使用了以下GCP产品:Dialogflow ES & Knowledge BasesSpeech to Text
  其它组件:WebhookWeathers & News API
  在这个demo中你可以使用麦克风输入,然后返回新闻或者天气
  一、Dialogflow ES(页面配置)
  1、意图配置
  ①配置输入
  ②配置回复
  2、Webhook配置
  ①意图开启Fulfillment
  ②添加webhook
  ③webhook代码import requests #新闻接口 from newsapi import NewsApiClient import time import json #使用了flask框架 from flask import Flask, request import pycountry #from gevent.pywsgi import WSGIServer  app = Flask(__name__)  @app.route("/webhook", methods=["POST"]) def webhook():     Dialogflow_data = json.loads(request.data)     intent =Dialogflow_data["queryResult"]["intent"]["displayName"]     print("--------------------------------------")     if intent == "news":         responseText = callnewsapi()         news = responseText["articles"][0]["title"]         print(news)         headline = " headline news is %s"%(news)         #需要按要求返回dialogflow才能回复给客户端         #"fulfillmentText"是客户端接收消息         res = {"fulfillmentText": headline ,"fulfillmentMessages": [{"text": {"text":[headline]}}]}         return(res)     elif intent == "weather":         CITY=Dialogflow_data["queryResult"]["parameters"]["geo-city"]         key = "479284d0d8574437b8170935221508"         responseText = json.loads(callweatherapi(key,CITY))         mintemp = responseText["data"]["ClimateAverages"][0]["month"][7]["avgMinTemp"]         maxtemp = responseText["data"]["ClimateAverages"][0]["month"][7]["absMaxTemp"]         tempres = "London Maxtemp is %s ℃ Mintempe is %s ℃"%(maxtemp,mintemp)         #需要按要求返回dialogflow才能回复给客户端         #"fulfillmentText"是客户端接收消息         res = {"fulfillmentText": tempres ,"fulfillmentMessages": [{"text": {"text":[tempres]}}]}         return(res)   def callweatherapi(key,CITY):     time.sleep(0.01)     response = requests.post("http://api.worldweatheronline.com/premium/v1/weather.ashx?key=%s&q=%s&fx=no&cc=no&mca=yes&format=json"%(key,CITY))     if response.status_code == 200:        return(response.text)  def callnewsapi():     newsapi = NewsApiClient(api_key="0eaad3923a654da2a2a32d84870e0405")     response = newsapi.get_top_headlines(language="es")     return(response)  if __name__ == "__main__":     #WSGIServer(("0.0.0.0", 5000), app).serve_forever()     app.run(host="0.0.0.0", port=5000, ssl_context=("/root/scs1660552637313_cbw404.cn/scs1660552637313_cbw404.cn_Nginx/scs1660552637313_cbw404.cn_server.crt", "/root/scs1660552637313_cbw404.cn/scs1660552637313_cbw404.cn_Nginx/scs1660552637313_cbw404.cn_server.key"))
  新闻接口:http://api.worldweatheronline.com/premium/v1/weather.ashx?key=apikey&q=city&fx=no&cc=no&mca=yes&format=json
  天气接口:#install pip install newsapi-python #usage from newsapi import NewsApiClient #init newsapi = NewsApiClient(api_key="API_KEY") # /v2/top-headlines top_headlines = newsapi.get_top_headlines(q="bitcoin",                                           sources="bbc-news,the-verge",                                           category="business",                                           language="en",                                           country="us") # /v2/everything all_articles = newsapi.get_everything(q="bitcoin",                                       sources="bbc-news,the-verge",                                       domains="bbc.co.uk,techcrunch.com",                                       from_param="2017-12-01",                                       to="2017-12-12",                                       language="en",                                       sort_by="relevancy",                                       page=2) # /v2/top-headlines/sources sources = newsapi.get_sources()
  二、Speech-to-text(后面简称stt) to Dialogflow
  1、准备工作
  ①权限配置下载service account json格式  Linux: 配置环境变量 export GOOGLE_APPLICATION_CREDENTIALS=  为1中下载的 sa 的json文件  Windows: set GOOGLE_APPLICATION_CREDENTIALS=C:UsersAdministratorDownloadssa.json
  ②python包python 包 google-cloud-speech pyaudio google-cloud-dialogflow python-dotenv uuid
  ③.env文件 用于读取配置PROJECT_ID= #这里做的西班牙语测试 LANGUAGE_CODE=es #语音的一些参数设置,保持默认 ENCODING=AUDIO_ENCODING_LINEAR_16 SAMPLE_RATE_HERZ=16000 SINGLE_UTTERANCE=false SPEECH_ENCODING=LINEAR16 SSML_GENDER=FEMALE #dialogflow的区域(有us,es,zh) LOCATION_ID=global
  2、Speech-to-text
  使用实时流式音频执行识别(transcribe_streaming_mic),也就是麦克风持续输入,代码如下:#!/usr/bin/env python  """Google Cloud Speech API sample application using the streaming API. NOTE: This module requires the additional dependency `pyaudio`. To install using pip:     pip install pyaudio Example usage:     python transcribe_streaming_mic.py """  from __future__ import pision  import re import sys  from google.cloud import speech  import pyaudio from six.moves import queue   RATE = 16000 CHUNK = int(RATE / 10)  # 100ms   class MicrophoneStream(object):     """Opens a recording stream as a generator yielding the audio chunks."""      def __init__(self, rate, chunk):         self._rate = rate         self._chunk = chunk           self._buff = queue.Queue()         self.closed = True      def __enter__(self):         self._audio_interface = pyaudio.PyAudio()         self._audio_stream = self._audio_interface.open(             format=pyaudio.paInt16,              channels=1,             rate=self._rate,             input=True,             frames_per_buffer=self._chunk,             stream_callback=self._fill_buffer,         )          self.closed = False          return self      def __exit__(self, type, value, traceback):         self._audio_stream.stop_stream()         self._audio_stream.close()         self.closed = True         self._buff.put(None)         self._audio_interface.terminate()      def _fill_buffer(self, in_data, frame_count, time_info, status_flags):         """Continuously collect data from the audio stream, into the buffer."""         self._buff.put(in_data)         return None, pyaudio.paContinue      def generator(self):         while not self.closed:             chunk = self._buff.get()             if chunk is None:                 return             data = [chunk]             while True:                 try:                     chunk = self._buff.get(block=False)                     if chunk is None:                         return                     data.append(chunk)                 except queue.Empty:                     break              yield b"".join(data)   def listen_print_loop(responses):     num_chars_printed = 0     for response in responses:         if not response.results:             continue          result = response.results[0]         if not result.alternatives:             continue          transcript = result.alternatives[0].transcript          overwrite_chars = " " * (num_chars_printed - len(transcript))          if not result.is_final:             sys.stdout.write(transcript + overwrite_chars + "r")             sys.stdout.flush()              num_chars_printed = len(transcript)          else:             print(transcript + overwrite_chars)              if re.search(r"b(exit|quit)b", transcript, re.I):                 print("Exiting..")                 break              num_chars_printed = 0   def main():      language_code = "en-US"  #  BCP-47       client = speech.SpeechClient()     config = speech.RecognitionConfig(         encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,         sample_rate_hertz=RATE,         language_code=language_code,     )      streaming_config = speech.StreamingRecognitionConfig(         config=config, interim_results=True     )      with MicrophoneStream(RATE, CHUNK) as stream:         audio_generator = stream.generator()         requests = (             speech.StreamingRecognizeRequest(audio_content=content)             for content in audio_generator         )          responses = client.streaming_recognize(streaming_config, requests)          # Now, put the transcription responses to use.         listen_print_loop(responses)   if __name__ == "__main__":     main()
  3、Dialogflow
  调用检测意图,代码如下:#!/usr/bin/env python  """DialogFlow API Detect Intent Python sample to use regional endpoint. Examples:   python detect_intent_texts_with_location.py -h   python detect_intent_texts_with_location.py --project-id PROJECT_ID    --location-id LOCATION_ID --session-id SESSION_ID    "hello" "book a meeting room" "Mountain View" """  import argparse import uuid    def detect_intent_texts_with_location(     project_id, location_id, session_id, texts, language_code ):      from google.cloud import dialogflow      session_client = dialogflow.SessionsClient(         client_options={"api_endpoint": f"{location_id}-dialogflow.googleapis.com"}     )      session = (         f"projects/{project_id}/locations/{location_id}/agent/sessions/{session_id}"     )     print(f"Session path: {session} ")      text_input = dialogflow.TextInput(text=texts, language_code=language_code)      query_input = dialogflow.QueryInput(text=text_input)      response = session_client.detect_intent(         request={"session": session, "query_input": query_input}     )      print("=" * 20)     print(f"Query text: {response.query_result.query_text}")     print(         f"Detected intent: {response.query_result.intent.display_name} (confidence: {response.query_result.intent_detection_confidence,}) "     )     print(f"Fulfillment text: {response.query_result.fulfillment_text} ")     if __name__ == "__main__":     parser = argparse.ArgumentParser(         description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter     )     parser.add_argument(         "--project-id", help="Project/agent id.  Required.", required=True     )     parser.add_argument("--location-id", help="Location id.  Required.", required=True)     parser.add_argument(         "--session-id",         help="Identifier of the DetectIntent session. " "Defaults to a random UUID.",         default=str(uuid.uuid4()),     )     parser.add_argument(         "--language-code",         help="Language code of the query. Defaults to "en-US".",         default="en-US",     )     parser.add_argument("texts", nargs="+", type=str, help="Text inputs.")      args = parser.parse_args()      detect_intent_texts_with_location(         args.project_id,         args.location_id,         args.session_id,         args.texts,         args.language_code,     )
  4、(主要代码)将stt的结果(文字)输出到Dialogflow 意图检测,Dialogflow作出回复
  流程:
  代码如下: #!/usr/bin/env python  """Google Cloud Speech API sample application using the streaming API. NOTE: This module requires the additional dependency `pyaudio`. To install using pip:     pip install pyaudio Example usage:     python transcribe_streaming_mic.py """  from __future__ import pision  import re import sys  from google.cloud import speech  import pyaudio from six.moves import queue import os import uuid #调用 Dialogflow意图检测包(代码见2.dialogflow) from detect_intent_texts_with_location import detect_intent_texts_with_location from dotenv import load_dotenv  RATE = 16000 CHUNK = int(RATE / 10)  # 100ms   class MicrophoneStream(object):     """Opens a recording stream as a generator yielding the audio chunks."""      def __init__(self, rate, chunk):         self._rate = rate         self._chunk = chunk                   self._buff = queue.Queue()         self.closed = True      def __enter__(self):         self._audio_interface = pyaudio.PyAudio()         self._audio_stream = self._audio_interface.open(             format=pyaudio.paInt16,             channels=1,             rate=self._rate,             input=True,             frames_per_buffer=self._chunk,             stream_callback=self._fill_buffer,         )          self.closed = False          return self      def __exit__(self, type, value, traceback):         self._audio_stream.stop_stream()         self._audio_stream.close()         self.closed = True         self._buff.put(None)         self._audio_interface.terminate()      def _fill_buffer(self, in_data, frame_count, time_info, status_flags):         """Continuously collect data from the audio stream, into the buffer."""         self._buff.put(in_data)         return None, pyaudio.paContinue      def generator(self):         while not self.closed:             chunk = self._buff.get()             if chunk is None:                 return             data = [chunk]             while True:                 try:                     chunk = self._buff.get(block=False)                     if chunk is None:                         return                     data.append(chunk)                 except queue.Empty:                     break              yield b"".join(data)   def listen_print_loop(responses):      load_dotenv(verbose=True)     num_chars_printed = 0     for response in responses:         if not response.results:             continue           result = response.results[0]         if not result.alternatives:             continue          transcript = result.alternatives[0].transcript          overwrite_chars = " " * (num_chars_printed - len(transcript))          if not result.is_final:             sys.stdout.write(transcript + overwrite_chars + "r")             sys.stdout.flush()              num_chars_printed = len(transcript)          else:         #从.env中导出Project_id等配置,可以通过修改.env修改             TEXT=transcript + overwrite_chars             print(transcript + overwrite_chars)             PROJECT_ID = os.getenv("PROJECT_ID")             SESSION_ID = uuid.uuid1()             LANGUAGE_CODE = os.getenv("LANGUAGE_CODE")         #Location_ID             LOCATION_ID = os.getenv("LOCATION_ID")         #意图检测 TEXT为mic接收到的语音转成的文字(代码见2.dialogflow)             detect_intent_texts_with_location(PROJECT_ID, LOCATION_ID, SESSION_ID, TEXT, LANGUAGE_CODE)             # Exit recognition if any of the transcribed phrases could be             # one of our keywords.             #对麦克风说exit即可退出             if re.search(r"b(exit|quit)b", transcript, re.I):                 print("Exiting..")                 break              num_chars_printed = 0   def main():     language_code = "en-US"  # BCP-47      client = speech.SpeechClient()     config = speech.RecognitionConfig(         encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,         sample_rate_hertz=RATE,         language_code=language_code,     )      streaming_config = speech.StreamingRecognitionConfig(         config=config, interim_results=True     )      with MicrophoneStream(RATE, CHUNK) as stream:         audio_generator = stream.generator()         requests = (             speech.StreamingRecognizeRequest(audio_content=content)             for content in audio_generator         )          responses = client.streaming_recognize(streaming_config, requests)           listen_print_loop(responses)  if __name__ == "__main__":     main()
  Location_id:(上面意图检测API的location_id参数)
  国家/地区分组
  地理位置
  地区 ID
  美洲
  爱荷华
  us-central1
  美洲
  蒙特利尔
  northamerica-northeast1
  美洲
  南卡罗来纳
  us-east1
  美洲
  俄勒冈
  us-west1
  欧洲
  比利时
  europe-west1
  欧洲
  伦敦
  europe-west2
  欧洲
  法兰克福
  europe-west3
  亚太地区
  悉尼
  australia-southeast1
  亚太地区
  东京
  asia-northeast1
  亚太地区
  孟买
  asia-south1
  亚太地区
  新加坡
  asia-southeast1
  全球
  全球服务,静态数据在美国
  global(首选)、us 或无区域(默认)
  5、测试
  ①Dialogflow web测试 :Fulfillment 通过 webhook response 格式化数据后返回给客户端 ,测试成功
  ②程测试:mic -- stt -- dialogflow --client(default welcome intent --default response)
  测试成功:
  可以看到语音输入的内容转成了文字,并发送给了dialogflow的意图检测,并匹配意图给出相应的回复
  ③全流程测试:mic -- stt -- dialogflow -- fulfillment -- webhook -- api -- client
  对麦克风说:noticias(西语新闻)
  返回:头条新闻的标题,测试成功
  三、总结
  至此,一个天气&新闻语音问答机器人就做好了
  官方还提供了另外的集成或者使用方式,可以供大家参考学习。希望这篇文章对大家有抛砖引玉的作用,以便大家能做出更高级更智能、更符合自己项目的交互机器人

再见蔡斌!再见中国女排!前奥运冠军主力深夜发文告别国家队再见蔡斌!再见中国女排!前奥运冠军主力深夜发文告别国家队!今天我们来关注一下中国女排的最新消息,在以第六名的身份结束了女排世锦赛之后,中国女排目前已经返回国内,接下里也将回到各自的17年过去了,葛优为了帮傅彪养儿子,付出的代价令人心酸2005年8月30日,年仅42岁的男演员傅彪因患肝癌晚期不幸去世了。站在病床前的除了傅彪的亲人之外,还有三个没有血缘关系的男人。傅彪撑着最后一口气交代后事,他真诚地祈求他们。待自己每天阳光明媚,却是光的智慧在灿烂,我们却浑然不知你了解光吗,你知道光的智慧吗?我们每天奔忙不息,你知道光存在的意义吗?光每日存在,与我何干?是的,光的确太普通,我们习惯了视而不见。但光确实是一种普通却又神奇的东西,它蕴藏着我们摸党代表有话说丨李会东加快科技创新不负伟大时代大河网讯(记者赵檬)身处大有可为的新时代,应该更进一步加快科技创新步伐,为不断塑造发展新动能新优势贡献自己的力量。科技兴则民族兴,人才强则国家强。党的二十大报告指出,必须坚持科技是特拉斯风暴告一段落,英镑兑美元能否摆脱平价命运?21世纪经济报道记者吴斌上海报道当地时间10月25日,刚刚当选为英国保守党党首的里希苏纳克在白金汉宫接受英国国王查尔斯三世的正式任命,成为英国新任首相。20日,前首相伊丽莎白特拉斯6只硬科技即将同步上市!仅花40天就出道,多位牛散斥资千万捧场本周三(10月26日),6只剑指卡脖子难题的硬科技ETF将同步上市。这是一批从申报获批到发行成立上市都堪称神速的硬科技ETF。公开资料显示,这6只ETF均于9月16日上报,9月18CBA最新消息!易建联第一阶段报销,上海男篮要换帅,亚当斯回归凭借大胜上海男篮的比赛,广东宏远总算是暂时走出了困境,但易建联却连续两场比赛都没有出场,虽然官方给出的理由是轮休,但根据媒体人透露,易建联在与深圳男篮的比赛中受伤,并且前往医院进行东莞一女子送月嫂三室一厅被指炒作,当事人否认以前还送过车和月嫂相识一场缘分,月嫂的为人和处事我们都看得到,是我们彼此真心换真心得来的,现在给月嫂这套三室一厅,就是想让她多陪伴亲人!10月23日,广东东莞,一女子发视频称给月嫂送一套三室一澳门冠军赛单打八强出炉!国乒六人晋级,四大主力输掉三场外战2022年10月22日,乒乓球澳门冠军赛落入尾声,三个比赛日结束,单打八强出炉,国乒六人晋级,四位队员成功会师,四大主力出局输掉三场外战,仅林高远被队友梁靖崑淘汰,梁靖崑不敌法国小她是前多特蒙德体能教练,也是世界上最性感的运动员艾丽卡施密特,1998年出生于德国,是一名田径运动员。然而她被更多人熟知的,还是那个从一出道就伴随她的世界上最性感的运动员的称号。2017年,艾丽卡在德国20岁以下田径锦标赛中夺得世界重量级拳坛又出变数!约书亚改变计划,或与张君龙巅峰对决10月21日,据多家国际拳击媒体披露,前两度重量级世界拳王约书亚已经改变了想法,原计划他想在12月17日复出,选择一名合适的对手热身,但经过反复权衡后,约书亚已经放弃了12月比赛的
Java虚拟机GC的根识别堆空间中活跃对象,JVM内部实现优化引入GC的根垃圾回收的根和虚拟机运行时紧密结合,理解起来并不容易。需要回答两个问题哪些是垃圾回收的根?如何实现标记?以JVM为例,JVM为了能执行Java代码,实现了一套完整的编译解释阅读如何埋下美好生活的种子?不妨引导小读者学会精读近年来,全国500多家出版社几乎蜂涌抢滩亲子阅读市场,中国童书创作与出版势头发展迅猛,是近20年来出版业增长最快的板块之一。随着童书市场持续领跑,细分赛道竞争激烈,如何创造更多彰显临安,连续三年全省第一梯队!近日,省统计局和省科技厅联合发布了2021年度浙江省县(市区)科技进步统计监测报告,我区创新指数达182。8,为历年最高,位列全省第17位,连续三年进入全省第一梯队。浙江省科技进步老章谈关于淘宝售假处罚升级案例的观点大家好我是老章,昨天发的两个客户朋友售假违规的截图案例,引起了不少电商商家的疑问和讨论。目前为止所有的讨论都只是商家站在自己角度说的,对其他商家来说除了情绪共鸣就没有其他有价值的内捷尼赛思EGV70正式上市新车!售价38。58万起,对标特斯拉ModelY近日,小编从捷尼赛思汽车官方获悉,中型纯电动SUVEGV70正式上市,该车提供了两款车型,售价分别为38。58万元和43。98万元,接下来我们一起了解一下。外观方面,大尺寸的进气格彻底扯下苹果的遮羞布?多花钱去买AC,到底值不值?作为一个苹果手机的老粉丝,每次购买新手机的时候,就总会纠结一个问题,那就是究竟要不要去购买AC呢?毕竟要是没有AC的话,那苹果手机各种问题确实都没办法直接换新。但要是买的话,那多出神秘鲸在大规模加密交易中移动1,296,926,801,221柴犬(SHIB)一只加密鲸鱼在一次大规模交易中突然转移数量惊人的狗狗币(DOGE)竞争对手柴犬(SHIB)。根据区块链搜索引擎Etherscan的最新数据,这位财大气粗的交易员在撰写本文时将价值约最新进展!劳荣枝家属已确定死刑复核辩护律师11月30日,江西省高级人民法院对劳荣枝故意杀人抢劫绑架上诉一案进行二审公开宣判。江西省高院裁定驳回上诉,维持原判,对劳荣枝的死刑裁定依法报请最高人民法院核准。宣判后,劳荣枝当庭表欧洲共享电网面临崩溃险境,多国计划限制电力出口环球时报综合报道今年冬天,依靠共享电网的欧洲或将面临严峻电力危机。英国路透社12月4日报道称,法国总统马克龙呼吁居民减少使用能源,并重启核电站防止停电。据英国金融时报报道,未来几个发布到售罄不满2个月,法拉利首款SUV爆单我们停止接受新的订单已经不是什么秘密了,要知道这是基于我们尚未交付一辆车的情况下达成的成就。法拉利首席营销和商务官EnricoGalliera在就法拉利SUV车型Purosangu为什么有的孕妈3个月就显怀,有的7个月才显怀?和这些因素有关怀孕短短九个多月的时间里,孕妈的身材会有巨大的变化,体重也会有不小的增加。变化最大的部位莫过于孕妈们的肚子,随着怀孕天数的增加,她们的肚子也慢慢地像吹了气的气球一般膨胀起来。说起孕