Spaces:
Sleeping
Sleeping
Download app.py from fajarario/gemas-ml-api: direct link, hf CLI and curl.
- Browser
- Download file 3.07 kB
-
https://huggingface.co/spaces/fajarario/gemas-ml-api/resolve/main/app.py
- Command line
-
hf download hf://spaces/fajarario/gemas-ml-api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/fajarario/gemas-ml-api/resolve/main/app.py
3.07 kB
| import os | |
| import joblib | |
| import pandas as pd | |
| from fastapi import FastAPI, HTTPException | |
| from pydantic import BaseModel | |
| # =============================== | |
| # PATH MODEL | |
| # =============================== | |
| BASE_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| MODEL_PATH = os.path.join(BASE_DIR, "model", "model.pkl") | |
| ENCODER_PATH = os.path.join(BASE_DIR, "model", "encoders.pkl") | |
| # =============================== | |
| # LOAD MODEL | |
| # =============================== | |
| try: | |
| model = joblib.load(MODEL_PATH) | |
| encoders = joblib.load(ENCODER_PATH) | |
| except Exception as e: | |
| raise RuntimeError(f"Gagal load model atau encoder: {e}") | |
| # =============================== | |
| # FASTAPI APP | |
| # =============================== | |
| app = FastAPI( | |
| title="GEMAS ML Risk Prediction API", | |
| version="1.0.0", | |
| description="API untuk prediksi tingkat risiko kesehatan remaja berdasarkan hasil pemeriksaan." | |
| ) | |
| # =============================== | |
| # REQUEST BODY | |
| # =============================== | |
| class RiskPredictionRequest(BaseModel): | |
| umur: int | |
| jenis_kelamin: str | |
| imt_kategori: str | |
| tensi_kategori: str | |
| gula_kategori: str | |
| tbc_status: str | |
| heeadsss_status: str | |
| # =============================== | |
| # HELPER | |
| # =============================== | |
| FEATURES = [ | |
| "umur", | |
| "jenis_kelamin", | |
| "imt_kategori", | |
| "tensi_kategori", | |
| "gula_kategori", | |
| "tbc_status", | |
| "heeadsss_status" | |
| ] | |
| TARGET = "risk_level" | |
| def encode_input(data: dict): | |
| df = pd.DataFrame([data]) | |
| for col in FEATURES: | |
| if col not in encoders: | |
| raise HTTPException( | |
| status_code=500, | |
| detail=f"Encoder untuk kolom {col} tidak ditemukan." | |
| ) | |
| try: | |
| df[col] = encoders[col].transform(df[col]) | |
| except ValueError: | |
| allowed_values = encoders[col].classes_.tolist() | |
| raise HTTPException( | |
| status_code=422, | |
| detail={ | |
| "message": f"Nilai tidak valid untuk kolom {col}.", | |
| "input": data[col], | |
| "allowed_values": allowed_values | |
| } | |
| ) | |
| return df[FEATURES] | |
| # =============================== | |
| # ROUTES | |
| # =============================== | |
| def root(): | |
| return { | |
| "message": "GEMAS ML API aktif", | |
| "endpoint": "/predict-risk" | |
| } | |
| def health_check(): | |
| return { | |
| "status": "ok", | |
| "model_loaded": True | |
| } | |
| def predict_risk(payload: RiskPredictionRequest): | |
| input_data = payload.model_dump() | |
| encoded_df = encode_input(input_data) | |
| prediction_encoded = model.predict(encoded_df)[0] | |
| risk_level = encoders[TARGET].inverse_transform([prediction_encoded])[0] | |
| confidence = None | |
| if hasattr(model, "predict_proba"): | |
| probabilities = model.predict_proba(encoded_df)[0] | |
| confidence = float(max(probabilities)) | |
| return { | |
| "risk_level": risk_level, | |
| "confidence": round(confidence, 4) if confidence is not None else None | |
| } |