Compare commits

...
4 Commits
Author SHA1 Message Date
mohitandGitHub 2c9cfe7a13 Merge ee823f8488 into 729ee86043 2026-07-04 09:56:35 -04:00
Josh HawkinsandGitHub 729ee86043 Miscellaneous fixes (#23619)
CI / AMD64 Build (push) Waiting to run
CI / ARM Build (push) Waiting to run
CI / AMD64 Extra Build (push) Blocked by required conditions
CI / ARM Extra Build (push) Blocked by required conditions
CI / Synaptics Build (push) Blocked by required conditions
CI / Assemble and push default build (push) Blocked by required conditions
CI / Jetson Jetpack 6 (push) Waiting to run
* fix stale active object indicators on the live dashboard

The camera_activity/<camera> snapshot cache is only written when a client sends onConnect, and object "end" events only update the local state of mounted useCameraActivity hooks, never the cache. As a result, a hook that seeded from a stale cache or missed an "end" event while disconnected showed objects that had already left, with no path to correct itself short of a full page reload.

This change will re-request the snapshot on hook mount (collapsed to one onConnect per task across camera cards), and always re-notify camera_activity topics so hooks reconcile against their own local state instead of relying on snapshot-vs-snapshot comparison, and clear the payload dedup cache on reconnect and resync so byte-identical snapshots still apply.

* docs tweaks

* fix mqtt log message

* use consistent values for lpr debug frame filenames

with millisecond resolution

* apply object events through a functional updater to prevent lost updates

The events effect derived a new objects list from the value captured at render time and wrote the whole list back. When events arrived close
together, a run derived from a stale list erased a concurrent run's removal; the resurrected object then had no remaining "end" event to clear it, and the add branch could mint a duplicate entry that no splice could ever remove, leaving the live dashboard showing active objects the backend had already cleared, until a page reload.

The fix is to apply each event inside setObjects so it operates on the true current list exactly once. Unchanged results return the same reference so React bails out of re-rendering, and the label rewrite is hoisted so added objects get the sub_label/verified label directly instead of relying on the effect re-running against its own state update.
2026-07-04 00:25:22 -06:00
Mohit Varikuti ee823f8488 fix(genai): drop twelvelabs SDK dep, call Marengo via REST 2026-06-25 16:45:21 -07:00
Mohit Varikuti 85e16eb31b feat(genai): add TwelveLabs Marengo embeddings provider
Adds an opt-in 'twelvelabs' GenAI provider implementing the embeddings
role using TwelveLabs' Marengo multimodal model. Text and image inputs
are embedded into a shared vector space, powering semantic search over
event thumbnails.

The provider only implements the embeddings role; descriptions/chat are
left to other providers since Marengo is an embedding model. Marengo
returns 512-dim vectors, which the existing GenAIEmbedding adapter pads
to Frigate's 768-dim search schema.

Includes no-network unit tests and a live test gated on
TWELVELABS_API_KEY.
2026-06-25 00:43:04 -07:00
13 changed files with 522 additions and 120 deletions
+2 -2
View File
@@ -126,12 +126,12 @@ birdseye:
### Sorting cameras in the Birdseye view
It is possible to override the order of cameras that are being shown in the Birdseye view. The order is set at the camera level.
It is possible to override the order of cameras that are being shown in the Birdseye view. The order is set at the camera level (when using YAML).
<ConfigTabs>
<TabItem value="ui">
Navigate to <NavPath path="Settings > Camera configuration > Birdseye" /> for each camera and set the **Position** field to control the display order.
Navigate to <NavPath path="Settings > System > Birdseye" /> and in the **Camera order** field, use the drag handle next to each camera name to control the display order.
</TabItem>
<TabItem value="yaml">
+1 -1
View File
@@ -194,7 +194,7 @@ Camera groups let you organize cameras together with a shared name and icon, mak
<ConfigTabs>
<TabItem value="ui">
On the Live dashboard, press the **+** icon in the main navigation to add a new camera group. Configure the group name, select which cameras to include, choose an icon, and set the display order.
On the Live dashboard, press the **pencil icon** in the main navigation to add a new camera group. Configure the group name, select which cameras to include, choose an icon, and set the display order.
</TabItem>
<TabItem value="yaml">
+39 -39
View File
@@ -7,27 +7,27 @@ import ConfigTabs from "@site/src/components/ConfigTabs";
import TabItem from "@theme/TabItem";
import NavPath from "@site/src/components/NavPath";
Some presets of FFmpeg args are provided by default to make the configuration easier. All presets can be seen in [this file](https://github.com/blakeblackshear/frigate/blob/master/frigate/ffmpeg_presets.py).
Frigate ships with a set of FFmpeg presets to keep your configuration short and readable. Each preset expands to a longer list of FFmpeg arguments at runtime. You can see exactly what every preset expands to in [this file](https://github.com/blakeblackshear/frigate/blob/master/frigate/ffmpeg_presets.py).
### Hwaccel Presets
In the config file you reference a preset by its name (for example, `preset-vaapi`). In the UI, the same preset is shown with a friendly label (for example, **VAAPI (Intel/AMD GPU)**). Both refer to the same thing — the tables below list the config name alongside the label you'll see in the UI.
It is highly recommended to use hwaccel presets in the config. These presets not only replace the longer args, but they also give Frigate hints of what hardware is available and allows Frigate to make other optimizations using the GPU such as when encoding the birdseye restream or when scaling a stream that has a size different than the native stream size.
### Hwaccel (Hardware Acceleration) Presets
See [the hwaccel docs](/configuration/hardware_acceleration_video.md) for more info on how to setup hwaccel for your GPU / iGPU.
Hardware acceleration arguments tell FFmpeg to decode your camera's video stream on a GPU or integrated graphics chip instead of the CPU, which dramatically lowers CPU usage. Using a preset is highly recommended. Beyond replacing a long list of arguments, each preset also tells Frigate what hardware is available so it can offload additional work to the GPU — for example, encoding the Birdseye restream or scaling a stream whose resolution differs from the camera's native size.
| Preset | Usage | Other Notes |
| --------------------- | ------------------------------ | ----------------------------------------------------- |
| preset-rpi-64-h264 | 64 bit Rpi with h264 stream | |
| preset-rpi-64-h265 | 64 bit Rpi with h265 stream | |
| preset-vaapi | Intel & AMD VAAPI | Check hwaccel docs to ensure correct driver is chosen |
| preset-intel-qsv-h264 | Intel QSV with h264 stream | If issues occur recommend using vaapi preset instead |
| preset-intel-qsv-h265 | Intel QSV with h265 stream | If issues occur recommend using vaapi preset instead |
| preset-nvidia | Nvidia GPU | |
| preset-jetson-h264 | Nvidia Jetson with h264 stream | |
| preset-jetson-h265 | Nvidia Jetson with h265 stream | |
| preset-rkmpp | Rockchip MPP | Use image with \*-rk suffix and privileged mode |
See [the hardware acceleration docs](/configuration/hardware_acceleration_video.md) for details on setting up hardware acceleration for your GPU / iGPU, then select the preset that matches your hardware.
Select the appropriate hwaccel preset for your hardware.
| Preset (YAML config) | UI Label | Usage | Notes |
| --------------------- | ----------------------- | --------------------------------- | --------------------------------------------------------------- |
| preset-rpi-64-h264 | Raspberry Pi (H.264) | 64-bit Raspberry Pi, H.264 stream | |
| preset-rpi-64-h265 | Raspberry Pi (H.265) | 64-bit Raspberry Pi, H.265 stream | |
| preset-vaapi | VAAPI (Intel/AMD GPU) | Intel or AMD GPU via VAAPI | Check the hwaccel docs to ensure the correct driver is selected |
| preset-intel-qsv-h264 | Intel QuickSync (H.264) | Intel QuickSync, H.264 stream | If you have issues, use the VAAPI preset instead |
| preset-intel-qsv-h265 | Intel QuickSync (H.265) | Intel QuickSync, H.265 stream | If you have issues, use the VAAPI preset instead |
| preset-nvidia | NVIDIA GPU | NVIDIA GPU | |
| preset-jetson-h264 | NVIDIA Jetson (H.264) | NVIDIA Jetson, H.264 stream | |
| preset-jetson-h265 | NVIDIA Jetson (H.265) | NVIDIA Jetson, H.265 stream | |
| preset-rkmpp | Rockchip RKMPP | Rockchip MPP | Use an image with the `-rk` suffix and run in privileged mode |
<ConfigTabs>
<TabItem value="ui">
@@ -53,25 +53,25 @@ cameras:
### Input Args Presets
Input args presets help make the config more readable and handle use cases for different types of streams to ensure maximum compatibility.
Input arguments are passed to FFmpeg before your camera source and control how Frigate connects to and reads the stream — the transport protocol, timeouts, reconnection behavior, and how the stream is probed. The right input args ensure a reliable connection and maximum compatibility for each type of stream.
See [the camera specific docs](/configuration/camera_specific.md) for more info on non-standard cameras and recommendations for using them in Frigate.
See [the camera-specific docs](/configuration/camera_specific.md) for more on non-standard cameras and recommendations for using them in Frigate.
| Preset | Usage | Other Notes |
| -------------------------------- | ------------------------- | ------------------------------------------------------------------------------------------------ |
| preset-http-jpeg-generic | HTTP Live Jpeg | Recommend restreaming live jpeg instead |
| preset-http-mjpeg-generic | HTTP Mjpeg Stream | Recommend restreaming mjpeg stream instead |
| preset-http-reolink | Reolink HTTP-FLV Stream | Only for reolink http, not when restreaming as rtsp |
| preset-rtmp-generic | RTMP Stream | |
| preset-rtsp-generic | RTSP Stream | This is the default when nothing is specified |
| preset-rtsp-restream | RTSP Stream from restream | Use for rtsp restream as source for frigate |
| preset-rtsp-restream-low-latency | RTSP Stream from restream | Use for rtsp restream as source for frigate to lower latency, may cause issues with some cameras |
| preset-rtsp-udp | RTSP Stream via UDP | Use when camera is UDP only |
| preset-rtsp-blue-iris | Blue Iris RTSP Stream | Use when consuming a stream from Blue Iris |
| Preset (config) | UI Label | Usage | Notes |
| -------------------------------- | ----------------------------------------- | --------------------------- | ------------------------------------------------------------------------------- |
| preset-http-jpeg-generic | HTTP JPEG (Generic) | HTTP live JPEG | Restreaming the live JPEG is recommended instead |
| preset-http-mjpeg-generic | HTTP MJPEG (Generic) | HTTP MJPEG stream | Restreaming the MJPEG stream is recommended instead |
| preset-http-reolink | HTTP - Reolink Cameras | Reolink HTTP-FLV stream | Only for Reolink HTTP, not when restreaming as RTSP |
| preset-rtmp-generic | RTMP (Generic) | RTMP stream | |
| preset-rtsp-generic | RTSP (Generic) | RTSP stream | The default when no input args are specified |
| preset-rtsp-restream | RTSP - Restream from go2rtc | RTSP stream from a restream | Use when a go2rtc restream is the source for Frigate |
| preset-rtsp-restream-low-latency | RTSP - Restream from go2rtc (Low Latency) | RTSP stream from a restream | Lowers latency for a go2rtc restream source; may cause issues with some cameras |
| preset-rtsp-udp | RTSP - UDP | RTSP stream over UDP | Use when the camera only supports UDP |
| preset-rtsp-blue-iris | RTSP - Blue Iris | Blue Iris RTSP stream | Use when consuming a stream from Blue Iris |
:::warning
It is important to be mindful of input args when using restream because you can have a mix of protocols. `http` and `rtmp` presets cannot be used with `rtsp` streams. For example, when using a reolink cam with the rtsp restream as a source for record the preset-http-reolink will cause a crash. In this case presets will need to be set at the stream level. See the example below.
Be mindful of input arguments when restreaming, because you can end up with a mix of protocols. The `http` and `rtmp` presets cannot be used with `rtsp` streams. For example, using a Reolink camera with an RTSP restream as the recording source while `preset-http-reolink` is applied will cause a crash. In cases like this, set the preset at the stream level instead. See the example below.
:::
@@ -96,13 +96,13 @@ cameras:
### Output Args Presets
Output args presets help make the config more readable and handle use cases for different types of streams to ensure consistent recordings.
Output arguments are passed to FFmpeg after your camera source and control how recordings are written — which codecs are used and whether audio and video are copied as-is or re-encoded. The right output args ensure consistent, playable recordings for each type of stream.
| Preset | Usage | Other Notes |
| -------------------------------- | --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| preset-record-generic | Record WITHOUT audio | If your camera doesn't have audio, or if you don't want to record audio, use this option |
| preset-record-generic-audio-copy | Record WITH original audio | Use this to enable audio in recordings |
| preset-record-generic-audio-aac | Record WITH transcoded aac audio | This is the default when no option is specified. Use it to transcode audio to AAC. If the source is already in AAC format, use preset-record-generic-audio-copy instead to avoid unnecessary re-encoding |
| preset-record-mjpeg | Record an mjpeg stream | Recommend restreaming mjpeg stream instead |
| preset-record-jpeg | Record live jpeg | Recommend restreaming live jpeg instead |
| preset-record-ubiquiti | Record ubiquiti stream with audio | Recordings with ubiquiti non-standard audio |
| Preset (config) | UI Label | Usage | Notes |
| -------------------------------- | ------------------------------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| preset-record-generic | Record (Generic, no audio) | Record without audio | Use this if your camera has no audio, or if you don't want to record audio |
| preset-record-generic-audio-copy | Record (Generic + Copy Audio) | Record with the original audio | Use this to keep the camera's audio in recordings without re-encoding |
| preset-record-generic-audio-aac | Record (Generic + Audio to AAC) | Record with audio transcoded to AAC | The default when no output args are specified. Transcodes audio to AAC. If the source is already AAC, use `preset-record-generic-audio-copy` to avoid re-encoding |
| preset-record-mjpeg | Record - MJPEG Cameras | Record an MJPEG stream | Restreaming the MJPEG stream is recommended instead |
| preset-record-jpeg | Record - JPEG Cameras | Record a live JPEG | Restreaming the live JPEG is recommended instead |
| preset-record-ubiquiti | Record - Ubiquiti Cameras | Record a Ubiquiti stream with audio | Handles Ubiquiti's non-standard audio format |
+42 -9
View File
@@ -9,7 +9,7 @@ import NavPath from "@site/src/components/NavPath";
## Configuration
A Generative AI provider can be configured in the global config, which will make the Generative AI features available for use. There are currently 4 native providers available to integrate with Frigate. Other providers that support the OpenAI standard API can also be used. See the OpenAI-Compatible section below.
A Generative AI provider can be configured in the global config, which will make the Generative AI features available for use. There are currently several native providers available to integrate with Frigate. Other providers that support the OpenAI standard API can also be used. See the OpenAI-Compatible section below.
To use Generative AI, you must define a single provider at the global level of your Frigate configuration. If the provider you choose requires an API key, you may either directly paste it in your configuration, or store it in an environment variable prefixed with `FRIGATE_`.
@@ -27,13 +27,12 @@ Running Generative AI models on CPU is not recommended, as high inference times
You must use a vision-capable model with Frigate. The following models are recommended for local deployment:
| Model | Notes |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `qwen3-vl` | Strong visual and situational understanding, enhanced ability to identify smaller objects and interactions with object. |
| `qwen3.5` | Strong situational understanding, but missing DeepStack from qwen3-vl leading to worse performance for identifying objects in people's hand and other small details. |
| `gemma4` | Strong situational understanding, sometimes resorts to more vague terms like 'interacts' instead of assigning a specific action. |
| `Intern3.5VL` | Relatively fast with good vision comprehension |
| `gemma3` | Slower model with good vision and temporal understanding |
| Model | Notes |
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `qwen3-vl` | Strong visual and situational understanding, enhanced ability to identify smaller objects and interactions with object. |
| `qwen3.5` | Strong situational understanding, but missing DeepStack from qwen3-vl leading to worse performance for identifying objects in people's hand and other small details. |
| `qwen3.6` | Strong situational understanding, similar to qwen3-vl |
| `gemma4` | Strong situational understanding, sometimes resorts to more vague terms like 'interacts' instead of assigning a specific action. |
:::info
@@ -294,7 +293,7 @@ Other HTTP options are available, see the [python-genai documentation](https://g
### OpenAI
OpenAI does not have a free tier for their API. With the release of gpt-4o, pricing has been reduced and each generation should cost fractions of a cent if you choose to go this route.
OpenAI does not have a free tier for their API.
#### Supported Models
@@ -386,3 +385,37 @@ genai:
</TabItem>
</ConfigTabs>
### TwelveLabs (Marengo embeddings)
[TwelveLabs](https://twelvelabs.io) provides the Marengo multimodal model, which embeds text and images into a shared vector space. This makes it usable as the `embeddings` provider for Frigate's [Semantic Search](/configuration/semantic_search), letting a natural-language query match stored event thumbnails directly.
This provider implements only the `embeddings` role. Use a separate provider (such as Ollama, Gemini, or OpenAI) for the `descriptions` and `chat` roles if you want generated descriptions as well.
#### Get API Key
Create an API key from the [TwelveLabs dashboard](https://playground.twelvelabs.io/dashboard/api-key). There is a generous free tier.
#### Configuration
<ConfigTabs>
<TabItem value="ui">
1. Navigate to <NavPath path="Settings > Enrichments > Generative AI" />.
- Set **Provider** to `twelvelabs`
- Set **API key** to your TwelveLabs API key (or use an environment variable such as `{FRIGATE_TWELVELABS_API_KEY}`)
- Optionally set **Model** to override the default Marengo model (`marengo3.0`)
</TabItem>
<TabItem value="yaml">
```yaml
genai:
provider: twelvelabs
api_key: "{FRIGATE_TWELVELABS_API_KEY}"
roles:
- embeddings
```
</TabItem>
</ConfigTabs>
+2 -2
View File
@@ -49,9 +49,9 @@ This almost always means that the width/height defined for your camera are not c
These messages in the logs are expected in certain situations. Frigate checks the integrity of the recordings before storing. Occasionally these cached files will be invalid and cleaned up automatically.
### "On connect called"
### "MQTT connected" repeats in the logs
If you see repeated "On connect called" messages in your logs, check for another instance of Frigate. This happens when multiple Frigate containers are trying to connect to MQTT with the same `client_id`.
If you see repeated "MQTT connected" messages in your logs, check for another instance of Frigate. This happens when multiple Frigate containers are trying to connect to MQTT with the same `client_id`.
### Error: Database Is Locked
+44 -1
View File
@@ -10,4 +10,47 @@ title: GPU Errors
Some users have reported issues using some Intel iGPUs with OpenVINO, where the GPU would not be detected. This error can be caused by various problems, so it is important to ensure the configuration is setup correctly. Some solutions users have noted:
- In some cases users have noted that an HDMI dummy plug was necessary to be plugged into the motherboard's HDMI port.
- When mixing an Intel iGPU with Nvidia GPU, the devices can be mixed up between `/dev/dri/renderD128` and `/dev/dri/renderD129` so it is important to confirm the correct device, or map the entire `/dev/dri` directory into the Frigate container.
- When mixing an Intel iGPU with Nvidia GPU, the devices can be mixed up between `/dev/dri/renderD128` and `/dev/dri/renderD129` so it is important to confirm the correct device, or map the entire `/dev/dri` directory into the Frigate container.
## Intel/AMD GPU
### Hardware acceleration is not being used
For VAAPI or QSV to work, the GPU's render device must be passed through to the Frigate container. Intel and AMD GPUs expose this as a render node under `/dev/dri`, usually `/dev/dri/renderD128`. If it is not passed through, hardware acceleration is unavailable — ffmpeg fails to initialize it (for example `Failed to open the drm device` or `No VA display found for device`) and GPU usage stays at zero while CPU usage remains high.
Pass the render device through when starting the container. With `docker compose`:
```yaml
services:
frigate:
devices:
- /dev/dri/renderD128:/dev/dri/renderD128 # Intel / AMD GPU, update for your hardware
```
Or with `docker run`, add `--device /dev/dri/renderD128`. See the [installation docs](/frigate/installation) for a complete example.
If it still isn't working after passing the device through:
- **Confirm the render node exists and is the correct one.** Run `ls /dev/dri` on the host — you should see one or more `renderD12X` entries. Systems with more than one GPU (an Intel iGPU plus a discrete GPU) can expose both `/dev/dri/renderD128` and `/dev/dri/renderD129`, and the numbering is not guaranteed. Pass through the correct node, or map the entire directory (`/dev/dri:/dev/dri`, or `--device /dev/dri`) so all render nodes are available.
- **Check device permissions.** The Frigate process must be able to access the render node. This is usually automatic when the container runs as root (the default), but nested setups such as an unprivileged Proxmox/LXC container often require making the device accessible on the host (for example, a world-readable render node) or running the container privileged. Note that running Frigate inside an LXC is not officially supported — see the [installation docs](/frigate/installation#proxmox) for details.
### Failed to download frame: -5
When using VAAPI or QSV hardware acceleration, ffmpeg may crash and restart periodically with a signature like this in the `ffmpeg.<camera>.detect` log:
```
[AVHWFramesContext @ 0x...] Failed to sync surface ... (operation failed).
[hwdownload @ 0x...] Failed to download frame: -5.
[vf#0:0 @ 0x...] Error while filtering: Input/output error
[vf#0:0 @ 0x...] Task finished with error code: -5 (Input/output error)
[frigate.video] <camera>: Unable to read frames from ffmpeg process.
```
This is a hardware frame synchronization failure between ffmpeg and the GPU driver, not a Frigate bug. It comes from how a specific camera stream interacts with the GPU's decode and scaling path, so it is highly dependent on your hardware, driver, and stream. Frigate's automatic hardware acceleration detection is a best-guess effort, so the fix is usually to tune the configuration for your specific hardware and camera. The solutions below are ordered from most to least likely to help:
- **Switch between the VAAPI and QSV presets.** On Intel Gen 12 and newer iGPUs, `preset-intel-qsv-h264` / `preset-intel-qsv-h265` is often more stable than the auto-detected `preset-vaapi`. See the [hardware acceleration docs](/configuration/hardware_acceleration_video.md#intel-based-cpus) for the recommended preset for your Intel generation.
- **Try a different VAAPI driver.** The default driver is `iHD`. On older Intel CPUs, `LIBVA_DRIVER_NAME=i965` can be more stable; on AMD GPUs use `LIBVA_DRIVER_NAME=radeonsi`. See [the hardware acceleration docs](/configuration/hardware_acceleration_video.md#intel-based-cpus) for how to set the driver.
- **Use a codec that decodes more reliably.** H.265/HEVC streams may trigger this error far more often than H.264 depending on your CPU generation. If your camera exposes a separate sub-stream, assign an H.264 stream to the `detect` role. Cameras that output full-range YUV (for example some Hikvision models) are especially prone to it.
- **Match the detect resolution to the stream resolution.** When the `detect` resolution differs from the stream, Frigate inserts a GPU scaling filter (`scale_vaapi`), which is where these surface-sync failures can often originate. Set the `detect` `width` and `height` to match the exact resolution of the stream assigned the `detect` role.
- **Match the detect `fps` to the camera stream.** Aggressively dropping frames (for example `detect` `fps: 1` on a stream that runs at 15 fps) can cause timing mismatches in the GPU's frame buffer. Lower the sub-stream's frame rate on the camera itself instead of dropping most frames in Frigate.
- **Fall back to software decoding.** If none of the above resolve it, remove the preset for that camera (`hwaccel_args: []`). Hardware decoding is only an optimization — on a capable CPU, software-decoding a low-resolution sub-stream is inexpensive and gives a stable detect pipeline.
+1
View File
@@ -15,6 +15,7 @@ class GenAIProviderEnum(str, Enum):
gemini = "gemini"
ollama = "ollama"
llamacpp = "llamacpp"
twelvelabs = "twelvelabs"
class GenAIRoleEnum(str, Enum):
@@ -86,13 +86,15 @@ class LicensePlateProcessingMixin:
self.similarity_threshold = 0.8
self.cluster_threshold = 0.85
def _detect(self, image: np.ndarray) -> List[np.ndarray]:
def _detect(self, image: np.ndarray, debug_frame_id: int) -> List[np.ndarray]:
"""
Detect possible areas of text in the input image by first resizing and normalizing it,
running a detection model, and filtering out low-probability regions.
Args:
image (np.ndarray): The input image in which license plates will be detected.
debug_frame_id (int): Shared id used to name debug images so all artifacts
from a single LPR pass share the same filename suffix.
Returns:
List[np.ndarray]: A list of bounding box coordinates representing detected license plates.
@@ -106,9 +108,8 @@ class LicensePlateProcessingMixin:
normalized_image = self._normalize_image(resized_image)
if WRITE_DEBUG_IMAGES:
current_time = int(datetime.datetime.now().timestamp())
cv2.imwrite(
f"debug/frames/license_plate_resized_{current_time}.jpg",
f"debug/frames/license_plate_resized_{debug_frame_id}.jpg",
resized_image,
)
@@ -203,7 +204,7 @@ class LicensePlateProcessingMixin:
return self.ctc_decoder(outputs)
def _process_license_plate(
self, camera: str, id: str, image: np.ndarray
self, camera: str, id: str, image: np.ndarray, debug_frame_id: int
) -> Tuple[List[str], List[List[float]], List[int]]:
"""
Complete pipeline for detecting, classifying, and recognizing license plates in the input image.
@@ -214,6 +215,8 @@ class LicensePlateProcessingMixin:
camera (str): Camera identifier.
id (str): Event identifier.
image (np.ndarray): The input image in which to detect, classify, and recognize license plates.
debug_frame_id (int): Shared id used to name debug images so all artifacts
from a single LPR pass share the same filename suffix.
Returns:
Tuple[List[str], List[List[float]], List[int]]: Detected license plate texts, character-level confidence scores for each plate (flattened into a single list per plate), and areas of the plates.
@@ -227,7 +230,7 @@ class LicensePlateProcessingMixin:
logger.debug("Model runners not loaded")
return [], [], []
boxes = self._detect(image)
boxes = self._detect(image, debug_frame_id)
if len(boxes) == 0:
logger.debug(f"{camera}: No boxes found by OCR detector model")
return [], [], []
@@ -243,7 +246,6 @@ class LicensePlateProcessingMixin:
boxes, plate_width=plate_width, gap_fraction=0.1
)
current_time = int(datetime.datetime.now().timestamp())
if WRITE_DEBUG_IMAGES:
debug_image = image.copy()
for box in boxes:
@@ -259,7 +261,7 @@ class LicensePlateProcessingMixin:
)
cv2.imwrite(
f"debug/frames/license_plate_boxes_{current_time}.jpg", debug_image
f"debug/frames/license_plate_boxes_{debug_frame_id}.jpg", debug_image
)
boxes = self._sort_boxes(list(boxes))
@@ -322,7 +324,7 @@ class LicensePlateProcessingMixin:
if WRITE_DEBUG_IMAGES:
for i, img in enumerate(group_plate_images):
cv2.imwrite(
f"debug/frames/license_plate_cropped_{current_time}_{group_indices[i] + 1}.jpg",
f"debug/frames/license_plate_cropped_{debug_frame_id}_{group_indices[i] + 1}.jpg",
img,
)
@@ -335,7 +337,7 @@ class LicensePlateProcessingMixin:
cv2.imwrite(
os.path.join(
CLIPS_DIR,
f"lpr/{camera}/{id}/{current_time}_{group_indices[i] + 1}.jpg",
f"lpr/{camera}/{id}/{debug_frame_id}_{group_indices[i] + 1}.jpg",
),
img,
)
@@ -1199,6 +1201,7 @@ class LicensePlateProcessingMixin:
self.metrics.yolov9_lpr_pps.value = self.plates_det_second.eps()
camera = obj_data if dedicated_lpr else obj_data["camera"]
current_time = int(datetime.datetime.now().timestamp())
debug_frame_id = int(datetime.datetime.now().timestamp() * 1000)
if not self.config.cameras[camera].lpr.enabled:
return
@@ -1214,7 +1217,7 @@ class LicensePlateProcessingMixin:
if WRITE_DEBUG_IMAGES:
cv2.imwrite(
f"debug/frames/dedicated_lpr_masked_{current_time}.jpg",
f"debug/frames/dedicated_lpr_masked_{debug_frame_id}.jpg",
rgb,
)
@@ -1326,7 +1329,7 @@ class LicensePlateProcessingMixin:
if WRITE_DEBUG_IMAGES:
cv2.imwrite(
f"debug/frames/car_frame_{current_time}.jpg",
f"debug/frames/car_frame_{debug_frame_id}.jpg",
car,
)
@@ -1454,7 +1457,7 @@ class LicensePlateProcessingMixin:
if WRITE_DEBUG_IMAGES:
cv2.imwrite(
f"debug/frames/license_plate_frame_{current_time}.jpg",
f"debug/frames/license_plate_frame_{debug_frame_id}.jpg",
license_plate_frame,
)
@@ -1464,7 +1467,7 @@ class LicensePlateProcessingMixin:
# run detection, returns results sorted by confidence, best first
start = datetime.datetime.now().timestamp()
license_plates, confidences, areas = self._process_license_plate(
camera, id, license_plate_frame
camera, id, license_plate_frame, debug_frame_id
)
self.plates_rec_second.update()
self.plate_rec_speed.update(datetime.datetime.now().timestamp() - start)
+139
View File
@@ -0,0 +1,139 @@
"""TwelveLabs provider for Frigate AI.
Provides multimodal embeddings for Frigate's semantic search via TwelveLabs'
Marengo model. Marengo produces text and image embeddings in a shared vector
space, so a natural-language query and a stored event thumbnail can be matched
directly — which is exactly what the ``embeddings`` GenAI role drives.
This provider is opt-in: it is only used when a ``genai`` config entry sets
``provider: twelvelabs`` and includes the ``embeddings`` role. It does not
implement the ``descriptions``/``chat`` roles — Marengo is an embedding model,
and TwelveLabs' Pegasus description model operates on whole video clips rather
than the per-frame thumbnails Frigate hands to ``_send``.
Marengo embeddings are 512-dimensional; Frigate's semantic search schema
expects 768 dimensions. The shared :class:`~frigate.embeddings.genai_embedding.GenAIEmbedding`
adapter zero-pads shorter vectors, so the dimension difference is handled
upstream and is consistent for both text and image inputs.
"""
import logging
import numpy as np
import requests
from frigate.config import GenAIProviderEnum
from frigate.genai import GenAIClient, register_genai_provider
logger = logging.getLogger(__name__)
# Default Marengo model. Overridable via the `model` config field.
DEFAULT_MODEL = "marengo3.0"
# Marengo embed REST endpoint. No SDK is needed — this is a plain multipart POST
# made through Frigate's existing `requests` dependency.
EMBED_URL = "https://api.twelvelabs.io/v1.3/embed"
@register_genai_provider(GenAIProviderEnum.twelvelabs)
class TwelveLabsClient(GenAIClient):
"""GenAI client for Frigate using TwelveLabs Marengo embeddings."""
def _init_provider(self):
"""Validate config for the TwelveLabs REST provider.
The provider is just an HTTPS API, so there is no client object to
build — the API key is the only thing required. A non-None sentinel is
returned so the shared ``ensure_provider``/initialization machinery
treats the provider as available.
"""
if not self.genai_config.api_key:
logger.error("TwelveLabs provider requires an api_key.")
return None
return self.genai_config.api_key
@property
def _model(self) -> str:
return self.genai_config.model or DEFAULT_MODEL
def list_models(self) -> list[str]:
"""Marengo is the embedding model exposed by this provider."""
return [DEFAULT_MODEL]
def embed(
self,
texts: list[str] | None = None,
images: list[bytes] | None = None,
) -> list[np.ndarray]:
"""Generate Marengo embeddings for text and/or images.
The TwelveLabs embed API embeds a single input per call, so inputs are
sent one at a time. Returns one 512-dim float32 vector per input, in
order (texts first, then images). The shared GenAIEmbedding adapter
pads these to Frigate's 768-dim search schema.
Calls the Marengo REST endpoint directly via ``requests`` — no SDK.
"""
if self.provider is None:
logger.warning(
"TwelveLabs provider has not been initialized. Check your configuration."
)
return []
results: list[np.ndarray] = []
for text in texts or []:
vector = self._embed_one(text=text)
if vector is not None:
results.append(vector)
for image in images or []:
vector = self._embed_one(image=image)
if vector is not None:
results.append(vector)
return results
def _embed_one(
self, text: str | None = None, image: bytes | None = None
) -> np.ndarray | None:
"""Embed a single text or image input, returning a float32 vector.
Posts a multipart form to the Marengo embed endpoint (``model_name`` plus
either a ``text`` or an ``image_file`` part). The endpoint requires
multipart/form-data, so every field — including text — is passed via
``files`` (the ``(None, value)`` form makes requests emit a multipart
text part). ``self.provider`` holds the validated API key. The 512-dim
vector is at ``<text|image>_embedding.segments[0].float`` in the JSON
response.
"""
headers = {"x-api-key": self.provider}
files: dict = {"model_name": (None, self._model)}
if text is not None:
files["text"] = (None, text)
result_key = "text_embedding"
else:
files["image_file"] = ("image.jpg", image, "image/jpeg")
result_key = "image_embedding"
try:
response = requests.post(
EMBED_URL,
headers=headers,
files=files,
timeout=self.timeout,
)
response.raise_for_status()
result = response.json().get(result_key) or {}
segments = result.get("segments") or []
if not segments:
logger.warning("TwelveLabs returned no embedding for input.")
return None
return np.array(segments[0]["float"], dtype=np.float32)
except Exception as e:
logger.warning("TwelveLabs returned an error: %s", e)
return None
+138
View File
@@ -0,0 +1,138 @@
"""Tests for the TwelveLabs GenAI provider (Marengo embeddings)."""
import io
import os
import unittest
from unittest.mock import MagicMock, patch
import numpy as np
from frigate.config.camera.genai import (
GenAIConfig,
GenAIProviderEnum,
GenAIRoleEnum,
)
from frigate.genai.plugins.twelvelabs import DEFAULT_MODEL, TwelveLabsClient
def _make_config(model: str = "") -> GenAIConfig:
return GenAIConfig(
provider=GenAIProviderEnum.twelvelabs,
api_key="test-key",
model=model,
roles=[GenAIRoleEnum.embeddings],
)
def _response(key: str, values):
"""Mimic the Marengo REST JSON: ``{<key>: {segments: [{float: [...]}]}}``."""
resp = MagicMock()
resp.raise_for_status.return_value = None
resp.json.return_value = {key: {"segments": [{"float": values}]}}
return resp
class TestTwelveLabsEmbedNoNetwork(unittest.TestCase):
"""Unit tests with ``requests`` mocked — no network access, no SDK."""
def _client(self) -> TwelveLabsClient:
client = TwelveLabsClient.__new__(TwelveLabsClient)
client.genai_config = _make_config()
client.timeout = 120
client.provider = "test-key"
return client
@patch("frigate.genai.plugins.twelvelabs.requests.post")
def test_text_embedding_returns_vector(self, post):
post.return_value = _response("text_embedding", [0.1, 0.2, 0.3])
out = self._client().embed(texts=["a person walking a dog"])
self.assertEqual(len(out), 1)
self.assertIsInstance(out[0], np.ndarray)
self.assertEqual(out[0].dtype, np.float32)
np.testing.assert_allclose(out[0], [0.1, 0.2, 0.3], rtol=1e-6)
_, kwargs = post.call_args
self.assertEqual(kwargs["files"]["model_name"][1], DEFAULT_MODEL)
self.assertEqual(kwargs["files"]["text"][1], "a person walking a dog")
self.assertEqual(kwargs["headers"]["x-api-key"], "test-key")
self.assertNotIn("image_file", kwargs["files"])
@patch("frigate.genai.plugins.twelvelabs.requests.post")
def test_image_embedding_uses_image_file(self, post):
post.return_value = _response("image_embedding", [1.0, 2.0])
out = self._client().embed(images=[b"\xff\xd8\xff jpeg bytes"])
self.assertEqual(len(out), 1)
_, kwargs = post.call_args
self.assertEqual(kwargs["files"]["image_file"][1], b"\xff\xd8\xff jpeg bytes")
self.assertNotIn("text", kwargs["files"])
@patch("frigate.genai.plugins.twelvelabs.requests.post")
def test_custom_model_name_is_used(self, post):
post.return_value = _response("text_embedding", [0.0])
client = self._client()
client.genai_config = _make_config(model="marengo-custom")
client.embed(texts=["x"])
_, kwargs = post.call_args
self.assertEqual(kwargs["files"]["model_name"][1], "marengo-custom")
@patch("frigate.genai.plugins.twelvelabs.requests.post")
def test_empty_segments_are_skipped(self, post):
resp = MagicMock()
resp.raise_for_status.return_value = None
resp.json.return_value = {"text_embedding": {"segments": []}}
post.return_value = resp
self.assertEqual(self._client().embed(texts=["x"]), [])
@patch("frigate.genai.plugins.twelvelabs.requests.post")
def test_api_error_is_swallowed(self, post):
post.side_effect = RuntimeError("boom")
self.assertEqual(self._client().embed(texts=["x"]), [])
def test_no_provider_returns_empty(self):
client = self._client()
client.provider = None
self.assertEqual(client.embed(texts=["x"]), [])
def test_no_inputs_returns_empty(self):
self.assertEqual(self._client().embed(), [])
@unittest.skipUnless(
os.environ.get("TWELVELABS_API_KEY"),
"TWELVELABS_API_KEY not set; skipping live TwelveLabs API test",
)
class TestTwelveLabsEmbedLive(unittest.TestCase):
"""Live smoke test against the real TwelveLabs API (Marengo)."""
def _client(self) -> TwelveLabsClient:
config = _make_config()
config.api_key = os.environ["TWELVELABS_API_KEY"]
return TwelveLabsClient(config)
def test_text_embedding_dim(self):
out = self._client().embed(texts=["a delivery person at the front door"])
self.assertEqual(len(out), 1)
self.assertEqual(out[0].shape, (512,))
def test_image_embedding_dim(self):
from PIL import Image
arr = (np.random.rand(224, 224, 3) * 255).astype("uint8")
buf = io.BytesIO()
Image.fromarray(arr, "RGB").save(buf, format="JPEG")
out = self._client().embed(images=[buf.getvalue()])
self.assertEqual(len(out), 1)
self.assertEqual(out[0].shape, (512,))
if __name__ == "__main__":
unittest.main()
+8 -1
View File
@@ -2,7 +2,11 @@ import { baseUrl } from "./baseUrl";
import { ReactNode, useCallback, useEffect, useRef } from "react";
import { WsSendContext } from "./wsContext";
import type { Update } from "./wsContext";
import { processWsMessage, resetWsStore } from "./ws";
import {
invalidateCameraActivityCache,
processWsMessage,
resetWsStore,
} from "./ws";
export function WsProvider({ children }: { children: ReactNode }) {
const wsUrl = `${baseUrl.replace(/^http/, "ws")}ws`;
@@ -34,6 +38,9 @@ export function WsProvider({ children }: { children: ReactNode }) {
ws.onopen = () => {
reconnectAttempt.current = 0;
// events may have been missed while disconnected — the snapshot
// requested below must fully apply even if byte-identical
invalidateCameraActivityCache();
ws.send(
JSON.stringify({ topic: "onConnect", message: "", retain: false }),
);
+28 -5
View File
@@ -82,12 +82,15 @@ export function processWsMessage(raw: string) {
function applyTopicUpdate(topic: string, newVal: unknown) {
const oldVal = wsState[topic];
// camera_activity snapshots always re-notify: consumers reconcile local
// state that may have diverged from an unchanged snapshot
const isActivitySnapshot = topic.startsWith("camera_activity/");
// Fast path: === for primitives ("ON"/"OFF", numbers).
// Fall back to isEqual for objects/arrays.
const unchanged =
oldVal === newVal ||
(typeof newVal === "object" && newVal !== null && isEqual(oldVal, newVal));
if (unchanged) return;
if (unchanged && !isActivitySnapshot) return;
wsState[topic] = newVal;
// Snapshot the Set — a listener may trigger unmount that modifies it.
@@ -131,6 +134,25 @@ let wsMessageIdCounter = 0;
// traversals) on every flush — critical with many cameras.
let lastCameraActivityPayload: string | null = null;
// Make the next camera_activity snapshot fully apply even when byte-identical
// to the previous one — local state may have diverged while no messages flowed
export function invalidateCameraActivityCache() {
lastCameraActivityPayload = null;
}
// Collapse same-task resync requests (one hook per camera card) into a
// single onConnect round-trip
let resyncScheduled = false;
function requestCameraActivityResync(sendOnConnect: () => void) {
if (resyncScheduled) return;
resyncScheduled = true;
queueMicrotask(() => {
resyncScheduled = false;
invalidateCameraActivityCache();
sendOnConnect();
});
}
function applyCameraActivity(payload: string) {
// Fast path: if the raw JSON string is identical, nothing changed.
if (payload === lastCameraActivityPayload) return;
@@ -509,15 +531,16 @@ export function useInitialCameraState(
// camera_activity sub-topic payload is already parsed by expandCameraActivity
const data = payload as FrigateCameraState | undefined;
// onConnect is sent once in WsProvider.onopen — no need to re-request on
// every component mount. Components read cached wsState immediately via
// useSyncExternalStore. Only re-request when the user tabs back in.
// the cached snapshot is only written on onConnect and can be stale by the
// time this hook mounts — re-request on mount and when the user tabs back in
useEffect(() => {
if (!revalidateOnFocus) return;
requestCameraActivityResync(() => sendCommand("onConnect"));
const listener = () => {
if (document.visibilityState === "visible") {
sendCommand("onConnect");
requestCameraActivityResync(() => sendCommand("onConnect"));
}
};
addEventListener("visibilitychange", listener);
+62 -47
View File
@@ -7,7 +7,7 @@ import {
} from "@/api/ws";
import { CameraConfig, FrigateConfig } from "@/types/frigateConfig";
import { MotionData, ReviewSegment } from "@/types/review";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import { AudioDetection, ObjectType } from "@/types/ws";
import { useTimelineUtils } from "./use-timeline-utils";
import useDeepMemo from "./use-deep-memo";
@@ -57,7 +57,13 @@ export function useCameraActivity(
);
useEffect(() => {
if (updatedCameraState) {
setObjects(updatedCameraState.objects);
// functional updater keeps `objects` out of the deps: this effect must
// only run on snapshot arrival, or it would re-assert a stale snapshot
// over newer event-driven state
const newObjects = updatedCameraState.objects ?? [];
setObjects((currentObjects) =>
isEqual(currentObjects, newObjects) ? currentObjects : newObjects,
);
}
}, [updatedCameraState, camera]);
@@ -82,15 +88,6 @@ export function useCameraActivity(
const { payload: event } = useFrigateEvents();
const updatedEvent = useDeepMemo(event);
const handleSetObjects = useCallback(
(newObjects: ObjectType[]) => {
if (!isEqual(objects, newObjects)) {
setObjects(newObjects);
}
},
[objects],
);
useEffect(() => {
if (!updatedEvent) {
return;
@@ -100,53 +97,71 @@ export function useCameraActivity(
return;
}
const updatedEventIndex =
objects?.findIndex((obj) => obj.id === updatedEvent.after.id) ?? -1;
// functional updater keeps `objects` out of the deps: each event applies
// exactly once against the true current list, so events arriving close
// together cannot clobber each other's changes with a stale write-back
setObjects((currentObjects) => {
const existingObjects = currentObjects ?? [];
const updatedEventIndex = existingObjects.findIndex(
(obj) => obj.id === updatedEvent.after.id,
);
let newObjects: ObjectType[] = [...(objects ?? [])];
if (updatedEvent.type === "end") {
if (updatedEventIndex !== -1) {
if (updatedEvent.type === "end") {
if (updatedEventIndex === -1) {
return currentObjects;
}
const newObjects = [...existingObjects];
newObjects.splice(updatedEventIndex, 1);
return newObjects;
}
} else {
let label = updatedEvent.after.label;
if (updatedEvent.after.sub_label) {
const sub_label = updatedEvent.after.sub_label[0];
if (attributeLabels.includes(sub_label)) {
label = sub_label;
} else {
label = `${label}-verified`;
}
}
if (updatedEventIndex === -1) {
// add unknown updatedEvent to list if not stationary
if (!updatedEvent.after.stationary) {
const newActiveObject: ObjectType = {
id: updatedEvent.after.id,
label: updatedEvent.after.label,
stationary: updatedEvent.after.stationary,
area: updatedEvent.after.area,
ratio: updatedEvent.after.ratio,
score: updatedEvent.after.score,
sub_label: updatedEvent.after.sub_label?.[0] ?? "",
};
newObjects = [...(objects ?? []), newActiveObject];
if (updatedEvent.after.stationary) {
return currentObjects;
}
} else {
let label = updatedEvent.after.label;
if (updatedEvent.after.sub_label) {
const sub_label = updatedEvent.after.sub_label[0];
if (attributeLabels.includes(sub_label)) {
label = sub_label;
} else {
label = `${label}-verified`;
}
}
newObjects[updatedEventIndex] = {
...newObjects[updatedEventIndex],
const newActiveObject: ObjectType = {
id: updatedEvent.after.id,
label,
stationary: updatedEvent.after.stationary,
area: updatedEvent.after.area,
ratio: updatedEvent.after.ratio,
score: updatedEvent.after.score,
sub_label: updatedEvent.after.sub_label?.[0] ?? "",
};
return [...existingObjects, newActiveObject];
}
}
handleSetObjects(newObjects);
}, [attributeLabels, camera, updatedEvent, objects, handleSetObjects]);
const existing = existingObjects[updatedEventIndex];
if (
existing.label === label &&
existing.stationary === updatedEvent.after.stationary
) {
return currentObjects;
}
const newObjects = [...existingObjects];
newObjects[updatedEventIndex] = {
...existing,
label,
stationary: updatedEvent.after.stationary,
};
return newObjects;
});
}, [attributeLabels, camera, updatedEvent]);
// determine if camera is offline