coba / app.py
adamrizz's picture
Upload 4 files
59090ae verified
from fastapi import FastAPI, UploadFile, File
from fastapi.responses import JSONResponse
import tensorflow as tf
import numpy as np
from PIL import Image
import io
app = FastAPI()
interpreter = tf.lite.Interpreter(model_path="daun_padi_cnn_model.tflite")
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
CLASS_NAMES = [
"Bacterial Leaf Blight", "Leaf Blast", "Leaf Scald",
"Brown Spot", "Narrow Brown Spot", "Healthy"
]
@app.post("/predict")
async def predict(file: UploadFile = File(...)):
image = Image.open(io.BytesIO(await file.read())).convert("RGB")
image = image.resize((150, 150))
img_array = np.expand_dims(np.array(image), axis=0).astype(np.float32) / 255.0
interpreter.set_tensor(input_details[0]['index'], img_array)
interpreter.invoke()
prediction = interpreter.get_tensor(output_details[0]['index'])[0]
predicted_index = int(np.argmax(prediction))
predicted_label = CLASS_NAMES[predicted_index]
confidence = float(np.max(prediction))
return JSONResponse({
"label": predicted_label,
"confidence": round(confidence, 4),
"probabilities": {
CLASS_NAMES[i]: round(float(pred), 4) for i, pred in enumerate(prediction)
}
})