AI-powered real-time fraud detection for UPI transactions using Hidden Markov Models and behavioral analysis.
- Real-time Fraud Detection - Analyze transactions instantly
- User Authentication - Secure JWT-based login system
- Transaction History - Track all your transactions
- ML-Powered Analysis - Uses Hidden Markov Models for pattern detection
- Behavioral Learning - Learns from your transaction patterns
- Risk Scoring - Provides detailed risk assessment
- React 18
- Vite
- Axios
- React Router
- Flask (Python)
- Flask-JWT-Extended
- Flask-CORS
- MongoDB (PyMongo)
- Hidden Markov Models (HMM)
- Conditional Random Fields (CRF)
- scikit-learn
- pandas, numpy
- hmmlearn
- sklearn-crfsuite
UPI-Secure/
βββ Backend/
β βββ app/
β β βββ __init__.py # Flask application factory
β β βββ config.py # Configuration management
β β βββ database.py # MongoDB connection manager
β β βββ models.py # ML model loader (ModelManager)
β β βββ utils.py # Feature calculation utilities
β β βββ routes/
β β β βββ auth.py # Authentication endpoints
β β β βββ fraud.py # Fraud detection endpoints
β β β βββ admin.py # Admin endpoints
β β βββ services/
β β βββ fraud_detection.py # FraudDetectionService
β β βββ risk_analysis.py # RiskAnalysisService
β βββ models/
β β βββ arlg_hmm_model.pkl # Trained AR-HMM model
β β βββ crf_model.pkl # Trained CRF model
β β βββ scaler.pkl # Feature scaler
β β βββ label_encoder.pkl # Label encoder
β βββ mainapp.py # Entry point (imports from wsgi)
β βββ wsgi.py # WSGI application
β βββ model.py # AutoRegressiveHMM class
β βββ requirements.txt # Python dependencies
βββ frontend/
β βββ src/
β β βββ pages/ # React pages (Home, Login, Register, TransactionForm, History, About)
β β βββ components/ # React components (Navbar)
β β βββ App.jsx # Main app component
β β βββ config.js # API configuration
β βββ package.json
β βββ vite.config.js
βββ models/ # Additional model copies
βββ UPI_SECURE.ipynb # Model training notebook
- Python 3.12+ (tested with 3.14)
- Node.js 18+
- MongoDB (local or Atlas)
cd Backend
python -m venv venv
venv\Scripts\activate # Windows
pip install -r requirements.txt
python mainapp.pyBackend runs on: http://localhost:5000
cd frontend
npm install
npm run devFrontend runs on: http://localhost:5173
See DEPLOYMENT_GUIDE.md for complete deployment instructions.
Quick Deploy:
- Frontend β Netlify
- Backend β Render
- Database β MongoDB Atlas
All free tier available!
- User Registration/Login - Secure authentication with JWT
- Transaction Submission - User submits transaction details
- Feature Extraction - System calculates 10 features from transaction
- Historical Analysis - Retrieves last 2 transactions for lagging
- Ensemble ML Prediction - HMM and CRF models analyze patterns
- Risk Assessment - Returns fraud score, risk factors, and confidence level
- History Tracking - Saves transaction with prediction for future learning
- Bcrypt password hashing
- JWT token authentication
- CORS protection
- Input validation
- SQL injection prevention
- XSS protection
Algorithms: Ensemble of HMM (Hidden Markov Model) and CRF (Conditional Random Field)
Features Used (10 total):
- Transaction Amount (INR) - Current transaction amount
- Transaction_Amount_Diff - Absolute difference from user's last transaction
- Transaction_Frequency_Score - Recent transactions in 30 days / 10
- Time_Anomaly_Score - Unusual hour detection scaled by amount ratio
- Recipient_Total_Transactions - Count of transactions to this recipient
- Recipient_Avg_Transaction_Amount - Average amount to this recipient
- Risk_Score - (Frequency_Score + Time_Anomaly_Score) / 2
- hour - Hour of day (0-23)
- day_of_week - Day of week (0-6, Monday=0)
- Location_Cluster - Placeholder (currently 0.0)
Classification Labels:
- 0: Normal (Low fraud risk)
- 1: Suspicious (Medium fraud risk)
- 2: Fraud (High fraud risk)
Ensemble Scoring:
- HMM prediction: Uses AR-HMM with 3 lags (requires β₯3 historical transactions)
- Retrieves last 2 transactions from MongoDB
- Creates lagged feature matrix: [t-2, t-1, t] features
- Applies scaler to all rows
- Creates 30-feature lagged observation: np.hstack([X[-1], X[-2], X[-3]])
- Predicts state (0, 1, or 2)
- CRF prediction: Uses current transaction's 10 scaled features
- Converts to dictionary format with exact attribute names
- Predicts label (0, 1, or 2)
- Final score: Average of HMM and CRF probabilities (0.0-1.0)
- HMM probability = state / 2.0
- CRF probability = label / 2.0
- Ensemble score = (HMM_prob + CRF_prob) / 2
- Classification:
- Score β₯0.67 β Label 2 (Fraud), High confidence
- Score 0.33-0.67 β Label 1 (Suspicious), Medium confidence
- Score <0.33 β Label 0 (Normal), Low confidence
POST /api/register- Register new userPOST /api/login- User login
POST /api/check_fraud- Check transaction for fraud (requires JWT)GET /api/history- Get user's transaction history (requires JWT)
GET /health- Health check (model status, DB connection)GET /api/admin/stats- Database statistics (users, transactions, fraud rate)GET /api/admin/users- Get all users (without passwords)GET /api/admin/transactions- Get all transactions with filters
POST /api/fraud/predict- Public fraud prediction endpoint (no auth required)
Test the API using the public endpoint:
curl -X POST http://localhost:5000/api/fraud/predict \
-H "Content-Type: application/json" \
-d '{
"username": "test_user",
"recipient_id": "merchant@paytm",
"transaction_amount": 5000,
"transaction_time": "2024-01-15T14:30:00"
}'Check health status:
curl http://localhost:5000/healthMONGODB_URI=mongodb://localhost:27017/
JWT_SECRET_KEY=your-secret-key-change-in-production
SECRET_KEY=dev-secret-key-change-in-production
FLASK_ENV=development
PORT=5000export const API_URL = 'http://localhost:5000';- Fork the repository
- Create feature branch (
git checkout -b feature/AmazingFeature) - Commit changes (
git commit -m 'Add AmazingFeature') - Push to branch (
git push origin feature/AmazingFeature) - Open Pull Request
This project is licensed under the MIT License.
- Your Name - Initial work
- Hidden Markov Model implementation using hmmlearn
- Flask framework for backend API
- React for frontend UI
- MongoDB for data storage
For issues and questions:
- Open an issue on GitHub
- Check DEPLOYMENT_GUIDE.md
- Review GITHUB_CHECKLIST.md
Made with β€οΈ for secure UPI transactions