Spaces:
Sleeping
Sleeping
Download main.py from Riceunjae/Project_TPA_AI: direct link, hf CLI and curl.
- Browser
- Download file 6.34 kB
-
https://huggingface.co/spaces/Riceunjae/Project_TPA_AI/resolve/main/main.py
- Command line
-
hf download hf://spaces/Riceunjae/Project_TPA_AI/main.py
-
curl -L -o main.py https://huggingface.co/spaces/Riceunjae/Project_TPA_AI/resolve/main/main.py
6.34 kB
| 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}") | |
| def root(): | |
| return { | |
| "status": "Online", | |
| "message": "API Layanan 3 Model AI (Sampah, TPA, & Metana) aktif dan siap digunakan!" | |
| } | |
| 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) ================= | |
| 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) ================= | |
| 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) ================= | |
| 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)}") |