目录
一、百度翻译API
二、腾讯翻译API
一、百度翻译API
百度翻译API接口免费翻译额度:标准版(5万字符免费/每月)、高级版(100万字符免费/每月-需个人认证,基本都能通过)、尊享版(200万字符免费/每月-需企业认证,门槛高);
超出免费额度价格:49元/百万字符;
官方介绍:百度翻译开放平台http://api.fanyi.baidu.com/product/111
代码调用测试:
import hashlib
import requests
import time# 百度翻译API配置信息
APP_ID = '20240624002084131'
SECRET_KEY = '467YvIvdT4SgJKnu80i9'# 定义百度翻译函数
def translate_to_chinese(text):url = "http://api.fanyi.baidu.com/api/trans/vip/translate"salt = str(time.time())sign = hashlib.md5((APP_ID + text + salt + SECRET_KEY).encode('utf-8')).hexdigest()params = {'q': text,'from': 'en','to': 'zh','appid': APP_ID,'salt': salt,'sign': sign}response = requests.get(url, params=params)result = response.json()# 添加错误处理和日志记录if 'trans_result' in result:return result['trans_result'][0]['dst']else:# 打印错误信息和完整的API响应print(f"翻译API响应错误: {result}")return text # 如果翻译失败,返回原文# 测试翻译功能
test_text = "Hello, this is a test."
translated_text = translate_to_chinese(test_text)
print(f"原文: {test_text}")
print(f"翻译结果: {translated_text}")
申请流程:
(1):打开百度翻译开放平台https://api.fanyi.baidu.com,点击开发者信息;
(2):首先注册开发者,然后您将可以在注册成功提示信息处看到“开通服务”的入口。另外,您也可随时前往【管理控制台】→ 【总览】处开通服务。开通服务时,请选择“通用翻译API”。
(3):开通之后点击开发者信息即可看到APP ID和密钥。
二、腾讯翻译API
腾讯翻译API接口免费翻译额度:500万字符免费/每月;
超出免费额度价格:58元/百万字符,有字符资源包出售;
官方介绍:机器翻译 计费概述-购买指南-文档中心-腾讯云https://cloud.tencent.com/document/product/551/35017
查看接口调用详情:自动翻译 - 机器翻译 - 控制台 (tencent.com)
代码调用测试:
import requests
import time
import hashlib
import hmac
import json# 腾讯翻译API配置信息
SECRET_ID = 'YOUR_SECRET_ID '
SECRET_KEY = 'YOUR_SECRET_KEY '
REGION = 'ap-guangzhou'
ENDPOINT = 'tmt.tencentcloudapi.com'
SERVICE = 'tmt'
VERSION = '2018-03-21'
ACTION = 'TextTranslate'def sign_request(secret_id, secret_key, method, endpoint, uri, params):timestamp = int(time.time())date = time.strftime('%Y-%m-%d', time.gmtime(timestamp))# 1. Build Canonical Request Stringhttp_request_method = methodcanonical_uri = uricanonical_querystring = ''canonical_headers = f'content-type:application/json\nhost:{endpoint}\n'signed_headers = 'content-type;host'payload_hash = hashlib.sha256(json.dumps(params).encode('utf-8')).hexdigest()canonical_request = (http_request_method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash)# 2. Build String to Signalgorithm = 'TC3-HMAC-SHA256'credential_scope = f"{date}/{SERVICE}/tc3_request"string_to_sign = (algorithm + '\n' + str(timestamp) + '\n' + credential_scope + '\n' + hashlib.sha256(canonical_request.encode('utf-8')).hexdigest())# 3. Sign Stringdef sign(key, msg):return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()secret_date = sign(('TC3' + secret_key).encode('utf-8'), date)secret_service = sign(secret_date, SERVICE)secret_signing = sign(secret_service, 'tc3_request')signature = hmac.new(secret_signing, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest()# 4. Build Authorization Headerauthorization = (f"{algorithm} "f"Credential={secret_id}/{credential_scope}, "f"SignedHeaders={signed_headers}, "f"Signature={signature}")return authorization, timestampdef translate_to_chinese(text):params = {"SourceText": text,"Source": "en","Target": "zh","ProjectId": 0}method = 'POST'uri = '/'authorization, timestamp = sign_request(SECRET_ID, SECRET_KEY, method, ENDPOINT, uri, params)headers = {'Content-Type': 'application/json','Host': ENDPOINT,'X-TC-Action': ACTION,'X-TC-Timestamp': str(timestamp),'X-TC-Version': VERSION,'X-TC-Region': REGION,'Authorization': authorization}response = requests.post(f'https://{ENDPOINT}{uri}', headers=headers, data=json.dumps(params))result = response.json()if 'Response' in result and 'TargetText' in result['Response']:return result['Response']['TargetText']else:print(f"翻译API响应错误: {result}")return text # 如果翻译失败,返回原文# 测试翻译功能
text_to_translate = "Hello, how are you?"
translated_text = translate_to_chinese(text_to_translate)
print(f"原文: {text_to_translate}")
print(f"译文: {translated_text}")
申请流程:
(1)打开如下链接:https://cloud.tencent.com/
(2)登录后, 在左上“产品”中搜索“机器翻译”并进入
(3)点击立即使用(可能需要实名认证)
(4)点击“开通付费版”(和百度翻译一样,月使用小于100万次,不会扣费)
(5)在右上角,选择“项目管理”
(6)在左边选择“访问管理”,在“访问密钥”选择“API密钥管理”
(7)选择“继续使用”,选择“新建密钥”,获取到SecretId和SecretKey,填入萌译的“API配置”中即可。