Spaces:
Sleeping
Download README.md from Digambar29/emotion-recognition-api: direct link, hf CLI and curl.
- Browser
- Download file 8.78 kB
-
https://huggingface.co/spaces/Digambar29/emotion-recognition-api/resolve/main/README.md
- Command line
-
hf download hf://spaces/Digambar29/emotion-recognition-api/README.md
-
curl -L -o README.md https://huggingface.co/spaces/Digambar29/emotion-recognition-api/resolve/main/README.md
title: Emotion Recognition API
emoji: π§
colorFrom: blue
colorTo: purple
sdk: docker
sdk_version: latest
app_file: app.py
pinned: false
π Emotion Recognition β RealβTime Facial Emotion Detection
Real-time facial emotion detection using deep learning
This project is a realβtime facial emotion recognition system built around a fineβtuned MobileNetV2 model.
We start from an ImageNetβpretrained MobileNetV2, fineβtune it on a custom facial emotion dataset, save the weights as emotion_recognition_model.pth, and then use that model behind a FastAPI backend and browser-based webcam UI to detect emotions such as π Angry, π¨ Fear, π Happy, π’ Sad, and π² Surprise from a live camera feed.
β¨ Features
- π€ Fineβtuned deep learning model β MobileNetV2 is fineβtuned on a labeled facial emotion dataset to specialize it for emotion recognition.
- πΉ Realβtime detection from your webcam (browser or local OpenCV).
- π FastAPI REST API endpoint for image-based emotion prediction.
- π¨ Simple HTML/JS frontend that streams frames to the backend and displays the predicted emotion.
- π» Standalone webcam script (
webcam.py) if you prefer running everything locally without the browser.
π Project Structure
π¦ Emotion Recognition Project
βββ π frontend/
β βββ π index.html # Minimal UI with a video element and live emotion text
β βββ π script.js # Grabs webcam frames, sends them to the backend
β βββ π style.css # Basic styling for the page and video element
βββ π model/
β βββ π api.py # FastAPI app exposing POST /api/predict
β βββ π inference.py # Loads model and defines predict(image) function
β βββ π model.py # MobileNetV2 architecture definition
β βββ π webcam.py # OpenCV-based realβtime emotion recognition
β βββ π working.ipynb # Jupyter notebook for fineβtuning MobileNetV2
β βββ πΎ emotion_recognition_model.pth # Fineβtuned PyTorch checkpoint
β βββ π Data/ # Dataset folders (Angry, Fear, Happy, Sad, Surprise)
βββ π³ DockerFile # Docker image definition for deployment
βββ π requirements.txt # Python dependencies
π οΈ Requirements
System Requirements
- π Python 3.8+ (recommended)
- π¦ pip for installing dependencies
- π· A webcam
- β‘ (Optional) GPU with CUDA for faster inference, otherwise CPU will be used.
Python Packages
Python packages (also listed in requirements.txt):
torch,torchvisionπ₯numpyπ’opencv-pythonπΉmatplotlibπpillowπΌοΈtqdmπrequestsπfastapi,uvicornβ‘ (install explicitly if missing)
Installation
You can install everything with:
pip install -r requirements.txt fastapi uvicorn
π How to Run
π Web API + Frontend
Navigate to the model folder:
cd modelStart the FastAPI server (with Uvicorn):
uvicorn api:app --host 0.0.0.0 --port 8000 --reloadOpen the frontend:
Option A: The API mounts the
frontendfolder as static files.
Open your browser and go to:http://localhost:8000/If needed, ensure the working directory is such that
../frontend(frommodel/api.py) points to thefrontendfolder in this repo.
Allow camera access π· in the browser when prompted.
You should see the live video and the predicted emotion updating underneath! π
π» Local Webcam Script (No Browser)
If you prefer a pure Python / OpenCV pipeline:
Make sure dependencies are installed:
pip install -r requirements.txtFrom the
modeldirectory, run:python webcam.pyA window called "Emotion Recognition" will appear:
- π€ Detected faces will be highlighted with a bounding box.
- π·οΈ The predicted emotion label will be shown next to each face.
- Press
qto quit.
π³ Run with Docker (Optional)
If you prefer not to manage Python and system dependencies manually, you can use the provided DockerFile:
Build the image from the project root:
docker build -t emotion-recognition -f DockerFile .Run the container and expose the API on port
8000:docker run --rm -p 8000:8000 emotion-recognitionOpen your browser at:
http://localhost:8000/and allow camera access. The behavior is the same as in the "Web API + Frontend" section above.
π§ Model & Inference Details
- The model is a MobileNetV2 classifier whose final layer is adapted to the number of emotion classes (e.g. π Angry, π¨ Fear, π Happy, π’ Sad, π² Surprise).
- The fineβtuned weights and class names are stored in
emotion_recognition_model.pth, which is produced by the training notebook (working.ipynb). - Images are preprocessed with:
- π Resize to (224 \times 224)
- π Conversion to tensor
- π Normalization with ImageNet mean and std
- Inference is done by
inference.pyvia:predict(pil_image)β returns a string label, e.g."Happy".
Testing the Model
You can test the model directly with a static image (from the model directory):
python inference.py
This will load Image.jpg and print the predicted emotion.
π‘ API Reference
Endpoints
GET /- Returns a simple JSON status:
{"status": "API running"}.
- Returns a simple JSON status:
POST /api/predict- Body:
multipart/form-datawith a single field:file: image file (e.g. JPEG/PNG).
- Response:
{ "emotion": "Happy" }
- Body:
The frontend uses this endpoint to send frames from your webcam (as blobs) approximately once per second.
π Dataset & Training (FineβTuning Overview)
- The (optional)
Datadirectory is expected to contain labeled images organized by emotion:- π
Angry/, π¨Fear/, πHappy/, π’Sad/, π²Suprise/.
- π
- The fineβtuning process is captured in
working.ipynb:- Load an ImageNetβpretrained MobileNetV2 from
torchvision. - Replace the final classification layer so that its output dimension matches the number of emotion classes.
- Create PyTorch
Dataset/DataLoaderobjects from theDatafolders with standard augmentations and preprocessing. - Train the network (typically using crossβentropy loss and an optimizer like Adam/SGD) while monitoring validation accuracy.
- Save the best model checkpoint and class mapping to
emotion_recognition_model.pth.
- Load an ImageNetβpretrained MobileNetV2 from
- You can adapt the model for new datasets by:
- Updating the
Datafolders and class list. - Reβrunning or modifying
working.ipynband, if needed, adjustingmodel.pyfor a different backbone or number of classes.
- Updating the
Dataset Source: Kaggle - Human Face Emotions
π§ Troubleshooting
π· Camera access denied (browser)
- Check browser permissions and ensure you're using
http://localhost(notfile://).
- Check browser permissions and ensure you're using
π "Backend not reachable" in the frontend
- Confirm the FastAPI server is running on the same host/port that
script.jsexpects (/api/predictβ defaulthttp://localhost:8000/api/predict). - Check for CORS issues or port conflicts.
- Confirm the FastAPI server is running on the same host/port that
π¦ Model file not found
- Ensure
emotion_recognition_model.pthis present in themodeldirectory when running any Python scripts there.
- Ensure
π License & Credits
- The project uses PyTorch, FastAPI, OpenCV, and PIL under their respective licenses.
- Dataset images in
Data/should respect their original source licenses (not provided here). - Feel free to modify or extend this project for research, learning, or personal use.
Made with β€οΈ using PyTorch, FastAPI, and OpenCV
β Star this repo if you find it helpful!