当前位置: 首页 > article >正文

Unity阿里云OpenAPI 获取 Token的C#【记录】

获取Token


using UnityEngine;
using System;
using System.Text;
using System.Linq;
using Newtonsoft.Json.Linq;  
using System.Security.Cryptography;
using UnityEngine.Networking;
using System.Collections.Generic;
using System.Globalization;
using Cysharp.Threading.Tasks;

#if UNITY_EDITOR
using UnityEditor;
#endif

/// <summary>
/// 获取阿里云的 Token 的代码
/// </summary>
public class AliTTSCtrl : MonoBehaviour
{
    private readonly string accessKeyId = "********"; 
    private readonly string accessKeySecret = "********"; 

    private readonly string accessKey = "********";
    private readonly string account = "********";

    private readonly string regionId = "cn-shanghai";
    private readonly string version = "2019-02-28";
    private readonly string action = "CreateToken";
    private readonly string formatType = "JSON";
    private readonly string signatureMethod = "HMAC-SHA1";
    private readonly string signatureVersion = "1.0";

    private DateTime expirationTime = DateTime.MinValue;

    void Start()
    {
       
    }

 
    // 获取当前有效的 Token
    [ContextMenu("获取 Token")]
#if UNITY_EDITOR
    [ExecuteInEditMode]
#endif
    public async UniTask<string> GetToken()
    {
        try {

            var res = CheckTokenExpireTime();
            if (res.Item1)
            {
                return res.Item2;
            }
            else
            {
                //StartCoroutine(RefreshToken());
                var token = await PostTokenRequest();
                // 如果正在刷新 Token,可以考虑返回空字符串或者等待刷新完成
                return token;
            }
        }catch(Exception e)
        {
            Debug.LogError($"错误: {e}");
        }
       
        
        throw new NullReferenceException("Token 无法获取");
    }

    /// <summary>
    /// 检查Token是否过期或者不存在
    /// </summary>
    /// <returns></returns>
    private (bool, string) CheckTokenExpireTime()
    {
        string tokenString = PlayerPrefs.GetString(accessKeyId, "");
        if (!string.IsNullOrEmpty(tokenString))
        {
            JObject token = JObject.Parse(tokenString);
            long expireTime = token["ExpireTime"].Value<long>();
            long currentTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
            long timeLeft = expireTime - currentTime;

            string tokenID = token["Id"].Value<string>();

            if (timeLeft < 86400) // 24小时 = 86400秒
            {
                Debug.Log("Token 将在24小时内过期  True");
                return (false, null);
            }
            else
            {
                Debug.Log("Token 还可以使用 False");
                return (true, tokenID);
            }
        }
        return (false, null);
    }

    async UniTask<string> PostTokenRequest()
    {
        // 获取当前时间戳
        string timestamp =   DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);

        // 生成随机数
        string signatureNonce =  Guid.NewGuid().ToString();

        // 构建请求参数字典 
        var parameters = new Dictionary<string, string>
        {
            { "AccessKeyId", accessKeyId },
            { "Action", action },
            { "Format", formatType },
            { "RegionId", regionId },
            { "SignatureMethod", signatureMethod },
            { "SignatureNonce", signatureNonce },
            { "SignatureVersion", signatureVersion },
            { "Timestamp", timestamp},
            { "Version", version }
        };

        // 排序并构建规范化的查询字符串
        string queryString = EncodeDictionary(parameters);
        //Debug.Log("规范化的请求字符串: " + queryString);

        string stringToSign = "GET&" + EncodeText("/") + "&" + EncodeText(queryString);
        //Debug.Log("待签名的字符串: " + stringToSign);


        string signature = CalculateSignature(accessKeySecret, stringToSign);
        //Debug.Log("签名: " + signature);

        signature = EncodeText(signature);
        //Debug.Log("URL编码后的签名: " + signature);

        // 构建最终 URL
        string url = $"https://nls-meta.cn-shanghai.aliyuncs.com/?Signature={signature}&{queryString}";
        //Debug.Log("url: " + url);

      
        using (UnityWebRequest www = UnityWebRequest.Get(url))
        { 
            var asyncOp = www.SendWebRequest();

            await asyncOp;
           
            var header = www.GetResponseHeaders();
            string headerStr = "";

            headerStr += www.uri.Host+"\n";
            //headerStr += www.uri. + "\n";

            foreach (var head in header)
            {
                headerStr += $"{head.Key} : {head.Value} \n";
            }

            Debug.Log($"请求 Response: {headerStr}");
            //await www.SendWebRequest();

            if (www.result != UnityWebRequest.Result.Success)
            {
                string textData = www.downloadHandler.text;
                Debug.LogError($"请求错误 Error:{www.result} +  {www.error} -> {textData}");
            }
            else
            {
                // 解析返回的 JSON 数据
                string jsonResponse = www.downloadHandler.text;
                Debug.Log($"请求成功 Response: {jsonResponse}");

                JObject json = JObject.Parse(jsonResponse);
                JToken token = json["Token"];
                if (token != null && token["ExpireTime"] != null && token["Id"] != null)
                {
                    // 缓存 Token 数据
                    PlayerPrefs.SetString(accessKeyId, token.ToString());
                    PlayerPrefs.Save();

                    long expireTime = token["ExpireTime"].Value<long>();
                    long currentTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds();


                    // 将 Unix 时间戳转换为 DateTime
                    DateTime expiryDateTime = DateTimeOffset.FromUnixTimeSeconds(expireTime).UtcDateTime;
                    DateTime currentDateTime = DateTimeOffset.FromUnixTimeSeconds(currentTime).UtcDateTime;
                    TimeSpan timeLeft = expiryDateTime - currentDateTime;

                     
                    string formattedTime = $"{timeLeft.Days}{timeLeft.Hours}小时 {timeLeft.Minutes}分钟 {timeLeft.Seconds}秒";

                    Debug.Log($"Token 数据保存成功 ; 当前时间:{currentDateTime.ToString("yyyy-MM-dd HH:mm:ss")} - 过期时间:{expiryDateTime.ToString("yyyy-MM-dd HH:mm:ss")} - 有效时长:{formattedTime}");
                    return token.ToString();
                }
                else
                {
                    Debug.Log("Token or required 的字段 不足或者丢失!");
                }
                 
            }

        }

        return "";
    }

    private string EncodeText(string text)
    {
        string encoded  =  UnityWebRequest.EscapeURL(text)
            .Replace("+", "%20")
            .Replace("*", "%2A")
            .Replace("%7E", "~")
            .Replace("%7E", "~");

        // 将所有小写十六进制代码转换为大写
        encoded = System.Text.RegularExpressions.Regex.Replace(encoded, "%[0-9a-f]{2}", m => m.Value.ToUpper());

        return encoded;
    }

    private string EncodeDictionary(Dictionary<string, string> dic)
    {
        var items = dic.OrderBy(kvp => kvp.Key).Select(kvp =>
            $"{EncodeText(kvp.Key)}={EncodeText(kvp.Value)}");
        return string.Join("&", items);
    }

 

    private string CalculateSignature(string accessKeySecret, string stringToSign)
    {
        // 将密钥字符串附加 "&" 后转换为字节
        var keyBytes = Encoding.UTF8.GetBytes(accessKeySecret + "&");
        // 将待签名字符串转换为字节
        var signBytes = Encoding.UTF8.GetBytes(stringToSign);

        using (var hmacsha1 = new HMACSHA1(keyBytes))
        {
            byte[] hashMessage = hmacsha1.ComputeHash(signBytes);
            string signature = Convert.ToBase64String(hashMessage);
            //signature = UnityWebRequest.EscapeURL(signature).Replace("+", "%20").Replace("*", "%2A").Replace("%7E", "~");

            return signature;// EncodeToUpper(signature);
        }
        
    }




 
}

使用阿里云 TTS

using System;
using UnityEngine;
//using NativeWebSocket;
using System.Text.RegularExpressions;
using System.Net.Http;
using System.IO;
using UnityEngine.Networking;
using System.Runtime.CompilerServices;
using Cysharp.Threading.Tasks;

//using System.Net.WebSockets;


//public static class UnityWebRequestExtensions
//{
//    public static TaskAwaiter<AsyncOperation> GetAwaiter(this UnityWebRequestAsyncOperation asyncOp)
//    {
//        TaskCompletionSource<AsyncOperation> tcs = new TaskCompletionSource<AsyncOperation>();
//        asyncOp.completed += obj => tcs.SetResult(asyncOp);
//        return tcs.Task.GetAwaiter();
//    }
//}

[Serializable]
public class Header
{
    public string message_id;
    public string task_id;
    public string @namespace;
    public string name;
    public string appkey;
}

public class VoiceSynthesis : MonoBehaviour
{
    private AliTTSCtrl aliTTSCtrl;

    private TTSGeneral tTSGeneral;
    private AudioSource audioSource;

    void Start()
    {
        aliTTSCtrl = GetComponent<AliTTSCtrl>();
        audioSource = GetComponent<AudioSource>();
    }

    // 获取当前有效的 Token
    [ContextMenu("进行TTS")]
#if UNITY_EDITOR
    [ExecuteInEditMode]
#endif
    private async UniTask TTS()
    {
        if (aliTTSCtrl == null)
        {
            aliTTSCtrl = GetComponent<AliTTSCtrl>();
        }
        if (audioSource == null)
        {
            audioSource = GetComponent<AudioSource>();
        }

        var token = await  aliTTSCtrl.GetToken();
        Debug.Log($"Token  {token}");
        if (tTSGeneral == null)
        {
            tTSGeneral = new TTSGeneral("******", token, audioSource);
        }

        await tTSGeneral.SpeakAsync();
    }



    void OnDestroy()
    {
        
    }

    private void OnApplicationQuit()
    {
        
    }
}


public class TTSGeneral
{

    private string appKey = "";  
    private string accessToken = "";
    private AudioSource audioSource;
    private string ttsUrl = "https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/tts";
    private string v;
    private UniTask<string> token;


    public TTSGeneral(
        string appKey,
        string accessToken,
        AudioSource audioSource)
    {
        this.appKey = appKey;
        this.accessToken = accessToken;
        this.audioSource = audioSource;
    }

    public async UniTask<string> SynthesizeSpeech(
        string text,
        string format = "wav",
        int sampleRate = 16000,
        string voice = "siyue")
    {
        try
        {
            using (var client = new HttpClient())
            {
                var url = $"{ttsUrl}?appkey={appKey}&token={accessToken}&text={Uri.EscapeDataString(text)}&format={format}&sample_rate={sampleRate}&voice={voice}";

                HttpResponseMessage response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode();

                byte[] audioBytes = await response.Content.ReadAsByteArrayAsync();

                // Save the audio file or play it directly in Unity
                string path = Path.Combine(Application.persistentDataPath, "output.wav");
                File.WriteAllBytes(path, audioBytes);

                return path;
            }
        }
        catch (Exception ex)
        {
            Debug.LogError($"Error synthesizing speech: {ex.Message}");
            throw;
        }
    }

    public async UniTask SpeakAsync()
    {
        string textToSpeak = "采用最先进的端到端语音识别框架,字错误率相比上一代系统相对下降10%至30%,并发推理速度相比业内主流推理推理框架提升10倍以上,同时支持实时和离线语音识别,毫秒级延迟。";
        string audioFilePath = null;
         
        try
        {
            audioFilePath = await SynthesizeSpeech(textToSpeak);
        }
        catch (Exception ex)
        {
            Debug.LogError($"Error during speech synthesis: {ex.Message}");
        }

        //audioFilePath = path.Result;

        if (!string.IsNullOrEmpty(audioFilePath))
        {
            // Load and play the audio file in Unity using UnityWebRequest
            using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip("file://" + audioFilePath, AudioType.WAV))
            {
                DownloadHandlerAudioClip downloadHandler = www.downloadHandler as DownloadHandlerAudioClip;
                downloadHandler.streamAudio = true; // Stream the audio to save memory

                await www.SendWebRequest();

                if (www.result == UnityWebRequest.Result.Success)
                {
                    AudioClip clip = downloadHandler.audioClip;
                   
                    if (audioSource != null)
                    {
                        audioSource.clip = clip;
                        audioSource.Play();
                    }
                    else
                    {
                        Debug.LogError($"必须有 AudioSource 组件才可以播放");
                    }
                }
                else
                {
                    Debug.LogError($"Failed to load audio file: {www.error}");
                }
            }
        }

           
    }
}


//public class TTSStream
//{
//    private WebSocket ws;
//    private bool isSynthesisStarted = false;

//    async void ConnectWebSocket()
//    {
//        // 替换为你的 WebSocket 服务地址和 Token
//        ws = new WebSocket("wss://nls-gateway-cn-beijing.aliyuncs.com/ws/v1?token=your-nls-token");
//        ws.OnOpen += () =>
//        {
//            Debug.Log("WebSocket connected!");
//            SendStartSynthesis();
//        };

//        ws.OnError += (e) =>
//        {
//            Debug.LogError("Error: " + e);
//        };
//        ws.OnClose += (e) =>
//        {
//            Debug.Log("WebSocket closed!");
//        };

//        ws.OnMessage += (bytes) =>
//        {
//            Debug.Log("Received message: " + bytes);
//        };

//         Keep sending messages at every 0.3s
//        //InvokeRepeating("SendWebSocketMessage", 0.0f, 0.3f);

//        await ws.Connect();
//    }

//    void Update()
//    {
//#if !UNITY_WEBGL || UNITY_EDITOR
//        if (ws != null)
//        {
//            ws.DispatchMessageQueue();

//        }

//#endif
//    }

//    async void SendWebSocketMessage()
//    {
//        if (ws.State == WebSocketState.Open)
//        {
//            // Sending bytes
//            await ws.Send(new byte[] { 10, 20, 30 });

//            // Sending plain text
//            await ws.SendText("plain text message");
//        }
//    }




//    private async void SendStartSynthesis()
//    {
//        var header = GetHeader("StartSynthesis");
//        var paramsJson = JsonUtility.ToJson(header);
//        await ws.SendText(paramsJson);
//    }

//    string GenerateUUID()
//    {
//        long d = DateTime.Now.Ticks;
//        long d2 = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds * 1000;
//        return Regex.Replace("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "[xy]", delegate (Match match)
//        {
//            int r = new System.Random().Next(16);
//            if (d > 0)
//            {
//                r = ((int)(d + r) % 16) | 0;
//                d = (long)Math.Floor(d / 16.0);
//            }
//            else
//            {
//                r = ((int)(d2 + r) % 16) | 0;
//                d2 = (long)Math.Floor(d2 / 16.0);
//            }
//            return (match.Value == "x" ? r : (r & 0x3 | 0x8)).ToString("x");
//        });
//    }


//    Header GetHeader(string name)
//    {
//        return new Header
//        {
//            message_id = GenerateUUID(),
//            task_id = GenerateUUID(), // 根据需要生成 task_id
//            @namespace = "FlowingSpeechSynthesizer",
//            name = name,
//            appkey = "your-nls-appkey"
//        };
//    }


//    public async void CloseWs()
//    {
//        if (ws != null)
//        {
//            await ws.Close();
//            ws = null;
//        }
//    }




//}

使用阿里云 OCR

using System;
using System.Collections;
using System.Collections.Generic;

using UnityEngine;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Imagine.WebAR;
using Cysharp.Threading.Tasks;
using Tea;
using AlibabaCloud.OpenApiClient.Models;
using AlibabaCloud.SDK.Ocr_api20210707.Models;
using AlibabaCloud.TeaUtil.Models;
using AlibabaCloud.SDK.Ocr_api20210707;
using AlibabaCloud.TeaUtil;
using AlibabaCloud.OpenApiClient;
using AlibabaCloud.OpenApiUtil;
using System.Reflection;

public class AliOCR : MonoBehaviour
{
    public Texture2D texture;
    public RenderTexture textureRender;
    private OCRUnified oCR;
    private TextureExtractor_WarpedImage warpedImage;

    private readonly string accessKeyId = "********"; 
    private readonly string accessKeySecret = "********";  


    // Start is called before the first frame update
    void Start()
    {
        if (oCR == null)
        {
            oCR = new OCRUnified(accessKeyId, accessKeySecret);
        }
        warpedImage = GetComponent<TextureExtractor_WarpedImage>();
    }

    public void OnImageFound(string id)
    {

        if (warpedImage == null)
        {
            warpedImage = GetComponent<TextureExtractor_WarpedImage>();
        }

        warpedImage.ExtractTexture(id);

        //string ocrContent  = await OCR();
        Debug.Log($"执行 OCR  识别.....");



        try
        {
            OCR(); // 启动但不等待

        }
        catch (Exception ex)
        {
            Debug.LogError("OCR failed 2 : " + ex.Message);

        }
    }

    public void OnImageLost(string id)
    {

    }





    // 获取当前有效的 Token
    [ContextMenu("进行ORC")]
#if UNITY_EDITOR
    [ExecuteInEditMode]
#endif
    private void OCR()
    {
        Debug.Log($"执行 OCR  识别2 .....");
        if (oCR == null)
        {
            oCR = new OCRUnified(accessKeyId, accessKeySecret);
        }

        try
        {
            //byte[] imageData = texture.EncodeToJPG();

            var imaStream = RenderTextureAsync();

            string res = oCR.Run(imaStream);

            //string res = await UniTask.Create(async () =>
            //{
            //    // 直接调用同步方法
            //    string result = oCR.Run(imaStream);
            //    await UniTask.Yield(); // 等待至少下一帧
            //    return result;
            //});


            if (res == "")
            {
                Debug.Log($"没有识别到任何文字:{res}");
            }
            else
            {
                Debug.Log($"识别到文字:{res}");
            }

            imaStream.Close();
            //return  res;
        }
        catch (Exception ex)
        {
            Debug.LogError("OCR failed2 : " + ex.Message);
            //return "OCR failed";  // 返回错误信息
        }

    }





    private Stream RenderTextureAsync()
    {
        // 等待渲染线程结束

        //await UniTask.WaitForEndOfFrame(this);

        // 临时激活渲染纹理的上下文
        RenderTexture.active = textureRender;

        // 创建一个新的 Texture2D 对象来接收像素
        Texture2D texture2D = new Texture2D(textureRender.width, textureRender.height, TextureFormat.RGB24, false);
        texture2D.ReadPixels(new Rect(0, 0, textureRender.width, textureRender.height), 0, 0);
        texture2D.Apply();

        // 重置渲染纹理的上下文
        RenderTexture.active = null;

        // 编码 Texture2D 数据为 JPG
        byte[] jpgData = texture2D.EncodeToJPG();

        // 释放 Texture2D 对象
#if UNITY_EDITOR
        DestroyImmediate(texture2D);
#else
        Destroy(texture2D);
#endif

        // 将 JPG 数据写入内存流
        //using (MemoryStream stream = new MemoryStream())
        //{
        //    stream.Write(jpgData, 0, jpgData.Length);
        //    return stream;
        //    // 这里可以添加额外的处理,如保存文件或发送数据
        //}

        return new MemoryStream(jpgData);
    }




}


/// <summary>
/// OCR 统一识别
/// </summary>
public class OCRUnified
{
    private AlibabaCloud.OpenApiClient.Client aliClient;
    private AlibabaCloud.SDK.Ocr_api20210707.Client aliClient2;

    public OCRUnified(string accessKeyId, string accessKeySecret)
    {
        aliClient = CreateClient(accessKeyId, accessKeySecret);
        aliClient2 = CreateClient2(accessKeyId, accessKeySecret);
    }


    public string Run(Stream textureBody)
    {
        try
        {

            Debug.Log($"执行 OCR  识别3 .....");

            AlibabaCloud.OpenApiClient.Models.Params params_ = CreateApiInfo();

            Debug.Log($" 1 OCR  创建 API 成功 .....");
            // query params
            Dictionary<string, object> queries = new Dictionary<string, object>() { };
            queries["Type"] = "Advanced";
            queries["OutputFigure"] = true;

            //byte[] imageData = texture.EncodeToJPG();

            // 需要安装额外的依赖库,直接点击下载完整工程即可看到所有依赖。
            //Stream body = new MemoryStream(imageData) ;//AlibabaCloud.DarabonbaStream.StreamUtil.ReadFromFilePath("<your-file-path>");
            // runtime options
            AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
            Debug.Log($" 2 OCR  创建 RuntimeOptions 成功 .....");
            AlibabaCloud.OpenApiClient.Models.OpenApiRequest request = new AlibabaCloud.OpenApiClient.Models.OpenApiRequest
            {
                Query = AlibabaCloud.OpenApiUtil.Client.Query(queries),
                Stream = textureBody,
            };

            Debug.Log($" 3 OCR  创建 OpenApiRequest 成功 .....");

            // 复制代码运行请自行打印 API 的返回值
            // 返回值实际为 Map 类型,可从 Map 中获得三类数据:响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。
            //Debug.Log($"执行 OCR  params_:{params_.ToString()} - request:{request} - runtime:{runtime}");
            Dictionary<string, object> res = null;
            try
            {
                Debug.Log($"params : {ConvertToJson(params_)}");
                Debug.Log($"request : {ConvertToJson(request)}");
                Debug.Log($"runtime : {ConvertToJson(runtime)}");
                res = aliClient.CallApi(params_, request, runtime); //new Dictionary<string, object>();

            }
            catch (Exception ex)
            {

                Debug.LogError($"CallApi 错误 {ex}");
            }



            Debug.Log($" 4 OCR  请求 成功 .....");

            string jsonString = JsonConvert.SerializeObject(res, Formatting.Indented);
            if (res.ContainsKey("statusCode"))
            {
                var statusCode = res["statusCode"];
                int code = int.Parse(statusCode.ToString());
                if (code == 200)
                {
                    // 打印 JSON 字符串到控制台
                    Debug.Log(jsonString);

                    // 将 JSON 字符串解析为 JObject
                    JObject jsonObject = JObject.Parse(jsonString);

                    // 从 JObject 获取 "Data" 下的 "Content"
                    string content = jsonObject["body"]["Data"]["Content"].ToString();

                    Debug.Log($"content = {content}");

                    return content;

                    //PrintDictionary(res);
                }
                else
                {
                    var strRes = $"识别异常 {code} -> {jsonString} ";
                    Debug.LogError(strRes);

                    return strRes;
                }
            }

            return $"不是有效的返回 {jsonString}";
        }
        catch (Exception ex)
        {
            var strRes = $"ORC 错误: {ex}";
            Debug.LogError(strRes);

            return strRes;
        }




    }

    public static string ConvertToJson(object obj)
    {
        var properties = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
        var result = new System.Text.StringBuilder();
        result.Append("{");

        bool first = true;
        foreach (var property in properties)
        {
            if (!first)
            {
                result.Append(", ");
            }
            else
            {
                first = false;
            }

            try
            {
                var value = property.GetValue(obj, null);
                string jsonValue = value != null ? value.ToString() : "null";
                result.AppendFormat("\"{0}\": {1}", property.Name, jsonValue);
            }
            catch (Exception ex)
            {
                // Handle the exception if the property cannot be serialized to JSON
                result.AppendFormat("\"{0}\": \"Error: {1}\"", property.Name, ex.Message);
            }
        }

        result.Append("}");
        return result.ToString();
    }

    public static void PrintJson(object obj)
    {
        Debug.Log(ConvertToJson(obj));
    }

    // 打印字典的方法
    //void PrintDictionary(Dictionary<string, object> dictionary)
    //{
    //    foreach (KeyValuePair<string, object> entry in dictionary)
    //    {
    //        // 检查值的类型,如果是列表或数组,需要特别处理
    //        if (entry.Value is List<string>)
    //        {
    //            List<string> list = entry.Value as List<string>;
    //            Debug.Log(entry.Key + ": [" + string.Join(", ", list) + "]");
    //        }
    //        else
    //        {
    //            Debug.Log(entry.Key + ": " + entry.Value);
    //        }
    //    }
    //}



    /// <term><b>Description:</b></term>
    /// <description>
    /// <para>使用AK&amp;SK初始化账号Client</para>
    public AlibabaCloud.OpenApiClient.Client CreateClient(string accessKeyId, string accessKeySecret)
    {
        // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378671.html。
        AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
        {
            // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
            AccessKeyId = accessKeyId,// Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
            // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
            AccessKeySecret = accessKeySecret //Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
        };
        // Endpoint 请参考 https://api.aliyun.com/product/ocr-api
        config.Endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        return new AlibabaCloud.OpenApiClient.Client(config);
    }

    public AlibabaCloud.SDK.Ocr_api20210707.Client CreateClient2(string accessKeyId, string accessKeySecret)
    {
        // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378671.html。
        AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
        {
            // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
            AccessKeyId = accessKeyId,//Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
            // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
            AccessKeySecret = accessKeySecret,// Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
        };
        // Endpoint 请参考 https://api.aliyun.com/product/ocr-api
        config.Endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        return new AlibabaCloud.SDK.Ocr_api20210707.Client(config);
    }

    public string Run2(Stream textureBody)
    {
        //AlibabaCloud.SDK.Ocr_api20210707.Client client = CreateClient();
        // 需要安装额外的依赖库,直接点击下载完整工程即可看到所有依赖。
        Stream bodyStream = AlibabaCloud.DarabonbaStream.StreamUtil.ReadFromFilePath("<your-file-path>");

        var dd = new AlibabaCloud.SDK.Ocr_api20210707.Models.DataSubImagesFigureInfoValue();


        AlibabaCloud.SDK.Ocr_api20210707.Models.RecognizeAllTextRequest recognizeAllTextRequest = new AlibabaCloud.SDK.Ocr_api20210707.Models.RecognizeAllTextRequest
        {
            Type = "Advanced",
            OutputFigure = true,
            Body = textureBody,
        };
        AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();

        try
        {
            // 复制代码运行请自行打印 API 的返回值
            recognizeAllTextRequest.Validate();
            Debug.Log($" 验证通过 ");
            var res = aliClient2.RecognizeAllTextWithOptions(recognizeAllTextRequest, runtime);
            return res.Body.Data.Content;

        }
        catch (TeaException error)
        {
            // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
            // 错误 message
            Debug.Log($"Tea错误 : {error.Message}");
            // 诊断地址
            Debug.Log($"Tea错误2 : {error.Data["Recommend"]}");

            AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
        }
        catch (Exception _error)
        {
            Debug.Log($"错误 : {_error}");

            TeaException error = new TeaException(new Dictionary<string, object>
                {
                    { "message", _error.Message }
                });
            // 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。

            // 错误 message
            Debug.Log($"错误2 : {error.Message}");
            // 诊断地址
            Debug.Log($"错误3 : {error.Data["Recommend"]}");

            AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
        }

        return "";
    }

    /// <term><b>Description:</b></term>
    /// <description>
    /// <para>API 相关</para>
    public AlibabaCloud.OpenApiClient.Models.Params CreateApiInfo()
    {
        AlibabaCloud.OpenApiClient.Models.Params params_ = new AlibabaCloud.OpenApiClient.Models.Params
        {
            // 接口名称
            Action = "RecognizeAllText",
            // 接口版本
            Version = "2021-07-07",
            // 接口协议
            Protocol = "HTTPS",
            // 接口 HTTP 方法
            Method = "POST",
            AuthType = "AK",
            Style = "V3",
            // 接口 PATH
            Pathname = "/",
            // 接口请求体内容格式
            ReqBodyType = "json",
            // 接口响应体内容格式
            BodyType = "json",
        };
        return params_;
    }


    public void RecognizeAllTextWithOptions()
    {

    }



}





http://www.kler.cn/a/525034.html

相关文章:

  • iperf 测 TCP 和 UDP 网络吞吐量
  • C++,STL,【目录篇】
  • C语言练习(29)
  • Hive安装教程
  • 【NLP251】NLP RNN 系列网络
  • 机器学习(三)
  • Windows程序设计4:API函数URLDownloadToFile和ShellExecuteEx
  • Python3 【函数】:见证算法的优雅与力量
  • 论文阅读(十三):复杂表型关联的贝叶斯、基于系统的多层次分析:从解释到决策
  • 26.useScript
  • 如何将DeepSeek部署到本地电脑
  • Shell特殊状态变量以及常用内置变量总结
  • Kmesh v1.0 正式发布
  • 用JavaScript实现观察者模式
  • 小白爬虫冒险之反“反爬”:无限debugger、禁用开发者工具、干扰控制台...(持续更新)
  • 【16届蓝桥杯寒假刷题营】第2期DAY4
  • 安卓逆向之脱壳-认识一下动态加载 双亲委派(二)
  • 洛谷P3383 【模板】线性筛素数
  • 在Visual Studio Code自带的按键编译无法使用该怎么办
  • JavaScript_01
  • Baklib如何重新定义企业知识管理提升组织效率与创新力
  • MyBatis 缓存机制详解
  • Java学习教程,从入门到精通,JDBC 删除表语法及案例(103)
  • 基于Langchain-Chatchat + ChatGLM 本地部署知识库
  • 240. 搜索二维矩阵||
  • 【JavaEE】Spring(6):Mybatis(下)