def check(idcard_name, idcard_number): try: #api_config = global_dict.get_value("api_config") cred = credential.Credential("AKID96rMeho9uQiqjRvCI8C3f6esstjMjFZi", "3toZ7RmtlSv9EA0f8LNJ6i6MOYXHoQr5") httpProfile = HttpProfile() httpProfile.endpoint = "faceid.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = faceid_client.FaceidClient(cred, "ap-guangzhou", clientProfile) req = models.IdCardOCRVerificationRequest() params = { "IdCard": idcard_number, "Name": idcard_name, } params_json = json.dumps(params) req.from_json_string(params_json) resp = client.IdCardOCRVerification(req) resp = resp.to_json_string() return resp except FileNotFoundError as err_file: return {'status': False, 'msg': err_file.strerror} except TencentCloudSDKException as err: return {'status': False, 'msg': err.get_message()}
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 ""
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
def getCodeFromImg(res, imgUrl): response = res.get(imgUrl, verify=False) # 将这个图片保存在内存 # 得到这个图片的base64编码 imgCode = str(base64.b64encode(BytesIO(response.content).read()), encoding='utf-8') # print(imgCode) try: cred = credential.Credential(Utils.getYmlConfig()['SecretId'], Utils.getYmlConfig()['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": imgCode} req.from_json_string(json.dumps(params)) resp = client.GeneralBasicOCR(req) codeArray = json.loads(resp.to_json_string())['TextDetections'] code = '' for item in codeArray: code += item['DetectedText'].replace(' ', '') if len(code) == 4: return code else: return Utils.getCodeFromImg(res, imgUrl) except TencentCloudSDKException as err: raise Exception('验证码识别出现问题了' + str(err.message))
def updateIngress(cred, host_ip): apidebug(host_ip.decode()) try: client = new_vpc_client(cred=cred, method="POST") httpProfile = HttpProfile() httpProfile.endpoint = "vpc.ap-guangzhou.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = vpc_client.VpcClient(cred, "ap-guangzhou", clientProfile) req = vpc_models.ReplaceSecurityGroupPolicyRequest() req.from_json_string(params) req.SecurityGroupPolicySet.Ingress[0].CidrBlock = str(host_ip.decode()) req.SecurityGroupPolicySet.Version = '11' resp = client.ReplaceSecurityGroupPolicy(req) if os.getenv('API_JSON_INFO') == "1": # resp = client.ReplaceSecurityGroupPolicy(req) apiinfo(resp.to_json_string()) return resp except TencentCloudSDKException as err: print(err)
def search(secu_id, secu_key, region, cpu, memory): try: # 连接数据库获取区域代码 region_data = ZoneCode.objects.get(zone=region).code 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_data, clientProfile) req = models.DescribeInstanceTypeConfigsRequest() # 过滤实例机型,S1,M1等 params = '{}' req.from_json_string(params) # 腾讯云返回结果 resp = client.DescribeInstanceTypeConfigs(req) # json转字典 instance_type_set = json.loads(resp.to_json_string()) # 查询出满足cpu,memory配置的机型地区zone,实例类型名称放入列表中,防止重复的无法放入 zone = [] ins_type = [] for ins in instance_type_set['InstanceTypeConfigSet']: if ins['CPU'] == int(cpu) and ins['Memory'] == int(memory): zone.append(ins['Zone']) ins_type.append(ins['InstanceType']) # 返回地区和类型,一一对应 return zone, ins_type except TencentCloudSDKException as err: raise err
def picocr(self): ocrarea = ImageGrab.grab(bbox=(p.left, p.top, p.right, p.bottom)) ocrarea.save(fp.ocr_area) with open(fp.ocr_area, 'rb') as f: base64_data = base64.b64encode(f.read()) s = base64_data.decode() ImageBase64_value = 'data:image/jpeg;base64,%s'%s try: cred = credential.Credential(k.SECRET_ID, k.SECRET_KEY) httpProfile = HttpProfile() httpProfile.endpoint = "ocr.ap-guangzhou.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = ocr_client.OcrClient(cred, "ap-guangzhou", clientProfile) req = models.GeneralBasicOCRRequest() params = '{"ImageBase64":"' + ImageBase64_value + '"}' req.from_json_string(params) resp = client.GeneralBasicOCR(req) Orecognition.ocrresult = resp.to_json_string() with open(fp.txt_ocr_path,"w", encoding='utf-8') as f: transjson = json.loads(ocrresult) for item in transjson['TextDetections']: line = item['DetectedText'] f.write("%s\n" %(line)) except TencentCloudSDKException as err: print(err)
def upload(test): try: cred = credential.Credential("AKIDqWw76td4PaibJoaEBMLBlARTdaXHhoVw", "PFs7DGNNCmCYfe7bqyucBVhcZ3PabU9h") httpProfile = HttpProfile() httpProfile.endpoint = "nlp.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = nlp_client.NlpClient(cred, "ap-guangzhou", clientProfile) req = models.ChatBotRequest() params = json.dumps({ "Query" : test }) req.from_json_string(params) resp = client.ChatBot(req) print(resp.to_json_string()) date = json.loads(resp.to_json_string())["Reply"] return date except TencentCloudSDKException as err: print(err) return "error"
def TencentFaceDetect(filepath: str): img = open(filepath, 'rb') # 对图像进行base64编码 base64_data = base64.b64encode(img.read()) # 对原图像进行base64解码,得到所处理图像 image = base64_data.decode() # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey cred = credential.Credential(APP_ID, APP_KEY) # 实例化一个http选项,可选的,没有特殊需求可以跳过。 httpProfile = HttpProfile() # 指定接入地域域名(默认就近接入) httpProfile.endpoint = "iai.tencentcloudapi.com" # 实例化一个client选项,可选的,没有特殊需求可以跳过。 clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile # 实例化请求产品的client对象,clientProfile是可选的。 client = iai_client.IaiClient(cred, "ap-beijing") #, clientProfile) # 实例化一个实例信息查询请求对象,每个接口都会对应一个request对象。 req = models.DetectFaceRequest() # 定义参数。 支持以标准json格式的string来赋值请求参数的方式。 params = {"MaxFaceNum": 10, "Image": image, "NeedFaceAttributes": 1} req.from_json_string(json.dumps(params)) # 通过client对象调用DetectFace方法发起请求。 resp = client.DetectFace(req) # 输出json格式的字符串回包 out = resp.to_json_string() # 将json格式返回值转为字典 face_dict = json.loads(out) # 遍历人脸信息列表,返回性别、位置等信息 for item in face_dict['FaceInfos']: yield (item['FaceAttributesInfo']['Gender'], item['X'], item['Y'], item['Width'], item['Height'])
def OcrBase64(Base64,SecretId,SecretKey): try: cred = credential.Credential(SecretId, SecretKey) 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\":\"+' Base64 '+\"}' req.from_json_string(params) resp = client.GeneralBasicOCR(req) jsonstr = json.loads(resp.to_json_string()) array = jsonstr['TextDetections'] s = '' for i in array: s = s + i['DetectedText'] return s # f = open('C:\\Users\\hasee\\Documents\\UiPath\\Play\\1.txt','w') # f.write(s) # return '1' except TencentCloudSDKException as err: print(err)
def tencentLanguageDetect(text): 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_language = models.LanguageDetectRequest() if text[-1:] == '\n': text = text[0:len(text) - 1] language_params_front = r'{"Text":"' language_params_back = r'","ProjectId":0}' language_params = language_params_front + text + language_params_back req_language.from_json_string(language_params) resp_language = client.LanguageDetect(req_language) responselanguage = resp_language.to_json_string() language = responselanguage[10:12] except TencentCloudSDKException as err: print(err) return language
def main(): parser = argparse.ArgumentParser(description='argparse') parser.add_argument('--SecretId', '-id', required =True, type=str, dest='SecretId', help="Tencent Cloud ID used to call the API interface") parser.add_argument('--SecretKey', '-key', required =True, type=str, dest='SecretKey', help="Tencent Cloud key used to call the API interface") parser.add_argument('--ProductId', '-pid', required =True, type=str, dest='ProductId', help="Product ID of the device to be created") parser.add_argument('--ProductNum', '-num', required =True, type=int, dest='ProductNum', help="The number of devices to be created") args = parser.parse_args() try: cred = credential.Credential(args.SecretId, args.SecretKey) httpProfile = HttpProfile() httpProfile.endpoint = "iotexplorer.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = iotexplorer_client.IotexplorerClient(cred, "ap-shanghai", clientProfile) i = 1 while i < args.ProductNum + 1: req = models.CreateDeviceRequest() params = { "ProductId":args.ProductId, "DeviceName":"test_"+ str(i) } req.from_json_string(json.dumps(params)) i += 1 resp = client.CreateDevice(req) print(resp.to_json_string()) except TencentCloudSDKException as err: print(err)
async def call_tencent_api(text: str) -> Optional[str]: """调用腾讯机器人的 API 获取回复""" cred = credential.Credential( plugin_config.tencent_ai_secret_id, plugin_config.tencent_ai_secret_key, ) httpProfile = HttpProfile() httpProfile.endpoint = "nlp.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = nlp_client.NlpClient(cred, "ap-guangzhou", clientProfile) req = models.ChatBotRequest() params = {"Query": text} req.from_json_string(json.dumps(params)) resp = client.ChatBot(req) if resp.Reply: msg: str = resp.Reply # 替换腾讯昵称 # 从小龙女换成设置的机器人昵称 nickname: str = list(global_config.nickname)[0] msg = msg.replace("腾讯小龙女", nickname) msg = msg.replace("小龙女", nickname) return msg
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
def search(account_name, secu_id, secu_key): region_name = [] region = [] try: # key,id cred = credential.Credential(secu_id, secu_key) httpProfile = HttpProfile() httpProfile.endpoint = "cvm.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = cvm_client.CvmClient(cred, "", clientProfile) # 所有可用地域 req = models.DescribeRegionsRequest() params = '{}' req.from_json_string(params) # 结果转成字典类型 resp = client.DescribeRegions(req) # print(resp.to_json_string()) res = json.loads(resp.to_json_string()) for i in range(res['TotalCount']): region.append(res['RegionSet'][i]['Region']) insert_ins_type(account_name, httpProfile, cred, res['RegionSet'][i]['Region']) region_name.append(res['RegionSet'][i]['RegionName']) except TencentCloudSDKException as err: print(err) return region, region_name
def tx_ocr(filePath, fileName): # 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey cred = credential.Credential("AKIDoPltlNQxwfdPxFP5h7qwFLCojSvDC5f3", "5wsZ5L1Vq0zlHYeV6yfGdkcFdmjTxCG6") httpProfile = HttpProfile() httpProfile.endpoint = "ocr.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = ocr_client.OcrClient(cred, "ap-guangzhou", clientProfile) req = models.TableOCRRequest() path = filePath with open(path, "rb") as f: #转为二进制格式 base64_data = base64.b64encode(f.read()) #使用base64进行加密 params = base64_data.decode('utf-8') req.ImageBase64 = str(params) resp = client.TableOCR(req) data = base64.b64decode(resp.Data) path = './res_xlsx/' + fileName + '.xlsx' with open(path, "wb") as f: f.write(data) f.close print('xlsx successed')
def transform( text: str, cred: credential.Credential = createCredential()) -> bytes: try: httpProfile = HttpProfile() httpProfile.endpoint = "aai.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = aai_client.AaiClient(cred, "ap-shanghai", clientProfile) req = models.TextToVoiceRequest() params = { "Text": text, "SessionId": "2021年5月11日", "SampleRate": 8000, "Codec": "mp3", "ModelType": 1, } req.from_json_string(json.dumps(params)) resp = client.TextToVoice(req) raw = resp.to_json_string() data = json.loads(raw) audio = data["Audio"].encode() return base64.b64decode(audio) except TencentCloudSDKException as err: traceback.print_exc() return b""
def ocr(file): try: idcardfile_base64 = str(base64.b64encode(file), 'utf-8') cred = credential.Credential(config.tencent['general']['secretid'], config.tencent['general']['secretkey']) httpProfile = HttpProfile() httpProfile.endpoint = "ocr.tencentcloudapi.com" clientProfile = ClientProfile('TC3-HMAC-SHA256') clientProfile.httpProfile = httpProfile client = ocr_client.OcrClient(cred, "ap-guangzhou", clientProfile) req = models.GeneralAccurateOCRRequest() params = { 'ImageBase64': idcardfile_base64, } params_json = json.dumps(params) req.from_json_string(params_json) resp = client.GeneralAccurateOCR(req) resp = json.loads(resp.to_json_string()) if not resp.get('TextDetections'): return {'status': False, 'msg': '识别失败'} data = [] for v in resp['TextDetections']: data.append(v['DetectedText']) return {'status': True, 'msg': 'success', 'data': data} except FileNotFoundError as err_file: return {'status': False, 'msg': err_file.strerror} except TencentCloudSDKException as err: return {'status': False, 'msg': err.get_message()}
def get_results(self, task_id, ind): try: print("Getting result for %s" % self.temp_data["file_path"][ind]) 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.DescribeTaskStatusRequest() params = {"TaskId": task_id} req.from_json_string(json.dumps(params)) seconds = 0 while True: time.sleep(1) seconds += 1 resp = client.DescribeTaskStatus(req) result_json = json.loads(resp.to_json_string()) result_status = result_json["Data"]["StatusStr"] if result_status in ["success", "failed"]: break print(seconds) result_data = result_json["Data"]["ResultDetail"] result_data_str = json.dumps(result_data, ensure_ascii=False) self.temp_data["result_data"].append(result_data_str) except TencentCloudSDKException as err: print(err)
def get_client_instance(id, key, product): '''获取指定endpoint的实例,用于后面对其的各种操作 ''' try: # 实例化一个认证对象,入参需要传入腾讯云账户 secretId,secretKey, 此处还需注意密钥对的保密 cred = credential.Credential(id, key) # 实例化一个 http 选项,可选 httpProfile = HttpProfile() # post 请求 (默认为 post 请求) httpProfile.reqMethod = "POST" # 请求超时时间,单位为秒 (默认60秒) httpProfile.reqTimeout = 30 # 不指定接入地域域名 (默认就近接入) httpProfile.endpoint = "{}.tencentcloudapi.com".format(product) # 实例化一个 client 选项,可选 clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile # 实例化要请求产品的 client 对象,clientProfile 是可选的 if product == "ssl": client = ssl_client.SslClient(cred, "", clientProfile) print("实例化一个ssl_client成功") elif product == "cdn": client = cdn_client.CdnClient(cred, "", clientProfile) print("实例化cdn client成功") elif product == "ecdn": client = ecdn_client.EcdnClient(cred, "", clientProfile) print("实例化ecdn client成功") else: exit("本程序仅支持ssl、cdn、ecdn") return client except TencentCloudSDKException as err: print(err) exit(-1)
def translate(source, target, ls): while True: 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 = models.TextTranslateBatchRequest() params = { "Source": source, "Target": target, "ProjectId": 0, "SourceTextList": ls } params = json.dumps(params) req.from_json_string(params) resp = client.TextTranslateBatch(req) result = json.loads(resp.to_json_string()) # print(result) ls_ = result.get("TargetTextList", []) return ls_ except TencentCloudSDKException as err: err = str(err) # 超时就继续 if 'RequestLimitExceeded' in err: continue else: print(err) break
def send_phone_access(phone, code): secret_id = getattr(settings, 'TENCENT_CLOUD_SECRETID') secret_key = getattr(settings, 'TENCENT_CLOUD_SECRETKEY') sms_appid = getattr(settings, 'SMS_APPID_TENCENT') sms_tplid = getattr(settings, 'SMS_TPL_ID_TENCENT') sms_tpl_sign = getattr(settings, 'SMS_TPL_SIGN_TENCENT') if not secret_id or not secret_key: logger.error('TENCENT CLOUD 配置错误') return False, 404 if not sms_appid or not sms_tplid or not sms_tpl_sign: logger.error('TENCENT SMS 配置错误') return False, 404 try: cred = credential.Credential(secret_id, secret_key) http_profile = HttpProfile() http_profile.endpoint = "sms.tencentcloudapi.com" client_profile = ClientProfile() client_profile.httpProfile = http_profile client = sms_client.SmsClient(cred, "", client_profile) req = sms_models.SendSmsRequest() req.SmsSdkAppid = sms_appid req.Sign = sms_tpl_sign req.ExtendCode = "" req.SenderId = "" req.PhoneNumberSet = ["+86" + phone] req.TemplateID = sms_tplid req.TemplateParamSet = [code] resp = client.SendSms(req) if resp.SendStatusSet[0].Code != 'Ok': logger.error(resp.to_json_string()) return False, 404 return True, code except TencentCloudSDKException as e: logger.error(e)
def run(SecretId, SecretKey, files): ''' 行业文档识别-表格识别, 使用本地图片转换为ImageBase64格式. ''' try: cred = credential.Credential(SecretId, SecretKey) httpProfile = HttpProfile() httpProfile.endpoint = "ocr.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = ocr_client.OcrClient(cred, "", clientProfile) # 调用接口 req = models.TableOCRRequest() for img_file in files: image_base64 = encode_image(img_file) params = '{"ImageBase64":"{}"}'.format(image_base64) print(params) req.from_json_string(params) resp = client.TableOCR(req) base64_res = resp["Response"][ "Data"] # String, Base64 编码后的 Excel 数据 destine_file = 'output/' + ".".join( img_file.split(".")[0:-1]) + ".xlsx" write_res2file(base64_res, destine_file) except TencentCloudSDKException as err: print(err)
def englishOCR(cls, bs, action="ImageBase64", region="ap-shanghai"): bs = str(bs, encoding="utf-8") try: cred = credential.Credential(cls._secretId, cls._secretKey) httpProfile = HttpProfile() httpProfile.endpoint = cls._endpoint clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = ocr_client.OcrClient(cred, region, clientProfile) req = models.EnglishOCRRequest() params = {action: bs} req.from_json_string(json.dumps(params)) resp = client.EnglishOCR(req) texts = resp.TextDetections total = len(texts) actual = 0 res = [] for ele in texts: text = ele.DetectedText text = text.strip() if not text: continue actual += 1 res.append(text) return {"data": res, "total": total, "actual": actual}, None except Exception as e: return None, e
def getTitle(text): try: cred = credential.Credential("AKIDmNTMzJ1KxKVYMzst0r33wayDG4cvC1mP", "iFaprj390oQnuyxZy8A0FH4c6NQK3Xlj") httpProfile = HttpProfile() httpProfile.endpoint = "nlp.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = nlp_client.NlpClient(cred, "ap-guangzhou", clientProfile) req = models.TextClassificationRequest() str_list = ['{"Text":"', text, '"}'] params = "".join(str_list) req.from_json_string(params) resp = client.KeywordsExtraction(req) data = demjson.decode(resp.to_json_string()) get = data['Keywords'] result = [''] for item in get: result.append(item['Word']) result.append('/') finalResult = "".join(result) return finalResult except TencentCloudSDKException as err: print(err)
def sms_callback(phone): """运营服务商发送短信callback""" try: cred = credential.Credential(settings.SMS_SECRET_ID, settings.SMS_SECRET_KEY) http_profile = HttpProfile() http_profile.endpoint = "sms.tencentcloudapi.com" client_profile = ClientProfile() client_profile.httpProfile = http_profile client = sms_client.SmsClient(cred, "", client_profile) req = models.SendSmsRequest() phone_number = phone sms_code = '%06d' % random.randint(0, 999999) print("手机验证码", sms_code) expire_in = "1" # min params = { "PhoneNumberSet": ["+86" + str(phone_number)], "TemplateParamSet": [sms_code, expire_in], "TemplateID": settings.SMS_TEMPLATE_ID, "SmsSdkAppid": settings.SMS_SDK_APP_ID, "Sign": settings.SMS_SIGN } req.from_json_string(json.dumps(params)) resp = client.SendSms(req) if json.loads( resp.to_json_string())["SendStatusSet"][0]["Code"] == "Ok": return sms_code except TencentCloudSDKException as err: print(err)
def Tencent_OCR_IDCard(pic_str, flag_side, flag_piccut, flag_porcut): cred = credential.Credential("Your ID", "Your Secret") httpProfile = HttpProfile() httpProfile.endpoint = "ocr.tencentcloudapi.com" clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = ocr_client.OcrClient(cred, "ap-beijing", clientProfile) req = models.IDCardOCRRequest() params_1 = r'{"ImageBase64":"' if flag_side: params_2 = r'","CardSide":"BACK","Config":"{\"CropIdCard\":' else: params_2 = r'","CardSide":"FRONT","Config":"{\"CropIdCard\":' if flag_piccut: params_3 = r'false,\"CropPortrait\":' else: params_3 = r'true,\"CropPortrait\":' if flag_porcut: params_4 = r'false}"}' else: params_4 = r'true}"}' params = params_1 + pic_str + params_2 + params_3 + params_4 #params = '{"ImageBase64":"pic_str","CardSide":"FRONT","Config":"{\\"CropIdCard\\":true,\\"CropPortrait\\":true}"}' req.from_json_string(params) resp = client.IDCardOCR(req) text = resp.to_json_string() return text
def search_zone(security_id, security_key, region): # 可用区代号,中文名 zone = [] zone_name = [] try: # id,key cred = credential.Credential(security_id, security_key) httpProfile = HttpProfile() httpProfile.endpoint = "cvm.tencentcloudapi.com" # 要查询的区域 clientProfile = ClientProfile() clientProfile.httpProfile = httpProfile client = cvm_client.CvmClient(cred, region, clientProfile) # 返回结果可用区信息 req = models.DescribeZonesRequest() params = '{}' req.from_json_string(params) # 结果转成字典 resp = client.DescribeZones(req) # print(resp.to_json_string()) res = json.loads(resp.to_json_string()) # 返回可用区的中文名和代号 for i in range(res['TotalCount']): zone.append(res['ZoneSet'][i]['Zone']) zone_name.append(res['ZoneSet'][i]['ZoneName']) except TencentCloudSDKException as err: print(err) return zone, zone_name
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 tencentOCR(src, format): try: cred = credential.Credential("AKIDqUBfvwgZCan9Ppq93kEVgcHM4QY24Z9U", "IqSTZUQ7nJSPzsxnOo34rQOFsIlx1tcI") 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":"data:image/' + format + ';base64,' + src + '"}' req.from_json_string(params) resp = client.GeneralBasicOCR(req) recv = resp.to_json_string() except TencentCloudSDKException as err: print(err) str = json.loads(recv) DetectedText = jsonpath.jsonpath(str, "$..DetectedText") parseDetect = "" for msg in DetectedText: print(msg) parseDetect += msg + '\n' return parseDetect