Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

baidufanyi.py 4.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import random
  17. from abc import ABC
  18. import requests
  19. from agent.component.base import ComponentBase, ComponentParamBase
  20. from hashlib import md5
  21. class BaiduFanyiParam(ComponentParamBase):
  22. """
  23. Define the BaiduFanyi component parameters.
  24. """
  25. def __init__(self):
  26. super().__init__()
  27. self.appid = "xxx"
  28. self.secret_key = "xxx"
  29. self.trans_type = 'translate'
  30. self.parameters = []
  31. self.source_lang = 'auto'
  32. self.target_lang = 'auto'
  33. self.domain = 'finance'
  34. def check(self):
  35. self.check_empty(self.appid, "BaiduFanyi APPID")
  36. self.check_empty(self.secret_key, "BaiduFanyi Secret Key")
  37. self.check_valid_value(self.trans_type, "Translate type", ['translate', 'fieldtranslate'])
  38. self.check_valid_value(self.source_lang, "Source language",
  39. ['auto', 'zh', 'en', 'yue', 'wyw', 'jp', 'kor', 'fra', 'spa', 'th', 'ara', 'ru', 'pt',
  40. 'de', 'it', 'el', 'nl', 'pl', 'bul', 'est', 'dan', 'fin', 'cs', 'rom', 'slo', 'swe',
  41. 'hu', 'cht', 'vie'])
  42. self.check_valid_value(self.target_lang, "Target language",
  43. ['auto', 'zh', 'en', 'yue', 'wyw', 'jp', 'kor', 'fra', 'spa', 'th', 'ara', 'ru', 'pt',
  44. 'de', 'it', 'el', 'nl', 'pl', 'bul', 'est', 'dan', 'fin', 'cs', 'rom', 'slo', 'swe',
  45. 'hu', 'cht', 'vie'])
  46. self.check_valid_value(self.domain, "Translate field",
  47. ['it', 'finance', 'machinery', 'senimed', 'novel', 'academic', 'aerospace', 'wiki',
  48. 'news', 'law', 'contract'])
  49. class BaiduFanyi(ComponentBase, ABC):
  50. component_name = "BaiduFanyi"
  51. def _run(self, history, **kwargs):
  52. ans = self.get_input()
  53. ans = " - ".join(ans["content"]) if "content" in ans else ""
  54. if not ans:
  55. return BaiduFanyi.be_output("")
  56. try:
  57. source_lang = self._param.source_lang
  58. target_lang = self._param.target_lang
  59. appid = self._param.appid
  60. salt = random.randint(32768, 65536)
  61. secret_key = self._param.secret_key
  62. if self._param.trans_type == 'translate':
  63. sign = md5((appid + ans + salt + secret_key).encode('utf-8')).hexdigest()
  64. url = 'http://api.fanyi.baidu.com/api/trans/vip/translate?' + 'q=' + ans + '&from=' + source_lang + '&to=' + target_lang + '&appid=' + appid + '&salt=' + salt + '&sign=' + sign
  65. headers = {"Content-Type": "application/x-www-form-urlencoded"}
  66. response = requests.post(url=url, headers=headers).json()
  67. if response.get('error_code'):
  68. BaiduFanyi.be_output("**Error**:" + response['error_msg'])
  69. return BaiduFanyi.be_output(response['trans_result'][0]['dst'])
  70. elif self._param.trans_type == 'fieldtranslate':
  71. domain = self._param.domain
  72. sign = md5((appid + ans + salt + domain + secret_key).encode('utf-8')).hexdigest()
  73. url = 'http://api.fanyi.baidu.com/api/trans/vip/fieldtranslate?' + 'q=' + ans + '&from=' + source_lang + '&to=' + target_lang + '&appid=' + appid + '&salt=' + salt + '&domain=' + domain + '&sign=' + sign
  74. headers = {"Content-Type": "application/x-www-form-urlencoded"}
  75. response = requests.post(url=url, headers=headers).json()
  76. if response.get('error_code'):
  77. BaiduFanyi.be_output("**Error**:" + response['error_msg'])
  78. return BaiduFanyi.be_output(response['trans_result'][0]['dst'])
  79. except Exception as e:
  80. BaiduFanyi.be_output("**Error**:" + str(e))