Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,15 +1,37 @@
|
|
| 1 |
import base64
|
| 2 |
import os
|
| 3 |
-
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
# Make sure the necessary directories exist and have proper permissions
|
| 7 |
-
|
| 8 |
-
os.makedirs(f'{app_data_path}/
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
os.environ['
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
import cv2
|
| 15 |
import numpy as np
|
|
@@ -51,15 +73,18 @@ def create_cnn_embedding_model():
|
|
| 51 |
Dense(512, activation='linear') # Final dense layer to produce a 512-dimensional embedding
|
| 52 |
])
|
| 53 |
return model
|
|
|
|
| 54 |
cnn_model = create_cnn_embedding_model()
|
| 55 |
cnn_model.compile(optimizer='adam', loss='mse')
|
| 56 |
# Using MSE loss as we are not training for classification
|
|
|
|
| 57 |
def cosine(embedding1, embedding2):
|
| 58 |
dot_product = np.dot(embedding1, embedding2)
|
| 59 |
norm1 = np.linalg.norm(embedding1)
|
| 60 |
norm2 = np.linalg.norm(embedding2)
|
| 61 |
similarity = dot_product / (norm1 * norm2)
|
| 62 |
return similarity
|
|
|
|
| 63 |
@app.route('/CNN-login', methods=['POST'])
|
| 64 |
def cnnlogin():
|
| 65 |
# Check for uploaded image
|
|
@@ -207,7 +232,19 @@ def register():
|
|
| 207 |
# Calculate mean embeddings
|
| 208 |
mean_facenet_embedding = np.mean(facenet_embeddings, axis=0).astype(float).tolist()
|
| 209 |
mean_cnn_embedding = np.mean(cnn_embeddings, axis=0).astype(float).tolist()
|
| 210 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
# Create user data
|
| 212 |
id = mongo.db.data.count_documents({}) + 1
|
| 213 |
user_data = {
|
|
@@ -251,20 +288,38 @@ def load_embeddings_from_db():
|
|
| 251 |
|
| 252 |
# Load face embeddings from MongoDB initially
|
| 253 |
face_data, labels, names = load_embeddings_from_db()
|
| 254 |
-
cnn_model.load_weights('cnn_model.weights.h5')
|
| 255 |
-
|
| 256 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
|
| 258 |
# Reload embeddings to update after a new registration
|
| 259 |
def reload_embeddings():
|
| 260 |
global face_data, labels, names
|
| 261 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
face_data, labels, names = load_embeddings_from_db()
|
| 263 |
|
| 264 |
# Recognize faces using MongoDB-stored embeddings
|
| 265 |
model = YOLO('yolov5s.pt') # Replace with your YOLO model path
|
| 266 |
|
| 267 |
-
|
| 268 |
@app.route('/crowd', methods=['POST'])
|
| 269 |
def upload_image():
|
| 270 |
if 'image' not in request.files:
|
|
@@ -397,3 +452,5 @@ def get_attendance():
|
|
| 397 |
records = list(mongo.db.attendance1.find({}, {"_id": 0}))
|
| 398 |
return jsonify({"attendance": records})
|
| 399 |
|
|
|
|
|
|
|
|
|
| 1 |
import base64
|
| 2 |
import os
|
| 3 |
+
import tempfile
|
| 4 |
+
|
| 5 |
+
# Use temporary directory or current working directory for app data
|
| 6 |
+
# This avoids permission issues in containerized environments
|
| 7 |
+
try:
|
| 8 |
+
# Try to use /tmp first (usually writable in containers)
|
| 9 |
+
app_data_path = '/tmp/app_data'
|
| 10 |
+
os.makedirs(app_data_path, exist_ok=True)
|
| 11 |
+
except PermissionError:
|
| 12 |
+
# Fallback to current directory or temp directory
|
| 13 |
+
app_data_path = os.path.join(os.getcwd(), 'app_data')
|
| 14 |
+
try:
|
| 15 |
+
os.makedirs(app_data_path, exist_ok=True)
|
| 16 |
+
except PermissionError:
|
| 17 |
+
# Last resort: use system temp directory
|
| 18 |
+
app_data_path = tempfile.mkdtemp(prefix='app_data_')
|
| 19 |
|
| 20 |
# Make sure the necessary directories exist and have proper permissions
|
| 21 |
+
try:
|
| 22 |
+
os.makedirs(f'{app_data_path}/ultralytics', exist_ok=True)
|
| 23 |
+
os.makedirs(f'{app_data_path}/.keras', exist_ok=True)
|
| 24 |
+
|
| 25 |
+
# Set environment variables for the respective paths
|
| 26 |
+
os.environ['ULTRALYTICS_CONFIG_DIR'] = f'{app_data_path}/ultralytics'
|
| 27 |
+
os.environ['KERAS_HOME'] = f'{app_data_path}/.keras'
|
| 28 |
+
|
| 29 |
+
print(f"Successfully created app data directory at: {app_data_path}")
|
| 30 |
+
except PermissionError as e:
|
| 31 |
+
print(f"Warning: Could not create app data directories: {e}")
|
| 32 |
+
# Set environment variables to current directory as fallback
|
| 33 |
+
os.environ['ULTRALYTICS_CONFIG_DIR'] = os.getcwd()
|
| 34 |
+
os.environ['KERAS_HOME'] = os.getcwd()
|
| 35 |
|
| 36 |
import cv2
|
| 37 |
import numpy as np
|
|
|
|
| 73 |
Dense(512, activation='linear') # Final dense layer to produce a 512-dimensional embedding
|
| 74 |
])
|
| 75 |
return model
|
| 76 |
+
|
| 77 |
cnn_model = create_cnn_embedding_model()
|
| 78 |
cnn_model.compile(optimizer='adam', loss='mse')
|
| 79 |
# Using MSE loss as we are not training for classification
|
| 80 |
+
|
| 81 |
def cosine(embedding1, embedding2):
|
| 82 |
dot_product = np.dot(embedding1, embedding2)
|
| 83 |
norm1 = np.linalg.norm(embedding1)
|
| 84 |
norm2 = np.linalg.norm(embedding2)
|
| 85 |
similarity = dot_product / (norm1 * norm2)
|
| 86 |
return similarity
|
| 87 |
+
|
| 88 |
@app.route('/CNN-login', methods=['POST'])
|
| 89 |
def cnnlogin():
|
| 90 |
# Check for uploaded image
|
|
|
|
| 232 |
# Calculate mean embeddings
|
| 233 |
mean_facenet_embedding = np.mean(facenet_embeddings, axis=0).astype(float).tolist()
|
| 234 |
mean_cnn_embedding = np.mean(cnn_embeddings, axis=0).astype(float).tolist()
|
| 235 |
+
|
| 236 |
+
# Save model weights with error handling
|
| 237 |
+
try:
|
| 238 |
+
weights_path = os.path.join(app_data_path, 'cnn_model.weights.h5')
|
| 239 |
+
cnn_model.save_weights(weights_path)
|
| 240 |
+
except Exception as e:
|
| 241 |
+
print(f"Warning: Could not save model weights: {e}")
|
| 242 |
+
# Try saving in current directory
|
| 243 |
+
try:
|
| 244 |
+
cnn_model.save_weights('cnn_model.weights.h5')
|
| 245 |
+
except Exception as e2:
|
| 246 |
+
print(f"Warning: Could not save model weights in current directory: {e2}")
|
| 247 |
+
|
| 248 |
# Create user data
|
| 249 |
id = mongo.db.data.count_documents({}) + 1
|
| 250 |
user_data = {
|
|
|
|
| 288 |
|
| 289 |
# Load face embeddings from MongoDB initially
|
| 290 |
face_data, labels, names = load_embeddings_from_db()
|
|
|
|
|
|
|
| 291 |
|
| 292 |
+
# Load CNN model weights with error handling
|
| 293 |
+
try:
|
| 294 |
+
weights_path = os.path.join(app_data_path, 'cnn_model.weights.h5')
|
| 295 |
+
if os.path.exists(weights_path):
|
| 296 |
+
cnn_model.load_weights(weights_path)
|
| 297 |
+
print("Loaded CNN model weights from app_data directory")
|
| 298 |
+
elif os.path.exists('cnn_model.weights.h5'):
|
| 299 |
+
cnn_model.load_weights('cnn_model.weights.h5')
|
| 300 |
+
print("Loaded CNN model weights from current directory")
|
| 301 |
+
else:
|
| 302 |
+
print("No existing CNN model weights found - will use initialized weights")
|
| 303 |
+
except Exception as e:
|
| 304 |
+
print(f"Warning: Could not load CNN model weights: {e}")
|
| 305 |
|
| 306 |
# Reload embeddings to update after a new registration
|
| 307 |
def reload_embeddings():
|
| 308 |
global face_data, labels, names
|
| 309 |
+
try:
|
| 310 |
+
weights_path = os.path.join(app_data_path, 'cnn_model.weights.h5')
|
| 311 |
+
if os.path.exists(weights_path):
|
| 312 |
+
cnn_model.load_weights(weights_path)
|
| 313 |
+
elif os.path.exists('cnn_model.weights.h5'):
|
| 314 |
+
cnn_model.load_weights('cnn_model.weights.h5')
|
| 315 |
+
except Exception as e:
|
| 316 |
+
print(f"Warning: Could not reload CNN model weights: {e}")
|
| 317 |
+
|
| 318 |
face_data, labels, names = load_embeddings_from_db()
|
| 319 |
|
| 320 |
# Recognize faces using MongoDB-stored embeddings
|
| 321 |
model = YOLO('yolov5s.pt') # Replace with your YOLO model path
|
| 322 |
|
|
|
|
| 323 |
@app.route('/crowd', methods=['POST'])
|
| 324 |
def upload_image():
|
| 325 |
if 'image' not in request.files:
|
|
|
|
| 452 |
records = list(mongo.db.attendance1.find({}, {"_id": 0}))
|
| 453 |
return jsonify({"attendance": records})
|
| 454 |
|
| 455 |
+
if __name__ == '__main__':
|
| 456 |
+
app.run(debug=True)
|