Ejemplo n.º 1
0
 def get_client(self):
     # Required steps:
     # Instantiate an authentication object. The Tencent Cloud account key pair `secretId` and `secretKey` need to be passed in as the input parameters.
     # The example here uses the way to read from the environment variable, so you need to set these two values in the environment variable first.
     # You can also write the key pair directly into the code, but be careful not to copy, upload, or share the code to others;
     # otherwise, the key pair may be leaked, causing damage to your properties.
     # Query the CAM key: https://console.cloud.tencent.com/cam/capi
     cred = credential.Credential(self.tencent_sms_secret_id,
                                  self.tencent_sms_secret_key)
     # cred = credential.Credential(
     #     os.environ.get(""),
     #     os.environ.get("")
     # )
     # (Optional) Instantiate an HTTP option
     httpProfile = HttpProfile()
     # If you need to specify the proxy for API access, you can initialize HttpProfile as follows
     # httpProfile = HttpProfile(proxy="http://*****:*****@proxy IP:proxy port")
     httpProfile.reqMethod = "POST"  # POST request (POST request by default)
     httpProfile.reqTimeout = 30  # Request timeout period in seconds (60 seconds by default)
     httpProfile.endpoint = "sms.tencentcloudapi.com"  # Specify the access region domain name (nearby access by default)
     # Optional steps:
     # Instantiate a client configuration object. You can specify the timeout period and other configuration items
     clientProfile = ClientProfile()
     clientProfile.signMethod = "TC3-HMAC-SHA256"  # Specify the signature algorithm
     clientProfile.language = "en-US"
     clientProfile.httpProfile = httpProfile
     # Instantiate the client object of the requested product (with SMS as an example)
     # The second parameter is the region information. You can directly enter the string `ap-guangzhou` or import the preset constant
     client = SmsClient(cred, self.tencent_sms_region, clientProfile)
     return client
def init_oral_process(SessionId,RefText,base64_data):
    # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
    cred = credential.Credential("AKIDxe5GDPX6aonW1G78hyzmLglpeFagr9Vc", "A9uRkpfFZpqb6MQEm48xVaTs0ub3GDtK")

    # 实例化一个http选项,可选的,没有特殊需求可以跳过。
    httpProfile = HttpProfile()
    httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
    httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
    httpProfile.endpoint = "soe.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)
    httpProfile.keepAlive = True

    # 实例化一个client选项,可选的,没有特殊需求可以跳过。
    clientProfile = ClientProfile()
    clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法(默认为HmacSHA256)
    clientProfile.unsignedPayload = True
    clientProfile.httpProfile = httpProfile

    client = soe_client.SoeClient(cred, "", clientProfile)
    req = models.InitOralProcessRequest()
    req.SessionId = SessionId
    req.RefText = RefText
    req.WorkMode = 1
    req.EvalMode = 0
    req.ScoreCoeff = 1.0

    resp = client.InitOralProcess(req)

    # 输出json格式的字符串回包
    print("初始化:%s" % resp.to_json_string())
    transmit(SessionId,base64_data)
Ejemplo n.º 3
0
def _test_describe_instances(http_method, sign_method, unsigned_payload=False):
    cred = credential.Credential(os.environ.get("TENCENTCLOUD_SECRET_ID"),
                                 os.environ.get("TENCENTCLOUD_SECRET_KEY"))

    httpProfile = HttpProfile()
    httpProfile.reqMethod = http_method

    clientProfile = ClientProfile()
    clientProfile.signMethod = sign_method
    clientProfile.unsignedPayload = unsigned_payload
    clientProfile.httpProfile = httpProfile

    client = cvm_client.CvmClient(cred, "ap-guangzhou", clientProfile)
    req = models.DescribeInstancesRequest()
    headers = {
        "X-TC-TraceId": "ffe0c072-8a5d-4e17-8887-a8a60252abca",
    }
    req.headers = headers

    fzone = models.Filter()
    fzone.Name = "zone"
    fzone.Values = ["ap-guangzhou-1", "ap-guangzhou-2"]
    fname = models.Filter()
    fname.Name = "instance-name"
    fname.Values = [u"中文", u"测试"]
    req.Filters = [fzone, fname]
    resp = client.DescribeInstances(req)
    assert resp.TotalCount >= 0
    def __init__(self):
        self.name = QC_NAME
        self.region = REGION
        self.logger = getLogger()
        self.logger.info("Init Qcloud SCF Client...\n")
        self.logger.info("The region is: %s\n" % self.region)
        cred = credential.Credential(QC_API_ID, QC_API_KEY)
        self.logger.info("The secert info:")
        self.logger.info("Secret Id: %s" % (QC_API_ID[0:5]+"******"))
        self.logger.info("Secret Key: %s\n" % (QC_API_KEY[0:5]+"******"))
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "GET"
        httpProfile.reqTimeout = 30
        httpProfile.endpoint = QC_ENDPOINT_MODEL % self.region
        self.logger.info("The request endpoint is: %s\n" % httpProfile.endpoint)
        httpProfile.keepAlive = True

        clientProfile = ClientProfile()

        clientProfile.signMethod = "HmacSHA256"
        clientProfile.httpProfile = httpProfile

        self.client = scf_client.ScfClient(cred, 'ap-' + self.region, clientProfile)

        self.logger.info("SCF client init success!\n")

        self.logger.info("Start to get VPC info...")
        self.logger.info("VPC id is: %s"% QC_VPC)
        self.logger.info("VPC-Subnet id is: %s\n" % QC_SUBNET)
Ejemplo n.º 5
0
 def GetAsrResult(self):
     #本地文件方式请求
     try:
         cred = credential.Credential(self.SecretID, self.SecretKey)
         httpProfile = HttpProfile()
         httpProfile.endpoint = self.Url
         clientProfile = ClientProfile()
         clientProfile.httpProfile = httpProfile
         clientProfile.signMethod = "TC3-HMAC-SHA256"
         client = asr_client.AsrClient(cred, "ap-shanghai", clientProfile)
         #读取文件以及 base64
         with open(self.AudioFile, "rb") as f:
             audio = f.read()
             if self.Format == 'pcm':
                 audio = utils.PcmToWav(audio)
             if sys.version_info[0] == 2:
                 content = base64.b64encode(audio)
             else:
                 content = base64.b64encode(audio).decode('utf-8')
         #发送请求
         req = models.SentenceRecognitionRequest()
         params = {"ProjectId": 0, "SubServiceType": 2, "SourceType": 1, "UsrAudioKey": "session-123"}
         req._deserialize(params)
         req.DataLen = len(content)
         req.Data = content
         req.EngSerViceType = "16k_zh"
         req.VoiceFormat = "wav"
         req.FilterPunc = 2 #是否过滤标点符号(目前支持中文普通话引擎)。 0:不过滤,1:过滤句末标点,2:过滤所有标点。默认为0。
         req.ConvertNumMode = 0 #是否进行阿拉伯数字智能转换。0:不转换,直接输出中文数字,1:根据场景智能转换为阿拉伯数字。默认值为1
         resp = client.SentenceRecognition(req)
         logger.info("file:%s, result:%s, sid:%s", self.AudioFile, resp.Result, resp.RequestId)
         return resp.Result
     except TencentCloudSDKException as err:
         logger.error("code:%s, message:%s, sid:%s", err.code, err.message, err.requestId)
         return ""
Ejemplo n.º 6
0
    def img_to_excel(self, image_path, secret_id, secret_key):

        # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
        cred = credential.Credential(secret_id, secret_key)

        # 实例化client对象
        httpProfile = HttpProfile()
        httpProfile.endpoint = "ocr.tencentcloudapi.com"
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        clientProfile.signMethod = "TC3-HMAC-SHA256"
        client = ocr_client.OcrClient(cred, "ap-guangzhou", clientProfile)

        # 实例化一个请求对象
        req = models.GeneralFastOCRRequest()

        # 读取图片数据,使用Base64编码
        with open(image_path, 'rb') as f:
            image = f.read()
            image_base64 = str(base64.b64encode(image), encoding='utf-8')
        req.ImageBase64 = image_base64

        # 通过client对象调用访问接口,传入请求对象
        resp = client.TableOCR(req)

        # 获取返回数据(Data为Base64编码后的Excel数据)
        data = resp.Data

        # 转换为Excel
        path_excel = image_path + ".xlsx"
        with open(path_excel, 'wb') as f:
            f.write(base64.b64decode(data))
        return path_excel
Ejemplo n.º 7
0
def test_big_package_with_signature_v1():
    for sign_method, req_method in product(["HmacSHA1", "HmacSHA256"], ["GET", "POST"]):
        cred = credential.Credential(
            os.environ.get("TENCENTCLOUD_SECRET_ID"),
            os.environ.get("TENCENTCLOUD_SECRET_KEY"))
        http_profile = HttpProfile()
        http_profile.reqMethod = req_method
        client_profile = ClientProfile()
        client_profile.httpProfile = http_profile
        client_profile.signMethod = sign_method
        client = iai_client.IaiClient(cred, "ap-guangzhou", client_profile)

        req = models.CompareFaceRequest()
        params = {
            "ImageA": "1" * 1024 * 1024 * 4,
            "ImageB": "1" * 1024 * 1024 * 1,
            "UrlA": "https://cloudapi-test-1254240205.cos.ap-nanjing.myqcloud.com/9d1f1393e5fc5ca13032e40e3bf9e882.jpeg",
            "UrlB": "https://cloudapi-test-1254240205.cos.ap-nanjing.myqcloud.com/9d1f1393e5fc5ca13032e40e3bf9e882.jpeg",
        }
        req.from_json_string(json.dumps(params))
        try:
            resp = client.CompareFace(req)
            assert False, 'expect fail but success'
        except TencentCloudSDKException:
            pass
Ejemplo n.º 8
0
def login():
    # if request.method == 'POST':
    # 获取通过url请求传参的数据
    Phone = request.form.get("Phone")
    Code = request.form.get("Code")
    print('Phone')
    # 获取url请求传的密码,明文
    try:
        # 必要步骤:
        # 实例化一个认证对象,入参需要传入腾讯云账户密钥对 secretId 和 secretKey
        # 本示例采用从环境变量读取的方式,需要预先在环境变量中设置这两个值
        # 您也可以直接在代码中写入密钥对,但需谨防泄露,不要将代码复制、上传或者分享给他人
        # CAM 密钥查询:https://console.cloud.tencent.com/cam/capi
        cred = credential.Credential("AKIDDBub3vFl6DZfaGe26B0cy6yb7d1Arcvy",
                                     "zkEgy1pIWUBdQy291tWhlYooZ5uVt1u4")
        # cred = credential.Credential(
        #     os.environ.get(""),
        #     os.environ.get("")
        # )
        # 实例化一个 http 选项,可选,无特殊需求时可以跳过
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # POST 请求(默认为 POST 请求)
        httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
        httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)
        # # 非必要步骤:
        # # 实例化一个客户端配置对象,可以指定超时时间等配置
        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
        clientProfile.language = "en-US"
        clientProfile.httpProfile = httpProfile
        client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)
        req = models.SendSmsRequest()
        req.SmsSdkAppid = "1400464331"
        # # 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名,可登录 [短信控制台] 查看签名信息
        req.Sign = "JiuKey"
        # 短信码号扩展号: 默认未开通,如需开通请联系 [sms helper]
        req.ExtendCode = ""
        # 用户的 session 内容: 可以携带用户侧 ID 等上下文信息,server 会原样返回
        req.SessionContext = "xxx"
        # 国际/港澳台短信 senderid: 国内短信填空,默认未开通,如需开通请联系 [sms helper]
        req.SenderId = ""
        # 下发手机号码,采用 e.164 标准,+[国家或地区码][手机号]
        # 例如+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号
        req.PhoneNumberSet = [Phone]
        # 模板 ID: 必须填写已审核通过的模板 ID,可登录 [短信控制台] 查看模板 ID
        req.TemplateID = "818049"
        # 模板参数: 若无模板参数,则设置为空
        req.TemplateParamSet = [Code]
        # # 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的
        resp = client.SendSms(req)
        # 输出 JSON 格式的字符串回包
        print(resp.to_json_string(indent=2))
        return Phone

    except TencentCloudSDKException as err:
        print(err)
    return 'success'
Ejemplo n.º 9
0
    def send_message(self, PhoneNumberSet, TemplateID, TemplateParamSet):
        """
        :param PhoneNumberSet: 发送手机号
        :param TemplateID: 短信模板ID
        :param TemplateParamSet: 模板中的参数
        :return:
        """
        cred = credential.Credential(self.apiId, self.apiKey)

        # 实例化一个 http 选项,可选,无特殊需求时可以跳过
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # POST 请求(默认为 POST 请求)
        httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
        # httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

        # 非必要步骤:
        # 实例化一个客户端配置对象,可以指定超时时间等配置
        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
        clientProfile.language = "en-US"
        clientProfile.httpProfile = httpProfile
        # 实例化 SMS 的 client 对象
        # 第二个参数是地域信息,可以直接填写字符串 ap-guangzhou,或者引用预设的常量
        client = sms_client.SmsClient(cred, "ap-shanghai", clientProfile)

        messageDict = {
            "PhoneNumberSet": PhoneNumberSet,
            "TemplateID": TemplateID,
            "SmsSdkAppid": smsAppId,
            "Sign": sign,
            "TemplateParamSet": TemplateParamSet,
        }

        # 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
        req = requestSms(messageDict)

        try:
            # 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的
            resp = client.SendSms(req)
            # 输出 JSON 格式的字符串回包
            print(resp.to_json_string(indent=2))
            resp = json.loads(
                resp.to_json_string(indent=0).replace(
                    r"\n", "")).get("SendStatusSet")[0]
            return resp
        except TencentCloudSDKException as err:
            print(err)
            err = {
                key.capitalize(): value
                for key, value in err.__dict__.items()
            }
            return err
Ejemplo n.º 10
0
def recognize_wav(wav_path, show_detail=True):
    # 通过本地语音上传方式调用
    try:

        # 重要:<Your SecretId>、<Your SecretKey>需要替换成用户自己的账号信息
        # 请参考接口说明中的使用步骤1进行获取。
        cred = credential.Credential(tencent_secret_id, tencent_secret_key)
        httpProfile = HttpProfile()
        httpProfile.endpoint = "asr.tencentcloudapi.com"
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        clientProfile.signMethod = "TC3-HMAC-SHA256"
        client = asr_client.AsrClient(cred, "ap-shanghai", clientProfile)

        # 读取文件以及base64
        with reader.SaveOpen(to_mp3(wav_path), 'rb') as fwave:
            data = str(fwave.read())
        dataLen = len(data)
        base64Wav = base64.b64encode(data)

        # 发送请求
        req = models.SentenceRecognitionRequest()
        params = {
            "ProjectId": 0,
            "SubServiceType": 2,
            "EngSerViceType": "16k_en",
            "SourceType": 1,
            "Url": "",
            "VoiceFormat": "mp3",
            "UsrAudioKey": "session-123",
            "Data": base64Wav,
            "DataLen": dataLen
        }
        req._deserialize(params)
        resp = client.SentenceRecognition(req)
        if show_detail:
            print(resp.to_json_string())
        # windows系统使用下面一行替换上面一行
        # print(resp.to_json_string().decode('UTF-8').encode('GBK') )

        words = []

        for w in resp.Result.split():
            if not re.match('[a-zA-W]', w[-1:]):
                w = w[0:-1]
            words.append(w)
        return ' '.join(words).lower()

    except TencentCloudSDKException as err:
        print(err)
        return '[ERROR]'
Ejemplo n.º 11
0
 def __init__(self, keys: Dict[str, str]):
     """
     Arguments:
         keys {Dict[str, str]} -- authorization keys
         requires "secret_id", "secret_key"
     """
     cred = credential.Credential(keys['secret_id'], keys['secret_key'])
     httpProfile = HttpProfile()
     httpProfile.endpoint = "asr.tencentcloudapi.com"
     clientProfile = ClientProfile()
     clientProfile.httpProfile = httpProfile
     clientProfile.signMethod = "TC3-HMAC-SHA256"
     self.client = asr_client.AsrClient(cred, "ap-shanghai", clientProfile)
     self.lang = keys.get('lang', 'zh')
Ejemplo n.º 12
0
def new_vpc_client(cred, method):

    httpProfile = HttpProfile()

    httpProfile.reqMethod = "GET"
    HttpProfile.reqTimeout = 30
    httpProfile.endpoint = "cvm.ap-guangzhou.tencentcloudapit.com"
    clientProfile = ClientProfile()
    clientProfile.signMethod = "HmacSHA256"
    clientProfile.HttpProfile = httpProfile

    client = vpc_client.VpcClient(cred, "ap-guangzhou", clientProfile)

    return client
Ejemplo n.º 13
0
    def __init__(self, secret_id: str, secret_key: str, sdkappid: str):
        self.sdkappid = sdkappid

        cred = credential.Credential(secret_id, secret_key)
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
        httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
        httpProfile.endpoint = "sms.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
        clientProfile.language = "en-US"
        clientProfile.httpProfile = httpProfile
        self.client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)
Ejemplo n.º 14
0
    def __init__(self):
        # 实例化一个客户端配置对象,可以指定超时时间等配置
        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法

        # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
        self.cred = credential.Credential(secretId, secretKey)
        
        # 实例化要请求产品(以cvm为例)的client对象
        self.client = ticm_client.TicmClient(self.cred,'ap-guangzhou',clientProfile)

        # 实例化一个请求对象
        self.req = models.ImageModerationRequest()
        self.req.Scenes = ["P**N"]
Ejemplo n.º 15
0
    def __init__(self):
        # 实例化一个客户端配置对象,可以指定超时时间等配置
        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法

        # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
        self.cred = credential.Credential(secretId, secretKey)

        # 实例化要请求产品(以cvm为例)的client对象
        self.client = iai_client.IaiClient(self.cred,'ap-chengdu',clientProfile)

        # 实例化一个请求对象
        self.req = models.DetectFaceRequest()
        self.req.FaceModelVersion = "3.0"
        self.req.NeedFaceAttributes = 1
def test_signature_v1_ok():
    for reqmethod in reqmethod_list:
        cred = credential.Credential(os.environ.get("TENCENTCLOUD_SECRET_ID"),
                                     os.environ.get("TENCENTCLOUD_SECRET_KEY"))
        httpProfile = HttpProfile()
        httpProfile.endpoint = "cvm.tencentcloudapi.com"
        httpProfile.reqMethod = reqmethod

        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"
        clientProfile.httpProfile = httpProfile
        client = cvm_client.CvmClient(cred, "ap-guangzhou", clientProfile)

        req = models.DescribeZonesRequest()
        resp = client.DescribeZones(req)
Ejemplo n.º 17
0
    def __init__(self):

        #####################################  以下为自定义设置区 ##########################################
        self.my_id = ''   # 自己的腾讯云secretId
        self.my_key = ''      # 自己的腾讯云secretKey

        #####################################  以上为自定义设置区 ##########################################

        cred = credential.Credential(self.my_id, self.my_key)
        httpProfile = HttpProfile()
        httpProfile.endpoint = "asr.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        clientProfile.signMethod = "TC3-HMAC-SHA256"

        self.client = asr_client.AsrClient(cred, "ap-shanghai", clientProfile)
Ejemplo n.º 18
0
    def sentence_asr(self):
        # 本地文件方式请求
        try:
            cred = credential.Credential(self.SecretId, self.SecretKey)
            httpProfile = HttpProfile()
            httpProfile.endpoint = "asr.tencentcloudapi.com"
            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            clientProfile.signMethod = "TC3-HMAC-SHA256"
            client = asr_client.AsrClient(cred, "ap-shanghai", clientProfile)
            # 读取文件以及 base64
            # 此处可以下载测试音频 https://asr-audio-1300466766.cos.ap-nanjing.myqcloud.com/test16k.wav
            with open(self.data, "rb") as f:
                content = base64.b64encode(f.read()).decode('utf-8')
            # 发送请求
            req = models.SentenceRecognitionRequest()
            if self.type:
                params = {
                    "ProjectId": 0,
                    "SubServiceType": 2,
                    "SourceType": 1,
                    "UsrAudioKey": "session-123"
                }
            else:
                params = {
                    "ProjectId": 0,
                    "SubServiceType": 2,
                    "SourceType": 0,
                    "UsrAudioKey": "session-123"
                }
                req.url = self.data

            req._deserialize(params)
            req.EngSerViceType = "16k_zh"
            req.VoiceFormat = "wav"
            if self.type:
                req.DataLen = len(content)
                req.Data = content

            resp = client.SentenceRecognition(req)
            res = resp.to_json_string()
            res = json.loads(res)['Result']
            res = res.replace('。', '').replace(',', '').replace(',', '')
            return res
        except TencentCloudSDKException as err:
            print('tencent返回错误:%s' % err)
Ejemplo n.º 19
0
def processing(path):
    try:
        cred = credential.Credential(api_id, api_key)
        httpProfile = HttpProfile()
        httpProfile.endpoint = "ocr.tencentcloudapi.com"

        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        clientProfile.signMethod = "TC3-HMAC-SHA256"
        client = ocr_client.OcrClient(cred, "ap-guangzhou", clientProfile)

        req = models.GeneralBasicOCRRequest()
        req.ImageBase64 = ImageBase64(path)

        resp = client.GeneralBasicOCR(req)
        return resp
    except TencentCloudSDKException as err:
        print("SDK错误:" + str(err))
        return None
def InitOral(text):

    try:
        # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
        cred = credential.Credential("AKIDb7SivKPjOsM9wYuYufbR6kCd8Yj1dA95",
                                     "yWmqsjR1qW0UmzARRfjcQ3byHEoDRZXl")

        # 实例化一个http选项,可选的,没有特殊需求可以跳过。
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
        httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
        httpProfile.endpoint = "soe.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

        # 实例化一个client选项,可选的,没有特殊需求可以跳过。
        clientProfile = ClientProfile()
        clientProfile.signMethod = "HmacSHA256"  # 指定签名算法(默认为HmacSHA256)
        clientProfile.httpProfile = httpProfile

        client = soe_client.SoeClient(cred, "", clientProfile)
        req = models.InitOralProcessRequest()
        req.SessionId = "stress_test_956938"
        req.RefText = "Actually, he has over a million subscribers."
        req.WorkMode = 0
        req.EvalMode = 1
        req.ScoreCoeff = 3.5

        headerDict = addPublicParameter("InitOralProcess")
        headerDict["SessionId"] = "zhm1213"
        headerDict["RefText"] = text
        headerDict["WorkMode"] = 0
        headerDict["EvalMode"] = 1
        headerDict["ScoreCoeff"] = 3.5
        strJson = json.dumps(headerDict)
        req.from_json_string(strJson)

        resp = client.InitOralProcess(req)

        # 输出json格式的字符串回包
        print("%s" % resp.to_json_string())

    except TencentCloudSDKException as err:
        print("%s" % err)
def test_signature_v3_fail():
    for reqmethod in reqmethod_list:
        cred = credential.Credential(os.environ.get("TENCENTCLOUD_SECRET_ID"),
                                     os.environ.get("TENCENTCLOUD_SECRET_KEY"))
        httpProfile = HttpProfile()
        httpProfile.endpoint = "cvm.tencentcloudapi.com"
        httpProfile.reqMethod = reqmethod

        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"
        clientProfile.httpProfile = httpProfile
        client = cvm_client.CvmClient(cred, "ap-guangzhou", clientProfile)

        req = models.DescribeInstancesOperationLimitRequest()
        params = {"InstanceIds": [""], "Operation": "INSTANCE_DEGRADE"}
        req.from_json_string(json.dumps(params))
        try:
            resp = client.DescribeInstancesOperationLimit(req)
            assert False, 'unexpected success, should fail'
        except TencentCloudSDKException as err:
            assert err.code == 'InvalidInstanceId.Malformed'
Ejemplo n.º 22
0
def send_sms(content, phones):
    try:
        logger.info(f"========{content}")
        secret_id, secret_key = __acquire_sms_config()
        cred = credential.Credential(secret_id, secret_key)
        # 实例化要请求产品(以cvm为例)的client对象
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
        httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
        httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
        clientProfile.language = "en-US"
        clientProfile.httpProfile = httpProfile

        client = sms_client.SmsClient(cred, "ap-beijing", clientProfile)
        # 实例化一个请求对象
        req = models.SendSmsRequest()
        req.SmsSdkAppid = "1400301649"
        req.Sign = "爱极客"
        req.PhoneNumberSet = phones
        req.TemplateID = "599228"
        req.TemplateParamSet = content
        resp = client.SendSms(req)
        result = resp.to_json_string(indent=2)
        print(resp.to_json_string(indent=2))
        for status in json.loads(resp.to_json_string(indent=2)).get(
                "SendStatusSet", {}):
            # 现在只发送一条短信数据
            code = status.get("Code")
            if code.lower() == "ok":
                break
            else:
                return False
        return True
    except Exception as e:
        print(e)
        return False
Ejemplo n.º 23
0
def test_big_package_with_signature_v3_post():
    cred = credential.Credential(
        os.environ.get("TENCENTCLOUD_SECRET_ID"),
        os.environ.get("TENCENTCLOUD_SECRET_KEY"))
    http_profile = HttpProfile()
    http_profile.reqMethod = "POST"
    client_profile = ClientProfile()
    client_profile.httpProfile = http_profile
    client_profile.signMethod = "TC3-HMAC-SHA256"
    client = iai_client.IaiClient(cred, "ap-guangzhou", client_profile)

    req = models.CompareFaceRequest()
    params = {
        "ImageA": "1" * 1024 * 1024 * 4,
        "ImageB": "1" * 1024 * 1024 * 1,
        "UrlA": "https://cloudapi-test-1254240205.cos.ap-nanjing.myqcloud.com/9d1f1393e5fc5ca13032e40e3bf9e882.jpeg",
        "UrlB": "https://cloudapi-test-1254240205.cos.ap-nanjing.myqcloud.com/9d1f1393e5fc5ca13032e40e3bf9e882.jpeg",
    }
    req.from_json_string(json.dumps(params))
    try:
        resp = client.CompareFace(req)
    except TencentCloudSDKException as e:
        assert e.code in ["ResourceUnavailable.NotExist", "FailedOperation.ImageDownloadError"]
Ejemplo n.º 24
0
 def send_message_by_sms(cls, message):
     cred = credential.Credential(SMSConfig.secretId, SMSConfig.secretKey)
     # 实例化一个http选项,可选的,没有特殊需求可以跳过。
     httpProfile = HttpProfile()
     # 如果需要指定proxy访问接口,可以按照如下方式初始化hp
     httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
     httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
     httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)
     # 实例化一个客户端配置对象,可以指定超时时间等配置
     clientProfile = ClientProfile()
     clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
     clientProfile.language = "en-US"
     clientProfile.httpProfile = httpProfile
     # 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,或者引用预设的常量
     client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)
     req = models.SendSmsRequest()
     # 基本类型的设置:
     req.SmsSdkAppId = SMSConfig.SdkAppId
     # 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名,签名信息可登录 [短信控制台] 查看
     req.SignName = SMSConfig.signName
     # 短信码号扩展号: 默认未开通,如需开通请联系 [sms helper]
     req.ExtendCode = ""
     # 用户的 session 内容: 可以携带用户侧 ID 等上下文信息,server 会原样返回
     req.SessionContext = "xxx"
     # 国际/港澳台短信 senderid: 国内短信填空,默认未开通,如需开通请联系 [sms helper]
     req.SenderId = ""
     # 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号]
     # 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号
     req.PhoneNumberSet = SMSConfig.sendPhone
     # 模板 ID: 必须填写已审核通过的模板 ID。模板ID可登录 [短信控制台] 查看
     req.TemplateId = SMSConfig.templateId
     # 模板参数: 若无模板参数,则设置为空
     req.TemplateParamSet = [i for i in message[0].split(',') if i]
     # 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的。
     # 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应。
     resp = client.SendSms(req)
     print(resp)
Ejemplo n.º 25
0
def transmit_oral_process(sessionId,
                          userVoiceData):  #  语音段唯一标识,一个完整语音一个SessionId。
    try:
        # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
        cred = credential.Credential(secretId, secretKey)

        # 实例化一个http选项,可选的,没有特殊需求可以跳过。
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
        httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
        httpProfile.endpoint = "soe.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法(默认为HmacSHA256)
        clientProfile.unsignedPayload = True
        clientProfile.httpProfile = httpProfile

        client = soe_client.SoeClient(cred, "", clientProfile)
        req = models.TransmitOralProcessRequest()
        req.SessionId = sessionId
        req.VoiceFileType = 2  # 语音文件类型 1:raw, 2:wav, 3:mp3(三种格式目前仅支持16k采样率16bit编码单声道
        req.SeqId = 1  # 流式数据包的序号,从1开始,当IsEnd字段为1后后续序号无意义,当
        #IsLongLifeSession不为1且为非流式模式时无意义。
        req.VoiceEncodeType = 1  # 语音编码类型 1:pcm。
        req.IsEnd = 1  #  是否传输完毕标志,若为0表示未完毕,若为1则传输完毕开始评估,非流式模式下无意义

        req.UserVoiceData = userVoiceData  # 当前数据包数据, 流式模式下数据包大小可以按需设置,数据包大小必须 >= 4K,且必
        #须保证分片帧完整(16bit的数据必须保证音频长度为偶数),编码格式要求为BASE64。

        # process
        resp = client.TransmitOralProcess(req)

        # 输出json格式的字符串回包
        print("%s" % resp.to_json_string())

    except TencentCloudSDKException as err:
        print("%s" % err)
Ejemplo n.º 26
0
def init_oral_process(text, sessionId):  #  语音段唯一标识,一个完整语音一个SessionId。
    try:
        # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
        cred = credential.Credential(secretId, secretKey)

        # 实例化一个http选项,可选的,没有特殊需求可以跳过。
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
        httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
        httpProfile.endpoint = "soe.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

        # 实例化一个client选项,可选的,没有特殊需求可以跳过。
        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法(默认为HmacSHA256)
        clientProfile.unsignedPayload = True
        clientProfile.httpProfile = httpProfile

        client = soe_client.SoeClient(cred, "", clientProfile)
        req = models.InitOralProcessRequest()
        #req.SessionId = "stress_test_956938"
        req.SessionId = sessionId
        req.RefText = text  # refer 的文本
        req.WorkMode = 1  # workMode  语音输入模式,0:流式分片,1:非流式一次性评估
        req.EvalMode = 1  # EvalMode 评估模式,0:词模式,,1::句子模式,2:段落模式,3:自由说模式,当为词模式
        #评估时,能够提供每个音节的评估信息,当为句子模式时,能够提供完整度和流利度信息。
        req.ScoreCoeff = 3.5
        # ScoreCoeff 评价苛刻指数,取值为[1.0 - 4.0]范围内的浮点数,用于平滑不同年龄段的分数,1.0
        #为小年龄段,4.0为最高年龄段

        resp = client.InitOralProcess(req)

        # 输出json格式的字符串回包
        print("%s" % resp.to_json_string())

    except TencentCloudSDKException as err:
        print("%s" % err)
Ejemplo n.º 27
0
    # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey
    cred = credential.Credential("", "")
    # cred = credential.Credential(
    #     os.environ.get("TENCENTCLOUD_SECRET_ID"),
    #     os.environ.get("TENCENTCLOUD_SECRET_KEY"))

    # 实例化一个http选项,可选的,没有特殊需求可以跳过。
    httpProfile = HttpProfile()
    httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
    httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
    httpProfile.endpoint = "tci.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)
    httpProfile.keepAlive = True

    # 实例化一个client选项,可选的,没有特殊需求可以跳过。
    clientProfile = ClientProfile()
    clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法(默认为HmacSHA256)
    clientProfile.unsignedPayload = True
    clientProfile.httpProfile = httpProfile

    client = tci_client.TciClient(cred, "", clientProfile)
    req = models.CreateFaceRequest()
    req.LibraryId = "tci_library_156403897035611372834"
    req.PersonId = "tci_person_1564039695429032573626"
    req.urls = ["https://img-blog.csdn.net/20161128171723259"]
    resp = client.CreateFace(req)

    # 输出json格式的字符串回包
    print("%s" % resp.to_json_string())

except TencentCloudSDKException as err:
    print("%s" % err)
Ejemplo n.º 28
0
import base64
import io 
import sys 
if sys.version_info[0] == 3:
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')

#本地文件方式请求
try: 
    #重要,此处<Your SecretId><Your SecretKey>需要替换成客户自己的账号信息,获取方法:
        #https://cloud.tencent.com/product/asr/getting-started
    cred = credential.Credential("AKIDX1GGzR5U9avzoPSmfKl79uNaaQ17nK2T", "IJ9l1D9oBH7oHWhbEaeS6VK4XjdKkz0t") 
    httpProfile = HttpProfile()
    httpProfile.endpoint = "asr.tencentcloudapi.com"
    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    clientProfile.signMethod = "TC3-HMAC-SHA256"  
    client = asr_client.AsrClient(cred, "ap-shanghai", clientProfile) 
    #读取文件以及 base64
    #此处可以下载测试音频 https://asr-audio-1300466766.cos.ap-nanjing.myqcloud.com/test16k.wav
    with open('./12.mp3', "rb") as f:
        if sys.version_info[0] == 2:
            content = base64.b64encode(f.read())
        else:
            content = base64.b64encode(f.read()).decode('utf-8')
    #发送请求
    req = models.SentenceRecognitionRequest()
    params = {"ProjectId":0,"SubServiceType":2,"SourceType":1,"UsrAudioKey":"session-123", "RequestId": '1c8400f1-913f-4938-a45f-0421b08782ad' }
    req._deserialize(params)
    req.DataLen = len(content)
    req.Data = content
    req.EngSerViceType = "16k_zh"
Ejemplo n.º 29
0
def send_vcode_sms(tel, code):
    try:
        # 必要步骤:
        # 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。
        # 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。
        # 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人,
        # 以免泄露密钥对危及你的财产安全。
        # CAM密匙查询: https://console.cloud.tencent.com/cam/capi
        cred = credential.Credential(TencentCloud_SecretId,
                                     TencentCloud_SecretKey)
        # cred = credential.Credential(
        #     os.environ.get(""),
        #     os.environ.get("")
        # )

        # 实例化一个http选项,可选的,没有特殊需求可以跳过。
        httpProfile = HttpProfile()
        httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
        httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
        httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

        # 非必要步骤:
        # 实例化一个客户端配置对象,可以指定超时时间等配置
        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
        clientProfile.language = "en-US"
        clientProfile.httpProfile = httpProfile

        # 实例化要请求产品(以sms为例)的client对象
        # 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,或者引用预设的常量
        client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)

        # 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
        # 你可以直接查询SDK源码确定SendSmsRequest有哪些属性可以设置
        # 属性可能是基本类型,也可能引用了另一个数据结构
        # 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明
        req = models.SendSmsRequest()

        # 基本类型的设置:
        # SDK采用的是指针风格指定参数,即使对于基本类型你也需要用指针来对参数赋值。
        # SDK提供对基本类型的指针引用封装函数
        # 帮助链接:
        # 短信控制台: https://console.cloud.tencent.com/sms/smslist
        # sms helper: https://cloud.tencent.com/document/product/382/3773

        # 短信应用ID: 短信SdkAppid在 [短信控制台] 添加应用后生成的实际SdkAppid,示例如1400006666
        req.SmsSdkAppid = SMS_SmsSdkAppid
        # 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名,签名信息可登录 [短信控制台] 查看
        req.Sign = "王冬代码练习"
        # 短信码号扩展号: 默认未开通,如需开通请联系 [sms helper]
        req.ExtendCode = ""
        # 用户的 session 内容: 可以携带用户侧 ID 等上下文信息,server 会原样返回
        req.SessionContext = ""
        # 国际/港澳台短信 senderid: 国内短信填空,默认未开通,如需开通请联系 [sms helper]
        req.SenderId = ""
        # 下发手机号码,采用 e.164 标准,+[国家或地区码][手机号]
        # 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号
        req.PhoneNumberSet = ["+86%s" % tel]
        # 模板 ID: 必须填写已审核通过的模板 ID。模板ID可登录 [短信控制台] 查看
        req.TemplateID = SMS_TemplateID
        # 模板参数: 若无模板参数,则设置为空
        req.TemplateParamSet = [code, variable.VERIFY_CODE_EXPIRE_TIME_CN]

        # 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的。
        # 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应。
        resp = client.SendSms(req)

        # 输出json格式的字符串回包
        print(resp.to_json_string())
        if resp.SendStatusSet[0].Code == "Ok" and resp.SendStatusSet[
                0].Message == "send success":
            return True
        else:
            # 发送失败,则打日志
            logger.warning(
                "tel:%s || vote:%s || RequestId:%s" %
                (tel, resp.SendStatusSet[0].Message, resp.RequestId))
            return resp.SendStatusSet[0].Message

    except TencentCloudSDKException as err:
        # 报错,则打日志
        logger.error("tel:%s || vote:%s" % (tel, str(err)))
        print(err)

    # 示例正常的返回值 res 的值
    """
    {
        "SendStatusSet": [
            {
                "SerialNo": "2019:538884*********",
                "PhoneNumber": "+86182********",
                "Fee": 1,
                "SessionContext": "",
                "Code": "Ok",
                "Message": "send success"
            }
        ],
        "RequestId": "bf0d639e-9956-4366-be0f-a23001900ce0"
    }
    """
    return '发送失败,未知原因'
Ejemplo n.º 30
0
    def tencent_send(phone_num):
        try:
            # 必要步骤:
            # 实例化一个认证对象,入参需要传入腾讯云账户密钥对 secretId 和 secretKey
            # 本示例采用从环境变量读取的方式,需要预先在环境变量中设置这两个值
            # 您也可以直接在代码中写入密钥对,但需谨防泄露,不要将代码复制、上传或者分享给他人
            # CAM 密钥查询:https://console.cloud.tencent.com/cam/capi

            # cred = credential.Credential("secretId","secretKey")
            cred = credential.Credential(os.environ.get("secretId"),
                                         os.environ.get("secretKey"))
            # print(os.environ.get("secretId"))
            verify_code = str(int((random.uniform(0, 1) * 9 + 1) * 100000))
            phone = '+86' + phone_num

            # 实例化一个 http 选项,可选,无特殊需求时可以跳过
            httpProfile = HttpProfile()
            httpProfile.reqMethod = "POST"  # POST 请求(默认为 POST 请求)
            httpProfile.reqTimeout = 30  # 请求超时时间,单位为秒(默认60秒)
            httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

            # 非必要步骤:
            # 实例化一个客户端配置对象,可以指定超时时间等配置
            clientProfile = ClientProfile()
            clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
            clientProfile.language = "en-US"
            clientProfile.httpProfile = httpProfile

            # 实例化 SMS 的 client 对象
            # 第二个参数是地域信息,可以直接填写字符串 ap-guangzhou,或者引用预设的常量
            client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)

            # 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
            # 您可以直接查询 SDK 源码确定 SendSmsRequest 有哪些属性可以设置
            # 属性可能是基本类型,也可能引用了另一个数据结构
            # 推荐使用 IDE 进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明
            req = models.SendSmsRequest()

            # 基本类型的设置:
            # SDK 采用的是指针风格指定参数,即使对于基本类型也需要用指针来对参数赋值
            # SDK 提供对基本类型的指针引用封装函数
            # 帮助链接:
            # 短信控制台:https://console.cloud.tencent.com/smsv2
            # sms helper:https://cloud.tencent.com/document/product/382/3773

            # 短信应用 ID: 在 [短信控制台] 添加应用后生成的实际 SDKAppID,例如1400006666
            req.SmsSdkAppid = "1400401547"
            # 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名,可登录 [短信控制台] 查看签名信息
            req.Sign = "瑞选网"
            # 短信码号扩展号: 默认未开通,如需开通请联系 [sms helper]
            req.ExtendCode = ""
            # 用户的 session 内容: 可以携带用户侧 ID 等上下文信息,server 会原样返回
            req.SessionContext = "xxx"
            # 国际/港澳台短信 senderid: 国内短信填空,默认未开通,如需开通请联系 [sms helper]
            req.SenderId = ""
            # 下发手机号码,采用 e.164 标准,+[国家或地区码][手机号]
            # 例如+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号
            req.PhoneNumberSet = [
                phone,
            ]
            # 模板 ID: 必须填写已审核通过的模板 ID,可登录 [短信控制台] 查看模板 ID
            req.TemplateID = "665620"
            # 模板参数: 若无模板参数,则设置为空
            req.TemplateParamSet = [
                verify_code,
            ]

            # 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的
            resp = client.SendSms(req)

            # 输出 JSON 格式的字符串回包
            re_data = json.loads(resp.to_json_string(indent=2))
            print(re_data)
            if resp and re_data.get('SendStatusSet')[0].get('Code') == 'Ok':
                return verify_code
            else:
                return None

            # if re_data.get('code') == 2:
            #     return verify_code
            # else:
            #     return None

        except TencentCloudSDKException as err:
            print(err)