LovnishVerma commited on
Commit
46acd56
·
verified ·
1 Parent(s): ff45b83

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -40
app.py CHANGED
@@ -1,62 +1,93 @@
1
  import streamlit as st
 
2
  import os
 
 
3
  from PIL import Image
4
  from huggingface_hub import HfApi
 
5
 
6
  # Constants
7
  KNOWN_FACES_DIR = "known_faces" # Directory to save user images
 
 
8
  REPO_NAME = "face_and_emotion_detection"
9
  REPO_ID = f"LovnishVerma/{REPO_NAME}"
10
 
11
- # Ensure the directory exists
12
  os.makedirs(KNOWN_FACES_DIR, exist_ok=True)
13
 
14
- # Retrieve Hugging Face token from environment variable
15
- hf_token = os.getenv("upload") # Replace with your actual Hugging Face token
16
- if not hf_token:
17
- st.error("Hugging Face token not found. Please set the environment variable.")
18
- st.stop()
19
-
20
  # Initialize Hugging Face API
 
21
  api = HfApi()
22
 
23
- def save_image_to_hugging_face(image, name, roll_no):
24
- """ Saves the image locally to the KNOWN_FACES_DIR and uploads it to Hugging Face. """
25
- # Ensure the directory exists
26
- if not os.path.exists(KNOWN_FACES_DIR):
27
- os.makedirs(KNOWN_FACES_DIR)
 
28
 
29
- # Construct the local file path
30
- filename = f"{name}_{roll_no}.jpg"
31
- local_path = os.path.join(KNOWN_FACES_DIR, filename)
 
 
 
32
 
33
- try:
34
- # Convert image to RGB if necessary
35
- if image.mode != "RGB":
36
- image = image.convert("RGB")
 
 
 
37
 
38
- # Save the image to the known_faces directory
39
- image.save(local_path)
40
-
41
- # Debug: Print the path where the image is saved
42
- st.write(f"Image saved locally at: {local_path}")
43
-
44
- # Upload the saved file to Hugging Face
45
- api.upload_file(
46
- path_or_fileobj=local_path,
47
- path_in_repo=filename,
48
- repo_id=REPO_ID,
49
- repo_type="space",
50
- token=hf_token,
51
- )
52
- st.success(f"Image saved to {KNOWN_FACES_DIR} and uploaded to Hugging Face as {filename}.")
53
- except Exception as e:
54
- st.error(f"Error saving or uploading image: {e}")
55
 
56
- return local_path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
  # Streamlit UI
59
- st.title("Student Registration with Hugging Face Image Upload")
60
 
61
  # Input fields for student details
62
  name = st.text_input("Enter your name")
@@ -85,7 +116,19 @@ if st.button("Register"):
85
  elif capture_mode == "Upload File" and picture:
86
  image = Image.open(picture)
87
 
88
- # Save the image locally and upload it to Hugging Face
89
- image_path = save_image_to_hugging_face(image, name, roll_no)
 
 
 
 
 
 
 
 
 
 
 
 
90
  except Exception as e:
91
  st.error(f"An error occurred: {e}")
 
1
  import streamlit as st
2
+ import cv2
3
  import os
4
+ import numpy as np
5
+ from keras.models import load_model
6
  from PIL import Image
7
  from huggingface_hub import HfApi
8
+ from datetime import datetime
9
 
10
  # Constants
11
  KNOWN_FACES_DIR = "known_faces" # Directory to save user images
12
+ EMOTION_MODEL_FILE = "CNN_Model_acc_75.h5"
13
+ EMOTION_LABELS = ["Angry", "Disgust", "Fear", "Happy", "Sad", "Surprise", "Neutral"]
14
  REPO_NAME = "face_and_emotion_detection"
15
  REPO_ID = f"LovnishVerma/{REPO_NAME}"
16
 
17
+ # Ensure the directories exist
18
  os.makedirs(KNOWN_FACES_DIR, exist_ok=True)
19
 
 
 
 
 
 
 
20
  # Initialize Hugging Face API
21
+ hf_token = os.getenv("upload") # Replace with your actual Hugging Face token
22
  api = HfApi()
23
 
24
+ # Load emotion detection model
25
+ try:
26
+ emotion_model = load_model(EMOTION_MODEL_FILE)
27
+ except Exception as e:
28
+ st.error(f"Error loading emotion model: {e}")
29
+ st.stop()
30
 
31
+ # Face and Emotion Detection Function
32
+ def detect_faces_and_emotions(image):
33
+ """Detect faces and emotions in the image"""
34
+ gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
35
+ face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
36
+ faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.3, minNeighbors=5)
37
 
38
+ emotion_label = None
39
+ for (x, y, w, h) in faces:
40
+ face = gray_image[y:y+h, x:x+w]
41
+ resized_face = cv2.resize(face, (48, 48)) # Resize face to 48x48
42
+ rgb_face = cv2.cvtColor(resized_face, cv2.COLOR_GRAY2RGB)
43
+ normalized_face = rgb_face / 255.0
44
+ reshaped_face = np.reshape(normalized_face, (1, 48, 48, 3))
45
 
46
+ # Predict the emotion
47
+ emotion_prediction = emotion_model.predict(reshaped_face)
48
+ emotion_label = np.argmax(emotion_prediction)
49
+
50
+ return faces, EMOTION_LABELS[emotion_label] if emotion_label else None
51
+
52
+ # Face Recognition Function
53
+ def recognize_face(image):
54
+ """Recognize the face in the uploaded image by comparing with known faces"""
55
+ recognizer = cv2.face.LBPHFaceRecognizer_create()
 
 
 
 
 
 
 
56
 
57
+ known_faces = []
58
+ labels = []
59
+
60
+ # Load known faces from the directory
61
+ for filename in os.listdir(KNOWN_FACES_DIR):
62
+ if filename.endswith(".jpg"):
63
+ image_path = os.path.join(KNOWN_FACES_DIR, filename)
64
+ known_image = cv2.imread(image_path)
65
+ gray_image = cv2.cvtColor(known_image, cv2.COLOR_BGR2GRAY)
66
+ faces = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml').detectMultiScale(gray_image, scaleFactor=1.3, minNeighbors=5)
67
+
68
+ for (x, y, w, h) in faces:
69
+ face = gray_image[y:y+h, x:x+w]
70
+ known_faces.append(face)
71
+ labels.append(filename.split(".")[0]) # Use image name as label
72
+
73
+ if known_faces:
74
+ recognizer.train(known_faces, np.array(range(len(labels)))) # Train recognizer with known faces
75
+
76
+ # Detect faces in the uploaded image
77
+ gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
78
+ faces = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml').detectMultiScale(gray_image, scaleFactor=1.3, minNeighbors=5)
79
+
80
+ recognized_name = "Unknown"
81
+ for (x, y, w, h) in faces:
82
+ face = gray_image[y:y+h, x:x+w]
83
+ label, confidence = recognizer.predict(face)
84
+ if confidence < 100: # Confidence threshold
85
+ recognized_name = labels[label] # Get the name from labels
86
+
87
+ return recognized_name
88
 
89
  # Streamlit UI
90
+ st.title("Student Registration with Face Recognition and Emotion Detection")
91
 
92
  # Input fields for student details
93
  name = st.text_input("Enter your name")
 
116
  elif capture_mode == "Upload File" and picture:
117
  image = Image.open(picture)
118
 
119
+ # Convert the image to numpy array for processing
120
+ img_array = np.array(image)
121
+
122
+ # Detect faces and emotions
123
+ faces, emotion_label = detect_faces_and_emotions(img_array)
124
+ if faces:
125
+ st.success(f"Emotion Detected: {emotion_label}")
126
+ else:
127
+ st.warning("No face detected.")
128
+
129
+ # Perform face recognition
130
+ recognized_name = recognize_face(img_array)
131
+ st.success(f"Face Recognized as: {recognized_name}")
132
+
133
  except Exception as e:
134
  st.error(f"An error occurred: {e}")