import os import io import zipfile import numpy as np from PIL import Image from fastapi import FastAPI, File, UploadFile from fastapi.middleware.cors import CORSMiddleware import tensorflow as tf from ultralytics import YOLO app = FastAPI() # CORS supaya Flutter bisa akses app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # --- GLOBALS (lazy loaded) --- yolo_model = None interpreter = None input_details = None output_details = None def ensure_yolo_weights(): """ Pastikan file YOLO weights ada. Kalau di repo masih 'best.pt.zip', unzip jadi 'best.pt' """ if os.path.exists("best.pt"): return if os.path.exists("best.pt.zip"): print("Unzipping best.pt.zip -> best.pt ...") with zipfile.ZipFile("best.pt.zip", "r") as z: z.extractall(".") print("Unzip selesai.") if not os.path.exists("best.pt"): raise Exception("File YOLO weights tidak ditemukan. Upload 'best.pt' atau 'best.pt.zip' ke repo.") def load_tflite_interpreter(): """ Load TFLite interpreter dari file yang SUDAH ADA di repo. (Jangan convert dari .h5 di server) """ global interpreter, input_details, output_details if interpreter is not None: return tflite_path = "model_kadar_air.tflite" if not os.path.exists(tflite_path): raise Exception("model_kadar_air.tflite tidak ditemukan. Buat di lokal lalu upload ke repo HF.") print("Loading TFLite interpreter...") interpreter = tf.lite.Interpreter(model_path=tflite_path) interpreter.allocate_tensors() input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() print("TFLite loaded.") def load_yolo(): global yolo_model if yolo_model is not None: return ensure_yolo_weights() print("Loading YOLOv8...") yolo_model = YOLO("best.pt") # detect model print("YOLO loaded.") def load_all_models(): load_yolo() load_tflite_interpreter() @app.get("/") def root(): return {"status": "Online", "message": "API Smart Roasting Ready"} @app.post("/predict") async def predict(file: UploadFile = File(...)): try: # Lazy load (request pertama) load_all_models() # --- Baca gambar --- contents = await file.read() image = Image.open(io.BytesIO(contents)).convert("RGB") # --- 1) YOLO: hitung jumlah biji --- results = yolo_model(np.array(image), verbose=False) count = int(len(results[0].boxes)) # --- 2) TFLite CNN: prediksi kadar air --- # Sesuaikan input size model TFLite kamu: # Kalau CNN kamu inputnya 224x224 seperti di kode awal, biarkan 224 img_cnn = image.resize((224, 224)) img_array = np.expand_dims(np.array(img_cnn) / 255.0, axis=0).astype(np.float32) interpreter.set_tensor(input_details[0]["index"], img_array) interpreter.invoke() pred = interpreter.get_tensor(output_details[0]["index"]) kadar_air = float(pred[0][0]) return { "success": True, "jumlah_biji": count, "kadar_air": round(kadar_air, 2), "status": "Sukses", } except Exception as e: # Penting: tampilkan juga di logs HF biar gampang debug print("ERROR /predict:", repr(e)) return {"success": False, "error": str(e)}