Spaces:
Sleeping
Sleeping
File size: 8,337 Bytes
c72db2d | 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 381 | # API Testing Guide
คู่มือการทดสอบ API สำหรับ Job Failure Prediction & Anomaly Detection
## 🚀 วิธีที่ 1: ใช้ Test Script (แนะนำ)
### Local Testing
```bash
# Test API ที่รันบน localhost:8000 (default)
python test_api.py
# Test API ที่รันบน localhost:7860 (Hugging Face Spaces port)
python test_api.py --port 7860
# Test API ที่ URL เฉพาะ
python test_api.py --url http://localhost:8000
```
### Hugging Face Spaces Testing
```bash
# Test API บน Hugging Face Spaces
python test_api.py --url https://your-username-your-space.hf.space
```
---
## 🧪 วิธีที่ 2: ใช้ cURL
### Health Check
```bash
# Local
curl http://localhost:8000/health
# Hugging Face Spaces
curl https://your-username-your-space.hf.space/health
```
### Job Failure Prediction
```bash
# Local
curl -X POST http://localhost:8000/predict/job-fail \
-H "Content-Type: application/json" \
-d '{
"zone": "prod",
"job_nm": "daily_export_customer",
"job_start_time": "2026-01-21T01:00:00",
"duration_sec": 5400,
"status": "SUCCESS",
"err_msg": "",
"explain": true
}'
# Hugging Face Spaces
curl -X POST https://your-username-your-space.hf.space/predict/job-fail \
-H "Content-Type: application/json" \
-d '{
"zone": "prod",
"job_nm": "daily_export_customer",
"job_start_time": "2026-01-21T01:00:00",
"duration_sec": 5400,
"status": "SUCCESS",
"explain": true
}'
```
### Anomaly Detection
```bash
# Local
curl -X POST http://localhost:8000/detect/anomaly \
-H "Content-Type: application/json" \
-d '{
"features": {
"duration_sec": 5400,
"duration_zscore": 1.6,
"avg_duration_7": 3000,
"failure_rate_7": 0.15,
"err_msg_len": 0,
"hour_sin": 0.2588,
"hour_cos": 0.9659
},
"threshold": 0.01
}'
# Hugging Face Spaces
curl -X POST https://your-username-your-space.hf.space/detect/anomaly \
-H "Content-Type: application/json" \
-d '{
"features": {
"duration_sec": 5400,
"duration_zscore": 1.6,
"avg_duration_7": 3000,
"failure_rate_7": 0.15,
"err_msg_len": 0
}
}'
```
---
## 🌐 วิธีที่ 3: ใช้ Swagger UI (Interactive)
### Local
1. เริ่ม API server:
```bash
uvicorn app:app --host 0.0.0.0 --port 8000
```
2. เปิด browser ไปที่:
```
http://localhost:8000/docs
```
3. ทดสอบ endpoints ผ่าน interactive UI
### Hugging Face Spaces
1. ไปที่ Space page
2. คลิก "API" tab หรือไปที่:
```
https://your-username-your-space.hf.space/docs
```
3. ทดสอบ endpoints ผ่าน interactive UI
---
## 📝 วิธีที่ 4: ใช้ Python Requests
### Example Script
```python
import requests
import json
# Base URL
BASE_URL = "http://localhost:8000" # หรือ URL ของ Hugging Face Space
# Test Health
response = requests.get(f"{BASE_URL}/health")
print("Health Check:", response.json())
# Test Prediction
payload = {
"zone": "prod",
"job_nm": "daily_export",
"job_start_time": "2026-01-21T01:00:00",
"duration_sec": 5400,
"status": "SUCCESS",
"explain": True
}
response = requests.post(
f"{BASE_URL}/predict/job-fail",
json=payload
)
print("Prediction:", response.json())
# Test Anomaly Detection
payload = {
"features": {
"duration_sec": 5400,
"duration_zscore": 1.6,
"err_msg_len": 0
}
}
response = requests.post(
f"{BASE_URL}/detect/anomaly",
json=payload
)
print("Anomaly Detection:", response.json())
```
---
## 🔍 วิธีที่ 5: ใช้ Postman / Insomnia
### Import Collection
1. สร้าง new collection
2. เพิ่ม requests:
**Health Check**
- Method: `GET`
- URL: `http://localhost:8000/health`
**Job Failure Prediction**
- Method: `POST`
- URL: `http://localhost:8000/predict/job-fail`
- Headers: `Content-Type: application/json`
- Body (JSON):
```json
{
"zone": "prod",
"job_nm": "daily_export",
"job_start_time": "2026-01-21T01:00:00",
"duration_sec": 5400,
"status": "SUCCESS",
"explain": true
}
```
**Anomaly Detection**
- Method: `POST`
- URL: `http://localhost:8000/detect/anomaly`
- Headers: `Content-Type: application/json`
- Body (JSON):
```json
{
"features": {
"duration_sec": 5400,
"duration_zscore": 1.6,
"err_msg_len": 0
}
}
```
---
## ✅ Expected Responses
### Health Check Response
```json
{
"status": "healthy",
"service": "job-failure-prediction",
"models_loaded": {
"predictor": true,
"anomaly_detector": true
}
}
```
### Job Failure Prediction Response
```json
{
"fail_probability": 0.79,
"risk_level": "MEDIUM",
"top_drivers": [
{
"feature": "failure_rate_7",
"shap_value": 0.30,
"effect": "increase"
}
],
"recommended_actions": [
"Monitor upstream dependencies and recent job history"
]
}
```
### Anomaly Detection Response
```json
{
"reconstruction_error": 0.0235,
"is_anomaly": true,
"threshold": 0.01,
"top_drivers": [
{
"feature": "duration_zscore",
"error": 0.0142
}
]
}
```
---
## 🐛 Troubleshooting
### Connection Error
**ปัญหา:** `ConnectionError: Could not connect to API`
**แก้ไข:**
- ตรวจสอบว่า API server กำลังรันอยู่
- ตรวจสอบ URL และ port
- ตรวจสอบ firewall settings
### 404 Not Found
**ปัญหา:** `404 Not Found`
**แก้ไข:**
- ตรวจสอบ endpoint path (`/health`, `/predict/job-fail`, `/detect/anomaly`)
- ตรวจสอบว่า API server รันอยู่
### 500 Internal Server Error
**ปัญหา:** `500 Internal Server Error`
**แก้ไข:**
- ตรวจสอบ logs ของ API server
- ตรวจสอบว่า models ถูก load ถูกต้อง
- ตรวจสอบ request payload format
### Models Not Loaded
**ปัญหา:** `models_loaded: {"predictor": false, "anomaly_detector": false}`
**แก้ไข:**
- ตรวจสอบว่า models อยู่ใน `models/` directory
- ตรวจสอบว่า model files มีครบถ้วน
- ตรวจสอบ logs สำหรับ error messages
---
## 📊 Test Cases
### Test Case 1: Basic Health Check
```bash
curl http://localhost:8000/health
```
**Expected:** Status 200, models_loaded = true
### Test Case 2: Prediction with Minimal Data
```bash
curl -X POST http://localhost:8000/predict/job-fail \
-H "Content-Type: application/json" \
-d '{"job_nm": "test_job", "job_start_time": "2026-01-21T01:00:00"}'
```
**Expected:** Status 200, fail_probability between 0-1
### Test Case 3: Prediction with Full Data
```bash
curl -X POST http://localhost:8000/predict/job-fail \
-H "Content-Type: application/json" \
-d '{
"zone": "prod",
"job_nm": "daily_export",
"job_start_time": "2026-01-21T01:00:00",
"duration_sec": 5400,
"status": "SUCCESS",
"explain": true
}'
```
**Expected:** Status 200, includes top_drivers and recommended_actions
### Test Case 4: Anomaly Detection
```bash
curl -X POST http://localhost:8000/detect/anomaly \
-H "Content-Type: application/json" \
-d '{
"features": {
"duration_sec": 10000,
"duration_zscore": 3.0,
"err_msg_len": 0
}
}'
```
**Expected:** Status 200, is_anomaly = true (for high zscore)
---
## 🎯 Quick Test Checklist
- [ ] Health endpoint returns 200
- [ ] Models are loaded (check health response)
- [ ] Prediction endpoint accepts requests
- [ ] Prediction returns valid probability (0-1)
- [ ] Risk level is one of: MINIMAL, LOW, MEDIUM, CRITICAL
- [ ] SHAP explanations work (when explain=true)
- [ ] Anomaly detection accepts feature dict
- [ ] Anomaly detection returns is_anomaly boolean
- [ ] Error handling works (invalid requests return 422/500)
- [ ] CORS works (if testing from browser)
---
## 📚 Additional Resources
- **Swagger UI**: `/docs` - Interactive API documentation
- **ReDoc**: `/redoc` - Alternative API documentation
- **OpenAPI Schema**: `/openapi.json` - Machine-readable API schema
|