MarceloLZR commited on
Commit
9401edd
·
verified ·
1 Parent(s): 52ddb22

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -92
app.py CHANGED
@@ -1,92 +1,91 @@
1
- import pickle
2
- from minisom import MiniSom
3
- import numpy as np
4
- import cv2
5
-
6
- import urllib.request
7
- import uuid
8
-
9
- from fastapi import FastAPI, HTTPException
10
- from pydantic import BaseModel
11
- from typing import List
12
-
13
- class InputData(BaseModel):
14
- data: str # image url
15
-
16
- app = FastAPI()
17
-
18
- # Función para construir el modelo manualmente
19
- def build_model():
20
- with open('somcancer.pkl', 'rb') as fid:
21
- somecoli = pickle.load(fid)
22
- MM = np.loadtxt('matrizMM.txt', delimiter=" ")
23
- return somecoli,MM
24
-
25
- som,MM = build_model() # Construir el modelo al iniciar la aplicación
26
-
27
-
28
- from scipy.ndimage import median_filter
29
- from scipy.signal import convolve2d
30
-
31
- def sobel(patron):
32
- gx = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype=np.float32)
33
- gy = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]], dtype=np.float32)
34
-
35
- Gx = convolve2d(patron, gx, mode='valid')
36
- Gy = convolve2d(patron, gy, mode='valid')
37
-
38
- return Gx, Gy
39
-
40
- def medfilt2(G, d=3):
41
- return median_filter(G, size=d)
42
-
43
- def orientacion(patron, w):
44
- Gx, Gy = sobel(patron)
45
- Gx = medfilt2(Gx)
46
- Gy = medfilt2(Gy)
47
-
48
- m, n = Gx.shape
49
- mOrientaciones = np.zeros((m // w, n // w), dtype=np.float32)
50
-
51
- for i in range(m // w):
52
- for j in range(n // w):
53
- Gx_patch = Gx[i*w:(i+1)*w, j*w:(j+1)*w]
54
- Gy_patch = Gy[i*w:(i+1)*w, j*w:(j+1)*w]
55
-
56
- YY = np.sum(2 * Gx_patch * Gy_patch)
57
- XX = np.sum(Gx_patch**2 - Gy_patch**2)
58
-
59
- mOrientaciones[i, j] = (0.5 * np.arctan2(YY, XX) + np.pi / 2.0) * (18.0 / np.pi)
60
-
61
- return mOrientaciones
62
-
63
- def redimensionar(img, h, v):
64
- return cv2.resize(img, (h, v), interpolation=cv2.INTER_AREA)
65
-
66
-
67
- def prediction(som, imgurl):
68
- archivo = f"/tmp/test-{uuid.uuid4()}.jpg"
69
- urllib.request.urlretrieve(imgurl, archivo)
70
- Xtest = redimensionar(cv2.imread(archivo),256,256)
71
- Xtest = np.array(Xtest)
72
- Xtest = cv2.cvtColor(Xtest, cv2.COLOR_BGR2GRAY)
73
-
74
- orientaciones = orientacion(Xtest, w=14)
75
- Xtest = Xtest.astype('float32') / 255.0
76
- orientaciones = orientaciones.reshape(-1)
77
- return som.winner(orientaciones)
78
-
79
- # Ruta de predicción
80
- @app.post("/predict/")
81
- async def predict(data: InputData):
82
- print(f"Data: {data}")
83
- global som
84
- global MM
85
- try:
86
- # Convertir la lista de entrada a un array de NumPy para la predicción
87
- imgurl = data.data
88
- print(type(data.data))
89
- w = prediction(som, imgurl)
90
- return {"prediction": MM[w]}
91
- except Exception as e:
92
- raise HTTPException(status_code=500, detail=str(e))
 
1
+ import pickle
2
+ from minisom import MiniSom
3
+ import numpy as np
4
+ import json
5
+ from fastapi import FastAPI, HTTPException
6
+ from pydantic import BaseModel
7
+ from typing import List
8
+ import math
9
+
10
+ class InputData(BaseModel):
11
+ data: List[float] # Lista de características numéricas (floats)
12
+
13
+ app = FastAPI()
14
+
15
+ # Função para construir o modelo manualmente
16
+ def build_model():
17
+ with open('somcancer.pkl', 'rb') as fid:
18
+ somhuella = pickle.load(fid)
19
+ MM = np.loadtxt('matrizMM.txt', delimiter=" ")
20
+ return somhuella,MM
21
+ #with open('label_map.json', 'r') as json_file:
22
+ # loaded_label_map_str_keys = json.load(json_file)
23
+
24
+ # Convertendo as chaves de volta para tuplas
25
+ #loaded_label_map = {eval(k): v for k, v in loaded_label_map_str_keys.items()}
26
+
27
+ #return somecoli, loaded_label_map
28
+
29
+ def sobel(I):
30
+ m, n = I.shape
31
+ Gx = np.zeros([m-2, n-2], np.float32)
32
+ Gy = np.zeros([m-2, n-2], np.float32)
33
+ gx = [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]
34
+ gy = [[1, 2, 1], [0, 0, 0], [-1, -2, -1]]
35
+ for j in range(1, m-2):
36
+ for i in range(1, n-2):
37
+ Gx[j-1, i-1] = sum(sum(I[j-1:j+2, i-1:i+2] * gx))
38
+ Gy[j-1, i-1] = sum(sum(I[j-1:j+2, i-1:i+2] * gy))
39
+ return Gx, Gy
40
+
41
+ def medfilt2(G, d=3):
42
+ m, n = G.shape
43
+ temp = np.zeros([m+2*(d//2), n+2*(d//2)], np.float32)
44
+ salida = np.zeros([m, n], np.float32)
45
+ temp[1:m+1, 1:n+1] = G
46
+ for i in range(1, m):
47
+ for j in range(1, n):
48
+ A = np.asarray(temp[i-1:i+2, j-1:j+2]).reshape(-1)
49
+ salida[i-1, j-1] = np.sort(A)[d+1]
50
+ return salida
51
+
52
+ def orientacion(patron, w):
53
+ Gx, Gy = sobel(patron)
54
+ Gx = medfilt2(Gx)
55
+ Gy = medfilt2(Gy)
56
+ m, n = Gx.shape
57
+ mOrientaciones = np.zeros([m//w, n//w], np.float32)
58
+ for i in range(m//w):
59
+ for j in range(n//w):
60
+ YY = sum(sum(2*Gx[i*w:(i+1)*w, j:j+1] * Gy[i*w:(i+1)*w, j:j+1]))
61
+ XX = sum(sum(Gx[i*w:(i+1)*w, j:j+1]**2 - Gy[i*w:(i+1)*w, j:j+1]**2))
62
+ mOrientaciones[i, j] = (0.5 * math.atan2(YY, XX) + math.pi / 2.0) * (180.0 / math.pi)
63
+ return mOrientaciones
64
+
65
+ def representativo(imarray):
66
+ imarray = np.squeeze(imarray) # Remover a dimensão extra do canal
67
+ m, n = imarray.shape
68
+ patron = imarray[1:m-1, 1:n-1] # de 256x256 a 254x254
69
+ EE = orientacion(patron, 14) # retorna EE de 18x18
70
+ return np.asarray(EE).reshape(-1)
71
+
72
+ som, MM = build_model() # Construir o modelo ao iniciar a aplicação
73
+
74
+ # Rota de previsão
75
+ @app.post("/predict/")
76
+ async def predict(data: InputData):
77
+ print(f"Data: {data}")
78
+ global som
79
+ global MM
80
+ try:
81
+ # Converter a lista de entrada para um array de NumPy para a previsão
82
+ input_data = np.array(data.data).reshape(256, 256, 1) # Assumindo que a entrada é uma imagem de 256x256 com 1 canal
83
+ representative_data = representativo(input_data)
84
+ representative_data = representative_data.reshape(1, -1) # Reformatar para (1, num_features)
85
+
86
+ w = som.winner(representative_data)
87
+ prediction = MM[w]
88
+
89
+ return {"prediction": prediction}
90
+ except Exception as e:
91
+ raise HTTPException(status_code=500, detail=str(e))