Esempio n. 1
0
def translate_tencent(stxt):
    try:
        cred = credential.Credential(SecretId, SecretKey)
        httpProfile = HttpProfile()
        httpProfile.endpoint = "tmt.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = tmt_client.TmtClient(cred, "ap-beijing", clientProfile)

        req = models.TextTranslateRequest()
        # params = '{u"SourceText":"'+str(stxt)+'","Source":"en","Target":"zh","ProjectId":}'
        params = {
            u'SourceText': stxt,
            u'Source': 'en',
            u'Target': 'zh',
            u'ProjectId': ProjectId
        }
        # req.from_json_string(params)
        req._deserialize(params=params)
        resp = client.TextTranslate(req)
        print(resp.to_json_string())
        return resp.TargetText
    except TencentCloudSDKException as err:
        print(err)
def tencent_fanyi_query(q, f, t):
    if __tencent_conf is None:
        return
    app_key = __tencent_conf['fanyi_app_key']
    secret_key = __tencent_conf['fanyi_secret_key']
    try:
        cred = credential.Credential(app_key, secret_key)
        httpProfile = HttpProfile()
        httpProfile.endpoint = "tmt.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = tmt_client.TmtClient(cred, "ap-shanghai", clientProfile)

        req = models.TextTranslateRequest()

        params = json.dumps({
            'SourceText': q,
            'Source': f,
            'Target': t,
            'ProjectId': '1129592'
        }).encode('utf-8')
        req.from_json_string(params)

        resp = client.TextTranslate(req)
        return [resp.TargetText]

    except TencentCloudSDKException as err:
        raise err
Esempio n. 3
0
    def api_request(self, text: str) -> str:
        try:
            cred = credential.Credential(self.secret_id, self.secret_key)
            # cred = credential.Credential()
            httpProfile = HttpProfile()
            httpProfile.endpoint = "tmt.tencentcloudapi.com"

            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            client = tmt_client.TmtClient(cred, "ap-shanghai", clientProfile)

            req = models.TextTranslateRequest()
            params = {
                "SourceText": text,
                "Source": "en",
                "Target": "zh",
                "ProjectId": 0
            }
            req.from_json_string(json.dumps(params))

            resp = client.TextTranslate(req)

            return resp.TargetText

        except TencentCloudSDKException as err:
            logging.error(f"Error to use TencentAPI with {err}")
            return ""
Esempio n. 4
0
def tencent_get_translate(enstr):
    from tencentcloud.common import credential
    from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
    from tencentcloud.tmt.v20180321 import tmt_client, models

    try:
        # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
        cred = credential.Credential("AKIDVpthFYiS3Pdbqx8RpztUs53kCOhnrFZd",
                                     "NWQBp9CqDLFxOYXExqlY5PUNCn4C7iyc")
        # 实例化要请求产品(以cvm为例)的client对象
        client = tmt_client.TmtClient(cred, "ap-guangzhou")
        # 实例化一个请求对象
        req = models.TextTranslateRequest()
        req.SourceText = enstr
        req.Source = "auto"
        req.Target = "zh"
        req.ProjectId = 0

        # 通过client对象调用想要访问的接口,需要传入请求对象
        resp = client.TextTranslate(req)
        # 输出json格式的字符串回包
        return resp.TargetText

    except TencentCloudSDKException as err:
        print(err)
Esempio n. 5
0
def tanslationFun(inputData):
    try:

        while True:

            cred = credential.Credential(SecretId, SecretKey)

            client = tmt_client.TmtClient(cred, "ap-guangzhou")

            # 进行语种识别
            req = models.LanguageDetectRequest()
            '''
                Text	是	String	待识别的文本
                ProjectId	是	Integer	项目id
            '''
            params = """{
                "Text": "%s",
                "ProjectId": 1
            }""" % (inputData)

            req.from_json_string(params)

            resp = client.LanguageDetect(req)

            # 进行英汉互译
            fromLang = json.loads(resp.to_json_string())["Lang"]
            toLang = None
            if fromLang == "en":
                toLang = "zh"
            elif fromLang == "zh":
                toLang = "en"
            else:
                print("请输入英文或者中文,本软件暂不支持其他语言的翻译!")

            if toLang:
                req = models.TextTranslateRequest()
                '''
                    SourceText	是	String	待翻译的文本
                    Source	是	String	源语言,参照Target支持语言列表
                    Target	是	String
                    ProjectId	是	Integer	项目id
                '''
                params = """{
                    "SourceText": "%s",
                    "Source": "%s",
                    "Target": "%s",
                    "ProjectId": 1
                }""" % (inputData, fromLang, toLang)

                req.from_json_string(params)

                resp = client.TextTranslate(req)

                return json.loads(resp.to_json_string())["TargetText"]

    except TencentCloudSDKException as e:
        return None
Esempio n. 6
0
    def initQQ(self):
        cred = credential.Credential("AKIDjLfWmLkSxnwN7ClhNNgJFYsVoRMerQkB",
                                     "pq3T4mcYGV8ngbnNGY8BXDGbIV2xLugk")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "tmt.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        self.client = tmt_client.TmtClient(cred, "ap-chengdu", clientProfile)

        self.req = models.TextTranslateRequest()
Esempio n. 7
0
 def TraslatorTencentPara(self, para: str) -> str:
     try:
         reqDoc = models.TextTranslateRequest()
         reqDoc.SourceText = para
         reqDoc.Source = "en"
         reqDoc.Target = "zh"
         reqDoc.ProjectId = 1
         resp = self.client.TextTranslate(reqDoc)
     except TencentCloudSDKException as err:
         print(err)
         return None
     return resp.TargetText
Esempio n. 8
0
def tencentTranslate(text, source_language, Is2language):
    try:
        cred = credential.Credential("ID", "Key")
        httpProfile = HttpProfile()
        httpProfile.endpoint = "tmt.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = tmt_client.TmtClient(cred, "ap-beijing", clientProfile)

        req_text = models.TextTranslateRequest()
        if text[-1:] == '\n':
            text = text[0:len(text) - 1]
        #source_language = tencentLanguageDetect(text)
        text_params_front = '{"SourceText":"'
        if source_language == 1:
            text_params_back = '","Source":"auto","Target":"en","ProjectId":0}'
        else:
            text_params_back = '","Source":"auto","Target":"zh","ProjectId":0}'
        text_params = text_params_front + text + text_params_back
        req_text.from_json_string(text_params)

        resp_text = client.TextTranslate(req_text)
        responsetext = resp_text.to_json_string()
        transtext = ''
        for index in range(16, len(responsetext)):
            if responsetext[index] != "\"":
                transtext += responsetext[index]
            else:
                break

    except TencentCloudSDKException as err:
        errortext = 'TencentCloudError' + str(err)
        return errortext

    return_text = ''
    if Is2language:
        return_text = text
        return_text += '\n'
    return_text += transtext
    if Is2language:
        return_text += '\n'
    return return_text


#text = 'common'
#print(tencentTranslate(text))
Esempio n. 9
0
def getChinese(English):
    try:
        cred = credential.Credential(os.environ.get('tencent_secret_id'),
                                     os.environ.get('tencent_secret_key'))
        httpProfile = HttpProfile()
        httpProfile.endpoint = "tmt.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = tmt_client.TmtClient(cred, "ap-chengdu", clientProfile)

        req = models.TextTranslateRequest()
        params = '{"SourceText":"%s","Source":"en","Target":"zh","ProjectId":0}' % English
        req.from_json_string(params)

        resp = client.TextTranslate(req)
        return resp.to_json_string()

    except TencentCloudSDKException as err:
        print(err)
        return False
Esempio n. 10
0
 def translate(self, text):
     try:
         cred = credential.Credential(self.config["tencentId"],
                                      self.config["tencentKey"])
         httpProfile = HttpProfile()
         httpProfile.endpoint = "tmt.tencentcloudapi.com"
         clientProfile = ClientProfile()
         clientProfile.httpProfile = httpProfile
         client = tmt_client.TmtClient(cred, "ap-guangzhou", clientProfile)
         req = models.TextTranslateRequest()
         params = {
             "SourceText": text,
             "Source": "auto",
             "Target": "zh",
             "ProjectId": 0
         }
         req.from_json_string(json.dumps(params))
         resp = client.TextTranslate(req)
         res = json.loads(resp.to_json_string())
         return res.get("TargetText")
     except TencentCloudSDKException as err:
         raise Exception(err)
Esempio n. 11
0
        # 进行英汉互译
        fromLang = json.loads(resp.to_json_string())["Lang"]  # en
        # print ('......', json.loads(resp.to_json_string()), '......', fromLang, '......')
        # {'Lang': 'en', 'RequestId': 'aeaaf5da-955f-4bd7-a8ea-04797e5e7a11'}

        toLang = None
        if fromLang == "en":
            toLang = "zh"
        elif fromLang == "zh":
            toLang = "en"
        else:
            print("请输入英文或者中文,本软件暂不支持其他语言的翻译!")

        if toLang:
            req = models.TextTranslateRequest()  # 初始化一个文本翻译类型实例
            '''
                SourceText	是	String	待翻译的文本
                Source	是	String	源语言,参照Target支持语言列表
                Target	是	String
                ProjectId	是	Integer	项目id
            '''
            params1 = """{
                "SourceText": "%s",
                "Source": "%s",
                "Target": "%s",
                "ProjectId": 1
            }""" % (inputData, fromLang, toLang)

            req.from_json_string(params1)
Esempio n. 12
0
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
inp = open('yuliao1.txt','r',encoding='utf-8').readlines()
oup = open('yuliaofanyi1.txt','w',encoding='utf-8')
try:
    cred = credential.Credential("AKIDvgAIwYPTlpfFa3KuhU3NfndQzIm3gzdI", "94kJQ3f2EaP9qQzDUbKgtxr0xlnjkeps")
    httpProfile = HttpProfile()
    httpProfile.endpoint = "tmt.tencentcloudapi.com"

    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = tmt_client.TmtClient(cred, "ap-beijing", clientProfile)

    req = models.TextTranslateRequest()

    params = {
        "SourceText": "eee1MichaelPentelladdd1 PhD , is Director of the eee2BureauSciencesddd2 at the eee3HintonInstituteddd3 , Commonwealth of eee4Massachusettsddd4 . He previously served as the Associate Director of the eee5Iowalaboratoryddd5 and as Clinical Associate Professor at the eee6CollegeHealthddd6 , eee7UniversityIowaddd7 .Dr. has more than 30 years of experience in clinical and public health laboratories and is board certified in medical microbiology and infection control.",
        "Source": "auto",
        "Target": "zh",
        "ProjectId": 0
    }
    for line in tqdm(inp):
        line =line.rstrip('\n')
        params["SourceText"]=line
        req.from_json_string(json.dumps(params))

        resp = client.TextTranslate(req)
        # print(eval(resp.to_json_string())['TargetText'])
        oup.write(eval(resp.to_json_string())['TargetText']+'\n')
Esempio n. 13
0
def tencent(sentence, secret_id, secret_key, logger):

    result = ""

    # 如果未注册
    if (not secret_id) or (not secret_key):
        return "私人腾讯: 还未注册私人腾讯API, 不可使用"

    try:
        cred = credential.Credential(secret_id, secret_key)
        httpProfile = HttpProfile()
        httpProfile.endpoint = "tmt.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        client = tmt_client.TmtClient(cred, "ap-guangzhou", clientProfile)

        req = models.TextTranslateRequest()
        sentence = sentence.replace('"', "'")
        params = '''{"SourceText":"%s","Source":"auto","Target":"zh","ProjectId":0}''' % (
            sentence)
        params = params.replace('\r', '\\r').replace('\n', '\\n')
        req.from_json_string(params)

        resp = client.TextTranslate(req)
        result = re.findall(r'"TargetText": "(.+?)"', resp.to_json_string())[0]
        result = result.replace('\\r', '\r').replace('\\n', '\n')

    except TencentCloudSDKException as err:

        try:
            err = str(err)
            code = re.findall(r'code:(.*?) message', err)[0]
            error = re.findall(r'message:(.+?) requestId', err)[0]

        except Exception:
            logger.error(format_exc())
            result = "私人腾讯:我抽风啦!"

        else:
            if code == "MissingParameter":
                pass

            elif code == "FailedOperation.NoFreeAmount":
                result = "私人腾讯:本月免费额度已经用完"

            elif code == "FailedOperation.ServiceIsolate":
                result = "私人腾讯:账号欠费停止服务"

            elif code == "FailedOperation.UserNotRegistered":
                result = "私人腾讯:还没有开通机器翻译服务"

            elif code == "InternalError":
                result = "私人腾讯:内部错误"

            elif code == "InternalError.BackendTimeout":
                result = "私人腾讯:后台服务超时,请稍后重试"

            elif code == "InternalError.ErrorUnknown":
                result = "私人腾讯:未知错误"

            elif code == "LimitExceeded":
                result = "私人腾讯:超过配额限制"

            elif code == "UnsupportedOperation":
                result = "私人腾讯:操作不支持"

            elif code == "InvalidCredential":
                result = "私人腾讯:secretId或secretKey错误"

            elif code == "AuthFailure.SignatureFailure":
                result = "私人腾讯:secretKey错误"

            elif code == "AuthFailure.SecretIdNotFound":
                result = "私人腾讯:secretId错误"

            elif code == "AuthFailure.SignatureExpire":
                result = "私人腾讯:签名过期,请将电脑系统时间调整至准确的时间后重试"

            else:
                result = "私人腾讯: %s, %s" % (code, error)

    except Exception:
        logger.error(format_exc())
        result = "私人腾讯:我抽风啦!"

    return result
Esempio n. 14
0
def tencent(sentence, data):

    secretId = data['tencentAPI']['Key']
    secretKey = data['tencentAPI']['Secret']

    if (not secretId) or (not secretKey):
        string = '私人腾讯:还未注册私人腾讯API,不可使用'
    else:
        try:
            cred = credential.Credential(secretId, secretKey)
            httpProfile = HttpProfile()
            httpProfile.endpoint = "tmt.tencentcloudapi.com"

            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            client = tmt_client.TmtClient(cred, "ap-guangzhou", clientProfile)

            req = models.TextTranslateRequest()
            sentence = sentence.replace('"', "'")
            params = '''{"SourceText":"%s","Source":"auto","Target":"zh","ProjectId":0}''' % (
                sentence)
            req.from_json_string(params)

            resp = client.TextTranslate(req)
            result = re.findall(r'"TargetText": "(.+?)"',
                                resp.to_json_string())[0]

        except TencentCloudSDKException as err:

            err = str(err)
            code = re.findall(r'code:(.*?) message', err)[0]
            error = re.findall(r'message:(.+?) requestId', err)[0]

            if code == 'MissingParameter':
                pass

            elif code == 'FailedOperation.NoFreeAmount':
                result = "私人腾讯:本月免费额度已经用完"

            elif code == 'FailedOperation.ServiceIsolate':
                result = "私人腾讯:账号欠费停止服务"

            elif code == 'FailedOperation.UserNotRegistered':
                result = "私人腾讯:还没有开通机器翻译服务"

            elif code == 'InternalError':
                result = "私人腾讯:内部错误"

            elif code == 'InternalError.BackendTimeout':
                result = "私人腾讯:后台服务超时,请稍后重试"

            elif code == 'InternalError.ErrorUnknown':
                result = "私人腾讯:未知错误"

            elif code == 'LimitExceeded':
                result = "私人腾讯:超过配额限制"

            elif code == 'UnsupportedOperation':
                result = "私人腾讯:操作不支持"

            elif code == 'InvalidCredential':
                result = "私人腾讯:secretId或secretKey错误"

            elif code == 'AuthFailure.SignatureFailure':
                result = "私人腾讯:secretKey错误"

            elif code == 'AuthFailure.SecretIdNotFound':
                result = "私人腾讯:secretId错误"

            elif code == 'AuthFailure.SignatureExpire':
                result = "私人腾讯:签名过期,请将电脑系统时间调整至准确的时间后重试"

            else:
                result = "私人腾讯:%s,%s" % (code, error)

        except Exception:
            print_exc()
            result = '私人腾讯:我抽风啦!'

    return result
Esempio n. 15
0
    def trans(self):
        content = self.textEdit.toPlainText()

        if content:
            contentList = content.split("\n")
            # print(contentList)
            resultData = []
            for inputData in contentList:
                SecretId = "AKIDkLoCSYPchcMvMhL01ylNo7I5Jk7JLCxY"
                SecretKey = "c5FzaDqRs8ECzbaTGFSXXM3jHj3Cg2GJ"
                cred = credential.Credential(SecretId, SecretKey)

                client = tmt_client.TmtClient(cred, "ap-guangzhou")

                # 进行语种识别
                req = models.LanguageDetectRequest()
                '''
                    Text	是	String	待识别的文本
                    ProjectId	是	Integer	项目id
                '''
                # language_content = re.f
                params = """{
                            "Text": "%s",
                            "ProjectId": 1
                        }""" % (inputData)

                req.from_json_string(params)

                resp = client.LanguageDetect(req)

                # 进行英汉互译
                fromLang = json.loads(resp.to_json_string())["Lang"]
                print('=====', fromLang)
                toLang = None
                if fromLang == "en":
                    toLang = "zh"
                elif fromLang == "zh":
                    toLang = "en"
                else:
                    # print ('=====')
                    self.textEdit_2.setText(
                        "请输入英文或者中文,本软件暂不支持其他语言的翻译!")  # 存在bug,这句执行结果不能在文本框中显示
                    # print ('+++')
                    break

                if toLang:
                    req = models.TextTranslateRequest()
                    '''
                        SourceText	是	String	待翻译的文本
                        Source	是	String	源语言,参照Target支持语言列表
                        Target	是	String
                        ProjectId	是	Integer	项目id
                    '''
                    params = """{
                                "SourceText": "%s",
                                "Source": "%s",
                                "Target": "%s",
                                "ProjectId": 1
                            }""" % (inputData, fromLang, toLang)

                    req.from_json_string(params)

                    resp = client.TextTranslate(req)

                    resultData.append(
                        json.loads(resp.to_json_string())["TargetText"])
            self.textEdit_2.setText("\n".join(resultData))
        else:
            self.textEdit_2.setText("请输入翻译内容!")