Update app.py
Browse files
app.py
CHANGED
|
@@ -29,12 +29,13 @@ def add_headers(response):
|
|
| 29 |
def index():
|
| 30 |
return jsonify({
|
| 31 |
"status": "ok",
|
| 32 |
-
"message": "
|
| 33 |
"endpoints": [
|
| 34 |
"POST /api/forecast",
|
| 35 |
"POST /api/health/classify",
|
| 36 |
"POST /api/coffee/forecast",
|
| 37 |
"POST /api/coffee/menu-analysis",
|
|
|
|
| 38 |
"POST /api/lottery/analyze"
|
| 39 |
]
|
| 40 |
})
|
|
@@ -360,6 +361,215 @@ def coffee_menu_analysis():
|
|
| 360 |
import traceback; print(traceback.format_exc())
|
| 361 |
return jsonify({"error": str(e)}), 500
|
| 362 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
if __name__ == "__main__":
|
| 364 |
port = int(os.environ.get("PORT", 7860))
|
| 365 |
app.run(host="0.0.0.0", port=port)
|
|
|
|
| 29 |
def index():
|
| 30 |
return jsonify({
|
| 31 |
"status": "ok",
|
| 32 |
+
"message": "AI Analytics API — Forecast Hub",
|
| 33 |
"endpoints": [
|
| 34 |
"POST /api/forecast",
|
| 35 |
"POST /api/health/classify",
|
| 36 |
"POST /api/coffee/forecast",
|
| 37 |
"POST /api/coffee/menu-analysis",
|
| 38 |
+
"POST /api/hr/classify",
|
| 39 |
"POST /api/lottery/analyze"
|
| 40 |
]
|
| 41 |
})
|
|
|
|
| 361 |
import traceback; print(traceback.format_exc())
|
| 362 |
return jsonify({"error": str(e)}), 500
|
| 363 |
|
| 364 |
+
# ─────────────────────────────────────
|
| 365 |
+
# POST /api/hr/classify
|
| 366 |
+
# พยากรณ์การลาออกของพนักงาน
|
| 367 |
+
# models: logistic | random_forest | xgboost | all
|
| 368 |
+
# ─────────────────────────────────────
|
| 369 |
+
@app.route("/api/hr/classify", methods=["POST", "OPTIONS"])
|
| 370 |
+
def hr_classify():
|
| 371 |
+
if request.method == "OPTIONS":
|
| 372 |
+
return jsonify({}), 200
|
| 373 |
+
try:
|
| 374 |
+
import time
|
| 375 |
+
t0 = time.time()
|
| 376 |
+
body = request.get_json()
|
| 377 |
+
data = body.get("data", [])
|
| 378 |
+
model_type = body.get("model", "xgboost").lower()
|
| 379 |
+
|
| 380 |
+
if len(data) < 10:
|
| 381 |
+
return jsonify({"error": "ต้องการข้อมูลอย่างน้อย 10 แถว"}), 400
|
| 382 |
+
|
| 383 |
+
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
|
| 384 |
+
from sklearn.linear_model import LogisticRegression
|
| 385 |
+
from sklearn.preprocessing import StandardScaler
|
| 386 |
+
from sklearn.pipeline import Pipeline
|
| 387 |
+
from sklearn.model_selection import train_test_split
|
| 388 |
+
from sklearn.metrics import (accuracy_score, recall_score,
|
| 389 |
+
precision_score, f1_score, roc_auc_score)
|
| 390 |
+
|
| 391 |
+
df = pd.DataFrame(data)
|
| 392 |
+
|
| 393 |
+
# ── Required columns ──
|
| 394 |
+
num_features = [
|
| 395 |
+
'age', 'years_at_company', 'years_in_current_role',
|
| 396 |
+
'salary_thb', 'salary_hike_pct', 'distance_from_home_km',
|
| 397 |
+
'overtime_hours_monthly', 'monthly_absent_days',
|
| 398 |
+
'satisfaction_score', 'performance_rating', 'num_projects',
|
| 399 |
+
'training_hours_yearly', 'promotion_last_3years',
|
| 400 |
+
'work_life_balance', 'job_involvement', 'manager_rating'
|
| 401 |
+
]
|
| 402 |
+
cat_features = ['department', 'gender', 'education']
|
| 403 |
+
all_features = num_features + cat_features
|
| 404 |
+
|
| 405 |
+
missing = [c for c in num_features if c not in df.columns]
|
| 406 |
+
if missing:
|
| 407 |
+
return jsonify({"error": f"Missing columns: {missing}"}), 400
|
| 408 |
+
|
| 409 |
+
# ── Fill missing categoricals ──
|
| 410 |
+
for c in cat_features:
|
| 411 |
+
if c not in df.columns:
|
| 412 |
+
df[c] = 'Unknown'
|
| 413 |
+
|
| 414 |
+
# ── Encode ──
|
| 415 |
+
df_enc = pd.get_dummies(df[all_features + (['resigned'] if 'resigned' in df.columns else [])],
|
| 416 |
+
columns=cat_features)
|
| 417 |
+
feature_cols = [c for c in df_enc.columns if c != 'resigned']
|
| 418 |
+
|
| 419 |
+
has_label = 'resigned' in df.columns
|
| 420 |
+
X = df_enc[feature_cols].fillna(0)
|
| 421 |
+
y = df_enc['resigned'].astype(int) if has_label else None
|
| 422 |
+
|
| 423 |
+
# ── Train/Test split ──
|
| 424 |
+
if has_label and len(df) >= 20:
|
| 425 |
+
from sklearn.model_selection import train_test_split
|
| 426 |
+
X_train, X_test, y_train, y_test = train_test_split(
|
| 427 |
+
X, y, test_size=0.2, random_state=42,
|
| 428 |
+
stratify=y if y.sum() >= 2 else None)
|
| 429 |
+
else:
|
| 430 |
+
X_train, X_test = X, X
|
| 431 |
+
y_train = y if has_label else pd.Series([0]*len(X))
|
| 432 |
+
y_test = y_train
|
| 433 |
+
|
| 434 |
+
results = {}
|
| 435 |
+
models_to_run = ['logistic', 'random_forest', 'xgboost'] if model_type == 'all' else [model_type]
|
| 436 |
+
|
| 437 |
+
for m_name in models_to_run:
|
| 438 |
+
if m_name == 'logistic':
|
| 439 |
+
clf = Pipeline([('scaler', StandardScaler()),
|
| 440 |
+
('clf', LogisticRegression(max_iter=1000, random_state=42))])
|
| 441 |
+
label = 'Logistic Regression'
|
| 442 |
+
elif m_name == 'random_forest':
|
| 443 |
+
clf = RandomForestClassifier(n_estimators=100, random_state=42)
|
| 444 |
+
label = 'Random Forest'
|
| 445 |
+
else:
|
| 446 |
+
clf = GradientBoostingClassifier(n_estimators=100, random_state=42)
|
| 447 |
+
label = 'XGBoost'
|
| 448 |
+
|
| 449 |
+
clf.fit(X_train, y_train)
|
| 450 |
+
y_pred = clf.predict(X_test)
|
| 451 |
+
y_prob = clf.predict_proba(X_test)[:, 1]
|
| 452 |
+
|
| 453 |
+
perf = {
|
| 454 |
+
"accuracy_pct": round(accuracy_score(y_test, y_pred)*100, 1),
|
| 455 |
+
"recall_pct": round(recall_score(y_test, y_pred, zero_division=0)*100, 1),
|
| 456 |
+
"precision_pct": round(precision_score(y_test, y_pred, zero_division=0)*100, 1),
|
| 457 |
+
"f1_pct": round(f1_score(y_test, y_pred, zero_division=0)*100, 1),
|
| 458 |
+
"auc": round(roc_auc_score(y_test, y_prob) if len(y_test.unique()) > 1 else 0.5, 3)
|
| 459 |
+
} if has_label else {}
|
| 460 |
+
|
| 461 |
+
# Feature importance
|
| 462 |
+
if hasattr(clf, 'feature_importances_'):
|
| 463 |
+
fi = sorted(zip(feature_cols, clf.feature_importances_),
|
| 464 |
+
key=lambda x: x[1], reverse=True)[:10]
|
| 465 |
+
elif hasattr(clf, 'named_steps'):
|
| 466 |
+
coef = clf.named_steps['clf'].coef_[0]
|
| 467 |
+
fi = sorted(zip(feature_cols, abs(coef)),
|
| 468 |
+
key=lambda x: x[1], reverse=True)[:10]
|
| 469 |
+
else:
|
| 470 |
+
fi = []
|
| 471 |
+
|
| 472 |
+
# Predict all rows
|
| 473 |
+
all_probs = clf.predict_proba(X)[:, 1]
|
| 474 |
+
results[m_name] = {
|
| 475 |
+
"model_name": label,
|
| 476 |
+
"performance": perf,
|
| 477 |
+
"feature_importance": [{"feature": k, "importance": round(float(v), 4)}
|
| 478 |
+
for k, v in fi],
|
| 479 |
+
}
|
| 480 |
+
|
| 481 |
+
# ── Best model predictions ──
|
| 482 |
+
best_model_name = model_type if model_type != 'all' else 'xgboost'
|
| 483 |
+
if best_model_name not in results:
|
| 484 |
+
best_model_name = list(results.keys())[0]
|
| 485 |
+
|
| 486 |
+
# Re-train best model on full data for predictions
|
| 487 |
+
if best_model_name == 'logistic':
|
| 488 |
+
best_clf = Pipeline([('scaler', StandardScaler()),
|
| 489 |
+
('clf', LogisticRegression(max_iter=1000, random_state=42))])
|
| 490 |
+
elif best_model_name == 'random_forest':
|
| 491 |
+
best_clf = RandomForestClassifier(n_estimators=100, random_state=42)
|
| 492 |
+
else:
|
| 493 |
+
best_clf = GradientBoostingClassifier(n_estimators=100, random_state=42)
|
| 494 |
+
|
| 495 |
+
best_clf.fit(X_train, y_train)
|
| 496 |
+
all_probs = best_clf.predict_proba(X)[:, 1]
|
| 497 |
+
all_preds = best_clf.predict(X)
|
| 498 |
+
|
| 499 |
+
# ── Employee predictions ──
|
| 500 |
+
predictions = []
|
| 501 |
+
for i, (_, row) in enumerate(df.iterrows()):
|
| 502 |
+
prob = float(all_probs[i])
|
| 503 |
+
risk = 'High' if prob >= 0.6 else 'Medium' if prob >= 0.3 else 'Low'
|
| 504 |
+
predictions.append({
|
| 505 |
+
"employee_id": str(row.get('employee_id', f'EMP{i:04d}')),
|
| 506 |
+
"department": str(row.get('department', '')),
|
| 507 |
+
"position": str(row.get('position', '')),
|
| 508 |
+
"resign_probability": round(prob, 3),
|
| 509 |
+
"risk_level": risk,
|
| 510 |
+
"actual_resigned": int(row['resigned']) if 'resigned' in row else None,
|
| 511 |
+
"key_factors": {
|
| 512 |
+
"satisfaction_score": float(row.get('satisfaction_score', 0)),
|
| 513 |
+
"overtime_hours": float(row.get('overtime_hours_monthly', 0)),
|
| 514 |
+
"salary_thb": float(row.get('salary_thb', 0)),
|
| 515 |
+
"years_at_company": float(row.get('years_at_company', 0))
|
| 516 |
+
}
|
| 517 |
+
})
|
| 518 |
+
|
| 519 |
+
# Risk summary
|
| 520 |
+
high = sum(1 for p in predictions if p['risk_level'] == 'High')
|
| 521 |
+
medium = sum(1 for p in predictions if p['risk_level'] == 'Medium')
|
| 522 |
+
low = sum(1 for p in predictions if p['risk_level'] == 'Low')
|
| 523 |
+
|
| 524 |
+
# Department risk
|
| 525 |
+
dept_risk = {}
|
| 526 |
+
for p in predictions:
|
| 527 |
+
dept = p['department']
|
| 528 |
+
if dept not in dept_risk:
|
| 529 |
+
dept_risk[dept] = {'count': 0, 'high_risk': 0, 'total_prob': 0}
|
| 530 |
+
dept_risk[dept]['count'] += 1
|
| 531 |
+
dept_risk[dept]['total_prob'] += p['resign_probability']
|
| 532 |
+
if p['risk_level'] == 'High':
|
| 533 |
+
dept_risk[dept]['high_risk'] += 1
|
| 534 |
+
dept_summary = [
|
| 535 |
+
{"department": dept,
|
| 536 |
+
"total": v['count'],
|
| 537 |
+
"high_risk": v['high_risk'],
|
| 538 |
+
"avg_resign_prob": round(v['total_prob']/v['count']*100, 1)}
|
| 539 |
+
for dept, v in sorted(dept_risk.items(),
|
| 540 |
+
key=lambda x: x[1]['high_risk'], reverse=True)
|
| 541 |
+
]
|
| 542 |
+
|
| 543 |
+
elapsed = round(time.time()-t0, 1)
|
| 544 |
+
print(f"✅ hr/classify: {len(df)}คน model={model_type} high={high} t={elapsed}s")
|
| 545 |
+
|
| 546 |
+
return jsonify({
|
| 547 |
+
"total_employees": len(df),
|
| 548 |
+
"model_requested": model_type,
|
| 549 |
+
"processing_time_sec": elapsed,
|
| 550 |
+
"risk_summary": {
|
| 551 |
+
"high_risk": high,
|
| 552 |
+
"medium_risk": medium,
|
| 553 |
+
"low_risk": low,
|
| 554 |
+
"high_risk_pct": round(high/len(df)*100, 1)
|
| 555 |
+
},
|
| 556 |
+
"department_summary": dept_summary,
|
| 557 |
+
"model_results": results,
|
| 558 |
+
"best_model": best_model_name,
|
| 559 |
+
"predictions": sorted(predictions,
|
| 560 |
+
key=lambda x: x['resign_probability'],
|
| 561 |
+
reverse=True),
|
| 562 |
+
"top_at_risk": sorted(predictions,
|
| 563 |
+
key=lambda x: x['resign_probability'],
|
| 564 |
+
reverse=True)[:10],
|
| 565 |
+
"disclaimer": "ผลการพยากรณ์ใช้เพื่อสนับสนุนการตัดสินใจ HR เท่านั้น"
|
| 566 |
+
})
|
| 567 |
+
|
| 568 |
+
except Exception as e:
|
| 569 |
+
import traceback; print(traceback.format_exc())
|
| 570 |
+
return jsonify({"error": str(e)}), 500
|
| 571 |
+
|
| 572 |
+
|
| 573 |
if __name__ == "__main__":
|
| 574 |
port = int(os.environ.get("PORT", 7860))
|
| 575 |
app.run(host="0.0.0.0", port=port)
|