Spaces:
Runtime error

File size: 2,655 Bytes
b3d057b
 
36623a8
4787f24
b3d057b
31964cf
b3d057b
 
4787f24
 
 
b3d057b
31964cf
4787f24
31964cf
 
 
 
 
 
 
 
 
b3d057b
31964cf
 
 
 
36623a8
31964cf
 
 
b3d057b
31964cf
 
b3d057b
31964cf
 
b3d057b
31964cf
 
 
 
 
 
 
 
b3d057b
4787f24
36623a8
 
b3d057b
4787f24
36623a8
4787f24
36623a8
b3d057b
36623a8
4787f24
b3d057b
4787f24
b3d057b
4787f24
b3d057b
36623a8
31964cf
 
 
36623a8
31964cf
 
 
4787f24
31964cf
 
 
 
36623a8
 
b3d057b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
from fastapi import FastAPI, File, UploadFile, HTTPException
from PIL import Image
import numpy as np
import tensorflow as tf
from io import BytesIO
import cv2

# Cargar el modelo previamente entrenado
def load_model():
    model = tf.keras.models.load_model('cancer_model.h5')
    return model

# Funci贸n para procesar las im谩genes (similar al c贸digo de Colab)
def preprocess_image(image):
    try:
        # Convertir la imagen a un arreglo numpy
        image_np = np.array(image)

        # Convertir la imagen a escala de grises
        grayscale = cv2.cvtColor(image_np, cv2.COLOR_RGB2GRAY)

        # Filtro Gaussiano para suavizar
        smoothed = cv2.GaussianBlur(grayscale, (5, 5), 0)

        # Resaltado de bordes con Sobel
        sobelx = cv2.Sobel(smoothed, cv2.CV_64F, 1, 0, ksize=3)
        sobely = cv2.Sobel(smoothed, cv2.CV_64F, 0, 1, ksize=3)
        sobel = cv2.magnitude(sobelx, sobely)

        # Normalizar la imagen a rango 0-255
        sobel_normalized = cv2.normalize(sobel, None, 0, 255, cv2.NORM_MINMAX)
        sobel_normalized = sobel_normalized.astype('uint8')

        # Redimensionar la imagen a 64x64
        resized = cv2.resize(sobel_normalized, (64, 64))

        # Convertir la imagen a 3 canales (RGB)
        resized_rgb = cv2.cvtColor(resized, cv2.COLOR_GRAY2RGB)

        # Normalizar la imagen
        normalized_image = resized_rgb / 255.0

        return np.expand_dims(normalized_image, axis=0)  # A帽adir la dimensi贸n del batch

    except Exception as e:
        print(f"Error procesando la imagen: {e}")
        return None

# Iniciar la aplicaci贸n FastAPI
app = FastAPI()

# Cargar el modelo previamente entrenado
model = load_model()

# Ruta para realizar la predicci贸n
@app.post("/predict/")
async def predict_image(file: UploadFile = File(...)):
    try:
        # Leer el archivo de imagen subido
        contents = await file.read()
        image = Image.open(BytesIO(contents))

        # Procesar la imagen
        processed_image = preprocess_image(image)

        if processed_image is not None:
            # Realizar la predicci贸n utilizando el modelo cargado
            prediction = model.predict(processed_image)

            # Interpretar la predicci贸n
            result = "Maligno" if prediction >= 0.5 else "Benigno"
            confidence = prediction[0][0]

            # Devolver la respuesta
            return {"prediction": result, "confidence": float(confidence)}
        else:
            raise HTTPException(status_code=400, detail="Error en el preprocesamiento de la imagen")

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))