Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import torchvision.transforms as transforms
|
| 7 |
+
|
| 8 |
+
# Modelo autoencoder
|
| 9 |
+
class Autoencoder(nn.Module):
|
| 10 |
+
def __init__(self):
|
| 11 |
+
super(Autoencoder, self).__init__()
|
| 12 |
+
self.conv1 = nn.Conv2d(1, 32, kernel_size=3, stride=2, padding=1)
|
| 13 |
+
self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1)
|
| 14 |
+
self.fc1 = nn.Linear(64 * 16 * 16, 16)
|
| 15 |
+
self.fc2 = nn.Linear(16, 64 * 16 * 16)
|
| 16 |
+
self.conv3 = nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2, padding=1, output_padding=1)
|
| 17 |
+
self.conv4 = nn.ConvTranspose2d(32, 1, kernel_size=3, stride=2, padding=1, output_padding=1)
|
| 18 |
+
|
| 19 |
+
def encode(self, x):
|
| 20 |
+
z = torch.tanh(self.conv1(x))
|
| 21 |
+
z = torch.tanh(self.conv2(z))
|
| 22 |
+
z = z.view(z.size(0), -1)
|
| 23 |
+
z = torch.tanh(self.fc1(z))
|
| 24 |
+
return z
|
| 25 |
+
|
| 26 |
+
def decode(self, x):
|
| 27 |
+
z = torch.tanh(self.fc2(x))
|
| 28 |
+
z = z.view(z.size(0), 64, 16, 16)
|
| 29 |
+
z = torch.tanh(self.conv3(z))
|
| 30 |
+
z = torch.sigmoid(self.conv4(z))
|
| 31 |
+
return z
|
| 32 |
+
|
| 33 |
+
def forward(self, x):
|
| 34 |
+
return self.decode(self.encode(x))
|
| 35 |
+
|
| 36 |
+
# Cargar el modelo
|
| 37 |
+
model = Autoencoder()
|
| 38 |
+
model.load_state_dict(torch.load("autoencoder.pth", map_location=torch.device("cpu")))
|
| 39 |
+
model.eval()
|
| 40 |
+
|
| 41 |
+
# Transformaci贸n de entrada
|
| 42 |
+
transform = transforms.Compose([
|
| 43 |
+
transforms.Grayscale(),
|
| 44 |
+
transforms.Resize((64, 64)),
|
| 45 |
+
transforms.ToTensor()
|
| 46 |
+
])
|
| 47 |
+
|
| 48 |
+
# Funci贸n de inferencia
|
| 49 |
+
def detectar_anomalia(imagen):
|
| 50 |
+
with torch.no_grad():
|
| 51 |
+
img_tensor = transform(imagen).unsqueeze(0) # A帽adir batch
|
| 52 |
+
reconstruida = model(img_tensor).squeeze(0).squeeze(_
|