File size: 6,102 Bytes
02f1d3b 6a6b87d 02f1d3b 6a6b87d 02f1d3b 6a6b87d 02f1d3b 19e011f 6a6b87d 19e011f 02f1d3b 6a6b87d 02f1d3b 6a6b87d | 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 | import streamlit as st
from streamlit_webrtc import webrtc_streamer, VideoProcessorBase
import cv2
import numpy as np
from insightface.app import FaceAnalysis
import av
from datetime import datetime
import os
import pickle
from PIL import Image
# ==========================================
# 1. CẤU HÌNH GIAO DIỆN VÀ AI ENGINE
# ==========================================
st.set_page_config(page_title="Hệ Thống Điểm Danh AI - Vo Van Sy", layout="wide")
st.markdown("""
<style>
.block-container { padding-top: 1rem !important; }
[data-testid="stVideo"], [data-testid="stCameraInput"] { border-radius: 10px; border: 3px solid #2e2e2e; }
.stButton>button { border-radius: 8px; font-weight: bold; width: 100%; }
.status-box { padding: 10px; border-radius: 8px; margin-bottom: 5px; font-weight: bold;}
</style>
""", unsafe_allow_html=True)
DB_FILE = "face_db.pkl"
@st.cache_resource
def load_ai_engine():
# Đọc mô hình trực tiếp từ thư mục models đã upload
app = FaceAnalysis(name='buffalo_sc', root='./models', providers=['CPUExecutionProvider'])
app.prepare(ctx_id=0, det_size=(640, 640))
return app
face_app = load_ai_engine()
def get_face_db():
if os.path.exists(DB_FILE):
try:
with open(DB_FILE, 'rb') as f: return pickle.load(f)
except: return {}
return {}
if 'live_attendance' not in st.session_state:
st.session_state.live_attendance = {}
# ==========================================
# 2. LỚP XỬ LÝ VIDEO TRỰC TUYẾN
# ==========================================
class MultiFaceProcessor(VideoProcessorBase):
def __init__(self):
self.face_db = get_face_db()
self.local_log = {}
def recv(self, frame):
img = frame.to_ndarray(format="bgr24")
faces = face_app.get(img)
for face in faces:
bbox = face.bbox.astype(int)
best_match = "Unknown"
max_sim = 0.55
for db_name, db_emb in self.face_db.items():
sim = np.dot(db_emb, face.embedding) / (np.linalg.norm(db_emb) * np.linalg.norm(face.embedding))
if sim > max_sim:
max_sim = sim
best_match = db_name
if best_match != "Unknown":
color = (0, 255, 0)
label = f"{best_match}"
self.local_log[best_match] = datetime.now().strftime("%H:%M:%S")
else:
color = (0, 0, 255)
label = "Unknown"
cv2.rectangle(img, (bbox[0], bbox[1]), (bbox[2], bbox[3]), color, 2)
cv2.putText(img, label, (bbox[0], bbox[1]-10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
return av.VideoFrame.from_ndarray(img, format="bgr24")
# ==========================================
# 3. GIAO DIỆN TABS
# ==========================================
tab1, tab2, tab3 = st.tabs(["Quét Điểm Danh", "Đăng Ký Sinh Viên", "Dữ Liệu Lớp"])
with tab1:
c1, c2 = st.columns([7, 3])
with c1:
# Cấu hình TURN Server đục tường lửa từ tài khoản Metered của bạn
ctx = webrtc_streamer(
key="multi-face-scanner",
video_processor_factory=MultiFaceProcessor,
rtc_configuration={
"iceServers": [
{"urls": ["stun:stun.l.google.com:19302"]},
{
"urls": ["turn:vovansy-turn.metered.live:80", "turn:vovansy-turn.metered.live:443"],
"username": "662b60daad0aa933efe44472",
"credential": "FA4w+gPK7n7yCVAP"
}
]
},
media_stream_constraints={
"video": {"width": {"ideal": 640}, "height": {"ideal": 480}},
"audio": False
},
)
if ctx.video_processor:
ctx.video_processor.face_db = get_face_db()
with c2:
st.subheader("Danh sách điểm danh")
st.button("🔄 LÀM MỚI DANH SÁCH")
db = get_face_db()
if ctx.video_processor:
for name, time_str in ctx.video_processor.local_log.items():
st.session_state.live_attendance[name] = time_str
total = len(db)
present = len(st.session_state.live_attendance)
st.write(f"Sĩ số: **{present}/{total}**")
st.progress(present / total if total > 0 else 0)
for student in sorted(db.keys()):
if student in st.session_state.live_attendance:
time_in = st.session_state.live_attendance[student]
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)
else:
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)
with tab2:
col_cam, col_info = st.columns([6, 3])
with col_cam:
img_file = st.camera_input("Chụp ảnh khuôn mặt")
with col_info:
st.subheader("Thêm Sinh Viên Mới")
name = st.text_input("Nhập Họ tên Sinh viên:")
if st.button("Lưu Sinh Viên") and name and img_file:
img_cv = np.array(Image.open(img_file).convert('RGB'))[:, :, ::-1]
res = face_app.get(img_cv)
if len(res) == 1:
db = get_face_db()
db[name] = res[0].embedding
with open(DB_FILE, 'wb') as f: pickle.dump(db, f)
st.success(f"Đã cập nhật: {name}")
st.rerun()
else:
st.error("Vui lòng chỉ để 1 khuôn mặt trong khung hình.")
with tab3:
st.subheader("Quản trị hệ thống")
if st.button("XÓA DANH SÁCH ĐIỂM DANH"):
st.session_state.live_attendance = {}
st.success("Đã reset!"); st.rerun() |