Graduate

Modify server.py

...@@ -42,6 +42,10 @@ async def get_distance(arr1, arr2): ...@@ -42,6 +42,10 @@ async def get_distance(arr1, arr2):
42 distance = np.linalg.norm(arr1 - arr2) 42 distance = np.linalg.norm(arr1 - arr2)
43 return distance 43 return distance
44 44
45 +async def get_cosine_similarity(arr1, arr2):
46 + similarity = np.inner(arr1, arr2) / (np.linalg.norm(arr1) * np.linalg.norm(arr2))
47 + return similarity
48 +
45 def get_argmin(someone, database): 49 def get_argmin(someone, database):
46 distance = get_distance(someone, database) 50 distance = get_distance(someone, database)
47 for i in range(len(distance)): 51 for i in range(len(distance)):
...@@ -126,7 +130,7 @@ async def thread(websocket, path): ...@@ -126,7 +130,7 @@ async def thread(websocket, path):
126 cursor.execute(sql) 130 cursor.execute(sql)
127 result = cursor.fetchall() 131 result = cursor.fetchall()
128 verified_id = '0' 132 verified_id = '0'
129 - distance_min = 1.0 133 + distance_min = 99
130 for row_data in result: 134 for row_data in result:
131 db_embedding = np.frombuffer(row_data['embedding'], dtype=np.float32) 135 db_embedding = np.frombuffer(row_data['embedding'], dtype=np.float32)
132 db_embedding = db_embedding.reshape((1,512)) 136 db_embedding = db_embedding.reshape((1,512))
...@@ -138,7 +142,7 @@ async def thread(websocket, path): ...@@ -138,7 +142,7 @@ async def thread(websocket, path):
138 # 출석 데이터 전송 142 # 출석 데이터 전송
139 send = '' 143 send = ''
140 print('[debug] distance:', distance_min) 144 print('[debug] distance:', distance_min)
141 - if distance_min >= 0.6: 145 + if distance_min >= 0.5:
142 # 해당하는 사람 DB에 없음 146 # 해당하는 사람 DB에 없음
143 msg='[{ip}] verification failed'.format(ip=remote_ip) 147 msg='[{ip}] verification failed'.format(ip=remote_ip)
144 print(msg) 148 print(msg)
...@@ -146,36 +150,40 @@ async def thread(websocket, path): ...@@ -146,36 +150,40 @@ async def thread(websocket, path):
146 else: 150 else:
147 # 해당하는 사람 DB에 있음 151 # 해당하는 사람 DB에 있음
148 # logging 152 # logging
149 - msg='[{ip}] verification success {id}'.format(ip=remote_ip, id=verified_id)
150 - print(msg)
151 -
152 # TODO: lecture DB에 tuple 삽입해야 아래 코드가 돌아감 153 # TODO: lecture DB에 tuple 삽입해야 아래 코드가 돌아감
153 - # 해당하는 사람이 DB에 있으면 출석 처리 154 + # DB에 오늘 이미 출석한 기록이 있는지 확인
154 - # 테이블 맨 뒤에 datetime attribute가 있음. 서버 시간 가져오게 default로 설정해둠. 155 + sql = "SELECT DATE(timestamp) FROM student_attendance WHERE (lecture_id=%s) AND (student_id=%s) AND (DATE(timestamp) = CURDATE());"
155 - #sql = "INSERT INTO student_attendance(lecture_id, student_id, status) VALUES (%s, %s, %s, %s)" 156 + cursor.execute(sql, ('0', verified_id))
156 - 157 +
157 - # TODO: attend / late 처리 158 + # 출석 기록이 없는 경우에만
158 - #cursor.execute(sql, ('0', verified_id, 'attend')) 159 + if not cursor.fetchone():
159 - 160 + # 테이블 맨 뒤에 datetime attribute가 있음. 서버 시간 가져오게 default로 설정해둠.
160 - # client에 전달 161 + sql = "INSERT INTO student_attendance(lecture_id, student_id, status) VALUES (%s, %s, %s)"
161 - send = json.dumps({'status': 'success', 'student_id': verified_id}) 162 + # TODO: attend / late 처리
163 + cursor.execute(sql, ('0', verified_id, 'attend'))
164 + attendance_db.commit()
165 + # log 작성
166 + msg='[{ip}] verification success {id}'.format(ip=remote_ip, id=verified_id)
167 + print(msg)
168 + # client에 전달
169 + send = json.dumps({'status': 'success', 'student_id': verified_id})
170 + else:
171 + send = json.dumps({'status': 'already', 'student_id': verified_id})
162 await websocket.send(send) 172 await websocket.send(send)
163 elif data['action'] == "save_image": 173 elif data['action'] == "save_image":
164 # 출석이 제대로 이뤄지지 않으면 이미지를 저장하여 174 # 출석이 제대로 이뤄지지 않으면 이미지를 저장하여
165 # 나중에 교강사가 출석을 확인할 수 있도록 한다 175 # 나중에 교강사가 출석을 확인할 수 있도록 한다
166 msg='[{ip}] save image'.format(ip=remote_ip) 176 msg='[{ip}] save image'.format(ip=remote_ip)
167 print(msg) 177 print(msg)
168 -
169 arr = np.asarray(data['image'], dtype = np.uint8) 178 arr = np.asarray(data['image'], dtype = np.uint8)
170 blob = arr.tobytes() 179 blob = arr.tobytes()
171 - #datetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
172 180
173 # TODO: lecture DB에 tuple 삽입해야 아래 코드가 돌아감 181 # TODO: lecture DB에 tuple 삽입해야 아래 코드가 돌아감
174 # 테이블 맨 뒤에 datetime attribute가 있음. 서버 시간 가져오게 default로 설정해둠. 182 # 테이블 맨 뒤에 datetime attribute가 있음. 서버 시간 가져오게 default로 설정해둠.
175 - #cursor = attendance_db.cursor(pymysql.cursors.DictCursor) 183 + cursor = attendance_db.cursor(pymysql.cursors.DictCursor)
176 - #sql = "INSERT INTO undefined_image(lecture_id, datetime, image, width, height) VALUES (%s, %s, _binary %s, %s, %s)" 184 + sql = "INSERT INTO undefined_image(lecture_id, image, width, height) VALUES (%s, _binary %s, %s, %s)"
177 - #cursor.execute(sql, ('0', datetime, blob, arr.shape[0], arr.shape[1])) 185 + cursor.execute(sql, ('0', blob, arr.shape[0], arr.shape[1]))
178 - #attendance_db.commit() 186 + attendance_db.commit()
179 else: 187 else:
180 print("unsupported event: {}", data) 188 print("unsupported event: {}", data)
181 finally: 189 finally:
......