vanv123 commited on
Commit
060b711
·
verified ·
1 Parent(s): 10848a9

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -44
app.py CHANGED
@@ -1,5 +1,5 @@
1
  import streamlit as st
2
- from streamlit_webrtc import webrtc_streamer, VideoProcessorBase, WebRtcMode
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
- # Cấu hình trang
13
- st.set_page_config(page_title="Hệ thống điểm danh AI - STU", layout="wide")
 
 
14
  st.markdown("""
15
  <style>
16
  .block-container { padding-top: 1rem !important; }
@@ -24,7 +26,7 @@ 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 +36,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
- return pickle.load(f)
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 +60,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,23 +79,32 @@ class MultiFaceProcessor(VideoProcessorBase):
79
 
80
  return av.VideoFrame.from_ndarray(img, format="bgr24")
81
 
82
- tab1, tab2, tab3 = st.tabs(["🔍 Quét Điểm Danh", "📝 Đăng Ký Sinh Viên", "📊 Dữ Liệu Lớp"])
 
 
 
83
 
84
  with tab1:
85
  c1, c2 = st.columns([7, 3])
86
  with c1:
 
87
  ctx = webrtc_streamer(
88
  key="multi-face-scanner",
89
  video_processor_factory=MultiFaceProcessor,
90
- rtc_configuration={"iceServers": [{"urls": ["stun:stun.l.google.com:19302"]}]},
 
 
 
 
 
 
 
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")
@@ -103,30 +112,27 @@ with tab1:
103
  @st.fragment(run_every=1.0)
104
  def live_attendance_board():
105
  db = get_face_db()
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
  for student in sorted(db.keys()):
118
  if student in st.session_state.live_attendance:
119
  time_in = st.session_state.live_attendance[student]
120
- st.markdown(f'<div class="status-box" style="background-color: #d4edda; color: #155724;"> {student} <span style="float:right; font-size:12px; font-weight:normal;">{time_in}</span></div>', unsafe_allow_html=True)
121
  else:
122
- st.markdown(f'<div class="status-box" style="background-color: #f8d7da; color: #721c24;"> {student} <span style="float:right; font-size:12px; font-weight:normal;">Vắng</span></div>', unsafe_allow_html=True)
123
-
124
  live_attendance_board()
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 để đăng ký")
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 +143,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
- pickle.dump(db, f)
142
- st.success(f"Đã đăng ký thành công: {name}")
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! Hãy chụp lại.")
147
  else:
148
- st.error("Có quá nhiều mặt trong ảnh! Yêu cầu chỉ 1 người.")
149
 
150
  with tab3:
151
  st.subheader("Quản trị hệ thống")
152
- if st.button("XÓA DỮ LIỆU ĐIỂM DANH HÔM NAY"):
153
  st.session_state.live_attendance = {}
154
- if ctx.video_processor:
155
- ctx.video_processor.local_log = {}
156
- st.success("Đã reset danh sách điểm danh!")
157
- st.rerun()
158
 
159
- if st.button("XÓA TOÀN BỘ DATABASE SINH VIÊN", type="primary"):
160
- if os.path.exists(DB_FILE):
161
- os.remove(DB_FILE)
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
+ # Đọ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
 
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()
 
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:
 
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ập nhật nhiều STUN servers để tránh lỗi Timeout
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
+ # Đồng bộ dữ liệu mới đăng ký vào luồng camera đang chạy
 
106
  if ctx.video_processor:
107
  ctx.video_processor.face_db = get_face_db()
 
108
 
109
  with c2:
110
  st.subheader("Danh sách điểm danh")
 
112
  @st.fragment(run_every=1.0)
113
  def live_attendance_board():
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
  live_attendance_board()
131
 
132
  with tab2:
133
  col_cam, col_info = st.columns([6, 3])
134
  with col_cam:
135
+ img_file = st.camera_input("Chụp ảnh khuôn mặt")
136
  with col_info:
137
  st.subheader("Thêm Sinh Viên Mới")
138
  name = st.text_input("Nhập Họ tên Sinh viên:")
 
143
  if len(res) == 1:
144
  db = get_face_db()
145
  db[name] = res[0].embedding
146
+ with open(DB_FILE, 'wb') as f: pickle.dump(db, f)
147
+ st.success(f"Đã cập nhật: {name}")
148
+ st.rerun()
 
 
149
  elif len(res) == 0:
150
+ st.error("Không tìm thấy khuôn mặt!")
151
  else:
152
+ st.error("Yêu cầu chỉ 1 người trong khung hình.")
153
 
154
  with tab3:
155
  st.subheader("Quản trị hệ thống")
156
+ if st.button("XÓA DANH SÁCH ĐIỂM DANH"):
157
  st.session_state.live_attendance = {}
158
+ if ctx.video_processor: ctx.video_processor.local_log = {}
159
+ st.success("Đã reset!"); st.rerun()
 
 
160
 
161
+ if st.button("XÓA TOÀN BỘ DATABASE", type="primary"):
162
+ if os.path.exists(DB_FILE): os.remove(DB_FILE)
163
+ st.session_state.clear(); st.rerun()