core/homeassistant/components/openalpr_cloud/image_processing.py

145 lines
3.7 KiB
Python
Raw Normal View History

"""Component that will help set the OpenALPR cloud for ALPR processing."""
import asyncio
2017-05-17 07:14:11 +00:00
from base64 import b64encode
from http import HTTPStatus
import logging
import aiohttp
import async_timeout
import voluptuous as vol
from homeassistant.components.image_processing import (
2019-07-31 19:25:30 +00:00
CONF_CONFIDENCE,
CONF_ENTITY_ID,
CONF_NAME,
CONF_SOURCE,
PLATFORM_SCHEMA,
2019-07-31 19:25:30 +00:00
)
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.
2019-03-19 06:07:39 +00:00
from homeassistant.components.openalpr_local.image_processing import (
2019-07-31 19:25:30 +00:00
ImageProcessingAlprEntity,
)
from homeassistant.const import CONF_API_KEY, CONF_REGION
from homeassistant.core import split_entity_id
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
OPENALPR_API_URL = "https://api.openalpr.com/v1/recognize"
OPENALPR_REGIONS = [
2019-07-31 19:25:30 +00:00
"au",
"auwide",
"br",
"eu",
"fr",
"gb",
"kr",
"kr2",
"mx",
"sg",
"us",
"vn2",
]
2019-07-31 19:25:30 +00:00
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_API_KEY): cv.string,
vol.Required(CONF_REGION): vol.All(vol.Lower, vol.In(OPENALPR_REGIONS)),
}
)
2019-07-31 19:25:30 +00:00
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 = {
2019-07-31 19:25:30 +00:00
"secret_key": config[CONF_API_KEY],
"tasks": "plate",
"return_image": 0,
"country": config[CONF_REGION],
}
entities = []
for camera in config[CONF_SOURCE]:
2019-07-31 19:25:30 +00:00
entities.append(
OpenAlprCloudEntity(
camera[CONF_ENTITY_ID], params, confidence, camera.get(CONF_NAME)
)
)
async_add_entities(entities)
class OpenAlprCloudEntity(ImageProcessingAlprEntity):
2017-05-17 07:14:11 +00:00
"""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:
2020-04-07 21:14:28 +00:00
self._name = f"OpenAlpr {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()
2019-07-31 19:25:30 +00:00
body = {"image_bytes": str(b64encode(image), "utf-8")}
try:
with async_timeout.timeout(self.timeout):
request = await websession.post(
OPENALPR_API_URL, params=params, data=body
)
data = await request.json()
if request.status != HTTPStatus.OK:
_LOGGER.error("Error %d -> %s", request.status, data.get("error"))
return
except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("Timeout for OpenALPR API")
return
2017-05-17 07:14:11 +00:00
# Processing API data
vehicles = 0
result = {}
2019-07-31 19:25:30 +00:00
for row in data["plate"]["results"]:
vehicles += 1
2019-07-31 19:25:30 +00:00
for p_data in row["candidates"]:
try:
2019-07-31 19:25:30 +00:00
result.update({p_data["plate"]: float(p_data["confidence"])})
except ValueError:
continue
self.async_process_plates(result, vehicles)