Use Raspberry Pi to implement chatbot _ PHP Tutorial

Source: Internet
Author: User
Use Raspberry Pi to implement chatbots. Raspberry Pi is used to implement a conversation robot. recently, Raspberry Pi is used to implement a robot that can communicate with people. RaspberryPi is the world's most popular micro-computer.
I recently used Raspberry Pi to implement a robot that can talk to people. I will give a brief introduction.

Raspberry Pi is the world's most popular micro-computer motherboard. it is a leading product of open-source hardware. it is designed for students in computer programming education, with only credit card sizes and low prices. Supports linux (debian) and other operating systems. The most important thing is comprehensive information and active community.
I use Raspberry Pi B +. The basic configuration is the BCM2836 processor, 4-core 900M clock speed, and 1G RAM.

My goal is to create a robot that talks to people. This requires robots to have input devices and output devices. The input device is a microphone, and the output can be HDMI, earphone, or audio. I use audio here. Below are my Raspberry Pi photos. The four USB interfaces are connected to wireless NICs, wireless keyboards, microphones, and audio power supplies.


We can divide robot conversations into three parts: listening, thinking, and speaking.
"Listen" is to record what people say and convert it into text.
"Thinking" means giving different outputs based on different inputs. For example, if the other party says "the current time", you can answer "the current time is Beijing time ".
"Speaking" refers to converting text into speech and playing it out.

These three parts involve a large number of speech recognition, speech synthesis, artificial intelligence and other technologies, which require a lot of time and effort to study. Fortunately, some companies have opened interfaces for customers. Here, I chose Baidu's API. The following describes the implementation of these three parts.

"Listen"

First, I recorded what people said. I used the arecord tool. The command is as follows:
  1. Arecord-D "plughw: 1"-f S16_LE-r 16000 test.wav
The-D parameter is followed by the recording device. after the microphone is connected, there are two devices on the Raspberry Pi: the internal device and the external usb device. plughw: 1 indicates that the external device is used. -F indicates the recording format, and-r indicates the audio sampling frequency. As the Baidu speech recognition mentioned later requires the audio file format, we need to record it into a compliant format. In addition, I didn't specify the recording time here. it keeps recording until the user presses ctrl-c. The audio files behind the recording are saved as test.wav.
Next, we will convert audio into text, that is, asr. Baidu's open speech platform provides free services and supports REST APIs.
See http://yuyin.baidu.com/docs/asr/57 for documentation
The process is basically to get the token, and send the speech information, voice data, and token to Baidu's speech recognition server to get the corresponding text. Because the server supports REST APIs, we can use any language to implement client code. here we use python
 
 
  1. # coding: utf-8

  2. import urllib.request
  3. import json
  4. import base64
  5. import sys

  6. def get_access_token():
  7. url = "https://openapi.baidu.com/oauth/2.0/token"
  8. grant_type = "client_credentials"
  9. client_id = "xxxxxxxxxxxxxxxxxx"
  10. client_secret = "xxxxxxxxxxxxxxxxxxxxxx"

  11. url = url + "?" + "grant_type=" + grant_type + "&" + "client_id=" + client_id + "&" + "client_secret=" + client_secret

  12. resp = urllib.request.urlopen(url).read()
  13. data = json.loads(resp.decode("utf-8"))
  14. return data["access_token"]


  15. def baidu_asr(data, id, token):
  16. speech_data = base64.b64encode(data).decode("utf-8")
  17. speech_length = len(data)

  18. post_data = {
  19. "format" : "wav",
  20. "rate" : 16000,
  21. "channel" : 1,
  22. "cuid" : id,
  23. "token" : token,
  24. "speech" : speech_data,
  25. "len" : speech_length
  26. }

  27. url = "http://vop.baidu.com/server_api"
  28. json_data = json.dumps(post_data).encode("utf-8")
  29. json_length = len(json_data)
  30. #print(json_data)

  31. req = urllib.request.Request(url, data = json_data)
  32. req.add_header("Content-Type", "application/json")
  33. req.add_header("Content-Length", json_length)

  34. print("asr start request\n")
  35. resp = urllib.request.urlopen(req)
  36. print("asr finish request\n")
  37. resp = resp.read()
  38. resp_data = json.loads(resp.decode("utf-8"))
  39. if resp_data["err_no"] == 0:
  40. return resp_data["result"]
  41. else:
  42. print(resp_data)
  43. return None

  44. def asr_main(filename):
  45. f = open(filename, "rb")
  46. audio_data = f.read()
  47. f.close()

  48. #token = get_access_token()
  49. token = "xxxxxxxxxxxxxxxxxx"
  50. uuid = "xxxx"
  51. resp = baidu_asr(audio_data, uuid, token)
  52. print(resp[0])
  53. return resp[0]


"Thinking"
Here I use the Turing Robot of Baidu api store. See the document: http://apistore.baidu.com/apiworks/servicedetail/736.html
It is very simple to use and will not be described here. the code is as follows:
 
 
  1. import urllib.request
  2. import sys
  3. import json

  4. def robot_main(words):
  5. url = "http://apis.baidu.com/turing/turing/turing?"

  6. key = "879a6cb3afb84dbf4fc84a1df2ab7319"
  7. userid = "1000"

  8. words = urllib.parse.quote(words)
  9. url = url + "key=" + key + "&info=" + words + "&userid=" + userid

  10. req = urllib.request.Request(url)
  11. req.add_header("apikey", "xxxxxxxxxxxxxxxxxxxxxxxxxx")

  12. print("robot start request")
  13. resp = urllib.request.urlopen(req)
  14. print("robot stop request")
  15. content = resp.read()
  16. if content:
  17. data = json.loads(content.decode("utf-8"))
  18. print(data["text"])
  19. return data["text"]
  20. else:
  21. return None


"Say"
First, you need to convert the text into speech, that is, speech synthesis (tts ). Then play the sound.
The open speech platform of Baidu provides the tts interface and can be used to configure the voice, tone, speed, and volume of men and women. The server returns audio data in mp3 format. We write data into the file in binary mode.
See http://yuyin.baidu.com/docs/tts/136
The code is as follows:
 
 
  1. # coding: utf-8

  2. import urllib.request
  3. import json
  4. import sys

  5. def baidu_tts_by_post(data, id, token):
  6. post_data = {
  7. "tex" : data,
  8. "lan" : "zh",
  9. "ctp" : 1,
  10. "cuid" : id,
  11. "tok" : token,
  12. }

  13. url = "http://tsn.baidu.com/text2audio"
  14. post_data = urllib.parse.urlencode(post_data).encode('utf-8')
  15. #print(post_data)
  16. req = urllib.request.Request(url, data = post_data)

  17. print("tts start request")
  18. resp = urllib.request.urlopen(req)
  19. print("tts finish request")
  20. resp = resp.read()
  21. return resp

  22. def tts_main(filename, words):
  23. token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
  24. text = urllib.parse.quote(words)
  25. uuid = "xxxx"
  26. resp = baidu_tts_by_post(text, uuid, token)

  27. f = open("test.mp3", "wb")
  28. f.write(resp)
  29. f.close()

After obtaining the audio file, you can use the mpg123 player to play the video.
  1. Mpg123 test.pdf


Integration
Finally, combine the three parts.
You can first integrate python-related code into main. py, as shown below:
 
 
  1. import asr
  2. import tts
  3. import robot

  4. words = asr.asr_main("test.wav")
  5. new_words = robot.robot_main(words)
  6. tts.tts_main("test.mp3", new_words)

Use the script to call related tools:
  1. #! /Bin/bash
  2. Arecord-D "plughw: 1"-f S16_LE-r 16000 test.wav
  3. Python3 main. py
  4. Mpg123 test.pdf


Now you can talk to the robot. Run the script, say something to the microphone, and press ctrl-c. Then the robot will reply to you.

Vivo recently used Raspberry Pi to implement a robot that can talk to people. Raspberry Pi is the world's most popular micro-computer...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.