sehaj13 commited on
Commit
4e995a5
·
verified ·
1 Parent(s): 01df85b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -47
app.py CHANGED
@@ -20,7 +20,6 @@ import numpy as np
20
  from PIL import Image
21
  from glob import glob
22
  import requests
23
- from urllib import request
24
 
25
  # Set the device (GPU or CPU)
26
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
@@ -55,21 +54,21 @@ def prod_function(app, prod_path, webcam_path):
55
 
56
  webcam_emb = app.get(cv2_webcam, max_num=1)
57
  if not webcam_emb:
58
- return torch.tensor([])
59
 
60
- webcam_emb = torch.from_numpy(np.array(webcam_emb[0].embedding))
61
 
62
  similarity_score = []
63
  for path in prod_path:
64
  img = cv2.imread(path)
65
  face_embedding = app.get(img, max_num=1)
66
  if not face_embedding:
67
- similarity_score.append(torch.tensor(-1.0)) # No face detected
68
  continue
69
- face_embedding = torch.from_numpy(np.array(face_embedding[0].embedding))
70
- similarity_score.append(F.cosine_similarity(face_embedding, webcam_emb, dim=0))
71
 
72
- return torch.stack(similarity_score)
73
 
74
  # Streamlit Tabs
75
  about_tab, app_tab = st.tabs(["About the app", "Face Recognition"])
@@ -83,7 +82,8 @@ with about_tab:
83
 
84
  This is a facial recognition-based attendance system enhanced with image classification using a Vision Transformer (ViT).
85
  Just capture your image to mark your attendance automatically!
86
- """)
 
87
 
88
  # Application Tab
89
  with app_tab:
@@ -97,37 +97,31 @@ with app_tab:
97
  image.save(webcam_path)
98
 
99
  # --- Face Recognition ---
100
- prediction = prod_function(app, image_paths, webcam_path)
101
 
102
- if len(prediction) == 0:
103
  st.warning("No face detected in the image.")
104
  else:
105
  match_idx = torch.argmax(prediction)
106
- st.subheader("Face Recognition Results")
107
- # st.write("Similarity Scores:", prediction.tolist())
108
- if prediction[match_idx] >= 0.6:
109
- name = image_paths[match_idx].split('/')[-1].split('.')[0].upper()
110
-
111
- # Extract face location from InsightFace result
112
- face_info = app.get(cv2_webcam, max_num=1)[0]
113
- faceLoc = face_info.bbox.astype(int) # returns [x1, y1, x2, y2]
114
-
115
- x1, y1, x2, y2 = faceLoc
116
- cv2.rectangle(cv2_webcam, (x1, y1), (x2, y2), (0, 255, 0), 2)
117
- cv2.rectangle(cv2_webcam, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)
118
- cv2.putText(cv2_webcam, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
119
 
120
- # Convert BGR to RGB before displaying in Streamlit
121
- st.image(cv2.cvtColor(cv2_webcam, cv2.COLOR_BGR2RGB), caption=f"Matched: {name}", use_column_width=True)
122
 
 
 
 
 
 
 
123
 
124
- if prediction[match_idx] >= 0.6:
125
- pname = image_paths[match_idx].split('/')[-1].split('.')[0]
126
- st.success(f'Welcome, {pname}!')
 
127
 
128
- # --- Send data to external API ---
129
  url = "https://skattendancesystem25.glitch.me/adds"
130
- data = {'rno': 15, 'sname': pname, 'sclass': 7}
131
  try:
132
  response = requests.post(url, data=data)
133
  if response.status_code == 200:
@@ -138,20 +132,3 @@ with app_tab:
138
  st.error(f"Request failed: {e}")
139
  else:
140
  st.error("❌ Match not found. Try again.")
141
- # try:
142
-
143
- # response = requests.post(url, data=data)
144
- # if response.status_code == 200:
145
- # st.success("✔️ Attendance data updated on remote server")
146
- # else:
147
- # st.warning("⚠️ Failed to update data")
148
- # except Exception as e:
149
- # st.error(f"❌ Error updating server: {e}")
150
- # else:
151
- # st.warning("❌ Face match not found.")
152
-
153
- # --- Image Classification ---
154
- # st.subheader("Image Classification (Vision Transformer)")
155
- # vit_results = vit_pipe(image)
156
- # for result in vit_results:
157
- # st.write(f"🔹 Label: **{result['label']}**, Score: {result['score']:.4f}")
 
20
  from PIL import Image
21
  from glob import glob
22
  import requests
 
23
 
24
  # Set the device (GPU or CPU)
25
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 
54
 
55
  webcam_emb = app.get(cv2_webcam, max_num=1)
56
  if not webcam_emb:
57
+ return torch.tensor([]), None, None
58
 
59
+ webcam_emb_tensor = torch.from_numpy(np.array(webcam_emb[0].embedding))
60
 
61
  similarity_score = []
62
  for path in prod_path:
63
  img = cv2.imread(path)
64
  face_embedding = app.get(img, max_num=1)
65
  if not face_embedding:
66
+ similarity_score.append(torch.tensor(-1.0))
67
  continue
68
+ face_tensor = torch.from_numpy(np.array(face_embedding[0].embedding))
69
+ similarity_score.append(F.cosine_similarity(face_tensor, webcam_emb_tensor, dim=0))
70
 
71
+ return torch.stack(similarity_score), cv2_webcam, webcam_emb[0].bbox.astype(int)
72
 
73
  # Streamlit Tabs
74
  about_tab, app_tab = st.tabs(["About the app", "Face Recognition"])
 
82
 
83
  This is a facial recognition-based attendance system enhanced with image classification using a Vision Transformer (ViT).
84
  Just capture your image to mark your attendance automatically!
85
+ """
86
+ )
87
 
88
  # Application Tab
89
  with app_tab:
 
97
  image.save(webcam_path)
98
 
99
  # --- Face Recognition ---
100
+ prediction, cv2_webcam, face_bbox = prod_function(app, image_paths, webcam_path)
101
 
102
+ if prediction is None or len(prediction) == 0:
103
  st.warning("No face detected in the image.")
104
  else:
105
  match_idx = torch.argmax(prediction)
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
+ if prediction[match_idx] >= 0.6:
108
+ name = image_paths[match_idx].split('/')[-1].split('.')[0].upper()
109
 
110
+ # Draw bounding box and name
111
+ x1, y1, x2, y2 = face_bbox
112
+ cv2.rectangle(cv2_webcam, (x1, y1), (x2, y2), (0, 255, 0), 2)
113
+ cv2.rectangle(cv2_webcam, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED)
114
+ cv2.putText(cv2_webcam, name, (x1 + 6, y2 - 6),
115
+ cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 255), 2)
116
 
117
+ # Show result
118
+ st.image(cv2.cvtColor(cv2_webcam, cv2.COLOR_BGR2RGB),
119
+ caption=f"Matched: {name}", use_column_width=True)
120
+ st.success(f"Welcome, {name}!")
121
 
122
+ # --- Send Attendance ---
123
  url = "https://skattendancesystem25.glitch.me/adds"
124
+ data = {'rno': 15, 'sname': name, 'sclass': 7}
125
  try:
126
  response = requests.post(url, data=data)
127
  if response.status_code == 200:
 
132
  st.error(f"Request failed: {e}")
133
  else:
134
  st.error("❌ Match not found. Try again.")