当前位置:   article > 正文

免费翻译API及使用指南——百度、腾讯_百度翻译api标准版

百度翻译api标准版

目录

一、百度翻译API

二、腾讯翻译API


一、百度翻译API

百度翻译API接口免费翻译额度:标准版(5万字符免费/每月)、高级版(100万字符免费/每月-需个人认证,基本都能通过)、尊享版(200万字符免费/每月-需企业认证,门槛高);

超出免费额度价格:49元/百万字符;

官方介绍:百度翻译开放平台icon-default.png?t=N7T8http://api.fanyi.baidu.com/product/111

代码调用测试:

  1. import hashlib
  2. import requests
  3. import time
  4. # 百度翻译API配置信息
  5. APP_ID = '20240624002084131'
  6. SECRET_KEY = '467YvIvdT4SgJKnu80i9'
  7. # 定义百度翻译函数
  8. def translate_to_chinese(text):
  9. url = "http://api.fanyi.baidu.com/api/trans/vip/translate"
  10. salt = str(time.time())
  11. sign = hashlib.md5((APP_ID + text + salt + SECRET_KEY).encode('utf-8')).hexdigest()
  12. params = {
  13. 'q': text,
  14. 'from': 'en',
  15. 'to': 'zh',
  16. 'appid': APP_ID,
  17. 'salt': salt,
  18. 'sign': sign
  19. }
  20. response = requests.get(url, params=params)
  21. result = response.json()
  22. # 添加错误处理和日志记录
  23. if 'trans_result' in result:
  24. return result['trans_result'][0]['dst']
  25. else:
  26. # 打印错误信息和完整的API响应
  27. print(f"翻译API响应错误: {result}")
  28. return text # 如果翻译失败,返回原文
  29. # 测试翻译功能
  30. test_text = "Hello, this is a test."
  31. translated_text = translate_to_chinese(test_text)
  32. print(f"原文: {test_text}")
  33. print(f"翻译结果: {translated_text}")

申请流程:

(1):打开百度翻译开放平台https://api.fanyi.baidu.com,点击开发者信息;

(2):首先注册开发者,然后您将可以在注册成功提示信息处看到“开通服务”的入口。另外,您也可随时前往【管理控制台】→ 【总览】处开通服务。开通服务时,请选择“通用翻译API”。

(3):开通之后点击开发者信息即可看到APP ID和密钥。

二、腾讯翻译API

腾讯翻译API接口免费翻译额度:500万字符免费/每月;

超出免费额度价格:58元/百万字符,有字符资源包出售;

官方介绍:机器翻译 计费概述-购买指南-文档中心-腾讯云icon-default.png?t=N7T8https://cloud.tencent.com/document/product/551/35017

查看接口调用详情:自动翻译 - 机器翻译 - 控制台 (tencent.com)

代码调用测试:

  1. import requests
  2. import time
  3. import hashlib
  4. import hmac
  5. import json
  6. # 腾讯翻译API配置信息
  7. SECRET_ID = 'YOUR_SECRET_ID '
  8. SECRET_KEY = 'YOUR_SECRET_KEY '
  9. REGION = 'ap-guangzhou'
  10. ENDPOINT = 'tmt.tencentcloudapi.com'
  11. SERVICE = 'tmt'
  12. VERSION = '2018-03-21'
  13. ACTION = 'TextTranslate'
  14. def sign_request(secret_id, secret_key, method, endpoint, uri, params):
  15. timestamp = int(time.time())
  16. date = time.strftime('%Y-%m-%d', time.gmtime(timestamp))
  17. # 1. Build Canonical Request String
  18. http_request_method = method
  19. canonical_uri = uri
  20. canonical_querystring = ''
  21. canonical_headers = f'content-type:application/json\nhost:{endpoint}\n'
  22. signed_headers = 'content-type;host'
  23. payload_hash = hashlib.sha256(json.dumps(params).encode('utf-8')).hexdigest()
  24. canonical_request = (http_request_method + '\n' +
  25. canonical_uri + '\n' +
  26. canonical_querystring + '\n' +
  27. canonical_headers + '\n' +
  28. signed_headers + '\n' +
  29. payload_hash)
  30. # 2. Build String to Sign
  31. algorithm = 'TC3-HMAC-SHA256'
  32. credential_scope = f"{date}/{SERVICE}/tc3_request"
  33. string_to_sign = (algorithm + '\n' +
  34. str(timestamp) + '\n' +
  35. credential_scope + '\n' +
  36. hashlib.sha256(canonical_request.encode('utf-8')).hexdigest())
  37. # 3. Sign String
  38. def sign(key, msg):
  39. return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()
  40. secret_date = sign(('TC3' + secret_key).encode('utf-8'), date)
  41. secret_service = sign(secret_date, SERVICE)
  42. secret_signing = sign(secret_service, 'tc3_request')
  43. signature = hmac.new(secret_signing, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest()
  44. # 4. Build Authorization Header
  45. authorization = (f"{algorithm} "
  46. f"Credential={secret_id}/{credential_scope}, "
  47. f"SignedHeaders={signed_headers}, "
  48. f"Signature={signature}")
  49. return authorization, timestamp
  50. def translate_to_chinese(text):
  51. params = {
  52. "SourceText": text,
  53. "Source": "en",
  54. "Target": "zh",
  55. "ProjectId": 0
  56. }
  57. method = 'POST'
  58. uri = '/'
  59. authorization, timestamp = sign_request(SECRET_ID, SECRET_KEY, method, ENDPOINT, uri, params)
  60. headers = {
  61. 'Content-Type': 'application/json',
  62. 'Host': ENDPOINT,
  63. 'X-TC-Action': ACTION,
  64. 'X-TC-Timestamp': str(timestamp),
  65. 'X-TC-Version': VERSION,
  66. 'X-TC-Region': REGION,
  67. 'Authorization': authorization
  68. }
  69. response = requests.post(f'https://{ENDPOINT}{uri}', headers=headers, data=json.dumps(params))
  70. result = response.json()
  71. if 'Response' in result and 'TargetText' in result['Response']:
  72. return result['Response']['TargetText']
  73. else:
  74. print(f"翻译API响应错误: {result}")
  75. return text # 如果翻译失败,返回原文
  76. # 测试翻译功能
  77. text_to_translate = "Hello, how are you?"
  78. translated_text = translate_to_chinese(text_to_translate)
  79. print(f"原文: {text_to_translate}")
  80. print(f"译文: {translated_text}")

申请流程:

(1)打开如下链接:https://cloud.tencent.com/

(2)登录后, 在左上“产品”中搜索“机器翻译”并进入

(3)点击立即使用(可能需要实名认证)

(4)点击“开通付费版”(和百度翻译一样,月使用小于100万次,不会扣费)

(5)在右上角,选择“项目管理”

 (6)在左边选择“访问管理”,在“访问密钥”选择“API密钥管理”

 (7)选择“继续使用”,选择“新建密钥”,获取到SecretId和SecretKey,填入萌译的“API配置”中即可。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/772998
推荐阅读
相关标签
  

闽ICP备14008679号