axelbm29 commited on
Commit
0eec46c
·
verified ·
1 Parent(s): 9747d51

Upload 5 files

Browse files
Files changed (5) hide show
  1. Dockerfile +19 -9
  2. app.py +73 -36
  3. modelo_cnn_tbc.h5 +3 -0
  4. modelo_cnn_tbc.json +1 -0
  5. requirements.txt +3 -3
Dockerfile CHANGED
@@ -1,17 +1,27 @@
1
- # Imagen base ligera
2
- FROM python:3.10-slim
3
 
4
- # Crear directorio de trabajo
 
 
 
 
5
  WORKDIR /app
6
 
7
- # Copiar archivos
8
- COPY . .
 
9
 
10
- # Instalar dependencias
11
  RUN pip install --no-cache-dir -r requirements.txt
12
 
13
- # Exponer puerto (Hugging Face ignora esto, pero bueno tenerlo)
 
 
 
 
 
14
  EXPOSE 7860
15
 
16
- # Comando de inicio
17
- CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
 
 
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
- from fastapi import FastAPI, UploadFile, File
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
- with open("tbc_label_encoder.pkl", "rb") as f:
13
- label_encoder = pickle.load(f)
 
 
 
 
14
 
15
- # Configuración de la app
16
  app = FastAPI(
17
- title="Clasificador TBC con CNN",
18
- description="Clasificador de placas de rayos-X de tórax (TBC o normal) usando una CNN",
19
  version="1.0"
20
  )
21
 
22
- def preprocess_image(file: UploadFile, size=(64, 64)) -> np.ndarray:
23
- img = Image.open(file.file).convert("L")
24
- img = img.resize(size, Image.Resampling.LANCZOS)
25
- img = ImageOps.equalize(img)
26
- img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)
27
- img = img.point(lambda x: 255 if x > 127 else 0, 'L')
28
- array = np.array(img) / 255.0
29
- array = np.expand_dims(array, axis=-1) # (64, 64, 1)
30
- array = np.expand_dims(array, axis=0) # (1, 64, 64, 1)
31
- return array
 
 
 
 
 
 
 
 
 
 
 
32
 
33
  @app.post("/predict/")
34
  async def predict(file: UploadFile = File(...)):
 
 
 
 
 
 
 
 
 
 
 
 
35
  try:
36
- image_array = preprocess_image(file)
37
- prediction = model.predict(image_array)
38
- predicted_index = np.argmax(prediction)
39
- predicted_label = label_encoder.inverse_transform([predicted_index])[0]
40
- confidence = float(np.max(prediction)) * 100
41
 
42
- return JSONResponse({
43
- "label": predicted_label,
44
- "confidence": round(confidence, 2)
45
- })
 
 
 
 
 
46
 
47
- except Exception as e:
48
- return JSONResponse({"error": str(e)}, status_code=500)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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