Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,122 +6,76 @@ import os
|
|
| 6 |
|
| 7 |
# Inisialisasi aplikasi Flask
|
| 8 |
app = Flask(__name__)
|
| 9 |
-
CORS(app)
|
| 10 |
-
|
| 11 |
-
# --- TAHAP 1:
|
| 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 |
-
# --- TAHAP 2: ENDPOINT PREDIKSI
|
| 37 |
-
# Ini adalah inti dari API Anda.
|
| 38 |
@app.route('/predict', methods=['POST'])
|
| 39 |
-
def predict():
|
| 40 |
-
|
| 41 |
-
if not all([model, scaler, jk_encoder, stunting_encoder]):
|
| 42 |
-
return jsonify({"error": "Satu atau lebih file model gagal dimuat di server"}), 500
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
try:
|
| 45 |
-
# 1. Ambil data JSON yang dikirim oleh React
|
| 46 |
data = request.get_json()
|
| 47 |
-
|
| 48 |
-
# React HARUS mengirim JSON dengan key yang SAMA PERSIS seperti ini:
|
| 49 |
-
# {
|
| 50 |
-
# "jenis_kelamin": "Laki-laki", // (atau "Perempuan")
|
| 51 |
-
# "umur": 24, // (angka)
|
| 52 |
-
# "tinggi": 85.5, // (angka)
|
| 53 |
-
# "berat": 10.1 // (angka)
|
| 54 |
-
# }
|
| 55 |
-
|
| 56 |
-
# --- MULAI PREPROCESSING ---
|
| 57 |
-
# Kita harus mengulang langkah yang sama persis seperti saat training
|
| 58 |
-
|
| 59 |
-
# 2. Ambil data mentah dari JSON
|
| 60 |
jk_string = data['jenis_kelamin']
|
| 61 |
umur = data['umur']
|
| 62 |
tinggi = data['tinggi']
|
| 63 |
berat = data['berat']
|
| 64 |
|
| 65 |
-
# 3. ENCODE 'Jenis Kelamin' (String -> Angka)
|
| 66 |
-
# Input: ["Laki-laki"] -> Output: [0]
|
| 67 |
-
# Kita ambil elemen pertama [0] untuk mendapatkan angkanya saja
|
| 68 |
jk_encoded = jk_encoder.transform([jk_string])[0]
|
| 69 |
-
|
| 70 |
-
# 4. SCALE Fitur Numerik (Angka -> Angka Skala 0-1)
|
| 71 |
-
# Scaler dilatih dengan urutan: ['Umur (bulan)', 'Tinggi Badan (cm)', 'Berat Badan (kg)']
|
| 72 |
-
# Kita harus memasukkan data dengan urutan yang SAMA PERSIS.
|
| 73 |
-
# Input harus 2D array, contoh: [[24, 85.5, 10.1]]
|
| 74 |
numerical_features = [[umur, tinggi, berat]]
|
| 75 |
scaled_features = scaler.transform(numerical_features)
|
| 76 |
|
| 77 |
-
# Outputnya adalah 2D array, contoh: [[0.25, 0.4, 0.3]]
|
| 78 |
-
# Kita ambil baris pertama [0]
|
| 79 |
umur_scaled = scaled_features[0][0]
|
| 80 |
tinggi_scaled = scaled_features[0][1]
|
| 81 |
berat_scaled = scaled_features[0][2]
|
| 82 |
|
| 83 |
-
# 5. GABUNGKAN SEMUA FITUR
|
| 84 |
-
# Model utama dilatih dengan urutan:
|
| 85 |
-
# ['Jenis Kelamin', 'Umur (bulan)', 'Tinggi Badan (cm)', 'Berat Badan (kg)']
|
| 86 |
-
# Kita gabungkan fitur yg sudah di-encode dan di-scale sesuai urutan itu
|
| 87 |
-
|
| 88 |
final_features_list = [jk_encoded, umur_scaled, tinggi_scaled, berat_scaled]
|
| 89 |
-
|
| 90 |
-
# 6. Ubah jadi 2D Numpy Array
|
| 91 |
-
# Sesuai format yang diterima model .predict()
|
| 92 |
final_features = [np.array(final_features_list)]
|
| 93 |
|
| 94 |
-
# --- SELESAI PREPROCESSING ---
|
| 95 |
-
|
| 96 |
-
# 7. Lakukan Prediksi
|
| 97 |
-
# Input: [[0, 0.25, 0.4, 0.3]]
|
| 98 |
prediction_encoded = model.predict(final_features)
|
| 99 |
-
# Output: [1] (Contoh)
|
| 100 |
-
|
| 101 |
-
# 8. UBAH PREDIKSI (Angka -> String)
|
| 102 |
-
# Kita pakai stunting_encoder untuk mengubah angka hasil prediksi
|
| 103 |
-
# kembali menjadi label string yang bisa dibaca manusia.
|
| 104 |
-
# Input: [1] -> Output: ["Stunted"]
|
| 105 |
prediction_string = stunting_encoder.inverse_transform(prediction_encoded)
|
| 106 |
|
| 107 |
-
|
| 108 |
-
output = prediction_string[0] # "Stunted"
|
| 109 |
-
|
| 110 |
-
# 10. Kirim hasil akhir ke React
|
| 111 |
return jsonify({'prediction': output})
|
| 112 |
|
| 113 |
except KeyError as e:
|
| 114 |
-
|
| 115 |
-
# (misal: "nama" bukan "jenis_kelamin")
|
| 116 |
-
return jsonify({"error": f"Key JSON tidak ditemukan: {str(e)}. Pastikan key adalah 'jenis_kelamin', 'umur', 'tinggi', dan 'berat'."}), 400
|
| 117 |
-
|
| 118 |
except Exception as e:
|
| 119 |
-
# Tangkap error lainnya (misal: user kirim "Pria" bukan "Laki-laki")
|
| 120 |
return jsonify({"error": f"Terjadi error saat prediksi: {str(e)}"}), 400
|
| 121 |
|
| 122 |
-
# ---
|
| 123 |
-
# (
|
| 124 |
-
|
| 125 |
if __name__ == '__main__':
|
| 126 |
-
port = int(os.environ.get('PORT',
|
| 127 |
-
app.run(
|
|
|
|
| 6 |
|
| 7 |
# Inisialisasi aplikasi Flask
|
| 8 |
app = Flask(__name__)
|
| 9 |
+
CORS(app)
|
| 10 |
+
|
| 11 |
+
# --- TAHAP 1: KOSONGKAN AREA GLOBAL ---
|
| 12 |
+
# JANGAN LOAD MODEL DI SINI.
|
| 13 |
+
# Kita buat variabelnya saja, tapi isinya 'None' (kosong)
|
| 14 |
+
# Ini membuat server NYALA INSTAN.
|
| 15 |
+
model = None
|
| 16 |
+
scaler = None
|
| 17 |
+
jk_encoder = None
|
| 18 |
+
stunting_encoder = None
|
| 19 |
+
|
| 20 |
+
# Fungsi untuk memuat model (hanya akan dipanggil 1x)
|
| 21 |
+
def load_models():
|
| 22 |
+
global model, scaler, jk_encoder, stunting_encoder
|
| 23 |
+
try:
|
| 24 |
+
if model is None: # Cek, jika masih kosong, baru di-load
|
| 25 |
+
print("Mencoba memuat model untuk PERTAMA KALI...")
|
| 26 |
+
model = joblib.load("best_model.joblib")
|
| 27 |
+
scaler = joblib.load("scaler.joblib")
|
| 28 |
+
jk_encoder = joblib.load("Jenis Kelamin_encoder.joblib")
|
| 29 |
+
stunting_encoder = joblib.load("Stunting_encoder.joblib")
|
| 30 |
+
print("Semua 4 model berhasil dimuat!")
|
| 31 |
+
return True
|
| 32 |
+
except Exception as e:
|
| 33 |
+
print(f"Error saat memuat model: {e}")
|
| 34 |
+
return False
|
| 35 |
|
| 36 |
+
# --- TAHAP 2: ENDPOINT PREDIKSI ---
|
|
|
|
| 37 |
@app.route('/predict', methods=['POST'])
|
| 38 |
+
def predict():
|
| 39 |
+
global model, scaler, jk_encoder, stunting_encoder
|
|
|
|
|
|
|
| 40 |
|
| 41 |
+
# Panggil fungsi load_models.
|
| 42 |
+
# Jika model belum di-load, dia akan di-load sekarang.
|
| 43 |
+
# Jika sudah, dia akan dilewati.
|
| 44 |
+
if not load_models():
|
| 45 |
+
return jsonify({"error": "Model gagal dimuat di server. Cek logs."}), 500
|
| 46 |
+
|
| 47 |
+
# ... (Sisa kodenya SAMA PERSIS) ...
|
| 48 |
try:
|
|
|
|
| 49 |
data = request.get_json()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
jk_string = data['jenis_kelamin']
|
| 51 |
umur = data['umur']
|
| 52 |
tinggi = data['tinggi']
|
| 53 |
berat = data['berat']
|
| 54 |
|
|
|
|
|
|
|
|
|
|
| 55 |
jk_encoded = jk_encoder.transform([jk_string])[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
numerical_features = [[umur, tinggi, berat]]
|
| 57 |
scaled_features = scaler.transform(numerical_features)
|
| 58 |
|
|
|
|
|
|
|
| 59 |
umur_scaled = scaled_features[0][0]
|
| 60 |
tinggi_scaled = scaled_features[0][1]
|
| 61 |
berat_scaled = scaled_features[0][2]
|
| 62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
final_features_list = [jk_encoded, umur_scaled, tinggi_scaled, berat_scaled]
|
|
|
|
|
|
|
|
|
|
| 64 |
final_features = [np.array(final_features_list)]
|
| 65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
prediction_encoded = model.predict(final_features)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
prediction_string = stunting_encoder.inverse_transform(prediction_encoded)
|
| 68 |
|
| 69 |
+
output = prediction_string[0]
|
|
|
|
|
|
|
|
|
|
| 70 |
return jsonify({'prediction': output})
|
| 71 |
|
| 72 |
except KeyError as e:
|
| 73 |
+
return jsonify({"error": f"Key JSON tidak ditemukan: {str(e)}."}), 400
|
|
|
|
|
|
|
|
|
|
| 74 |
except Exception as e:
|
|
|
|
| 75 |
return jsonify({"error": f"Terjadi error saat prediksi: {str(e)}"}), 400
|
| 76 |
|
| 77 |
+
# --- TAHAP 3: SERVER RUN ---
|
| 78 |
+
# (Ini sudah benar, JANGAN DIUBAH)
|
|
|
|
| 79 |
if __name__ == '__main__':
|
| 80 |
+
port = int(os.environ.get('PORT', 7860))
|
| 81 |
+
app.run(host="0.0.0.0", port=port, debug=False)
|