# Notifier

{% hint style="info" %}
This API Reference is based on DeGirum Tools version 1.2.0.
{% endhint %}

## Notification Analyzer Module Overview <a href="#notification-analyzer-module-overview" id="notification-analyzer-module-overview"></a>

This module provides tools for generating and delivering notifications based on AI inference events. It implements the `EventNotifier` analyzer for triggering notifications and optional clip saving on events.

Key Features

* Event-Based Triggers: Generates notifications when user-defined event conditions are met
* Message Formatting: Supports `${expression}` fields for dynamic notification content
* Holdoff Control: Configurable time/frame windows to suppress repeat notifications
* Video Clip Saving: Optional video clip saving with local or cloud storage
* Visual Overlay: Annotates active notification status on images
* File Management: Handles temporary file cleanup and storage integration

Typical Usage

1. Configure notification service. For external services, use Apprise URL or config file. For console output, use "json://console" as notification\_config
2. Define event conditions and create `EventNotifier` instances
3. Process inference results through the notifier chain
4. Notifications are sent when conditions are met

Integration Notes

* Requires `EventDetector` analyzer in the chain to provide event detection
* Optional dependencies (e.g., apprise) must be installed for external notification services
* Storage configuration required for clip saving (supports both local and cloud storage)
* Supports both frame-based and time-based notification holdoff periods

Key Classes

* `EventNotifier`: Analyzer for triggering notifications based on event conditions

Configuration Options

* `notification_config`: Apprise URL or config file for notification service, or "json://console" for stdout output
* `notification_title`: Default title for notifications
* `holdoff_frames`: Number of frames to wait between notifications
* `holdoff_seconds`: Time in seconds to wait between notifications
* `clip_save`: Enable/disable video clip saving
* `storage_config`: Storage configuration for clip saving (supports local and cloud storage)
* `show_overlay`: Enable/disable visual annotations

Message Formatting

* Use `${expression}` fields in the `message` parameter to include dynamic content (e.g., `${time}` for the time the notification was sent)
* Use markdown formatting for rich text notifications (e.g. `**bold**`, `*italic*`, `[link](url)`)
* Supported variables to use in `${expression}` fields include:
  * `${result}`: The inference result
  * `${time}`: The time the notification was sent
  * `${url}`: The URL of the uploaded file
  * `${filename}`: The name of the uploaded file

Example

For local storage configuration:

{% code overflow="wrap" %}

```
clip_storage_config = ObjectStorageConfig(
    endpoint=".",  # path to local folder
    access_key="",  # not needed for local storage
    secret_key="",  # not needed for local storage
    bucket="my_bucket_dir",  # subdirectory name for local storage
)
```

{% endcode %}

## Classes <a href="#classes" id="classes"></a>

## EventNotifier <a href="#eventnotifier" id="eventnotifier"></a>

`EventNotifier`

Bases: `ResultAnalyzerBase`

Analyzer for event-based notifications.

Works in conjunction with an `EventDetector` analyzer by examining the `events_detected` set in the inference results. Generates notifications when user-defined event conditions are met.

Features

* Message Formatting: supports `${expression}` fields for dynamic notification content.
* Holdoff to suppress repeat notifications within a specified time/frame window
* Optional video clip saving upon notification trigger with local or cloud storage
* Records triggered notifications in the result object's `notifications` dictionary
* Overlay annotation of active notification status on images

### EventNotifier Methods <a href="#eventnotifier-methods" id="eventnotifier-methods"></a>

#### \_\_init\_\_(name, ...) <a href="#init" id="init"></a>

`__init__(name, condition, *, message='', notify_while_true=False, holdoff=0, notification_config=None, notification_tags=None, show_overlay=True, annotation_color=None, annotation_font_scale=None, annotation_pos=AnchorPoint.BOTTOM_LEFT, annotation_cool_down=3.0, clip_save=False, clip_sub_dir='', clip_duration=0, clip_pre_trigger_delay=0, clip_embed_ai_annotations=True, clip_target_fps=30.0, storage_config=None, notification_timeout_s=None)`

Constructor.

Parameters:

| Name                        | Type                                          | Description                                                                                                                                                                                                      | Default       |
| --------------------------- | --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
| `name`                      | `str`                                         | Name of the notification.                                                                                                                                                                                        | *required*    |
| `condition`                 | `str`                                         | Python expression defining the condition to trigger the notification (references event names from `EventDetector`).                                                                                              | *required*    |
| `message`                   | `str`                                         | Notification message format string. If empty, uses "Notification triggered: {name}". Default is "".                                                                                                              | `''`          |
| `notify_while_true`         | `bool`                                        | Whether to notify continuously while the condition is true. Default is False: notify only when condition changes from False to True.                                                                             | `False`       |
| `holdoff`                   | `int \| float \| Tuple[float, str]`           | Holdoff duration to suppress repeated notifications. If int, interpreted as frames; if float, as seconds; if tuple (value, "seconds"/"frames"), uses the specified unit. Default is 0 (no holdoff).              | `0`           |
| `notification_config`       | `str`                                         | Notification service config file path, Apprise URL, or "json://console" for stdout output. If None, notifications are not sent to any external service.                                                          | `None`        |
| `notification_tags`         | `str`                                         | Tags to attach to notifications for filtering. Multiple tags can be separated by commas (for logical AND) or spaces (for logical OR).                                                                            | `None`        |
| `show_overlay`              | `bool`                                        | Whether to overlay notification text on images. Default is True.                                                                                                                                                 | `True`        |
| `annotation_color`          | `tuple`                                       | RGB color for the annotation text background. If None, uses a complementary color to the result overlay.                                                                                                         | `None`        |
| `annotation_font_scale`     | `float`                                       | Font scale for the annotation text. If None, uses the default model font scale.                                                                                                                                  | `None`        |
| `annotation_pos`            | `AnchorPoint \| Tuple[int, int] \| List[int]` | Position to place annotation text (either an AnchorPoint or an (x,y) coordinate). Default is AnchorPoint.BOTTOM\_LEFT.                                                                                           | `BOTTOM_LEFT` |
| `annotation_cool_down`      | `float`                                       | Time in seconds to display the notification text on the image. Default is 3.0.                                                                                                                                   | `3.0`         |
| `clip_save`                 | `bool`                                        | If True, save a video clip when the notification triggers. Default is False.                                                                                                                                     | `False`       |
| `clip_sub_dir`              | `str`                                         | Subdirectory name in the storage bucket for saved clips. Default is "" (no subdirectory).                                                                                                                        | `''`          |
| `clip_duration`             | `int`                                         | Length of the saved video clip in frames. Default is 0 (uses available frames around event).                                                                                                                     | `0`           |
| `clip_pre_trigger_delay`    | `int`                                         | Number of frames to include before the trigger event in the saved clip. Default is 0.                                                                                                                            | `0`           |
| `clip_embed_ai_annotations` | `bool`                                        | If True, embed AI annotations in the saved clip. Default is True.                                                                                                                                                | `True`        |
| `clip_target_fps`           | `float`                                       | Frame rate (FPS) for the saved video clip. Default is 30.0.                                                                                                                                                      | `30.0`        |
| `storage_config`            | `ObjectStorageConfig`                         | Storage configuration for clip saving. For local storage, use endpoint="./" and local directory as bucket. For cloud storage, use S3-compatible endpoint and credentials. If None, clips are only saved locally. | `None`        |
| `notification_timeout_s`    | `float`                                       | Maximum time in seconds to wait for a notification job to complete before marking it as timed out. If None, uses the default timeout.                                                                            | `None`        |

Raises: ValueError: If holdoff unit is not "seconds" or "frames". ImportError: If required optional packages are not installed.

Message Formatting

* Use `${expression}` fields in the `message` parameter to include dynamic content (e.g., `${time}` for the time the notification was sent)
* Use markdown formatting for rich text notifications (e.g. `**bold**`, `*italic*`, `[link](url)`)
* Supported variables to use in `${expression}` fields include:
  * `${result}`: The inference result
  * `${time}`: The time the notification was sent
  * `${url}`: The URL of the uploaded file
  * `${filename}`: The name of the uploaded file
* `re` and `json` modules are also available for advanced formatting

#### analyze(result) <a href="#analyze" id="analyze"></a>

`analyze(result)`

Evaluate the notification condition on the given inference result.

If the condition is satisfied (and not within a holdoff period), generates a notification message and stores it in `result.notifications`. Optionally saves a video clip when a notification is triggered, and schedules that clip for upload if storage is configured. This method modifies the input result object in-place.

Parameters:

| Name     | Type                                                                                                                             | Description                                                                                  | Default    |
| -------- | -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | ---------- |
| `result` | [InferenceResults](https://docs.degirum.com/pysdk/user-guide-pysdk/api-ref/postprocessor#degirum.postprocessor.inferenceresults) | The inference result to analyze, which should include events detected by an `EventDetector`. | *required* |

Returns:

| Type   | Description                                            |
| ------ | ------------------------------------------------------ |
| `None` | This method modifies the input result object in-place. |

Raises:

| Type             | Description                                                                   |
| ---------------- | ----------------------------------------------------------------------------- |
| `AttributeError` | If the result does not contain events\_detected (EventDetector not in chain). |

#### annotate(result, ...) <a href="#annotate" id="annotate"></a>

`annotate(result, image)`

Draws the active notification message on the image.

Only draws the message if the notification is currently active and within its cool-down period.

Parameters:

| Name     | Type                                                                                                                             | Description                                                     | Default    |
| -------- | -------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- | ---------- |
| `result` | [InferenceResults](https://docs.degirum.com/pysdk/user-guide-pysdk/api-ref/postprocessor#degirum.postprocessor.inferenceresults) | The inference result object (may contain a notification entry). | *required* |
| `image`  | `ndarray`                                                                                                                        | The image frame (BGR format) to annotate.                       | *required* |

Returns:

| Type      | Description                      |
| --------- | -------------------------------- |
| `ndarray` | np.ndarray: The annotated image. |

#### finalize <a href="#finalize" id="finalize"></a>

`finalize()`

Finalize and clean up resources.

Waits for all background clip-saving threads to finish, stops the notification server, and removes the temporary clip directory if it was used.
