-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain-integrate.py
More file actions
208 lines (183 loc) · 5.9 KB
/
Copy pathmain-integrate.py
File metadata and controls
208 lines (183 loc) · 5.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import base64
import os
import webbrowser
import sqlite3
import shutil
from pyecharts.charts import Bar
from pyecharts import options as opts
from aip import AipFace
from icrawler.builtin import BingImageCrawler
""" 三码 """
APP_ID = '119427968'
API_KEY = 'rgoAdHB9JuTTul0INkCeKuix'
SECRET_KEY = 's8hkvt1xOPFPj3Ns1tmtpKKfC3eP1eFo'
keyword = ''
count = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # 存储每个分类下的图片数量
def bing_image_crawler(keyword, max_num):
"""
通过Bing搜索下载图片
:param keyword: 关键字
:param max_num: 最大尝试数量
:return:
"""
dic = 'bing_img'
# 如果有之前的文件夹,先删了
if os.path.exists(dic):
# 删了文件夹
shutil.rmtree(dic)
bing_crawler = BingImageCrawler(
feeder_threads=1,
parser_threads=2,
downloader_threads=4,
storage={'root_dir': dic}
)
bing_crawler.crawl(keyword=keyword, max_num=max_num)
def get_file_content(file_path):
"""
文件转BASE64编码字符串
:param file_path: 文件路径
:return: 转换后的结果
"""
file = open(file_path, 'rb')
data = file.read()
content = base64.b64encode(data)
file.close()
base = content.decode('utf-8')
return base
def detect_face(base):
"""
送给百度服务器进行人脸检测
:param base: BASE64编码之后的图片
:return: 服务器返回的JSON数据
"""
client = AipFace(APP_ID, API_KEY, SECRET_KEY)
options = {'face_field': 'beauty'}
json = client.detect(base, 'BASE64', options)
return json
def parse_json(json):
"""
解析服务器返回的JSON数据
:param json:
:return:解析出的颜值,如果检测失败返回-1
"""
# 判断是否成功
code = json['error_code']
if code == 0:
# 成功检测到人脸,返回颜值分数(十分制)
beauty = int(json['result']['face_list'][0]['beauty'] / 10) + 1
else:
beauty = -1
return beauty
def classify():
"""
先爬取图片,百度检测每张图片,在Windows中按照颜值分拣成不同的文件夹
:return: TODO
"""
root_dir = 'bing_img' # 图片根目录
file_list = os.listdir(root_dir) # 把文件夹中的文件名都存到列表中
print(file_list)
# 遍历图片
for i in file_list:
# 拼接出文件路径
path = root_dir + '/' + i
print(path)
# 判断是否是文件
if os.path.isfile(path):
base = get_file_content(path) # BASE64
json = detect_face(base) # 百度
beauty = parse_json(json) # 解析颜值
# 拿到外部的count列表
global count
# 统计图片数量
if beauty == -1: # 不是人脸
count[0] += 1 # 计数 + 1
else: # 是人脸
count[beauty] += 1 # 计数+1
# 把图片分类到不同的目录
dic = root_dir + '/' + str(beauty) # 文件夹路径
if not os.path.exists(dic): # 如果文件夹不存在
os.makedirs(dic) # 创建文件夹
# 移动文件到所属的目录位置
# 参数1:源文件的位置
# 参数2:目标文件位置
os.rename(path, dic + '/' + i)
def draw_charts(keyword, y_axis):
"""
画柱状图
:param keyword: 关键字
:param y_axis: y轴数据
:return: 生成的网页
"""
# 不习惯链式调用的开发者依旧可以单独调用方法
bar = Bar() # 创建一个柱状图对象
# 添加x轴
bar.add_xaxis(['无人脸', '1', '2', '3', '4',
'5', '6', '7', '8', '9', '10'])
# 添加y轴
bar.add_yaxis(keyword, y_axis)
# 设置标题
bar.set_global_opts(title_opts=opts.TitleOpts(title="颜值分布"))
file_name = '颜值分布.html'
# 生成网页,参数为网页名称
bar.render(file_name)
return file_name
def save_data2db(keyword, y_axis):
"""
存储数据分析的结果到数据库
:param keyword: 关键字
:param y_axis: 颜值的y轴数据
"""
# 连接到SQLite
# 参数为数据库文件名称
# 返回值:数据库连接对象
conn = sqlite3.connect('data_analyze.db')
# 创建一个游标对象,用于执行SQL语句等操作
cursor = conn.cursor()
# 执行建表语句
sql = '''
CREATE TABLE IF NOT EXISTS beauty(
id INTEGER PRIMARY KEY,
detect_time TEXT DEFAULT CURRENT_TIMESTAMP,
keyword TEXT,
no_face INTEGER DEFAULT 0,
one INTEGER DEFAULT 0,
two INTEGER DEFAULT 0,
three INTEGER DEFAULT 0,
four INTEGER DEFAULT 0,
five INTEGER DEFAULT 0,
six INTEGER DEFAULT 0,
seven INTEGER DEFAULT 0,
eight INTEGER DEFAULT 0,
nine INTEGER DEFAULT 0,
ten INTEGER DEFAULT 0
);
'''
cursor.execute(sql)
# 插入数据
# 组装已有数据为一个元组
y_axis.insert(0, keyword)
params = tuple(y_axis)
print(params)
# 准备一个预处理的SQL语句
sql = '''
INSERT INTO beauty(keyword,no_face,one,two,three,four,five,six,seven,eight,nine,ten)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?);
'''
# 替换占位符并执行插入操作
# 参数1:预处理的SQL语句(包含占位符)
# 参数2:要替换的参数列表
cursor.execute(sql, params)
# 提交事务
conn.commit()
# 关闭游标和连接
cursor.close()
conn.close()
if __name__ == '__main__':
keyword = input('请输入爬取的关键字:')
bing_image_crawler(keyword, 100)
classify()
file = draw_charts(keyword, count)
# 通过Python代码直接调用浏览器打开网页
webbrowser.open(file)
print("颜值分布情况:", count)
save_data2db(keyword, count)