kauzan25 commited on
Commit
563e0f2
·
verified ·
1 Parent(s): 0f68da3

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +15 -15
app.py CHANGED
@@ -1,9 +1,8 @@
1
  import gradio as gr
2
  import pickle
3
  import pandas as pd
4
- import xgboost as xgb
5
 
6
- # 1. Load Model Bundle XGBoost
7
  with open("best_model_xgb.pkl", "rb") as f:
8
  bundle = pickle.load(f)
9
 
@@ -11,30 +10,31 @@ model = bundle['model']
11
  impute_col = bundle['impute_col']
12
  feature_names = bundle['feature_names']
13
 
14
- # 2. Fungsi Prediksi untuk API
15
- def predict_api(*args):
16
- # Mapping input ke dictionary berdasarkan nama fitur
17
- input_data = dict(zip(feature_names, args))
18
- df = pd.DataFrame([input_data])
19
 
20
- # Handle missing values berdasarkan impute_col
 
 
 
21
  for col in impute_col:
22
  if pd.isna(df[col].iloc[0]):
23
- df[col] = 0 # Sesuaikan dengan nilai imputasi jika dibutuhkan
24
 
25
- # Prediksi dengan XGBoost
26
  prediction = model.predict(df)
27
  return float(prediction[0])
28
 
29
  # 3. Setup UI Gradio
30
- inputs = [gr.Number(label=col) for col in feature_names]
31
-
32
  app = gr.Interface(
33
  fn=predict_api,
34
- inputs=inputs,
35
  outputs=gr.Number(label="Hasil Prediksi"),
36
- title="NutriSnapS XGBoost Prediction API",
37
- api_name="predict_kidney" # Endpoint API sudah disesuaikan
38
  )
39
 
40
  if __name__ == "__main__":
 
1
  import gradio as gr
2
  import pickle
3
  import pandas as pd
 
4
 
5
+ # 1. Load Model
6
  with open("best_model_xgb.pkl", "rb") as f:
7
  bundle = pickle.load(f)
8
 
 
10
  impute_col = bundle['impute_col']
11
  feature_names = bundle['feature_names']
12
 
13
+ # 2. Fungsi Prediksi yang Menerima 1 JSON (Dictionary)
14
+ def predict_api(input_dict):
15
+ # Langsung ubah dictionary yang diterima dari mobile ke DataFrame
16
+ df = pd.DataFrame([input_dict])
 
17
 
18
+ # Pastikan urutan kolom sesuai dengan yang diharapkan XGBoost
19
+ df = df.reindex(columns=feature_names)
20
+
21
+ # Handle missing values
22
  for col in impute_col:
23
  if pd.isna(df[col].iloc[0]):
24
+ df[col] = 0 # Sesuaikan logika imputasi
25
 
26
+ # Eksekusi
27
  prediction = model.predict(df)
28
  return float(prediction[0])
29
 
30
  # 3. Setup UI Gradio
31
+ # Kita ganti inputs menjadi gr.JSON agar API menerima dictionary utuh
 
32
  app = gr.Interface(
33
  fn=predict_api,
34
+ inputs=gr.JSON(label="Input Data (JSON)"),
35
  outputs=gr.Number(label="Hasil Prediksi"),
36
+ title="NutriSnapS XGBoost API",
37
+ api_name="predict_kidney"
38
  )
39
 
40
  if __name__ == "__main__":