Difference between revisions of "五分钟学会彩云小译 API 2"

From Caiyun Wiki
Jump to: navigation, search
(Created page with "<div style="padding:5px;border: 1px dashed MediumAquamarine;text-align:right;float:right"> <div> [https://app.swaggerhub.com/apis/caiyun/lingo-cloud_api/1.0.1 API spec] </div>...")
 
 
(11 intermediate revisions by the same user not shown)
Line 16: Line 16:
 
[[File:Screen Shot 2018-09-06 at 11.22.04 PM.png|800px]]
 
[[File:Screen Shot 2018-09-06 at 11.22.04 PM.png|800px]]
  
= 一分钟介绍=
+
= API 应用 =
  
 
下面的一分钟介绍,我们制作一个命令行工具,可以让你翻译简短的一句话。
 
下面的一分钟介绍,我们制作一个命令行工具,可以让你翻译简短的一句话。
Line 22: Line 22:
 
=== 申请访问令牌===
 
=== 申请访问令牌===
  
* 如果你要测试,可以使用 '''3975l6lr5pcbvidl6jl2''' 作为测试 Token,我们不保证该 Token 的可用性,所以如果要持续使用,还请申请正式 Token。
+
* 请先至[https://dashboard.caiyunapp.com/user/sign_in/ 彩云科技开放平台]注册账号,申请开通小译 Token,并获取到 secret_key
 
 
* 请先至[https://dashboard.caiyunapp.com/user/sign_in/ 彩云科技开放平台]注册账号,申请开通小译 Token。
 
  
 
* 每月翻译100万字之内都是免费的,如果您每月超过100万字,我们会按照 20元 / 100万字 的费率收费。(字数按照翻译原文字符计算,包含空格和标点)
 
* 每月翻译100万字之内都是免费的,如果您每月超过100万字,我们会按照 20元 / 100万字 的费率收费。(字数按照翻译原文字符计算,包含空格和标点)
  
=== 文本翻译===
+
=== 接口说明 ===
 +
 +
* 文本翻译 API 地址
 +
"http://api.interpreter.caiyunai.com/v1/translator"
  
执行下述 BASH 命令创建命令行工具 xiaoyi.sh
+
* 参数说明
 +
{| class="wikitable"
 +
|-
 +
! 字段名 !! 类型 !! 含义 !! 必填 !! 备注
 +
|-
 +
| source || string/list || 源文本 || true || 支持字符串,也支持字符串的 list
 +
|-
 +
| trans_type || string || 翻译方向 || true || 见下方支持的语言
 +
|-
 +
| detect || boolean || 是否自动识别源语种 || false || 具体见下方说明
 +
|-
 +
| salt || string || uuid string || true || 根据 salt 来防重放,所以要求是 uuid
 +
|-
 +
| current_time || string || 当前UTC时间戳(秒) || true || timestamp
 +
|-
 +
| sign || string || 签名 || true || 见下方签名方法
 +
|}
  
<syntaxhighlight lang="bash">
+
* 签名方法
#!/bin/bash
+
** sign=sha256(YOUR_TOKEN+salt+current_time+YOUR_SECRET_KEY+source_input);
tee xiaoyi.sh << END
+
** source_input: 如果 source 是 字符串,且长度<= 20,则就是 source,如果长度> 20, 则取字符串的前10个字符+后10个字符(source[:10]+str(len(source))+source[-10:]); 如果 source 是 list, 则以list的第一个 item 为基础,如果长度 <=20,则为source[0],否则为 source[0][:10]+str(len(source[0]))+source[0][-10:];
DIRECTION=\$1
+
** secret_key: 用户在开放平台获取的 secret_key;
SOURCE=\$2
 
  
if test -f \$HOME/.xiaoyi ; then
+
* header 说明
  . \$HOME/.xiaoyi
+
    headers = {
else
+
            'content-type': "application/json",
  echo "Please input your token: "
+
            'x-authorization': "token " + YOUR_TOKEN,
  read TOKEN
+
    }
  echo "TOKEN=\$TOKEN" > \$HOME/.xiaoyi
 
fi
 
  
BODY='{"source": ["'\$SOURCE'"], "trans_type": "'\$DIRECTION'", "replaced": true, "media": "text", "request_id": "demo" }'
+
=== python 示例===
  
export PYTHONIOENCODING=utf8
+
请把 YOUR_TOKEN 设置为你的 token,将 YOUR_SECRET_KEY 设置为你的 secret_key, 并发请求的速度会是逐个请求的数倍,如有可能,请将长度类似的 20-40 个句子打包请求,下面是实例代码。
curl -s -X POST http://api.interpreter.caiyunai.com/v1/translator\
 
      -H 'Content-Type: application/json'\
 
      -H "X-Authorization: token \$TOKEN"\
 
      -d "\$BODY" | python -c "import sys, json; print json.load(sys.stdin)['target']"
 
END
 
</syntaxhighlight>
 
  
再按照下面的方式执行 xiaoyi.sh 就会得到翻译结果
+
<source lang="python">
 
+
import requests
<syntaxhighlight lang="bash">
+
import json
sh xiaoyi.sh en2zh "You know some birds are not meant to be caged, their feathers are just too bright."
+
import hashlib
</syntaxhighlight>
+
import time
 
+
import uuid
你知道有些鸟不应该被关在笼子里,它们的羽毛太亮了。
 
  
<syntaxhighlight lang="bash">
+
def truncate(source):
sh xiaoyi.sh ja2zh "薄紅の秋の実に"
+
    if source is None:
</syntaxhighlight>
+
        return None
 +
    if isinstance(source, str):
 +
        source = source.decode('utf-8')
 +
    size = len(source)
 +
    return source if size <= 20 else source[:10] + str(size) + source[-10:]
  
淡红色的秋天的果实
+
def encrypt(sign_str):
 +
    hash_algorithm = hashlib.sha256()
 +
    hash_algorithm.update(sign_str.encode('utf-8'))
 +
    return hash_algorithm.hexdigest()
  
备注:第一次执行 xiaoyi.sh 时会要求输入访问令牌 Token 。
 
 
=进阶使用=
 
===python 调用===
 
 
请把 YOUR_TOKEN 设置为你的 token,并发请求的速度会是逐个请求的数倍,如有可能,请将长度类似的 20-40 个句子打包请求,下面是实例代码。
 
 
<source lang="python">
 
 
def tranlate(source, direction):
 
def tranlate(source, direction):
  
    import requests
 
    import json
 
   
 
 
     url = "http://api.interpreter.caiyunai.com/v1/translator"
 
     url = "http://api.interpreter.caiyunai.com/v1/translator"
      
+
 
     #WARNING, this token is a test token for new developers, and it should be replaced by your token
+
    token = YOUR_TOKEN
     token = "3975l6lr5pcbvidl6jl2"
+
     secret_key = YOUR_SECRET_KEY
      
+
     current_time = str(int(time.time()))
      
+
    salt = str(uuid.uuid1())
 +
     source_input = source
 +
     if isinstance(source, list):
 +
        source_input = source[0]
 +
     sign_str = token + salt + current_time + secret_key + truncate(source_input)
 
     payload = {
 
     payload = {
             "source" : source,  
+
             "source" : source,
 
             "trans_type" : direction,
 
             "trans_type" : direction,
            "request_id" : "demo",
 
 
             "detect": True,
 
             "detect": True,
 +
            "salt": salt,
 +
            "current_time": current_time,
 +
            "sign": encrypt(sign_str),
 
             }
 
             }
   
+
 
 
     headers = {
 
     headers = {
 
             'content-type': "application/json",
 
             'content-type': "application/json",
 
             'x-authorization': "token " + token,
 
             'x-authorization': "token " + token,
 
     }
 
     }
   
+
 
 
     response = requests.request("POST", url, data=json.dumps(payload), headers=headers)
 
     response = requests.request("POST", url, data=json.dumps(payload), headers=headers)
 +
    print response.text
  
 
     return json.loads(response.text)['target']
 
     return json.loads(response.text)['target']
  
 +
 +
 +
 +
#source = "彩云小译は最高の翻訳サービスです"
 
source = ["Lingocloud is the best translation service.","彩云小译は最高の翻訳サービスです"]
 
source = ["Lingocloud is the best translation service.","彩云小译は最高の翻訳サービスです"]
 
target = tranlate(source, "auto2zh")
 
target = tranlate(source, "auto2zh")
  
print(target)
+
print target
 +
 
  
 
</source>
 
</source>
Line 135: Line 150:
 
| ja2zh || - || -
 
| ja2zh || - || -
 
|}
 
|}
 +
 +
= 关于语种自动识别 =
 +
 +
即在调用接口时,增加 detect=True 参数。
 +
 +
当 detect=True 时,trans_type 由之前的 4 种:zh2en、en2zh、zh2ja、ja2zh,增加为 7 种:zh2en、en2zh、zh2ja、ja2zh、auto2zh、auto2en、auto2ja。
 +
 +
当 trans_type 为 auto2zh 时:会将 en 和 ja 翻译为 zh,其他语种原样返回;
 +
 +
当 trans_type 为 auto2en 时:会将 zh 翻译为 en,其他语种原样返回;
 +
 +
当 trans_type 为 auto2ja 时:会将 zh 翻译为 ja,其他语种原样返回。
  
 
使用 auto2xx 可以自动识别源语言的语种。2019年底将支持到15种以上语言,200种以上语言方向。
 
使用 auto2xx 可以自动识别源语言的语种。2019年底将支持到15种以上语言,200种以上语言方向。

Latest revision as of 10:11, 1 November 2019

能用彩云小译 API 做什么?

彩云小译 API 可以用来把信息翻译到指定的语言,我们可以支持文本、网页、PDF/Word文档、语音、视频等多种形式。

您可以使用它来构建你的应用程序、网站、工具或任何需要多语言支持的解决方案。例如:彩云小译 API 是维基百科自动翻译的技术提供者,也为钉钉、石墨文档、财新传媒等一线机构和众多开发者提供技术支持。

维基百科内容翻译

Screen Shot 2018-09-06 at 11.03.18 PM.png

石墨文档翻译

Screen Shot 2018-09-06 at 11.22.04 PM.png

API 应用

下面的一分钟介绍,我们制作一个命令行工具,可以让你翻译简短的一句话。

申请访问令牌

  • 每月翻译100万字之内都是免费的,如果您每月超过100万字,我们会按照 20元 / 100万字 的费率收费。(字数按照翻译原文字符计算,包含空格和标点)

接口说明

  • 文本翻译 API 地址

"http://api.interpreter.caiyunai.com/v1/translator"

  • 参数说明
字段名 类型 含义 必填 备注
source string/list 源文本 true 支持字符串,也支持字符串的 list
trans_type string 翻译方向 true 见下方支持的语言
detect boolean 是否自动识别源语种 false 具体见下方说明
salt string uuid string true 根据 salt 来防重放,所以要求是 uuid
current_time string 当前UTC时间戳(秒) true timestamp
sign string 签名 true 见下方签名方法
  • 签名方法
    • sign=sha256(YOUR_TOKEN+salt+current_time+YOUR_SECRET_KEY+source_input);
    • source_input: 如果 source 是 字符串,且长度<= 20,则就是 source,如果长度> 20, 则取字符串的前10个字符+后10个字符(source[:10]+str(len(source))+source[-10:]); 如果 source 是 list, 则以list的第一个 item 为基础,如果长度 <=20,则为source[0],否则为 source[0][:10]+str(len(source[0]))+source[0][-10:];
    • secret_key: 用户在开放平台获取的 secret_key;
  • header 说明
   headers = {
           'content-type': "application/json",
           'x-authorization': "token " + YOUR_TOKEN,
   }

python 示例

请把 YOUR_TOKEN 设置为你的 token,将 YOUR_SECRET_KEY 设置为你的 secret_key, 并发请求的速度会是逐个请求的数倍,如有可能,请将长度类似的 20-40 个句子打包请求,下面是实例代码。

import requests
import json
import hashlib
import time
import uuid

def truncate(source):
    if source is None:
        return None
    if isinstance(source, str):
        source = source.decode('utf-8')
    size = len(source)
    return source if size <= 20 else source[:10] + str(size) + source[-10:]

def encrypt(sign_str):
    hash_algorithm = hashlib.sha256()
    hash_algorithm.update(sign_str.encode('utf-8'))
    return hash_algorithm.hexdigest()

def tranlate(source, direction):

    url = "http://api.interpreter.caiyunai.com/v1/translator"

    token = YOUR_TOKEN
    secret_key = YOUR_SECRET_KEY
    current_time = str(int(time.time()))
    salt = str(uuid.uuid1())
    source_input = source
    if isinstance(source, list):
        source_input = source[0]
    sign_str = token + salt + current_time + secret_key + truncate(source_input)
    payload = {
            "source" : source,
            "trans_type" : direction,
            "detect": True,
            "salt": salt,
            "current_time": current_time,
            "sign": encrypt(sign_str),
            }

    headers = {
            'content-type': "application/json",
            'x-authorization': "token " + token,
    }

    response = requests.request("POST", url, data=json.dumps(payload), headers=headers)
    print response.text

    return json.loads(response.text)['target']




#source = "彩云小译は最高の翻訳サービスです"
source = ["Lingocloud is the best translation service.","彩云小译は最高の翻訳サービスです"]
target = tranlate(source, "auto2zh")

print target

输出为:

['小译翻译是最好的翻译服务。', '彩云小译是最好的翻译服务']

支持的语言

目前支持的语言和翻译方向如下表所示

To
From
中文 zh 英语 en 日文 ja
中文 zh - zh2en zh2ja
英语 en en2zh - -
日文 ja ja2zh - -

关于语种自动识别

即在调用接口时,增加 detect=True 参数。

当 detect=True 时,trans_type 由之前的 4 种:zh2en、en2zh、zh2ja、ja2zh,增加为 7 种:zh2en、en2zh、zh2ja、ja2zh、auto2zh、auto2en、auto2ja。

当 trans_type 为 auto2zh 时:会将 en 和 ja 翻译为 zh,其他语种原样返回;

当 trans_type 为 auto2en 时:会将 zh 翻译为 en,其他语种原样返回;

当 trans_type 为 auto2ja 时:会将 zh 翻译为 ja,其他语种原样返回。

使用 auto2xx 可以自动识别源语言的语种。2019年底将支持到15种以上语言,200种以上语言方向。

想要更多?

    437px-Beary861921651.jpg