Agent lambda development
========================
Here is *agent* lambda development description.
.. note::
For a comprehensive reference of all available functions, classes, and constants for each lambda type,
see the `Lambda reference table <./lambda_reference.html>`_.
More information about lambda types and the differences between
*agent* and others available at `lambda types description <./lambda_types.html#standalone>`_.
More information about LUNA videoanalytics, in particular, *luna-video-manager*, *video-agents* and their interaction
see its' developers manuals.
.. note::
There is a service internal http resource in lambda-agent which show *agent_id*, the *streams* which are taken in progress by
lambda agent and other things (see lambda agent `/agent/info` resource from agent spec documentation available
by using `get lambda documentation request <./_static/api.html#operation/getLambdaSpec>`_)
Agent lambda requirements
-------------------------
Agent lambda has several requirements to addition with `basic requirements <./lambda_requirements.html#lunaservicesrequirements>`_:
- `Luna Video Manager` available by credentials from `Luna-Configurator`
- `Luna Licenses` available by credentials from `Luna-Configurator`
- `Luna Events` available by credentials from `Luna-Configurator`; it can be disabled using the
*ADDITIONAL_SERVICES_USAGE* setting and it this case *lambda* should provide for work without `Luna-Events` usage
- `Luna Sender` available by credentials from `Luna-Configurator`; it can be disabled using the
*ADDITIONAL_SERVICES_USAGE* setting and it this case *lambda* should provide for work without `Luna-Sender` usage
- `Luna Faces/Images Samples Store` available by credentials from `Luna-Configurator`; it can be disabled using the
*ADDITIONAL_SERVICES_USAGE* setting and it this case *lambda* should provide for work without `Luna-Image-Store` usage
- Some kernel parameters must but adjusted on k8s node level for the agent `retransmission_fallback` feature to work:
- `fs.inotify.max_user_instances` - 1280
- `fs.inotify.max_user_watches` - 655360
Lower values could cause `retransmission_fallback` to stop working.
Agent lambda configuration
--------------------------
Luna-Configurator settings
~~~~~~~~~~~~~~~~~~~~~~~~~~
The agent lambda required several settings from *luna-configurator*, whose can be separated to several groups:
- *LUNA_LAMBDA_AGENT_UNIT_LOGGER* - lambda logger settings
- luna-services addresses and timeouts settings (for example, *LUNA_EVENTS_ADDRESS* and *LUNA_EVENTS_TIMEOUTS* will
be used by the lambda to make requests to the *luna-events* service)
- *ADDITIONAL_SERVICES_USAGE* setting will be used to determine which *luna-services* can be used by the lambda
(the lambda will not check connection to disabled services and will raise an error if a user try to make a request
to such a service)
- *LUNA_LAMBDA_AGENT_UNIT_ANALYTICS_SETTINGS* - lambda analytics-specific settings, for example, settings of which
device must be used by one or another analytics - CPU or GPU
- *LUNA_LAMBDA_AGENT_UNIT_VIDEO_SETTINGS* / *LUNA_LAMBDA_AGENT_UNIT_RUNTIME_SETTINGS* - lambda video processing settings
User settings
~~~~~~~~~~~~~
Some agent lambda settings, which are received from *Luna-Configurator* by default,
can be overridden by settings from the `user config <./lambda_config.html#user-config>`_.
If the user settings do not pass validation, they are ignored. (See the validation schemes in Luna-Configurator.)
.. list-table::
:header-rows: 1
* - User setting
- Configurator setting
* - ``max_stream_count``
- ``LUNA_LAMBDA_AGENT_UNIT_SETTINGS.max_active_streams``
* - ``luna_video_agent_groups``
- ``LUNA_LAMBDA_AGENT_UNIT_GROUPS``
External agent
--------------
An agent can be started as an external service by setting up agent creation parameters. In this regime agent
will be treated as external to the main product service and all communication with the product will be performed via
the `luna-api` service. Running an agent in this regime requires luna account credentials or an access token set via the creation parameters.
Note, that used token must be provided with specific permissions to work properly.
The minimal set of permissions is:
.. code-block:: json
{
"event": ["creation"],
"image": ["creation"],
"video_stream": ["creation"],
"video_analytic": ["view", "creation", "modification"],
"video_agent": ["creation", "deletion"],
}
Things to note:
- **Services** `luna-api`, `luna-licenses` **and** `luna-configurator` **services must be available for the external lambda agent**
- **If some of the analytics were previously created by an internal agent or external agent with other account id,
the agent will not start, as the analytics update will fail. To overcome this analytics must be removed manually**
- **Only** `luna-api <./luna_clients.html#luna-api-client>`_ **client will be available for use in custom routes**
Read `luna-video-agent` development documentation for more information
Autonomous agent
----------------
Besides creating streams for the lambda agent via `Luna Video Manager` it is possible to launch streams directly from the lambda agent. This autonomous regime has it limitations and lacks
some of the features of the standard way of creating streams. For more informations see the `autonomous` section of the `Luna Video Agent` developer documentation.
**Note: all autonomous streams, logs, etc. will be lost after lambda pod shutdown**
Agent lambda development
------------------------
Lambda agent works with analytics, each lambda agent must have at least one video analytics.
It is possible to specify video analytics as a separate package which will installed as a lambda dependency or
include analytics as a module into lambda. The `lambda_main.py` and other configuration files will not differ in this
cases.
The description below describes the case when the analytics represents itself separate package, for description in the
case of analytics is a module in lambda see the `analytics development chapter <./agent.html#agent-video-analytics-development>`_.
The agent lambda development in the easiest way consists of it's configuration by specifying several parameters in
the *lambda_main.py* file.
.. warning::
The names of analytics, features, etc. listed below are fictitious and have nothing in common with the names of
real analytics, etc.
The only required variable which must be specified is the list of available analytics, which also must be specified
as lambda requirements, for example:
.. code-block::
:caption: lambda_main.py
#: list of analytics for agent lambda
AVAILABLE_ANALYTICS = ["people"]
.. code-block::
:caption: requirements.txt
people_analytics==1.2.0
There are some more parameters which can also be relevant:
The `ANALYTICS_LICENSE_FEATURES` is a map with analytics and their licensing feature names. If an analytics not required
licensing, it must not be included in this map. If no one analytics must depends on licensing, this map must be empty
or may not be included in `lambda_main.py`.
The `ESTIMATORS_TO_INITIALIZE` and `ESTIMATORS_TARGETS` are lists of SDK estimators and their targets which must
initialized before the analytics usage. If no one analytics not required SDK estimators usage, this lists must be empty
or may not be included in `lambda_main.py`.
.. note::
In this example lambda has the *people_analytics* package version 1.2.0 as a requirement, which represents video
analytics package with analytics named *people*. The usage of this analytics is regulated by a license feature
named *people_feature*. It requires the estimator from the *luna-sdkloop* package named *people* and the *people*
target estimator to be initialized before the lambda starts.
.. code-block::
:caption: lambda_main.py
from sdk_loop.enums import Estimators, LoopEstimations
#: list of analytics for agent lambda
AVAILABLE_ANALYTICS = ["people"]
#: map with analytics and their license features
ANALYTICS_LICENSE_FEATURES = {"people": "people_feature"}
#: list of estimators for initialization
ESTIMATORS_TO_INITIALIZE = [Estimators.people]
#: list of estimators targets for initialization
ESTIMATORS_TARGETS = [LoopEstimations.people]
.. code-block::
:caption: requirements.txt
people_analytics==1.2.0
There are some more settings which can be used for an *agent* lambda in the *lambda_main.py* file:
.. code-block::
:caption: lambda_main.py
# count of video-agent registration attempt in *luna-video-manager*
REGISTRATION_ATTEMPT_COUNT = 5
# delay between registration attempts
REGISTRATION_ATTEMPT_DELAY = 1
# max size of feedback which can be sent to *luna-video-manager* at one time
FEEDBACK_MAX_BATCH_COUNT = 1000
# the code of response for ws-connections when the agent shutdown
WSCODE_GOING_AWAY = 1001
# the name of the lambda video-agent which will be registered in *luna-video-manager*
AGENT_NAME = "luna-lambda-great-video-agent"
# the description of the lambda video-agent which will be registered in *luna-video-manager*
AGENT_DESCRIPTION = "luna-lambda-greatest-video-agent"
The are many other possibilities to modify such a lambda agent behavior, it's interaction with analytics and so on, which
can be realized in the same way as regular *luna-video-agent*, for more information, see the *luna-video-agent* developers
manual.
Agent video analytics development
---------------------------------
It is possible to specify video analytics as a separate package which will installed as a lambda dependency or
include analytics as a module into lambda. The description below describes analytics module, which can then be included
as a module or package.
.. note::
A complete user video analytics development guide is in development and will be included in future releases.
In presented example(s) the `poetry `_ tool using for dependencies management, so
the *pyproject.toml* file is filled by the user and the *poetry.lock* file must be generated using the *poetry* tool.
The example of a video analytics which detect suits in video/streams and generate events if suits appears.
**Suit analytics description**
**How it works**: The analytics processes video frames through a ResNet-50 neural network to classify whether a person is wearing a suit.
It supports both CPU and GPU inference, with configurable frame processing rates and region-of-interest (ROI) analysis.
**When events are generated**: Events are generated based on configurable policies:
- **Start trigger** (default): Events when a suit is first detected
- **End trigger**: Events when suit detection ends
- **Periodic trigger**: Events at regular intervals during detection
By default event will be generated when a suit is detected.
.. code-block:: json
{
"account_id": "string",
"event_create_time": "string",
"event_end_time": "string",
"event_type": "suit",
"event": {
"stream_id": "557d54ec-29ad-4f3c-93b4-c9092ef12515",
"event_id": "557d54ec-29ad-4f3c-93b4-c9092ef12515",
"track_id": "557d54ec-29ad-4f3c-93b4-c9092ef12515",
"source": "string",
"name": "suit",
"overview": {
"image": "string",
"time_offset": 1.234
},
"location": {
"city": "St. Louis",
"area": "Central",
"district": "Downtown",
"street": "Washington Avenue",
"house_number": "100",
"geo_position": {
"longitude": -90.185,
"latitude": 38.624
}
},
"video_segment": {
"start_time_offset": 0.123,
"end_time_offset": 1.234
}
}
}
.. note::
The example below uses an image classification model (`"resnet50-v2-7.onnx" `_)
and a json file (`"imagenet-simple-labels.json" `_) from
`github `_.
To make this example works it needs to get this files from github and place into the *data* folder of the lambda agent archive.
.. code-block::
:caption: Suit analytics example file structure itself
├──__init__.py
├──analytics.py
├──classes.py
├──common.py
├──models.py
├──spec.html
├──spec.yml
└──data
├──resnet50-v2-7.onnx
└──imagenet-simple-labels.json
└──suit_nodes
├──__init__.py
├──events.py
├──suit_estimator.py
└──suid_nodes.py
.. note::
The video analytics requires some dependencies which are available on `the company's pypi `_
for local run. All provided examples use the company's pypi specification at `tool.poetry.source` section of
the *pyproject.toml* file which make possible to install dependencies from the above source.
It is also required HASP license provided by the software provider. For agent lambda creation, all
required video analytics dependencies are already included in the base image (which is used for agent lambda building).
If it needs to build this analytics as a separate package, it must include its' dependencies for example using the
pyproject.toml/poetry.lock files:
.. literalinclude:: examples/200/agent_lambda_suit/lambda/suit_analytics/pyproject.toml
:caption: pyproject.toml
:language: toml
After dependencies resolving it must be built into a packages (for example, using `poetry build`).
.. raw:: html
The *__init__.py* module must contains all presented imported objects and classes to make the analytics works.
.. literalinclude:: examples/200/agent_lambda_suit/lambda/suit_analytics/__init__.py
:caption: __init__.py
:language: python
.. raw:: html
.. raw:: html
The *analytics.py* module contains the analytics initialization, frame, and analytics contexts.
.. literalinclude:: examples/200/agent_lambda_suit/lambda/suit_analytics/analytics.py
:caption: analytics.py
:language: python
.. raw:: html
.. raw:: html
The *classes.py* module contains frame and analytics results containers description.
.. literalinclude:: examples/200/agent_lambda_suit/lambda/suit_analytics/classes.py
:caption: classes.py
:language: python
.. raw:: html
.. raw:: html
The *common.py* module contains the analytics target, mandatory nodes, and the `getDocumentation` function
which returns raw html analytics documentation for the user.
.. literalinclude:: examples/200/agent_lambda_suit/lambda/suit_analytics/common.py
:caption: common.py
:language: python
.. raw:: html
.. raw:: html
The *models.py* module contains the analytics parameters models.
.. literalinclude:: examples/200/agent_lambda_suit/lambda/suit_analytics/models.py
:caption: models.py
:language: python
.. raw:: html
.. raw:: html
The *__init__.py* module in the *suit_nodes* path is empty.
.. literalinclude:: examples/200/agent_lambda_suit/lambda/suit_analytics/suit_nodes/__init__.py
:caption: __init__.py
:language: python
.. raw:: html
.. raw:: html
The *events.py* module in the *suit_nodes* path contains events and track structures.
.. literalinclude:: examples/200/agent_lambda_suit/lambda/suit_analytics/suit_nodes/events.py
:caption: events.py
:language: python
.. raw:: html
.. raw:: html
The *suit_estimator.py* module in the *suit_nodes* path contains the suit estimator responsible
for image preprocessing, processing and neural model results postprocessing.
.. literalinclude:: examples/200/agent_lambda_suit/lambda/suit_analytics/suit_nodes/suit_estimator.py
:caption: suit_estimator.py
:language: python
.. raw:: html
.. raw:: html
The *suit_nodes.py* module in the *suit_nodes* path contains the suit nodes structures.
.. literalinclude:: examples/200/agent_lambda_suit/lambda/suit_analytics/suit_nodes/suit_nodes.py
:caption: suit_nodes.py
:language: python
.. raw:: html
.. raw:: html
The *spec.yml* file contains the openapi documentation with analytics parameters description in yaml format.
.. literalinclude:: examples/200/agent_lambda_suit/lambda/suit_analytics/spec.yml
:caption: spec.yml
:language: yaml
.. raw:: html
`The *spec.html* file contains the openapi documentation with analytics parameters description in html format. <./_static/suit_spec.html>`_
|
Agent lambda service clients
----------------------------
The set of luna services clients available for an *agent* lambda depends on its regime.
An **internal** agent lambda can use the following clients: ``events``, ``faceSamplesStore``,
``bodySamplesStore``, ``imageOriginStore``, ``sdk``, ``videoAgent``, ``sender``, ``handlers`` and always
available ``lambdas``. The ``faces``, ``matcher``, ``objectOriginStore`` and ``api`` clients are not
available for this lambda type.
An **external** agent lambda communicates with the platform only via *luna-api*, so it has just two
clients: ``api`` (complete REST api of the platform, see
`Luna Api client <./luna_clients.html#luna-api-client>`_) and always available ``lambdas``. All other
typed clients are unavailable, use ``request.clients.api`` instead, in particular in custom routes
(see `external agent <#external-agent>`_).
In both regimes the clients are accessed through the request object (in custom routes it is available as
``self.request.clients``), the same way as for other lambda types:
.. code-block::
:caption: lambda_main.py
from luna_lambda_tools import LambdaUserHandler
class AdditionalHandler(LambdaUserHandler):
route = r"/additional"
async def post(self):
self.request.clients.events.saveEvents(events=[...]) # internal agent only
return self.sendResponse(json={"status": "success"})
ROUTES_TO_ADD = [AdditionalHandler]
Accessing a client of a disabled or unsupported service raises ``UserTaskLambdaException``. See the
`clients reference <./luna_clients.html>`_ for the full description of every client.
Agent lambda examples
---------------------
**Example of an agent lambda with suit video analytics:**
To include the video analytics presented in the `previous chapter `_ into lambda agent as a package
() it needs the following lambda archive file structure:
.. code-block::
:caption: Lambda agent with suit analytics example file structure (the case when the analytics includes in the lambda as a package)
├──pyproject.toml
├──poetry.lock
└──lambda_main.py
The `lambda_main.py` module:
.. literalinclude:: examples/200/agent_lambda_suit/lambda/lambda_main.py
:caption: lambda_main.py
:language: python
It this case, the dependencies of the lambda agent must include only the analytics as dependency, not the analytics dependencies:
.. raw:: html
*pyproject.toml*
.. literalinclude:: examples/200/agent_lambda_suit/lambda/pyproject_minimal.toml
:caption: pyproject.toml
:language: toml
.. raw:: html
|
To include the video analytics presented in the `previous chapter `_ into lambda agent as a module it needs the following lambda archive file structure
(just put all files except *pyproject.toml* and *poetry.lock*, which are not needed in this case, into a newly created *suit_analytics* folder):
.. code-block::
:caption: Lambda agent with suit analytics example file structure (the case when the analytics includes in the lambda as a module)
├──pyproject.toml
├──poetry.lock
├──lambda_main.py
└──suit_analytics
├──__init__.py
├──analytics.py
├──classes.py
├──common.py
├──models.py
├──spec.html
├──spec.yml
└──data
├──resnet50-v2-7.onnx
└──imagenet-simple-labels.json
└──suit_nodes
├──__init__.py
├──events.py
├──suit_estimator.py
└──suid_nodes.py
|
In this case, the analytics dependencies must be included into lambda dependencies. The lambda dependencies are described
as *pyproject.toml* file:
.. raw:: html
*pyproject.toml*
.. literalinclude:: examples/200/agent_lambda_suit/lambda/pyproject.toml
:caption: pyproject.toml
:language: toml
.. raw:: html
|
**Example of an agent lambda with animals video analytics:**
Video analytics implementation using ONNX YOLOv3 model from the `ONNX Model Zoo `_.
The analytics tracks the appearance of animals in video frames. Processing frame by frame, it:
- **Starts a track** when at least one animal appears in the frame that the YOLOv3 model is capable of detecting
- **Ends a track** when all animals disappear from the frame.
Example requires
Events sent via callback:
.. code-block:: json
{
"event_type": "animal_detection",
"account_id": "557d54ec-29ad-4f3c-93b4-c9092ef12515",
"event_create_time": "string",
"event_end_time": "string",
"event": {
"stream_id": "557d54ec-29ad-4f3c-93b4-c9092ef12515",
"track_id": "557d54ec-29ad-4f3c-93b4-c9092ef12515",
"track_status": "started"
}
}
Exemple requires
At key moments when tracks begin (an animal appears) and end (an animal disappears), the analytics creates events and executes the configured callbacks.
.. literalinclude:: examples/200/agent_lambda_animal_detector/lambda/lambda-animal-detector-example/lambda_animal_detector_analytics_archive/lambda_main.py
:caption: The *lambda_main.py* contains the list of analytics supported by the agent
:language: python
.. literalinclude:: examples/200/agent_lambda_animal_detector/lambda/lambda-animal-detector-example/lambda_animal_detector_analytics_archive/animal_detector_analytics/analytics.py
:caption: The *analytics.py* module contains the analytics initialization, analytics nodes, frame and analytics contexts.
:language: python
.. literalinclude:: examples/200/agent_lambda_animal_detector/lambda/lambda-animal-detector-example/lambda_animal_detector_analytics_archive/animal_detector_analytics/common.py
:caption: The *common.py* module contains the analytics target, mandatory nodes and the `getDocumentation` function which returns raw html analytics documentation for the user.
:language: python
.. literalinclude:: examples/200/agent_lambda_animal_detector/lambda/lambda-animal-detector-example/lambda_animal_detector_analytics_archive/animal_detector_analytics/estimator.py
:caption: The *estimator.py* module contains animals estimator responsible for image preprocessing, processing and neural model results postprocessing.
:language: python
.. literalinclude:: examples/200/agent_lambda_animal_detector/lambda/lambda-animal-detector-example/lambda_animal_detector_analytics_archive/animal_detector_analytics/models.py
:caption: The *models.py* module contains the analytics result models.
:language: python
.. literalinclude:: examples/200/agent_lambda_animal_detector/lambda/lambda-animal-detector-example/lambda_animal_detector_analytics_archive/animal_detector_analytics/__init__.py
:caption: The *__init__.py* contains all the main objects and classes need for analytic to work.
:language: python
.. literalinclude:: examples/200/agent_lambda_animal_detector/lambda/lambda-animal-detector-example/lambda_animal_detector_analytics_archive/animal_detector_analytics/spec.yml
:caption: spec.yml
:language: yaml
.. raw:: html
`The *spec.html* file contains the openapi documentation with analytics parameters description in html format. <./_static/animal_spec.html>`_
.. code-block::
:caption: Lambda agent with animal analytics example file structure (the case when the analytics includes in the lambda as a module)
├── animal_detector_analytics
│ ├── analytics.py
│ ├── common.py
│ ├── config.conf
│ ├── data
│ │ ├── coco_classes.txt
│ │ └── yolov3-10.onnx
│ ├── estimator.py
│ ├── __init__.py
│ ├── models.py
│ ├── spec.html
│ └── spec.yml
├── lambda_main.py
├── poetry.lock
└── pyproject.toml
In this case, the analytics dependencies must be included into lambda dependencies. The lambda dependencies are described
as *pyproject.toml* file:
.. raw:: html
*pyproject.toml*
.. literalinclude:: examples/200/agent_lambda_animal_detector/lambda/pyproject_full.toml
:caption: pyproject.toml
:language: toml
.. raw:: html
|