vanv123 commited on
Commit
02f1d3b
·
verified ·
1 Parent(s): b49b139

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +161 -160
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="AI Attendance - 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
- app = FaceAnalysis(name='buffalo_sc', root='./models', providers=['CPUExecutionProvider'])
30
- app.prepare(ctx_id=0, det_size=(640, 640))
31
- return app
32
-
33
- face_app = load_ai_engine()
34
-
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()
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
- 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:
65
- max_sim = sim
66
- best_match = db_name
67
-
68
- if best_match != "Unknown":
69
- color = (0, 255, 0)
70
- label = f"{best_match}"
71
- self.local_log[best_match] = datetime.now().strftime("%H:%M:%S")
72
- else:
73
- color = (0, 0, 255)
74
- label = "Unknown"
75
-
76
- cv2.rectangle(img, (bbox[0], bbox[1]), (bbox[2], bbox[3]), color, 2)
77
- cv2.putText(img, label, (bbox[0], bbox[1]-10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2)
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])
88
- with c1:
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:")
137
- if st.button("Lưu Sinh Viên") and name and img_file:
138
- img_cv = np.array(Image.open(img_file).convert('RGB'))[:, :, ::-1]
139
- res = face_app.get(img_cv)
140
-
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()
 
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()