关于人工智能:微软小冰的颜值鉴定接口

44次阅读

共计 2856 个字符,预计需要花费 8 分钟才能阅读完成。

把我的老铁机器人的颜值鉴定接口源码放进去,逻辑都在 execute 函数外面,看不懂也不解释了。

const sharp = require('sharp')
const _ = require('lodash')

const {sendMsg, Recent, localPic} = require('../qq_api')
const {rp, UA, auraCdChk, num} = require('../utils')

module.exports = {
  name: '颜值',
  tags: ['exec', 'aura', 'group', 'cd'],
  keywords: ['难看吗'],
  usage: ['(发照片后)[botNick_] 颜值鉴定', '我难看吗?', '@某用户 难看吗'],
  value: {冷却工夫: { def: '20 秒', chk: auraCdChk} },
  help: '给照片中人物的颜值打分。AT 某用户可鉴定他 / 她的头像,发送“我难看吗”则鉴定本人的头像。\n☍ 数据接口:微软小冰 https://ux.xiaoice.com/beautyv3',
  execute: async ({name, bot, user, msg: { content: cont, ats = [], pics: [pic] = []}, g }) => {cont = cont.replace(/( 鉴定 | 的 |\?|?)/, '')
    if (cont === '我' || ats.length) {const q = cont === '我' ? user : ats[0]
      pic = {url: `http://q1.qlogo.cn/g?b=qq&nk=${q}&s=640` }
    } else if (!pic) {pic = await Recent.get('pic', user, g)
      if (!pic) { // 须要补发照片
        Recent.set('cmd', user, g, name)
        return sendMsg(bot, g, user, '[at] 颜值鉴定须要你提供蕴含人脸的照片,请在 20 秒内收回'), 'WAITING_PIC' // eslint-disable-line
      }
      Recent.del('pic', user, g)
    }
    ;(async () => { // 异步执行,防止指令执行工夫过长
      try {
        const opts = {jar: rp.jar(),
          headers: {'User-Agent': UA}
        }
        let [res, buf] = await Promise.all([rp.head('https://ux.xiaoice.com/beautyv3', opts), // 小冰颜值首页,拜访此页面仅用于填充 cookies,HEAD 比 GET 速度更快
          rp.get(pic.url, { encoding: null})]) // 获取图像数据
        // 从 cookies 中提取 TraceId 参数
        const TraceId = JSON.parse(decodeURIComponent(opts.jar.getCookies('http://ux.xiaoice.com').find(c => c.key === 'logInfo').value)).tid
        // 对非动画 gif,大于 200K 或大于 30 万像素的,则放大至 30 万像素以节俭流量
        const img = sharp(buf)
        const {format, width, height} = await img.metadata()
        if (format !== 'gif' && ((buf.length > 200000) || width * height > 300000)) {const nw = ~~Math.sqrt(width * 300000 / height)
          if (nw < width) buf = await img.resize(nw).jpeg({quality: 75, chromaSubsampling: '4:2:0'}).toBuffer()}
        // base64 形式上传图片
        _.merge(opts, {headers: { 'Content-Type': 'application/x-www-form-urlencoded', Referer: 'https://ux.xiaoice.com/beautyv3'},
          body: buf.toString('base64')
        })
        res = await rp.post('https://ux.xiaoice.com/api/image/UploadBase64?exp=1', opts)
        res = JSON.parse(res) // 应答体 JSON 格局,蕴含上传后的图片 host 和 uri
        const MsgId = Date.now()
        // 调用颜值鉴定接口,个别须要 10 秒以上,需设定较长的超时工夫
        _.merge(opts, {
          json: true,
          timeout: 45000,
          headers: {'Content-Type': 'application/json'},
          body: {MsgId, CreateTime: ~~(MsgId / 1000), TraceId, Content: {imageUrl: res.Host + res.Url} }
        })
        res = await rp.post('https://ux.xiaoice.com/api/imageAnalyze/Process?service=beauty', opts)
        // 胜利获取到鉴定后果
        const {imageUrl, metadata, text} = res.content
        let txt = text
        if (metadata.score) {txt = `???? 下面 ${{ male: '帅哥', female: '美女'}[metadata.gender]} 的颜值有 ${metadata.score} 分!????`
          if (metadata.FBR_Cnt) {const fbr = Object.entries(metadata).reduce((o, [k, v]) => {const mch = /^FBR_(Key|Score)(\d+)$/.exec(k)
              if (mch) (o[+mch[2]] = o[+mch[2]] || {})[mch[1]] = v
              return o
            }, [])
            txt += `\n 评分详情:\n${num(fbr.map(f => `${f.Key}:${f.Score} 分 `)).join('\n')}`
          }
          txt += `\n⭐${text}`
          if (metadata.Comment_Improve) txt += `\n????${metadata.Comment_Improve}`
        }
        const lpic = await localPic(imageUrl)
        sendMsg(bot, g, user, txt, lpic)
      } catch (e) {sendMsg(bot, g, user, `[at] 颜值鉴定失败,谬误:${e.message}`)
      }
    })()
    return sendMsg(bot, g, user, `[at] 正在鉴定颜值,大概须要 20~30 秒,请稍候 `), 'OK' // eslint-disable-line
  }
}

正文完
 0