File size: 1,315 Bytes
8a469fd |
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 |
from scripts.physton_prompt.translator.base_tanslator import BaseTranslator
import uuid
import requests
import json
from scripts.physton_prompt.get_lang import get_lang
class CaiyunTranslator(BaseTranslator):
def __init__(self):
super().__init__('caiyun')
def translate(self, text):
if not text:
return ''
url = 'http://api.interpreter.caiyunai.com/v1/translator'
token = self.api_config.get('token', '')
if not token:
raise Exception(get_lang('is_required', {'0': 'Token'}))
payload = {
"source": text,
"trans_type": f'{self.from_lang}2{self.to_lang}',
"request_id": str(uuid.uuid4()),
"detect": True,
}
headers = {
"content-type": "application/json",
"x-authorization": "token " + token,
}
response = requests.post(url, data=json.dumps(payload), headers=headers)
if not response.text:
raise Exception(get_lang('response_is_empty', {'0': 'caiyun'}))
result = response.json()
if 'message' in result:
raise Exception(result['message'])
if 'target' not in result:
raise Exception(get_lang('no_response_from', {'0': 'caiyun'}))
return result['target']
|