Spaces:
Sleeping
Sleeping
Commit 路
22efc22
1
Parent(s): 527fc20
Delete files
Browse filesFiles changed (5)
- files/cifar_net.pthDeleted-3
- files/inference.pyDeleted-96
- files/static/uploads/avion_img.jpgDeleted
- files/static/uploads/cat_image.jpgDeleted
- files/templates/index.htmlDeleted-25
123version https://git-lfs.github.com/spec/v1oid sha256:d68a16753138b325ae729b384dc00046eebd1eefd2c871b8efe9e10bd5a0f7a0size 251604123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596import torchimport torch.nn as nnimport torch.nn.functional as Fimport torchvision.transforms as transformsfrom PIL import Imagefrom flask import Flask, jsonify, request, render_templateimport os
app = Flask(__name__)
# Directorio de carga de im谩genesUPLOAD_FOLDER = 'static/uploads'app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# Aplicar la transformaci贸ntransform = transforms.Compose([ transforms.Resize((32, 32)), # Ajustar al tama帽o de entrada de la red transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
# Mostrar la imagen# imshow(transform(image)) class Net(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10)
def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = torch.flatten(x, 1) # flatten all dimensions except batch x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x
classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')net = Net()PATH='cifar_net.pth'net.load_state_dict(torch.load(PATH))net.eval() # Establecer la red en modo de evaluaci贸n
# Endpoint para hacer predicciones@app.route('/predict', methods=['GET', 'POST'])def predict(): prediction = None image_path = None
if request.method == 'POST': try: # Obtener la imagen desde la solicitud POST file = request.files['file']
# Guardar la imagen cargada en el directorio de carga image_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename) file.save(image_path)
# Aplicar la transformaci贸n a la imagen image = Image.open(file) image_tensor = transform(image).unsqueeze(0)
# Obtener la salida del modelo output = net(image_tensor)
# Aplicar softmax para obtener las probabilidades probabilities = F.softmax(output, dim=1)
# Obtener la clase predicha y la probabilidad m谩xima max_prob, predicted_class = torch.max(probabilities, 1) predicted_class_name = classes[predicted_class.item()]
# Almacenar el resultado de la predicci贸n prediction = { 'predicted_class': predicted_class_name, 'probability': round(max_prob.item() * 100, 2) }
except Exception as e: return jsonify({'error': str(e)}) return render_template('index.html', prediction=prediction, image_path=image_path)
if __name__ == '__main__': app.run(debug=True, host="0.0.0.0")12345678910111213141516171819202122232425<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Predicci贸n de Im谩genes</title></head><body> <h1>Sube una imagen para predecir</h1> <form action="/predict" method="post" enctype="multipart/form-data"> <input type="file" name="file" accept="image/*" required> <br> <input type="submit" value="Predecir"> </form> <br> {% if prediction %} <h2>Resultado de la Predicci贸n:</h2> <p>Clase: {{ prediction['predicted_class'] }}</p> <p>Probabilidad: {{ prediction['probability'] }}%</p> <img src="{{ image_path }}" alt="Imagen Cargada"> <!-- <p>{{ image_path }}</p> --> {% endif %}</body></html>files/cifar_net.pthDeleted-3
files/inference.pyDeleted-96
files/static/uploads/avion_img.jpgDeleted
files/static/uploads/cat_image.jpgDeleted
files/templates/index.htmlDeleted-25