def porn_detect(data): print data client = Client(appid, secret_id, secret_key, bucket) client.use_http() client.set_timeout(30) a=client.porn_detect(CIUrls(data[0:5])) print a
def __init__(self, appid, secret_id, secret_key, bucket=''): try: self.client = Client(appid, secret_id, secret_key, bucket) self.client.use_http() self.client.set_timeout(30) except Exception as e: print(e)
def get_client(self): """获取连接对象""" client = Client(self.app_id, self.secret_id, self.secret_key, self.bucket) client.use_http() client.set_timeout(30) return client
def test_t(a, b): from qcloud_image import Client from qcloud_image import CIUrl, CIFile, CIBuffer, CIUrls, CIFiles, CIBuffers appid = cf.get("qq", "appid") secret_id = cf.get("qq", "secret_id") secret_key = cf.get("qq", "secret_key") bucket = 'BUCKET' client = Client(appid, secret_id, secret_key, bucket) client.use_http() client.set_timeout(30) print("compare {} and {}".format(a, b)) print(client.face_compare(CIFile(a), CIFile(b)))
def check_image(): client = Client(appid, secret_id, secret_key, bucket) client.use_http() client.set_timeout(30) status = True while status: num = str(int(random.uniform(200000, 500000))) url = "https://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-" + num + ".jpg" result = client.porn_detect(CIUrls([url]))["result_list"][0] if result["message"] == "success": if result["data"]["porn_score"] < 1: status = False return url, result
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 event["body"] == "": return {"code": 412, "errorMsg": "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 logger.info("Start to upload images to cos") res_cos = client_cos.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") client_ai = Client(appid, secret_id, secret_key, bucket_upload) client_ai.use_http() client_ai.set_timeout(30) res_ai = client_ai.word_detect(CIFile(local_path)) res_text = " " print len(res_ai["data"]["items"]) for i in range(len(res_ai["data"]["items"])): res_text = res_text + str( res_ai["data"]["items"][i]["itemstring"].encode('utf-8')) delete_local_file(local_path) response = { "isBase64Encoded": False, "statusCode": 200, "headers": { "Content-Type": "text", "Access-Control-Allow-Origin": "*" }, "body": res_text } return response
def __init__(self, path): self.path = path #初始化配置 os.chdir(os.path.dirname(os.path.abspath(__file__))) self.cf = configparser.ConfigParser() self.cf.read("config.conf") self.__appid = self.cf.get("info", "appid") self.__secret_id = self.cf.get("info", "secret_id") self.__secret_key = self.cf.get("info", "secret_key") self.is_same = int(self.cf.get("info", "is_same")) # 初始化Client self.client = Client(self.__appid, self.__secret_id, self.__secret_key, self.__bucket) self.client.use_http() self.client.set_timeout(30) # 初始化group self.__group = self.get_board_serialnumber()
def get_tags(self, path=None): appid = "1257930116" secret_id = "AKIDMXTCQT2n9rgJiape1HNiSdFgZHsSDR8d" secret_key = "RhFg4TwPkR5Zs362udyFSVVmySvRk1GQ" bucket = 'BUCKET' client = Client(appid, secret_id, secret_key, bucket) client.use_http() client.set_timeout(100) res = client.tag_detect(CIFile(path)) # print(res) try: tags = res['tags'] except KeyError: try: res = client.tag_detect(CIFile(path)) tags = res['tags'] except KeyError: print('Error {}: {}'.format(res['code'], res['message'])) return None return tags
def faceplus(filepath): # result = { # 'underLipTop':0, # 'mouthRight':0, # 'upperLipTop':0, # 'upperLipBottom':0, # 'mouthLeft':0, # 'underLipBottom':0 # } # face_file = filepath # image = open(face_file, "rb") # image_body = image.read() client = Client(appid, secret_id, secret_key, bucket) client.use_http() client.set_timeout(30) result = [] raw = client.face_shape(CIFile(filepath + '.jpg'), 1) rawData = raw["data"] if "face_shape" in rawData: if len(rawData["face_shape"]) != 0: result = rawData["face_shape"][0]['mouth'] else: print(raw) # conn = http.client.HTTPSConnection('api.cognitive.azure.cn') # conn.request("POST", "/face/v1.0/detect?%s" % params, image_body, headers) # response = conn.getresponse() # rawData = response.read().decode() # if not json.loads(rawData)[0]: # return False # print(json.loads(rawData)) # rawData = json.loads(rawData)[0]['faceLandmarks'] # conn.close() # for i in rawData: # if 'Lip' in i or 'mouth' in i: # result[i]=rawData[i] # print(i) return result
def qcloud_general(ttf): #控制台-访问管理-云API秘钥管理-新建或获取现有 appid = 'your appid' secret_id = 'your secret_id' secret_key = 'your secret_key' #对象存储 bucket = 'your bucket' client = Client(appid, secret_id, secret_key, bucket) client.use_http() client.set_timeout(30) # 通用印刷体识别 ocr = client.general_detect(CIFile('./merge.png')) ocr_list = [] if ocr['code'] == 0: if len(ocr['data']['items']) > 0: for i, item in enumerate(ocr['data']['items']): for word in item['words']: if word['character'] != '': ocr_list.append(word['character']) if word['character'] == '': print('第%d行,字符串"%s"中有空字符' % (i, item['itemstring'])) ocr_ttf = {} for n in numbers: if n in ttf: ttf.remove(n) for i, t in enumerate(ttf): if i < len(ocr_list): print('%s --> %s' % (t, ocr_list[i])) ocr_ttf[t] = ocr_list[i] else: print('%s 没有被匹配' % t) print(ocr_ttf) else: print('ocr识别结果有误,错误码: %d' % ocr['code'])
def picture_verify(picture): """第三方图片审核api(万象优图)""" appid = "10072767" # 项目ID secret_id = "AKIDZBf2DdSCLNoAPXvH4kHeq2AHF1bz4b9a" # 密钥ID secret_key = "1xjPxMjx4zsfGICvyvg4MX5cHAAze9Xp" # 密钥key bucket = 'chuangyi' # 图片空间名称 image = tencentyun.ImageV2(appid, secret_id, secret_key) try: # image_data = open(picture_url, "rb").read() # 将图片上传到图片空间 obj = image.upload_binary(picture, bucket) # 第二个参数为空间名称 if obj["code"] == 0: fileid = obj["data"]["fileid"] download_url = obj["data"]["download_url"] # 图片检测 client = Client(appid, secret_id, secret_key, bucket) client.use_http() client.set_timeout(30) pornRet = client.porn_detect(CIUrls([download_url])) image.delete(bucket, fileid) return pornRet["result_list"][0]["data"]["result"] except IOError: return None
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from qcloud_image import Client from qcloud_image import CIUrl, CIFile, CIBuffer, CIUrls, CIFiles, CIBuffers appid = '#########' secret_id = '##############' secret_key = '#####################' bucket = 'faceslib' client = Client(appid, secret_id, secret_key, bucket) client.use_http() client.set_timeout(30) result = client.face_identify('group1', CIFile('./10xxl2.jpeg')) value_no=80 value_yes=96 person=client.face_getinfo(result['data']['candidates'][0]['person_id']) person_name = person['data']['person_name'] confidence=result['data']['candidates'][0]['confidence'] print(confidence) if confidence<value_no: print("不存在该顾客") if value_no<=confidence<value_yes: print("该顾客可能是:") print(person_name) if confidence>=value_yes: print('该顾客是:')
def Face(filename): appid = '1256531249' secret_id = 'AKIDGK9iwx8IbgYCcoNW1IK8h27wVosg8ZfV' secret_key = 'iAMIxNxLTKuFJ7fx3uVqwlKdjbEcmhOq' bucket = 'ocrbucket-1256531249' client = Client(appid, secret_id, secret_key, bucket) client.use_http() client.set_timeout(30) print '人脸识别' if client.face_detect(CIFile(filename), 1).get('message') == 'OK': #如果监测到人脸进行如下操作 print 'indect face' # 数据库连接 #conn = pymssql.connect('localhost', 'root', '123456', 'album') db = MySQLdb.connect("localhost", "root", "123456", "album", charset='utf8') cursor = db.cursor() # 数据库查询操作 cursor.execute('SELECT name FROM names') row = cursor.fetchone() flag = 0 id = 1 # 对于每一个查询到的人名 while row: id = id + 1 # print("ID=%d, Name=%s" % (row[0], row[1])) if client.face_verify(row[0], CIFile(filename)).get('data').get( 'confidence') > 90: # 若跟这个人置信度大于90 print '\t\tget ' + row[0] client.face_addface(row[0], CIFiles([ filename, ])) # 就加脸 sql = "update picture set namelabel='" + row[ 0] + "' where pictureid='" + filename.replace( '/home/ubuntu/album/public/', "") + "'" try: cursor.execute(sql) db.commit() print 'update namelabel success' except: db.rollback() print "update namelabel error" flag = 1 break else: # 取下个人名继续判断 row = cursor.fetchone() # 若判断完仍未找到对的人 if flag == 0: client.face_newperson('people' + str(id), [ 'group1', ], CIFile(filename)) # 就添加新人 try: # 并将其插入到数据库中 cursor.execute("INSERT INTO names VALUES( '" + 'people' + str(id) + "')") # 如果没有指定autocommit属性为True的话就需要调用commit()方法 db.commit() print 'insert names success' except: db.rollback() print 'insert names error' try: cursor.execute( "UPDATE picture SET namelabel ='" + 'people' + str(id) + "' where pictureid='" + filename.replace('/home/ubuntu/album/public/', "") + "'") db.commit() print 'update picture.namelabel success' except: db.rollback() print 'update picture.namelabel success' db.close()
def main_handler(event, context): logger.info("start main handler") for record in event['Records']: try: bucket = record['cos']['cosBucket']['name'] + '-' + str(appid) key = record['cos']['cosObject']['key'] key = key.replace( '/' + str(appid) + '/' + record['cos']['cosBucket']['name'] + '/', '', 1) download_path = '/tmp/{}'.format(key) tmpload_path = '/tmp/resized-{}'.format(key) print("Key is " + key) print("Get from [%s] to download file [%s]" % (bucket, key)) # download image from cos try: response = client.get_object( Bucket=bucket, Key=key, ) response['Body'].get_stream_to_file(download_path) except CosServiceError as e: print(e.get_error_code()) print(e.get_error_msg()) print(e.get_resource_location()) return "Fail" logger.info("Download file [%s] Success" % key) logger.info("Image compress function start") starttime = datetime.datetime.now() # compress image here resize_image(download_path, tmpload_path) endtime = datetime.datetime.now() logger.info("compress image take " + str((endtime - starttime).microseconds / 1000) + "ms") # detect idcard print("Start Detection") client_card = Client(appid, secret_id, secret_key, record['cos']['cosBucket']['name']) client_card.use_http() client_card.set_timeout(30) res_up = client_card.idcard_detect(CIFiles([tmpload_path]), 0) res_down = client_card.idcard_detect(CIFiles([tmpload_path]), 1) if res_up["result_list"][0][ "code"] == 0 and res_down["result_list"][0]["code"] != 0: res_up_print = { "姓名:": res_up["result_list"][0]["data"]["name"], "性别:": res_up["result_list"][0]["data"]["sex"], "出生:": res_up["result_list"][0]["data"]["birth"], "住址:": res_up["result_list"][0]["data"]["address"], "民族:": res_up["result_list"][0]["data"]["nation"], "公民身份证号:": res_up["result_list"][0]["data"]["id"] } print json.dumps(res_up_print).decode('unicode-escape') elif res_up["result_list"][0]["code"] != 0 and res_down[ "result_list"][0]["code"] == 0: res_down_print = { "有效期限:": res_down["result_list"][0]["data"]["valid_date"], "签发机关:": res_down["result_list"][0]["data"]["authority"] } print json.dumps(res_down_print).decode('unicode-escape') else: print("err_message: [%s]" % (res_up["result_list"][0]["message"])) print("err_code: [%s]" % (res_up["result_list"][0]["code"])) print("err_filename: [%s]" % (res_up["result_list"][0]["filename"])) delete_local_file(str(download_path)) delete_local_file(str(tmpload_path)) return "Detect Fail" # delete local file delete_local_file(str(download_path)) delete_local_file(str(tmpload_path)) return "Success" except Exception as e: print(e) raise e return "Detect Fail"
import datetime from SmartDjango import E from qcloud_image import Client from qcloud_image import CIUrls from Config.models import Config, CI APP_ID = Config.get_value_by_key(CI.QCLOUD_APP_ID) SECRET_ID = Config.get_value_by_key(CI.QCLOUD_SECRET_ID) SECRET_KEY = Config.get_value_by_key(CI.QCLOUD_SECRET_KEY) BUCKET = 'BUCKET' client = Client(APP_ID, SECRET_ID, SECRET_KEY, BUCKET) client.use_http() client.set_timeout(30) @E.register(id_processor=E.idp_cls_prefix()) class IDCardError: IDCARD_DETECT_ERROR = E("身份证自动验证错误") REAL_VERIFIED = E("已实名认证") CARD_NOT_COMPLETE = E("身份证正反面照片没有完善") CARD_VALID_EXPIRED = E("身份证认证过期") AUTO_VERIFY_FAILED = E("自动实名认证失败,请尝试人工认证") VERIFYING = E("您已提交认证") class IDCard: @staticmethod def detect_front(link):