当前位置: 首页 > 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]
#endifpublic 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);// 构建最终 URLstring 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 时间戳转换为 DateTimeDateTime 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]
#endifprivate 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 Unitystring 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 UnityWebRequestusing (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip("file://" + audioFilePath, AudioType.WAV)){DownloadHandlerAudioClip downloadHandler = www.downloadHandler as DownloadHandlerAudioClip;downloadHandler.streamAudio = true; // Stream the audio to save memoryawait 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 updatevoid 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]
#endifprivate 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 数据为 JPGbyte[] jpgData = texture2D.EncodeToJPG();// 释放 Texture2D 对象
#if UNITY_EDITORDestroyImmediate(texture2D);
#elseDestroy(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 paramsDictionary<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 optionsAlibabaCloud.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 字符串解析为 JObjectJObject 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 JSONresult.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-apiconfig.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-apiconfig.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){// 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。// 错误 messageDebug.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 }});// 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。// 错误 messageDebug.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",// 接口 PATHPathname = "/",// 接口请求体内容格式ReqBodyType = "json",// 接口响应体内容格式BodyType = "json",};return params_;}public void RecognizeAllTextWithOptions(){}}

相关文章:

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.Thr…...

2023年吉林省职业院校技能大赛网络系统管理样题-网络配置(华三代码)

目录 附录1:拓扑图 附录2:地址规划表 1.S1 2.S3 3.S4 4.S5 5.S7 6.S8 7.S9 8.R1 9.R2 10.R3 11.EG1 12.EG2 13.AC1 14.AC2 附录1:拓扑图 编号 型号...

WSL 安装cuDNN

WSL 安装cuDNN 参考文档&#xff1a;https://docs.nvidia.com/deeplearning/cudnn/installation/latest/linux.html#verifying-the-install-on-linux 1. 下载相应包 根据下方下载地址进入下载界面&#xff0c;并选择与自己电脑相对应的平台执行图中的命令 下载地址&#xff1…...

SSRF漏洞学习总结

一、SSRF漏洞 1.原理 SSRF&#xff08;Server-Side Request Forgery&#xff0c;服务器端请求伪造&#xff09;是一种安全漏洞&#xff0c;攻击者利用这个漏洞可以诱使服务器端发起由攻击者构造的请求。这种攻击通常发生在应用接受来自用户的输入&#xff0c;并且该输入用于构…...

stack 和 queue容器的介绍和使用

1.stack的介绍 1.1stack容器的介绍 stack容器的基本特征和功能我们在数据结构篇就已经详细介绍了&#xff0c;还不了解的uu&#xff0c; 可以移步去看这篇博客哟&#xff1a; 数据结构-栈数据结构-队列 简单回顾一下&#xff0c;重要的概念其实就是后进先出&#xff0c;栈在…...

Windows中本地组策略编辑器gpedit.msc打不开/微软远程桌面无法复制粘贴

目录 背景 解决gpedit.msc打不开 解决复制粘贴 剪贴板的问题 启用远程桌面剪贴板与驱动器 重启RDP剪贴板监视程序 以上都不行&#xff1f;可能是操作被Win11系统阻止 最后 背景 远程桌面无法复制粘贴&#xff0c;需要查看下主机策略组设置&#xff0c;结果按WinR输入…...

(2023 RESS ) Federated multi-source domain adversarial adaptation framework

&#x1f4da; 研究背景与挑战 机械设备的故障诊断对于保障生产效率和安全至关重要。传统的智能诊断方法依赖于大量的训练数据&#xff0c;但在实际工业场景中&#xff0c;数据收集受到经济和时间因素的限制。更棘手的是&#xff0c;由于行业竞争和隐私安全问题&#xff0c;不…...

Java实现FIFO缓存策略实战

实现FIFO模型选择FIFO模型实现过程FIFO模型完整代码下面看一下先进先出的示例过程总结FIFO(First In First Out,先进先出)策略是一种基本的数据处理和存储管理方法,在Java中,这种策略通常用于管理那些需要按照顺序处理的数据项,比如任务的队列、数据的传输缓冲区等。在Ja…...

虚幻基础07:蓝图接口

能帮到你的话&#xff0c;就给个赞吧 &#x1f618; 文章目录 作用原理事件函数 作用 实现对象间的通知。 A 通知 B 做什么。 原理 将接口抽象为蓝图&#xff0c;使得任意蓝图都能直接访问。 只需要再传入对象地址&#xff0c;就能执行对象的功能。 事件 黄色&#xff1a;…...

978.最长湍流子数组

目录 题目过程解法收获 题目 给定一个整数数组 arr &#xff0c;返回 arr 的 最大湍流子数组的长度 。 如果比较符号在子数组中的每个相邻元素对之间翻转&#xff0c;则该子数组是 湍流子数组 。 更正式地来说&#xff0c;当 arr 的子数组 A[i], A[i1], …, A[j] 满足仅满足…...

Python数据分析-Python语法基础,IPython和Jupyter-Notebooks(二)

title: ‘Python数据分析:Python语法基础&#xff0c;IPython和Jupyter Notebooks&#xff08;二&#xff09;’ tags: python数据分析 categories:python数据分析 keywords:python数据分析 cover: …/img/404_icecream_whale.png description: 本文介绍python的基础语法和jup…...

Redis学习之哨兵一

一、基本概念 1.主从复制的问题&#xff1a; 一旦主节点出现故障需要手动的将一个从节点晋升为主节点同时需要修改应用方的主节点地址还需要通过命令其他节点去复制新的主节点。 主节点的写能力和存储能力受到单机的限制 2.高可用&#xff1a; 上图为一主二从的redis主从复制模…...

【C++高并发服务器WebServer】-9:多线程开发

本文目录 一、线程概述1.1 线程和进程的区别1.2 线程之间共享和非共享资源1.3 NPTL 二、线程操作2.1 pthread_create2.2 pthread_exit2.3 pthread_join2.4 pthread_detach2.5 patch_cancel2.6 pthread_attr 三、实战demo四、线程同步五、死锁六、读写锁七、生产消费者模型 一、…...

【时时三省】(C语言基础)文件的随机读写

山不在高&#xff0c;有仙则名。水不在深&#xff0c;有龙则灵。 ----CSDN 时时三省 fseek 根据文件指针的位置和偏移量来定位文件指针 示例&#xff1a; 这个输出的就是ade seek&#xff3f;cur的意思是从当前偏移量 2就是从a往后偏移两个就是d 偏移量 SEEK&#xff3f;CUR…...

【python】python基于机器学习与数据分析的二手手机特性关联与分类预测(源码+数据集)【独一无二】

&#x1f449;博__主&#x1f448;&#xff1a;米码收割机 &#x1f449;技__能&#x1f448;&#xff1a;C/Python语言 &#x1f449;专__注&#x1f448;&#xff1a;专注主流机器人、人工智能等相关领域的开发、测试技术。 python基于机器学习与数据分析的二手手机特性关联与…...

WPF进阶 | WPF 数据绑定进阶:绑定模式、转换器与验证

WPF进阶 | WPF 数据绑定进阶&#xff1a;绑定模式、转换器与验证 一、前言二、WPF 数据绑定基础回顾2.1 数据绑定的基本概念2.2 数据绑定的基本语法 三、绑定模式3.1 单向绑定&#xff08;One - Way Binding&#xff09;3.2 双向绑定&#xff08;Two - Way Binding&#xff09;…...

java.util.Random类(详细案例拆解)(已完结)

前言&#xff1a; 小编打算近期更俩三期类的专栏&#xff0c;一些常用的专集类&#xff0c;给大家分好类别总结和详细的代码举例解释。 今天是除夕&#xff0c;小编先祝贺大家除夕快乐啦&#xff01;&#xff01; 今天是第六个 java.lang.Math 包中的 java.util.Random类 我…...

【数据结构】动态内存管理函数

动态内存管理 为什么存在动态内存管理动态内存函数的介绍&#x1f38a;malloc补充&#xff1a;perror函数&#x1f38a;free&#x1f38a;calloc&#x1f38a;realloc 常见动态内存错误对空指针的解引用操作对动态开辟空间的越界访问对非动态开辟内存使用free释放使用free释放一…...

TVM框架学习笔记

TVM是陈天齐等人一个开源的深度学习编译器栈,用于优化和部署机器学习模型到各种硬件后端。它支持多种前端框架,如TensorFlow、PyTorch、ONNX等,并且可以在不同的硬件平台上运行,包括CPU、GPU和专用加速器。官方文档: Apache TVM Documentation — tvm 0.20.dev0 documenta…...

neo4j-community-5.26.0 install in window10

在住处电脑重新配置一下neo4j, 1.先至官方下载 Neo4j Desktop Download | Free Graph Database Download Neo4j Deployment Center - Graph Database & Analytics 2.配置java jdk jdk 21 官网下载 Java Downloads | Oracle 中国 path: 4.查看java -version 版本 5.n…...

macbook安装go语言

通过brew来安装go语言 使用brew命令时&#xff0c;一般都会通过brew search看看有哪些版本 brew search go执行后&#xff0c;返回了一堆内容&#xff0c;最下方展示 If you meant "go" specifically: It was migrated from homebrew/cask to homebrew/core. Cas…...

LCD液晶屏的工作原理以及背光模组

LCD液晶屏的工作原理以及背光模组 液晶屏工作原理 像素点的主要结构背光模组 LCD液晶屏主要由两部分组成&#xff0c;液晶屏和背光模组。背光模组提供均匀稳定的光源&#xff0c;液晶屏控制光线的传播路径&#xff0c;是屏幕显示设定的图像。 液晶屏 LCD的核心是两片玻璃之间…...

es数据同步

Logstash 是 Elastic 技术栈中的一个技术&#xff0c;它是一个数据采集引擎&#xff0c;可以从数据库采集数据到 ES 中。可以通过设置 自增 ID 主键 或 更新时间 来控制数据的自动同步&#xff1a; 自增 ID 主键&#xff1a;Logstatsh 会有定时任务&#xff0c;如果发现有主键…...

maven的打包插件如何使用

默认的情况下&#xff0c;当直接执行maven项目的编译命令时&#xff0c;对于结果来说是不打第三方包的&#xff0c;只有一个单独的代码jar&#xff0c;想要打一个包含其他资源的完整包就需要用到maven编译插件&#xff0c;使用时分以下几种情况 第一种&#xff1a;当只是想单纯…...

【Elasticsearch】中数据流需要配置索引模板吗?

是的&#xff0c;数据流需要配置索引模板。在Elasticsearch中&#xff0c;数据流&#xff08;Data Streams&#xff09;是一种用于处理时间序列数据的高级结构&#xff0c;它背后由多个隐藏的索引组成&#xff0c;这些索引被称为后备索引&#xff08;Backing Indices&#xff0…...

Controller 层优化四步曲

Controller 层优化四步曲 前言 在开发过程中&#xff0c;Controller 层作为系统与外界交互的桥梁&#xff0c;承担着接收请求、解析参数、调用业务逻辑、处理异常等职责。 然而&#xff0c;随着业务复杂度的增加&#xff0c;Controller 层的代码往往会变得臃肿且难以维护。 …...

Java后端之AOP

AOP&#xff1a;面向切面编程&#xff0c;本质是面向特定方法编程 引入依赖&#xff1a; <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency>示例&#xff1a;记录…...

中文输入法方案

使用了三年的自然码双拼&#xff0c;毫无疑问是推荐使用双拼输入法。 三年积累下来的习惯是&#xff1a; 1 自然码方案 2 空格出字 字母选字 直到如今&#xff0c;想要做出改变&#xff0c;是因为这样的方案带来的痛点&#xff1a; 1 使用空格出字就无法使用辅助码&#…...

Elasticsearch中的度量聚合:深度解析与实战应用

在大数据和实时分析日益重要的今天&#xff0c;Elasticsearch以其强大的搜索和聚合能力&#xff0c;成为了众多企业和开发者进行数据分析和处理的首选工具。本文将深入探讨Elasticsearch中的度量聚合&#xff08;Metric Aggregations&#xff09;&#xff0c;展示其如何在数据分…...

Julius AI 人工智能数据分析工具介绍

Julius AI 是一款由 Casera Labs 开发的人工智能数据分析工具&#xff0c;旨在通过自然语言交互和强大的算法能力&#xff0c;帮助用户快速分析和可视化复杂数据。这款工具特别适合没有数据科学背景的用户&#xff0c;使数据分析变得简单高效。 核心功能 自然语言交互&#x…...