Unity 接入有道智云AI - 文档翻译

2022-08-29 17:02:31 浏览数 (1)

一、接口介绍

文档翻译API接口提供有道的文档翻译服务,只需要通过调用文档翻译API,传入文档的Base64编码,指定源语言与目标语言,通过POST请求方式,就可以将文档中的文字内容进行翻译。

协议须知:

二、申请App ID、密钥

1.登录有道智云AI开放平台,进入控制台

2.在应用总览中创建应用,填写相关内容

3.获取应用ID、密钥

三、在Unity中应用

1. 定义请求数据结构

根据官方文档中接口调用参数说明定义对应的数据结构:

代码语言:javascript复制
/// <summary>
/// 上传请求数据结构
/// </summary>
public class UploadRequest
{
    /// <summary>
    /// 待翻译文档 Base64编码 大小限制40M
    /// </summary>
    public string q;
    /// <summary>
    /// 文档名称
    /// </summary>
    public string fileName;
    /// <summary>
    /// 文档类型
    /// docx/pdf/doc/jpg/png/bmp/ppt/pptx
    /// </summary>
    public string fileType;
    /// <summary>
    /// 源语言
    /// en/zh-CHS
    /// </summary>
    public string langFrom;
    /// <summary>
    /// 目标语言
    /// en/zh-CHS
    /// </summary>
    public string langTo;
    /// <summary>
    /// 应用ID
    /// </summary>
    public string appKey;
    /// <summary>
    /// UUID 唯一通用识别码
    /// </summary>
    public string salt;
    /// <summary>
    /// 当前UTC时间戳 单位秒
    /// </summary>
    public string curtime;
    /// <summary>
    /// 签名 sha256 应用ID input salt curtime 应用密钥
    /// </summary>
    public string sign;
    /// <summary>
    /// 服务器响应类型
    /// </summary>
    public string docType;
    /// <summary>
    /// 签名类型
    /// </summary>
    public string signType;

    public UploadRequest(string q, string fileName, string fileType, string langFrom, string langTo, string appKey, string secret)
    {
        this.fileName = fileName;
        this.fileType = fileType;
        this.langFrom = langFrom;
        this.langTo = langTo;
        this.appKey = appKey;
        salt = DateTime.Now.Millisecond.ToString();

        //获取时间戳
        TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        long mills = (long)ts.TotalMilliseconds;
        curtime = Convert.ToString(mills / 1000);

        //获取签名
        string input = q.Length <= 20 ? q : (q.Substring(0, 10)   q.Length   q.Substring(q.Length - 10, 10));
        string signStr = appKey   input   salt   curtime   secret;
        byte[] inputBytes = Encoding.UTF8.GetBytes(signStr);
        byte[] hashedBytes = new SHA256CryptoServiceProvider().ComputeHash(inputBytes);
        sign = BitConverter.ToString(hashedBytes).Replace("-", "");

        //UrlEncode编码
        this.q = HttpUtility.UrlEncode(q);

        docType = "json";
        signType = "v3";
    }

    public override string ToString()
    {
        return string.Format("q={0}&fileName={1}&fileType={2}&langFrom={3}&langTo={4}&appKey={5}&salt={6}&curtime={7}&sign={8}&docType={9}&signType={10}",
            q, fileName, fileType, langFrom, langTo, appKey, salt, curtime, sign, docType, signType);
    }
}
代码语言:javascript复制
/// <summary>
/// 进度查询请求数据结构
/// </summary>
public class QueryRequest
{
    /// <summary>
    /// 文档流水号
    /// </summary>
    public string flownumber;
    /// <summary>
    /// 应用ID
    /// </summary>
    public string appKey;
    /// <summary>
    /// UUID
    /// </summary>
    public string salt;
    /// <summary>
    /// 当前UTC时间戳
    /// </summary>
    public string curtime;
    /// <summary>
    /// 签名
    /// </summary>
    public string sign;
    /// <summary>
    /// 服务器响应类型
    /// </summary>
    public string docType;
    /// <summary>
    /// 签名类型
    /// </summary>
    public string signType;

    public QueryRequest(string flownumber, string appKey, string secret)
    {
        this.flownumber = flownumber;
        this.appKey = appKey;
        salt = DateTime.Now.Millisecond.ToString();

        //获取时间戳
        TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        long mills = (long)ts.TotalMilliseconds;
        curtime = Convert.ToString(mills / 1000);

        //获取签名
        string input = flownumber.Length <= 20 ? flownumber : (flownumber.Substring(0, 10)   flownumber.Length   flownumber.Substring(flownumber.Length - 10, 10));
        string signStr = appKey   input   salt   curtime   secret;
        byte[] inputBytes = Encoding.UTF8.GetBytes(signStr);
        byte[] hashedBytes = new SHA256CryptoServiceProvider().ComputeHash(inputBytes);
        sign = BitConverter.ToString(hashedBytes).Replace("-", "");

        docType = "json";
        signType = "v3";
    }

    public override string ToString()
    {
        return string.Format("flownumber={0}&appKey={1}&salt={2}&curtime={3}&sign={4}&docType={5}&signType={6}",
            flownumber, appKey, salt, curtime, sign, docType, signType);
    }
}
代码语言:javascript复制
/// <summary>
/// 文档下载请求数据结构
/// </summary>
public class DownloadRequest : QueryRequest
{
    /// <summary>
    /// 下载类型 word/ppt
    /// </summary>
    public string downloadFileType;

    public DownloadRequest(string downloadFileType, string flownumber, string appKey, string secret) : base(flownumber, appKey, secret)
    {
        this.downloadFileType = downloadFileType;
    }

    public override string ToString()
    {
        return string.Format("flownumber={0}&downloadFileType={1}&appKey={2}&salt={3}&curtime={4}&sign={5}&docType={6}&signType={7}",
            flownumber, downloadFileType, appKey, salt, curtime, sign, docType, signType);
    }
}

2.定义响应数据结构

根据官方文档中接口返回结果参数说明定义对应的数据结构:

代码语言:javascript复制
#region 响应数据结构
/// <summary>
/// 上传响应数据结构
/// </summary>
public class UploadResponse
{
    /// <summary>
    /// 错误码
    /// </summary>
    public string errorCode;
    /// <summary>
    /// 文档流水号
    /// </summary>
    public string flownumber;
}
/// <summary>
/// 进度查询响应数据结构
/// </summary>
public class QueryResponse
{
    /// <summary>
    /// 错误码
    /// </summary>
    public string errorCode;
    /// <summary>
    /// 进度状态码
    /// </summary>
    public string status;
    /// <summary>
    /// 进度状态描述
    /// </summary>
    public string statusString;
}
/// <summary>
/// 文档下载响应数据结构
/// </summary>
public class DownloadResponse
{
    /// <summary>
    /// 错误码
    /// </summary>
    public string errorCode;
}
#endregion

3.封装调用函数

代码语言:javascript复制
using System;
using System.IO;
using System.Net;
using System.Web;
using System.Text;
using UnityEngine;
using System.Security.Cryptography;

/// <summary>
/// 文档翻译
/// </summary>
public class FileTrans
{
    //应用ID和密钥 在有道智云AI开放平台创建应用获取
    private static readonly string appid = "";
    private static readonly string secret = "";

    public static UploadResponse Upload(string q, string fileName, string fileType, string langFrom, string langTo)
    {
        string url = "https://openapi.youdao.com/file_trans/upload";
        string result = "";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        string postData = new UploadRequest(q, fileName, fileType, langFrom, langTo, appid, secret).ToString();
        byte[] data = Encoding.UTF8.GetBytes(postData);
        request.ContentLength = data.Length;
        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(data, 0, data.Length);
            requestStream.Close();
        }
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        using(StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
        {
            result = reader.ReadToEnd();
        }
        Debug.Log("上传结果: "   result);
        return JsonUtility.FromJson<UploadResponse>(result);
    }

    public static QueryResponse Query(string flownumber)
    {
        string url = "https://openapi.youdao.com/file_trans/query";
        string result = "";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        string postData = new QueryRequest(flownumber, appid, secret).ToString();
        byte[] data = Encoding.UTF8.GetBytes(postData);
        request.ContentLength = data.Length;
        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(data, 0, data.Length);
            requestStream.Close();
        }
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
        {
            result = reader.ReadToEnd();
        }
        Debug.Log("查询结果: "   result);
        return JsonUtility.FromJson<QueryResponse>(result);
    }

    public static string Download(string flownumber, string downloadFileType)
    {
        string url = "https://openapi.youdao.com/file_trans/download";
        string result = "";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        string postData = new DownloadRequest(downloadFileType, flownumber, appid, secret).ToString();
        byte[] data = Encoding.UTF8.GetBytes(postData);
        request.ContentLength = data.Length;
        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(data, 0, data.Length);
            requestStream.Close();
        }
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
        {
            result = reader.ReadToEnd();
        }
        Debug.Log("下载结果: "   result);
        return result;
    }
}

4.测试

准备一个pdf英文文档

测试代码:

代码语言:javascript复制
using System;
using System.IO;
using UnityEngine;

public class FileTransExample : MonoBehaviour
{
    //用于记录文档流水号
    private string flownumber;

    private void OnGUI()
    {
        if(GUILayout.Button("上传", GUILayout.Width(200f), GUILayout.Height(50f)))
        {
            byte[] data = File.ReadAllBytes(Application.dataPath   "/test.pdf");
            string q = Convert.ToBase64String(data);
            var response = FileTrans.Upload(q, "test", "pdf", "en", "zh-CHS");
            flownumber = response.flownumber;
        }
        if (GUILayout.Button("查询", GUILayout.Width(200f), GUILayout.Height(50f)))
        {
            FileTrans.Query(flownumber);
        }
        if (GUILayout.Button("下载", GUILayout.Width(200f), GUILayout.Height(50f)))
        {
            FileTrans.Download(flownumber, "word");
        }
    }
}

上传结果:

查询结果:

下载结果:

0 人点赞