File size: 3,695 Bytes
bb47051
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc85f1e
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
"""
Face Validation Utilities - EmotionMirror Application

Utilities for validating face count and displaying appropriate messages to users.
"""

import streamlit as st
import logging
import cv2
import numpy as np
from typing import Dict, List, Tuple, Any, Optional

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def validate_image_faces(face_service, img_bgr: np.ndarray, max_faces: int = 5) -> Dict[str, Any]:
    """
    Validate that the image does not contain too many faces for processing.
    
    Args:
        face_service: The face detection service instance
        img_bgr: Input image (BGR format for OpenCV)
        max_faces: Maximum number of faces allowed for processing
        
    Returns:
        Dictionary with validation result, detected faces, and messages
    """
    result = {
        "valid": True,
        "faces": None,
        "message": "",
        "warning": "",
        "count": 0
    }
    
    try:
        # Detect faces in the image
        faces = face_service.detect_faces(img_bgr)
        result["faces"] = faces
        result["count"] = len(faces)
        
        # Validate face count
        validation = face_service.validate_face_count(faces, max_faces)
        result["valid"] = validation["valid"]
        result["message"] = validation["message"]
        result["warning"] = validation["warning"]
        
        return result
    except Exception as e:
        logger.error(f"Error in face validation: {str(e)}")
        result["valid"] = False
        result["message"] = "Error validating faces in the image."
        result["warning"] = f"Error details: {str(e)}"
        return result

def display_face_validation_result(result: Dict[str, Any], img_array: np.ndarray) -> None:
    """
    Display appropriate messages and visualizations based on face validation results.
    
    Args:
        result: The validation result dictionary
        img_array: The original image array (RGB format)
    """
    try:
        if not result["valid"]:
            # Too many faces detected - show warning message
            st.error(result["message"])
            st.warning(result["warning"])
            
            # Display the image with a message indicating too many faces
            st.image(img_array, caption=f"Image with {result['count']} faces detected (exceeds limit)", width=400)
            
            # Store in session state to prevent further processing
            st.session_state["too_many_faces"] = True
            st.session_state["should_continue_analysis"] = False
        else:
            # Valid number of faces - store for later use
            if result["faces"] is not None:
                st.session_state["detected_faces"] = result["faces"]
                
            # Reset flags in session state
            st.session_state["too_many_faces"] = False
            st.session_state["should_continue_analysis"] = True
            
            # Optional: Display informational message if faces were found
            if result["count"] > 0:
                st.success(f"Detected {result['count']} face(s) in the image, ready for analysis.")
    except Exception as e:
        logger.error(f"Error displaying face validation result: {str(e)}")
        st.error(f"Error displaying validation results: {str(e)}")

def should_continue_processing() -> bool:
    """
    Check if processing should continue based on face validation result.
    
    Returns:
        Boolean indicating whether to continue processing
    """
    # Si la validación no ha ocurrido aún, asumimos que debemos continuar
    return not st.session_state.get("too_many_faces", False)