Alex Vega commited on
Commit
6c3f7aa
·
0 Parent(s):
Files changed (5) hide show
  1. .gitattributes +1 -0
  2. Dockerfile +13 -0
  3. Makefile +9 -0
  4. main.py +78 -0
  5. requirements.txt +6 -0
.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ *.pkl filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+
3
+ WORKDIR /app
4
+
5
+ COPY requirements.txt .
6
+
7
+ RUN pip install --no-cache-dir -r requirements.txt
8
+
9
+ COPY . .
10
+
11
+ EXPOSE 8000
12
+
13
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Makefile ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ run:
2
+ docker run -p 8001:8000 --name lsp-container lsp-api
3
+
4
+ clean:
5
+ docker stop lsp-container
6
+ docker rm lsp-container
7
+
8
+ build:
9
+ docker build -t lsp-api .
main.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pickle
2
+ import numpy as np
3
+ import io
4
+ import math
5
+ from fastapi import FastAPI, File, UploadFile, HTTPException
6
+ from PIL import Image
7
+
8
+ app = FastAPI(
9
+ title="Peruvian Sign Language (LSP) Recognition API",
10
+ description="Sube una imagen de una seña del alfabeto de la LSP para predecir la letra correspondiente usando un Mapa Autoorganizado (SOM).",
11
+ version="1.0.0"
12
+ )
13
+
14
+ try:
15
+ with open('lsp_som_model.pkl', 'rb') as f:
16
+ model_data = pickle.load(f)
17
+ som = model_data['som']
18
+ label_map = model_data['label_map']
19
+ CLASSES = model_data['classes'] # La lista ['A', 'B', 'C', ...]
20
+ IMG_SIZE = model_data['img_size'] # El tamaño de la imagen
21
+ print("✅ Modelo y activos cargados exitosamente.")
22
+ print(f" - Clases reconocidas: {CLASSES}")
23
+ print(f" - Tamaño de imagen esperado: {IMG_SIZE}x{IMG_SIZE}")
24
+ except FileNotFoundError:
25
+ print("❌ ERROR: No se encontró el archivo del modelo 'lsp_som_model.pkl'.")
26
+ som = None
27
+
28
+ def preprocess_image_from_bytes(image_bytes: bytes):
29
+ try:
30
+ img = Image.open(io.BytesIO(image_bytes)).convert('L') # 'L' para escala de grises
31
+ img = img.resize((IMG_SIZE, IMG_SIZE))
32
+ img_array = np.array(img)
33
+ img_normalized = img_array / 255.0
34
+ return img_normalized.flatten()
35
+ except Exception as e:
36
+ raise HTTPException(status_code=400, detail=f"Archivo de imagen inválido. Error: {e}")
37
+
38
+ @app.get("/", tags=["Status"])
39
+ def read_root():
40
+ return {"status": "ok", "message": "API de Reconocimiento de LSP!!"}
41
+
42
+ @app.post("/predict", tags=["Prediction"])
43
+ async def predict_sign(file: UploadFile = File(..., description="Un archivo de imagen de una seña de la LSP.")):
44
+ if not som:
45
+ raise HTTPException(status_code=503, detail="El modelo no está cargado.")
46
+
47
+ image_bytes = await file.read()
48
+
49
+ feature_vector = preprocess_image_from_bytes(image_bytes)
50
+
51
+ winner_neuron = som.winner(feature_vector)
52
+
53
+ predicted_index = label_map.get(winner_neuron, -1)
54
+
55
+ # Vecino mas cercano para prediccion
56
+ is_best_guess = False
57
+ if predicted_index == -1:
58
+ is_best_guess = True
59
+ min_dist = float('inf')
60
+ for mapped_pos, mapped_label in label_map.items():
61
+ dist = math.sqrt((winner_neuron[0] - mapped_pos[0])**2 + (winner_neuron[1] - mapped_pos[1])**2)
62
+ if dist < min_dist:
63
+ min_dist = dist
64
+ predicted_index = mapped_label
65
+
66
+ if predicted_index != -1:
67
+ predicted_letter = CLASSES[predicted_index]
68
+ prediction_type = "Nearest Neighbor" if is_best_guess else "Direct Match"
69
+ else:
70
+ predicted_letter = "Unknown"
71
+ prediction_type = "Error (No Mapped Neurons Found)"
72
+
73
+ return {
74
+ "filename": file.filename,
75
+ "predicted_letter": predicted_letter,
76
+ "prediction_type": prediction_type,
77
+ "winner_neuron_on_map": [int(coord) for coord in winner_neuron]
78
+ }
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn[standard]
3
+ python-multipart
4
+ minisom
5
+ numpy
6
+ Pillow