|
import streamlit as st |
|
import cv2 |
|
import numpy as np |
|
import time |
|
from keras.models import load_model |
|
from PIL import Image |
|
from huggingface_hub import HfApi, Repository |
|
import os |
|
import tempfile |
|
|
|
|
|
st.set_page_config(page_title="Emotion Detection", layout="centered") |
|
|
|
|
|
st.markdown("<h1 style='text-align: center;'>Emotion Detection</h1>", unsafe_allow_html=True) |
|
st.markdown("<h3 style='text-align: center;'>angry, fear, happy, neutral, sad, surprise</h3>", unsafe_allow_html=True) |
|
|
|
|
|
@st.cache_resource |
|
def load_emotion_model(): |
|
model = load_model('CNN_Model_acc_75.h5') |
|
return model |
|
|
|
start_time = time.time() |
|
model = load_emotion_model() |
|
st.write(f"Model loaded in {time.time() - start_time:.2f} seconds.") |
|
|
|
|
|
emotion_labels = ['angry', 'fear', 'happy', 'neutral', 'sad', 'surprise'] |
|
img_shape = 48 |
|
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') |
|
|
|
def process_frame(frame): |
|
"""Detect faces and predict emotions.""" |
|
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) |
|
faces = face_cascade.detectMultiScale(gray_frame, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)) |
|
for (x, y, w, h) in faces: |
|
roi_gray = gray_frame[y:y+h, x:x+w] |
|
roi_color = frame[y:y+h, x:x+w] |
|
face_roi = cv2.resize(roi_color, (img_shape, img_shape)) |
|
face_roi = np.expand_dims(face_roi, axis=0) |
|
face_roi = face_roi / float(img_shape) |
|
predictions = model.predict(face_roi) |
|
emotion = emotion_labels[np.argmax(predictions[0])] |
|
|
|
|
|
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) |
|
cv2.putText(frame, emotion, (x, y + h + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2) |
|
return frame |
|
|
|
|
|
st.sidebar.title("Choose Input Source") |
|
upload_choice = st.sidebar.radio("Select:", ["Camera", "Upload Video", "Upload Image", "Upload to Hugging Face"]) |
|
|
|
if upload_choice == "Camera": |
|
|
|
st.sidebar.info("Click a picture to analyze emotion.") |
|
picture = st.camera_input("Take a picture") |
|
if picture: |
|
image = Image.open(picture) |
|
frame = np.array(image) |
|
frame = process_frame(frame) |
|
st.image(frame, caption="Processed Image", use_column_width=True) |
|
|
|
elif upload_choice == "Upload Video": |
|
uploaded_video = st.file_uploader("Upload Video", type=["mp4", "mov", "avi", "mkv", "webm"]) |
|
if uploaded_video: |
|
with tempfile.NamedTemporaryFile(delete=False) as tfile: |
|
tfile.write(uploaded_video.read()) |
|
video_source = cv2.VideoCapture(tfile.name) |
|
frame_placeholder = st.empty() |
|
while video_source.isOpened(): |
|
ret, frame = video_source.read() |
|
if not ret: |
|
break |
|
frame = process_frame(frame) |
|
frame_placeholder.image(frame, channels="BGR", use_column_width=True) |
|
video_source.release() |
|
|
|
elif upload_choice == "Upload Image": |
|
uploaded_image = st.file_uploader("Upload Image", type=["png", "jpg", "jpeg"]) |
|
if uploaded_image: |
|
image = Image.open(uploaded_image) |
|
frame = np.array(image) |
|
frame = process_frame(frame) |
|
st.image(frame, caption="Processed Image", use_column_width=True) |
|
|
|
elif upload_choice == "Upload to Hugging Face": |
|
st.sidebar.info("Upload images to the 'known_faces' directory in the Hugging Face repository.") |
|
|
|
|
|
REPO_NAME = "face_emotion_detection2" |
|
REPO_ID = "LovnishVerma/" + REPO_NAME |
|
hf_token = os.getenv("uploadphoto1") |
|
|
|
if not hf_token: |
|
st.error("Hugging Face token not found. Please set it as an environment variable named 'HF_TOKEN'.") |
|
st.stop() |
|
|
|
|
|
api = HfApi() |
|
|
|
def create_hugging_face_repo(): |
|
"""Create or verify the Hugging Face repository.""" |
|
try: |
|
api.create_repo(repo_id=REPO_ID, repo_type="dataset", token=hf_token, exist_ok=True) |
|
st.success(f"Repository '{REPO_NAME}' is ready on Hugging Face!") |
|
except Exception as e: |
|
st.error(f"Error creating Hugging Face repository: {e}") |
|
|
|
def upload_to_hugging_face(file): |
|
"""Upload a file to the Hugging Face repository.""" |
|
try: |
|
with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as temp_file: |
|
temp_file.write(file.read()) |
|
temp_file_path = temp_file.name |
|
|
|
api.upload_file( |
|
path_or_fileobj=temp_file_path, |
|
path_in_repo=f"known_faces/{os.path.basename(temp_file_path)}", |
|
repo_id=REPO_ID, |
|
token=hf_token, |
|
) |
|
st.success("File uploaded successfully to Hugging Face!") |
|
except Exception as e: |
|
st.error(f"Error uploading file to Hugging Face: {e}") |
|
|
|
|
|
create_hugging_face_repo() |
|
|
|
|
|
hf_uploaded_image = st.file_uploader("Upload Image to Hugging Face", type=["png", "jpg", "jpeg"]) |
|
if hf_uploaded_image: |
|
upload_to_hugging_face(hf_uploaded_image) |
|
|
|
st.sidebar.write("Emotion Labels: Angry, Fear, Happy, Neutral, Sad, Surprise") |