A professional deep learning web application that detects human emotions from text in real time using a Bidirectional LSTM (BiLSTM) neural network. Built with TensorFlow, Keras, Flask, and Bootstrap, this project transforms raw text into meaningful emotional insights.
Emotion-AI is a production-oriented sentiment understanding app that combines an NLP model with a Flask UI. In practice, the system works as a pipeline:
- User enters free-form text in the web page (
templates/index.html). - Backend sanitizes text (lowercasing + regex cleanup) before inference (
app.py). - Inference strategy is selected at runtime:
- Local model mode (TensorFlow assets loaded from disk) for full deep-learning predictions.
- Remote inference mode (API forwarding) for lightweight cloud deployment such as Vercel limits.
- Lexicon fallback mode for resilient predictions when ML dependencies are unavailable.
- Emotion + confidence are returned as JSON and rendered instantly in the UI.
- Reliability: graceful fallback prevents total outage if model/runtime is unavailable.
- Deployability: remote inference keeps serverless package size small.
- Maintainability: model assets and app logic are separated (
model_loader.pyvsapp.py).
app.pyโ Flask routes, runtime mode switching, normalization, and fallback logic.model_loader.pyโ loading tokenizer/encoder/model artifacts.templates/+static/โ web experience (UI, styles, interactions).requirements*.txtโ dependency sets for local vs deployment scenarios.
-
๐ฎ Real-time emotion prediction
-
๐ง BiLSTM-powered deep learning model
-
๐ญ Supports 7 emotions:
๐ Joy | ๐ข Sadness | ๐ก Anger | ๐จ Fear | ๐ Love | ๐ฒ Surprise | ๐ Neutral -
๐ Interactive Flask web interface
1๏ธโฃ Data Loading & Exploration
Dataset is ingested and split into 80% training / 20% testing.
2๏ธโฃ Text Cleaning & Tokenization
Regex cleaning โ Tokenization โ Padding to fixed sequence length.
3๏ธโฃ Model Architecture
Embedding โ Bidirectional LSTM โ Dropout โ Softmax Output.
4๏ธโฃ Training & Validation
Categorical Cross-Entropy + Adam Optimizer with Early Stopping & Checkpointing.
5๏ธโฃ Evaluation & Optimization
Accuracy, Precision, Recall, Confusion Matrix & Hyperparameter tuning.
6๏ธโฃ Deployment & Inference
Trained model (emotion_model.h5) integrated into Flask for real-time prediction.
- Input text via a modern UI
- One-click โTry a Sampleโ emotion buttons
- Live prediction display with confidence bar
- Fully responsive design
| Layer | Technology |
|---|---|
| Frontend | HTML, CSS, JS, Bootstrap |
| Backend | Flask (Python) |
| ML / DL | TensorFlow, Keras |
| NLP | Tokenizer, Padding, Regex |
| Deployment | Flask Web App |
- Dataset loaded from
.csv/.txtfile - Text tokenized using Keras Tokenizer
- Sequences padded for uniform input length
- Emotion labels converted to numeric form using
LabelEncoder - One-hot encoding applied for multi-class classification
Built using Keras Sequential API:
- ๐น Embedding Layer โ Converts words into dense vectors
- ๐น Flatten Layer โ Converts embeddings into 1D vector
- ๐น Dense Layer โ Learns complex patterns
- ๐น Output Layer โ Softmax activation for multi-class prediction
Compiled with:
- Optimizer:
Adam - Loss Function:
categorical_crossentropy
- Dataset split using
train_test_split - Trained for 10 epochs
- Batch size: 32
- Validation data used to monitor performance
- Model predicts emotions for unseen text
- Example:
Input:
"I am feeling very nostalgic"
Output:"Love"
flowchart LR
subgraph DP[๐ Data Preparation]
A["๐ฆ Import Libraries"]
B["๐ Load Dataset"]
C["โ๏ธ Preprocessing"]
end
subgraph LP[๐ท๏ธ Label Encoding]
D["๐ข Encode Emotions"]
E["๐ One-Hot Encoding"]
end
subgraph MT[๐ค Modeling & Training]
F["๐๏ธ Build Model"]
G["โก Train Model"]
end
subgraph PR[๐ฎ Prediction]
H["๐ User Input"]
I["๐ Tokenize & Pad"]
J["๐ฏ Predict Emotion"]
end
A --> B --> C --> D --> E --> F --> G --> H --> I --> J
%% --- Styles ---
style A fill:#FFD54F,stroke:#F57F17,stroke-width:2px,color:#000;
style B fill:#4FC3F7,stroke:#0277BD,stroke-width:2px,color:#fff;
style C fill:#AED581,stroke:#33691E,stroke-width:2px,color:#000;
style D fill:#FFCC80,stroke:#EF6C00,stroke-width:2px,color:#000;
style E fill:#FFE082,stroke:#F9A825,stroke-width:2px,color:#000;
style F fill:#BA68C8,stroke:#4A148C,stroke-width:2px,color:#fff;
style G fill:#FF8A65,stroke:#BF360C,stroke-width:2px,color:#fff;
style H fill:#81D4FA,stroke:#01579B,stroke-width:2px,color:#000;
style I fill:#B3E5FC,stroke:#0288D1,stroke-width:2px,color:#000;
style J fill:#90CAF9,stroke:#0D47A1,stroke-width:2px,color:#000;
# Clone the repository
git clone https://github.com/shivareddy2002/emotion-ai.git
cd emotion-ai
# Install dependencies
pip install -r requirements.txt
# Run the app
python app.py- Text Tokenization & Padding
- Multi-class Emotion Classification
- Deep Learning with Embeddings
- One-Hot Encoded Labels
- Validation-Based Training
- Python
- TensorFlow / Keras
- NumPy, Pandas
- Scikit-learn
- Jupyter Notebook
- ๐ฑ Social Media Sentiment Analysis
- ๐ Customer Feedback Classification
- ๐ก๏ธ Content Moderation
- ๐ง Mental Health Monitoring
- ๐ฌ Chatbots & Virtual Assistants
This project demonstrates how Neural Networks can effectively understand and classify human emotions from text.
It highlights the power of NLP in real-world applications such as customer service, analytics, and well-being platforms.
Lomada Siva Gangi Reddy
- ๐ B.Tech CSE (Data Science), RGMCET (2021โ2025)
- ๐ก Interests: Python | Machine Learning | Deep Learning | Data Science
- ๐ Open to Internships & Job Offers
Contact Me:
- ๐ง Email: lomadasivagangireddy3@gmail.com
- ๐ Phone: 9346493592
- ๐ผ LinkedIn ๐ GitHub ๐ Portfolio
Vercel serverless functions have strict bundle limits, and tensorflow-cpu is usually too large.
This repository now supports two modes:
- Local mode: uses TensorFlow model files directly.
- Vercel mode (default on Vercel): skips TensorFlow and forwards inference requests to a remote API.
- Deploy a small Python API for model inference on a platform that supports heavy ML dependencies (Render/Railway/EC2).
- In Vercel project settings, add:
USE_LOCAL_MODEL=falseREMOTE_INFERENCE_URL=https://your-ml-api.example.com/predict
- Deploy this repo to Vercel. It installs only
requirements-vercel.txt, which avoids large ML packages.
Use local dependencies when running model inference in the same process:
pip install -r requirements-local.txt
python app.pyIf Vercel shows FUNCTION_INVOCATION_FAILED:
- Open
https://<your-domain>/healthand verify:use_local_modelisfalseon Vercelremote_inference_configuredistrue
- In Vercel Project Settings โ Environment Variables, set:
USE_LOCAL_MODEL=falseREMOTE_INFERENCE_URL=https://your-ml-api.example.com/predict
- Redeploy after saving env vars.
If /predict cannot reach your remote inference API, the app now returns a lightweight fallback prediction so the UI still responds.
For production-quality predictions, configure REMOTE_INFERENCE_URL to your ML service and keep USE_LOCAL_MODEL=false on Vercel.
Remote API payload should include either {emotion, confidence} or {label, score}. If payload is invalid, the app automatically falls back to lightweight local keyword prediction.
For highest quality predictions in production:
- Prefer a dedicated remote inference service with your trained TensorFlow model.
- Set
REMOTE_INFERENCE_URLin Vercel to that endpoint. - Keep
USE_LOCAL_MODEL=falseon Vercel to avoid serverless crashes and size limits. - Use
/healthto verify runtime status (remote_inference_configured=true).
If remote service is unavailable, the app will safely fall back to the built-in lite model.
- Ensure
vercel.jsonincludestemplates/**andstatic/**inincludeFilesfor@vercel/python. - Keep
USE_LOCAL_MODEL=falseon Vercel unless TensorFlow and model files are actually available. - Check
https://<your-domain>/healthafter deploy; it should return JSON (not crash page). - If root route fails, verify templates are deployed (missing templates cause serverless 500s).
A common root cause is different Vercel environment configuration between Preview and Production after merge:
- Preview deployment may have
REMOTE_INFERENCE_URLconfigured while Production does not. - Production may still have stale
USE_LOCAL_MODEL=truefrom older deploys. - Build packaging can differ if
vercel.jsonchanges were not merged cleanly.
After merging to main, verify Production env values in Vercel Project Settings and redeploy Production.