⚡ A few lines of code show that your beauty is high!!! ⚡

Posted by frewuill on Thu, 16 Dec 2021 13:19:09 +0100

Achieve goals:
  use Baidu AI interface to score photos.

1, Foreword

   presumably, many people are full of curiosity about their looks, and many software provide you with interesting features for scoring their looks. Today, we will use Baidu's platform to detect the face value. Its platform has accurately recognized a variety of face attribute information, including age, gender, face value, expression, emotion, mask, face shape, head posture, whether to close your eyes, whether to wear glasses, face quality information and type, etc

2, Environmental preparation

Editor: pycharm

Libraries used: os, AipFace, base64

3, Concrete implementation

1. Install Baidu AI Library

  Python SDK can be installed and used in the following ways: [official documents]

If pip is installed, execute PIP install Baidu AIP.
If setuptools is installed, execute Python setup Py install.

2. New AipFace

   AipFace is a Python SDK client for face recognition, which provides a series of interaction methods for developers using face recognition.
  create an AipFace by referring to the following code:

from aip import AipFace

""" Yours APPID AK SK """
APP_ID = 'Yours App ID'
API_KEY = 'Yours Api Key'
SECRET_KEY = 'Yours Secret Key'

client = AipFace(APP_ID, API_KEY, SECRET_KEY)

In the above code, the constant APP_ID is created in Baidu cloud console, constant API_KEY and secret_ Keys are strings assigned by the system to the user after the application is created. They are used to identify the user and perform signature verification for access. They can be viewed in the application list in the AI service console.

3. Interface description

image = "Depending on image_type Parameters, passing in BASE64 String or URL String or FACE_TOKEN character string"

imageType = "BASE64"
# image_type: 
# Picture type base64: base64 value of the picture, base64 encoded picture data, and the encoded picture size does not exceed 2M;
# URL: the URL address of the picture (it may take too long to download the picture due to network and other reasons);
# FACE_TOKEN: the unique identifier of the face image. When calling the face detection interface, a unique face will be given to each face image_ Token, the face obtained from multiple tests of the same picture_ Token is the same

""" Call face detection """
client.detect(image, imageType);

""" If there are optional parameters """
options = {}
options["face_field"] = "age"
#face_field 
#Including age,beauty,expression,face_shape,gender,glasses,landmark,landmark72,landmark150,quality,eye_status,emotion,face_type information is separated by commas 
# Only face is returned by default_ Token, face frame, probability and rotation angle
options["max_face_num"] = 2
options["face_type"] = "LIVE"

options["liveness_control"] = "LOW"

""" Call face detection with parameters """
client.detect(image, imageType, options)

4. Return data

  the returned data is json data. What we mainly need is the value of beauty

{
  "face_num": 1,
  "face_list": [
        {
            "face_token": "35235asfas21421fakghktyfdgh68bio",
            "location": {
                "left": 117,
                "top": 131,
                "width": 172,
                "height": 170,
                "rotation": 4
            },
            "face_probability": 1,
            "angle" :{
                 "yaw" : -0.34859421849251
                 "pitch" 1.9135693311691
                 "roll" :2.3033397197723
            }
            "landmark": [
                {
                    "x": 161.74819946289,
                    "y": 163.30244445801
                },
                ...
            ],
            "landmark72": [
                {
                    "x": 115.86531066895,
                    "y": 170.0546875
                },
                ...
            ],
            "age": 29.298097610474,
            "beauty": 55.128883361816,
            "expression": {
                "type": "smile",
                "probability" : 0.5543018579483
            },
            "gender": {
                "type": "male",
                "probability": 0.99979132413864
            },
            "glasses": {
          "type": "sun",
                "probability": 0.99999964237213
            },
            "face_shape": {
                "type": "triangle",
                "probability": 0.5543018579483
            }
            "quality": {
                "occlusion": {
                    "left_eye": 0,
                    "right_eye": 0,
                    "nose": 0,
                    "mouth": 0,
                    "left_cheek": 0.0064102564938366,
                    "right_cheek": 0.0057411273010075,
                    "chin": 0
                },
                "blur": 1.1886881756684e-10,
                "illumination": 141,
                "completeness": 1
            }
        }
    ]
}

5. Define function

   define the function to obtain beauty, and the passed in parameter is the file name

def get_score(file_name):
    APP_ID = '24792216'
    API_KEY = 'r5dKhE5Yloc74x3mxrhaXdpP'
    SECRET_KEY = 'CMPnLas3QvkU2u64W3ItG9dtWchBZXSs'

    client = AipFace(APP_ID, API_KEY, SECRET_KEY)
	
	#Read pictures for base64
    with open("img/" + file_name, mode="rb")as fp:
        data = base64.b64encode(fp.read())

    imageType = "BASE64"
    image = data.decode()

    options = {
        "face_field": "beauty"
    }
    result = client.detect(image, imageType, options)
    beauty_score = result['result']['face_list'][0]['beauty']
    return beauty_score # Returns the value of beauty

6. Picture crawling function

def save_pic():
    url = 'https://www.huya.com/g/4079'
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safar"
    }
    tree = etree.HTML(requests.get(url=url, headers=headers).text)
    img_list = tree.xpath('//li[@class="game-live-item"]/a/img/@data-original')
    name_list = tree.xpath('//li[@class="game-live-item"]//span[@class="avatar fl"]/i/text()')
    for img, name in zip(img_list, name_list):
        with open("img/" + name + ".jpg", mode="wb")as fp:
            fp.write(requests.get(url=img, headers=headers).content)

7. Main function

if __name__ == '__main__':
	save_pic()
	
    path = "./img"
    file_name_list = os.listdir(path) # Read files under folder

    info_list = [] # Store all picture information
    for file_name in file_name_list:
        info = {}
        try:
            beauty_score = get_score(file_name)
            info["name"] = file_name[:-4]
            info["beauty"] = beauty_score
            info_list.append(info)
        except Exception as e:
            info["name"] = file_name[:-4]
            info["beauty"] = 0
            info_list.append(info)

8. Results

    read the cover pictures of 20 tiger tooth anchor and score their appearance. Through the results, we can see that this case is successful.
   the size of the leaked face of the picture will also affect the evaluation score. For some 0 points, open the picture to observe because the face is blocked and the face is not completely recognized. Baidu is particularly good in this regard!

4, Finally

  finally, put the anchor photo with the highest score~~~~

Topics: Python crawler