Upload app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 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
|
|
@@ -9,8 +9,10 @@ import os
|
|
| 9 |
import pickle
|
| 10 |
from PIL import Image
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
|
|
|
|
|
|
|
| 14 |
st.markdown("""
|
| 15 |
<style>
|
| 16 |
.block-container { padding-top: 1rem !important; }
|
|
@@ -24,7 +26,6 @@ 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
|
|
@@ -34,17 +35,16 @@ face_app = load_ai_engine()
|
|
| 34 |
def get_face_db():
|
| 35 |
if os.path.exists(DB_FILE):
|
| 36 |
try:
|
| 37 |
-
with open(DB_FILE, 'rb') as f:
|
| 38 |
-
|
| 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()
|
|
@@ -59,7 +59,6 @@ class MultiFaceProcessor(VideoProcessorBase):
|
|
| 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:
|
|
@@ -79,7 +78,10 @@ class MultiFaceProcessor(VideoProcessorBase):
|
|
| 79 |
|
| 80 |
return av.VideoFrame.from_ndarray(img, format="bgr24")
|
| 81 |
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
with tab1:
|
| 85 |
c1, c2 = st.columns([7, 3])
|
|
@@ -87,46 +89,48 @@ with tab1:
|
|
| 87 |
ctx = webrtc_streamer(
|
| 88 |
key="multi-face-scanner",
|
| 89 |
video_processor_factory=MultiFaceProcessor,
|
| 90 |
-
rtc_configuration={
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 104 |
-
|
| 105 |
-
|
| 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 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 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:")
|
|
@@ -137,28 +141,21 @@ with tab2:
|
|
| 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 |
-
|
| 142 |
-
st.
|
| 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!
|
| 147 |
else:
|
| 148 |
-
st.error("
|
| 149 |
|
| 150 |
with tab3:
|
| 151 |
st.subheader("Quản trị hệ thống")
|
| 152 |
-
if st.button("XÓA
|
| 153 |
st.session_state.live_attendance = {}
|
| 154 |
-
if ctx.video_processor:
|
| 155 |
-
|
| 156 |
-
st.success("Đã reset danh sách điểm danh!")
|
| 157 |
-
st.rerun()
|
| 158 |
|
| 159 |
-
if st.button("XÓA TOÀN BỘ DATABASE
|
| 160 |
-
if os.path.exists(DB_FILE):
|
| 161 |
-
|
| 162 |
-
st.session_state.clear()
|
| 163 |
-
st.success("Đã xóa toàn bộ dữ liệu lớp!")
|
| 164 |
-
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
|
|
|
|
| 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="AI Attendance - Vo Van Sy", layout="wide")
|
| 16 |
st.markdown("""
|
| 17 |
<style>
|
| 18 |
.block-container { padding-top: 1rem !important; }
|
|
|
|
| 26 |
|
| 27 |
@st.cache_resource
|
| 28 |
def load_ai_engine():
|
|
|
|
| 29 |
app = FaceAnalysis(name='buffalo_sc', root='./models', providers=['CPUExecutionProvider'])
|
| 30 |
app.prepare(ctx_id=0, det_size=(640, 640))
|
| 31 |
return app
|
|
|
|
| 35 |
def get_face_db():
|
| 36 |
if os.path.exists(DB_FILE):
|
| 37 |
try:
|
| 38 |
+
with open(DB_FILE, 'rb') as f: return pickle.load(f)
|
| 39 |
+
except: return {}
|
|
|
|
|
|
|
| 40 |
return {}
|
| 41 |
|
|
|
|
|
|
|
| 42 |
if 'live_attendance' not in st.session_state:
|
| 43 |
st.session_state.live_attendance = {}
|
| 44 |
|
| 45 |
+
# ==========================================
|
| 46 |
+
# 2. LỚP XỬ LÝ VIDEO TRỰC TUYẾN
|
| 47 |
+
# ==========================================
|
| 48 |
class MultiFaceProcessor(VideoProcessorBase):
|
| 49 |
def __init__(self):
|
| 50 |
self.face_db = get_face_db()
|
|
|
|
| 59 |
best_match = "Unknown"
|
| 60 |
max_sim = 0.55
|
| 61 |
|
|
|
|
| 62 |
for db_name, db_emb in self.face_db.items():
|
| 63 |
sim = np.dot(db_emb, face.embedding) / (np.linalg.norm(db_emb) * np.linalg.norm(face.embedding))
|
| 64 |
if sim > max_sim:
|
|
|
|
| 78 |
|
| 79 |
return av.VideoFrame.from_ndarray(img, format="bgr24")
|
| 80 |
|
| 81 |
+
# ==========================================
|
| 82 |
+
# 3. GIAO DIỆN TABS
|
| 83 |
+
# ==========================================
|
| 84 |
+
tab1, tab2, tab3 = st.tabs(["Quét Điểm Danh", "Đăng Ký Sinh Viên", "Dữ Liệu Lớp"])
|
| 85 |
|
| 86 |
with tab1:
|
| 87 |
c1, c2 = st.columns([7, 3])
|
|
|
|
| 89 |
ctx = webrtc_streamer(
|
| 90 |
key="multi-face-scanner",
|
| 91 |
video_processor_factory=MultiFaceProcessor,
|
| 92 |
+
rtc_configuration={
|
| 93 |
+
"iceServers": [
|
| 94 |
+
{"urls": ["stun:stun.l.google.com:19302"]},
|
| 95 |
+
{"urls": ["stun:stun1.l.google.com:19302"]},
|
| 96 |
+
{"urls": ["stun:stun2.l.google.com:19302"]},
|
| 97 |
+
{"urls": ["stun:stun.services.mozilla.com"]}
|
| 98 |
+
]
|
| 99 |
+
},
|
| 100 |
media_stream_constraints={"video": True, "audio": False},
|
| 101 |
)
|
| 102 |
|
|
|
|
|
|
|
| 103 |
if ctx.video_processor:
|
| 104 |
ctx.video_processor.face_db = get_face_db()
|
|
|
|
| 105 |
|
| 106 |
with c2:
|
| 107 |
st.subheader("Danh sách điểm danh")
|
| 108 |
|
| 109 |
+
# Nút bấm thủ công giúp App chạy mượt mà, không bị crash camera
|
| 110 |
+
if st.button("🔄 LÀM MỚI DANH SÁCH"):
|
| 111 |
+
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
+
db = get_face_db()
|
| 114 |
+
if ctx.video_processor:
|
| 115 |
+
for name, time_str in ctx.video_processor.local_log.items():
|
| 116 |
+
st.session_state.live_attendance[name] = time_str
|
| 117 |
+
|
| 118 |
+
total = len(db)
|
| 119 |
+
present = len(st.session_state.live_attendance)
|
| 120 |
+
st.write(f"Sĩ số: **{present}/{total}**")
|
| 121 |
+
st.progress(present / total if total > 0 else 0)
|
| 122 |
+
|
| 123 |
+
for student in sorted(db.keys()):
|
| 124 |
+
if student in st.session_state.live_attendance:
|
| 125 |
+
time_in = st.session_state.live_attendance[student]
|
| 126 |
+
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)
|
| 127 |
+
else:
|
| 128 |
+
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)
|
| 129 |
|
| 130 |
with tab2:
|
| 131 |
col_cam, col_info = st.columns([6, 3])
|
| 132 |
with col_cam:
|
| 133 |
+
img_file = st.camera_input("Chụp ảnh khuôn mặt")
|
| 134 |
with col_info:
|
| 135 |
st.subheader("Thêm Sinh Viên Mới")
|
| 136 |
name = st.text_input("Nhập Họ tên Sinh viên:")
|
|
|
|
| 141 |
if len(res) == 1:
|
| 142 |
db = get_face_db()
|
| 143 |
db[name] = res[0].embedding
|
| 144 |
+
with open(DB_FILE, 'wb') as f: pickle.dump(db, f)
|
| 145 |
+
st.success(f"Đã cập nhật: {name}")
|
| 146 |
+
st.rerun()
|
|
|
|
|
|
|
| 147 |
elif len(res) == 0:
|
| 148 |
+
st.error("Không tìm thấy khuôn mặt!")
|
| 149 |
else:
|
| 150 |
+
st.error("Yêu cầu chỉ 1 người trong khung hình.")
|
| 151 |
|
| 152 |
with tab3:
|
| 153 |
st.subheader("Quản trị hệ thống")
|
| 154 |
+
if st.button("XÓA DANH SÁCH ĐIỂM DANH"):
|
| 155 |
st.session_state.live_attendance = {}
|
| 156 |
+
if ctx.video_processor: ctx.video_processor.local_log = {}
|
| 157 |
+
st.success("Đã reset!"); st.rerun()
|
|
|
|
|
|
|
| 158 |
|
| 159 |
+
if st.button("XÓA TOÀN BỘ DATABASE", type="primary"):
|
| 160 |
+
if os.path.exists(DB_FILE): os.remove(DB_FILE)
|
| 161 |
+
st.session_state.clear(); st.rerun()
|
|
|
|
|
|
|
|
|