百度AI認爲最漂亮的中國女星是----范冰冰

1、程序說明

1.1 程序說明

以前寫調用百度AI接口的程序,而後刷到了兩條明星的新聞,就想到了寫個給明星顏值排下名的程序。javascript

程序的關鍵點是兩個,第一個是百度AI接口的調用這點其實直接使用早前實現的類因此沒有費什麼勁(見Python3+BaiduAI識別高顏值妹子圖片)。php

第二個是怎麼個排法,這個問題還比較大能夠分紅幾個點,第一點是排哪些明星,有哪些明星我也不是很清楚就隨便百度一下而後用了這個網站的名單:https://123fans.cn/rank.php?c=2html

第二個點是去哪裏取圖片,開始想的是從百度異步加載圖片接口取圖片可是發現百度用了一些防止這種操做的措施返回的結果列表直接訪問會返回403,再分析一陣應該能夠處理上selenium硬剛應該也能夠可是不必,換用了搜狗的。結果看到排第一的是範女皇,又加了一個360的排名有了些變化但總的排第一的仍是範女皇。第一就第一吧我也不那麼在乎。java

因此現的程序流程就是:從一個網頁中取回明星名單----for循環名單列表----到搜狗和360各取一次ajax(大概各40張)----將每張圖片傳到百度AI接口----獲取AI接口評分存入數據庫。web

1.2 程序結果說明

百度AI評分排行前99名:ajax

 

百度AI評分最高二十張圖片(AI思想出了問題,慎點):sql

方數真----97.77404785----sougou----http://s4.sinaimg.cn/mw690/001TftpDzy6JKwGUAAb33&690
陳紫函----97.15953064----360----http://images.rednet.cn/articleimage/2010/10/12/1129069853.jpg
楊冪----96.82311249----sougou----http://img5q.duitang.com/uploads/item/201505/12/20150512211001_5uvdh.jpeg
甘婷婷----96.7035675----360----http://s10.sinaimg.cn/mw690/5330f076gd6c34d9b4a29&690
張馨予----96.45571899----sougou----http://s8.sinaimg.cn/mw690/001AxaSkgy6VfYILP3pa7&690
孟子義----96.44942474----360----http://upload.qianhuaweb.com/2016/0830/1472529588682.jpg
范冰冰----95.78607178----sougou----http://p5.qhimg.com/t01d29f433bf172993e.png
張萌----95.58099365----sougou----http://himg2.huanqiu.com/attachment2010/2017/0219/20170219021506253.jpg
楊子姍----95.5355835----sougou----http://www.marubi.cn/vancheerfile/images/2017/3/2017030809597975.jpg
穆婷婷----95.47248077----sougou----http://img.cechoice.com/2016/03/24/201603241349he6ke.500x749.jpg
穆婷婷----95.35915375----sougou----http://img.cechoice.com/2016/03/24/201603241355gd6jd.500x749.jpg
范冰冰----95.2871933----360----http://pic16.nipic.com/20110915/8042943_090150767000_2.jpg
張萌----95.12875366----sougou----http://s8.sinaimg.cn/mw690/0041rhFZzy768ajttf927&690
蔣夢婕----94.87149048----360----http://img1.gtimg.com/ent/pics/hv1/52/109/1370/89112097.jpg
楊冪----94.79195404----sougou----http://cdn.duitang.com/uploads/item/201510/06/20151006152520_Eca3e.jpeg
趙麗穎----94.52903748----360----http://pic1.win4000.com/wallpaper/a/51a845cf17335.jpg
楊冪----94.52243042----360----http://img4.guang.j.cn/g5/M02/C7/76/wKghslZ_uXLT9fwLAADH7H3o2kY14.jpeg!q.50
江語晨----94.43437958----sougou----http://www.ttpaihang.com/image/vote/20111107092812512110.jpg
陳紫函----94.32379913----360----http://news.youth.cn/yl/201307/W020130726332937171156.jpg
江疏影----94.25344086----sougou----http://img0.ph.126.net/8s_MG7gI11mRTMu2W0MGiA==/6631915489163583882.jpg數據庫

 

2、程序源碼

 主程序源代碼(beauty_rank.py):express

import time
import json
import logging
import sqlite3
import requests
from lxml import etree
from urllib.parse import quote
from BaiduFaceIdentify import BaiduFaceIdentify


class BeautyRank():
    def __init__(self):
        self.db_conn = sqlite3.connect('beauty_rank.db')
        self.db_cursor = self.db_conn.cursor()
        self.model_count = 0
        self.bfi = BaiduFaceIdentify()
        pass

    def request_name_list_url(self,name_list_url):
        headers = {
            'Host': '123fans.cn',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
            'Accept-Encoding': 'gzip, deflate, br',
            'Referer': 'https://www.ugirls.com/Models/',
        }
        # 訪問明星名單url
        response = requests.get(name_list_url,headers=headers,timeout=10)
        if response.status_code != 200:
            logging.warning(f"請求失敗:{response.status_code}")
            return False
        sel = etree.HTML(response.text)
        # 獲取明星名單列表
        name_lists = sel.xpath('//div[@id="main"]//div[@class="ranking"]//td[@class="name"]//a/text()')
        star_counts = len(name_lists)
        count = 0
        # 遍歷明星名單
        for star_name in name_lists:
            count += 1
            try:
                logging.warning(f'\r\n開始採集{count}/{star_counts}:{star_name}')
                # 經過搜狗獲取明星圖片
                self.request_and_parse_star_img(star_name,'sougou')
                # 經過360獲取明星圖片
                self.request_and_parse_star_img(star_name,'360')
            except:
                logging.warning(f'\r\n{count}/{star_counts}:{star_name}出現錯誤')
                continue

    def request_and_parse_star_img(self, star_name, search_engine):
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
            'X-Requested-With': 'XMLHttpRequest',
            'Connection': 'close',
        }
        # 根據要求使用的搜索引擎構建請求的url和完善頭部信息
        if search_engine == 'sougou':
            star_img_ajax_request_url = f'http://pic.sogou.com/pics?query={quote(star_name)}&mode=1&start=96&reqType=ajax&reqFrom=result&tn=0'
            headers['Host'] = 'pic.sogou.com'
            headers['Referer'] = 'http://pic.sogou.com/pics?ie=utf8&p=40230504&interV=kKIOkrELjboMmLkEk7kTkKILlLELjboLmLkEkrgTkKIMkrELjboImLkEk74TkKILmrELjb8TkKIKmrELjbkI_1093829215&query=%E8%B5%B5%E4%B8%BD%E9%A2%96&'
            # 下邊從json_results中抽取明星圖片列表的key name
            img_frames_key = 'items'
            # 下邊從明星圖片中抽取圖片具體url的key name
            img_url_key = 'pic_url'
        elif search_engine == '360':
            star_img_ajax_request_url = f'http://image.so.com/j?q={quote(star_name)}&src=tab_www&correct={quote(star_name)}&pn=60&ch=&sn=120&sid=af5aac1212d41c3b5cd6a96a0c311ba2&ran=0&ras=0&cn=0&gn=10&kn=50'
            headers['Host'] = 'image.so.com'
            headers['Referer'] = 'http://image.so.com/i?q=%E8%B5%B5%E4%B8%BD%E9%A2%96&src=tab_www'
            img_frames_key = 'list'
            img_url_key = 'img'
        # 訪問搜索引擎,獲取明星圖片url
        try:
            response = requests.get(star_img_ajax_request_url, headers=headers, timeout=10)
            if response.status_code != 200:
                logging.warning('請求出錯:%s' % response.status_code)
                return False
            json_results = json.loads(response.text)
        except:
            return False
        # 遍歷圖片列表,調用百度AI接口並接收圖片顏值
        for img_frame in json_results[img_frames_key]:
            img_url = img_frame[img_url_key]
            logging.warning(f'{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}開始識別:{img_url}')
            try:
                beauty_value = self.bfi.parse_face_pic(img_url)
            except:
                logging.warning('百度識別出現錯誤')
                continue
            # 若是顏值沒有問題則插入數據庫
            if beauty_value > 1.0:
                logging.warning(
                    f'{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}即將插入數據庫({search_engine}):{star_name}-{beauty_value}-{img_url}')
                self.insert_into_database(star_name, beauty_value, img_url,search_engine)
        return True

    # 此函數用於將結果插入數據庫
    def insert_into_database(self,star_name,beauty_value,img_url,search_engine):
        # 若是表star_beauty_value不存在則先建立
        sql = '''create table if not exists star_beauty_value(star_name text,beauty_value int,img_url text,search_engine text)'''
        self.db_cursor.execute(sql)
        self.db_conn.commit()
        # 將結果插入數據庫
        sql = f'''insert into star_beauty_valuex values('{star_name}','{beauty_value}','{img_url}','{search_engine}')'''
        self.db_cursor.execute(sql)
        self.db_conn.commit()


    def __del__(self):
        self.db_cursor.close()
        self.db_conn.close()
        pass


if __name__ == '__main__':
    # 明星名單url
    name_list_url = 'https://123fans.cn/rank.php?c=2'
    # 實例化
    beauty_rank = BeautyRank()
    beauty_rank.request_name_list_url(name_list_url)

百度AI圖像識別接口調用代碼(BaiduFaceIdentify.py):json

import base64
import requests
import json
import logging
import time


class BaiduFaceIdentify():
    #此函數用於獲取access_token,返回access_token的值
    #此函數被parse_face_pic調用
    def get_access_token(self):
        client_id = 'KuLRFhTzX3zBFBSrbQBsl6Q4'                #此變量賦值成本身API Key的值
        client_secret = '8ahbIb2hEOePzXhehw9ZDL9kGvbzIHTU'    #此變量賦值成本身Secret Key的值
        auth_url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + client_id + '&client_secret=' + client_secret

        response_at = requests.get(auth_url,timeout=10)
        json_result = json.loads(response_at.text)
        access_token = json_result['access_token']
        return access_token

    #此函數進行人臉識別,返回識別到的人臉列表
    #此函數被parse_face_pic調用
    def identify_faces(self,url_pic,url_fi):
        headers = {
            'Content-Type': 'application/json; charset=UTF-8'
        }
        # 由於提交URL讓baidu去讀取圖片,老是返回圖片下載錯了
        # 因此咱們這裏將讀取URL指向的圖片,將圖片轉成BASE64編碼,改用提交BASE64編碼而不是提交URL
        # pic_obj = urllib.request.urlopen(url_pic)
        # pic_base64 = base64.b64encode(pic_obj.read())
        response = requests.get(url_pic,timeout=10)
        pic_base64 = base64.b64encode(response.content)
        post_data = {
            # 'image': url_pic,
            # 'image_type' : 'URL',
            'image': pic_base64,
            'image_type': 'BASE64',
            'face_field': 'facetype,gender,age,beauty', #expression,faceshape,landmark,race,quality,glasses
            'max_face_num': 1
        }
        logging.warning(f'{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}即將識別b2:{url_pic}')
        response_fi = requests.post(url_fi,headers=headers,data=post_data,timeout=10)
        json_fi_result = json.loads(response_fi.text)
        # 有些圖片是沒有人臉的,或者識別有問題,這個咱們不細管直接捕獲異常就返回空列表
        try:
            # if json_fi_result['result'] is None:
            #     return []
            # else:
            return json_fi_result['result']['face_list']
        except Exception:
            return []
        #下邊的print也許是最直觀,你最想要的
        #print(json_fi_result['result']['face_list'][0]['age'])
        #print(json_fi_result['result']['face_list'][0]['beauty'])

    #此函數用於解析進行人臉圖片,返回圖片中人物顏值
    #此函數調用get_access_token、identify_faces
    def parse_face_pic(self,url_pic):
        #調用get_access_token獲取access_token
        access_token = self.get_access_token()
        # access_token = '24.69a8b9206b4989703e38f4fb92878127.2592000.1534075146.282335-11407672'
        url_fi = 'https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=' + access_token
        #調用identify_faces,獲取人臉列表
        logging.warning(f'{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}開始識別b1:{url_pic}')
        json_faces = self.identify_faces(url_pic,url_fi)
        # 若是沒有人臉,那麼就以0.0爲顏值評分返回
        if len(json_faces) == 0:
            # logging.warning('未識別到人臉')
            return 0.0
        else:
            for json_face in json_faces:
                logging.debug('種類:'+json_face['face_type']['type'])
                logging.debug('性別:'+json_face['gender']['type'])
                logging.debug('年齡:'+str(json_face['age']))
                logging.debug('顏值:'+str(json_face['beauty']))
                # 若是識別到的不是妹子,也以1.0爲顏值評分返回
                # 若是識別到的是妹子,直接以值顏值返回
                if json_face['gender']['type'] != 'female':
                    # logging.info('圖片不是妹子')
                    return 1.0
                else:
                    return json_face['beauty']

if __name__ == '__main__':
    #uil_pic賦值成本身要測試的圖片的url地址
    url_pic = 'http://pic.ikafan.com/imgp/L3Byb3h5L2h0dHAvdXNlcmltYWdlMy4zNjBkb2MuY29tLzEzLzA1MDkvMDUvNjYyMjAxMF8yMDEzMDUwOTA1Mzk0NjA4MDMuanBn.jpg'
    bfi = BaiduFaceIdentify()
    bfi.parse_face_pic(url_pic)
View Code
相關文章
相關標籤/搜索