yizhangliu commited on
Commit
4778a57
1 Parent(s): 7519d09

Upload utils.py

Browse files
Files changed (1) hide show
  1. utils.py +54 -0
utils.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json, os
2
+ from tencentcloud.common import credential
3
+ from tencentcloud.common.profile.client_profile import ClientProfile
4
+ from tencentcloud.common.profile.http_profile import HttpProfile
5
+ from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
6
+ from tencentcloud.tmt.v20180321 import tmt_client, models
7
+
8
+ def get_tmt_client():
9
+ try:
10
+ # 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
11
+ # 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见:https://cloud.tencent.com/document/product/1278/85305
12
+ # 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
13
+ SecretId = os.environ.get("TENCENTCLOUD_SECRET_ID")
14
+ SecretKey = os.environ.get("TENCENTCLOUD_SECRET_KEY")
15
+ cred = credential.Credential(SecretId, SecretKey)
16
+ # 实例化一个http选项,可选的,没有特殊需求可以跳过
17
+ httpProfile = HttpProfile()
18
+ httpProfile.endpoint = "tmt.tencentcloudapi.com"
19
+
20
+ # 实例化一个client选项,可选的,没有特殊需求可以跳过
21
+ clientProfile = ClientProfile()
22
+ clientProfile.httpProfile = httpProfile
23
+ # 实例化要请求产品的client对象,clientProfile是可选的
24
+ client = tmt_client.TmtClient(cred, "ap-shanghai", clientProfile)
25
+ print(f'client_{client}')
26
+ return client
27
+ except TencentCloudSDKException as err:
28
+ print(f'client_err_{err}')
29
+ return None
30
+
31
+ def getTextTrans_tmt(tmt_client, text, source='zh', target='en'):
32
+ def is_chinese(string):
33
+ for ch in string:
34
+ if u'\u4e00' <= ch <= u'\u9fff':
35
+ return True
36
+ return False
37
+
38
+ if tmt_client is None:
39
+ return text
40
+ if not is_chinese(text) and target == 'en':
41
+ return text
42
+ try:
43
+ req = models.TextTranslateRequest()
44
+ params = {
45
+ "SourceText": text,
46
+ "Source": source,
47
+ "Target": target,
48
+ "ProjectId": 0
49
+ }
50
+ req.from_json_string(json.dumps(params))
51
+ resp = tmt_client.TextTranslate(req)
52
+ return resp.TargetText
53
+ except Exception as e:
54
+ return text