Handlers lambda development =========================== Here is *handlers* 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 *handlers* and others available at `lambda types description <./lambda_types.html#handlers>`_. Handlers lambda requirements ---------------------------- The handlers lambda has several requirements in addition to the `basic requirements <./lambda_requirements.html#lunaservicesrequirements>`_: - `Luna Faces` 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 the *lambda* should provide for work without `Luna-Events` usage - `Luna Python Matcher` available by credentials from `Luna-Configurator` - `Luna Faces/Bodies/Images Samples Store` available by credentials from `Luna-Configurator`; it can be disabled using the *ADDITIONAL_SERVICES_USAGE* setting and it this case the *lambda* should provide for work without `Luna-Image-Store` usage - `Luna Remote SDK` available by credentials from `Luna-Configurator` The usage and purpose of these services are described `here <#handlers-lambda-examples>`_. Handlers lambda configuration ----------------------------- The handlers lambda required several settings from *luna-configurator*, whose can be separated to several groups: - *LUNA_LAMBDA_UNIT_LOGGER* - lambda logger settings - luna-services addresses and timeouts settings (for example, *LUNA_FACES_ADDRESS* and *LUNA_FACES_TIMEOUTS* will be used by the lambda to make requests to the *luna-faces* service) - the *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 the user try to make a request to such a service) Handlers lambda request usage ----------------------------- A request to a handlers lambda has some additions compared to the `standalone lambda request <./standalone.html#id1>`_. The `HandlersLambdaRequest` has the `data` property (a detailed description presented at `handlers incoming data <./handlers.html#handlers-lambda-incoming-data>`_) A simple example: .. code-block:: :caption: lambda_main.py from luna_lambda_tools import HandlersLambdaRequest, logger async def main(request: HandlersLambdaRequest) -> dict: logger.info(request.data.sources) # log count of images in the request logger.info(request.handlerId) # request initiator handler id logger.info(request.headers) # all request headers logger.info(request.args) # print dictionary with query arguments ... Handlers lambda incoming data ----------------------------- The handlers lambda must be designed to process requests from the *Luna-Handlers* service. .. raw:: html
The incoming request structure is presented here .. autosummary:: :toctree: _autosummary :recursive: luna_lambda_tools.public.handlers.schemas .. raw:: html
The `data` property usage assumes that the request will be validated using presented schema above and content type of this request is `application/msgpack`. If the request's body content type will differs or the incoming data not pass validation, it will raise an exception and a reply with the 400 status code will be returned. It will be available using `data` property of the incoming request as follows: .. code-block:: :caption: lambda_main.py from luna_lambda_tools import HandlersLambdaRequest, logger async def main(request: HandlersLambdaRequest) -> dict: logger.info("request images count: ", len(request.data.sources)) for i, image in enumerate(request.data.sources): logger.info(f"face bounding box for image number {i+1}: {image.faceBoundingBoxes[0] if image.faceBoundingBoxes else 'not presented'}") ... Handlers lambda service clients ------------------------------- A *handlers* lambda can use the same set of luna services clients as a `standalone lambda <./standalone.html#standalone-lambda-service-clients>`_: ``events``, ``faces``, ``matcher``, ``faceSamplesStore``, ``bodySamplesStore``, ``imageOriginStore``, ``sdk``, ``videoAgent``, ``sender``, ``handlers`` and always available ``lambdas``. The ``objectOriginStore`` and ``api`` clients are not available for this lambda type. Clients are accessed through the request object: .. code-block:: :caption: lambda_main.py from luna_lambda_tools import HandlersLambdaRequest async def main(request: HandlersLambdaRequest) -> dict: faces = request.clients.faces.getFaces(pageSize=10) request.clients.events.saveGeneralEvents(events=[...]) return {"status": "success"} Accessing a client of a disabled service raises ``UserTaskLambdaException``. Which services a *handlers* lambda requires is described in the `handlers lambda requirements <#handlers-lambda-requirements>`_, see also the `clients reference <./luna_clients.html>`_. Handlers lambda examples ------------------------ The handlers lambda can use luna-services for different operations. - The exception whose caused by requests to luna service processing can be regulated using the `raiseError` flag (True by default). The examples demonstrate `raiseError` flag usage: - if a request to a luna service causes an error, an exception will be raised and the example will returns response with the 500 status code and a json like this: .. literalinclude:: examples/500/handlers_lambda_status_500/lambda/lambda_main.py :caption: lambda_main.py :language: python .. literalinclude:: examples/500/handlers_lambda_status_500/make_request.py :caption: request example :language: python .. code-block:: { "error_code": 42004, "desc": "Lambda exception", "detail": "Not expected code from service: 404 GET http://127.0.0.1:5030/3/faces/048e1428-c7de-426b-82f8-3971bf00284c, error: {\"error_code\":22002,\"desc\":\"Object not found\",\"detail\":\"Face with id '048e1428-c7de-426b-82f8-3971bf00284c' not found\",\"link\":\"http:\\/\\/127.0.0.1:5320\\/info\\/luna\\/troubleshooting\\/errors-description\\/code-22002\"}", "link": "http://127.0.0.1:5320/info/luna/troubleshooting/errors-description/code-42005" } - in this case, the request will raise an error and for any request, labmda will return response with the 201 status code and a json like this: .. literalinclude:: examples/201/handlers_lambda_status_201/lambda/lambda_main.py :caption: lambda_main.py :language: python .. literalinclude:: examples/201/handlers_lambda_status_201/make_request.py :caption: request example :language: python .. code-block:: { "error_code": 22002, "desc": "Object not found", "detail": "Face with id 'fece7f31-ea14-40fb-8c57-40230aa17256' not found", "link": "http://127.0.0.1:5320/info/luna/troubleshooting/errors-description/code-22002" } - An example lambda which use canonical product handler, enrich received result and send it to the user as a reply. The id of the canonical (non-lambda) handler is specified by a query parameter. (such a lambda cannot be used as a canonical *luna* handler) .. literalinclude:: examples/201/handlers_lambda_enrich/lambda/lambda_main.py :caption: lambda_main.py :language: python .. literalinclude:: examples/201/handlers_lambda_enrich/make_request.py :caption: request example :language: python - An example lambda which estimates emotions for each specified image and return received results as a reply (such a lambda cannot be used as a canonical *luna* handler) .. literalinclude:: examples/201/handlers_lambda_estimate/lambda/lambda_main.py :caption: lambda_main.py :language: python .. literalinclude:: examples/201/handlers_lambda_estimate/make_request.py :caption: request example :language: python - A lambda example which extracts a face descriptor from an image, match it against general events, saves the general event if there is any general event and its' descriptor similarity higher than the threshold and return most similar general event id and similarity as a reply (such a lambda cannot be used as a canonical *luna* handler) .. literalinclude:: examples/201/handlers_lambda_extract_and_match_general/lambda/lambda_main.py :caption: lambda_main.py :language: python .. literalinclude:: examples/201/handlers_lambda_extract_and_match_general/make_request.py :caption: request example :language: python - A lambda example which extracts face descriptors from two images, match them, saves the general event if the similarity higher than the threshold and return result as a reply (such a lambda cannot be used as a canonical *luna* handler) .. literalinclude:: examples/201/handlers_lambda_extract_and_match/lambda/lambda_main.py :caption: lambda_main.py :language: python .. literalinclude:: examples/201/handlers_lambda_extract_and_match/make_request.py :caption: request example :language: python - A lambda example which extracts the face descriptor, basic attributes and saves the face descriptor, sample and event with the estimated data (such a lambda can be used as a canonical *luna* handler) .. literalinclude:: examples/201/handlers_lambda_extract_and_save/lambda/lambda_main.py :caption: lambda_main.py :language: python .. literalinclude:: examples/201/handlers_lambda_extract_and_save/make_request.py :caption: request example :language: python - A lambda example which gets a face detection and estimate mask in some detection area directly using the LUNA SDK (such a user lambda cannot be used as a canonical *luna* handler) (available at http://pypi.vlabs/root/public/lunavl) The LUNA python SDK must be added it to requirements.txt (`requirements description available here `_) .. note:: The LUNA python SDK is named and can be imported as the `lunavl` library in the lambda code. .. literalinclude:: examples/201/handlers_lambda_sdk/lambda/requirements.txt :caption: requirements.txt .. note:: To develop a lambda with lunasdk locally it needs LUNA FSDK python bindings to be installed previously. .. warning:: Such a user lambda requires the LUNA SDK data available from the user lambda (the `fsdk/data` folder next to the `lambda_main.py` main file) The SDK is available on the company release portal which must be extracted to the `fsdk` folder (see the archive file structure below). The only thing which is needed is *data* folder with used fsdk plans and config files (*faceengine.conf* and *runtime.conf*). It is recommended to not include irrelevant plans from the folder in the archive to decrease result lambda image size. .. code-block:: :caption: Archive file structure with files required for the example ├──lambda_main.py ├──requirements.txt └──fsdk └──data ├──faceengine.conf ├──runtime.conf ├──FaceDet_v3_a5_cpu-avx2.plan ├──FaceDet_v3_redetect_v3_cpu-avx2.plan ├──LNet_precise_v2_cpu-avx2.plan ├──mask_clf_v3_cpu-avx2.plan └──slnet_v6_cpu-avx2.plan .. literalinclude:: examples/201/handlers_lambda_sdk/lambda/lambda_main.py :caption: lambda_main.py :language: python .. literalinclude:: examples/201/handlers_lambda_sdk/make_request.py :caption: request example :language: python The LUNA SDK can work with a CPU or GPU, by default all estimations, extraction and so on carried out using CPU. The GPU usage allows to speed up most of the above actions. For more information about GPU usage, see the `LUNA SDK documentation `_. It also needs to add the required GPU plans to the `fsdk/data` folder. Add the following code to the example to enable GPU usage for all estimators/extractor: .. code-block:: python :caption: example from lunavl.sdk.launch_options import DeviceClass, LaunchOptions from lunavl.sdk.faceengine.setting_provider import RuntimeSettingsProvider ... runtimeSettings = RuntimeSettingsProvider() runtimeSettings.runtimeSettings.deviceClass = DeviceClass.gpu faceEngine = VLFaceEngine(runtimeConf=runtimeSettings) ... Add the following code to the example to enable GPU usage for one specified estimator/extractor: .. code-block:: python :caption: example from lunavl.sdk.launch_options import DeviceClass, LaunchOptions ... faceEngine = VLFaceEngine() extractor = faceEngine.createFaceDescriptorEstimator(launchOptions=LaunchOptions(deviceClass=DeviceClass.gpu)) ...