Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
528 lines (452 loc) · 22.8 KB
/
Copy pathapp.py
File metadata and controls
528 lines (452 loc) · 22.8 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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
#app.py
import streamlit as st
import cv2, requests, json, time, os, base64
import numpy as np
import mediapipe as mp
from keras_facenet import FaceNet
from cryptography.fernet import Fernet
from dotenv import load_dotenv
from scipy.spatial.distance import cosine
st.set_page_config(layout="wide", page_title="FaceSecure Yüz Tanıma Sistemi")
load_dotenv()
API_URL = os.getenv("API_URL", "http://localhost:5000")
FERNET_KEY = os.getenv("FERNET_KEY")
if FERNET_KEY is None:
st.error("HATA: FERNET_KEY ortam değişkeni tanımlanmamış. .env dosyanızı kontrol edin.")
st.stop()
try:
fernet = Fernet(FERNET_KEY.encode())
except Exception as e:
st.error(f"HATA: FERNET_KEY geçerli değil veya bozuk. {e}")
st.stop()
@st.cache_resource
def load_models():
"""FaceNet ve MediaPipe modellerini yükler ve önbelleğe alır."""
try:
embedder = FaceNet()
face_detection = mp.solutions.face_detection.FaceDetection(model_selection=0, min_detection_confidence=0.5)
return embedder, face_detection
except Exception as e:
st.error(f"Model yüklenirken hata oluştu: {e}. Gerekli kütüphanelerin (tensorflow, keras-facenet, mediapipe) yüklü olduğundan ve internet bağlantınızın olduğundan emin olun.")
st.stop()
embedder, mp_face_detection_model = load_models()
def encrypt_embedding(embedding):
"""NumPy dizisini şifreler ve URL güvenli base64 stringine dönüştürür."""
embedding_bytes = np.array(embedding).astype(np.float32).tobytes()
enc = fernet.encrypt(embedding_bytes)
return base64.urlsafe_b64encode(enc).decode()
def decrypt_embedding(enc_embedding_str):
"""URL güvenli base64 stringini çözer ve NumPy dizisine dönüştürür."""
encrypted = base64.urlsafe_b64decode(enc_embedding_str.encode())
decrypted_bytes = fernet.decrypt(encrypted)
return np.frombuffer(decrypted_bytes, dtype=np.float32)
def api_login(username, password):
try:
res = requests.post(f"{API_URL}/login", json={"username": username, "password": password})
if res.status_code == 200:
st.success("Giriş başarılı!")
return res.json().get("access_token")
else:
st.error(f"Giriş hatası: {res.json().get('msg', 'Bilinmeyen hata')}")
return None
except requests.exceptions.RequestException as e:
st.error(f"API'ye bağlanırken hata oluştu: {e}. API sunucusunun çalıştığından emin olun.")
return None
except json.JSONDecodeError as e:
st.error(f"API'den geçersiz JSON yanıtı (login): {e}. Yanıt: {res.text if 'res' in locals() else 'Yanıt alınamadı'}")
return None
def api_add_user(user_name, token):
headers = {"Authorization": f"Bearer {token}"}
try:
response = requests.post(f"{API_URL}/users", json={"user": user_name}, headers=headers)
response.raise_for_status()
st.success(f"Kullanıcı '{user_name}' başarıyla eklendi.")
return response.json()
except requests.exceptions.RequestException as e:
st.error(f"Kullanıcı eklenirken API hatası: {e}. Mesaj: {response.json().get('msg', 'Yanıt yok') if 'response' in locals() else 'Yanıt yok'}")
return {"error": str(e)}
except json.JSONDecodeError as e:
st.error(f"API'den geçersiz JSON yanıtı (add_user): {e}. Yanıt metni: {response.text}")
return {"error": "Geçersiz JSON yanıtı"}
def api_delete_user(user_id, token):
headers = {"Authorization": f"Bearer {token}"}
try:
response = requests.delete(f"{API_URL}/users/{user_id}", headers=headers)
response.raise_for_status()
st.success(f"Kullanıcı '{user_id}' başarıyla silindi.")
return response.json()
except requests.exceptions.RequestException as e:
st.error(f"Kullanıcı silinirken API hatası: {e}. Mesaj: {response.json().get('msg', 'Yanıt yok') if 'response' in locals() else 'Yanıt yok'}")
return {"error": str(e)}
except json.JSONDecodeError as e:
st.error(f"API'den geçersiz JSON yanıtı (delete_user): {e}. Yanıt metni: {response.text}")
return {"error": "Geçersiz JSON yanıtı"}
def api_get_users(token):
headers = {"Authorization": f"Bearer {token}"}
try:
response = requests.get(f"{API_URL}/users", headers=headers)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
st.error(f"Kullanıcılar alınırken API hatası: {e}. Mesaj: {response.json().get('msg', 'Yanıt yok') if 'response' in locals() else 'Yanıt yok'}")
return []
except json.JSONDecodeError as e:
st.error(f"API'den geçersiz JSON yanıtı (get_users): {e}. Yanıt metni: {response.text}")
return []
def api_update_user_embeddings(user_id, embeddings, token):
headers = {"Authorization": f"Bearer {token}"}
try:
response = requests.post(f"{API_URL}/users/{user_id}/embeddings", json={"embeddings": embeddings}, headers=headers)
response.raise_for_status()
st.success(f"Embeddingler '{user_id}' kullanıcısına başarıyla kaydedildi.")
return response.json()
except requests.exceptions.RequestException as e:
st.error(f"Embeddingler güncellenirken API hatası: {e}. Mesaj: {response.json().get('msg', 'Yanıt yok') if 'response' in locals() else 'Yanıt yok'}")
return {"error": str(e)}
except json.JSONDecodeError as e:
st.error(f"API'den geçersiz JSON yanıtı (update_embeddings): {e}. Yanıt metni: {response.text}")
return {"error": "Geçersiz JSON yanıtı"}
def api_log_failed():
try:
requests.post(f"{API_URL}/log_failed", timeout=1)
except requests.exceptions.RequestException as e:
pass
except json.JSONDecodeError as e:
pass
def get_logs(token):
headers = {"Authorization": f"Bearer {token}"}
try:
res = requests.get(f"{API_URL}/logs", headers=headers)
res.raise_for_status()
return res.json()
except requests.exceptions.RequestException as e:
st.error(f"Loglar alınırken API hatası: {e}. Mesaj: {res.json().get('msg', 'Yanıt yok') if 'res' in locals() else 'Yanıt yok'}")
return []
except json.JSONDecodeError as e:
st.error(f"API'den geçersiz JSON yanıtı (get_logs): {e}. Yanıt metni: {res.text}")
return []
def calculate_similarity(embedding1, embedding2):
return 1 - cosine(embedding1, embedding2)
def recognize_face(face_rgb, embeddings_data, threshold=0.7):
new_embedding = embedder.embeddings([face_rgb])[0]
best_score = -1
best_user = None
for user in embeddings_data:
user_id = user["user_id"]
embeddings = []
for e_enc in user.get("embeddings_enc", []):
try:
embeddings.append(decrypt_embedding(e_enc))
except Exception as e:
continue
if embeddings:
scores = [calculate_similarity(new_embedding, e) for e in embeddings]
current_max_score = max(scores)
if current_max_score > best_score:
best_score = current_max_score
best_user = user_id
return (best_user, best_score) if best_score >= threshold else (None, best_score)
def capture_and_register_user_stream(user_id, num_samples=10, token=None):
if token is None:
st.error("Kullanıcı kaydı için geçerli bir token (admin yetkisi) gerekli.")
return
cap = cv2.VideoCapture(0)
if not cap.isOpened():
st.error("Kamera açılamadı. Lütfen başka bir uygulama kullanıp kullanmadığını kontrol edin veya kamera izinlerini kontrol edin.")
return False
embeddings_to_save = []
stframe = st.empty()
status_message = st.empty()
face_detection = mp_face_detection_model
count = 0
last_face_detection_time = time.time()
while count < num_samples:
ret, frame = cap.read()
if not ret:
status_message.error("Kameradan görüntü alınamadı.")
break
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = face_detection.process(rgb)
display_frame = frame.copy()
if results.detections:
if len(results.detections) > 1:
status_message.warning("Birden fazla yüz algılandı! Lütfen sadece bir kişi kameraya baksın.")
cv2.putText(display_frame, "Birden fazla yuz!", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 165, 255), 2) # Turuncu
else:
detection = results.detections[0]
bbox = detection.location_data.relative_bounding_box
h, w, _ = frame.shape
x1, y1 = int(bbox.xmin * w), int(bbox.ymin * h)
x2, y2 = x1 + int(bbox.width * w), y1 + int(bbox.height * h)
cv2.rectangle(display_frame, (x1, y1), (x2, y2), (0, 255, 0), 2) # Yeşil kutu
face = frame[y1:y2, x1:x2]
if face.size == 0:
status_message.warning("Algılanan yüz alanı boş veya geçersiz. Tekrar deneyin.")
continue
face_rgb = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
embedding = embedder.embeddings([face_rgb])[0].tolist()
embeddings_to_save.append(encrypt_embedding(embedding))
count += 1
status_message.info(f"Yüz verisi toplandı: {count}/{num_samples}")
cv2.putText(display_frame, f"Toplaniyor: {count}/{num_samples}", (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
last_face_detection_time = time.time()
else:
current_time = time.time()
if current_time - last_face_detection_time > 2:
status_message.warning("Yüz algılanmadı! Lütfen yüzünüzü kameraya doğru ortalayın.")
cv2.putText(display_frame, "Yuz algilanmadi!", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) # Kırmızı
stframe.image(cv2.cvtColor(display_frame, cv2.COLOR_BGR2RGB), channels="RGB", width=800)
time.sleep(0.1)
cap.release()
stframe.empty()
status_message.empty()
if embeddings_to_save:
st.success(f"Toplam {len(embeddings_to_save)} adet yüz verisi toplandı.")
update_result = api_update_user_embeddings(user_id, embeddings_to_save, token)
if "error" not in update_result:
st.success(f"'{user_id}' kullanıcısının yüz verileri başarıyla güncellendi.")
else:
st.error(f"Yüz verileri kaydedilirken hata oluştu: {update_result['error']}")
else:
st.warning(f"'{user_id}' için hiçbir yüz verisi toplanamadı. Lütfen kamera erişimini ve yüzünüzün netliğini kontrol edin.")
return True
def live_face_recognition_stream(embeddings_data, threshold=0.7):
cap = cv2.VideoCapture(0)
if not cap.isOpened():
st.error("Kamera açılamadı. Lütfen başka bir uygulama kullanıp kullanmadığını kontrol edin veya kamera izinlerini kontrol edin.")
return False
stframe = st.empty()
status_message = st.empty()
last_unrecognized_log_time = 0
face_detection = mp_face_detection_model
while st.session_state.get('live_recognition_active', False):
ret, frame = cap.read()
if not ret:
status_message.error("Kameradan görüntü alınamadı.")
break
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
results = face_detection.process(rgb)
display_frame = frame.copy()
face_detected = False
if results.detections:
if len(results.detections) > 1:
status_message.warning("Birden fazla yüz algılandı!")
cv2.putText(display_frame, "Birden fazla yuz!", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 165, 255), 2) # Turuncu
for detection in results.detections:
bbox = detection.location_data.relative_bounding_box
h, w, _ = frame.shape
x1, y1 = int(bbox.xmin * w), int(bbox.ymin * h)
x2, y2 = x1 + int(bbox.width * w), y1 + int(bbox.height * h)
face = frame[y1:y2, x1:x2]
if face.size == 0:
continue
face_rgb = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
user, score = recognize_face(face_rgb, embeddings_data, threshold)
if user:
label, color = f"{user} ({score*100:.2f}%)", (0, 255, 0) # Yeşil
status_message.success(f"Hoş Geldin, {user}!")
last_unrecognized_log_time = 0
else:
label, color = f"Tanınmadı ({score*100:.2f}%)", (0, 0, 255) # Kırmızı
current_time = time.time()
if current_time - last_unrecognized_log_time > 5:
api_log_failed()
last_unrecognized_log_time = current_time
status_message.error("Kimlik doğrulama başarısız. Lütfen tekrar deneyin.")
cv2.rectangle(display_frame, (x1, y1), (x2, y2), color, 2)
cv2.putText(display_frame, label, (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, color, 2)
face_detected = True
if not face_detected:
status_message.info("Yüz algılanmadı. Lütfen kameraya doğru bakın.")
cv2.putText(display_frame, "Yuz algilanmadi!", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 255), 2) # Pembe
stframe.image(cv2.cvtColor(display_frame, cv2.COLOR_BGR2RGB), channels="RGB", width=800)
time.sleep(0.05)
cap.release()
stframe.empty()
status_message.empty()
st.markdown(
"""
<style>
.main-header {
font-size: 3.5em;
color: #4CAF50;
text-align: center;
margin-bottom: 0.5em;
font-weight: bold;
text-shadow: 2px 2px 4px #aaa;
}
.subheader {
font-size: 1.5em;
color: #555;
text-align: center;
margin-bottom: 2em;
}
.stButton>button {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border-radius: 5px;
border: none;
font-size: 1.1em;
margin: 5px;
box-shadow: 2px 2px 5px rgba(0,0,0,0.2);
}
.stButton>button:hover {
background-color: #45a049;
transform: translateY(-2px);
}
.stTextInput>div>div>input {
padding: 10px;
font-size: 1.1em;
border-radius: 5px;
border: 1px solid #ddd;
}
.stSlider > div > div > div > div {
background-color: #4CAF50;
}
</style>
""", unsafe_allow_html=True
)
st.markdown("<h1 class='main-header'>🔐 FaceSecure</h1>", unsafe_allow_html=True)
st.markdown("<h2 class='subheader'>Yüz Tanıma ve Yönetim Sistemi</h2>", unsafe_allow_html=True)
if "token" not in st.session_state:
st.session_state["token"] = None
if "admin_logged_in" not in st.session_state:
st.session_state["admin_logged_in"] = False
if "live_recognition_active" not in st.session_state:
st.session_state["live_recognition_active"] = False
admin_tab, user_mgmt_tab, user_reg_tab, live_rec_tab, logs_tab = st.tabs([
"🔑 Admin Girişi",
"👥 Kullanıcı Yönetimi",
"✍️ Kullanıcı Yüz Kaydı",
"👁️ Canlı Yüz Tanıma",
"📜 Hatalı Girişler"
])
with admin_tab:
st.subheader("Admin Paneline Giriş")
username = st.text_input("Kullanıcı Adı", key="login_username_tab")
password = st.text_input("Şifre", type="password", key="login_password_tab")
col_admin_login_btn, col_logout_btn = st.columns(2)
with col_admin_login_btn:
if st.button("Giriş Yap", key="login_button_tab"):
token = api_login(username, password)
if token:
st.session_state["token"] = token
st.session_state["admin_logged_in"] = True
st.rerun()
with col_logout_btn:
if st.session_state["admin_logged_in"]:
if st.button("Çıkış Yap", key="logout_button_tab"):
st.session_state["token"] = None
st.session_state["admin_logged_in"] = False
st.success("Admin çıkışı yapıldı.")
st.rerun()
if st.session_state["admin_logged_in"]:
st.info("Admin olarak giriş yapıldı.")
else:
st.warning("Devam etmek için lütfen admin olarak giriş yapın.")
if not st.session_state["admin_logged_in"]:
pass
with user_mgmt_tab:
if not st.session_state["admin_logged_in"]:
st.warning("Önce admin olarak giriş yapmalısınız!")
else:
st.subheader("Kullanıcı Ekle/Sil")
col1, col2 = st.columns(2)
with col1:
st.write("### Yeni Kullanıcı Ekle")
new_user = st.text_input("Kullanıcı Adı", key="add_user_input_tab")
if st.button("Kullanıcı Ekle", key="add_user_button_tab"):
if new_user:
api_add_user(new_user, st.session_state["token"])
st.session_state['refresh_users'] = True
else:
st.error("Kullanıcı adı boş olamaz.")
with col2:
st.write("### Kullanıcı Sil")
users_list_data = api_get_users(st.session_state["token"])
user_options = [user['user_id'] for user in users_list_data if user['user_id'] != 'admin']
if user_options:
del_user = st.selectbox("Silinecek Kullanıcıyı Seç", options=user_options, key="del_user_select_tab")
if st.button("Kullanıcıyı Sil", key="del_user_button_tab"):
if del_user:
api_delete_user(del_user, st.session_state["token"])
st.session_state['refresh_users'] = True
else:
st.error("Silinecek bir kullanıcı seçmelisiniz.")
else:
st.info("Sistemde silinecek kullanıcı bulunamadı.")
st.markdown("---")
st.subheader("Mevcut Kullanıcılar")
if st.button("Kullanıcı Listesini Yenile", key="list_users_button_tab") or st.session_state.get('refresh_users', False):
users_list_data = api_get_users(st.session_state["token"])
if users_list_data:
st.dataframe([{'Kullanıcı ID': user['user_id'], 'Kayıtlı Yüz Sayısı': len(user.get('embeddings_enc', []))} for user in users_list_data if user['user_id'] != 'admin'])
else:
st.info("Sistemde kayıtlı kullanıcı bulunamadı.")
st.session_state['refresh_users'] = False
with user_reg_tab:
if not st.session_state["admin_logged_in"]:
st.warning("Önce admin olarak giriş yapmalısınız!")
else:
st.subheader("Kullanıcı Yüz Kaydı")
users_for_reg = api_get_users(st.session_state["token"])
user_reg_options = [user['user_id'] for user in users_for_reg if user['user_id'] != 'admin']
if user_reg_options:
register_user_id = st.selectbox("Kaydedilecek Kullanıcıyı Seç", options=user_reg_options, key="register_user_id_select")
num_samples = st.slider("Alınacak Yüz Örnek Sayısı", 5, 20, 10, key="num_samples_slider")
if st.button("Yüz Kaydını Başlat", key="start_registration_button_tab"):
if register_user_id:
st.info(f"'{register_user_id}' kullanıcısı için yüz kaydı başlatılıyor. Lütfen kameraya bakın ve hareket etmeyin.")
capture_and_register_user_stream(register_user_id, num_samples, st.session_state["token"])
else:
st.error("Kaydedilecek Kullanıcı ID'si seçmelisiniz.")
else:
st.info("Yüz kaydı yapılacak kullanıcı bulunamadı. Lütfen önce 'Kullanıcı Yönetimi' menüsünden kullanıcı ekleyin.")
def run_live_recognition(embeddings_data, threshold):
live_face_recognition_stream(embeddings_data, threshold)
with live_rec_tab:
if not st.session_state["admin_logged_in"]:
st.warning("Önce admin olarak giriş yapmalısınız!")
else:
st.subheader("Canlı Yüz Tanıma")
threshold_value = st.slider("Tanıma Eşik Değeri (%)", 0, 100, 70, key="threshold_slider_tab")
threshold = threshold_value / 100.0
embeddings_data_for_rec = api_get_users(st.session_state["token"])
valid_users_for_rec = [u for u in embeddings_data_for_rec if u.get('embeddings_enc') and len(u['embeddings_enc']) > 0]
if not valid_users_for_rec:
st.warning("Canlı tanıma için kayıtlı yüz verisi olan kullanıcı bulunamadı. Lütfen kullanıcı ekleyin ve yüz kaydı yapın.")
else:
# Durum kontrolü için bir container oluştur
status_container = st.empty()
# Butonları her zaman göster
col_start, col_stop = st.columns(2)
with col_start:
if st.button("Canlı Tanımayı Başlat", key="start_recognition_button_tab"):
if not st.session_state.get("live_recognition_active", False):
st.session_state["live_recognition_active"] = True
status_container.info("Canlı yüz tanıma başlatılıyor...")
live_face_recognition_stream(valid_users_for_rec, threshold)
else:
status_container.warning("Canlı tanıma zaten aktif.")
with col_stop:
if st.button("Canlı Tanımayı Durdur", key="stop_recognition_button_tab"):
if st.session_state.get("live_recognition_active", False):
st.session_state["live_recognition_active"] = False
status_container.info("Canlı tanıma durduruldu. Yeni bir işlem başlatabilirsiniz.")
else:
status_container.warning("Canlı tanıma zaten durdurulmuş durumda.")
# Başlangıç durumu mesajı
if not st.session_state.get("live_recognition_active", False):
status_container.info("Tanımayı başlatmak için 'Canlı Tanımayı Başlat' düğmesine basın.")
with logs_tab:
if not st.session_state["admin_logged_in"]:
st.warning("Önce admin olarak giriş yapmalısınız!")
else:
st.subheader("Son Hatalı Giriş Denemeleri")
if st.button("Logları Yenile", key="refresh_logs_button_tab"):
logs = get_logs(st.session_state["token"])
if logs:
st.dataframe(logs)
else:
st.info("Hatalı giriş kaydı bulunamadı.")