tesisapi / app.py
AntonyUWU's picture
Update app.py
f2bea7c verified
Raw History Blame Contribute Delete
1.42 kB
from fastapi import FastAPI, File, UploadFile
import numpy as np
import tensorflow as tf
import keras
from PIL import Image
from io import BytesIO
from fastapi.middleware.cors import CORSMiddleware
import time
app = FastAPI()
app.title = "API de prueba"
app.version = "0.0.1"
origins = ["*"]
clases = ["Industria", "Golpeada", "Partida"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Cargar el modelo una vez
model = keras.saving.load_model("models/modelo_fin_effi.keras")
@app.get("/")
def api_home():
return {'detail': 'Tesis Uvillas'}
@app.post("/analyze")
async def analyze(file: UploadFile = File(...)):
image = await file.read()
return predecir(image)
def predecir(imagen):
start_time = time.time()
image = Image.open(BytesIO(imagen))
image = image.resize((96, 96))
input_arr = keras.utils.img_to_array(image)
input_arr = np.array([input_arr])
predictions = model.predict(input_arr)
end_time = time.time()
prediction_time = end_time - start_time
predicted_class = clases[np.argmax(predictions[0])]
prediction_percentages = {clase: float(pred) * 100 for clase, pred in zip(clases, predictions[0])}
return {
'clase_predicha': predicted_class,
'porcentajes_de_precisión': prediction_percentages,
'time':prediction_time
}