RaulHuaroteZegarra commited on
Commit
542b39e
1 Parent(s): f6484ad

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -78
app.py CHANGED
@@ -1,106 +1,92 @@
1
  import pickle
2
  from minisom import MiniSom
3
  import numpy as np
4
- from io import BytesIO
5
- from fastapi import FastAPI, File, UploadFile, HTTPException
 
 
 
 
6
  from pydantic import BaseModel
7
  from typing import List
8
- from scipy.ndimage import median_filter
9
- from scipy.signal import convolve2d
10
- import cv2
11
- from PIL import Image
12
- import math
13
- #from tensorflow.keras.preprocessing import image
14
 
15
  class InputData(BaseModel):
16
- data: List[float] # Lista de características numéricas (floats)
17
 
18
  app = FastAPI()
19
 
 
20
  def build_model():
21
- with open('somlucuma.pkl', 'rb') as fid:
22
- somlucuma = pickle.load(fid)
23
- MM = np.loadtxt('matrizMM.txt', delimiter=" ")
24
- return somlucuma,MM
 
 
 
 
 
 
25
 
26
  def sobel(patron):
27
- gx = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype=np.float32)
28
- gy = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]], dtype=np.float32)
29
 
30
- Gx = convolve2d(patron, gx, mode='valid')
31
- Gy = convolve2d(patron, gy, mode='valid')
32
 
33
- return Gx, Gy
34
 
35
  def medfilt2(G, d=3):
36
- return median_filter(G, size=d)
37
 
38
  def orientacion(patron, w):
39
- Gx, Gy = sobel(patron)
40
- Gx = medfilt2(Gx)
41
- Gy = medfilt2(Gy)
42
 
43
- m, n = Gx.shape
44
- mOrientaciones = np.zeros((m // w, n // w), dtype=np.float32)
45
 
46
- for i in range(m // w):
47
- for j in range(n // w):
48
- Gx_patch = Gx[i*w:(i+1)*w, j*w:(j+1)*w]
49
- Gy_patch = Gy[i*w:(i+1)*w, j*w:(j+1)*w]
50
 
51
- YY = np.sum(2 * Gx_patch * Gy_patch)
52
- XX = np.sum(Gx_patch**2 - Gy_patch**2)
53
 
54
- mOrientaciones[i, j] = (0.5 * np.arctan2(YY, XX) + np.pi / 2.0) * (18.0 / np.pi)
55
 
56
- return mOrientaciones
57
 
58
  def redimensionar(img, h, v):
59
- return cv2.resize(img, (h, v), interpolation=cv2.INTER_AREA)
60
-
61
- def testeo(som,archivo):
62
- archivo = np.squeeze(archivo)
63
- print(archivo)
64
- orientaciones = orientacion(archivo, w=14)
65
- orientaciones = orientaciones.reshape(1,-1)
66
- #orientaciones = np.concatenate([orientaciones.ravel()])
67
- return som.winner(orientaciones)
68
-
69
- som, MM = build_model() # Construir modelo
 
 
 
70
 
 
71
  @app.post("/predict/")
72
- async def predict(data: UploadFile = File(...)):
73
-
74
- #global som
75
- #global MM
76
- try:
77
- contents = await data.read()
78
- img = redimensionar(Image.open(BytesIO(contents)),256,256)
79
-
80
- #print(f"Data: {data}")
81
- #img = image.img_to_array(Image.open(BytesIO(contents))).flatten() / 255.0
82
- """
83
- img = Image.open(BytesIO(contents))
84
- img = redimensionar(img,256,256)
85
- img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
86
- img = np.array(img)
87
- img = orientacion(img,w = 14)
88
- img = img.astype('float32') / 255.0
89
- img = img.reshape(-1)
90
- #data = image.img_to_array(Image.open(BytesIO(contents))
91
- #w = som.winner(img)
92
- """
93
- prediction = "1.0"#MM[w]
94
-
95
- w = "1.0"
96
- #input_data = np.array(data.data).reshape(256, 256, 1)
97
- #w = testeo(som,input_data)
98
- #prediction = MM[w]
99
- print(w,prediction)
100
- return {"prediction": prediction}
101
- except Exception as e:
102
- raise HTTPException(status_code=500, detail=str(e))
103
-
104
- @app.get("/texto/")
105
- async def texto():
106
- return {"texto": "hola"}
 
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('somlucuma.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))