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)
def buy(secu_id, secu_key, region, pay_type, zone, instype, imageid, disksize, width): try: cred = credential.Credential(secu_id, secu_key) httpProfile = HttpProfile() httpProfile.endpoint = "cvm.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = cvm_client.CvmClient(cred, region, clientProfile) req = models.RunInstancesRequest() params = '{"InstanceChargeType":"%s","Placement":{"Zone":"%s"},' \ '"InstanceType":"%s","ImageId":"%s","SystemDisk":{"DiskSize":%d},' \ '"InternetAccessible":{"InternetMaxBandwidthOut":%d,"PublicIpAssigned":true}}' \ % (pay_type, zone, instype, imageid, int(disksize), int(width)) req.from_json_string(params) resp = client.RunInstances(req) # print(resp.to_json_string()) return "购买成功,等待实例创建开启" except TencentCloudSDKException as err: print(err)
def test_signature_v1_fail(): for signmethod, reqmethod in product(signmethod_list, 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.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'
def ocr_api(self): with open(self.paths["num"], "rb") as f: # 转为二进制格式 base64_data = base64.b64encode(f.read()) cred = credential.Credential(tencentcloudKeys.secretId, tencentcloudKeys.secretKey) httpProfile = HttpProfile() httpProfile.endpoint = "ocr.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = ocr_client.OcrClient(cred, "ap-beijing", clientProfile) req = models.GeneralBasicOCRRequest() params = { "ImageBase64": str(base64_data, encoding="utf-8"), } req.from_json_string(json.dumps(params)) resp = client.GeneralBasicOCR(req) result = json.loads(resp.to_json_string()) # 识别出的文字,已经是最终剩余数量 < >/30 result_text = result["TextDetections"][0]["DetectedText"] result_text = int(result_text.split("/")[0].replace(" ", "")) return result_text
def tencent_embedding(self, sentences): vector_embeds = [] failed_inds = [] for ind, sentence in enumerate(sentences): if ind % 100 == 0: self.logger.info("Now at {}, {} in total".format(ind, len(sentences))) try: cred = credential.Credential( "AKIDlJdkbExRlwueDaqjZAaomVFlDSVOuqCL", "iTefWR6XklmIfroVyQergHqAG9qIsvkO", ) httpProfile = HttpProfile() httpProfile.endpoint = "nlp.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = nlp_client.NlpClient(cred, "ap-guangzhou", clientProfile) req = models.SentenceEmbeddingRequest() params = {"Text": sentence} req.from_json_string(json.dumps(params)) resp = client.SentenceEmbedding(req) vector = json.loads(resp.to_json_string())["Vector"] vector_embeds.append(vector) except TencentCloudSDKException as err: print(err) failed_inds.append(ind) # ——————输入处理—————— np.savez( "vector_embed", embed=np.array(vector_embeds), dropped_ind=np.array(failed_inds), ) return vector_embeds
def main_handler(event, context): try: provision_params = json.loads(event['Message']) if len(provision_params) < 4: return ("Missing parameters") cred = credential.Credential( os.environ.get('TENCENTCLOUD_SECRETID'), os.environ.get('TENCENTCLOUD_SECRETKEY'), os.environ.get('TENCENTCLOUD_SESSIONTOKEN')) httpProfile = HttpProfile() httpProfile.endpoint = "scf.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = scf_client.ScfClient(cred, provision_params["Region"], clientProfile) req = models.PutProvisionedConcurrencyConfigRequest() params = { "FunctionName": provision_params.get("FunctionName"), "Namespace": provision_params.get("Namespace"), "Qualifier": provision_params.get("Qualifier"), "VersionProvisionedConcurrencyNum": provision_params.get("VersionProvisionedConcurrencyNum") } req.from_json_string(json.dumps(params)) resp = client.PutProvisionedConcurrencyConfig(req) print(resp.to_json_string()) except TencentCloudSDKException as err: print(err) return ("Hello Serverless")
def test_temp_credential_invalid(): temp_info = _get_temp_redentials() for reqmethod in reqmethod_list: invalid_cred = credential.Credential(temp_info[0], temp_info[1], temp_info[2] + 'err') httpProfile = HttpProfile() httpProfile.endpoint = "cvm.tencentcloudapi.com" httpProfile.reqMethod = reqmethod clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = cvm_client.CvmClient(invalid_cred, "ap-guangzhou", clientProfile) req = cvm_models.DescribeInstancesOperationLimitRequest() params = { "InstanceIds": [""], "Operation": "INSTANCE_DEGRADE", } req.from_json_string(json.dumps(params)) try: resp = client.DescribeInstancesOperationLimit(req) except TencentCloudSDKException as err: assert err.code == 'AuthFailure.TokenFailure'
def getRedisBackupURL(self, BackupId): ''' 查询备份rdb下载地址 https://console.cloud.tencent.com/api/explorer?Product=redis&Version=2018-04-12&Action=DescribeBackupUrl&SignVersion= ''' try: httpProfile = HttpProfile() httpProfile.endpoint = "redis.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = redis_client.RedisClient(self.clt, self.region, clientProfile) req = redis_models.DescribeBackupUrlRequest() params = '{\"InstanceId\":\"%s\",\"BackupId\":\"%s\"}' % ( self.DBInstanceId, BackupId) req.from_json_string(params) resp = client.DescribeBackupUrl(req) return resp.to_json_string() except TencentCloudSDKException as err: return '{"msg": "腾讯云获取rdb下载地址失败:%s", "status": 1}' % (err)
def getMongoDBBackups(self): ''' 获取MongoDB的备份列表 https://console.cloud.tencent.com/api/explorer?Product=mongodb&Version=2019-07-25&Action=DescribeDBBackups&SignVersion= https://console.cloud.tencent.com/api/explorer?Product=mongodb&Version=2019-07-25&Action=DescribeBackupAccess&SignVersion= TODO 暂不确定分片集群与复制集的备份查询方式是否有差异 ''' try: httpProfile = HttpProfile() httpProfile.endpoint = "mongodb.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = mongodb_client.MongodbClient(self.clt, self.region, clientProfile) req = mongodb_models.DescribeDBBackupsRequest() params = '{\"InstanceId\":\"%s\"}' % self.DBInstanceId req.from_json_string(params) resp = client.DescribeDBBackups(req) return resp.to_json_string() except TencentCloudSDKException as err: return '{"msg": "腾讯云获取MongoDB备份列表失败:%s", "status": 1}' % (err)
def api_use(encodestr): ''' 调用 api 识别文图片上的文字 ''' try: cred = credential.Credential(你的密匙) httpProfile = HttpProfile() httpProfile.endpoint = "ocr.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = ocr_client.OcrClient(cred, "ap-guangzhou", clientProfile) req = models.GeneralBasicOCRRequest() params = '{"ImageBase64":"%s"}' % encodestr req.from_json_string(params) resp = client.GeneralBasicOCR(req) resp = resp.to_json_string() # print(resp) return resp except TencentCloudSDKException as err: print(err)
def TencentFaceBeauty(pic_str, white, smooth, facelift, eyeenlarge): try: cred = credential.Credential("ID", "Key") httpProfile = HttpProfile() httpProfile.endpoint = "fmu.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = fmu_client.FmuClient(cred, "ap-beijing", clientProfile) req = models.BeautifyPicRequest() # params = '{"Image":" ", "Whitening":30, "Smoothing":10, "FaceLifting":70, "EyeEnlarging":70}' print(pic_str[2:-1]) params_1 = '{"Image":"' params_2 = '", "Whitening":' params_3 = ', "Smoothing":' params_4 = ', "FaceLifting":' params_5 = ', "EyeEnlarging":' params_6 = '}' params = params_1 + pic_str[ 2: -1] + params_2 + white + params_3 + smooth + params_4 + facelift + params_5 + eyeenlarge + params_6 req.from_json_string(params) resp = client.BeautifyPic(req) req_text = resp.to_json_string() for index in range(17, len(str(req_text))): if req_text[index] == r'"': out_str = req_text[17:index] break return out_str except TencentCloudSDKException as err: print(err)
def create(region, ccn_name, ccn_description, instance_charge_type, band_width_limit_type): """管理服务器创建云联网,目前只为北京地域,后续要有各地域,在管理服务器应该购买各地域的实例,用于通信传送服务器文件等""" try: cred = credential.Credential("AKIDYxBJFzqxBDNODqfcjgR2TkpiQvGOiBpI", "Pf0EHzYxAC6nKfqskSzObdUCk9MOGxUp") httpProfile = HttpProfile() httpProfile.endpoint = "vpc.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = vpc_client.VpcClient(cred, region, clientProfile) req = models.CreateCcnRequest() params = '{"CcnName":"%s","CcnDescription":"%s","InstanceChargeType":"%s","BandwidthLimitType":"%s"}' \ % (ccn_name, ccn_description, instance_charge_type, band_width_limit_type) req.from_json_string(params) resp = client.CreateCcn(req) print(resp.to_json_string()) except TencentCloudSDKException as err: print(err)
def requset_tc(base64_data): try: cred = credential.Credential("AKIDUO6pHXxSu6EOI5fstc6iMPK6qLXTK8j4", "EAsGk2yjDSQArVxGPEoAF4n2IH0Xpuki") httpProfile = HttpProfile() httpProfile.endpoint = "ocr.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = ocr_client.OcrClient(cred, "ap-guangzhou", clientProfile) req = models.GeneralHandwritingOCRRequest() # print(str(base64_data)) params = "{\"ImageBase64\":\"" + str(base64_data) + "\"}" req.from_json_string(params) resp = client.GeneralHandwritingOCR(req) print(resp.to_json_string()) return json.loads(resp.to_json_string()) except TencentCloudSDKException as err: print(err) return str(err)
def __init__(self, config): self.config = config cred = credential.Credential(config['secret_id'], config['secret_key'], config['token']) httpProfile = HttpProfile() httpProfile.endpoint = "cdn.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile cdnClient = cdn_client.CdnClient(cred, config['scf_region'], clientProfile) self.cdn_client = cdnClient self.cos_path = config['cos_path'] cos_config = CosConfig( Region=config['cos_region'], Secret_id=config['secret_id'], Secret_key=config['secret_key'], Token=config.get('token', None), ) self.cos_client = CosS3Client(cos_config) self.cos_bucket = config['cos_bucket']
def upload_audio(self, file_path): print("Uploading %s" % file_path) try: audio_path = file_path with open(audio_path, "rb") as f: audio_data = f.read() audio_data_b64 = base64.b64encode(audio_data).decode("utf-8") cred = credential.Credential(self._secret_id, self._secret_key) httpProfile = HttpProfile() httpProfile.endpoint = self._endpoint clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = asr_client.AsrClient(cred, "", clientProfile) req = models.CreateRecTaskRequest() params = { "EngineModelType": "16k_zh_video", "ChannelNum": 1, "SpeakerDiarization": 1, "SpeakerNumber": 1, "ResTextFormat": 2, "SourceType": 1, "Data": audio_data_b64, } req.from_json_string(json.dumps(params)) resp = client.CreateRecTask(req) result_json = json.loads(resp.to_json_string()) task_id = result_json["Data"]["TaskId"] self.temp_data["file_path"].append(audio_path) self.temp_data["task_id"].append(task_id) print("Upload %s success" % file_path) except TencentCloudSDKException as err: print(err)
from tencentcloud.common.profile.http_profile import HttpProfile from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException from tencentcloud.lighthouse.v20200324 import lighthouse_client, models try: #参数 SecretId = os.environ["SecretId"] SecretKey = os.environ["SecretKey"] region = os.environ["region"] percent = 0.95 #流量限额,1表示使用到100%关机,默认设置为95% tgBotUrl = os.environ["tgBotUrl"] tgToken = os.environ["tgToken"] # 以下不用管 cred = credential.Credential(SecretId, SecretKey) httpProfile = HttpProfile() httpProfile.endpoint = "lighthouse.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = lighthouse_client.LighthouseClient(cred, region, clientProfile) #获取实例列表 req_instances = models.DescribeInstancesRequest() params = {} req_instances.from_json_string(json.dumps(params)) resp_instances = client.DescribeInstances(req_instances) s1 = json.loads(resp_instances.to_json_string())['InstanceSet'] for j in range(len(s1)): params.setdefault("InstanceIds", []).append(s1[j]['InstanceId']) #获取实例ID #获取实例流量
from tencentcloud.common.profile.http_profile import HttpProfile from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException from tencentcloud.asr.v20190614 import asr_client, models 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)
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 '发送失败,未知原因'
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.cvm.v20170312 import cvm_client, models try: cred = credential.Credential("", "") httpProfile = HttpProfile() httpProfile.endpoint = "cvm.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = cvm_client.CvmClient(cred, "ap-beijing", clientProfile) req = models.DescribeInstancesRequest() params = '{}' req.from_json_string(params) resp = client.DescribeInstances(req) print(resp.to_json_string()) except TencentCloudSDKException as err: print(err)
import 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.wss.v20180426 import wss_client, models try: cred = credential.Credential(os.environ.get("TENCENTCLOUD_SECRET_ID"), os.environ.get("TENCENTCLOUD_SECRET_KEY")) httpProfile = HttpProfile() httpProfile.endpoint = "wss.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = wss_client.WssClient(cred, "", clientProfile) req = models.UploadCertRequest() # This is just an example, please use your real certificate file instead. req.Cert = """-----BEGIN CERTIFICATE----- MIIFejCCBGKgAwIBAgISA2rvMNLaaa+8oqfizkFpXqhxMA0GCSqGSIb3DQEBCwUA MEoxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MSMwIQYDVQQD ExpMZXQncyBFbmNyeXB0IEF1dGhvcml0eSBYMzAeFw0xOTEyMjgyMDIyNDVaFw0y MDAzMjcyMDIyNDVaMCAxHjAcBgNVBAMTFWZ1bWVuZ3dhbmdsdW9rZWppLmNvbTCC ASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAPOuUV+f3cGhz+bi9SRNnfqB tIGvvvGCsIZ/23juRxD2bS+L2RMq6aY1d5cESgPZKjEKOPmtMOgUyuGAY+nFfCkt oBYTVtH+p/AdhDSmPbKgI+pxrxbCL7TWrUDokZQ5wqkyoVrEGyDt2SezPDoHx9Ml Uypm107VdEh9sLJNaNFWl+7yfKBdeXqSfIM1aNJRsxX65UuFCDJnvHOQ2LJx6pvt 5McxWY+yAyOVPtMOFB6F66khIQaEyKTh/I6wa+OSYycnA1FXXWJKEEl+THw/xHl1 SORcWDJPaaoT/V/TeZ/8MgENrrRTxho6et7MsJFTD4rRCHf9WtZKDaSOPFWKOJ8C AwEAAaOCAoIwggJ+MA4GA1UdDwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcD AQYIKwYBBQUHAwIwDAYDVR0TAQH/BAIwADAdBgNVHQ4EFgQUsn2926q4GyQrK62/
from tencentcloud.cvm.v20170312 import cvm_client, models import json # 导入可选配置类 from tencentcloud.common.profile.client_profile import ClientProfile from tencentcloud.common.profile.http_profile import HttpProfile import ssl ssl._create_default_https_context = ssl._create_unverified_context try: # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey cred = credential.Credential("AKIDylMjqkOq7Azay9Nq8D5kCSVM1Sfft4Sd", "K8lBONAk7IEzXt30kGXcS5UfbJm0zkG4") httpProfile = HttpProfile() httpProfile.endpoint = "cvm.api3.test.403a.tcecqpoc.fsphere.cn" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile # 实例化要请求产品(以cvm为例)的client对象,clientProfile是可选的。 client = cvm_client.CvmClient(cred, "shanghai", clientProfile) # 实例化一个cvm实例信息查询请求对象,每个接口都会对应一个request对象。 req = models.ModifyInstancesAttributeRequest() # 这里还支持以标准json格式的string来赋值请求参数的方式。下面的代码跟上面的参数赋值是等效的。 # params = '{"InstanceIds":["ins-i4ekkudx","ins-gwggvy39"],"InstanceName":"Mysql_Server"}' # params = '{"InstanceIds":["ins-i4ekkudx"],"InstanceName":"故障迁移测试3"}' params = '{"InstanceIds":["ins-gwggvy39"],"InstanceName":"故障迁移测试1"}' req.from_json_string(params)
import base64 import json import cv2 from tencentcloud.bda.v20200324 import bda_client, models from tencentcloud.common import credential from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException from tencentcloud.common.profile.client_profile import ClientProfile from tencentcloud.common.profile.http_profile import HttpProfile # 检测一张照片中的人并框出 try: cred = credential.Credential("", "") httpProfile = HttpProfile() httpProfile.endpoint = "bda.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = bda_client.BdaClient(cred, "ap-shanghai", clientProfile) req = models.DetectBodyRequest() image_path = 'D:/detect/img/1.jpg' with open(image_path, 'rb') as f: image = f.read() image_base64 = str(base64.b64encode(image), encoding='utf-8') params = { "Image": image_base64, "MaxBodyNum": 10, "AttributesOptions": { "Orientation": True
# 导入对应产品模块的client models。 from tencentcloud.cvm.v20170312 import cvm_client, models # 导入可选配置类 from tencentcloud.common.profile.client_profile import ClientProfile from tencentcloud.common.profile.http_profile import HttpProfile try: # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey cred = credential.Credential(os.environ.get("TENCENTCLOUD_SECRET_ID"), os.environ.get("TENCENTCLOUD_SECRET_KEY")) # 实例化一个http选项,可选的,没有特殊需求可以跳过。 httpProfile = HttpProfile() httpProfile.reqMethod = "GET" # post请求(默认为post请求) httpProfile.reqTimeout = 30 # 请求超时时间,单位为秒(默认60秒) httpProfile.endpoint = "cvm.ap-shanghai.tencentcloudapi.com" # 指定接入地域域名(默认就近接入) # 实例化一个client选项,可选的,没有特殊需求可以跳过。 clientProfile = ClientProfile() clientProfile.signMethod = "TC3-HMAC-SHA256" # 指定签名算法 clientProfile.language = "en-US" clientProfile.httpProfile = httpProfile # 实例化要请求产品(以cvm为例)的client对象,clientProfile是可选的。 client = cvm_client.CvmClient(cred, "ap-shanghai", clientProfile) # 实例化一个cvm实例信息查询请求对象,每个接口都会对应一个request对象。 req = models.DescribeInstancesRequest() # 填充请求参数,这里request对象的成员变量即对应接口的入参。 # 你可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义。
def login(self): """登录""" print('正在登录…') self.driver.get(self.kanaLink) self.del_element(self.driver.find_element_by_class_name('redirect')) usernameBox = self.driver.find_element_by_name('username') passwordBox = self.driver.find_element_by_name('pwd') ac = ActionChains(self.driver) ac.send_keys_to_element(usernameBox, self.username) ac.send_keys_to_element(passwordBox, self.password).perform() cap_correction = {'丫': 'Y', '了': '3', '尺': 'R'} # 手动纠错 while True: if self.driver.current_url == self.kanaLink: break self.driver.execute_script( 'document.getElementById("submitButton").style.display = "none"' ) self.driver.execute_script( 'document.getElementById("cap").childNodes[1].style.width="150%"' ) frame = self.driver.find_element_by_xpath( '/html/body/div[2]/div/form/div[1]/object') self.driver.switch_to.frame(frame) try: a = self.driver.find_element_by_css_selector('[fill="none"]') self.del_element(a) except: sleep(1) continue self.driver.switch_to.default_content() cap = -1 self.driver.get_screenshot_as_file('a.png') try: cred = credential.Credential(self.secretId, self.secretKey) http_profile = HttpProfile() http_profile.endpoint = 'ocr.tencentcloudapi.com' client_profile = ClientProfile() client_profile.httpProfile = http_profile client = ocr_client.OcrClient(cred, 'ap-shanghai', client_profile) req = models.GeneralBasicOCRRequest() params = { 'ImageBase64': base64.b64encode(open('a.png', 'rb').read()).decode() } req.from_json_string(json.dumps(params)) resp = client.GeneralBasicOCR(req) a = json.loads(resp.to_json_string()) except TencentCloudSDKException as err: print(err) self.driver.execute_script( 'document.getElementById("cap").childNodes[1].style.width="100%"' ) for i in a['TextDetections']: tmp = i['DetectedText'] s = '' for j in tmp: if j != '(' and j != ')': # 去除诡异括号 s += j if j in cap_correction: s += cap_correction[j] tmp = s if re.match(r'\w\w\w\w', tmp) and len(tmp) == 4: cap = tmp break print(cap) ac = ActionChains(self.driver) ac.send_keys_to_element(self.driver.find_element_by_name("cap"), cap).perform() self.driver.execute_script( 'document.getElementById("submitButton").style.display = ""') self.driver.find_element_by_id("submitButton").click() try: WebDriverWait(self.driver, 10).until(EC.url_to_be(self.kanaLink)) break except TimeoutException: pass print("登录成功!") return
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)
from sagiri_bot.utils import group_setting saya = Saya.current() channel = Channel.current() # channel.name("Speak") channel.author("nullqwertyuiop, SAGIRI-kawaii") channel.description("语音合成插件,在群中发送 `说 {content}` 即可") core = AppCore.get_core_instance() config = core.get_config() user_data = config.functions["tencent"] cred = credential.Credential(user_data["secret_id"], user_data["secret_key"]) http_profile = HttpProfile() http_profile.endpoint = "tts.tencentcloudapi.com" client_profile = ClientProfile() client_profile.httpProfile = http_profile @channel.use( ListenerSchema( listening_events=[GroupMessage], inline_dispatchers=[ Twilight([ FullMatch("说").space(SpacePolicy.FORCE), ArgumentMatch("-v", "--voice", type=int, optional=True) @ "voice_type", WildcardMatch().flags(re.DOTALL) @ "content" ]) ],
from tencentcloud.tci.v20190318 import tci_client, models from tencentcloud.common.profile.client_profile import ClientProfile from tencentcloud.common.profile.http_profile import HttpProfile try: # 实例化一个认证对象,入参需要传入腾讯云账户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)
def main_handler(event, context): logger.info("start main handler") if "requestContext" not in event.keys(): return {"code": 410, "errorMsg": "event is not come from api gateway"} if "body" not in event.keys(): return { "isBase64Encoded": False, "statusCode": 200, "headers": { "Content-Type": "text", "Access-Control-Allow-Origin": "*" }, "body": "there is no file from api gateway" } # save api gateway file to local temp file logger.info("Start to download images from APIGW") time = datetime.datetime.now() file_name = '{}'.format(time) + "-test.jpg" logger.info("file_name is : %s" % file_name) local_path = u'/tmp/{}'.format(file_name) logger.info("local_path is : %s" % local_path) with open(local_path, 'w') as wfile: wfile.write(base64.b64decode(event['body'])) # start to upload to cos secret_id = os.environ.get('TENCENTCLOUD_SECRETID') # 使用环境变量中的 secretId secret_key = os.environ.get('TENCENTCLOUD_SECRETKEY') # 使用环境变量中的 secretKey token = os.environ.get('TENCENTCLOUD_SESSIONTOKEN') config = CosConfig( Region=bucket_region, SecretId=secret_id, SecretKey=secret_key, Token=token, ) cos_client = CosS3Client(config) logger.info("Start to upload images to cos") res_cos = cos_client.put_object_from_local_file(Bucket=bucket_upload, LocalFilePath=local_path, Key='{}'.format(file_name)) logger.info("upload to cos result is : %s" % res_cos) # start to detection logger.info("Start to detection") try: cred = credential.Credential(secret_id, secret_key, token) httpProfile = HttpProfile() httpProfile.endpoint = "ocr.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = ocr_client.OcrClient(cred, "ap-beijing", clientProfile) req = models.GeneralBasicOCRRequest() params = '{"ImageBase64":"%s"}' % event['body'] req.from_json_string(params) resp = client.GeneralBasicOCR(req) res_ai = json.loads(resp.to_json_string()) res_text = " " print len(res_ai["TextDetections"]) for i in range(len(res_ai["TextDetections"])): res_text = res_text + str( res_ai["TextDetections"][i]["DetectedText"].encode('utf-8')) except TencentCloudSDKException as err: print(err) delete_local_file(local_path) response = { "isBase64Encoded": False, "statusCode": 200, "headers": { "Content-Type": "text", "Access-Control-Allow-Origin": "*" }, "body": res_text } return response
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.nlp.v20190408 import nlp_client, models try: cred = credential.Credential("qqq", "xxx") httpProfile = HttpProfile() httpProfile.endpoint = "nlp.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = nlp_client.NlpClient(cred, "ap-guangzhou", clientProfile) req = models.KeywordsExtractionRequest() params = '{"Text":"被问及法国为什么不采取意大利式的封锁,法国政府发言人 NDIAYE 公开蔑视意大利政府的措施:在欧洲,他们第一个中断中国的航班,第一个在机场测温,第一个禁止其他国家国民入境,第一个封城 ... 但是,这并没有阻挡疫情爆发... 这些法国都没有做,因为法国政府听取(国际)医疗界的专"}' req.from_json_string(params) resp = client.KeywordsExtraction(req) print(resp.to_json_string()) except TencentCloudSDKException as err: print(err)
def getresult(file): data = [] import ssl ssl._create_default_https_context = ssl._create_unverified_context try: cred = credential.Credential("AKIDhCSKyOceP5TUIFfh2Bdsrc7fzFybI2tV", "e3B0bx3siJdkaBauxFI6dugoeBUmsinf") httpProfile = HttpProfile() httpProfile.endpoint = "ocr.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = ocr_client.OcrClient(cred, "ap-shanghai", clientProfile) req = models.VatInvoiceOCRRequest() with open("image/"+file, "rb") as f: filedate = base64.b64encode(f.read()) params = { "ImageBase64": str(filedate,'utf-8') } req.from_json_string(json.dumps(params)) resp = client.VatInvoiceOCR(req) result = resp.to_json_string() result = json.loads(result) for msg in result['VatInvoiceInfos']: if msg["Name"]=='打印发票号码': num = msg["Value"][2:] if num[0]=="0": num = "'"+num data.insert(0,num) if msg["Name"]=='销售方名称': data.insert(1,msg["Value"]) if msg["Name"]=='备注': data.insert(2,msg["Value"]) if msg["Name"]=='合计金额': data.insert(3,msg["Value"]) if msg["Name"]=='合计税额': data.insert(4,msg["Value"]) if msg["Name"]=='小写金额': if msg["Value"][-2:] == "00": data.insert(5, msg["Value"][:-3]) else: data.insert(5,msg["Value"]) if msg["Name"]=='购买方名称': name = msg["Name"] if msg["Value"]=="上海晓篪信息技术有限公司": name = "Xiaochi" elif msg["Value"]=="上海兢展电子科技有限公司": name = "Jingzhan" elif msg["Value"]== "上海巢威计算机科技有限公司": name = "Chaowei" elif msg["Value"]== "上海楷晟信息技术有限公司": name = "Kaisheng" elif msg["Value"]== "上海翊瑄电子科技有限公司": name = "Yixuan" data.insert(6,name) print("正在处理发票"+file) os.remove("image/"+file) except TencentCloudSDKException as err: print(err) print("未识别"+file) return data