|
import json, os |
|
from tencentcloud.common import credential |
|
from tencentcloud.common.profile.client_profile import ClientProfile |
|
from tencentcloud.common.profile.http_profile import HttpProfile |
|
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException |
|
from tencentcloud.tmt.v20180321 import tmt_client, models |
|
|
|
def get_tmt_client(): |
|
try: |
|
|
|
|
|
|
|
SecretId = os.environ.get("TENCENTCLOUD_SECRET_ID") |
|
SecretKey = os.environ.get("TENCENTCLOUD_SECRET_KEY") |
|
cred = credential.Credential(SecretId, SecretKey) |
|
|
|
httpProfile = HttpProfile() |
|
httpProfile.endpoint = "tmt.tencentcloudapi.com" |
|
|
|
|
|
clientProfile = ClientProfile() |
|
clientProfile.httpProfile = httpProfile |
|
|
|
client = tmt_client.TmtClient(cred, "ap-shanghai", clientProfile) |
|
print(f'client_{client}') |
|
return client |
|
except TencentCloudSDKException as err: |
|
print(f'client_err_{err}') |
|
return None |
|
|
|
def getTextTrans_tmt(tmt_client, text, source='zh', target='en'): |
|
def is_chinese(string): |
|
for ch in string: |
|
if u'\u4e00' <= ch <= u'\u9fff': |
|
return True |
|
return False |
|
|
|
if tmt_client is None: |
|
return text |
|
if not is_chinese(text) and target == 'en': |
|
return text |
|
try: |
|
req = models.TextTranslateRequest() |
|
params = { |
|
"SourceText": text, |
|
"Source": source, |
|
"Target": target, |
|
"ProjectId": 0 |
|
} |
|
req.from_json_string(json.dumps(params)) |
|
resp = tmt_client.TextTranslate(req) |
|
return resp.TargetText |
|
except Exception as e: |
|
return text |
|
|
|
def getTextTrans(text, source='zh', target='en'): |
|
return getTextTrans_tmt(get_tmt_client(), text, source, target) |