Consolidate all platforms that have tests (#22109)
* Moved climate components with tests into platform dirs. * Updated tests from climate component. * Moved binary_sensor components with tests into platform dirs. * Updated tests from binary_sensor component. * Moved calendar components with tests into platform dirs. * Updated tests from calendar component. * Moved camera components with tests into platform dirs. * Updated tests from camera component. * Moved cover components with tests into platform dirs. * Updated tests from cover component. * Moved device_tracker components with tests into platform dirs. * Updated tests from device_tracker component. * Moved fan components with tests into platform dirs. * Updated tests from fan component. * Moved geo_location components with tests into platform dirs. * Updated tests from geo_location component. * Moved image_processing components with tests into platform dirs. * Updated tests from image_processing component. * Moved light components with tests into platform dirs. * Updated tests from light component. * Moved lock components with tests into platform dirs. * Moved media_player components with tests into platform dirs. * Updated tests from media_player component. * Moved scene components with tests into platform dirs. * Moved sensor components with tests into platform dirs. * Updated tests from sensor component. * Moved switch components with tests into platform dirs. * Updated tests from sensor component. * Moved vacuum components with tests into platform dirs. * Updated tests from vacuum component. * Moved weather components with tests into platform dirs. * Fixed __init__.py files * Fixes for stuff moved as part of this branch. * Fix stuff needed to merge with balloob's branch. * Formatting issues. * Missing __init__.py files. * Fix-ups * Fixup * Regenerated requirements. * Linting errors fixed. * Fixed more broken tests. * Missing init files. * Fix broken tests. * More broken tests * There seems to be a thread race condition. I suspect the logger stuff is running in another thread, which means waiting until the aio loop is done is missing the log messages. Used sleep instead because that allows the logger thread to run. I think the api_streams sensor might not be thread safe. * Disabled tests, will remove sensor in #22147 * Updated coverage and codeowners.
This commit is contained in:
1 parent
46ece3603f
commit
f195ecca4b
486 files changed
+662
-455
No files matched your search
@@ -1,260 +0,0 @@
|
||||
"""
|
||||
Component that will perform facial detection and identification via facebox.
|
||||
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://home-assistant.io/components/image_processing.facebox
|
||||
"""
|
||||
import base64
|
||||
import logging
|
||||
|
||||
import requests
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.const import (
|
||||
ATTR_ENTITY_ID, ATTR_NAME)
|
||||
from homeassistant.core import split_entity_id
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.components.image_processing import (
|
||||
PLATFORM_SCHEMA, ImageProcessingFaceEntity, ATTR_CONFIDENCE, CONF_SOURCE,
|
||||
CONF_ENTITY_ID, CONF_NAME, DOMAIN)
|
||||
from homeassistant.const import (
|
||||
CONF_IP_ADDRESS, CONF_PORT, CONF_PASSWORD, CONF_USERNAME,
|
||||
HTTP_BAD_REQUEST, HTTP_OK, HTTP_UNAUTHORIZED)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
ATTR_BOUNDING_BOX = 'bounding_box'
|
||||
ATTR_CLASSIFIER = 'classifier'
|
||||
ATTR_IMAGE_ID = 'image_id'
|
||||
ATTR_ID = 'id'
|
||||
ATTR_MATCHED = 'matched'
|
||||
FACEBOX_NAME = 'name'
|
||||
CLASSIFIER = 'facebox'
|
||||
DATA_FACEBOX = 'facebox_classifiers'
|
||||
FILE_PATH = 'file_path'
|
||||
SERVICE_TEACH_FACE = 'facebox_teach_face'
|
||||
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Required(CONF_IP_ADDRESS): cv.string,
|
||||
vol.Required(CONF_PORT): cv.port,
|
||||
vol.Optional(CONF_USERNAME): cv.string,
|
||||
vol.Optional(CONF_PASSWORD): cv.string,
|
||||
})
|
||||
|
||||
SERVICE_TEACH_SCHEMA = vol.Schema({
|
||||
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
|
||||
vol.Required(ATTR_NAME): cv.string,
|
||||
vol.Required(FILE_PATH): cv.string,
|
||||
})
|
||||
|
||||
|
||||
def check_box_health(url, username, password):
|
||||
"""Check the health of the classifier and return its id if healthy."""
|
||||
kwargs = {}
|
||||
if username:
|
||||
kwargs['auth'] = requests.auth.HTTPBasicAuth(username, password)
|
||||
try:
|
||||
response = requests.get(
|
||||
url,
|
||||
**kwargs
|
||||
)
|
||||
if response.status_code == HTTP_UNAUTHORIZED:
|
||||
_LOGGER.error("AuthenticationError on %s", CLASSIFIER)
|
||||
return None
|
||||
if response.status_code == HTTP_OK:
|
||||
return response.json()['hostname']
|
||||
except requests.exceptions.ConnectionError:
|
||||
_LOGGER.error("ConnectionError: Is %s running?", CLASSIFIER)
|
||||
return None
|
||||
|
||||
|
||||
def encode_image(image):
|
||||
"""base64 encode an image stream."""
|
||||
base64_img = base64.b64encode(image).decode('ascii')
|
||||
return base64_img
|
||||
|
||||
|
||||
def get_matched_faces(faces):
|
||||
"""Return the name and rounded confidence of matched faces."""
|
||||
return {face['name']: round(face['confidence'], 2)
|
||||
for face in faces if face['matched']}
|
||||
|
||||
|
||||
def parse_faces(api_faces):
|
||||
"""Parse the API face data into the format required."""
|
||||
known_faces = []
|
||||
for entry in api_faces:
|
||||
face = {}
|
||||
if entry['matched']: # This data is only in matched faces.
|
||||
face[FACEBOX_NAME] = entry['name']
|
||||
face[ATTR_IMAGE_ID] = entry['id']
|
||||
else: # Lets be explicit.
|
||||
face[FACEBOX_NAME] = None
|
||||
face[ATTR_IMAGE_ID] = None
|
||||
face[ATTR_CONFIDENCE] = round(100.0*entry['confidence'], 2)
|
||||
face[ATTR_MATCHED] = entry['matched']
|
||||
face[ATTR_BOUNDING_BOX] = entry['rect']
|
||||
known_faces.append(face)
|
||||
return known_faces
|
||||
|
||||
|
||||
def post_image(url, image, username, password):
|
||||
"""Post an image to the classifier."""
|
||||
kwargs = {}
|
||||
if username:
|
||||
kwargs['auth'] = requests.auth.HTTPBasicAuth(username, password)
|
||||
try:
|
||||
response = requests.post(
|
||||
url,
|
||||
json={"base64": encode_image(image)},
|
||||
**kwargs
|
||||
)
|
||||
if response.status_code == HTTP_UNAUTHORIZED:
|
||||
_LOGGER.error("AuthenticationError on %s", CLASSIFIER)
|
||||
return None
|
||||
return response
|
||||
except requests.exceptions.ConnectionError:
|
||||
_LOGGER.error("ConnectionError: Is %s running?", CLASSIFIER)
|
||||
return None
|
||||
|
||||
|
||||
def teach_file(url, name, file_path, username, password):
|
||||
"""Teach the classifier a name associated with a file."""
|
||||
kwargs = {}
|
||||
if username:
|
||||
kwargs['auth'] = requests.auth.HTTPBasicAuth(username, password)
|
||||
try:
|
||||
with open(file_path, 'rb') as open_file:
|
||||
response = requests.post(
|
||||
url,
|
||||
data={FACEBOX_NAME: name, ATTR_ID: file_path},
|
||||
files={'file': open_file},
|
||||
**kwargs
|
||||
)
|
||||
if response.status_code == HTTP_UNAUTHORIZED:
|
||||
_LOGGER.error("AuthenticationError on %s", CLASSIFIER)
|
||||
elif response.status_code == HTTP_BAD_REQUEST:
|
||||
_LOGGER.error("%s teaching of file %s failed with message:%s",
|
||||
CLASSIFIER, file_path, response.text)
|
||||
except requests.exceptions.ConnectionError:
|
||||
_LOGGER.error("ConnectionError: Is %s running?", CLASSIFIER)
|
||||
|
||||
|
||||
def valid_file_path(file_path):
|
||||
"""Check that a file_path points to a valid file."""
|
||||
try:
|
||||
cv.isfile(file_path)
|
||||
return True
|
||||
except vol.Invalid:
|
||||
_LOGGER.error(
|
||||
"%s error: Invalid file path: %s", CLASSIFIER, file_path)
|
||||
return False
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_entities, discovery_info=None):
|
||||
"""Set up the classifier."""
|
||||
if DATA_FACEBOX not in hass.data:
|
||||
hass.data[DATA_FACEBOX] = []
|
||||
|
||||
ip_address = config[CONF_IP_ADDRESS]
|
||||
port = config[CONF_PORT]
|
||||
username = config.get(CONF_USERNAME)
|
||||
password = config.get(CONF_PASSWORD)
|
||||
url_health = "http://{}:{}/healthz".format(ip_address, port)
|
||||
hostname = check_box_health(url_health, username, password)
|
||||
if hostname is None:
|
||||
return
|
||||
|
||||
entities = []
|
||||
for camera in config[CONF_SOURCE]:
|
||||
facebox = FaceClassifyEntity(
|
||||
ip_address, port, username, password, hostname,
|
||||
camera[CONF_ENTITY_ID], camera.get(CONF_NAME))
|
||||
entities.append(facebox)
|
||||
hass.data[DATA_FACEBOX].append(facebox)
|
||||
add_entities(entities)
|
||||
|
||||
def service_handle(service):
|
||||
"""Handle for services."""
|
||||
entity_ids = service.data.get('entity_id')
|
||||
|
||||
classifiers = hass.data[DATA_FACEBOX]
|
||||
if entity_ids:
|
||||
classifiers = [c for c in classifiers if c.entity_id in entity_ids]
|
||||
|
||||
for classifier in classifiers:
|
||||
name = service.data.get(ATTR_NAME)
|
||||
file_path = service.data.get(FILE_PATH)
|
||||
classifier.teach(name, file_path)
|
||||
|
||||
hass.services.register(
|
||||
DOMAIN, SERVICE_TEACH_FACE, service_handle,
|
||||
schema=SERVICE_TEACH_SCHEMA)
|
||||
|
||||
|
||||
class FaceClassifyEntity(ImageProcessingFaceEntity):
|
||||
"""Perform a face classification."""
|
||||
|
||||
def __init__(self, ip_address, port, username, password, hostname,
|
||||
camera_entity, name=None):
|
||||
"""Init with the API key and model id."""
|
||||
super().__init__()
|
||||
self._url_check = "http://{}:{}/{}/check".format(
|
||||
ip_address, port, CLASSIFIER)
|
||||
self._url_teach = "http://{}:{}/{}/teach".format(
|
||||
ip_address, port, CLASSIFIER)
|
||||
self._username = username
|
||||
self._password = password
|
||||
self._hostname = hostname
|
||||
self._camera = camera_entity
|
||||
if name:
|
||||
self._name = name
|
||||
else:
|
||||
camera_name = split_entity_id(camera_entity)[1]
|
||||
self._name = "{} {}".format(CLASSIFIER, camera_name)
|
||||
self._matched = {}
|
||||
|
||||
def process_image(self, image):
|
||||
"""Process an image."""
|
||||
response = post_image(
|
||||
self._url_check, image, self._username, self._password)
|
||||
if response:
|
||||
response_json = response.json()
|
||||
if response_json['success']:
|
||||
total_faces = response_json['facesCount']
|
||||
faces = parse_faces(response_json['faces'])
|
||||
self._matched = get_matched_faces(faces)
|
||||
self.process_faces(faces, total_faces)
|
||||
|
||||
else:
|
||||
self.total_faces = None
|
||||
self.faces = []
|
||||
self._matched = {}
|
||||
|
||||
def teach(self, name, file_path):
|
||||
"""Teach classifier a face name."""
|
||||
if (not self.hass.config.is_allowed_path(file_path)
|
||||
or not valid_file_path(file_path)):
|
||||
return
|
||||
teach_file(
|
||||
self._url_teach, name, file_path, self._username, self._password)
|
||||
|
||||
@property
|
||||
def camera_entity(self):
|
||||
"""Return camera entity id from process pictures."""
|
||||
return self._camera
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the sensor."""
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def device_state_attributes(self):
|
||||
"""Return the classifier attributes."""
|
||||
return {
|
||||
'matched_faces': self._matched,
|
||||
'total_matched_faces': len(self._matched),
|
||||
'hostname': self._hostname
|
||||
}
|
||||
@@ -1,117 +0,0 @@
|
||||
"""
|
||||
Component that will help set the Microsoft face detect processing.
|
||||
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://home-assistant.io/components/image_processing.microsoft_face_detect/
|
||||
"""
|
||||
import logging
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.image_processing import (
|
||||
ATTR_AGE, ATTR_GENDER, ATTR_GLASSES, CONF_ENTITY_ID, CONF_NAME,
|
||||
CONF_SOURCE, PLATFORM_SCHEMA, ImageProcessingFaceEntity)
|
||||
from homeassistant.components.microsoft_face import DATA_MICROSOFT_FACE
|
||||
from homeassistant.core import split_entity_id
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
DEPENDENCIES = ['microsoft_face']
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
SUPPORTED_ATTRIBUTES = [
|
||||
ATTR_AGE,
|
||||
ATTR_GENDER,
|
||||
ATTR_GLASSES
|
||||
]
|
||||
|
||||
CONF_ATTRIBUTES = 'attributes'
|
||||
DEFAULT_ATTRIBUTES = [ATTR_AGE, ATTR_GENDER]
|
||||
|
||||
|
||||
def validate_attributes(list_attributes):
|
||||
"""Validate face attributes."""
|
||||
for attr in list_attributes:
|
||||
if attr not in SUPPORTED_ATTRIBUTES:
|
||||
raise vol.Invalid("Invalid attribute {0}".format(attr))
|
||||
return list_attributes
|
||||
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Optional(CONF_ATTRIBUTES, default=DEFAULT_ATTRIBUTES):
|
||||
vol.All(cv.ensure_list, validate_attributes),
|
||||
})
|
||||
|
||||
|
||||
async def async_setup_platform(hass, config, async_add_entities,
|
||||
discovery_info=None):
|
||||
"""Set up the Microsoft Face detection platform."""
|
||||
api = hass.data[DATA_MICROSOFT_FACE]
|
||||
attributes = config[CONF_ATTRIBUTES]
|
||||
|
||||
entities = []
|
||||
for camera in config[CONF_SOURCE]:
|
||||
entities.append(MicrosoftFaceDetectEntity(
|
||||
camera[CONF_ENTITY_ID], api, attributes, camera.get(CONF_NAME)
|
||||
))
|
||||
|
||||
async_add_entities(entities)
|
||||
|
||||
|
||||
class MicrosoftFaceDetectEntity(ImageProcessingFaceEntity):
|
||||
"""Microsoft Face API entity for identify."""
|
||||
|
||||
def __init__(self, camera_entity, api, attributes, name=None):
|
||||
"""Initialize Microsoft Face."""
|
||||
super().__init__()
|
||||
|
||||
self._api = api
|
||||
self._camera = camera_entity
|
||||
self._attributes = attributes
|
||||
|
||||
if name:
|
||||
self._name = name
|
||||
else:
|
||||
self._name = "MicrosoftFace {0}".format(
|
||||
split_entity_id(camera_entity)[1])
|
||||
|
||||
@property
|
||||
def camera_entity(self):
|
||||
"""Return camera entity id from process pictures."""
|
||||
return self._camera
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the entity."""
|
||||
return self._name
|
||||
|
||||
async def async_process_image(self, image):
|
||||
"""Process image.
|
||||
|
||||
This method is a coroutine.
|
||||
"""
|
||||
face_data = None
|
||||
try:
|
||||
face_data = await self._api.call_api(
|
||||
'post', 'detect', image, binary=True,
|
||||
params={'returnFaceAttributes': ",".join(self._attributes)})
|
||||
|
||||
except HomeAssistantError as err:
|
||||
_LOGGER.error("Can't process image on microsoft face: %s", err)
|
||||
return
|
||||
|
||||
if not face_data:
|
||||
face_data = []
|
||||
|
||||
faces = []
|
||||
for face in face_data:
|
||||
face_attr = {}
|
||||
for attr in self._attributes:
|
||||
if attr in face['faceAttributes']:
|
||||
face_attr[attr] = face['faceAttributes'][attr]
|
||||
|
||||
if face_attr:
|
||||
faces.append(face_attr)
|
||||
|
||||
self.async_process_faces(faces, len(face_data))
|
||||
@@ -1,121 +0,0 @@
|
||||
"""
|
||||
Component that will help set the Microsoft face for verify processing.
|
||||
|
||||
For more details about this component, please refer to the documentation at
|
||||
https://home-assistant.io/components/image_processing.microsoft_face_identify/
|
||||
"""
|
||||
import logging
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.image_processing import (
|
||||
ATTR_CONFIDENCE, CONF_CONFIDENCE, CONF_ENTITY_ID, CONF_NAME, CONF_SOURCE,
|
||||
PLATFORM_SCHEMA, ImageProcessingFaceEntity)
|
||||
from homeassistant.components.microsoft_face import DATA_MICROSOFT_FACE
|
||||
from homeassistant.const import ATTR_NAME
|
||||
from homeassistant.core import split_entity_id
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
DEPENDENCIES = ['microsoft_face']
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
CONF_GROUP = 'group'
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Required(CONF_GROUP): cv.slugify,
|
||||
})
|
||||
|
||||
|
||||
async def async_setup_platform(hass, config, async_add_entities,
|
||||
discovery_info=None):
|
||||
"""Set up the Microsoft Face identify platform."""
|
||||
api = hass.data[DATA_MICROSOFT_FACE]
|
||||
face_group = config[CONF_GROUP]
|
||||
confidence = config[CONF_CONFIDENCE]
|
||||
|
||||
entities = []
|
||||
for camera in config[CONF_SOURCE]:
|
||||
entities.append(MicrosoftFaceIdentifyEntity(
|
||||
camera[CONF_ENTITY_ID], api, face_group, confidence,
|
||||
camera.get(CONF_NAME)
|
||||
))
|
||||
|
||||
async_add_entities(entities)
|
||||
|
||||
|
||||
class MicrosoftFaceIdentifyEntity(ImageProcessingFaceEntity):
|
||||
"""Representation of the Microsoft Face API entity for identify."""
|
||||
|
||||
def __init__(self, camera_entity, api, face_group, confidence, name=None):
|
||||
"""Initialize the Microsoft Face API."""
|
||||
super().__init__()
|
||||
|
||||
self._api = api
|
||||
self._camera = camera_entity
|
||||
self._confidence = confidence
|
||||
self._face_group = face_group
|
||||
|
||||
if name:
|
||||
self._name = name
|
||||
else:
|
||||
self._name = "MicrosoftFace {0}".format(
|
||||
split_entity_id(camera_entity)[1])
|
||||
|
||||
@property
|
||||
def confidence(self):
|
||||
"""Return minimum confidence for send events."""
|
||||
return self._confidence
|
||||
|
||||
@property
|
||||
def camera_entity(self):
|
||||
"""Return camera entity id from process pictures."""
|
||||
return self._camera
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the entity."""
|
||||
return self._name
|
||||
|
||||
async def async_process_image(self, image):
|
||||
"""Process image.
|
||||
|
||||
This method is a coroutine.
|
||||
"""
|
||||
detect = []
|
||||
try:
|
||||
face_data = await self._api.call_api(
|
||||
'post', 'detect', image, binary=True)
|
||||
|
||||
if face_data:
|
||||
face_ids = [data['faceId'] for data in face_data]
|
||||
detect = await self._api.call_api(
|
||||
'post', 'identify',
|
||||
{'faceIds': face_ids, 'personGroupId': self._face_group})
|
||||
|
||||
except HomeAssistantError as err:
|
||||
_LOGGER.error("Can't process image on Microsoft face: %s", err)
|
||||
return
|
||||
|
||||
# Parse data
|
||||
known_faces = []
|
||||
total = 0
|
||||
for face in detect:
|
||||
total += 1
|
||||
if not face['candidates']:
|
||||
continue
|
||||
|
||||
data = face['candidates'][0]
|
||||
name = ''
|
||||
for s_name, s_id in self._api.store[self._face_group].items():
|
||||
if data['personId'] == s_id:
|
||||
name = s_name
|
||||
break
|
||||
|
||||
known_faces.append({
|
||||
ATTR_NAME: name,
|
||||
ATTR_CONFIDENCE: data['confidence'] * 100,
|
||||
})
|
||||
|
||||
self.async_process_faces(known_faces, total)
|
||||
@@ -1,146 +0,0 @@
|
||||
"""
|
||||
Component that will help set the OpenALPR cloud for ALPR processing.
|
||||
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://home-assistant.io/components/image_processing.openalpr_cloud/
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
from base64 import b64encode
|
||||
|
||||
import aiohttp
|
||||
import async_timeout
|
||||
import voluptuous as vol
|
||||
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.core import split_entity_id
|
||||
from homeassistant.const import CONF_API_KEY
|
||||
from homeassistant.components.image_processing import (
|
||||
PLATFORM_SCHEMA, CONF_CONFIDENCE, CONF_SOURCE, CONF_ENTITY_ID, CONF_NAME)
|
||||
from homeassistant.components.image_processing.openalpr_local import (
|
||||
ImageProcessingAlprEntity)
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
OPENALPR_API_URL = "https://api.openalpr.com/v1/recognize"
|
||||
|
||||
OPENALPR_REGIONS = [
|
||||
'au',
|
||||
'auwide',
|
||||
'br',
|
||||
'eu',
|
||||
'fr',
|
||||
'gb',
|
||||
'kr',
|
||||
'kr2',
|
||||
'mx',
|
||||
'sg',
|
||||
'us',
|
||||
'vn2'
|
||||
]
|
||||
|
||||
CONF_REGION = 'region'
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Required(CONF_API_KEY): cv.string,
|
||||
vol.Required(CONF_REGION): vol.All(vol.Lower, vol.In(OPENALPR_REGIONS)),
|
||||
})
|
||||
|
||||
|
||||
async def async_setup_platform(hass, config, async_add_entities,
|
||||
discovery_info=None):
|
||||
"""Set up the OpenALPR cloud API platform."""
|
||||
confidence = config[CONF_CONFIDENCE]
|
||||
params = {
|
||||
'secret_key': config[CONF_API_KEY],
|
||||
'tasks': "plate",
|
||||
'return_image': 0,
|
||||
'country': config[CONF_REGION],
|
||||
}
|
||||
|
||||
entities = []
|
||||
for camera in config[CONF_SOURCE]:
|
||||
entities.append(OpenAlprCloudEntity(
|
||||
camera[CONF_ENTITY_ID], params, confidence, camera.get(CONF_NAME)
|
||||
))
|
||||
|
||||
async_add_entities(entities)
|
||||
|
||||
|
||||
class OpenAlprCloudEntity(ImageProcessingAlprEntity):
|
||||
"""Representation of an OpenALPR cloud entity."""
|
||||
|
||||
def __init__(self, camera_entity, params, confidence, name=None):
|
||||
"""Initialize OpenALPR cloud API."""
|
||||
super().__init__()
|
||||
|
||||
self._params = params
|
||||
self._camera = camera_entity
|
||||
self._confidence = confidence
|
||||
|
||||
if name:
|
||||
self._name = name
|
||||
else:
|
||||
self._name = "OpenAlpr {0}".format(
|
||||
split_entity_id(camera_entity)[1])
|
||||
|
||||
@property
|
||||
def confidence(self):
|
||||
"""Return minimum confidence for send events."""
|
||||
return self._confidence
|
||||
|
||||
@property
|
||||
def camera_entity(self):
|
||||
"""Return camera entity id from process pictures."""
|
||||
return self._camera
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the entity."""
|
||||
return self._name
|
||||
|
||||
async def async_process_image(self, image):
|
||||
"""Process image.
|
||||
|
||||
This method is a coroutine.
|
||||
"""
|
||||
websession = async_get_clientsession(self.hass)
|
||||
params = self._params.copy()
|
||||
|
||||
body = {
|
||||
'image_bytes': str(b64encode(image), 'utf-8')
|
||||
}
|
||||
|
||||
try:
|
||||
with async_timeout.timeout(self.timeout, loop=self.hass.loop):
|
||||
request = await websession.post(
|
||||
OPENALPR_API_URL, params=params, data=body
|
||||
)
|
||||
|
||||
data = await request.json()
|
||||
|
||||
if request.status != 200:
|
||||
_LOGGER.error("Error %d -> %s.",
|
||||
request.status, data.get('error'))
|
||||
return
|
||||
|
||||
except (asyncio.TimeoutError, aiohttp.ClientError):
|
||||
_LOGGER.error("Timeout for OpenALPR API")
|
||||
return
|
||||
|
||||
# Processing API data
|
||||
vehicles = 0
|
||||
result = {}
|
||||
|
||||
for row in data['plate']['results']:
|
||||
vehicles += 1
|
||||
|
||||
for p_data in row['candidates']:
|
||||
try:
|
||||
result.update(
|
||||
{p_data['plate']: float(p_data['confidence'])})
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
self.async_process_plates(result, vehicles)
|
||||
@@ -1,216 +0,0 @@
|
||||
"""
|
||||
Component that will help set the OpenALPR local for ALPR processing.
|
||||
|
||||
For more details about this platform, please refer to the documentation at
|
||||
https://home-assistant.io/components/image_processing.openalpr_local/
|
||||
"""
|
||||
import asyncio
|
||||
import io
|
||||
import logging
|
||||
import re
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.core import split_entity_id, callback
|
||||
from homeassistant.const import CONF_REGION
|
||||
from homeassistant.components.image_processing import (
|
||||
PLATFORM_SCHEMA, ImageProcessingEntity, CONF_CONFIDENCE, CONF_SOURCE,
|
||||
CONF_ENTITY_ID, CONF_NAME, ATTR_ENTITY_ID, ATTR_CONFIDENCE)
|
||||
from homeassistant.util.async_ import run_callback_threadsafe
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
RE_ALPR_PLATE = re.compile(r"^plate\d*:")
|
||||
RE_ALPR_RESULT = re.compile(r"- (\w*)\s*confidence: (\d*.\d*)")
|
||||
|
||||
EVENT_FOUND_PLATE = 'image_processing.found_plate'
|
||||
|
||||
ATTR_PLATE = 'plate'
|
||||
ATTR_PLATES = 'plates'
|
||||
ATTR_VEHICLES = 'vehicles'
|
||||
|
||||
OPENALPR_REGIONS = [
|
||||
'au',
|
||||
'auwide',
|
||||
'br',
|
||||
'eu',
|
||||
'fr',
|
||||
'gb',
|
||||
'kr',
|
||||
'kr2',
|
||||
'mx',
|
||||
'sg',
|
||||
'us',
|
||||
'vn2'
|
||||
]
|
||||
|
||||
CONF_ALPR_BIN = 'alp_bin'
|
||||
|
||||
DEFAULT_BINARY = 'alpr'
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Required(CONF_REGION): vol.All(vol.Lower, vol.In(OPENALPR_REGIONS)),
|
||||
vol.Optional(CONF_ALPR_BIN, default=DEFAULT_BINARY): cv.string,
|
||||
})
|
||||
|
||||
|
||||
async def async_setup_platform(hass, config, async_add_entities,
|
||||
discovery_info=None):
|
||||
"""Set up the OpenALPR local platform."""
|
||||
command = [config[CONF_ALPR_BIN], '-c', config[CONF_REGION], '-']
|
||||
confidence = config[CONF_CONFIDENCE]
|
||||
|
||||
entities = []
|
||||
for camera in config[CONF_SOURCE]:
|
||||
entities.append(OpenAlprLocalEntity(
|
||||
camera[CONF_ENTITY_ID], command, confidence, camera.get(CONF_NAME)
|
||||
))
|
||||
|
||||
async_add_entities(entities)
|
||||
|
||||
|
||||
class ImageProcessingAlprEntity(ImageProcessingEntity):
|
||||
"""Base entity class for ALPR image processing."""
|
||||
|
||||
def __init__(self):
|
||||
"""Initialize base ALPR entity."""
|
||||
self.plates = {}
|
||||
self.vehicles = 0
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
"""Return the state of the entity."""
|
||||
confidence = 0
|
||||
plate = None
|
||||
|
||||
# search high plate
|
||||
for i_pl, i_co in self.plates.items():
|
||||
if i_co > confidence:
|
||||
confidence = i_co
|
||||
plate = i_pl
|
||||
return plate
|
||||
|
||||
@property
|
||||
def device_class(self):
|
||||
"""Return the class of this device, from component DEVICE_CLASSES."""
|
||||
return 'alpr'
|
||||
|
||||
@property
|
||||
def state_attributes(self):
|
||||
"""Return device specific state attributes."""
|
||||
attr = {
|
||||
ATTR_PLATES: self.plates,
|
||||
ATTR_VEHICLES: self.vehicles
|
||||
}
|
||||
|
||||
return attr
|
||||
|
||||
def process_plates(self, plates, vehicles):
|
||||
"""Send event with new plates and store data."""
|
||||
run_callback_threadsafe(
|
||||
self.hass.loop, self.async_process_plates, plates, vehicles
|
||||
).result()
|
||||
|
||||
@callback
|
||||
def async_process_plates(self, plates, vehicles):
|
||||
"""Send event with new plates and store data.
|
||||
|
||||
plates are a dict in follow format:
|
||||
{ 'plate': confidence }
|
||||
|
||||
This method must be run in the event loop.
|
||||
"""
|
||||
plates = {plate: confidence for plate, confidence in plates.items()
|
||||
if confidence >= self.confidence}
|
||||
new_plates = set(plates) - set(self.plates)
|
||||
|
||||
# Send events
|
||||
for i_plate in new_plates:
|
||||
self.hass.async_add_job(
|
||||
self.hass.bus.async_fire, EVENT_FOUND_PLATE, {
|
||||
ATTR_PLATE: i_plate,
|
||||
ATTR_ENTITY_ID: self.entity_id,
|
||||
ATTR_CONFIDENCE: plates.get(i_plate),
|
||||
}
|
||||
)
|
||||
|
||||
# Update entity store
|
||||
self.plates = plates
|
||||
self.vehicles = vehicles
|
||||
|
||||
|
||||
class OpenAlprLocalEntity(ImageProcessingAlprEntity):
|
||||
"""OpenALPR local api entity."""
|
||||
|
||||
def __init__(self, camera_entity, command, confidence, name=None):
|
||||
"""Initialize OpenALPR local API."""
|
||||
super().__init__()
|
||||
|
||||
self._cmd = command
|
||||
self._camera = camera_entity
|
||||
self._confidence = confidence
|
||||
|
||||
if name:
|
||||
self._name = name
|
||||
else:
|
||||
self._name = "OpenAlpr {0}".format(
|
||||
split_entity_id(camera_entity)[1])
|
||||
|
||||
@property
|
||||
def confidence(self):
|
||||
"""Return minimum confidence for send events."""
|
||||
return self._confidence
|
||||
|
||||
@property
|
||||
def camera_entity(self):
|
||||
"""Return camera entity id from process pictures."""
|
||||
return self._camera
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the entity."""
|
||||
return self._name
|
||||
|
||||
async def async_process_image(self, image):
|
||||
"""Process image.
|
||||
|
||||
This method is a coroutine.
|
||||
"""
|
||||
result = {}
|
||||
vehicles = 0
|
||||
|
||||
alpr = await asyncio.create_subprocess_exec(
|
||||
*self._cmd,
|
||||
loop=self.hass.loop,
|
||||
stdin=asyncio.subprocess.PIPE,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.DEVNULL
|
||||
)
|
||||
|
||||
# Send image
|
||||
stdout, _ = await alpr.communicate(input=image)
|
||||
stdout = io.StringIO(str(stdout, 'utf-8'))
|
||||
|
||||
while True:
|
||||
line = stdout.readline()
|
||||
if not line:
|
||||
break
|
||||
|
||||
new_plates = RE_ALPR_PLATE.search(line)
|
||||
new_result = RE_ALPR_RESULT.search(line)
|
||||
|
||||
# Found new vehicle
|
||||
if new_plates:
|
||||
vehicles += 1
|
||||
continue
|
||||
|
||||
# Found plate result
|
||||
if new_result:
|
||||
try:
|
||||
result.update(
|
||||
{new_result.group(1): float(new_result.group(2))})
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
self.async_process_plates(result, vehicles)
|
||||
Reference in new issue
Block a user