def check(idcard_name, idcard_number): api_config = global_dict.get_value("api_config") data = { 'api_key': api_config['appid'], 'api_secret': api_config['appsecret'], 'comparison_type': "1", 'face_image_type': "raw_image", 'idcard_name': idcard_name, 'idcard_number': idcard_number, } image_file = {'image': func.read_file(env.root_path + "/api/avatar.png")} response = requests.post('https://api.megvii.com/faceid/v2/verify', data=data, files=image_file) result = json.loads(response.text) if result.get('error_message'): if result.get('error_message') == 'INVALID_NAME_FORMAT': raise Exception('当前姓名与身份证号码不匹配') elif result.get('error_message') == 'INVALID_IDCARD_NUMBER': raise Exception('当前姓名与身份证号码不匹配') elif result.get('error_message') == 'NO_SUCH_ID_NUMBER': raise Exception('身份证号码不存在') elif result.get('error_message') == 'ID_NUMBER_NAME_NOT_MATCH': raise Exception('身份证号码和姓名不匹配') else: raise Exception(result.get('error_message') + ':校验失败') return {'status': True, 'msg': 'success'}
def ocr(file, side='front'): idcardfile_base64 = str(base64.b64encode(file), 'utf-8') try: api_config = global_dict.get_value("api_config") cred = credential.Credential(api_config['appid'], api_config['appsecret']) 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.IDCardOCRRequest() params = { 'ImageBase64': idcardfile_base64, 'CardSide': 'FRONT' if side == 'front' else 'BACK', 'Config': '{"CopyWarn":true,"BorderCheckWarn":true,"ReshootWarn":true,"DetectPsWarn":true,"TempIdWarn":true,"InvalidDateWarn":true}' } params_json = json.dumps(params) req.from_json_string(params_json) resp = client.IDCardOCR(req) resp = json.loads(resp.to_json_string()) warns = ";".join(get_warns(resp)) if not resp.get('Name') and not resp.get('Authority'): err_msg = "身份证识别错误;" + warns return {'status': False, 'msg': err_msg} msg = '读取成功;' + warns if side == 'front': return { 'status': True, 'msg': msg, 'data': { 'name': resp['Name'], 'gender': resp['Sex'], 'nation': resp['Nation'], 'birth': resp['Birth'].replace('/', '-'), 'address': resp['Address'], 'idnum': resp['IdNum'], } } else: return { 'status': True, 'msg': msg, 'data': { 'authority': resp['Authority'], 'validity': resp['ValidDate'], } } except TencentCloudSDKException as err: return {'status': False, 'msg': err.get_message()}
def compare(image1, image2, **kw): api_config = global_dict.get_value("api_config") nonce_str = get_randstr(16) data = { 'sign': make_sign(api_config['appid'], api_config['appsecret']), 'sign_version': "hmac_sha1", 'liveness_type': "raw_image", 'comparison_type': "0", 'uuid': nonce_str, 'multi_oriented_detection': '1', 'biz_no': nonce_str, 'biz_extra_data': '', } image_file = { 'image': image1, # 待对比的人脸照片 'image_ref1': image2, } response = requests.post( 'https://api.megvii.com/faceid/v3/sdk/get_biz_token', data=data, files=image_file) result = json.loads(response.text) if result.get('error'): raise Exception(result.get('error')) # 拿到biz_token,做验证 biz_token = result['biz_token'] vdata = { 'sign': make_sign(api_config['appid'], api_config['appsecret']), 'sign_version': "hmac_sha1", 'biz_token': biz_token, } vresponse = requests.post('https://api.megvii.com/faceid/v3/sdk/verify', data=vdata) vresult = json.loads(vresponse.text) if vresult.get('error'): raise Exception(vresult.get('error')) if vresult['result_code'] >= 1000 and vresult['result_code'] < 3000: return {'status': True, 'msg': 'success'} if vresult['result_code'] >= 3000 and vresult['result_code'] < 3100: raise Exception(vresult['result_code']) if vresult['result_code'] >= 3100 and vresult['result_code'] < 4000: raise Exception('参考数据调用出错') if vresult['result_code'] >= 4000 and vresult['result_code'] < 4100: raise Exception(vresult['result_code']) if vresult['result_code'] >= 4100 and vresult['result_code'] < 4200: raise Exception('云端活体判断未通过') if vresult['result_code'] >= 4200 and vresult['result_code'] < 4300: raise Exception('SDK活体图像采集失败') raise Exception('验证失败')
def ocr(file): try: api_config = global_dict.get_value("api_config") invoicefile_base64 = str(base64.b64encode(file), 'utf-8') cred = credential.Credential(api_config['appid'], api_config['appsecret']) 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.VatInvoiceOCRRequest() params = { 'ImageBase64': invoicefile_base64, } params_json = json.dumps(params) req.from_json_string(params_json) resp = client.VatInvoiceOCR(req) resp = json.loads(resp.to_json_string()) if not resp.get('VatInvoiceInfos'): return {'status': False, 'msg': '发票识别失败'} data = {} for v in resp['VatInvoiceInfos']: if v['Name'] == '货物或应税劳务、服务名称': data['goods_name'] = v['Value'] if v['Name'] == '购买方名称': data['payer_name'] = v['Value'] if v['Name'] == '数量': data['goods_num'] = v['Value'] if v['Name'] == '单位': data['goods_unit'] = v['Value'] if v['Name'] == '开票日期': data['issue_date'] = v['Value'] if v['Name'] == '发票号码': data['invoice_number'] = v['Value'] if v['Name'] == '金额': data['invoice_amount'] = v['Value'] if v['Name'] == '单价': data['invoice_unit_price'] = v['Value'] return {'status': True, 'data': data} except TencentCloudSDKException as err: return {'status': False, 'msg': str(err)}
def get_token(idcard_name, idcard_number, **kw): api_config = global_dict.get_value("api_config") nonce_str = get_randstr(16) data = { 'api_key': api_config['appid'], 'api_secret': api_config['appsecret'], 'comparison_type': "1", 'idcard_name': idcard_name, 'idcard_number': idcard_number, 'return_url': kw.get('return_url'), 'notify_url': 'http://{host}/liveness/faceid/callback?project={project}&api_provider={api_provider}' .format(host=config.server_name, project=api_config['project'], api_provider=api_config['api_provider']), 'biz_no': nonce_str, 'biz_extra_data': '', } image_file = {} if kw.get('image_ref1'): image_file['image_ref1'] = kw.get('image_ref1') if kw.get('image_ref2'): image_file['image_ref2'] = kw.get('image_ref2') if kw.get('image_ref3'): image_file['image_ref3'] = kw.get('image_ref3') #response = requests.post('https://api.megvii.com/faceid/liveness/v2/get_token', data=data, files=image_file) response = requests.post('https://api.megvii.com/faceid/lite/get_token', data=data, files=image_file) result = json.loads(response.text) log_id = func.save_api_log('liveness', json.dumps(result), api_config['project'], api_config['api_provider'], nonce_str) if not result.get('token'): raise Exception('token获取失败') return {'token': result['token'], 'log_id': log_id, 'nonce_str': nonce_str}
def callback(): api_config = global_dict.get_value("api_config") data_json = request.form.get('data') outsign = request.form.get('sign') sign_str = api_config['appsecret'] + data_json sign = hashlib.sha1(sign_str.encode("utf-8")).hexdigest() data = json.loads(data_json) nonce_str = data['biz_no'] liveness_callback = LivenessCallback.Model() liveness_callback.nonce_str = nonce_str liveness_callback.result = data_json liveness_callback.created = datetime.now().strftime('%Y-%m-%d %H:%M:%S') if sign != outsign: raise Exception('签名错误') # 活体检测结果 liveness_result_fail = None if data['liveness_result']['result'] != 'success': failure_reason = data['liveness_result']['result'] if failure_reason.get('action_mixed'): liveness_result_fail = '做了错误的动作' elif failure_reason.get('not_video'): liveness_result_fail = '检测到活体攻击' elif failure_reason.get('timeout'): liveness_result_fail = '活体动作超时' elif failure_reason.get('quality_check_timeout'): liveness_result_fail = '照镜子流程超时(120秒)' elif failure_reason.get('no_input_frame'): liveness_result_fail = '视频流输入中断' elif failure_reason.get('interrupt_in_mirro_state'): liveness_result_fail = '用户在照镜子流程中断了网页端活体检测' elif failure_reason.get('interrupt_in_action_state'): liveness_result_fail = '用户在活体做动作时中断了网页端活体检测' else: liveness_result_fail = '活体检测结果未知' if liveness_result_fail: liveness_callback.check_status = 0 liveness_callback.check_status = 1 liveness_callback.insert() return {'status': True, 'msg': 'success'}
def getHeader(): api_config = global_dict.get_value("api_config") # 应用APPID(必须为webapi类型应用,并开通身份证识别服务,参考帖子如何创建一个webapi应用:http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=36481) APPID = api_config['appid'] # 接口密钥(webapi类型应用开通身份证识别服务后,控制台--我的应用---身份证识别---相应服务的apikey) API_KEY = api_config['appsecret'] curTime = str(int(time.time())) param = {"engine_type": "idcard", "head_portrait": "0"} param = json.dumps(param) paramBase64 = base64.b64encode(param.encode('utf-8')) m2 = hashlib.md5() str1 = API_KEY + curTime + str(paramBase64, 'utf-8') m2.update(str1.encode('utf-8')) checkSum = m2.hexdigest() # 组装http请求头 header = { 'X-CurTime': curTime, 'X-Param': paramBase64, 'X-Appid': APPID, 'X-CheckSum': checkSum, 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8', } return header
def ocr(file, side='front'): api_config = global_dict.get_value("api_config") data = { 'api_key': api_config['appid'], 'api_secret': api_config['appsecret'], # 传1时返回头像 'return_portrait': '0', } image_file = {'image': file} response = requests.post('https://api.megvii.com/faceid/v3/ocridcard', data=data, files=image_file) result = json.loads(response.text) if not result.get('result'): #return {'status': False, 'msg': result['error']} return {'status': False, 'msg': '当前身份证照片非法'} if result['result'] != 1001 and result['result'] != 1002: return {'status': False, 'msg': '身份证照片非法'} if result['legality']['Edited'] > 0: msg = '该身份证照片为PS合成' else: if result['result'] == 1001: msg = '该身份证照片完全合法' else: if result['legality']['ID_Photo'] >= ID_Photo_Threshold: msg = '该身份证照片为真实拍摄的合法照片' else: msg = '该身份证照片不合法,请确认照片是否完整或PS' if result['side'] == 0: return { 'status': True, 'msg': msg, 'data': { 'side': 'front', 'name': result['name']['result'], 'gender': result['gender']['result'], 'nation': result['nationality']['result'], 'birth': result['birth_year']['result'] + '-' + result['birth_month']['result'] + '-' + result['birth_day']['result'], 'address': result['address']['result'], 'idnum': result['idcard_number']['result'], } } else: return { 'status': True, 'msg': msg, 'data': { 'side': 'back', 'authority': result['issued_by']['result'], 'validity': func.insert_str(result['valid_date_start']['result'], '.', [4, 7]) + '-' + func.insert_str(result['valid_date_end']['result'], '.', [4, 7]), } }
def __init__(self): api_config = global_dict.get_value("api_config") self.appid = api_config['appid'] self.api_key = api_config['appsecret'] self.api_url = 'http://webapi.xfyun.cn/v1/service/v1/ocr/invoice' self.set_header()