Upload 5 files
Browse files- Dockerfile +19 -9
- app.py +73 -36
- modelo_cnn_tbc.h5 +3 -0
- modelo_cnn_tbc.json +1 -0
- requirements.txt +3 -3
Dockerfile
CHANGED
|
@@ -1,17 +1,27 @@
|
|
| 1 |
-
#
|
| 2 |
-
FROM python:3.10-slim
|
| 3 |
|
| 4 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
WORKDIR /app
|
| 6 |
|
| 7 |
-
# Copiar
|
| 8 |
-
|
|
|
|
| 9 |
|
| 10 |
-
# Instalar dependencias
|
| 11 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 12 |
|
| 13 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
EXPOSE 7860
|
| 15 |
|
| 16 |
-
#
|
| 17 |
-
|
|
|
|
|
|
| 1 |
+
# Dockerfile
|
|
|
|
| 2 |
|
| 3 |
+
# Usar una imagen base oficial de Python.
|
| 4 |
+
# 'slim' es una versión ligera, ideal para producción.
|
| 5 |
+
FROM python:3.9-slim
|
| 6 |
+
|
| 7 |
+
# Establecer el directorio de trabajo dentro del contenedor
|
| 8 |
WORKDIR /app
|
| 9 |
|
| 10 |
+
# Copiar el archivo de requerimientos primero para aprovechar el cache de Docker.
|
| 11 |
+
# Si los requerimientos no cambian, esta capa no se reconstruirá.
|
| 12 |
+
COPY requirements.txt .
|
| 13 |
|
| 14 |
+
# Instalar las dependencias de Python
|
| 15 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 16 |
|
| 17 |
+
# Copiar el resto de los archivos de la aplicación al directorio de trabajo.
|
| 18 |
+
# Esto incluye app.py y tu modelo .h5
|
| 19 |
+
COPY . .
|
| 20 |
+
|
| 21 |
+
# Exponer el puerto en el que se ejecutará la aplicación.
|
| 22 |
+
# Hugging Face Spaces espera que las apps escuchen en el puerto 7860.
|
| 23 |
EXPOSE 7860
|
| 24 |
|
| 25 |
+
# El comando para iniciar la aplicación cuando el contenedor se ejecute.
|
| 26 |
+
# --host 0.0.0.0 es crucial para que la app sea accesible desde fuera del contenedor.
|
| 27 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
app.py
CHANGED
|
@@ -1,48 +1,85 @@
|
|
| 1 |
-
|
| 2 |
-
from fastapi.responses import JSONResponse
|
| 3 |
-
from PIL import Image, ImageFilter, ImageOps
|
| 4 |
-
import numpy as np
|
| 5 |
-
import tensorflow as tf
|
| 6 |
-
import pickle
|
| 7 |
-
import io
|
| 8 |
-
|
| 9 |
-
# Cargar modelo y codificador
|
| 10 |
-
model = tf.keras.models.load_model("tbc_cnn_model.h5")
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
#
|
| 16 |
app = FastAPI(
|
| 17 |
-
title="
|
| 18 |
-
description="
|
| 19 |
version="1.0"
|
| 20 |
)
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
@app.post("/predict/")
|
| 34 |
async def predict(file: UploadFile = File(...)):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
try:
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
predicted_label = label_encoder.inverse_transform([predicted_index])[0]
|
| 40 |
-
confidence = float(np.max(prediction)) * 100
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
+
import io
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from fastapi import FastAPI, File, UploadFile
|
| 7 |
+
from fastapi.responses import JSONResponse
|
| 8 |
+
from tensorflow.keras.models import load_model
|
| 9 |
|
| 10 |
+
# Inicializar la aplicación FastAPI
|
| 11 |
app = FastAPI(
|
| 12 |
+
title="API de Clasificación de TBC",
|
| 13 |
+
description="Una API para clasificar radiografías de tórax como 'normal' o 'tbc' usando un modelo CNN.",
|
| 14 |
version="1.0"
|
| 15 |
)
|
| 16 |
|
| 17 |
+
# --- Carga del Modelo ---
|
| 18 |
+
# Cargar el modelo .h5 al iniciar la aplicación para que esté listo para las predicciones.
|
| 19 |
+
# Esto es mucho más eficiente que cargarlo en cada solicitud.
|
| 20 |
+
try:
|
| 21 |
+
model = load_model('modelo_cnn_tbc.h5')
|
| 22 |
+
print("Modelo cargado exitosamente.")
|
| 23 |
+
except Exception as e:
|
| 24 |
+
print(f"Error al cargar el modelo: {e}")
|
| 25 |
+
model = None
|
| 26 |
+
|
| 27 |
+
# Definir las constantes del modelo
|
| 28 |
+
IMG_HEIGHT = 150
|
| 29 |
+
IMG_WIDTH = 150
|
| 30 |
+
CLASS_NAMES = ["normal", "tbc"]
|
| 31 |
+
|
| 32 |
+
# --- Endpoints de la API ---
|
| 33 |
+
|
| 34 |
+
@app.get("/")
|
| 35 |
+
def read_root():
|
| 36 |
+
"""Endpoint raíz para verificar que la API está funcionando."""
|
| 37 |
+
return {"message": "Bienvenido a la API de Clasificación de TBC. Usa el endpoint /predict/ para hacer una predicción."}
|
| 38 |
|
| 39 |
@app.post("/predict/")
|
| 40 |
async def predict(file: UploadFile = File(...)):
|
| 41 |
+
"""
|
| 42 |
+
Endpoint para predecir si una radiografía es 'normal' o 'tbc'.
|
| 43 |
+
- Acepta un archivo de imagen (JPG, PNG, etc.).
|
| 44 |
+
- Devuelve la clase predicha y la confianza de la predicción.
|
| 45 |
+
"""
|
| 46 |
+
if not model:
|
| 47 |
+
return JSONResponse(status_code=500, content={"error": "El modelo no está cargado. Revisa los logs del servidor."})
|
| 48 |
+
|
| 49 |
+
# 1. Leer el contenido del archivo subido en memoria
|
| 50 |
+
contents = await file.read()
|
| 51 |
+
|
| 52 |
+
# 2. Convertir los bytes en una imagen PIL
|
| 53 |
try:
|
| 54 |
+
image = Image.open(io.BytesIO(contents)).convert('RGB')
|
| 55 |
+
except Exception as e:
|
| 56 |
+
return JSONResponse(status_code=400, content={"error": f"Archivo inválido. No se pudo procesar la imagen: {e}"})
|
|
|
|
|
|
|
| 57 |
|
| 58 |
+
# 3. Preprocesar la imagen para que coincida con la entrada del modelo
|
| 59 |
+
# Redimensionar la imagen
|
| 60 |
+
image = image.resize((IMG_WIDTH, IMG_HEIGHT))
|
| 61 |
+
# Convertir la imagen a un array de numpy
|
| 62 |
+
img_array = np.array(image)
|
| 63 |
+
# Normalizar los valores de los píxeles (de 0-255 a 0-1)
|
| 64 |
+
img_array = img_array / 255.0
|
| 65 |
+
# Añadir una dimensión de batch (el modelo espera una forma de [1, 150, 150, 3])
|
| 66 |
+
image_batch = np.expand_dims(img_array, axis=0)
|
| 67 |
|
| 68 |
+
# 4. Realizar la predicción
|
| 69 |
+
prediction = model.predict(image_batch)
|
| 70 |
+
score = prediction[0][0] # La salida de la sigmoide
|
| 71 |
+
|
| 72 |
+
# 5. Interpretar el resultado
|
| 73 |
+
if score > 0.5:
|
| 74 |
+
predicted_class = CLASS_NAMES[1] # 'tbc'
|
| 75 |
+
confidence = score
|
| 76 |
+
else:
|
| 77 |
+
predicted_class = CLASS_NAMES[0] # 'normal'
|
| 78 |
+
confidence = 1 - score
|
| 79 |
+
|
| 80 |
+
# 6. Devolver el resultado en formato JSON
|
| 81 |
+
return {
|
| 82 |
+
"filename": file.filename,
|
| 83 |
+
"prediction": predicted_class,
|
| 84 |
+
"confidence": float(confidence)
|
| 85 |
+
}
|
modelo_cnn_tbc.h5
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d1f2360569a7f3b20f133e0a2c896c3506ecbf98992647e6de86a9a6e0b306c4
|
| 3 |
+
size 228458584
|
modelo_cnn_tbc.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"module": "keras", "class_name": "Sequential", "config": {"name": "sequential", "trainable": true, "dtype": {"module": "keras", "class_name": "DTypePolicy", "config": {"name": "float32"}, "registered_name": null}, "layers": [{"module": "keras.layers", "class_name": "InputLayer", "config": {"batch_shape": [null, 150, 150, 3], "dtype": "float32", "sparse": false, "name": "input_layer"}, "registered_name": null}, {"module": "keras.layers", "class_name": "Conv2D", "config": {"name": "conv2d", "trainable": true, "dtype": {"module": "keras", "class_name": "DTypePolicy", "config": {"name": "float32"}, "registered_name": null}, "filters": 32, "kernel_size": [3, 3], "strides": [1, 1], "padding": "valid", "data_format": "channels_last", "dilation_rate": [1, 1], "groups": 1, "activation": "relu", "use_bias": true, "kernel_initializer": {"module": "keras.initializers", "class_name": "GlorotUniform", "config": {"seed": null}, "registered_name": null}, "bias_initializer": {"module": "keras.initializers", "class_name": "Zeros", "config": {}, "registered_name": null}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "registered_name": null, "build_config": {"input_shape": [null, 150, 150, 3]}}, {"module": "keras.layers", "class_name": "MaxPooling2D", "config": {"name": "max_pooling2d", "trainable": true, "dtype": {"module": "keras", "class_name": "DTypePolicy", "config": {"name": "float32"}, "registered_name": null}, "pool_size": [2, 2], "padding": "valid", "strides": [2, 2], "data_format": "channels_last"}, "registered_name": null}, {"module": "keras.layers", "class_name": "Conv2D", "config": {"name": "conv2d_1", "trainable": true, "dtype": {"module": "keras", "class_name": "DTypePolicy", "config": {"name": "float32"}, "registered_name": null}, "filters": 64, "kernel_size": [3, 3], "strides": [1, 1], "padding": "valid", "data_format": "channels_last", "dilation_rate": [1, 1], "groups": 1, "activation": "relu", "use_bias": true, "kernel_initializer": {"module": "keras.initializers", "class_name": "GlorotUniform", "config": {"seed": null}, "registered_name": null}, "bias_initializer": {"module": "keras.initializers", "class_name": "Zeros", "config": {}, "registered_name": null}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "registered_name": null, "build_config": {"input_shape": [null, 74, 74, 32]}}, {"module": "keras.layers", "class_name": "MaxPooling2D", "config": {"name": "max_pooling2d_1", "trainable": true, "dtype": {"module": "keras", "class_name": "DTypePolicy", "config": {"name": "float32"}, "registered_name": null}, "pool_size": [2, 2], "padding": "valid", "strides": [2, 2], "data_format": "channels_last"}, "registered_name": null}, {"module": "keras.layers", "class_name": "Conv2D", "config": {"name": "conv2d_2", "trainable": true, "dtype": {"module": "keras", "class_name": "DTypePolicy", "config": {"name": "float32"}, "registered_name": null}, "filters": 128, "kernel_size": [3, 3], "strides": [1, 1], "padding": "valid", "data_format": "channels_last", "dilation_rate": [1, 1], "groups": 1, "activation": "relu", "use_bias": true, "kernel_initializer": {"module": "keras.initializers", "class_name": "GlorotUniform", "config": {"seed": null}, "registered_name": null}, "bias_initializer": {"module": "keras.initializers", "class_name": "Zeros", "config": {}, "registered_name": null}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "registered_name": null, "build_config": {"input_shape": [null, 36, 36, 64]}}, {"module": "keras.layers", "class_name": "MaxPooling2D", "config": {"name": "max_pooling2d_2", "trainable": true, "dtype": {"module": "keras", "class_name": "DTypePolicy", "config": {"name": "float32"}, "registered_name": null}, "pool_size": [2, 2], "padding": "valid", "strides": [2, 2], "data_format": "channels_last"}, "registered_name": null}, {"module": "keras.layers", "class_name": "Flatten", "config": {"name": "flatten", "trainable": true, "dtype": {"module": "keras", "class_name": "DTypePolicy", "config": {"name": "float32"}, "registered_name": null}, "data_format": "channels_last"}, "registered_name": null, "build_config": {"input_shape": [null, 17, 17, 128]}}, {"module": "keras.layers", "class_name": "Dense", "config": {"name": "dense", "trainable": true, "dtype": {"module": "keras", "class_name": "DTypePolicy", "config": {"name": "float32"}, "registered_name": null}, "units": 512, "activation": "relu", "use_bias": true, "kernel_initializer": {"module": "keras.initializers", "class_name": "GlorotUniform", "config": {"seed": null}, "registered_name": null}, "bias_initializer": {"module": "keras.initializers", "class_name": "Zeros", "config": {}, "registered_name": null}, "kernel_regularizer": null, "bias_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "registered_name": null, "build_config": {"input_shape": [null, 36992]}}, {"module": "keras.layers", "class_name": "Dropout", "config": {"name": "dropout", "trainable": true, "dtype": {"module": "keras", "class_name": "DTypePolicy", "config": {"name": "float32"}, "registered_name": null}, "rate": 0.5, "seed": null, "noise_shape": null}, "registered_name": null}, {"module": "keras.layers", "class_name": "Dense", "config": {"name": "dense_1", "trainable": true, "dtype": {"module": "keras", "class_name": "DTypePolicy", "config": {"name": "float32"}, "registered_name": null}, "units": 1, "activation": "sigmoid", "use_bias": true, "kernel_initializer": {"module": "keras.initializers", "class_name": "GlorotUniform", "config": {"seed": null}, "registered_name": null}, "bias_initializer": {"module": "keras.initializers", "class_name": "Zeros", "config": {}, "registered_name": null}, "kernel_regularizer": null, "bias_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "registered_name": null, "build_config": {"input_shape": [null, 512]}}], "build_input_shape": [null, 150, 150, 3]}, "registered_name": null, "build_config": {"input_shape": [null, 150, 150, 3]}, "compile_config": {"optimizer": {"module": "keras.optimizers", "class_name": "Adam", "config": {"name": "adam", "learning_rate": 0.0010000000474974513, "weight_decay": null, "clipnorm": null, "global_clipnorm": null, "clipvalue": null, "use_ema": false, "ema_momentum": 0.99, "ema_overwrite_frequency": null, "loss_scale_factor": null, "gradient_accumulation_steps": null, "beta_1": 0.9, "beta_2": 0.999, "epsilon": 1e-07, "amsgrad": false}, "registered_name": null}, "loss": "binary_crossentropy", "loss_weights": null, "metrics": ["accuracy"], "weighted_metrics": null, "run_eagerly": false, "steps_per_execution": 1, "jit_compile": false}}
|
requirements.txt
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
|
|
| 1 |
fastapi
|
| 2 |
uvicorn
|
| 3 |
-
tensorflow
|
| 4 |
-
pillow
|
| 5 |
-
scikit-learn
|
| 6 |
numpy
|
|
|
|
| 7 |
python-multipart
|
|
|
|
| 1 |
+
# requirements.txt
|
| 2 |
fastapi
|
| 3 |
uvicorn
|
| 4 |
+
tensorflow-cpu
|
|
|
|
|
|
|
| 5 |
numpy
|
| 6 |
+
pillow
|
| 7 |
python-multipart
|