File size: 9,300 Bytes
03bcd34 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 | # Predictive Maintenance FastAPI
## 🚀 Quick Start
### 1. Install Dependencies
```bash
pip install -r requirements.txt
```
### 2. Run API Server
```bash
# Development mode with auto-reload
python main.py
# Or using uvicorn directly
uvicorn main:app --reload --host 0.0.0.0 --port 8000
```
### 3. Access API
- **HTML Test Interface**: Open `index.html` in browser (recommended for testing)
- **Interactive Docs**: http://localhost:8000/docs
- **ReDoc**: http://localhost:8000/redoc
- **Health Check**: http://localhost:8000/health
### 4. Quick Testing (Windows)
```bash
# Install dependencies
install_requirements.bat
# Start server
start_server.bat
# Open test interface
open_test_interface.bat
```
---
## 📡 API Endpoints
### 1. Single Prediction: `POST /predict`
**Request Body:**
```json
{
"machine_id": "M_L_01",
"air_temperature": 298.1,
"process_temperature": 308.6,
"rotational_speed": 1551,
"torque": 42.8,
"tool_wear": 0,
"type": "M"
}
```
**Response (Enhanced with Features & Anomaly Detection):**
```json
{
"machine_id": "M_L_01",
"timestamp": "2024-11-26T10:30:00.123456",
"prediction": "HEALTHY",
"confidence": 0.9234,
"diagnostics": {
"primary_cause": "Normal Operation",
"sensor_alert": "All parameters within optimal range. Health score: 100%.",
"recommended_action": "CONTINUE NORMAL OPERATION. Next scheduled maintenance as planned.",
"severity": "LOW"
},
"features": {
"Air_temp_K": 298.1,
"Process_temp_K": 308.6,
"Speed_rpm": 1551,
"Torque_Nm": 42.8,
"Tool_wear_min": 0,
"Tool_wear_hours": 0.0,
"Temperature_Diff": 10.5,
"Power_W": 6951.2,
"Type_Encoded": 1
},
"anomalies": [],
"overall_health": "🟢 EXCELLENT HEALTH - All systems operating optimally within normal parameters."
}
```
### 2. Batch Prediction (CSV Download): `POST /predict/batch`
**Request:**
- Upload CSV file (any size)
- **Flexible CSV Format** - accepts columns with:
- UPPERCASE/lowercase/MixedCase names
- Units in brackets: `air_temperature_[k]`, `Air Temperature [K]`, etc.
- Extra columns (will be ignored)
- Any column order
**Required Columns (flexible naming):**
- `air_temperature` or `air_temperature_[k]`
- `process_temperature` or `process_temperature_[k]`
- `rotational_speed` or `rotational_speed_[rpm]`
- `torque` or `torque_[nm]`
- `tool_wear` or `tool_wear_[min]`
- `type`
- Optional: `machine_id`
**Response:**
- CSV file download with added columns:
- `Prediction`: HEALTHY or FAILURE
- `Confidence`: 0.0 to 1.0
- `Primary_Cause`: Root cause analysis
- `Sensor_Alert`: Specific sensor readings
- `Recommended_Action`: Actionable maintenance advice
- `Severity`: LOW, MEDIUM, HIGH, CRITICAL
- `Processed_At`: Timestamp
### 3. Batch Prediction (JSON for UI): `POST /predict/batch/json`
**Request:**
- Upload CSV file (max 500 rows)
- Same flexible format as `/predict/batch`
**Response:**
```json
{
"summary": {
"total_records": 5,
"predictions": {
"failure": 2,
"healthy": 3,
"errors": 0
},
"failure_rate": 40.0
},
"results": [
{
"row_number": 1,
"machine_id": "M_001",
"prediction": "HEALTHY",
"confidence": 0.9234,
"diagnostics": {...},
"features": {...},
"anomalies": [...],
"overall_health": "🟢 EXCELLENT HEALTH",
"input_data": {...}
}
],
"processed_at": "2024-11-26T10:30:00"
}
```
---
## 🧠 Diagnostic Engine Rules
### Priority 1: CRITICAL
- **Tool Wear > 200 min**: Immediate tool replacement required
### Priority 2: HIGH
- **Power > 9000 W** or **Torque > 60 Nm**: Mechanical overload detected
- **ML Anomaly (Confidence > 80%)**: Unusual pattern detected
### Priority 3: MEDIUM
- **Temperature Diff < 8.0 K at Speed > 1300 RPM**: Cooling system issue
- **Temperature Diff > 15.0 K**: Excessive thermal stress
- **Speed > 2500 RPM**: High-speed operation risk
### Priority 4: LOW
- **All parameters normal**: Continue operation
---
## 🔬 Feature Engineering (Physics-Based)
The API automatically calculates:
1. **Temperature_Diff** = `process_temperature` - `air_temperature`
- Indicates thermal stress
- Optimal range: 8-12 K
2. **Power_W** = `torque` × `rotational_speed` × (2π / 60)
- Mechanical power output
- Safety limit: 9000 W
3. **Type_Encoded** = {L: 0, M: 1, H: 2}
- Machine type categorization
---
## 📊 Example cURL Commands
### Single Prediction
```bash
curl -X POST "http://localhost:8000/predict" \
-H "Content-Type: application/json" \
-d '{
"machine_id": "M_L_01",
"air_temperature": 298.1,
"process_temperature": 308.6,
"rotational_speed": 1551,
"torque": 42.8,
"tool_wear": 0,
"type": "M"
}'
```
### Batch Prediction
```bash
curl -X POST "http://localhost:8000/predict/batch" \
-F "file=@test_data.csv" \
-o predictions_output.csv
```
### Health Check
```bash
curl http://localhost:8000/health
```
### Model Info
```bash
curl http://localhost:8000/model/info
```
---
## 🛠️ Python Client Example
```python
import requests
import pandas as pd
# Single prediction
url = "http://localhost:8000/predict"
data = {
"machine_id": "M_L_01",
"air_temperature": 298.1,
"process_temperature": 308.6,
"rotational_speed": 1551,
"torque": 42.8,
"tool_wear": 0,
"type": "M"
}
response = requests.post(url, json=data)
result = response.json()
print(f"Prediction: {result['prediction']}")
print(f"Confidence: {result['confidence']}")
print(f"Action: {result['diagnostics']['recommended_action']}")
# Batch prediction
url_batch = "http://localhost:8000/predict/batch"
files = {'file': open('test_data.csv', 'rb')}
response = requests.post(url_batch, files=files)
with open('predictions.csv', 'wb') as f:
f.write(response.content)
```
---
## 📂 CSV Format for Batch Processing (FLEXIBLE!)
### ✅ Format 1: Simple (Recommended)
```csv
machine_id,air_temperature,process_temperature,rotational_speed,torque,tool_wear,type
M_L_01,298.1,308.6,1551,42.8,0,M
M_L_02,299.2,310.1,1450,38.5,150,L
M_H_01,297.5,312.8,1800,65.2,220,H
```
### ✅ Format 2: With Units (Dataset Format)
```csv
machine_id,air_temperature_[k],process_temperature_[k],rotational_speed_[rpm],torque_[nm],tool_wear_[min],type
M_L_01,298.1,308.6,1551,42.8,0,M
M_L_02,299.2,310.1,1450,38.5,150,L
```
### ✅ Format 3: Mixed Case with Spaces
```csv
Machine ID,Air Temperature [K],Process Temperature [K],Rotational Speed [RPM],Torque [Nm],Tool Wear [min],TYPE
M_L_01,298.1,308.6,1551,42.8,0,M
```
### ✅ Format 4: Extra Columns (Will be Ignored)
```csv
machine_id,timestamp,air_temperature,process_temperature,rotational_speed,torque,tool_wear,type,location,operator
M_L_01,2024-11-26,298.1,308.6,1551,42.8,0,M,Factory_A,John
```
**All formats above are automatically handled by the API!**
**Output CSV** (additional columns):
```csv
...,Prediction,Confidence,Primary_Cause,Sensor_Alert,Recommended_Action,Severity,Processed_At
...,HEALTHY,0.9234,Normal Operation,All parameters within optimal range...,CONTINUE NORMAL OPERATION...,LOW,2024-11-26T10:30:00
...,HEALTHY,0.8876,Normal Operation,All parameters within optimal range...,CONTINUE NORMAL OPERATION...,LOW,2024-11-26T10:30:01
...,FAILURE,0.9567,Tool End of Life,Tool wear (220 min) exceeds safety threshold...,IMMEDIATE ACTION: Replace cutting tool...,CRITICAL,2024-11-26T10:30:02
```
---
## 🔐 Production Deployment
### Environment Variables
```bash
export MODEL_PATH="/path/to/model_pipeline.joblib"
export API_HOST="0.0.0.0"
export API_PORT="8000"
export LOG_LEVEL="info"
```
### Docker Deployment
```dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
```
### Run with Gunicorn (Production)
```bash
pip install gunicorn
gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000
```
---
## 📈 Performance Metrics
- **Model**: RandomForest Classifier (Optimized with Ensemble)
- **Features**: 9 engineered features (including Tool_wear_hours)
- **F1-Score**: ~75-85% (after optimization)
- **Inference Time**: ~10-20ms per prediction
- **Batch Processing**:
- CSV Download: Unlimited rows
- JSON Response: Max 500 rows (for UI display)
- Throughput: ~100-200 records/second
- **Anomaly Detection**: 7 parameter checks (Real-time)
- **Overall Health Assessment**: 4 levels (EXCELLENT/GOOD/FAIR/POOR)
---
## 🐛 Troubleshooting
### Model Not Loading
```bash
# Check if model file exists
ls ../models/model_pipeline_improved.joblib
ls ../models/model_pipeline.joblib
# Verify model structure
python -c "import joblib; m = joblib.load('../models/model_pipeline.joblib'); print(m.keys())"
```
### CORS Issues
- Already configured for `allow_origins=["*"]`
- Modify in `main.py` if needed for specific domains
### Port Already in Use
```bash
# Change port in main.py or use:
uvicorn main:app --port 8001
```
---
## 📞 API Support
For issues or questions:
1. Check `/health` endpoint for model status
2. Review logs for detailed error messages
3. Validate input data matches schema in `/docs`
---
**Built with FastAPI 🚀 | Production-Ready | ML + Physics-Based Diagnostics**
|