Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,190 +1,102 @@
|
|
1 |
-
# Transformers and its models
|
2 |
-
#import transformers
|
3 |
-
|
4 |
-
# For Image Processing
|
5 |
-
#from transformers import ViTImageProcessor
|
6 |
-
|
7 |
-
# For Model
|
8 |
-
#from transformers import ViTModel, ViTConfig, pipeline
|
9 |
-
import insightface
|
10 |
-
from insightface.app import FaceAnalysis
|
11 |
-
|
12 |
-
# For data augmentation
|
13 |
-
from torchvision import transforms, datasets
|
14 |
-
from flask import request
|
15 |
-
# For GPU
|
16 |
-
#from transformers import set_seed
|
17 |
-
#from torch.optim import AdamW
|
18 |
-
#from accelerate import Accelerator, notebook_launcher
|
19 |
-
|
20 |
-
# For Data Loaders
|
21 |
-
import datasets
|
22 |
-
from torch.utils.data import Dataset, DataLoader
|
23 |
-
|
24 |
-
# For Display
|
25 |
-
#from tqdm.notebook import tqdm
|
26 |
-
|
27 |
-
# Other Generic Libraries
|
28 |
-
import torch
|
29 |
-
from PIL import Image
|
30 |
-
import cv2
|
31 |
import os
|
|
|
|
|
|
|
32 |
import streamlit as st
|
33 |
-
import
|
|
|
|
|
34 |
from glob import glob
|
35 |
-
import
|
36 |
-
import pandas as pd
|
37 |
-
import numpy as np
|
38 |
-
#import matplotlib.pyplot as plt
|
39 |
-
from io import BytesIO
|
40 |
import torch.nn.functional as F
|
41 |
|
42 |
-
# Set the device
|
43 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
44 |
|
45 |
-
#
|
46 |
-
|
47 |
-
BATCH_SIZE = 8
|
48 |
-
|
49 |
-
# Set Paths
|
50 |
data_path = 'employees'
|
51 |
-
model_path = 'vit_pytorch_GPU_1.pt'
|
52 |
webcam_path = 'captured_image.jpg'
|
53 |
|
54 |
-
|
55 |
-
|
56 |
-
# Set Title
|
57 |
st.title("AIML-Student Attendance System")
|
58 |
-
|
59 |
-
#
|
60 |
-
image_paths =
|
61 |
-
|
62 |
-
#
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
# Define the ML model - Evaluation function
|
72 |
-
def prod_function(app, prod_path, webcam_path):
|
73 |
-
webcam_img = Image.open(webcam_path)
|
74 |
-
np_webcam = np.array(webcam_img) # Convert to NumPy array
|
75 |
-
cv2_webcam = cv2.cvtColor(np_webcam, cv2.COLOR_RGB2BGR) # Convert RGB (PIL) to BGR (OpenCV)
|
76 |
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
|
81 |
-
|
|
|
|
|
82 |
for path in prod_path:
|
83 |
img = cv2.imread(path)
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
return similarity_score #prod_preds
|
93 |
|
|
|
|
|
|
|
|
|
94 |
about_tab, app_tab = st.tabs(["About the app", "Face Recognition"])
|
95 |
-
|
96 |
with about_tab:
|
97 |
-
st.markdown(
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
## 🧠 How It Works: The AI in Action
|
109 |
-
At the core of this app is Google’s Vision Transformer (ViT) architecture, trained on the Labeled Faces in the Wild (LFW) dataset for robust, real-world face recognition.
|
110 |
-
|
111 |
-
- **Face Detection & Feature Extraction**
|
112 |
-
The model scans an employee’s face and extracts a high-dimensional representation of their unique features.
|
113 |
-
|
114 |
-
- **Identity Matching with Confidence Scoring**
|
115 |
-
The scanned features are compared to stored profiles. If the confidence score crosses a threshold, the model confirms the match and automatically marks attendance.
|
116 |
-
|
117 |
-
- **Real-Time Logging**
|
118 |
-
The app logs entry and exit times in real-time, providing live dashboards and attendance reports for HR and management.
|
119 |
-
|
120 |
-
## 🏗️ About the Architecture: Vision Transformer (ViT)
|
121 |
-
The Vision Transformer (ViT) brings the power of transformer models—originally created for language—to the world of images. Here's how it works:
|
122 |
-
|
123 |
-
- An input image is split into fixed-size non-overlapping patches.
|
124 |
-
- Each patch is flattened and embedded into a higher-dimensional space.
|
125 |
-
- These embeddings are fed into a transformer encoder, which learns complex spatial and contextual relationships across the entire image using multi-head self-attention.
|
126 |
-
- ViT’s ability to capture global dependencies enables it to outperform traditional CNNs when trained on sufficient data.
|
127 |
-
|
128 |
-
This makes it ideal for high-accuracy face recognition in dynamic, real-world environments.
|
129 |
-
|
130 |
-
## 📚 About the Dataset: Labeled Faces in the Wild (LFW)
|
131 |
-
To train the model, we used the renowned Labeled Faces in the Wild (LFW) dataset, consisting of 13,000+ facial images, 5,749 individuals, each shown in diverse lighting, angles, and backgrounds. Sourced from real-world photographs of public figures. Benchmark dataset for tasks like face verification and recognition. The diversity in LFW ensures our model is resilient to variations in appearance, making it highly reliable in real-world workplace scenarios.
|
132 |
-
|
133 |
-
## ✅ Key Features
|
134 |
-
- Fast, contactless attendance logging
|
135 |
-
- High-security identity verification
|
136 |
-
- Real-time data and analytics
|
137 |
-
- Powered by state-of-the-art Vision Transformer architecture
|
138 |
-
- Eliminates manual records, reduces fraud, enhances efficiency
|
139 |
-
|
140 |
-
## 👥 Use Cases
|
141 |
-
- Corporate Offices: Accurate time tracking and security for large workforces
|
142 |
-
- Factories & Warehouses: Contactless attendance in high-throughput environments
|
143 |
-
- Educational Institutions: Seamless student and staff attendance
|
144 |
-
- Healthcare & Public Services: Ensures hygienic, automated check-ins
|
145 |
-
|
146 |
-
## 🚀 Future Scope
|
147 |
-
Looking ahead, we aim to integrate multi-face detection for group scanning, mask-aware recognition, and cross-location synchronization for distributed teams—all while preserving data privacy and security.
|
148 |
-
""")
|
149 |
-
|
150 |
-
# Gesture recognition Tab
|
151 |
with app_tab:
|
152 |
-
# Read image from Camera
|
153 |
enable = st.checkbox("Enable camera")
|
154 |
picture = st.camera_input("Take a picture", disabled=not enable)
|
|
|
155 |
if picture is not None:
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
prediction = prod_function(app, image_paths, picture)
|
160 |
-
#prediction = torch.cat(prediction, 0).to(device)
|
161 |
-
match_idx = torch.argmax(prediction)
|
162 |
-
st.write(prediction)
|
163 |
-
st.write(image_paths)
|
164 |
-
|
165 |
-
# Display the results
|
166 |
-
if prediction[match_idx] >= 0.6:
|
167 |
-
pname = image_paths[match_idx].split('/')[-1].split('.')[0]
|
168 |
-
st.write('Welcome: ',pname)
|
169 |
-
|
170 |
-
###### upload the data to Glitch https://aimljan25f.glitch.me/adds
|
171 |
-
# # using post method
|
172 |
-
url = "https://aimljan25f.glitch.me/adds"
|
173 |
-
|
174 |
-
data = {'rno': '15','sname': pname, 'sclass': '7' }
|
175 |
-
# response = requests.post(url +url1 , data=data)
|
176 |
-
|
177 |
-
# Post Method is invoked if data != None
|
178 |
-
req = request.Request(url , method="POST", data=data)
|
179 |
-
|
180 |
-
# Response
|
181 |
-
resp = request.urlopen(req)
|
182 |
-
if response.status_code == 200:
|
183 |
-
st.success("Data updated on: " + "https://aimljan25f.glitch.me/")
|
184 |
-
else:
|
185 |
-
st.warning("Data not updated")
|
186 |
-
########## end update website
|
187 |
|
188 |
-
|
|
|
189 |
else:
|
190 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
+
import cv2
|
3 |
+
import torch
|
4 |
+
import numpy as np
|
5 |
import streamlit as st
|
6 |
+
import requests
|
7 |
+
|
8 |
+
from PIL import Image
|
9 |
from glob import glob
|
10 |
+
from insightface.app import FaceAnalysis
|
|
|
|
|
|
|
|
|
11 |
import torch.nn.functional as F
|
12 |
|
13 |
+
# Set the device
|
14 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
15 |
|
16 |
+
# Global Variables
|
17 |
+
IMAGE_SHAPE = 640
|
|
|
|
|
|
|
18 |
data_path = 'employees'
|
|
|
19 |
webcam_path = 'captured_image.jpg'
|
20 |
|
21 |
+
# Set Streamlit title
|
|
|
|
|
22 |
st.title("AIML-Student Attendance System")
|
23 |
+
|
24 |
+
# Load employee image paths
|
25 |
+
image_paths = glob(os.path.join(data_path, '*.jpg'))
|
26 |
+
|
27 |
+
# Initialize Face Analysis
|
28 |
+
app = FaceAnalysis(name="buffalo_l") # ArcFace model
|
29 |
+
app.prepare(ctx_id=0 if torch.cuda.is_available() else -1, det_size=(IMAGE_SHAPE, IMAGE_SHAPE))
|
30 |
+
|
31 |
+
# Define function to match face embeddings
|
32 |
+
def prod_function(app, prod_path, webcam_img_pil):
|
33 |
+
np_webcam = np.array(webcam_img_pil)
|
34 |
+
cv2_webcam = cv2.cvtColor(np_webcam, cv2.COLOR_RGB2BGR)
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
|
36 |
+
webcam_faces = app.get(cv2_webcam, max_num=1)
|
37 |
+
if not webcam_faces:
|
38 |
+
return None, None
|
39 |
|
40 |
+
webcam_emb = torch.tensor(webcam_faces[0].embedding, dtype=torch.float32)
|
41 |
+
|
42 |
+
similarity_scores = []
|
43 |
for path in prod_path:
|
44 |
img = cv2.imread(path)
|
45 |
+
faces = app.get(img, max_num=1)
|
46 |
+
if not faces:
|
47 |
+
similarity_scores.append(torch.tensor(-1.0))
|
48 |
+
continue
|
49 |
+
|
50 |
+
face_emb = torch.tensor(faces[0].embedding, dtype=torch.float32)
|
51 |
+
score = F.cosine_similarity(face_emb, webcam_emb, dim=0)
|
52 |
+
similarity_scores.append(score)
|
|
|
53 |
|
54 |
+
similarity_scores = torch.stack(similarity_scores)
|
55 |
+
return similarity_scores, torch.argmax(similarity_scores)
|
56 |
+
|
57 |
+
# Streamlit tabs
|
58 |
about_tab, app_tab = st.tabs(["About the app", "Face Recognition"])
|
59 |
+
|
60 |
with about_tab:
|
61 |
+
st.markdown("""
|
62 |
+
# 👁️🗨️ AI-Powered Face Recognition Attendance System
|
63 |
+
Secure and Accurate Attendance using Vision Transformer + ArcFace Embeddings.
|
64 |
+
|
65 |
+
- **Automated, contactless attendance logging**
|
66 |
+
- **Uses InsightFace ArcFace embeddings for recognition**
|
67 |
+
- **Real-time logging with confidence scoring**
|
68 |
+
- **Future Scope: Mask-aware recognition, Group detection, and more**
|
69 |
+
""")
|
70 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
with app_tab:
|
|
|
72 |
enable = st.checkbox("Enable camera")
|
73 |
picture = st.camera_input("Take a picture", disabled=not enable)
|
74 |
+
|
75 |
if picture is not None:
|
76 |
+
with st.spinner("Analyzing face..."):
|
77 |
+
image_pil = Image.open(picture)
|
78 |
+
prediction_scores, match_idx = prod_function(app, image_paths, image_pil)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
79 |
|
80 |
+
if prediction_scores is None:
|
81 |
+
st.warning("No face detected in the captured image.")
|
82 |
else:
|
83 |
+
st.write("Similarity Scores:", prediction_scores)
|
84 |
+
matched_score = prediction_scores[match_idx].item()
|
85 |
+
|
86 |
+
if matched_score >= 0.6:
|
87 |
+
matched_name = os.path.basename(image_paths[match_idx]).split('.')[0]
|
88 |
+
st.success(f"✅ Welcome: {matched_name}")
|
89 |
+
|
90 |
+
# Send attendance via POST
|
91 |
+
url = "https://aimljan25f.glitch.me/adds"
|
92 |
+
data = {'rno': '15', 'sname': matched_name, 'sclass': '7'}
|
93 |
+
try:
|
94 |
+
response = requests.post(url, data=data)
|
95 |
+
if response.status_code == 200:
|
96 |
+
st.success("Attendance marked successfully.")
|
97 |
+
else:
|
98 |
+
st.warning("Failed to update attendance.")
|
99 |
+
except Exception as e:
|
100 |
+
st.error(f"Request failed: {e}")
|
101 |
+
else:
|
102 |
+
st.error("❌ Match not found. Try again.")
|