Face_app / app.py
nithisri's picture
Rename stream.py to app.py
09926b5 verified
Raw History Blame Contribute Delete
6.6 kB
import av
import cv2
import torch
import asyncio
import streamlit as st
from PIL import Image, ImageEnhance
from facenet_pytorch import MTCNN
from transformers import pipeline
from collections import deque, Counter
from streamlit_webrtc import webrtc_streamer, VideoProcessorBase
# Fix for asyncio event loop issues on Hugging Face Spaces
try:
asyncio.get_event_loop()
except RuntimeError:
asyncio.set_event_loop(asyncio.new_event_loop())
# =========================
# CONFIG
# =========================
MODEL_NAME = "trpakov/vit-face-expression"
FACE_CONFIDENCE = 0.90
PROCESS_EVERY_N_FRAMES = 2
SMOOTHING_FRAMES = 10
SAD_MIN_SCORE = 0.18
SAD_NEUTRAL_MARGIN = 0.15
EMOTION_COLORS = {
"happy": (0, 255, 0), # Green
"sad": (255, 0, 0), # Blue (BGR)
"neutral": (255, 255, 0), # Cyan
}
device = "cuda" if torch.cuda.is_available() else "cpu"
# =========================
# STREAMLIT UI
# =========================
st.set_page_config(page_title="Face Emotion Detection", page_icon="😊", layout="wide")
st.title("😊 Real-Time Face Emotion Detection")
st.write("Detects face emotions in real time: **Happy**, **Sad**, or **Neutral**.")
# =========================
# CACHE MODELS
# =========================
@st.cache_resource
def load_models():
face_detector = MTCNN(
keep_all=True,
device=device,
min_face_size=60,
thresholds=[0.6, 0.7, 0.7]
)
emotion_model = pipeline(
"image-classification",
model=MODEL_NAME,
top_k=None,
device=0 if torch.cuda.is_available() else -1
)
return face_detector, emotion_model
face_detector, emotion_model = load_models()
# =========================
# HELPERS
# =========================
def get_emotion(preds: list) -> tuple[str, float]:
"""
Extract happy / sad / neutral from model predictions.
Applies a soft boost for sad so it isn't drowned out by neutral.
Always returns one of the three labels β€” no 'uncertain' fallback.
"""
scores = {p["label"].lower(): float(p["score"]) for p in preds}
happy = scores.get("happy", 0.0)
sad = scores.get("sad", 0.0)
neutral = scores.get("neutral", 0.0)
candidates = {"happy": happy, "sad": sad, "neutral": neutral}
# Soft boost: prefer sad over neutral when it's close
if sad >= SAD_MIN_SCORE and sad >= neutral - SAD_NEUTRAL_MARGIN:
candidates["sad"] = max(sad, neutral - SAD_NEUTRAL_MARGIN + 0.01)
label = max(candidates, key=candidates.get)
score = candidates[label]
return label, score
# =========================
# VIDEO PROCESSOR
# =========================
class EmotionProcessor(VideoProcessorBase):
def __init__(self):
self.history = deque(maxlen=SMOOTHING_FRAMES)
self.frame_count = 0
self.last_box = None
self.last_label = "No Face"
self.last_score = 0.0
def recv(self, frame):
img = frame.to_ndarray(format="bgr24")
img = cv2.flip(img, 1)
display = img.copy()
h, w = img.shape[:2]
self.frame_count += 1
if self.frame_count % PROCESS_EVERY_N_FRAMES == 0:
rgb_frame = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
pil_frame = Image.fromarray(rgb_frame)
boxes, probs = face_detector.detect(pil_frame)
if boxes is None or probs is None:
self._reset()
else:
# Keep only high-confidence faces; pick the largest one
valid_faces = []
for box, prob in zip(boxes, probs):
if prob >= FACE_CONFIDENCE:
x1, y1, x2, y2 = box.astype(int)
x1, y1 = max(0, x1), max(0, y1)
x2, y2 = min(w, x2), min(h, y2)
area = (x2 - x1) * (y2 - y1)
if area > 0:
valid_faces.append((area, x1, y1, x2, y2))
if not valid_faces:
self._reset()
else:
valid_faces.sort(reverse=True)
_, x1, y1, x2, y2 = valid_faces[0]
# Pad the crop for better context
pad_x = int((x2 - x1) * 0.20)
pad_y = int((y2 - y1) * 0.25)
x1p = max(0, x1 - pad_x)
y1p = max(0, y1 - pad_y)
x2p = min(w, x2 + pad_x)
y2p = min(h, y2 + pad_y)
face_crop = rgb_frame[y1p:y2p, x1p:x2p]
if face_crop.size != 0:
face_img = Image.fromarray(face_crop).resize((224, 224))
face_img = ImageEnhance.Contrast(face_img).enhance(1.25)
face_img = ImageEnhance.Sharpness(face_img).enhance(1.15)
preds = emotion_model(face_img)
label, score = get_emotion(preds)
self.history.append(label)
smoothed_label = Counter(self.history).most_common(1)[0][0]
self.last_box = (x1p, y1p, x2p, y2p)
self.last_label = smoothed_label
self.last_score = score
# Draw results on frame
if self.last_box is not None:
x1, y1, x2, y2 = self.last_box
color = EMOTION_COLORS.get(self.last_label, (200, 200, 200))
cv2.rectangle(display, (x1, y1), (x2, y2), color, 2)
cv2.putText(
display,
f"{self.last_label.upper()} ({self.last_score:.2f})",
(x1, max(30, y1 - 10)),
cv2.FONT_HERSHEY_SIMPLEX,
0.75,
color,
2
)
else:
cv2.putText(
display,
"NO FACE DETECTED",
(30, 50),
cv2.FONT_HERSHEY_SIMPLEX,
0.9,
(0, 0, 255),
2
)
return av.VideoFrame.from_ndarray(display, format="bgr24")
def _reset(self):
"""Clear state when no valid face is found."""
self.last_box = None
self.last_label = "No Face"
self.last_score = 0.0
self.history.clear()
# =========================
# START CAMERA
# =========================
webrtc_streamer(
key="emotion-detection",
video_processor_factory=EmotionProcessor,
media_stream_constraints={
"video": True,
"audio": False
},
async_processing=True,
)