vanv123 commited on
Commit
e727cd2
·
verified ·
1 Parent(s): 11efd0f

Upload 11 files

Browse files
Files changed (11) hide show
  1. .gitattributes +2 -35
  2. .gitignore +7 -0
  3. README.md +34 -19
  4. app.py +164 -0
  5. collect_data.py +63 -0
  6. face_db.pkl +0 -0
  7. main.py +114 -0
  8. my_face.jpg +0 -0
  9. recognizer.py +0 -0
  10. requirements.txt +12 -3
  11. train_antispoof.py +78 -0
.gitattributes CHANGED
@@ -1,35 +1,2 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ *.pth filter=lfs diff=lfs merge=lfs -text
2
+ *.onnx filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ venv/
2
+ __pycache__/
3
+ models/
4
+ *.zip
5
+ *.onnx
6
+ *.pth
7
+ *.dat
README.md CHANGED
@@ -1,19 +1,34 @@
1
- ---
2
- title: Aidd
3
- emoji: 🚀
4
- colorFrom: red
5
- colorTo: red
6
- sdk: docker
7
- app_port: 8501
8
- tags:
9
- - streamlit
10
- pinned: false
11
- short_description: Streamlit template space
12
- ---
13
-
14
- # Welcome to Streamlit!
15
-
16
- Edit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart:
17
-
18
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
19
- forums](https://discuss.streamlit.io).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🎓 AI Attendance Mini - Hệ Thống Điểm Danh Nhận Diện Khuôn Mặt Tích Hợp Chống Giả Mạo
2
+
3
+ Dự án này là một ứng dụng Web điểm danh tự động bằng công nghệ AI, được xây dựng với Python và Streamlit. Hệ thống không chỉ nhận diện khuôn mặt sinh viên theo thời gian thực mà còn tích hợp mô hình Liveness Detection (Chống giả mạo) để phân biệt người thật và ảnh chụp/màn hình điện thoại.
4
+
5
+ ## 🚀 Các Tính Năng Nổi Bật (Features)
6
+ * **Nhận diện khuôn mặt Real-time:** Sử dụng thư viện `face_recognition` và OpenCV để trích xuất và so khớp đặc trưng khuôn mặt với độ chính xác cao.
7
+ * **Liveness Detection (Anti-Spoofing):** Huấn luyện mô hình AI phân loại ảnh thật (`real`) và ảnh giả mạo (`fake`) để ngăn chặn hành vi điểm danh hộ qua ảnh in hoặc thiết bị điện tử.
8
+ * **Giao diện trực quan:** Triển khai Web App bằng Streamlit giúp giảng viên dễ dàng thao tác, theo dõi camera trực tiếp.
9
+ * **Quản lý dữ liệu:** Lưu trữ danh sách điểm danh và hỗ trợ xuất báo cáo (ví dụ: định dạng CSV).
10
+
11
+ ## 🛠️ Công Nghệ Sử Dụng (Tech Stack)
12
+ * **Ngôn ngữ:** Python 3.x
13
+ * **AI & Computer Vision:** OpenCV, face_recognition, (scikit-learn/TensorFlow/PyTorch - *tuỳ thuộc vào thư viện em dùng trong train_antispoof*)
14
+ * **Frontend / Web Framework:** Streamlit, Streamlit-WebRTC
15
+ * **Database / Lưu trữ mô hình:** file `.pkl` (Pickle) để lưu vector khuôn mặt
16
+
17
+ ## 📂 Cấu Trúc Thư Mục (Project Structure)
18
+ ```text
19
+ AI_ATTENDANCE_MINI/
20
+ │
21
+ ├── dataset/ # Thư mục chứa dữ liệu huấn luyện Liveness Detection
22
+ │ ├── fake/ # Dữ liệu ảnh khuôn mặt giả mạo (ảnh in, màn hình)
23
+ │ └── real/ # Dữ liệu ảnh khuôn mặt người thật
24
+ │
25
+ ├── models/ # Chứa các file trọng số mô hình sau khi train
26
+ │
27
+ ├── app.py # File chính chạy giao diện Web Streamlit
28
+ ├── collect_data.py # Script hỗ trợ chụp và thu thập dữ liệu khuôn mặt
29
+ ├── main.py # File thực thi luồng logic chính hoặc test hệ thống
30
+ ├── recognizer.py # Module chứa các hàm trích xuất và so khớp khuôn mặt
31
+ ├── train_antispoof.py # Script huấn luyện mô hình phân biệt thật/giả
32
+ ├── face_db.pkl # File cơ sở dữ liệu đã mã hoá đặc trưng khuôn mặt
33
+ ├── my_face.jpg # Ảnh mẫu để test
34
+ └── requirements.txt # Danh sách các thư viện cần cài đặt
app.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from streamlit_webrtc import webrtc_streamer, VideoProcessorBase, WebRtcMode
3
+ import cv2
4
+ import numpy as np
5
+ from insightface.app import FaceAnalysis
6
+ import av
7
+ from datetime import datetime
8
+ import os
9
+ import pickle
10
+ from PIL import Image
11
+
12
+ # Cấu hình trang
13
+ st.set_page_config(page_title="Hệ thống điểm danh AI - STU", layout="wide")
14
+ st.markdown("""
15
+ <style>
16
+ .block-container { padding-top: 1rem !important; }
17
+ [data-testid="stVideo"], [data-testid="stCameraInput"] { border-radius: 10px; border: 3px solid #2e2e2e; }
18
+ .stButton>button { border-radius: 8px; font-weight: bold; width: 100%; }
19
+ .status-box { padding: 10px; border-radius: 8px; margin-bottom: 5px; font-weight: bold;}
20
+ </style>
21
+ """, unsafe_allow_html=True)
22
+
23
+ DB_FILE = "face_db.pkl"
24
+
25
+ @st.cache_resource
26
+ def load_ai_engine():
27
+ # Sử dụng mô hình buffalo_sc để cân bằng giữa tốc độ và độ chính xác
28
+ app = FaceAnalysis(name='buffalo_sc', root='./models', providers=['CPUExecutionProvider'])
29
+ app.prepare(ctx_id=0, det_size=(640, 640))
30
+ return app
31
+
32
+ face_app = load_ai_engine()
33
+
34
+ def get_face_db():
35
+ if os.path.exists(DB_FILE):
36
+ try:
37
+ with open(DB_FILE, 'rb') as f:
38
+ return pickle.load(f)
39
+ except:
40
+ return {}
41
+ return {}
42
+
43
+ st.subheader("Hệ Thống Điểm Danh Sinh Viên")
44
+
45
+ if 'live_attendance' not in st.session_state:
46
+ st.session_state.live_attendance = {}
47
+
48
+ class MultiFaceProcessor(VideoProcessorBase):
49
+ def __init__(self):
50
+ self.face_db = get_face_db()
51
+ self.local_log = {}
52
+
53
+ def recv(self, frame):
54
+ img = frame.to_ndarray(format="bgr24")
55
+ faces = face_app.get(img)
56
+
57
+ for face in faces:
58
+ bbox = face.bbox.astype(int)
59
+ best_match = "Unknown"
60
+ max_sim = 0.55
61
+
62
+ # So sánh với database trong bộ nhớ
63
+ for db_name, db_emb in self.face_db.items():
64
+ sim = np.dot(db_emb, face.embedding) / (np.linalg.norm(db_emb) * np.linalg.norm(face.embedding))
65
+ if sim > max_sim:
66
+ max_sim = sim
67
+ best_match = db_name
68
+
69
+ if best_match != "Unknown":
70
+ color = (0, 255, 0)
71
+ label = f"{best_match}"
72
+ self.local_log[best_match] = datetime.now().strftime("%H:%M:%S")
73
+ else:
74
+ color = (0, 0, 255)
75
+ label = "Unknown"
76
+
77
+ cv2.rectangle(img, (bbox[0], bbox[1]), (bbox[2], bbox[3]), color, 2)
78
+ cv2.putText(img, label, (bbox[0], bbox[1]-10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
79
+
80
+ return av.VideoFrame.from_ndarray(img, format="bgr24")
81
+
82
+ tab1, tab2, tab3 = st.tabs(["🔍 Quét Điểm Danh", "📝 Đăng Ký Sinh Viên", "📊 Dữ Liệu Lớp"])
83
+
84
+ with tab1:
85
+ c1, c2 = st.columns([7, 3])
86
+ with c1:
87
+ ctx = webrtc_streamer(
88
+ key="multi-face-scanner",
89
+ video_processor_factory=MultiFaceProcessor,
90
+ rtc_configuration={"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]},
91
+ media_stream_constraints={"video": True, "audio": False},
92
+ )
93
+
94
+ # --- ĐOẠN SỬA LỖI QUAN TRỌNG ---
95
+ # Cập nhật database mới nhất vào processor đang chạy mỗi khi ứng dụng rerun
96
+ if ctx.video_processor:
97
+ ctx.video_processor.face_db = get_face_db()
98
+ # ------------------------------
99
+
100
+ with c2:
101
+ st.subheader("Danh sách điểm danh")
102
+
103
+ @st.fragment(run_every=1.0)
104
+ def live_attendance_board():
105
+ db = get_face_db()
106
+
107
+ if ctx.video_processor:
108
+ for name, time_str in ctx.video_processor.local_log.items():
109
+ st.session_state.live_attendance[name] = time_str
110
+
111
+ total_students = len(db)
112
+ present_students = len(st.session_state.live_attendance)
113
+
114
+ st.write(f"Sĩ số: **{present_students}/{total_students}**")
115
+ st.progress(present_students / total_students if total_students > 0 else 0)
116
+
117
+ for student in sorted(db.keys()):
118
+ if student in st.session_state.live_attendance:
119
+ time_in = st.session_state.live_attendance[student]
120
+ st.markdown(f'<div class="status-box" style="background-color: #d4edda; color: #155724;"> {student} <span style="float:right; font-size:12px; font-weight:normal;">{time_in}</span></div>', unsafe_allow_html=True)
121
+ else:
122
+ st.markdown(f'<div class="status-box" style="background-color: #f8d7da; color: #721c24;"> {student} <span style="float:right; font-size:12px; font-weight:normal;">Vắng</span></div>', unsafe_allow_html=True)
123
+
124
+ live_attendance_board()
125
+
126
+ with tab2:
127
+ col_cam, col_info = st.columns([6, 3])
128
+ with col_cam:
129
+ img_file = st.camera_input("Chụp ảnh khuôn mặt để đăng ký")
130
+ with col_info:
131
+ st.subheader("Thêm Sinh Viên Mới")
132
+ name = st.text_input("Nhập Họ tên Sinh viên:")
133
+ if st.button("Lưu Sinh Viên") and name and img_file:
134
+ img_cv = np.array(Image.open(img_file).convert('RGB'))[:, :, ::-1]
135
+ res = face_app.get(img_cv)
136
+
137
+ if len(res) == 1:
138
+ db = get_face_db()
139
+ db[name] = res[0].embedding
140
+ with open(DB_FILE, 'wb') as f:
141
+ pickle.dump(db, f)
142
+ st.success(f"Đã đăng ký thành công: {name}")
143
+ # Rerun để Tab 1 nhận diện được ngay lập tức
144
+ st.rerun()
145
+ elif len(res) == 0:
146
+ st.error("Không tìm thấy khuôn mặt! Hãy chụp lại.")
147
+ else:
148
+ st.error("Có quá nhiều mặt trong ảnh! Yêu cầu chỉ 1 người.")
149
+
150
+ with tab3:
151
+ st.subheader("Quản trị hệ thống")
152
+ if st.button("XÓA DỮ LIỆU ĐIỂM DANH HÔM NAY"):
153
+ st.session_state.live_attendance = {}
154
+ if ctx.video_processor:
155
+ ctx.video_processor.local_log = {}
156
+ st.success("Đã reset danh sách điểm danh!")
157
+ st.rerun()
158
+
159
+ if st.button("XÓA TOÀN BỘ DATABASE SINH VIÊN", type="primary"):
160
+ if os.path.exists(DB_FILE):
161
+ os.remove(DB_FILE)
162
+ st.session_state.clear()
163
+ st.success("Đã xóa toàn bộ dữ liệu lớp!")
164
+ st.rerun()
collect_data.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import os
3
+ import time
4
+
5
+ # 1. Định nghĩa đường dẫn lưu ảnh
6
+ REAL_PATH = 'dataset/train/real'
7
+ FAKE_PATH = 'dataset/train/fake'
8
+
9
+ # 2. Khởi tạo webcam (0 là camera mặc định của laptop)
10
+ cap = cv2.VideoCapture(0)
11
+
12
+ def capture_images(label_path, num_images=100):
13
+ print(f"\n[INFO] Đang chuẩn bị chụp {num_images} ảnh...")
14
+ time.sleep(2) # Dừng 2 giây để em chuẩn bị tư thế
15
+
16
+ count = 0
17
+ while count < num_images:
18
+ ret, frame = cap.read()
19
+ if not ret:
20
+ break
21
+
22
+ # Lưu ảnh với tên chứa timestamp để không bị trùng
23
+ img_name = os.path.join(label_path, f"img_{int(time.time() * 1000)}_{count}.jpg")
24
+ cv2.imwrite(img_name, frame)
25
+ count += 1
26
+
27
+ # Hiển thị thông báo lên màn hình
28
+ cv2.putText(frame, f"Dang chup: {count}/{num_images}", (50, 50),
29
+ cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
30
+ cv2.imshow('Thu thap Dataset', frame)
31
+ cv2.waitKey(50) # Tốc độ chụp: 0.05 giây / ảnh
32
+
33
+ print("[INFO] Đã chụp xong!")
34
+
35
+ # 3. Vòng lặp chính điều khiển bằng bàn phím
36
+ print("=== HƯỚNG DẪN SỬ DỤNG ===")
37
+ print("- Nhấn phím 'r' để chụp mặt THẬT (Real).")
38
+ print("- Nhấn phím 'f' để chụp mặt GIẢ (Fake).")
39
+ print("- Nhấn phím 'q' để THOÁT.")
40
+
41
+ while True:
42
+ ret, frame = cap.read()
43
+ if not ret:
44
+ print("[LỖI] Không thể kết nối với webcam.")
45
+ break
46
+
47
+ cv2.putText(frame, "Nhan: 'r' (That), 'f' (Gia), 'q' (Thoat)", (10, 30),
48
+ cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 0, 0), 2)
49
+ cv2.imshow('Thu thap Dataset', frame)
50
+
51
+ key = cv2.waitKey(1) & 0xFF
52
+
53
+ if key == ord('r'):
54
+ # Chụp mặt thật: Em cứ ngồi bình thường, hơi xoay đầu nhẹ
55
+ capture_images(REAL_PATH, 100)
56
+ elif key == ord('f'):
57
+ # Chụp mặt giả: Lấy điện thoại mở ảnh 1 khuôn mặt, giơ lên trước camera
58
+ capture_images(FAKE_PATH, 100)
59
+ elif key == ord('q'):
60
+ break
61
+
62
+ cap.release()
63
+ cv2.destroyAllWindows()
face_db.pkl ADDED
Binary file (2.21 kB). View file
 
main.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import torch
3
+ import torch.nn as nn
4
+ import numpy as np
5
+ from torchvision import models, transforms
6
+ from insightface.app import FaceAnalysis
7
+
8
+ # ==========================================
9
+ # 1. KHỞI TẠO VÀ TẢI CÁC MÔ HÌNH AI
10
+ # ==========================================
11
+ print("[INFO] Đang khởi tạo hệ thống AI...")
12
+
13
+ # 1.1 Tải mô hình Anti-Spoofing (PyTorch)
14
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
15
+ liveness_model = models.mobilenet_v2()
16
+ num_ftrs = liveness_model.classifier[1].in_features
17
+ liveness_model.classifier[1] = nn.Linear(num_ftrs, 2) # 2 lớp: 0 (Fake), 1 (Real)
18
+ liveness_model.load_state_dict(torch.load('models/anti_spoofing_model.pth', map_location=device))
19
+ liveness_model = liveness_model.to(device)
20
+ liveness_model.eval() # Đặt ở chế độ suy luận (không train nữa)
21
+
22
+ # Bộ tiền xử lý ảnh cho Anti-Spoofing
23
+ preprocess = transforms.Compose([
24
+ transforms.ToPILImage(),
25
+ transforms.Resize((224, 224)),
26
+ transforms.ToTensor(),
27
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
28
+ ])
29
+
30
+ # 1.2 Tải mô hình Nhận diện khuôn mặt (InsightFace)
31
+ # Dùng bộ 'buffalo_l' siêu chuẩn
32
+ app = FaceAnalysis(name='buffalo_l', root='./models', providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
33
+ app.prepare(ctx_id=0, det_size=(640, 640))
34
+
35
+ # ==========================================
36
+ # 2. ĐĂNG KÝ KHUÔN MẶT GỐC (DATABASE)
37
+ # ==========================================
38
+ print("[INFO] Đang đọc khuôn mặt gốc...")
39
+ base_img = cv2.imread('my_face.jpg')
40
+ if base_img is None:
41
+ print("[LỖI] Không tìm thấy file 'my_face.jpg'. Vui lòng thêm ảnh vào thư mục!")
42
+ exit()
43
+
44
+ faces_base = app.get(base_img)
45
+ if len(faces_base) == 0:
46
+ print("[LỖI] Không tìm thấy khuôn mặt nào trong ảnh gốc!")
47
+ exit()
48
+ base_embedding = faces_base[0].embedding # Vector 512 chiều của khuôn mặt gốc
49
+
50
+ # Hàm so sánh 2 khuôn mặt
51
+ def compare_faces(emb1, emb2, threshold=0.45):
52
+ sim = np.dot(emb1, emb2) / (np.linalg.norm(emb1) * np.linalg.norm(emb2))
53
+ return sim >= threshold, sim
54
+
55
+ # ==========================================
56
+ # 3. CHẠY WEBCAM VÀ XỬ LÝ THEO THỜI GIAN THỰC
57
+ # ==========================================
58
+ print("[INFO] Bắt đầu quét điểm danh. Nhấn 'q' để thoát.")
59
+ cap = cv2.VideoCapture(0)
60
+
61
+ while True:
62
+ ret, frame = cap.read()
63
+ if not ret:
64
+ break
65
+
66
+ # Bước 1: Phát hiện khuôn mặt
67
+ faces = app.get(frame)
68
+
69
+ for face in faces:
70
+ # Lấy tọa độ khung khuôn mặt (Bounding Box)
71
+ bbox = face.bbox.astype(int)
72
+ x1, y1, x2, y2 = bbox
73
+
74
+ # Đảm bảo tọa độ không vượt quá kích thước ảnh
75
+ x1, y1 = max(0, x1), max(0, y1)
76
+ x2, y2 = min(frame.shape[1], x2), min(frame.shape[0], y2)
77
+
78
+ # Cắt khuôn mặt ra để kiểm tra
79
+ face_crop = frame[y1:y2, x1:x2]
80
+ if face_crop.shape[0] == 0 or face_crop.shape[1] == 0:
81
+ continue
82
+
83
+ # Bước 2: Kiểm tra Thực thể (Anti-Spoofing)
84
+ input_tensor = preprocess(face_crop).unsqueeze(0).to(device)
85
+ with torch.no_grad():
86
+ output = liveness_model(input_tensor)
87
+ _, pred = torch.max(output, 1)
88
+ is_real = (pred.item() == 1)
89
+
90
+ if not is_real:
91
+ # Nếu là FAKE: Cảnh báo đỏ, không nhận diện
92
+ cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 0, 255), 2)
93
+ cv2.putText(frame, "FAKE - Canh Bao!", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
94
+ else:
95
+ # Bước 3: Nếu là REAL, tiến hành Nhận diện
96
+ current_embedding = face.embedding
97
+ match, score = compare_faces(base_embedding, current_embedding)
98
+
99
+ if match:
100
+ # Trùng khớp: Xanh lá
101
+ cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
102
+ cv2.putText(frame, f"Sy (Real) - {score:.2f}", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
103
+ else:
104
+ # Người lạ nhưng là thật: Vàng
105
+ cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 255), 2)
106
+ cv2.putText(frame, f"Unknown (Real)", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 2)
107
+
108
+ # Hiển thị kết quả lên màn hình
109
+ cv2.imshow("He Thong Diem Danh AI", frame)
110
+ if cv2.waitKey(1) & 0xFF == ord('q'):
111
+ break
112
+
113
+ cap.release()
114
+ cv2.destroyAllWindows()
my_face.jpg ADDED
recognizer.py ADDED
File without changes
requirements.txt CHANGED
@@ -1,3 +1,12 @@
1
- altair
2
- pandas
3
- streamlit
 
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ streamlit-webrtc
3
+ av
4
+ opencv-python
5
+ numpy
6
+ insightface
7
+ onnxruntime-gpu
8
+ torch
9
+ torchvision
10
+ Pillow
11
+ pandas
12
+ gdown
train_antispoof.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.optim as optim
4
+ from torchvision import datasets, models, transforms
5
+ from torch.utils.data import DataLoader
6
+ import os
7
+
8
+ # 1. Cấu hình thiết bị (Ưu tiên dùng Card đồ họa)
9
+ device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
10
+ print(f"[INFO] Đang sử dụng thiết bị tính toán: {device}")
11
+
12
+ # 2. Chuẩn bị và làm phong phú dữ liệu (Data Augmentation)
13
+ # Giúp AI học tốt hơn bằng cách tự động lật ảnh, thay đổi kích thước cho chuẩn
14
+ data_transforms = transforms.Compose([
15
+ transforms.Resize((224, 224)),
16
+ transforms.RandomHorizontalFlip(),
17
+ transforms.ToTensor(),
18
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
19
+ ])
20
+
21
+ # Load dữ liệu từ thư mục
22
+ data_dir = 'dataset/train'
23
+ image_dataset = datasets.ImageFolder(data_dir, data_transforms)
24
+ dataloader = DataLoader(image_dataset, batch_size=16, shuffle=True)
25
+
26
+ # In ra các nhãn để kiểm tra (thường sẽ là {'fake': 0, 'real': 1})
27
+ print(f"[INFO] Các nhãn đã nhận diện: {image_dataset.class_to_idx}")
28
+
29
+ # 3. Khởi tạo Mô hình AI (MobileNetV2)
30
+ print("[INFO] Đang tải cấu trúc mạng MobileNetV2...")
31
+ model = models.mobilenet_v2(weights=models.MobileNet_V2_Weights.DEFAULT)
32
+
33
+ # Thay đổi lớp cuối cùng để chỉ phân loại 2 lớp: Fake và Real
34
+ num_ftrs = model.classifier[1].in_features
35
+ model.classifier[1] = nn.Linear(num_ftrs, 2)
36
+ model = model.to(device) # Đẩy model lên GPU
37
+
38
+ # 4. Định nghĩa hàm tính sai số (Loss) và bộ tối ưu hóa (Optimizer)
39
+ criterion = nn.CrossEntropyLoss()
40
+ optimizer = optim.Adam(model.parameters(), lr=0.001)
41
+
42
+ # 5. Vòng lặp Huấn luyện (Training Loop)
43
+ num_epochs = 10 # Cho AI học đi học lại 10 lần qua toàn bộ dữ liệu
44
+
45
+ print("[INFO] Bắt đầu quá trình huấn luyện...")
46
+ for epoch in range(num_epochs):
47
+ model.train() # Đặt mô hình ở chế độ huấn luyện
48
+ running_loss = 0.0
49
+ corrects = 0
50
+
51
+ for inputs, labels in dataloader:
52
+ inputs = inputs.to(device)
53
+ labels = labels.to(device)
54
+
55
+ optimizer.zero_grad() # Xóa bộ nhớ đệm
56
+
57
+ # Lan truyền tiến (Đưa ảnh qua mạng AI)
58
+ outputs = model(inputs)
59
+ _, preds = torch.max(outputs, 1)
60
+ loss = criterion(outputs, labels)
61
+
62
+ # Lan truyền ngược (Cập nhật trọng số để AI thông minh hơn)
63
+ loss.backward()
64
+ optimizer.step()
65
+
66
+ running_loss += loss.item() * inputs.size(0)
67
+ corrects += torch.sum(preds == labels.data)
68
+
69
+ epoch_loss = running_loss / len(image_dataset)
70
+ epoch_acc = corrects.double() / len(image_dataset)
71
+
72
+ print(f"Vòng lặp (Epoch) {epoch+1}/{num_epochs} | Sai số (Loss): {epoch_loss:.4f} | Độ chính xác (Acc): {epoch_acc:.4f}")
73
+
74
+ # 6. Lưu lại "bộ não" đã được huấn luyện
75
+ os.makedirs('models', exist_ok=True)
76
+ save_path = 'models/anti_spoofing_model.pth'
77
+ torch.save(model.state_dict(), save_path)
78
+ print(f"[INFO] Huấn luyện hoàn tất! Mô hình đã được lưu tại: {save_path}")