robmarkcole / HASS-Deepstack-face

Home Assistant custom component for using Deepstack face recognition
https://community.home-assistant.io/t/face-and-person-detection-with-deepstack-local-and-free/92041
MIT License
218 stars 68 forks source link

FR: Add a list of names to the integration #46

Open DivanX10 opened 3 years ago

DivanX10 commented 3 years ago

I made corrections to the code and got the output of names in one line. Please add this code to your integration and if you see that you need to fix it, fix it. I'm not a programmer, I just read python literature and tried to implement it, so I'm sorry for my mistakes. Внес исправления в код и получил вывод имен в одну строку. Добавьте пожалуйста этот код в свою интеграцию и если увидите, что нужно исправить - исправьте. Я не программист, просто читал литературу питона и попробовал это реализовать, так что простите за мои ошибки.

image image

image image

def get_valid_filename(name: str) -> str:
    return re.sub(r"(?u)[^-\w.]", "", str(name).strip().replace(" ", "_"))

def get_faces(predictions: list, img_width: int, img_height: int):
    """Return faces with formatting for annotating images."""

    faces = []
    names_list = []
    decimal_places = 3
    for pred in predictions:
        if not "userid" in pred.keys():
            name = "unknown"
        else:
            name = pred["userid"]
        confidence = round(pred["confidence"] * 100, decimal_places)
        box_width = pred["x_max"] - pred["x_min"]
        box_height = pred["y_max"] - pred["y_min"]
        box = {
            "height": round(box_height / img_height, decimal_places),
            "width": round(box_width / img_width, decimal_places),
            "y_min": round(pred["y_min"] / img_height, decimal_places),
            "x_min": round(pred["x_min"] / img_width, decimal_places),
            "y_max": round(pred["y_max"] / img_height, decimal_places),
            "x_max": round(pred["x_max"] / img_width, decimal_places),
        }
        faces.append(
            {"name": name, "confidence": confidence, "bounding_box": box, "prediction": pred}
        )
        if name == 'Valentina' or name == 'valentina':
            name = 'Валентина'
        elif name == 'Svetlana' or name == 'svetlana':
            name = 'Светлана'
        elif name == 'Aleksandr' or name == 'aleksandr':
            name = 'Александр'
        elif name == 'Oleg' or name == 'oleg':
            name = 'Олег'
        elif name == 'Artem' or name == 'artem':
            name = 'Артем'
        elif name == 'Igor' or name == 'igor':
            name = 'Игорь'
        names_list.append(name)
    faces[0]['bounding_box']['names'] = ', '.join(names_list)
    return faces

def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the classifier."""
    if DATA_DEEPSTACK not in hass.data:
        hass.data[DATA_DEEPSTACK] = []

Output the sensor Выводим сенсор

# The sensor displays the name of the identified person
# Сенсор отображает имя опознанного лица
     identified_person:
        friendly_name: 'Name of the identified person'
        value_template: >
            {{ states.image_processing.detect_face_smartphone_camera.attributes.faces[0].bounding_box.names }}
robmarkcole commented 2 years ago

Could do this with targets like in https://github.com/robmarkcole/HASS-Deepstack-object but in general this should be handled in downstream automations IMO. Will leave as a FR in case anyone wants to make a PR