Upload 8 files
Browse files- Dockerfile +26 -0
- app (1).py +144 -0
- config.json +12 -0
- config.py +14 -0
- model.py +22 -0
- model.safetensors +3 -0
- requirements.txt +6 -0
- static/background.png +0 -0
Dockerfile
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM python:3.9
|
2 |
+
|
3 |
+
# Crear un usuario y establecer el directorio de trabajo
|
4 |
+
RUN useradd -m -u 1000 user
|
5 |
+
USER user
|
6 |
+
ENV PATH="/home/user/.local/bin:$PATH"
|
7 |
+
WORKDIR /app
|
8 |
+
|
9 |
+
# Limpiar y crear directorio apt/lists/partial
|
10 |
+
USER root
|
11 |
+
RUN rm -rf /var/lib/apt/lists/partial && mkdir -p /var/lib/apt/lists/partial
|
12 |
+
|
13 |
+
# Instalar dependencias del sistema
|
14 |
+
RUN apt-get update && apt-get install -y \
|
15 |
+
libgl1-mesa-glx \
|
16 |
+
&& rm -rf /var/lib/apt/lists/*
|
17 |
+
|
18 |
+
# Instalar las dependencias de Python
|
19 |
+
COPY --chown=user ./requirements.txt requirements.txt
|
20 |
+
RUN pip install --no-cache-dir --upgrade -r requirements.txt
|
21 |
+
|
22 |
+
# Copiar el resto de los archivos de la aplicación
|
23 |
+
COPY --chown=user . /app
|
24 |
+
|
25 |
+
# Comando para iniciar la aplicación
|
26 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
app (1).py
ADDED
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, UploadFile, File, Request
|
2 |
+
from fastapi.responses import JSONResponse
|
3 |
+
from fastapi.responses import HTMLResponse
|
4 |
+
from pydantic import BaseModel
|
5 |
+
from fastapi.staticfiles import StaticFiles
|
6 |
+
from fastapi.templating import Jinja2Templates
|
7 |
+
import torch
|
8 |
+
import cv2
|
9 |
+
from PIL import Image
|
10 |
+
from model import Resnet50FER
|
11 |
+
from config import Resnet50Config
|
12 |
+
|
13 |
+
# Crear una instancia de FastAPI
|
14 |
+
app = FastAPI()
|
15 |
+
|
16 |
+
# Directorio donde se encuentran los archivos estáticos (como imágenes)
|
17 |
+
STATIC_DIR = "static"
|
18 |
+
|
19 |
+
# Montar la carpeta 'static' para servir archivos estáticos como imágenes
|
20 |
+
app.mount("/static", StaticFiles(directory="static"), name="static")
|
21 |
+
|
22 |
+
# Configurar los templates usando Jinja2
|
23 |
+
templates = Jinja2Templates(directory="templates")
|
24 |
+
|
25 |
+
# Definir la configuración de tu modelo
|
26 |
+
config = Resnet50Config(
|
27 |
+
num_classes=10 # Ejemplo: número de clases para tu tarea específica
|
28 |
+
)
|
29 |
+
|
30 |
+
# Definir el contenido HTML directamente en Python
|
31 |
+
html_content = """
|
32 |
+
<!DOCTYPE html>
|
33 |
+
<html lang="en">
|
34 |
+
<head>
|
35 |
+
<meta charset="UTF-8">
|
36 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
37 |
+
<title>FastAPI con Imagen de Fondo</title>
|
38 |
+
<style>
|
39 |
+
body {
|
40 |
+
background-image: url('static/background.png'); /* Ruta a tu imagen de fondo en la carpeta 'static' */
|
41 |
+
background-size: cover;
|
42 |
+
background-repeat: no-repeat;
|
43 |
+
background-attachment: fixed;
|
44 |
+
font-family: Arial, sans-serif;
|
45 |
+
color: #333;
|
46 |
+
margin: 0;
|
47 |
+
padding: 0;
|
48 |
+
}
|
49 |
+
.container {
|
50 |
+
max-width: 800px;
|
51 |
+
margin: 0 auto;
|
52 |
+
padding: 20px;
|
53 |
+
background-color: rgba(255, 255, 255, 0.8); /* Fondo semi-transparente para mejor legibilidad */
|
54 |
+
border-radius: 10px;
|
55 |
+
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
|
56 |
+
}
|
57 |
+
</style>
|
58 |
+
</head>
|
59 |
+
<body>
|
60 |
+
<div class="container">
|
61 |
+
<h1>FastAPI con Imagen de Fondo</h1>
|
62 |
+
<p>Ejemplo de una aplicación FastAPI con una imagen de fondo.</p>
|
63 |
+
<form id="uploadForm" action="/upload/" method="post" enctype="multipart/form-data" onsubmit="uploadImage(event)">
|
64 |
+
<input type="file" name="image" accept="image/*" required>
|
65 |
+
<button type="submit">Subir Imagen</button>
|
66 |
+
</form>
|
67 |
+
</div>
|
68 |
+
<script>
|
69 |
+
async function uploadImage(event) {
|
70 |
+
event.preventDefault(); // Evita el envío tradicional del formulario
|
71 |
+
const formData = new FormData();
|
72 |
+
formData.append('image', document.querySelector('input[name="image"]').files[0]);
|
73 |
+
try {
|
74 |
+
const response = await fetch('/recognize-face/', {
|
75 |
+
method: 'POST',
|
76 |
+
body: formData
|
77 |
+
});
|
78 |
+
if (!response.ok) {
|
79 |
+
throw new Error('Error al enviar la imagen');
|
80 |
+
}
|
81 |
+
const result = await response.json();
|
82 |
+
console.log(result);
|
83 |
+
} catch (error) {
|
84 |
+
console.error('Error:', error);
|
85 |
+
}
|
86 |
+
}
|
87 |
+
</script>
|
88 |
+
</body>
|
89 |
+
</html>
|
90 |
+
"""
|
91 |
+
|
92 |
+
# Ruta para la página principal con imagen de fondo configurada desde Python
|
93 |
+
@app.get("/", response_class=HTMLResponse)
|
94 |
+
async def homepage(request: Request):
|
95 |
+
return HTMLResponse(content=html_content)
|
96 |
+
|
97 |
+
# Crear una instancia de tu modelo
|
98 |
+
model = Resnet50FER(config)
|
99 |
+
model.eval() # Asegúrate de que el modelo esté en modo evaluación
|
100 |
+
|
101 |
+
# Clase para los datos de entrada esperados en la solicitud
|
102 |
+
class Item(BaseModel):
|
103 |
+
# Asumiendo que tu modelo espera imágenes como entrada
|
104 |
+
image: UploadFile # Usamos UploadFile para manejar la carga de archivos
|
105 |
+
|
106 |
+
# Endpoint para subir la imagen
|
107 |
+
@app.post("/upload/")
|
108 |
+
async def upload_image(image: UploadFile = File(...)):
|
109 |
+
return {"filename": image.filename}
|
110 |
+
|
111 |
+
# Endpoint para hacer predicciones
|
112 |
+
@app.post("/predict/")
|
113 |
+
def predict(item: Item):
|
114 |
+
# Procesar la imagen recibida
|
115 |
+
image_bytes = item.image.file.read()
|
116 |
+
# Aquí deberías procesar la imagen y convertirla al formato adecuado para tu modelo
|
117 |
+
# Por ahora, simplemente mostramos un mensaje de ejemplo
|
118 |
+
return {"message": "Endpoint para predicciones con Resnet50FER"}
|
119 |
+
|
120 |
+
# Endpoint para reconocimiento facial
|
121 |
+
@app.post("/recognize-face/")
|
122 |
+
async def recognize_face(image: UploadFile = File(...)):
|
123 |
+
try:
|
124 |
+
# Leer la imagen
|
125 |
+
contents = await image.read()
|
126 |
+
img = Image.open(BytesIO(contents))
|
127 |
+
|
128 |
+
# Aquí deberías realizar el reconocimiento facial usando tu modelo entrenado
|
129 |
+
# Ejemplo básico: detectar rostros con OpenCV
|
130 |
+
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
|
131 |
+
gray = cv2.cvtColor(np.array(img), cv2.COLOR_BGR2GRAY)
|
132 |
+
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
|
133 |
+
|
134 |
+
# Procesar resultados y devolver respuesta
|
135 |
+
detected_faces = [{"x": int(x), "y": int(y), "w": int(w), "h": int(h)} for (x, y, w, h) in faces]
|
136 |
+
return JSONResponse(content={"detected_faces": detected_faces})
|
137 |
+
|
138 |
+
except Exception as e:
|
139 |
+
raise HTTPException(status_code=500, detail=str(e))
|
140 |
+
|
141 |
+
# Ejecutar la aplicación con Uvicorn
|
142 |
+
if __name__ == "__main__":
|
143 |
+
import uvicorn
|
144 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
config.json
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"architectures": [
|
3 |
+
"Resnet50FER"
|
4 |
+
],
|
5 |
+
"auto_map": {
|
6 |
+
"AutoConfig": "config.Resnet50Config",
|
7 |
+
"AutoModelForImageClassification": "model.Resnet50FER"
|
8 |
+
},
|
9 |
+
"num_classes": 6,
|
10 |
+
"torch_dtype": "float32",
|
11 |
+
"transformers_version": "4.37.2"
|
12 |
+
}
|
config.py
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import PretrainedConfig
|
2 |
+
|
3 |
+
class Resnet50Config(PretrainedConfig):
|
4 |
+
# since we have an image classification task
|
5 |
+
# we need to put a model type that is close to our task
|
6 |
+
# don't worry this will not affect our model
|
7 |
+
#model_type = "MobileNetV1"
|
8 |
+
def __init__(
|
9 |
+
self,
|
10 |
+
num_classes=6,
|
11 |
+
**kwargs):
|
12 |
+
|
13 |
+
self.num_classes = num_classes
|
14 |
+
super().__init__(**kwargs)
|
model.py
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torchvision.models as models
|
4 |
+
from config import Resnet50Config
|
5 |
+
from transformers import PreTrainedModel
|
6 |
+
|
7 |
+
class Resnet50FER(PreTrainedModel):
|
8 |
+
config_class = Resnet50Config
|
9 |
+
def __init__(self, config):
|
10 |
+
super().__init__(config)
|
11 |
+
# Load the ResNet50 model without the final fully connected layer
|
12 |
+
self.resnet = models.resnet50(pretrained=False)
|
13 |
+
|
14 |
+
num_ftrs = self.resnet.fc.in_features
|
15 |
+
# Replace the fully connected layer with a new one for your specific classification task
|
16 |
+
self.resnet.fc = nn.Linear(num_ftrs, config.num_classes)
|
17 |
+
|
18 |
+
def forward(self, x):
|
19 |
+
# Forward pass through the ResNet50 model
|
20 |
+
x = self.resnet(x)
|
21 |
+
|
22 |
+
return x
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0eee7468c7e125b5499bb7d42c79b8261da5cd6aa07e9dd571e761f6edba8bbc
|
3 |
+
size 94324992
|
requirements.txt
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
fastapi
|
2 |
+
uvicorn[standard]
|
3 |
+
torch
|
4 |
+
torchvision
|
5 |
+
transformers
|
6 |
+
opencv-python
|
static/background.png
ADDED