Spaces:
Sleeping
Sleeping
File size: 6,342 Bytes
6a4d3bb 6ec31d7 6a4d3bb 6ec31d7 6a4d3bb 54965eb 6a4d3bb 8ab4cd9 6a4d3bb 9b02ce5 6a4d3bb 9b02ce5 6a4d3bb | 1 2 3 4 5 6 7 8 9 10 11 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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.middleware.cors import CORSMiddleware
import tensorflow as tf
import joblib
import numpy as np
from PIL import Image
import io
# 1. Inisialisasi Backend FastAPI dengan Dokumentasi Otomatis
app = FastAPI(
title="API Manajemen Sampah & TPA - 3 Model AI",
description="API tunggal untuk melayani 3 model AI: Klasifikasi Sampah (CNN), Clustering TPA (K-Means), dan Prediksi Emisi Metana (Linear Regression).",
version="1.0.0"
)
# === TAMBAHKAN CORS TEPAT DI SINI (Setelah app dibuat) ===
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 2. Status model disiapkan di awal agar endpoint bisa memberi respons jelas jika startup gagal
MODEL_CNN = None
MODEL_KMEANS = None
SCALER_TPA = None
MODEL_REGRESSION = None
# 3. Optimasi (Lazy Loading): Memuat semua file model dan scaler sekali saja di awal (Global Scope)
try:
MODEL_CNN = tf.keras.models.load_model("models/waste_classifier_cnn.h5")
MODEL_KMEANS = joblib.load("models/clustering_tpa_model.pkl")
SCALER_TPA = joblib.load("models/scaler_tpa.pkl")
MODEL_REGRESSION = joblib.load("models/methane_regression_model.pkl")
print("🚀 SUKSES: Semua 3 model AI dan Scaler berhasil dimuat ke memori server!")
except Exception as e:
print(f"❌ ERROR: Gagal memuat file model. Periksa folder 'models/'. Detail: {e}")
@app.get("/", tags=["Main Route"])
def root():
return {
"status": "Online",
"message": "API Layanan 3 Model AI (Sampah, TPA, & Metana) aktif dan siap digunakan!"
}
@app.get("/health", tags=["Main Route"])
def health_check():
models_loaded = all(
model is not None
for model in (MODEL_CNN, MODEL_KMEANS, SCALER_TPA, MODEL_REGRESSION)
)
return {
"status": "ok" if models_loaded else "degraded",
"models_loaded": models_loaded
}
# ================= MODEL 1: CNN (KLASIFIKASI JENIS SAMPAH) =================
@app.post("/predict-cnn", tags=["1. Waste Classification (CNN)"])
async def predict_cnn(file: UploadFile = File(...)):
"""
Endpoint untuk mengklasifikasikan jenis sampah berdasarkan input gambar.
Menerima file gambar (.jpg / .png).
"""
if file.content_type not in ["image/jpeg", "image/png"]:
raise HTTPException(status_code=400, detail="Format file tidak didukung. Harus berupa JPG atau PNG.")
if MODEL_CNN is None:
raise HTTPException(status_code=503, detail="Model CNN belum siap di server.")
try:
# Membaca data gambar yang diunggah
image_bytes = await file.read()
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
# Pengujian & Pemrosesan Input: Ubah ukuran ke 150x150 sesuai spesifikasi training kamu
image = image.resize((224, 224))
image_array = np.array(image) / 255.0 # Normalisasi nilai pixel gambar
image_array = np.expand_dims(image_array, axis=0) # Ubah matriks dimensi menjadi (1, 150, 150, 3)
# Eksekusi Prediksi CNN
predictions = MODEL_CNN.predict(image_array)
pred_class = int(np.argmax(predictions, axis=1)[0])
confidence = float(np.max(predictions))
return {
"success": True,
"model_type": "Convolutional Neural Network (CNN)",
"result": {
"predicted_class_index": pred_class,
"confidence_score": round(confidence, 4)
}
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Gagal memproses gambar pada model CNN: {str(e)}")
# ================= MODEL 2: K-MEANS (CLUSTERING TPA) =================
@app.post("/predict-kmeans", tags=["2. TPA Clustering (K-Means)"])
def predict_kmeans(features: list[float]):
"""
Endpoint untuk melakukan clustering/pengelompokan kondisi TPA.
Masukkan data array numerik linear (fitur) sesuai dengan variabel saat training.
Contoh JSON Input Body: [0.45, 1.2, 3.44, 0.12]
"""
try:
if MODEL_KMEANS is None or SCALER_TPA is None:
raise HTTPException(status_code=503, detail="Model K-Means atau scaler belum siap di server.")
# Konversi list data input menjadi array 2D
data_array = np.array([features])
# Jalankan SCALER terlebih dahulu menggunakan data_array
scaled_data = SCALER_TPA.transform(data_array)
# Pengujian Input: Lakukan transformasi normalisasi menggunakan Scaler bawaan training
scaled_data_4_features = scaled_data[:, :4]
# Eksekusi Prediksi Cluster K-Means
assigned_cluster = int(MODEL_KMEANS.predict(scaled_data_4_features)[0])
return {
"success": True,
"model_type": "K-Means Clustering",
"result": {
"assigned_cluster": assigned_cluster
}
}
except Exception as e:
raise HTTPException(status_code=400, detail=f"Format input salah atau jumlah fitur tidak cocok dengan scaler/model: {str(e)}")
# ================= MODEL 3: LINEAR REGRESSION (PREDIKSI GAS METANA) =================
@app.post("/predict-regression", tags=["3. Methane Emission Prediction (Linear Regression)"])
def predict_regression(features: list[float]):
"""
Endpoint untuk memprediksi volume emisi gas metana secara kontinu.
Masukkan data fitur angka numerik linier sebagai input.
Contoh JSON Input Body: [25.5, 400.0, 12.3]
"""
try:
if MODEL_REGRESSION is None:
raise HTTPException(status_code=503, detail="Model regresi belum siap di server.")
# Konversi input list menjadi array 2D untuk scikit-learn
data_array = np.array([features])
# Eksekusi Prediksi Linear Regression
regression_result = MODEL_REGRESSION.predict(data_array)
predicted_value = float(regression_result[0])
return {
"success": True,
"model_type": "Linear Regression",
"result": {
"predicted_methane_value": round(predicted_value, 4)
}
}
except Exception as e:
raise HTTPException(status_code=400, detail=f"Format input salah atau tidak sesuai dengan model regresi: {str(e)}") |