前面实现了Unity调用百度的语音识别与语音合成之后呢,我想制作一个智能语音对话助手,本文就来实现智能人机对话(Unit)。
第一步还是在百度智能云平台上选择相应的模块(智能对话Unit)创建应用,具体的过程就不多赘述了,以下就直接切入正题。
(1)制作一个对话框UI
(2)获取Access Token,代码如下:
///
/// 获取accessToken请求令牌
///
///
IEnumerator _GetAccessToken()
{
var uri =
string.Format(
"https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id={0}&client_secret={1}",
api_key, secret_key);
UnityWebRequest unityWebRequest = UnityWebRequest.Get(uri);
yield return unityWebRequest.SendWebRequest();
if (unityWebRequest.isDone)
{
Match match = Regex.Match(unityWebRequest.downloadHandler.text, @"access_token.:.(.*?).,");
if (match.Success)
{
Debug.Log("Token已经匹配");
accessToken = match.Groups[1].ToString();
}
else
{
Debug.Log("验证错误,获取AccessToken失败!!!");
}
}
}
(3)其它逻辑编写以及智能对话Unit API的调用
///
/// NLP的人工智能对话功能
///
///
///
///
void Unit_NLP(string mysay, string session_id = "", string action_id = "")
{
string token = accessToken;
string host = "https://aip.baidubce.com/rpc/2.0/unit/service/chat?access_token=" + token;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
request.Method = "post";
request.ContentType = "application/json";
request.KeepAlive = true;
JsonData send = new JsonData();
send["version"] = "2.0";
send["service_id"] = "S27034";
send["log_id"] = "home";
send["session_id"] = "home";
send["action_id"] = "1017002";
send["request"] = new JsonData();
send["request"]["user_id"] = "88888";
send["request"]["query"] = mysay;
send["request"]["query_info"] = new JsonData();
send["request"]["query_info"]["type"] = "TEXT";
JsonData bot_session = new JsonData();
bot_session["session_id"] = "";
send["bot_session"] = JsonMapper.ToJson(bot_session);
string sendStr = JsonMapper.ToJson(send);
byte[] buffer = Encoding.UTF8.GetBytes(sendStr);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string result = reader.ReadToEnd();
JsonDecode(result);
}
(4)对返回的数据进行解析,获得对话内容
///
/// 对NLP的回复进行Json解析
///
///
///
public List<string> JsonDecode(string js)
{
List<string> Says = new List<string>();
var json = SimpleJson.SimpleJson.DeserializeObject<SimpleJson.JsonObject>(js);
if (json.ContainsKey("result"))
{
var result = (SimpleJson.JsonObject)json["result"];
if (result.ContainsKey("response_list"))
{
var resArray = (SimpleJson.JsonArray)result["response_list"];
var res = (SimpleJson.JsonObject)resArray[0];
if (res.ContainsKey("action_list"))
{
var actArray = (SimpleJson.JsonArray)res["action_list"];
var act = (SimpleJson.JsonObject)actArray[0];
if (act.ContainsKey("say"))
{
var say = (string)act["say"];
chat.AddChatMessage(say,ChatUI.enumChatMessageType.MessageLeft);
Says.Add(say);
}
}
}
}
return Says;
}
完整的代码如下:
using LitJson;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
public class NLPScript : MonoBehaviour
{
//自行填写自己的API密钥
public string api_key;
public string secret_key;
string accessToken = string.Empty;
InputField messagePanel;
ChatUI chat;//一个类似微信聊天的UI界面
// Start is called before the first frame update
void Start()
{
chat = GameObject.Find("Canvas/ChatUI").GetComponent<ChatUI>();
messagePanel = GameObject.Find("Canvas/ChatUI/InputArea/InputField").GetComponent<InputField>();
StartCoroutine(_GetAccessToken());
if (messagePanel!=null)
{
messagePanel.onEndEdit.AddListener(delegate
{
if (messagePanel.text == "")
return;
chat.AddChatMessage(messagePanel.text,ChatUI.enumChatMessageType.MessageRight);
Unit_NLP(messagePanel.text);
});
}
}
///
/// NLP的人工智能对话功能
///
///
///
///
void Unit_NLP(string mysay, string session_id = "", string action_id = "")
{
string token = accessToken;
string host = "https://aip.baidubce.com/rpc/2.0/unit/service/chat?access_token=" + token;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
request.Method = "post";
request.ContentType = "application/json";
request.KeepAlive = true;
JsonData send = new JsonData();
send["version"] = "2.0";
send["service_id"] = "S27034";
send["log_id"] = "home";
send["session_id"] = "home";
send["action_id"] = "1017002";
send["request"] = new JsonData();
send["request"]["user_id"] = "88888";
send["request"]["query"] = mysay;
send["request"]["query_info"] = new JsonData();
send["request"]["query_info"]["type"] = "TEXT";
JsonData bot_session = new JsonData();
bot_session["session_id"] = "";
send["bot_session"] = JsonMapper.ToJson(bot_session);
string sendStr = JsonMapper.ToJson(send);
byte[] buffer = Encoding.UTF8.GetBytes(sendStr);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string result = reader.ReadToEnd();
JsonDecode(result);
}
///
/// 对NLP的回复进行Json解析
///
///
///
public List<string> JsonDecode(string js)
{
List<string> Says = new List<string>();
var json = SimpleJson.SimpleJson.DeserializeObject<SimpleJson.JsonObject>(js);
if (json.ContainsKey("result"))
{
var result = (SimpleJson.JsonObject)json["result"];
if (result.ContainsKey("response_list"))
{
var resArray = (SimpleJson.JsonArray)result["response_list"];
var res = (SimpleJson.JsonObject)resArray[0];
if (res.ContainsKey("action_list"))
{
var actArray = (SimpleJson.JsonArray)res["action_list"];
var act = (SimpleJson.JsonObject)actArray[0];
if (act.ContainsKey("say"))
{
var say = (string)act["say"];
chat.AddChatMessage(say,ChatUI.enumChatMessageType.MessageLeft);
Says.Add(say);
}
}
}
}
return Says;
}
///
/// 获取accessToken请求令牌
///
///
IEnumerator _GetAccessToken()
{
var uri =
string.Format(
"https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id={0}&client_secret={1}",
api_key, secret_key);
UnityWebRequest unityWebRequest = UnityWebRequest.Get(uri);
yield return unityWebRequest.SendWebRequest();
if (unityWebRequest.isDone)
{
Match match = Regex.Match(unityWebRequest.downloadHandler.text, @"access_token.:.(.*?).,");
if (match.Success)
{
Debug.Log("Token已经匹配");
accessToken = match.Groups[1].ToString();
}
else
{
Debug.Log("验证错误,获取AccessToken失败!!!");
}
}
}
}