forked from baagee/face_lock
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathface_lock.py
More file actions
executable file
·208 lines (194 loc) · 8.1 KB
/
Copy pathface_lock.py
File metadata and controls
executable file
·208 lines (194 loc) · 8.1 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
208
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
Author : dangliuhui
date: 2017/12/20
-------------------------------------------------
"""
import os
import json
import base64
import cv2
import time
import datetime
import logging
import configparser
import shutil
import requests
import ctypes
import platform
import pyautogui as pag
from PIL import Image
class FaceLock(object):
""" 人脸识别锁屏类 """
LOCK_SCREEN = False
POINT_X = POINT_Y = GET_AT_TIME = GET_FACE_TIME = FACE_MATCH_TIME = 0
ALERT_TIMEOUT = 1000 * 4
ALERT_TITLE = '人脸识别锁屏'
def __init__(self):
# 读取配置文件
conf = configparser.ConfigParser()
conf.read('./conf.ini', encoding='utf-8')
self.AK = conf.get('setting', 'API_KEY')
self.SK = conf.get('setting', 'SECRET_KEY')
self.SCREEN_LOCK_LEVEL = float(conf.get('setting', 'SCREEN_LOCK_LEVEL'))
self.LOCK_FACE_LIVENESS = float(conf.get('setting', 'LOCK_FACE_LIVENESS'))
self.RETRY_TIME = int(conf.get('setting', 'RETRY_TIME'))
if not os.path.exists('./log'):
os.mkdir('./log')
logName = './log/%s.log' % datetime.datetime.now().strftime('%Y_%m_%d')
self.logger = logging.getLogger('face_lock_logger')
fh = logging.FileHandler(logName, encoding='utf-8')
self.logger.setLevel(logging.INFO)
formatter = logging.Formatter('[%(asctime)s] - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
fh.setFormatter(formatter)
self.logger.addHandler(fh)
self.PLATFORM = platform.system()
if self.PLATFORM not in ['Darwin', 'Windows']:
self.logger.error('暂不支持您的系统:%s,程序退出' % self.PLATFORM)
exit()
# Access Token的有效期为30天(以秒为单位)
self.ACCESS_TOKEN = self.__getAccessToken()
# 获取接口access token
def __getAccessToken(self):
url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s' % (
self.AK, self.SK)
try:
request = requests.get(url)
request.raise_for_status()
res = json.loads(request.text)
return res['access_token']
except Exception as e:
self.logger.error('获取access token失败:%s' % e)
if self.GET_AT_TIME < self.RETRY_TIME:
self.GET_AT_TIME += 1
self.__getAccessToken()
else:
self.logger.error('获取access token失败,重试次数已用尽,程序退出')
pag.alert(text='获取access token失败,重试次数已用尽,程序退出', title=self.ALERT_TITLE, timeout=self.ALERT_TIMEOUT)
exit()
# 开始检测
def __checkIsMe(self):
time.sleep(10)
self.__getFace()
res = self.__matchFace()
self.logger.info('人脸识别结果:%s' % res)
if res.get('result_num', 0) > 0:
faceliveness = res.get('ext_info').get('faceliveness').split(',')[0]
score = res['result'][0].get('score')
if float(faceliveness) < self.LOCK_FACE_LIVENESS or float(score) < self.SCREEN_LOCK_LEVEL:
self.logger.info('人脸识别相似度太小,或者不是真人,即将锁屏')
self.__lockScreen()
else:
self.logger.info('人脸相似度:%s,真人概率:%s,不锁屏' % (score, faceliveness))
else:
self.logger.error('人脸识别失败,可能没人在电脑面前,立即锁屏')
self.__lockScreen(True)
# 锁屏
def __lockScreen(self, now=False):
# 当前日期
nowDate = datetime.datetime.now().strftime("%Y_%m_%d")
# 当前时间
nowTime = datetime.datetime.now().strftime("%H_%M_%S")
# 保存导致锁屏的图片
lock_picture_path = './picture/lock_pictures/%s' % nowDate
if not os.path.exists(lock_picture_path):
os.makedirs(lock_picture_path)
new_path = '%s/%s.jpg' % (lock_picture_path, nowTime)
shutil.move('./picture/face.jpg', new_path)
res = 'NOW'
if not now:
res = pag.confirm('倒计时4秒,确定要锁屏吗?', title=self.ALERT_TITLE, timeout=self.ALERT_TIMEOUT)
self.logger.info('confirm 弹框返回值: %s' % res)
if res == 'OK' or res == 'Timeout' or res == 'NOW':
self.LOCK_SCREEN = True
if self.PLATFORM == 'Darwin':
# macOS
os.system('/System/Library/CoreServices/Menu\ Extras/User.menu/Contents/Resources/CGSession -suspend')
elif self.PLATFORM == 'Windows':
# windows
dll = ctypes.WinDLL('user32.dll')
dll.LockWorkStation()
time.sleep(7)
x, y = pag.position()
self.logger.info('锁屏前鼠标坐标:x=%d,y=%d' % (x, y))
self.POINT_X = x
self.POINT_Y = y
# 人脸识别匹配
def __matchFace(self):
url = 'https://aip.baidubce.com/rest/2.0/face/v2/match?access_token=%s' % self.ACCESS_TOKEN
img1 = base64.b64encode(open('./picture/face.jpg', 'rb').read()).decode()
img2 = base64.b64encode(open('./picture/myFace.jpg', 'rb').read()).decode()
data = {
'images': img1 + ',' + img2,
'image_liveness': 'faceliveness,',
'types': '7,7'
}
try:
request = requests.post(url, data=data)
request.raise_for_status()
res = request.text
res = json.loads(res)
err_code = res.get('error_code')
if err_code != None:
raise Exception(res.get('error_msg'))
else:
return res
except Exception as e:
self.logger.error('人脸识别错误: %s' % e)
if self.FACE_MATCH_TIME < self.RETRY_TIME:
self.FACE_MATCH_TIME += 1
self.__matchFace()
else:
self.logger.error('人脸识别失败,重试次数已用尽,程序退出')
pag.alert('人脸识别失败,重试次数已用尽,程序退出', title=self.ALERT_TITLE, timeout=self.ALERT_TIMEOUT)
exit()
# 拍照
def __getFace(self):
cap = cv2.VideoCapture(0)
while True:
time.sleep(0.2)
ret, frame = cap.read()
if ret:
# 制作缩略图
image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
image.thumbnail((500, 300))
if not os.path.exists('./picture'):
os.mkdir('./picture')
image.save("./picture/face.jpg", format='jpeg')
del frame, ret, image
break
else:
self.logger.error('拍照失败,重试...')
if self.GET_FACE_TIME < self.RETRY_TIME:
self.GET_FACE_TIME += 1
else:
self.logger.error('拍照失败,重试次数已用尽,程序退出')
pag.alert('拍照失败,重试次数已用尽,程序退出', title=self.ALERT_TITLE, timeout=self.ALERT_TIMEOUT)
exit()
cap.release()
# 检查鼠标是否移动
def __checkPointMove(self):
# 每隔10秒检查一次
time.sleep(10)
x, y = pag.position()
self.logger.info('鼠标坐标:x=%d,y=%d' % (x, y))
if x == self.POINT_X and y == self.POINT_Y:
self.logger.info('鼠标没动,还是锁屏状态')
else:
# 鼠标移动了,说明锁屏,继续运行
self.LOCK_SCREEN = False
self.logger.info('鼠标动了,继续开始识别')
# 开始执行
def execute(self):
while True:
if self.LOCK_SCREEN:
self.__checkPointMove()
else:
self.__checkIsMe()
def __del__(self):
print('已关闭')
if __name__ == '__main__':
fl = FaceLock()
print('已开启...')
fl.execute()