文章

腾讯云TMT机器翻译demo

腾讯云TMT机器翻译demo

TMT: Tencent Machine Translate (腾讯机器翻译)

申请API

https://console.cloud.tencent.com/cam/capi

SecretIdSecretKey是需要妥善保存的机密信息,请勿泄露。云 API 密钥安全方案推荐

demo (python)

版本要求: Python 2.7+, 3.7+

在代码所在目录下创建apikey.json文件

1
2
3
4
{
    "SecretId": "xxx",
    "SecretKey": "xxx"
}
1
pip install tencentcloud-sdk-python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import json
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import (
    TencentCloudSDKException,
)
from tencentcloud.tmt.v20180321 import tmt_client, models


class TencentTranslateAPI:
    def __init__(self, apikey_path="apikey.json"):
        self.apikey_path = apikey_path
        self.secret_id, self.secret_key = self.load_apikey()
        self.client = self.create_client()

    def load_apikey(self):
        """读取apikey文件并返回SecretId和SecretKey"""
        try:
            with open(self.apikey_path, "r") as f:
                apikey = json.load(f)
            return apikey["SecretId"], apikey["SecretKey"]
        except Exception as e:
            print(f"Failed to load apikey: {e}")
            raise e

    def create_client(self):
        """根据SecretId和SecretKey创建TmtClient客户端"""
        try:
            cred = credential.Credential(self.secret_id, self.secret_key)
            client = tmt_client.TmtClient(cred, "ap-beijing")
            return client
        except TencentCloudSDKException as err:
            print(f"Error creating client: {err}")
            raise err

    def translate(self, text, source_lang="en", target_lang="zh"):
        """翻译文本"""
        try:
            req = models.TextTranslateRequest()
            params = {
                "SourceText": text,
                "Source": source_lang,
                "Target": target_lang,
                "ProjectId": 0,
            }
            req.from_json_string(json.dumps(params))
            resp = self.client.TextTranslate(req)
            resp_json = json.loads(resp.to_json_string())
            return resp_json["TargetText"]
        except TencentCloudSDKException as err:
            print(f"Error in translation: {err}")
            raise err
        except Exception as e:
            print(f"An error occurred during translation: {e}")
            raise e


# 使用示例
if __name__ == "__main__":
    translator = TencentTranslateAPI()
    result = translator.translate("hello world", source_lang="en", target_lang="zh")
    print(result)

其他

腾讯云在API Explorer提供各类demo

API Explorer文档; API Inspector文档

TMT系统设置关闭后付费或服务

本文由作者按照 CC BY 4.0 进行授权