waste-api / app.py
Mohamed-salah-dev's picture
Update app.py
c1ec9b2 verified
Raw
History Blame Contribute Delete
1.59 kB
import os
from fastapi import FastAPI, File, UploadFile
import tensorflow as tf
import numpy as np
from PIL import Image
import io
app = FastAPI()
ORIGINAL_FILE = "priority_model.bin"
MODEL_H5 = "model_fix.h5"
model = None
error_msg = "Starting..."
@app.on_event("startup")
def load_model():
global model, error_msg
try:
# ุชุญูˆูŠู„ bin ู„ู€ h5 ุนุดุงู† ู†ู‡ุฑุจ ู…ู† ุงู„ู€ Xet ูˆู†ุฑุถูŠ TensorFlow 2.15
if os.path.exists(ORIGINAL_FILE):
if os.path.exists(MODEL_H5): os.remove(MODEL_H5)
os.rename(ORIGINAL_FILE, MODEL_H5)
if os.path.exists(MODEL_H5):
model = tf.keras.models.load_model(MODEL_H5, compile=False)
error_msg = "None"
else:
error_msg = "Model file not found"
except Exception as e:
error_msg = str(e)
@app.get("/")
def home():
return {
"model_loaded": model is not None,
"tf_version": tf.__version__,
"error": error_msg
}
@app.post("/predict")
async def predict(file: UploadFile = File(...)):
if model is None: return {"error": "Model not loaded"}
contents = await file.read()
image = Image.open(io.BytesIO(contents)).convert("RGB").resize((224, 224))
img_array = np.array(image) / 255.0
img_array = np.expand_dims(img_array, axis=0).astype(np.float32)
predictions = model.predict(img_array)
classes = ["High Priority", "Low Priority", "Medium Priority"]
idx = np.argmax(predictions[0])
return {"prediction": classes[idx], "confidence": f"{float(predictions[0][idx])*100:.2f}%"}