aephidayatuloh commited on
Commit
3606d66
·
verified ·
1 Parent(s): 989d8d6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -31
app.py CHANGED
@@ -9,13 +9,16 @@ from huggingface_hub import hf_hub_download
9
  # --- KONFIGURASI HF HUB ---
10
  HF_REPO_ID = "aephidayatuloh/bank-model"
11
  HF_MODEL_FILENAME = "random_forest_bank_marketing_pipeline.joblib"
 
12
 
13
- # --- DEFINISI DATA INPUT (Pydantic) ---
14
- # [Pastikan ini sama persis dengan yang Anda gunakan sebelumnya]
15
- class PredictionInput(BaseModel):
 
16
  age: int
17
  balance: int
18
  day: int
 
19
  campaign: int
20
  pdays: int
21
  previous: int
@@ -28,43 +31,32 @@ class PredictionInput(BaseModel):
28
  contact: str
29
  month: str
30
  poutcome: str
 
31
 
32
- # --- SETUP MODEL (DIJALANKAN SEKALI SAAT STARTUP) ---
33
- app = FastAPI(title="Bank Deposit Prediction (Docker)")
34
-
35
- @app.on_event("startup")
36
- def load_model():
37
- global MODEL_PIPELINE
38
- try:
39
- # Download model dari HF Hub (direkomendasikan)
40
- downloaded_model_path = hf_hub_download(
41
- repo_id=HF_REPO_ID,
42
- filename=HF_MODEL_FILENAME
43
- )
44
- MODEL_PIPELINE = joblib.load(downloaded_model_path)
45
- print("✅ Model berhasil dimuat dari Hugging Face Hub.")
46
- except Exception as e:
47
- print(f"❌ Gagal memuat model: {e}")
48
- MODEL_PIPELINE = None
49
-
50
-
51
- # --- ENDPOINT PREDIKSI ---
52
-
53
- @app.get("/")
54
- def home():
55
- return {"status": "ok", "message": "FastAPI is running inside Docker on HF Spaces."}
56
 
 
57
  @app.post("/predict")
58
- def predict(data: PredictionInput):
 
 
59
  if MODEL_PIPELINE is None:
60
  raise HTTPException(status_code=500, detail="Model gagal dimuat.")
61
 
62
  try:
63
- input_df = pd.DataFrame([data.dict()])
64
-
 
 
 
 
65
  prediction = MODEL_PIPELINE.predict(input_df)[0]
66
  prediction_proba = MODEL_PIPELINE.predict_proba(input_df)[0].tolist()
67
-
68
  return {
69
  "prediction_class": int(prediction),
70
  "probability": prediction_proba
 
9
  # --- KONFIGURASI HF HUB ---
10
  HF_REPO_ID = "aephidayatuloh/bank-model"
11
  HF_MODEL_FILENAME = "random_forest_bank_marketing_pipeline.joblib"
12
+ # app.py (atau index.py)
13
 
14
+ # --- 1. Definisi Skema Fitur (Data Mentah) ---
15
+ # Model ini mendefinisikan struktur objek yang ada di dalam key "features"
16
+ class FeaturesSchema(BaseModel):
17
+ """Skema Pydantic untuk data fitur internal."""
18
  age: int
19
  balance: int
20
  day: int
21
+ duration: int
22
  campaign: int
23
  pdays: int
24
  previous: int
 
31
  contact: str
32
  month: str
33
  poutcome: str
34
+ # Pastikan semua 15 fitur ada di sini, sesuai urutan.
35
 
36
+ # --- 2. Definisi Skema Payload (Wrapper) ---
37
+ # Model ini mendefinisikan struktur payload keseluruhan (yang memiliki key "features")
38
+ class PredictionPayload(BaseModel):
39
+ """Skema Pydantic untuk payload yang dikirim."""
40
+ features: FeaturesSchema # 💡 PERUBAHAN UTAMA DI SINI
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
+ # --- 3. Perubahan pada Endpoint ---
43
  @app.post("/predict")
44
+ # Ganti nama model input di endpoint dari 'PredictionInput' menjadi 'PredictionPayload'
45
+ def predict(payload_data: PredictionPayload):
46
+
47
  if MODEL_PIPELINE is None:
48
  raise HTTPException(status_code=500, detail="Model gagal dimuat.")
49
 
50
  try:
51
+ # 💡 PERUBAHAN PADA PENGAMBILAN DATA
52
+ # Ambil data fitur dari wrapper 'payload_data'
53
+ input_dict = payload_data.features.dict()
54
+ input_df = pd.DataFrame([input_dict])
55
+
56
+ # ... sisa kode prediksi tetap sama ...
57
  prediction = MODEL_PIPELINE.predict(input_df)[0]
58
  prediction_proba = MODEL_PIPELINE.predict_proba(input_df)[0].tolist()
59
+
60
  return {
61
  "prediction_class": int(prediction),
62
  "probability": prediction_proba