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(""" """, 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'
{student} {time_in}
', unsafe_allow_html=True) else: st.markdown(f'
{student} Vắng
', 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()