CoolFace
Apppublic

pylord/API-BFSI

sourceHugging Faceupdated 11mo agoView on Hugging Face
0likes
README copy.md394 linesDownload Raw Back to root
1# ๐Ÿ›ก๏ธ RiskShield - Fraud Detection API2 3Professional fraud detection system using hybrid ML and rule-based approach.4 5## ๐Ÿš€ Features6 7- **Hybrid Fraud Detection**: Combines CatBoost ML model with rule-based system8- **User Authentication**: Secure registration and login9- **Transaction Prediction**: Real-time fraud detection with risk scoring10- **Transaction History**: Complete audit trail per user11- **Analytics Dashboard**: Comprehensive fraud analytics and visualizations12- **Model Metrics**: Performance monitoring and feature importance13 14## ๐Ÿ“‹ Prerequisites15 16- Python 3.8+17- PostgreSQL 12+18- pip (Python package manager)19 20## ๐Ÿ”ง Installation21 22### 1. Clone the Repository23 24```bash25git clone <repository-url>26cd riskshield27```28 29### 2. Create Virtual Environment30 31```bash32python -m venv venv33 34# On Windows35venv\Scripts\activate36 37# On Linux/Mac38source venv/bin/activate39```40 41### 3. Install Dependencies42 43```bash44pip install -r requirements.txt45```46 47### 4. Setup PostgreSQL Database48 49```sql50-- Connect to PostgreSQL51psql -U postgres52 53-- Create database54CREATE DATABASE "RiskShield";55 56-- Create user (if not exists)57CREATE USER admin WITH PASSWORD 'admin123';58 59-- Grant privileges60GRANT ALL PRIVILEGES ON DATABASE "RiskShield" TO admin;61```62 63### 5. Update Database Configuration64 65Edit `database.py` with your PostgreSQL credentials:66 67```python68DB_USER = "admin"69DB_PASSWORD = "admin123"70DB_HOST = "localhost"71DB_PORT = "5432"72DB_NAME = "RiskShield"73```74 75### 6. Create Model Directory76 77```bash78mkdir model79# Place your trained CatBoost model file here:80# model/catboost_fraud_model_balanced_tuned.cbm81```82 83## ๐Ÿƒ Running the Application84 85### Start the Server86 87```bash88# Development mode (with auto-reload)89uvicorn main:app --reload --host 0.0.0.0 --port 800090 91# Or using Python92python main.py93```94 95The API will be available at: `http://localhost:8000`96 97### Access API Documentation98 99- **Swagger UI**: http://localhost:8000/docs100- **ReDoc**: http://localhost:8000/redoc101 102## ๐Ÿ“ก API Endpoints103 104### Authentication105 106#### Register User107```http108POST /api/register109Content-Type: application/json110 111{112  "full_name": "John Doe",113  "email": "john.doe@example.com",114  "password": "securepass123"115}116```117 118#### Login119```http120POST /api/login121Content-Type: application/json122 123{124  "email": "john.doe@example.com",125  "password": "securepass123"126}127```128 129### Fraud Detection130 131#### Predict Transaction132```http133POST /api/predict134Content-Type: application/json135 136{137  "email": "john.doe@example.com",138  "customer_id": "CUST12345",139  "transaction_id": "TXN98765",140  "transaction_datetime": "2025-01-15 14:30:00",141  "transaction_amount": 75000.50,142  "kyc_verified": 1,143  "account_age_days": 180,144  "channel_encoded": 0145}146```147 148**Response:**149```json150{151  "status": "success",152  "message": "Prediction completed successfully",153  "data": {154    "prediction_id": 123,155    "user": "John Doe",156    "model_risk_score": 0.7234,157    "rule_score": 0.15,158    "combined_score": 0.8734,159    "is_fraud": 1,160    "rules_triggered": [161      "High amount transaction (>โ‚น100K)"162    ],163    "derived_features": {...},164    "explanation": "โš ๏ธ This transaction has been flagged...",165    "timestamp": "2025-01-15T14:30:00"166  }167}168```169 170### Transaction History171 172#### Get User Transactions173```http174GET /api/transactions/{email}175```176 177### Analytics178 179#### Get Dashboard Analytics180```http181GET /api/analytics182```183 184**Response includes:**185- **KPIs**: Total transactions, fraud detected, accuracy rate, amount protected186- **Graphs**: 187  - Fraud vs Legitimate bar chart data188  - Monthly fraud rate trend189  - Fraud distribution by channel190  - Amount vs risk score scatter plot191 192### Model Performance193 194#### Get Model Metrics195```http196GET /api/metrics197```198 199**Returns:**200- Model accuracy, precision, recall, F1-score201- Confusion matrix202- Feature importance203- Performance summary204 205## ๐Ÿ“Š Channel Encoding206 207| Code | Channel |208|------|---------|209| 0    | Online  |210| 1    | ATM     |211| 2    | POS     |212| 3    | Mobile  |213 214## ๐ŸŽฏ Risk Scoring215 216- **Combined Score** = Model Probability + Rule Score217- **Fraud Threshold**: โ‰ฅ 0.6218- **Risk Levels**:219  - 0.0 - 0.3: Low Risk220  - 0.3 - 0.6: Medium Risk221  - 0.6 - 0.8: High Risk222  - 0.8 - 1.0: Critical Risk223 224## ๐Ÿ” Rule-Based Detection225 226The system implements the following fraud rules:227 2281. **High Amount**: Transaction > โ‚น100,000 (+0.2 score)2292. **Night Transaction**: Large amount during 10 PM - 6 AM (+0.2 score)2303. **New Unverified Account**: Age < 10 days + No KYC (+0.25 score)2314. **Weekend High-Value**: Weekend transaction > โ‚น80,000 (+0.15 score)2325. **Holiday Risk**: Holiday transaction > โ‚น70,000 (+0.1 score)2336. **Repeated High-Risk**: 3+ high-risk transactions in 1 hour (+0.3 score)234 235## ๐Ÿ—„๏ธ Database Schema236 237### Users Table238- email (Primary Key)239- full_name240- password (hashed)241- created_at242 243### Predictions Table244- id (Primary Key)245- customer_id246- transaction_id (Unique)247- email (Foreign Key)248- risk_score249- is_fraud250- derived_features (JSON)251- explanation (Text)252- timestamp253 254## ๐Ÿงช Testing255 256### Using curl257 258```bash259# Health check260curl http://localhost:8000/api/health261 262# Register user263curl -X POST http://localhost:8000/api/register \264  -H "Content-Type: application/json" \265  -d '{"full_name":"Test User","email":"test@example.com","password":"test123"}'266 267# Predict transaction268curl -X POST http://localhost:8000/api/predict \269  -H "Content-Type: application/json" \270  -d '{271    "email": "test@example.com",272    "customer_id": "C001",273    "transaction_id": "T001",274    "transaction_datetime": "2025-01-15 14:30:00",275    "transaction_amount": 50000,276    "kyc_verified": 1,277    "account_age_days": 90,278    "channel_encoded": 0279  }'280```281 282### Using Python requests283 284```python285import requests286 287BASE_URL = "http://localhost:8000"288 289# Register290response = requests.post(f"{BASE_URL}/api/register", json={291    "full_name": "Test User",292    "email": "test@example.com",293    "password": "test123"294})295print(response.json())296 297# Predict298response = requests.post(f"{BASE_URL}/api/predict", json={299    "email": "test@example.com",300    "customer_id": "C001",301    "transaction_id": "T001",302    "transaction_datetime": "2025-01-15 14:30:00",303    "transaction_amount": 50000,304    "kyc_verified": 1,305    "account_age_days": 90,306    "channel_encoded": 0307})308print(response.json())309```310 311## ๐Ÿ› Troubleshooting312 313### Database Connection Issues314 315```bash316# Check PostgreSQL is running317sudo systemctl status postgresql318 319# Test connection320psql -U admin -d RiskShield -h localhost321```322 323### Model Loading Issues324 325- Ensure the model file exists at `model/catboost_fraud_model_balanced_tuned.cbm`326- Check file permissions327- Verify CatBoost version compatibility328 329### Port Already in Use330 331```bash332# Kill process on port 8000333# Linux/Mac334lsof -ti:8000 | xargs kill -9335 336# Windows337netstat -ano | findstr :8000338taskkill /PID <PID> /F339```340 341## ๐Ÿ“ˆ Performance342 343- **Average Response Time**: < 200ms344- **Throughput**: 100+ requests/second345- **Model Inference**: < 50ms346- **Database Query**: < 100ms347 348## ๐Ÿ”’ Security Best Practices349 3501. **Change Default Credentials**: Update database credentials in production3512. **Use Environment Variables**: Store sensitive data in `.env` file3523. **Enable HTTPS**: Use SSL certificates in production3534. **Rate Limiting**: Implement API rate limiting3545. **Input Validation**: All inputs are validated using Pydantic3556. **Password Hashing**: Passwords are hashed using bcrypt356 357## ๐Ÿ“ Environment Variables358 359Create a `.env` file:360 361```env362DB_USER=admin363DB_PASSWORD=admin123364DB_HOST=localhost365DB_PORT=5432366DB_NAME=RiskShield367MODEL_PATH=model/catboost_fraud_model_balanced_tuned.cbm368SECRET_KEY=your-secret-key-here369```370 371## ๐Ÿค Contributing372 3731. Fork the repository3742. Create feature branch (`git checkout -b feature/NewFeature`)3753. Commit changes (`git commit -m 'Add NewFeature'`)3764. Push to branch (`git push origin feature/NewFeature`)3775. Open Pull Request378 379## ๐Ÿ“„ License380 381This project is licensed under the MIT License.382 383## ๐Ÿ‘ฅ Support384 385For issues and questions:386- Create an issue on GitHub387- Email: support@riskshield.com388 389## ๐Ÿ™ Acknowledgments390 391- CatBoost for the ML framework392- FastAPI for the web framework393- PostgreSQL for database394- HuggingFace for NLP capabilities