Ejemplo n.º 1
0
 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)
Ejemplo n.º 2
0
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
Ejemplo n.º 3
0
    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()
Ejemplo n.º 4
0
class SDK(object):
    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 send(self, lists):
        try:
            res = self.client.porn_detect(CIFiles(lists))
            if 'httpcode' in res and res[
                    'httpcode'] == 200:  # 'httpcode': 200 为成功
                return res['result_list']
            else:
                return False
        except Exception as e:
            print(e)
            return False
Ejemplo n.º 5
0
 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
Ejemplo n.º 6
0
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)))
Ejemplo n.º 7
0
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
Ejemplo n.º 8
0
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
Ejemplo n.º 9
0
    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
Ejemplo n.º 10
0
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
Ejemplo n.º 11
0
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
Ejemplo n.º 12
0
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'])
Ejemplo n.º 13
0
from qcloud_image import Client
from qcloud_image import CIUrl, CIFile, CIBuffer, CIUrls, CIFiles, CIBuffers

appid = '##############'
secret_id = '###################'
secret_key = '####################'
bucket = '#################'

client = Client(appid, secret_id, secret_key, bucket)
client.use_http()
client.set_timeout(30)

print(client.face_newperson('1', [
    'group2',
], CIFile('1刘德华.jpeg')))
print(client.face_setinfo('1', '刘德华'))
Ejemplo n.º 14
0
class MyQcloudImage:
    __appid = '1252858602'
    __secret_id = 'AKIDTu9e3MafaJuMexuID0er22qUzLgwA3rS'  #  https: // console.qcloud.com / cam / capi获取
    __secret_key = 'oCUccQD43wfheYN0Sir16YzGLEC9pRdR'
    __bucket = 'BUCKET'
    __group = ''
    __person = 'person'
    __id = 1
    is_same = 70
    path = ''
    fileList = []
    picInfo = {}

    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()

    # 主板
    @staticmethod
    def get_board_serialnumber():
        c = wmi.WMI()
        for board_id in c.Win32_BaseBoard():
            return board_id.SerialNumber  # 主板序列号

    def traverse(self):
        fs = os.listdir(self.path)
        for f1 in fs:
            tmp_path = os.path.join(self.path, f1)
            if not os.path.isdir(tmp_path):
                self.fileList.append(tmp_path)

    def add_new_pic(self, path):
        print(self.__person + str(self.__id))
        print(
            self.client.face_newperson(self.__person + str(self.__id), [
                self.__group,
            ], CIFile(path)))
        person_id = self.__person + str(self.__id)
        if person_id in self.picInfo:
            self.picInfo[person_id] = self.picInfo[person_id] + "," + path
        else:
            self.picInfo[person_id] = path
        self.__id = self.__id + 1

    def find_pic(self, path):
        result = self.client.face_identify(self.__group, CIFile(path))
        if result['code'] == 0:
            result = result['data']['candidates']
        else:
            result = []
        return result

    def lookup_pic(self, path):
        mem_list = self.find_pic(path)
        if len(mem_list) == 0:
            self.add_new_pic(path)
            mem_list = self.find_pic(path)
        find_pic = False
        for item in mem_list:
            if item['confidence'] >= self.is_same:
                find_pic = True
                person_id = item['person_id']
                if person_id in self.picInfo:
                    self.picInfo[
                        person_id] = self.picInfo[person_id] + "," + path
                else:
                    self.picInfo[person_id] = path
                return
            if not find_pic:
                self.add_new_pic(path)

    def delete_group(self):
        # 获取组列表
        groups = self.client.face_getgroupids()
        if groups['code'] == 0:
            for item in groups['data']['group_ids']:
                persons = self.client.face_getpersonids(item)
                if persons['code'] == 0:
                    if "person_ids" in persons['data']:
                        for item2 in persons['data']['person_ids']:
                            print(self.client.face_delperson(item2))

    def do_excute(self):
        self.traverse()
        for item in self.fileList:
            self.lookup_pic(item)
        return self.picInfo
Ejemplo n.º 15
0
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()
Ejemplo n.º 16
0
# --coding:utf8--
from qcloud_image import Client
from qcloud_image import CIUrl, CIFile, CIBuffer, CIUrls, CIFiles, CIBuffers

appid = '1254259578'
secret_id = 'AKID5GH7nMzkcKtHTTq2c1FIAtUxFdLvraif'
secret_key = 'vfQ3VL3Zu42qTJzWJD2xyIk28MPI2sZ7'
bucket = 'blog'
client = Client(appid, secret_id, secret_key, bucket)
client.use_http()
client.set_timeout(30)

print(client.porn_detect(CIFiles([
    './45.png',
])))
Ejemplo n.º 17
0
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):
Ejemplo n.º 18
0
#!/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 = '1255316848'
secret_id = 'AKIDkIacaJz26vZy83qAPO7anoZ4JI3ZDrdA'
secret_key = 'QbV9XfX8TYNvDF2auzpPjqiLjsmRr2yf'
bucket = 'faceslib'
client = Client(appid, secret_id, secret_key, bucket)
client.use_http()
client.set_timeout(30)

# appid = '1255955027'
# secret_id = 'AKIDwnT9iA3caNyNbfqLJAqKdrxsdIm55URH'
# secret_key = 'oUyY0LWQJCC81mLm3b3KPSN6e4IQNAmC'
# bucket = 'nvrenlian'

# appid = nan_appid
# secret_id = nan_secretid
# secret_key = nan_secretkey
# bucket = nan_bucket

# client = Client(appid, secret_id, secret_key, bucket)
# client.use_http()
# client.set_timeout(30)

# inf=client.face_detect(CIFile('../photos/init.jpg'))
# gender=inf['data']['face'][0]['gender']
@author:sunyihuan
'''

from qcloud_image import Client
from qcloud_image import CIUrl, CIFile, CIBuffer, CIUrls, CIFiles, CIBuffers
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

# 腾讯云获得
appid = '1256126369'
secret_id = 'AKIDENK7iBfpOn160lzxRk1FJEykOrPwn3Tu'
secret_key = 'c9VfecUExb7YwFXjpttnmkhZL1b6QccU'
bucket = 'test0'

client = Client(appid, secret_id, secret_key, bucket)
client.use_http()
client.set_timeout(30)

# //单个图片file,mode:1为检测最大的人脸 , 0为检测所有人脸
face = client.face_shape(CIFile('./test0.jpg'), 1)

# //单个图片Url,mode:1为检测最大的人脸 , 0为检测所有人脸
# face = client.face_shape(
#     CIUrl('https://xdimg.meiyezhushou.com/xiaomei/material_library/sample_face/2db161612335d559.jpg'), 1)

# 打印脸部数据
print(face["data"])

# 打印图片的高
print('image_height:', face["data"]["image_height"])
Ejemplo n.º 20
0
from qcloud_image import CIUrl, CIFile, CIBuffer, CIUrls, CIFiles, CIBuffers

filename = sys.argv[1]
filepath = sys.argv[2]
'''
appid = 'APPID'
secret_id = 'SECRETID'
secret_key = 'SECRETKEY'
bucket = 'BUCKET'
'''
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)
'''
#图片鉴黄
#单个或多个图片Url
print (client.porn_detect(CIUrls(['YOUR URL A','YOUR URL B'])))
#单个或多个图片File
print (client.porn_detect(CIFiles(['/Users/lishijie/Desktop/1.jpg',])))
#print (client.porn_detect(CIFiles(['./test.jpg',])))
'''
print '智能鉴黄'
a = client.porn_detect(CIFiles([
    filepath,
]))
print a
Ejemplo n.º 21
0
#!/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 = '1255955027'
secret_id = 'AKIDwnT9iA3caNyNbfqLJAqKdrxsdIm55URH'
secret_key = 'oUyY0LWQJCC81mLm3b3KPSN6e4IQNAmC'
bucket = 'nvrenlian'

c = Client(appid, secret_id, secret_key, bucket)
c.use_http()
c.set_timeout(30)

inf = c.face_detect(CIFile('../photos/init.jpg'))
gender = inf['data']['face'][0]['gender']
print(inf['data']['face'][0]['gender'])
print(type(gender))
if gender > 50:
    appid = '1255955027'
    secret_id = 'AKIDwnT9iA3caNyNbfqLJAqKdrxsdIm55URH'
    secret_key = 'oUyY0LWQJCC81mLm3b3KPSN6e4IQNAmC'
    bucket = 'nvrenlian'
    client = Client(appid, secret_id, secret_key, bucket)
    client.use_http()
    client.set_timeout(30)
else:
    appid = '1255316848'
    secret_id = 'AKIDkIacaJz26vZy83qAPO7anoZ4JI3ZDrdA'
Ejemplo n.º 22
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from GetphotoPath import xz
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)

# input_photopath=xz()
input_photopath = 'xiaowei.jpg'
result = client.face_identify('group1', CIFile(input_photopath))
value_no = 80
value_yes = 96
person = client.face_getinfo(result['data']['candidates'][0]['person_id'])
person_id = person['data']['person_id']
person_name = person['data']['person_name']

original_photo_name = person_id + person_name + '.jpeg'
this_path = os.getcwd()
original_photopath = this_path + '/' + original_photo_name
print(input_photopath, original_photopath, person_name)

confidence = result['data']['candidates'][0]['confidence']
Ejemplo n.º 23
0
#!/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 = 'APPID'
secret_id = 'SECRETID'
secret_key = 'SECRETKEY'
bucket = 'BUCKET'

client = Client(appid, secret_id, secret_key, bucket)
client.use_http()
client.set_timeout(30)

#图片鉴黄
#单个或多个图片Url
print(
    client.porn_detect(
        CIUrls([
            'http://jiangsu.china.com.cn/uploadfile/2015/1102/1446443026382534.jpg',
            'http://n.sinaimg.cn/fashion/transform/20160704/flgG-fxtspsa6612705.jpg'
        ])))
#单个或多个图片File
print(client.porn_detect(CIFiles([
    './test.jpg',
])))

# 图片标签
#单个图片url
Ejemplo n.º 24
0
# -*- coding: utf-8 -*-
import os

from qcloud_image import Client
from qcloud_image import CIUrl, CIFile, CIBuffer, CIUrls, CIFiles, CIBuffers

appid = 'APPID'
secret_id = 'SECRETID'
secret_key = 'SECRETKEY'
bucket = 'BUCKET'

client = Client(appid, secret_id, secret_key, bucket)
client.use_http()
client.set_timeout(30)
Ejemplo n.º 25
0
#!/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('该顾客是:')
Ejemplo n.º 26
0
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"