小程序实现文字情绪识别并生成参考回复,从此不怕说错话

一、文章前言

此文主要通过小程序实现检测日常沟通文本背后所蕴含的情绪,针对正面和负面的情绪,还可给出参考话术。

在这里插入图片描述

二、具体流程及准备

2.1、注册百度开放平台及微信公众平台账号。
2.2、下载及安装微信Web开发者工具。
2.3、如需通过SDK调用及需准备对应语言的开发工具。

三、开发步骤

3.1、访问百度开放平台左侧产品服务中选择自然语言处理。
在这里插入图片描述
3.2、选择领取免费资源并填写对应的表单信息创建应用。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
3.3、创建完毕后回到应用列表,将API Key 以及Serect Key复制出来,后面我们需要通过这些凭证来获取Token。
在这里插入图片描述

在这里插入图片描述

3.4、信息准备好后,打开微信开发者工具,新建项目,选择不使用模板、不使用云服务。
在这里插入图片描述
3.5、在pages文件夹下面创建一个文件夹并新建对应的page文件。
在这里插入图片描述
3.6、在JS文件中的onLoad函数中请求获取Token的接口,这时候就需要用到上面刚才所申请的ApiKey等信息。

在这里插入图片描述
在这里插入图片描述

/**
 * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
    
    let that = this;
    let ApiKey='这里填你所申请的ApiKey';
    let SecretKey='这里填你所申请的SecretKey';
    wx.request({
    
    
      url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + ApiKey+'&client_secret='+SecretKey,
      method: 'POST',
      success: function (res) {
    
    
        that.setData({
    
    
          AccessToken:res.data.access_token
        });
      }
    });
  },

3.7、编译程序,检查接口是否有正常返回并将返回的token字段赋值给data里面所定义的token,下图所标记的字段就是我们所需要的token了,它的有效期为30天,到期了记得及时更新。
在这里插入图片描述
在这里插入图片描述
3.8、查看对话情绪识别接口请求说明及注意事项。

  • 请求体格式化:Content-Type为application/json,使用JSON格式的结构体来描述一个请求的具体内容。
  • body整体文本内容可以支持GBK和UTF-8两种格式的编码。
参数 是否必选 类型 说明
text string 待识别情感文本,输入限制512字节
scene string default(默认项-不区分场景),talk(闲聊对话-如度秘聊天等),task(任务型对话-如导航对话等),customer_service(客服对话-如电信/银行客服等)
{
    
    
    "scene":"talk",
    "text": "本来今天高高兴兴"
}

3.9、因为接口请求的scene参数给出了四个选项,所以我们需要在界面上实现一个选项卡以及给用户输入文字的入口。

在JS中定义数组,数据如下,sceneIndex为选中的下标

sceneData: [{
      title: '默认',
      value: 'default'
    }, {
      title: '闲聊对话',
      value: 'talk'
    }, {
      title: '任务型对话',
      value: 'task'
    }, {
      title: '客服对话',
      value: 'customer_service'
    }],
    sceneIndex: 0,
在wxml实现picker选项卡以及用于用户输入文字的区域。

在这里插入图片描述

<view class="box">
  <view class="title">请选择场景:</view>
  <picker class="title" bindchange="bindViewEvent" data-model="component" bindchange="bindSelect" data-name="index" value='{
    
    {sceneIndex}}' range="{
    
    {sceneData}}" range-key="title">
    <view class="label-right">
      {
    
    {
    
    sceneData[sceneIndex].title}}
    </view>
  </picker>
</view>
<textarea class="textArea" bindinput="gettext"></textarea>
.box{
  display: flex;
}
.title{
  color:#2B79F5;font-size:32rpx;margin-left:24rpx;
}
.textArea{
  margin-left:24rpx;margin-top:24rpx;width:702rpx;border:5rpx solid #999999;border-radius:10rpx;height:150rpx;
}
.rightBtn{
  width:181rpx;
  height:62rpx;
  color:white;
  border:1rpx solid #4FAFF2;
  border-radius:10rpx;
  text-align: center;
  line-height:62rpx;
  font-size:28rpx;
  margin-left: 24rpx;
  background:#4FAFF2;
  margin-top:24rpx;
}
.Detail{
  margin-top:24rpx;
}

3.10、当用户改变picker时,需要获取当前下标并给其赋值,所以需要给它加上对应的bindchange事件。

  bindSelect: function (e) {
    this.setData({
      sceneIndex: e.detail.value
    })
  },

3.11、同时当用户改变文本框的值时,也需要获取对应的值并存储到全局data变量中。

  gettext: function (e) {
   this.setData({
     text:e.detail.value
   });
  },

在这里插入图片描述
3.12、当大体界面呈现出来后,查看接口返回的字段解析并实现对应的接口请求。

参数 类型 说明
items list 分析结果数组
prob double 情绪一级分类标签对应的概率
label string 情绪分类标签;pessimistic(负向)、neutral(中性)、optimistic(正向)

3.12、给wxml情绪识别按钮绑定对应的响应事件来请求接口,这里要注意的是参数要以一个JSON格式的结构体来传递。

    let that = this;
    let requestData = {
    
    
      scene:that.data.sceneData[that.data.sceneIndex].value,
      text:that.data.text
    };
    wx.request({
    
    
      url: 'https://aip.baidubce.com/rpc/2.0/nlp/v1/emotion?access_token=' + that.data.token,
      method: 'POST',
      header: {
    
    
        'content-type': 'application/json'
      },
      data: requestData,
      success: function (identify) {
    
    
        that.setData({
    
    
          result:identify.data.items[0],
          isShowDetail: true,
        });
      }
    })

在这里插入图片描述

3.13、将接口所返回的识别结果在页面进行展示。

<view class="rightBtn" bindtap="getApiResult">情绪识别</view>
<view wx:if="{
    
    {isShowDetail}}" class="Detail">
  <view class="title">情绪概率:{
    
    {
    
    result.prob}}</view>
  <view class="title">情绪标签:
  {
    
    {
    
    result.label=='pessimistic'?'负向情绪':result.label=='neutral'?'中性情绪':'正向情绪'}}</view>
  <view class="title">参考话术:{
    
    {
    
    result.replies}}</view>
</view>

在这里插入图片描述

四、完整代码

<!--index.wxml-->

<view class="box">
  <view class="title">请选择场景:</view>
  <picker class="title" bindchange="bindViewEvent" data-model="component" bindchange="bindSelect" data-name="index" value='{
    
    {sceneIndex}}' range="{
    
    {sceneData}}" range-key="title">
    <view class="label-right">
      {
    
    {
    
    sceneData[sceneIndex].title}}
    </view>
  </picker>
</view>
<textarea class="textArea" bindinput="gettext"></textarea>

<view class="rightBtn" bindtap="getApiResult">情绪识别</view>
<view wx:if="{
    
    {isShowDetail}}" class="Detail">
  <view class="title">情绪概率:{
    
    {
    
    result.prob}}</view>
  <view class="title">情绪标签:
  {
    
    {
    
    result.label=='pessimistic'?'负向情绪':result.label=='neutral'?'中性情绪':'正向情绪'}}</view>
  <view class="title">参考话术:{
    
    {
    
    result.replies}}</view>
</view>


<!--index.wxss-->
/* pages/index/index.wxss */
.box{
    
    
  display: flex;
}
.title{
    
    
  color:#2B79F5;font-size:32rpx;margin-left:24rpx;
}
.textArea{
    
    
  margin-left:24rpx;margin-top:24rpx;width:702rpx;border:5rpx solid #999999;border-radius:10rpx;height:150rpx;
}
.rightBtn{
    
    
  width:181rpx;
  height:62rpx;
  color:white;
  border:1rpx solid #4FAFF2;
  border-radius:10rpx;
  text-align: center;
  line-height:62rpx;
  font-size:28rpx;
  margin-left: 24rpx;
  background:#4FAFF2;
  margin-top:24rpx;
}
.Detail{
    
    
  margin-top:24rpx;
}
  /**
   * 页面的初始数据
   */
  data: {
    
    
    token: '',
    sceneData: [{
    
    
      title: '默认',
      value: 'default'
    }, {
    
    
      title: '闲聊对话',
      value: 'talk'
    }, {
    
    
      title: '任务型对话',
      value: 'task'
    }, {
    
    
      title: '客服对话',
      value: 'customer_service'
    }],
    sceneIndex: 0,
    text:'',
    isShowDetail: false,
    result: {
    
    },
  },
let that = this;
    let grant_type = 'client_credentials';
    let client_id = '';
    let client_secret = '';
    wx.request({
    
    
      url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=' + grant_type + '&client_id=' + client_id + '&client_secret=' + client_secret,
      method: 'post',
      header: {
    
    
        'content-type': 'application/json'
      },
      success: function (res) {
    
    
        that.setData({
    
    
          token: res.data.access_token
        });
      }
    })
let that = this;
    let requestData = {
    
    
      scene:that.data.sceneData[that.data.sceneIndex].value,
      text:that.data.text
    };
    wx.request({
    
    
      url: 'https://aip.baidubce.com/rpc/2.0/nlp/v1/emotion?access_token=' + that.data.token,
      method: 'POST',
      header: {
    
    
        'content-type': 'application/json'
      },
      data: requestData,
      success: function (identify) {
    
    
        that.setData({
    
    
          result:identify.data.items[0],
          isShowDetail: true,
        });
        console.log(identify.data.items[0]);
      }
    })

猜你喜欢

转载自blog.csdn.net/weixin_42794881/article/details/127396189