existerostro / app.py
RaulHuarote's picture
Update app.py
3ec3815 verified
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
from typing import List
import cv2
import numpy as np
app = FastAPI()
def buscar_existe(image):
existe = "no"
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3,5,minSize=(30, 30))
for (x,y,w,h) in faces:
existe = "si"
break
return existe
# Ruta para la p谩gina principal con formulario HTML
@app.get('/')
async def main():
content = """
<html>
<head>
<title>RECONOCIMIENTO FACIAL</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-image: url('Background.png'); /* Reemplaza con la ruta de tu imagen */
background-size: cover; /* Ajusta el tama帽o para cubrir todo el cuerpo */
background-position: center; /* Centra la imagen en el cuerpo */
background-repeat: no-repeat; /* Evita que la imagen se repita */
}
.container {
position: relative;
padding: 20px;
border-radius: 10px;
box-shadow: 0px 0px 10px rgba(247, 15, 15, 0.808);
text-align: center;
}
.overlay{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0); /* Capa de opacidad */
border-radius: 10px;
}
.content {
position: relative;
z-index: 1;
}
.content h1 {
margin-bottom: 20px;
}
.custom-file-input {
display: none;
}
.file-label {
background-color: #007bff;
color: white;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
display: inline-block;
margin-top: 20px;
margin-bottom: 20px;
}
.file-label:hover {
background-color: #000000;
}
.custom-button {
background-color: #2cb1ff;
color: white;
border: none;
padding: 10px 20px;
margin-top: 20px;
border-radius: 5px;
cursor: pointer;
display: inline-block;
}
.custom-button:hover {
background-color: #01050a;
}
.container img {
margin: 20px auto;
max-width: 100%;
max-height: 300px;
border-radius: 10px;
display: none;
}
</style>
</head>
<body style="background-image: url('Background.png'); background-size: cover; background-position: center; background-repeat: no-repeat;">
<div class="container">
<div class="overlay"></div>
<div class="content">
<h1>RECONOCIMIENTO FACIAL</h1>
<form action="/predict" method="post" enctype="multipart/form-data" onsubmit="mostrarResultado(event)">
<label for="file-input" class="file-label">Seleccionar archivo</label>
<input id="file-input" class="custom-file-input" name="file" type="file" accept="image/*" onchange="mostrarImagen(event)">
<img id="imagenSeleccionada">
<button type="submit" class="custom-button">Subir Imagen</button>
</form>
</div>
</div>
<script>
function mostrarImagen(event) {
const archivo = event.target.files[0];
if (archivo) {
const lector = new FileReader();
lector.onload = function(e) {
const imagen = document.getElementById('imagenSeleccionada');
imagen.src = e.target.result;
imagen.style.display = 'block';
}
lector.readAsDataURL(archivo);
}
}
// Funci贸n para mostrar el resultado como un alert
async function mostrarResultado(event) {
event.preventDefault(); // Evitar que el formulario se env铆e autom谩ticamente
event.preventDefault(); // Evitar que el formulario se env铆e autom谩ticamente
try {
const formData = new FormData(event.target);
const response = await fetch('/predict', {
method: 'POST',
body: formData
});
if (!response.ok) {
throw new Error('HTTP error! Status: ${response.status}');
}
const data = await response.json();
alert('Rostro detectado : ${data.emotion}');
} catch (error) {
console.error('Error al procesar la solicitud:', error);
alert('Ocurri贸 un error al procesar la solicitud.');
}
}
</script>
</body>
</html>
"""
return HTMLResponse(content)
# Ruta de predicci贸n
@app.post('/predict')
async def predict(file: UploadFile = File(...)):
try:
# Verificar si es una imagen v谩lida
if not file.content_type.startswith('image/'):
raise HTTPException(status_code=400, detail="El archivo debe ser una imagen.")
# Convertir la imagen a formato adecuado
image = cv2.imdecode(np.frombuffer(await file.read(), np.uint8), cv2.IMREAD_COLOR)
# Realizar el reconocimiento de emociones en la imagen
emotion = buscar_existe(image)
#print(emotion)
# Devolver la emoci贸n detectada como respuesta en formato JSON
return {'emotion': emotion}
except HTTPException as he:
raise he
except Exception as e:
print(f"Error general: {str(e)}")
raise HTTPException(status_code=500, detail="Error durante la predicci贸n de emociones.")
# Punto de entrada principal para la aplicaci贸n
if __name__ == '__main__':
# Ejecutar la aplicaci贸n FastAPI utilizando Uvicorn
import uvicorn
uvicorn.run(app, host='0.0.0.0', port=8000)