Update app.py
Browse files
app.py
CHANGED
|
@@ -1,161 +1,162 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
-
from streamlit_webrtc import webrtc_streamer, VideoProcessorBase
|
| 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 |
-
# ==========================================
|
| 13 |
-
# 1. CẤU HÌNH GIAO DIỆN VÀ AI ENGINE
|
| 14 |
-
# ==========================================
|
| 15 |
-
st.set_page_config(page_title="
|
| 16 |
-
st.markdown("""
|
| 17 |
-
<style>
|
| 18 |
-
.block-container { padding-top: 1rem !important; }
|
| 19 |
-
[data-testid="stVideo"], [data-testid="stCameraInput"] { border-radius: 10px; border: 3px solid #2e2e2e; }
|
| 20 |
-
.stButton>button { border-radius: 8px; font-weight: bold; width: 100%; }
|
| 21 |
-
.status-box { padding: 10px; border-radius: 8px; margin-bottom: 5px; font-weight: bold;}
|
| 22 |
-
</style>
|
| 23 |
-
""", unsafe_allow_html=True)
|
| 24 |
-
|
| 25 |
-
DB_FILE = "face_db.pkl"
|
| 26 |
-
|
| 27 |
-
@st.cache_resource
|
| 28 |
-
def load_ai_engine():
|
| 29 |
-
|
| 30 |
-
app
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
#
|
| 47 |
-
#
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
self.
|
| 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 |
-
cv2.
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
#
|
| 83 |
-
#
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
{"urls": ["stun:
|
| 97 |
-
{"urls": ["stun:
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
st.
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
db
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
st.
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
|
|
|
| 161 |
st.session_state.clear(); st.rerun()
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from streamlit_webrtc import webrtc_streamer, VideoProcessorBase
|
| 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 |
+
# ==========================================
|
| 13 |
+
# 1. CẤU HÌNH GIAO DIỆN VÀ AI ENGINE
|
| 14 |
+
# ==========================================
|
| 15 |
+
st.set_page_config(page_title="Hệ Thống Điểm Danh AI - Vo Van Sy", layout="wide")
|
| 16 |
+
st.markdown("""
|
| 17 |
+
<style>
|
| 18 |
+
.block-container { padding-top: 1rem !important; }
|
| 19 |
+
[data-testid="stVideo"], [data-testid="stCameraInput"] { border-radius: 10px; border: 3px solid #2e2e2e; }
|
| 20 |
+
.stButton>button { border-radius: 8px; font-weight: bold; width: 100%; }
|
| 21 |
+
.status-box { padding: 10px; border-radius: 8px; margin-bottom: 5px; font-weight: bold;}
|
| 22 |
+
</style>
|
| 23 |
+
""", unsafe_allow_html=True)
|
| 24 |
+
|
| 25 |
+
DB_FILE = "face_db.pkl"
|
| 26 |
+
|
| 27 |
+
@st.cache_resource
|
| 28 |
+
def load_ai_engine():
|
| 29 |
+
# Đọc mô hình trực tiếp từ thư mục models đã upload trên Hugging Face
|
| 30 |
+
app = FaceAnalysis(name='buffalo_sc', root='./models', providers=['CPUExecutionProvider'])
|
| 31 |
+
app.prepare(ctx_id=0, det_size=(640, 640))
|
| 32 |
+
return app
|
| 33 |
+
|
| 34 |
+
face_app = load_ai_engine()
|
| 35 |
+
|
| 36 |
+
def get_face_db():
|
| 37 |
+
if os.path.exists(DB_FILE):
|
| 38 |
+
try:
|
| 39 |
+
with open(DB_FILE, 'rb') as f: return pickle.load(f)
|
| 40 |
+
except: return {}
|
| 41 |
+
return {}
|
| 42 |
+
|
| 43 |
+
if 'live_attendance' not in st.session_state:
|
| 44 |
+
st.session_state.live_attendance = {}
|
| 45 |
+
|
| 46 |
+
# ==========================================
|
| 47 |
+
# 2. LỚP XỬ LÝ VIDEO TRỰC TUYẾN
|
| 48 |
+
# ==========================================
|
| 49 |
+
class MultiFaceProcessor(VideoProcessorBase):
|
| 50 |
+
def __init__(self):
|
| 51 |
+
self.face_db = get_face_db()
|
| 52 |
+
self.local_log = {}
|
| 53 |
+
|
| 54 |
+
def recv(self, frame):
|
| 55 |
+
img = frame.to_ndarray(format="bgr24")
|
| 56 |
+
faces = face_app.get(img)
|
| 57 |
+
|
| 58 |
+
for face in faces:
|
| 59 |
+
bbox = face.bbox.astype(int)
|
| 60 |
+
best_match = "Unknown"
|
| 61 |
+
max_sim = 0.55
|
| 62 |
+
|
| 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 |
+
# ==========================================
|
| 83 |
+
# 3. GIAO DIỆN TABS
|
| 84 |
+
# ==========================================
|
| 85 |
+
tab1, tab2, tab3 = st.tabs(["Quét Điểm Danh", "Đăng Ký Sinh Viên", "Dữ Liệu Lớp"])
|
| 86 |
+
|
| 87 |
+
with tab1:
|
| 88 |
+
c1, c2 = st.columns([7, 3])
|
| 89 |
+
with c1:
|
| 90 |
+
# Cấu hình STUN server giúp xuyên tường lửa mạng nội bộ
|
| 91 |
+
ctx = webrtc_streamer(
|
| 92 |
+
key="multi-face-scanner",
|
| 93 |
+
video_processor_factory=MultiFaceProcessor,
|
| 94 |
+
rtc_configuration={
|
| 95 |
+
"iceServers": [
|
| 96 |
+
{"urls": ["stun:stun.l.google.com:19302"]},
|
| 97 |
+
{"urls": ["stun:stun1.l.google.com:19302"]},
|
| 98 |
+
{"urls": ["stun:stun2.l.google.com:19302"]},
|
| 99 |
+
{"urls": ["stun:stun.services.mozilla.com"]}
|
| 100 |
+
]
|
| 101 |
+
},
|
| 102 |
+
media_stream_constraints={"video": True, "audio": False},
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
if ctx.video_processor:
|
| 106 |
+
ctx.video_processor.face_db = get_face_db()
|
| 107 |
+
|
| 108 |
+
with c2:
|
| 109 |
+
st.subheader("Danh sách điểm danh")
|
| 110 |
+
|
| 111 |
+
# Nút bấm thủ công an toàn, tránh lỗi sập camera (is_alive error)
|
| 112 |
+
st.button("🔄 LÀM MỚI DANH SÁCH")
|
| 113 |
+
|
| 114 |
+
db = get_face_db()
|
| 115 |
+
if ctx.video_processor:
|
| 116 |
+
for name, time_str in ctx.video_processor.local_log.items():
|
| 117 |
+
st.session_state.live_attendance[name] = time_str
|
| 118 |
+
|
| 119 |
+
total = len(db)
|
| 120 |
+
present = len(st.session_state.live_attendance)
|
| 121 |
+
st.write(f"Sĩ số: **{present}/{total}**")
|
| 122 |
+
st.progress(present / total if total > 0 else 0)
|
| 123 |
+
|
| 124 |
+
for student in sorted(db.keys()):
|
| 125 |
+
if student in st.session_state.live_attendance:
|
| 126 |
+
time_in = st.session_state.live_attendance[student]
|
| 127 |
+
st.markdown(f'<div class="status-box" style="background-color: #d4edda; color: #155724;"> {student} <span style="float:right;">{time_in}</span></div>', unsafe_allow_html=True)
|
| 128 |
+
else:
|
| 129 |
+
st.markdown(f'<div class="status-box" style="background-color: #f8d7da; color: #721c24;"> {student} <span style="float:right;">Vắng</span></div>', unsafe_allow_html=True)
|
| 130 |
+
|
| 131 |
+
with tab2:
|
| 132 |
+
col_cam, col_info = st.columns([6, 3])
|
| 133 |
+
with col_cam:
|
| 134 |
+
img_file = st.camera_input("Chụp ảnh khuôn mặt")
|
| 135 |
+
with col_info:
|
| 136 |
+
st.subheader("Thêm Sinh Viên Mới")
|
| 137 |
+
name = st.text_input("Nhập Họ tên Sinh viên:")
|
| 138 |
+
if st.button("Lưu Sinh Viên") and name and img_file:
|
| 139 |
+
img_cv = np.array(Image.open(img_file).convert('RGB'))[:, :, ::-1]
|
| 140 |
+
res = face_app.get(img_cv)
|
| 141 |
+
|
| 142 |
+
if len(res) == 1:
|
| 143 |
+
db = get_face_db()
|
| 144 |
+
db[name] = res[0].embedding
|
| 145 |
+
with open(DB_FILE, 'wb') as f: pickle.dump(db, f)
|
| 146 |
+
st.success(f"Đã cập nhật: {name}")
|
| 147 |
+
st.rerun()
|
| 148 |
+
elif len(res) == 0:
|
| 149 |
+
st.error("Không tìm thấy khuôn mặt!")
|
| 150 |
+
else:
|
| 151 |
+
st.error("Yêu cầu chỉ 1 người trong khung hình.")
|
| 152 |
+
|
| 153 |
+
with tab3:
|
| 154 |
+
st.subheader("Quản trị hệ thống")
|
| 155 |
+
if st.button("XÓA DANH SÁCH ĐIỂM DANH"):
|
| 156 |
+
st.session_state.live_attendance = {}
|
| 157 |
+
if ctx.video_processor: ctx.video_processor.local_log = {}
|
| 158 |
+
st.success("Đã reset!"); st.rerun()
|
| 159 |
+
|
| 160 |
+
if st.button("XÓA TOÀN BỘ DATABASE", type="primary"):
|
| 161 |
+
if os.path.exists(DB_FILE): os.remove(DB_FILE)
|
| 162 |
st.session_state.clear(); st.rerun()
|