aardio 文档

aardio 范例: 腾讯云机器翻译接口:文本翻译

参考图像翻译 | 参考免费 OCR API

//腾讯云机器翻译接口:文本翻译
/*
开通后每月免费 500 万字符,翻译速度很快。
默认关闭后付费(需手动勾选),仅开通免费版不会收任何费用。
*/
//参考图像翻译: https://www.aardio.com/zh-cn/docs/examples/Web/REST/tencentCloud/ImageTranslate.html
//参考免费 OCR API: https://www.aardio.com/zh-cn/docs/examples/Automation/ComputerVision/ocr.space.html

import console;
import web.rest.tencentCloud;

// 1. 配置腾讯云 API 
var tencentConfig = {
    //https://console.cloud.tencent.com/cam/capi 获取 API 密钥
    secretId = "你的SecretId";       // 替换为你的 SecretId
    secretKey = "你的SecretKey";     // 替换为你的 SecretKey
    region = "ap-guangzhou";        // 接口地域
    service = "tmt";                // 机器翻译服务标识
    version = "2018-03-21";         // 接口版本号
    action = "TextTranslate";       // 接口动作
}

// 2. 创建腾讯云 REST 客户端
var client = web.rest.tencentCloud(tencentConfig);

// 3. 声明 API 接口对象
// 机器翻译的域名通常为 tmt.tencentcloudapi.com
var tmtApi = client.api("https://tmt.tencentcloudapi.com");

console.showLoading("正在翻译 ");

/*
检测文本是否以拉丁字母为主(例如英文)。
考虑英文双单词短语多数情况下多于 6 个字母(含空格),而 2 个汉字的 UTF-8 编码一般为 6 个字节。
*/
var latinLike = lambda(str) !..string.find(str,":") || (..string.len(str) > #str/1.5);

var inputText = "这是一个免费翻译接口,支持中译英、英译中、多语种互译! "              

/*
4. 调用翻译接口
参数参考:https://cloud.tencent.com/document/product/551/15619
*/
var result, err = tmtApi.post({
    "SourceText": inputText,
    "Source": "auto", // 自动检测源语言
    "Target": latinLike(inputText)?"zh":"en",   // 目标语言为中文
    "ProjectId": 0    // 项目 ID,默认填 0
});

// 5. 处理结果
if(result){
    var resp = result[["Response"]];

    // 检查是否有业务错误
    if(resp[["Error"]]){
        console.error("翻译失败!");
        console.dumpJson(resp.Error);
    }
    else {
        console.success("翻译成功:");
        console.log("原文:", inputText);
        console.log("译文:", resp[["TargetText"]]);
        console.log("RequestId:", resp[["RequestId"]]);
    }
}
else {
    // 网络错误或鉴权失败(err 包含错误详情)
    console.error("网络请求错误:", err);
}

console.pause();
Markdown 格式