Use Python3 to call Baidu AI and Turing Robot to realize a smart (bushi) AI chatbot

The topic seems to be tall, but in fact this is just an illusion. The key is to clarify the thinking and process. After mastering this, the whole project is basically simplified into a "dumb" project, which requires less programming ability.

Ideas and processes

Be sure to figure out this process and don't be stunned.
Insert picture description here

Complete code

Among them, the Baidu AI speech recognition API parameters in step 2 and the Turing robot parameters in step 3 must be modified to their own account. If you want to modify other parameters, first go to the Baidu AI open platform and Turing Robot official website to read the technical documents .

from aip import AipSpeech
import requests
import json
import speech_recognition as sr
import win32com.client

# 1、人类说出问题,生成问题音频
speaker = win32com.client.Dispatch("SAPI.SpVoice")


def my_record(rate=16000):
    r = sr.Recognizer()
    with sr.Microphone(sample_rate=rate) as source:
        print("please say something")
        audio = r.listen(source)

    with open("voices.wav", "wb") as f:
        f.write(audio.get_wav_data())

# 2、问题音频文件转成问题文本
#    导入我们需要的模块,然后将音频文件发送出去,返回文本
#    百度语音识别API配置参数
APP_ID = '你自己的AppID'
API_KEY = '你自己的API Key'
SECRET_KEY = '你自己的Secret Key'
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
path = "voices.wav"


# 将语音转文本STT
def listen():
    with open(path, 'rb') as fp:
        voices = fp.read()
    try:
        result = client.asr(voices, 'wav', 16000, {
    
    'dev_pid': 1537, }) # 'dev_pid'参数1537是识别普通话,也可以设置成其他语言,详情见       
                                                                          百度AI开放平台
        result_text = result["result"][0]
        print("you said: " + result_text)
        return result_text
    except KeyError:
        print("KeyError")
        speaker.Speak("我没有听清楚,请再说一遍...")


# 3、与机器人对话:调用的是图灵机器人
#    图灵机器人的API_KEY、API_URL配置
turing_api_key = "你自己机器人的apikey"
api_url = "http://openapi.tuling123.com/openapi/api/v2"  # 图灵机器人api网址
headers = {
    
    'Content-Type': 'application/json;charset=UTF-8'}


# 图灵机器人回复
def Turing(text_words=""):
    req = {
    
    
        "reqType": 0,
        "perception": {
    
    
            "inputText": {
    
    
                "text": text_words
            },

            "selfInfo": {
    
    
                "location": {
    
    
                    "city": "扬州",  # 必须有的参数
                    "province": "可有可无的参数",
                    "street": "可有可无的参数"
                }
            }
        },
        "userInfo": {
    
    
            "apiKey": turing_api_key,  # 你的图灵机器人apiKey
            "userId": "Stephanie"  # 用户唯一标识(随便填,非密钥)
        }
    }

    req["perception"]["inputText"]["text"] = text_words
    response2 = requests.request("post", api_url, json=req, headers=headers)
    response_dict = json.loads(response2.text)

    result = response_dict["results"][0]["values"]["text"]
    print("AI Robot said:" + result)
    return result


while True:
    my_record()
    request1 = listen()
    response = Turing(request1)
# 4、回复文本转成回复音频输出,回复问题
    speaker.Speak(response)

Achievement demonstration video

Chatting with the AI ​​robot I wrote gradually went beyond the script and evolved into two elementary school chickens arguing and two children arguing about the day, but the AI ​​can only be so angry that it is speechless.

Homemade Funny New Year Movies | "I, Robot 2-Two Children's Debate Day"

Experience

  1. detail! detail! detail! details make a difference. The ancients did not deceive me either. I have been working on this code for many days, and it has been running with problems, and I have not been able to find any bugs. I was so downhearted that I thought: I and this mentally retarded robot must be crazy first. In the end, I found that the problem actually appeared in the spelling of a parameter name! It's a tiny detail of lowercase i and uppercase I! This lesson also reflects the importance of copy and paste (bushi) to a certain extent. For this API call alone, Baidu and Turing Robot’s official website have given specific and detailed API call codes. We can copy and paste it and run it to see if it can be successful, and then personalize ourselves based on the understanding of the code. Modifications.
  2. Although API calls are in the field of AI, the actual requirements for programming technology are not high. It is suitable for pretending to be B in front of laymen, or as a performance (dog head) in front of relatives and family members during the Chinese New Year.
  3. Don't be afraid of difficulties. For example, when the studio assigns this homework, before I actually start to do this thing, all I have in my mind are: What? I have only been in contact with programming for more than a year, so you want me to come out this whole thing? You praised me too much...this is an impossible task...but when I had to bite the bullet a week before the deadline, I found out, that's it? That's it? So, believe in yourself! Young people, don't talk about martial ethics, you'll be done rushing, holding back questioning yourself all day, thinking about these useless things, and you can't walk far.

Guess you like

Origin blog.csdn.net/m0_51210480/article/details/111924648