Spaces:
Build error
Build error
| import streamlit as st | |
| import cv2 | |
| import numpy as np | |
| import os | |
| import base64 | |
| from PIL import Image | |
| import io | |
| def main(): | |
| st.title("Diagnóstico de Detección Facial") | |
| st.write("Esta herramienta ayuda a diagnosticar problemas con la detección de rostros en Hugging Face.") | |
| # Verificar archivos de modelo | |
| st.subheader("1. Verificación de archivos de modelo") | |
| model_files = [ | |
| "deploy.prototxt.txt", | |
| "res10_300x300_ssd_iter_140000.caffemodel" | |
| ] | |
| missing_files = [] | |
| for file in model_files: | |
| if os.path.exists(file): | |
| st.success(f"✅ Archivo encontrado: {file}") | |
| else: | |
| st.error(f"❌ Archivo NO encontrado: {file}") | |
| missing_files.append(file) | |
| if missing_files: | |
| st.warning("Intentando descargar archivos faltantes...") | |
| try: | |
| import download_models | |
| download_models.main() | |
| st.success("Descarga completada. Verificando archivos nuevamente...") | |
| # Verificar nuevamente | |
| still_missing = [] | |
| for file in missing_files: | |
| if os.path.exists(file): | |
| st.success(f"✅ Archivo ahora encontrado: {file}") | |
| else: | |
| st.error(f"❌ Archivo sigue faltando: {file}") | |
| still_missing.append(file) | |
| if still_missing: | |
| st.error("No se pudieron descargar todos los archivos. La detección facial podría fallar.") | |
| except Exception as e: | |
| st.error(f"Error al descargar modelos: {e}") | |
| # Cargar modelo de detección facial | |
| st.subheader("2. Carga del modelo DNN") | |
| try: | |
| modelFile = "res10_300x300_ssd_iter_140000.caffemodel" | |
| configFile = "deploy.prototxt.txt" | |
| net = cv2.dnn.readNetFromCaffe(configFile, modelFile) | |
| st.success(f"✅ Modelo cargado correctamente. Tipo: {type(net)}") | |
| except Exception as e: | |
| st.error(f"❌ Error al cargar el modelo: {e}") | |
| st.stop() | |
| # Crear imagen de prueba | |
| st.subheader("3. Prueba de detección con imagen de ejemplo") | |
| # Opción 1: Usar una imagen predeterminada | |
| example_image = None | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| st.write("Opción 1: Usar imagen de prueba") | |
| use_example = st.checkbox("Usar imagen de ejemplo", value=True) | |
| with col2: | |
| st.write("Opción 2: Subir una imagen") | |
| uploaded_file = st.file_uploader("Cargar imagen", type=["jpg", "jpeg", "png"]) | |
| if use_example: | |
| # Crear una imagen de prueba con un óvalo como rostro | |
| example_image = np.zeros((400, 400, 3), dtype=np.uint8) | |
| # Dibujar un óvalo que simule un rostro | |
| cv2.ellipse(example_image, (200, 200), (100, 140), 0, 0, 360, (200, 200, 200), -1) | |
| # Dibujar ojos | |
| cv2.circle(example_image, (150, 150), 15, (255, 255, 255), -1) | |
| cv2.circle(example_image, (250, 150), 15, (255, 255, 255), -1) | |
| # Dibujar boca | |
| cv2.ellipse(example_image, (200, 250), (50, 20), 0, 0, 360, (150, 150, 150), -1) | |
| st.image(example_image, caption="Imagen de ejemplo generada", channels="BGR") | |
| test_image = example_image | |
| elif uploaded_file is not None: | |
| file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8) | |
| test_image = cv2.imdecode(file_bytes, cv2.IMREAD_COLOR) | |
| st.image(test_image, caption="Imagen cargada", channels="BGR") | |
| else: | |
| st.warning("Por favor, usa la imagen de ejemplo o sube una imagen para continuar.") | |
| st.stop() | |
| # Ejecutar detección | |
| st.subheader("4. Ejecutando detección facial") | |
| # Crear un blob de la imagen | |
| try: | |
| h, w = test_image.shape[:2] | |
| st.write(f"Dimensiones de la imagen: {w}x{h}") | |
| blob = cv2.dnn.blobFromImage(cv2.resize(test_image, (300, 300)), 1.0, | |
| (300, 300), (104.0, 177.0, 123.0)) | |
| st.success(f"✅ Blob creado correctamente. Forma: {blob.shape}") | |
| except Exception as e: | |
| st.error(f"❌ Error al crear blob: {e}") | |
| st.stop() | |
| # Realizar detección | |
| try: | |
| net.setInput(blob) | |
| detections = net.forward() | |
| st.success(f"✅ Detección realizada correctamente. Forma de detecciones: {detections.shape}") | |
| except Exception as e: | |
| st.error(f"❌ Error al realizar detección: {e}") | |
| st.stop() | |
| # Procesar resultados | |
| st.subheader("5. Procesando resultados") | |
| # Probando diferentes umbrales | |
| threshold_values = [0.1, 0.2, 0.3, 0.4, 0.5] | |
| for conf_threshold in threshold_values: | |
| st.write(f"### Umbral: {conf_threshold}") | |
| # Procesar detecciones | |
| bboxes = [] | |
| frame_h, frame_w = test_image.shape[:2] | |
| detection_count = 0 | |
| for i in range(detections.shape[2]): | |
| confidence = detections[0, 0, i, 2] | |
| if confidence > conf_threshold: | |
| detection_count += 1 | |
| box = detections[0, 0, i, 3:7] * np.array([frame_w, frame_h, frame_w, frame_h]) | |
| x1, y1, x2, y2 = box.astype("int") | |
| # Asegurar que las coordenadas estén dentro de los límites | |
| x1, y1 = max(0, x1), max(0, y1) | |
| x2, y2 = min(frame_w, x2), min(frame_h, y2) | |
| # Verificar validez de la caja | |
| width, height = x2 - x1, y2 - y1 | |
| if width <= 0 or height <= 0: | |
| continue | |
| bboxes.append([x1, y1, x2, y2, confidence]) | |
| # Dibujar resultados | |
| result_image = test_image.copy() | |
| for bbox in bboxes: | |
| x1, y1, x2, y2, confidence = bbox | |
| # Dibujar rectángulo verde grueso para mejor visibilidad | |
| cv2.rectangle(result_image, (x1, y1), (x2, y2), (0, 255, 0), 3) | |
| # Añadir texto con confianza | |
| cv2.putText(result_image, f"{confidence:.2f}", (x1, y1-10), | |
| cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2) | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| st.write(f"Detecciones encontradas: {len(bboxes)}") | |
| st.write(f"Coordenadas de cajas: {bboxes}") | |
| with col2: | |
| # Convertir a RGB para mostrar | |
| rgb_result = cv2.cvtColor(result_image, cv2.COLOR_BGR2RGB) | |
| st.image(rgb_result, caption=f"Resultado con umbral {conf_threshold}", use_column_width=True) | |
| # Añadir botón de descarga | |
| if len(bboxes) > 0: | |
| # Convertir imagen a bytes para descarga | |
| pil_img = Image.fromarray(rgb_result) | |
| buf = io.BytesIO() | |
| pil_img.save(buf, format="PNG") | |
| byte_im = buf.getvalue() | |
| # Crear link de descarga | |
| b64 = base64.b64encode(byte_im).decode() | |
| href = f'<a href="data:image/png;base64,{b64}" download="deteccion_umbral_{conf_threshold}.png">Descargar imagen</a>' | |
| st.markdown(href, unsafe_allow_html=True) | |
| # Mostrar instrucciones finales | |
| st.subheader("Conclusiones") | |
| st.write(""" | |
| Si no ves cajas verdes en ninguno de los umbrales: | |
| 1. Puede que el modelo no esté detectando correctamente los rostros | |
| 2. Verifica que los archivos del modelo estén correctamente cargados | |
| 3. Prueba con una imagen que contenga rostros más claros | |
| Si ves cajas verdes en las imágenes de ejemplo pero no en tu aplicación principal: | |
| 1. El problema podría estar en la visualización, no en la detección | |
| 2. Revisa cómo se procesan y muestran las imágenes en la aplicación principal | |
| """) | |
| if __name__ == "__main__": | |
| main() |