Compare commits

...
8 Commits
Author SHA1 Message Date
Nicolas Mowen 1831c5818a Refactor detector and model management 2026-08-14 14:00:00 -06:00
Ersa Oktavian RamadanandJosh Hawkins 74c932c3f5 Refactor Birdseye activity types as composable booleans (#23940)
* Add combined motion and object Birdseye mode

Add a motion_objects mode that keeps Birdseye active when motion is detected or a confirmed tracked object is present, including stationary objects.

Wire the mode through configuration, runtime commands, API schemas, documentation, and UI labels. Exclude false-positive trackers and add regression coverage for Birdseye activation and MQTT validation.

* Refactor Birdseye activity types as booleans

Replace combination-specific Birdseye modes with composable boolean activity types for motion, active objects, stationary objects, and continuous display.

Preserve legacy single-mode configuration and MQTT inputs, support canonical comma-separated MQTT combinations, and allow scalar YAML values to be replaced by nested settings through the config API.

* Preserve OpenVINO config translations

Regenerate the configuration translations with the OpenVINO detector schema available so the unrelated production detector labels remain intact.

* Preserve partial Birdseye mode overrides

Allow an empty activity selection with a canonical NONE MQTT state so partial camera and profile overrides can disable inherited flags without failing validation.

Add regression coverage for camera and profile inheritance, document the NONE contract, and keep the generated schema fixture scoped to Birdseye.

* Address Birdseye activity review feedback

Move scalar mode compatibility into the 0.18-1 config migration and reject empty activity selections instead of publishing a NONE state.

Pass activity signals through a frozen dataclass, preserve existing active-object tracker behavior, and require confirmed stationary objects. Revert the generic YAML mutation and cover migration, inheritance, MQTT, and activation regressions.

* Move Birdseye migration to 0.19

Use the 0.19-0 configuration revision for converting scalar Birdseye modes to composable activity flags, and update the migration regression coverage accordingly.

* Remove Birdseye migration test

Drop the dedicated config migration test as requested during review while retaining the 0.19-0 migration implementation.
2026-08-14 10:05:08 -05:00
Josh Hawkins a0042b8d7f Fix birdseye layout overlap with mixed landscape/portrait cameras (#22917)
* fix birdseye layout calculation

replace the two pass layout with a single pass pixel space algorithm

* add test
2026-08-14 10:05:08 -05:00
Nicolas MowenandJosh Hawkins 659d26658b Don't require object type for parameter in categorized names tool 2026-08-14 10:05:08 -05:00
6c47bbfbbc Dynamically resolve Intel NPU (#23761)
* Add support for newer Intel NPU busy time counter

* Resolve Intel NPU device dynamically

---------

Co-authored-by: Filious Louis <1417132+fjlouis@users.noreply.github.com>
2026-08-14 10:05:08 -05:00
DoFabienandJosh Hawkins c4d53484b7 Improve recording timeline and VOD query performance (#23862)
* Improve recording timeline and VOD query performance

* Add recording query boundary tests
2026-08-14 10:05:08 -05:00
Nicolas MowenandJosh Hawkins 928dac506a GenAI Chat Prompt Refinements (#23864)
* Prompt refactoring and optimization

* Update spec
2026-08-14 10:05:08 -05:00
Nicolas MowenandJosh Hawkins c1bde8ca20 Update to 0.19 2026-08-14 10:05:08 -05:00
68 changed files with 3386 additions and 1407 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
default_target: local default_target: local
COMMIT_HASH := $(shell git log -1 --pretty=format:"%h"|tail -1) COMMIT_HASH := $(shell git log -1 --pretty=format:"%h"|tail -1)
VERSION = 0.18.0 VERSION = 0.19.0
IMAGE_REPO ?= ghcr.io/blakeblackshear/frigate IMAGE_REPO ?= ghcr.io/blakeblackshear/frigate
GITHUB_REF_NAME ?= $(shell git rev-parse --abbrev-ref HEAD) GITHUB_REF_NAME ?= $(shell git rev-parse --abbrev-ref HEAD)
BOARDS= #Initialized empty BOARDS= #Initialized empty
+185 -153
View File
@@ -7,10 +7,9 @@ edgeTPU:
download: A TensorFlow Lite model is provided in the container at `/edgetpu_model.tflite` and is used by this detector type by default. To provide your own model, bind mount the file into the container and provide the path with `model.path`. download: A TensorFlow Lite model is provided in the container at `/edgetpu_model.tflite` and is used by this detector type by default. To provide your own model, bind mount the file into the container and provide the path with `model.path`.
ui: Navigate to **Settings > System > Detectors and model** and select **EdgeTPU** from the detector type dropdown and click **Add**, then set device to `usb`. ui: Navigate to **Settings > System > Detectors and model** and select **EdgeTPU** from the detector type dropdown and click **Add**, then set device to `usb`.
yaml: |- yaml: |-
detectors: models:
coral: - devices:
type: edgetpu - edgetpu:usb
device: usb
- key: yolov9 - key: yolov9
label: YOLOv9 label: YOLOv9
recommended: false recommended: false
@@ -29,12 +28,9 @@ edgeTPU:
| **Model Input D Type** | `int` (Frigate's default value) | | **Model Input D Type** | `int` (Frigate's default value) |
| **Object Detection Model Type** | `yolo-generic` | | **Object Detection Model Type** | `yolo-generic` |
yaml: |- yaml: |-
detectors: models:
coral: - devices:
type: edgetpu - edgetpu:usb
device: usb
model:
model_type: yolo-generic model_type: yolo-generic
width: 320 # <--- should match the imgsize of the model, typically 320 width: 320 # <--- should match the imgsize of the model, typically 320
height: 320 # <--- should match the imgsize of the model, typically 320 height: 320 # <--- should match the imgsize of the model, typically 320
@@ -62,12 +58,9 @@ hailo8l:
The detector automatically selects the default model based on your hardware. Optionally, specify a local model path or URL to override. The detector automatically selects the default model based on your hardware. Optionally, specify a local model path or URL to override.
yaml: |- yaml: |-
detectors: models:
hailo: - devices:
type: hailo8l - hailo8l:PCIe
device: PCIe
model:
width: 320 width: 320
height: 320 height: 320
input_tensor: nhwc input_tensor: nhwc
@@ -106,12 +99,9 @@ hailo8l:
Specify the local model path or URL for SSD MobileNet v1. Specify the local model path or URL for SSD MobileNet v1.
yaml: |- yaml: |-
detectors: models:
hailo: - devices:
type: hailo8l - hailo8l:PCIe
device: PCIe
model:
width: 300 width: 300
height: 300 height: 300
input_tensor: nhwc input_tensor: nhwc
@@ -166,12 +156,9 @@ openvino:
| **Model Input D Type** | `float` | | **Model Input D Type** | `float` |
| **Object Detection Model Type** | `yolo-generic` | | **Object Detection Model Type** | `yolo-generic` |
yaml: |- yaml: |-
detectors: models:
ov: - devices:
type: openvino - openvino:GPU
device: GPU # or NPU
model:
model_type: yolo-generic model_type: yolo-generic
width: 320 # <--- should match the imgsize set during model export width: 320 # <--- should match the imgsize set during model export
height: 320 # <--- should match the imgsize set during model export height: 320 # <--- should match the imgsize set during model export
@@ -197,12 +184,9 @@ openvino:
| **Model Input D Type** | `int` (Frigate's default value) | | **Model Input D Type** | `int` (Frigate's default value) |
| **Object Detection Model Type** | `ssd` (Frigate's default value) | | **Object Detection Model Type** | `ssd` (Frigate's default value) |
yaml: |- yaml: |-
detectors: models:
ov: - devices:
type: openvino - openvino:GPU
device: GPU # Or NPU
model:
width: 300 width: 300
height: 300 height: 300
input_tensor: nhwc input_tensor: nhwc
@@ -235,12 +219,9 @@ openvino:
| **Model Input D Type** | `float` | | **Model Input D Type** | `float` |
| **Object Detection Model Type** | `yolo-generic` | | **Object Detection Model Type** | `yolo-generic` |
yaml: |- yaml: |-
detectors: models:
ov: - devices:
type: openvino - openvino:GPU
device: GPU # or NPU
model:
model_type: yolo-generic model_type: yolo-generic
width: 320 # <--- should match the imgsize set during model export width: 320 # <--- should match the imgsize set during model export
height: 320 # <--- should match the imgsize set during model export height: 320 # <--- should match the imgsize set during model export
@@ -275,12 +256,9 @@ openvino:
| **Model Input D Type** | `int` (Frigate's default value) | | **Model Input D Type** | `int` (Frigate's default value) |
| **Object Detection Model Type** | `yolonas` | | **Object Detection Model Type** | `yolonas` |
yaml: |- yaml: |-
detectors: models:
ov: - devices:
type: openvino - openvino:GPU
device: GPU
model:
model_type: yolonas model_type: yolonas
width: 320 # <--- should match whatever was set in notebook width: 320 # <--- should match whatever was set in notebook
height: 320 # <--- should match whatever was set in notebook height: 320 # <--- should match whatever was set in notebook
@@ -303,12 +281,9 @@ openvino:
| **Model Input D Type** | `int` (Frigate's default value) | | **Model Input D Type** | `int` (Frigate's default value) |
| **Object Detection Model Type** | `yolox` | | **Object Detection Model Type** | `yolox` |
yaml: |- yaml: |-
detectors: models:
ov: - devices:
type: openvino - openvino:GPU
device: GPU
model:
model_type: yolox model_type: yolox
path: /config/model_cache/yolox.onnx # use the filename you generated above path: /config/model_cache/yolox.onnx # use the filename you generated above
labelmap_path: /labelmap/coco-80.txt labelmap_path: /labelmap/coco-80.txt
@@ -345,12 +320,9 @@ openvino:
| **Model Input D Type** | `float` | | **Model Input D Type** | `float` |
| **Object Detection Model Type** | `rfdetr` | | **Object Detection Model Type** | `rfdetr` |
yaml: |- yaml: |-
detectors: models:
ov: - devices:
type: openvino - openvino:GPU
device: GPU
model:
model_type: rfdetr model_type: rfdetr
width: 320 width: 320
height: 320 height: 320
@@ -443,12 +415,9 @@ openvino:
| **Model Input D Type** | `float` | | **Model Input D Type** | `float` |
| **Object Detection Model Type** | `dfine` | | **Object Detection Model Type** | `dfine` |
yaml: |- yaml: |-
detectors: models:
ov: - devices:
type: openvino - openvino:CPU
device: CPU
model:
model_type: dfine model_type: dfine
width: 640 width: 640
height: 640 height: 640
@@ -499,12 +468,9 @@ appleSilicon:
| **Model Input D Type** | `float` | | **Model Input D Type** | `float` |
| **Object Detection Model Type** | `yolo-generic` | | **Object Detection Model Type** | `yolo-generic` |
yaml: |- yaml: |-
detectors: models:
apple-silicon: - devices:
type: zmq - zmq:tcp://host.docker.internal:5555
endpoint: tcp://host.docker.internal:5555
model:
model_type: yolo-generic model_type: yolo-generic
width: 320 # <--- should match the imgsize set during model export width: 320 # <--- should match the imgsize set during model export
height: 320 # <--- should match the imgsize set during model export height: 320 # <--- should match the imgsize set during model export
@@ -538,12 +504,9 @@ appleSilicon:
| **Model Input D Type** | `float` | | **Model Input D Type** | `float` |
| **Object Detection Model Type** | `yolo-generic` | | **Object Detection Model Type** | `yolo-generic` |
yaml: |- yaml: |-
detectors: models:
apple-silicon: - devices:
type: zmq - zmq:tcp://host.docker.internal:5555
endpoint: tcp://host.docker.internal:5555
model:
model_type: yolo-generic model_type: yolo-generic
width: 320 # <--- should match the imgsize set during model export width: 320 # <--- should match the imgsize set during model export
height: 320 # <--- should match the imgsize set during model export height: 320 # <--- should match the imgsize set during model export
@@ -594,11 +557,9 @@ onnx:
| **Model Input D Type** | `float` | | **Model Input D Type** | `float` |
| **Object Detection Model Type** | `yolo-generic` | | **Object Detection Model Type** | `yolo-generic` |
yaml: |- yaml: |-
detectors: models:
onnx: - devices:
type: onnx - onnx
model:
model_type: yolo-generic model_type: yolo-generic
width: 320 # <--- should match the imgsize set during model export width: 320 # <--- should match the imgsize set during model export
height: 320 # <--- should match the imgsize set during model export height: 320 # <--- should match the imgsize set during model export
@@ -639,11 +600,9 @@ onnx:
| **Model Input D Type** | `float` | | **Model Input D Type** | `float` |
| **Object Detection Model Type** | `rfdetr` | | **Object Detection Model Type** | `rfdetr` |
yaml: |- yaml: |-
detectors: models:
onnx: - devices:
type: onnx - onnx
model:
model_type: rfdetr model_type: rfdetr
width: 320 width: 320
height: 320 height: 320
@@ -677,11 +636,9 @@ onnx:
| **Model Input D Type** | `int` (Frigate's default value) | | **Model Input D Type** | `int` (Frigate's default value) |
| **Object Detection Model Type** | `yolonas` | | **Object Detection Model Type** | `yolonas` |
yaml: |- yaml: |-
detectors: models:
onnx: - devices:
type: onnx - onnx
model:
model_type: yolonas model_type: yolonas
width: 320 # <--- should match whatever was set in notebook width: 320 # <--- should match whatever was set in notebook
height: 320 # <--- should match whatever was set in notebook height: 320 # <--- should match whatever was set in notebook
@@ -707,11 +664,9 @@ onnx:
| **Model Input D Type** | `float_denorm` | | **Model Input D Type** | `float_denorm` |
| **Object Detection Model Type** | `yolox` | | **Object Detection Model Type** | `yolox` |
yaml: |- yaml: |-
detectors: models:
onnx: - devices:
type: onnx - onnx
model:
model_type: yolox model_type: yolox
width: 416 # <--- should match the imgsize set during model export width: 416 # <--- should match the imgsize set during model export
height: 416 # <--- should match the imgsize set during model export height: 416 # <--- should match the imgsize set during model export
@@ -805,11 +760,9 @@ onnx:
| **Model Input D Type** | `float` | | **Model Input D Type** | `float` |
| **Object Detection Model Type** | `dfine` | | **Object Detection Model Type** | `dfine` |
yaml: |- yaml: |-
detectors: models:
onnx: - devices:
type: onnx - onnx
model:
model_type: dfine model_type: dfine
width: 640 width: 640
height: 640 height: 640
@@ -843,11 +796,9 @@ onnx:
| **Model Input D Type** | `float` | | **Model Input D Type** | `float` |
| **Object Detection Model Type** | `yolo-generic` | | **Object Detection Model Type** | `yolo-generic` |
yaml: |- yaml: |-
detectors: models:
onnx: - devices:
type: onnx - onnx
model:
model_type: yolo-generic model_type: yolo-generic
width: 320 # <--- should match the imgsize set during model export width: 320 # <--- should match the imgsize set during model export
height: 320 # <--- should match the imgsize set during model export height: 320 # <--- should match the imgsize set during model export
@@ -870,10 +821,9 @@ cpu:
| **Detector type** | `cpu` | | **Detector type** | `cpu` |
| **Num threads** | `3` | | **Num threads** | `3` |
yaml: |- yaml: |-
detectors: models:
cpu1: - devices:
type: cpu - cpu:3
num_threads: 3
deepstack: deepstack:
title: DeepStack / CodeProject.AI title: DeepStack / CodeProject.AI
models: models:
@@ -889,11 +839,9 @@ deepstack:
| **API URL** | `http://<your_codeproject_ai_server_ip>:<port>/v1/vision/detection` | | **API URL** | `http://<your_codeproject_ai_server_ip>:<port>/v1/vision/detection` |
| **API Timeout** | `0.1` (seconds) | | **API Timeout** | `0.1` (seconds) |
yaml: |- yaml: |-
detectors: models:
deepstack: - devices:
api_url: http://<your_codeproject_ai_server_ip>:<port>/v1/vision/detection - deepstack:http://<your_codeproject_ai_server_ip>:<port>/v1/vision/detection
type: deepstack
api_timeout: 0.1 # seconds
memryx: memryx:
title: MemryX title: MemryX
models: models:
@@ -923,12 +871,9 @@ memryx:
| **Model Input D Type** | `float` | | **Model Input D Type** | `float` |
| **Object Detection Model Type** | `yolonas` | | **Object Detection Model Type** | `yolonas` |
yaml: |- yaml: |-
detectors: models:
memx0: - devices:
type: memryx - memryx:PCIe:0
device: PCIe:0
model:
model_type: yolonas model_type: yolonas
width: 320 # (Can be set to 640 for higher resolution) width: 320 # (Can be set to 640 for higher resolution)
height: 320 # (Can be set to 640 for higher resolution) height: 320 # (Can be set to 640 for higher resolution)
@@ -960,12 +905,9 @@ memryx:
| **Model Input D Type** | `float` | | **Model Input D Type** | `float` |
| **Object Detection Model Type** | `yolo-generic` | | **Object Detection Model Type** | `yolo-generic` |
yaml: |- yaml: |-
detectors: models:
memx0: - devices:
type: memryx - memryx:PCIe:0
device: PCIe:0
model:
model_type: yolo-generic model_type: yolo-generic
width: 320 # (Can be set to 640 for higher resolution) width: 320 # (Can be set to 640 for higher resolution)
height: 320 # (Can be set to 640 for higher resolution) height: 320 # (Can be set to 640 for higher resolution)
@@ -996,12 +938,9 @@ memryx:
| **Model Input D Type** | `float_denorm` | | **Model Input D Type** | `float_denorm` |
| **Object Detection Model Type** | `yolox` | | **Object Detection Model Type** | `yolox` |
yaml: |- yaml: |-
detectors: models:
memx0: - devices:
type: memryx - memryx:PCIe:0
device: PCIe:0
model:
model_type: yolox model_type: yolox
width: 640 width: 640
height: 640 height: 640
@@ -1032,12 +971,9 @@ memryx:
| **Model Input D Type** | `float` | | **Model Input D Type** | `float` |
| **Object Detection Model Type** | `ssd` | | **Object Detection Model Type** | `ssd` |
yaml: |- yaml: |-
detectors: models:
memx0: - devices:
type: memryx - memryx:PCIe:0
device: PCIe:0
model:
model_type: ssd model_type: ssd
width: 320 width: 320
height: 320 height: 320
@@ -1082,12 +1018,9 @@ tensorrt:
| **Model Input D Type** | `int` (Frigate's default value) | | **Model Input D Type** | `int` (Frigate's default value) |
| **Object Detection Model Type** | `ssd` (Frigate's default value) | | **Object Detection Model Type** | `ssd` (Frigate's default value) |
yaml: |- yaml: |-
detectors: models:
tensorrt: - devices:
type: tensorrt - tensorrt:0
device: 0 #This is the default, select the first GPU
model:
path: /config/model_cache/tensorrt/yolov7-320.trt # use the filename you generated above path: /config/model_cache/tensorrt/yolov7-320.trt # use the filename you generated above
labelmap_path: /labelmap/coco-80.txt labelmap_path: /labelmap/coco-80.txt
input_tensor: nchw input_tensor: nchw
@@ -1115,11 +1048,10 @@ synaptics:
| **Model Input D Type** | `int` (Frigate's default value) | | **Model Input D Type** | `int` (Frigate's default value) |
| **Object Detection Model Type** | `ssd` (Frigate's default value) | | **Object Detection Model Type** | `ssd` (Frigate's default value) |
yaml: |- yaml: |-
detectors: # required models:
synap_npu: # required - # required
type: synaptics # required devices:
- synaptics
model: # required
path: /synaptics/mobilenet.synap # required path: /synaptics/mobilenet.synap # required
width: 224 # required width: 224 # required
height: 224 # required height: 224 # required
@@ -1149,7 +1081,9 @@ rknn:
| **Model Input D Type** | `int` (Frigate's default value) | | **Model Input D Type** | `int` (Frigate's default value) |
| **Object Detection Model Type** | `yolo-generic` | | **Object Detection Model Type** | `yolo-generic` |
yaml: |- yaml: |-
model: # required models:
- devices:
- rknn
# name of model (will be automatically downloaded) or path to your own .rknn model file # name of model (will be automatically downloaded) or path to your own .rknn model file
# possible values are: # possible values are:
# - frigate-fp16-yolov9-t # - frigate-fp16-yolov9-t
@@ -1187,7 +1121,9 @@ rknn:
| **Model Input D Type** | `int` (Frigate's default value) | | **Model Input D Type** | `int` (Frigate's default value) |
| **Object Detection Model Type** | `yolonas` | | **Object Detection Model Type** | `yolonas` |
yaml: |- yaml: |-
model: # required models:
- devices:
- rknn
# name of model (will be automatically downloaded) or path to your own .rknn model file # name of model (will be automatically downloaded) or path to your own .rknn model file
# possible values are: # possible values are:
# - deci-fp16-yolonas_s # - deci-fp16-yolonas_s
@@ -1222,7 +1158,9 @@ rknn:
| **Model Input D Type** | `int` (Frigate's default value) | | **Model Input D Type** | `int` (Frigate's default value) |
| **Object Detection Model Type** | `yolox` | | **Object Detection Model Type** | `yolox` |
yaml: |- yaml: |-
model: # required models:
- devices:
- rknn
# name of model (will be automatically downloaded) or path to your own .rknn model file # name of model (will be automatically downloaded) or path to your own .rknn model file
# possible values are: # possible values are:
# - rock-i8-yolox_nano # - rock-i8-yolox_nano
@@ -1257,6 +1195,7 @@ axengine:
| **Model Input D Type** | `int` | | **Model Input D Type** | `int` |
| **Object Detection Model Type** | `yolo-generic` | | **Object Detection Model Type** | `yolo-generic` |
yaml: |- yaml: |-
<<<<<<< HEAD
detectors: detectors:
axengine: axengine:
type: axengine type: axengine
@@ -1269,3 +1208,96 @@ axengine:
input_dtype: int input_dtype: int
input_pixel_format: bgr input_pixel_format: bgr
labelmap_path: /labelmap/coco-80.txt labelmap_path: /labelmap/coco-80.txt
=======
models:
- devices:
- axengine
path: frigate-yolov9-tiny
model_type: yolo-generic
width: 320
height: 320
input_dtype: int
input_pixel_format: bgr
labelmap_path: /labelmap/coco-80.txt
degirumAiServer:
title: DeGirum AI Server
models:
- key: ai-server-inference
label: AI Server Inference
recommended: true
download: |-
Launch a DeGirum AI server as a Docker container, then point the detector at it. Add this to your `docker-compose.yml`:
```yaml
degirum_detector:
container_name: degirum
image: degirum/aiserver:latest
privileged: true
ports:
- "8778:8778"
```
Set `location` to the server's service name, container name, or `host:port`.
ui: |
Navigate to **Settings > System > Detectors and model** and select **DeGirum** from the detector type dropdown and click **Add**.
| Field | Value |
| --- | --- |
| **Location** | `degirum` |
| **Zoo** | `degirum/public` |
| **Token** | your AI Hub token (optional for the public zoo) |
yaml: |
models:
- devices:
- degirum:degirum
path: ./mobilenet_v2_ssd_coco--300x300_quant_n2x_orca1_1
width: 300
height: 300
input_pixel_format: rgb
degirumLocal:
title: DeGirum Local
models:
- key: local-inference
label: Local Inference
recommended: true
download: Run hardware directly inside the Frigate container with `@local`, removing the AI server hop. The matching device runtime (e.g. the Hailo runtime) must be installed in the container; confirm it with `degirum sys-info`.
ui: |
Navigate to **Settings > System > Detectors and model** and select **DeGirum** from the detector type dropdown and click **Add**.
| Field | Value |
| --- | --- |
| **Location** | `@local` |
| **Zoo** | `degirum/public` |
| **Token** | your AI Hub token (optional for the public zoo) |
yaml: |
models:
- devices:
- degirum:@local
path: ./mobilenet_v2_ssd_coco--300x300_quant_n2x_orca1_1
width: 300
height: 300
input_pixel_format: rgb
degirumCloud:
title: DeGirum AI Hub Cloud
models:
- key: ai-hub-cloud-inference
label: AI Hub Cloud Inference
recommended: true
download: Run inferences on DeGirum's [AI Hub](https://hub.degirum.com) cloud with `@cloud`. Sign up, create an access token, and set it as `token`. Network latency may require lowering your detection fps.
ui: |
Navigate to **Settings > System > Detectors and model** and select **DeGirum** from the detector type dropdown and click **Add**.
| Field | Value |
| --- | --- |
| **Location** | `@cloud` |
| **Zoo** | `degirum/public` |
| **Token** | your AI Hub token (optional for the public zoo) |
yaml: |
models:
- devices:
- degirum:@cloud
path: ./mobilenet_v2_ssd_coco--300x300_quant_n2x_orca1_1
width: 300
height: 300
input_pixel_format: rgb
>>>>>>> 34363affa (Refactor detector and model management)
+29 -18
View File
@@ -56,17 +56,6 @@ mqtt:
# 2 = exactly once # 2 = exactly once
qos: 0 qos: 0
# Optional: Detectors configuration. Defaults to a single CPU detector
detectors:
# Required: name of the detector
detector_name:
# Required: type of the detector
# Frigate provides many types, see https://docs.frigate.video/configuration/object_detectors for more details (default: shown below)
# Additional detector types can also be plugged in.
# Detectors may require additional configuration.
# Refer to the Detectors configuration page for more information.
type: cpu
# Optional: Database configuration # Optional: Database configuration
database: database:
# The path to store the SQLite DB (default: shown below) # The path to store the SQLite DB (default: shown below)
@@ -157,10 +146,22 @@ auth:
- front_door - front_door
- back_yard - back_yard
# Optional: model modifications # Optional: object detection models. Defaults to a single model on a CPU detector.
# NOTE: The default values are for the EdgeTPU detector. # NOTE: The default values are for the EdgeTPU detector.
# Other detectors will require the model config to be set. # Other detectors will require the model config to be set.
model: models:
# Optional: the camera environment this model is for (default: shown below)
# Cameras select a model by setting detect -> scene to a matching value, and
# a model with a scene of all is used by any camera that does not set one.
# Valid values are all, indoor, outdoor, indoor_thermal, outdoor_thermal
- scene: all
# Required: hardware this model runs on, as <detector> or <detector>:<device>
# See https://docs.frigate.video/configuration/object_detectors for the
# detectors available and the devices each one accepts. All of a model's
# devices must use the same detector. Listing the same device more than once
# runs additional inference processes on it.
devices:
- edgetpu:pci:0
# Required: path to the model. Frigate+ models use plus://<model_id> (default: automatic based on detector) # Required: path to the model. Frigate+ models use plus://<model_id> (default: automatic based on detector)
path: /edgetpu_model.tflite path: /edgetpu_model.tflite
# Required: path to the labelmap (default: shown below) # Required: path to the labelmap (default: shown below)
@@ -251,11 +252,17 @@ birdseye:
# Optional: Encoding quality of the mpeg1 feed (default: shown below) # Optional: Encoding quality of the mpeg1 feed (default: shown below)
# 1 is the highest quality, and 31 is the lowest. Lower quality feeds utilize less CPU resources. # 1 is the highest quality, and 31 is the lowest. Lower quality feeds utilize less CPU resources.
quality: 8 quality: 8
# Optional: Mode of the view. Available options are: objects, motion, and continuous # Optional: Activity types that include cameras in Birdseye (default: shown below)
# objects - cameras are included if they have had a tracked object within the last 30 seconds # Multiple activity types can be enabled at the same time.
# motion - cameras are included if motion was detected in the last 30 seconds mode:
# continuous - all cameras are included always # Optional: All cameras are included always (default: shown below)
mode: objects continuous: False
# Optional: Cameras are included if motion was detected in the last 30 seconds (default: shown below)
motion: False
# Optional: Cameras are included if they have had an active tracked object within the last 30 seconds (default: shown below)
objects: True
# Optional: Cameras are included while they have a stationary tracked object (default: shown below)
stationary_objects: False
# Optional: Threshold for camera activity to stop showing camera (default: shown below) # Optional: Threshold for camera activity to stop showing camera (default: shown below)
inactivity_threshold: 30 inactivity_threshold: 30
# Optional: Configure the birdseye layout # Optional: Configure the birdseye layout
@@ -306,6 +313,10 @@ detect:
width: 1280 width: 1280
# Optional: height of the frame for the input with the detect role (default: use native stream resolution) # Optional: height of the frame for the input with the detect role (default: use native stream resolution)
height: 720 height: 720
# Optional: the environment this camera looks at, which picks the model it runs on
# (default: the model with a scene of all)
# Valid values are all, indoor, outdoor, indoor_thermal, outdoor_thermal
scene: outdoor
# Optional: desired fps for your camera for the input with the detect role (default: shown below) # Optional: desired fps for your camera for the input with the detect role (default: shown below)
# NOTE: Recommended value of 5. Ideally, try and reduce your FPS on the camera. # NOTE: Recommended value of 5. Ideally, try and reduce your FPS on the camera.
fps: 5 fps: 5
+5 -3
View File
@@ -192,7 +192,9 @@ Navigate to <NavPath path="Settings > System > Detectors and model" /> and open
```yaml ```yaml
# Optional: model config # Optional: model config
model: models:
- devices:
- openvino:GPU
path: /path/to/model path: /path/to/model
width: 320 width: 320
height: 320 height: 320
@@ -214,8 +216,8 @@ If the labelmap is customized then the labels used for alerts will need to be ad
The labelmap can be customized to your needs. A common reason to do this is to combine multiple object types that are easily confused when you don't need to be as granular such as car/truck. By default, truck is renamed to car because they are often confused. You cannot add new object types, but you can change the names of existing objects in the model. The labelmap can be customized to your needs. A common reason to do this is to combine multiple object types that are easily confused when you don't need to be as granular such as car/truck. By default, truck is renamed to car because they are often confused. You cannot add new object types, but you can change the names of existing objects in the model.
```yaml ```yaml
model: models:
labelmap: - labelmap:
2: vehicle 2: vehicle
3: vehicle 3: vehicle
5: vehicle 5: vehicle
+15 -11
View File
@@ -18,13 +18,14 @@ Each camera tile in Birdseye is composed from the frames of the stream assigned
## Birdseye Behavior ## Birdseye Behavior
### Birdseye Modes ### Birdseye Activity Types
Birdseye offers different modes to customize which cameras show under which circumstances. Birdseye offers independent activity types that control when cameras are shown. Multiple activity types can be enabled together.
- **continuous:** All cameras are always included - **continuous:** The camera is always included
- **motion:** Cameras that have detected motion within the last 30 seconds are included - **motion:** The camera is included when motion was detected within the last 30 seconds
- **objects:** Cameras that have tracked an active object within the last 30 seconds are included - **objects:** The camera is included when an active object was tracked within the last 30 seconds
- **stationary_objects:** The camera is included while a stationary object is tracked
### Custom Birdseye Icon ### Custom Birdseye Icon
@@ -39,27 +40,30 @@ To include a camera in Birdseye view only for specific circumstances, or exclude
**Global settings:** Navigate to <NavPath path="Settings > System > Birdseye" /> to configure the default Birdseye behavior for all cameras. **Global settings:** Navigate to <NavPath path="Settings > System > Birdseye" /> to configure the default Birdseye behavior for all cameras.
**Per-camera overrides:** Navigate to <NavPath path="Settings > Camera configuration > Birdseye" /> to override the mode or disable Birdseye for a specific camera. **Per-camera overrides:** Navigate to <NavPath path="Settings > Camera configuration > Birdseye" /> to override the activity types or disable Birdseye for a specific camera.
| Field | Description | | Field | Description |
| ------------------- | ------------------------------------------------------------- | | ---------------------- | ---------------------------------------------------------- |
| **Enable Birdseye** | Whether this camera appears in Birdseye view | | **Enable Birdseye** | Whether this camera appears in Birdseye view |
| **Tracking mode** | When to show the camera: `continuous`, `motion`, or `objects` | | **Activity types** | Conditions that determine when to show the camera |
</TabItem> </TabItem>
<TabItem value="yaml"> <TabItem value="yaml">
```yaml {8-10,12-14} ```yaml {8-11,13-15}
# Include all cameras by default in Birdseye view # Include all cameras by default in Birdseye view
birdseye: birdseye:
enabled: True enabled: True
mode: continuous mode:
continuous: True
cameras: cameras:
front: front:
# Only include the "front" camera in Birdseye view when objects are detected # Only include the "front" camera in Birdseye view when objects are detected
birdseye: birdseye:
mode: objects mode:
continuous: False
objects: True
back: back:
# Exclude the "back" camera from Birdseye view # Exclude the "back" camera from Birdseye view
birdseye: birdseye:
+9 -14
View File
@@ -172,10 +172,9 @@ mqtt:
ffmpeg: ffmpeg:
hwaccel_args: preset-rpi-64-h264 hwaccel_args: preset-rpi-64-h264
detectors: models:
coral: - devices:
type: edgetpu - edgetpu:usb
device: usb
record: record:
enabled: True enabled: True
@@ -249,10 +248,9 @@ mqtt:
ffmpeg: ffmpeg:
hwaccel_args: preset-vaapi hwaccel_args: preset-vaapi
detectors: models:
coral: - devices:
type: edgetpu - edgetpu:usb
device: usb
record: record:
enabled: True enabled: True
@@ -329,12 +327,9 @@ mqtt:
ffmpeg: ffmpeg:
hwaccel_args: preset-vaapi hwaccel_args: preset-vaapi
detectors: models:
ov: - devices:
type: openvino - openvino:AUTO
device: AUTO
model:
width: 300 width: 300
height: 300 height: 300
input_tensor: nhwc input_tensor: nhwc
+201 -59
View File
@@ -68,12 +68,66 @@ Frigate supports multiple different detectors that work on different types of ha
:::note :::note
Multiple detectors can not be mixed for object detection (ex: OpenVINO and Coral EdgeTPU can not be used for object detection at the same time). A single model can not be spread across different detector types (ex: OpenVINO and Coral EdgeTPU can not run the same model at the same time). Configuring more than one model, each on its own detector type, is supported.
This does not affect using hardware for accelerating other tasks such as [semantic search](./semantic_search.md) This does not affect using hardware for accelerating other tasks such as [semantic search](./semantic_search.md)
::: :::
### Configuring models and hardware
Object detection is configured with a `models` list. Each entry describes one model and the hardware it runs on:
```yaml
models:
- devices:
- openvino:GPU
path: /config/model_cache/yolov9-s.onnx
model_type: yolo-generic
width: 320
height: 320
```
Each entry in `devices` is a detector type, optionally followed by a colon and a device for that detector, such as `edgetpu:pci:0`, `openvino:NPU`, or `tensorrt:0`. The per-detector sections below document the device values each one accepts. Listing several devices runs the model on all of them, and listing the **same** device more than once runs additional inference processes against it, which can improve throughput on hardware that keeps up with more than one stream:
```yaml
models:
- devices:
- openvino:GPU
- openvino:GPU
```
Coral EdgeTPU and MemryX accelerators can only be opened by one process, so those devices can not be repeated.
### Running more than one model
Cameras can be split across models by scene, which is useful when indoor and outdoor cameras benefit from differently trained models. Each model declares the `scene` it is for, and each camera picks one with `detect -> scene`:
```yaml
models:
- scene: outdoor
path: plus://your-outdoor-model
devices:
- edgetpu:pci:0
- scene: indoor
path: /config/model_cache/indoor.onnx
model_type: yolo-generic
devices:
- openvino:GPU
cameras:
driveway:
detect:
scene: outdoor
...
hallway:
detect:
scene: indoor
...
```
Available scenes are `all`, `indoor`, `outdoor`, `indoor_thermal`, and `outdoor_thermal`. A model with a scene of `all` is used by every camera that does not set one, and `all` is the default when a model does not declare a scene. Changing a camera's scene requires a restart.
### Choosing a model size ### Choosing a model size
Along with picking a detector for your hardware, you will choose a model's **input resolution** (such as `320x320` or `640x640`) and, for model families like YOLOv9, a **variant size** (`tiny`, `small`, etc.). Both affect the balance between accuracy and the inference time your hardware can sustain. Along with picking a detector for your hardware, you will choose a model's **input resolution** (such as `320x320` or `640x640`) and, for model families like YOLOv9, a **variant size** (`tiny`, `small`, etc.). Both affect the balance between accuracy and the inference time your hardware can sustain.
@@ -92,11 +146,11 @@ The best detection accuracy comes from a model trained on images that look like
# Officially Supported Detectors # Officially Supported Detectors
Frigate provides a number of builtin detector types. By default, Frigate will use a single CPU detector. Other detectors may require additional configuration as described below. When using multiple detectors they will run in dedicated processes, but pull from a common queue of detection requests from across all cameras. Frigate provides a number of builtin detector types. By default, Frigate will use a single CPU detector. Other detectors may require additional configuration as described below. Each of a model's devices runs in a dedicated process, and they pull from a common queue of detection requests from the cameras assigned to that model.
## Edge TPU Detector ## Edge TPU Detector
The Edge TPU detector type runs TensorFlow Lite models utilizing the Google Coral delegate for hardware acceleration. To configure an Edge TPU detector, set the `"type"` attribute to `"edgetpu"`. The Edge TPU detector type runs TensorFlow Lite models utilizing the Google Coral delegate for hardware acceleration. To use it, prefix a model's device with `edgetpu`.
The Edge TPU device can be specified using the `"device"` attribute according to the [Documentation for the TensorFlow Lite Python API](https://coral.ai/docs/edgetpu/multiple-edgetpu/#using-the-tensorflow-lite-python-api). If not set, the delegate will use the first device it finds. The Edge TPU device can be specified using the `"device"` attribute according to the [Documentation for the TensorFlow Lite Python API](https://coral.ai/docs/edgetpu/multiple-edgetpu/#using-the-tensorflow-lite-python-api). If not set, the delegate will use the first device it finds.
@@ -117,10 +171,9 @@ Navigate to <NavPath path="Settings > System > Detectors and model" /> and selec
<TabItem value="yaml"> <TabItem value="yaml">
```yaml ```yaml
detectors: models:
coral: - devices:
type: edgetpu - edgetpu:usb
device: usb
``` ```
</TabItem> </TabItem>
@@ -137,13 +190,10 @@ Navigate to <NavPath path="Settings > System > Detectors and model" /> and selec
<TabItem value="yaml"> <TabItem value="yaml">
```yaml ```yaml
detectors: models:
coral1: - devices:
type: edgetpu - edgetpu:usb:0
device: usb:0 - edgetpu:usb:1
coral2:
type: edgetpu
device: usb:1
``` ```
</TabItem> </TabItem>
@@ -162,10 +212,9 @@ Navigate to <NavPath path="Settings > System > Detectors and model" /> and selec
<TabItem value="yaml"> <TabItem value="yaml">
```yaml ```yaml
detectors: models:
coral: - devices:
type: edgetpu - 'edgetpu:'
device: ""
``` ```
</TabItem> </TabItem>
@@ -182,10 +231,9 @@ Navigate to <NavPath path="Settings > System > Detectors and model" /> and selec
<TabItem value="yaml"> <TabItem value="yaml">
```yaml ```yaml
detectors: models:
coral: - devices:
type: edgetpu - edgetpu:pci
device: pci
``` ```
</TabItem> </TabItem>
@@ -202,13 +250,10 @@ Navigate to <NavPath path="Settings > System > Detectors and model" /> and selec
<TabItem value="yaml"> <TabItem value="yaml">
```yaml ```yaml
detectors: models:
coral1: - devices:
type: edgetpu - edgetpu:pci:0
device: pci:0 - edgetpu:pci:1
coral2:
type: edgetpu
device: pci:1
``` ```
</TabItem> </TabItem>
@@ -225,13 +270,10 @@ Navigate to <NavPath path="Settings > System > Detectors and model" /> and selec
<TabItem value="yaml"> <TabItem value="yaml">
```yaml ```yaml
detectors: models:
coral_usb: - devices:
type: edgetpu - edgetpu:usb
device: usb - edgetpu:pci
coral_pci:
type: edgetpu
device: pci
``` ```
</TabItem> </TabItem>
@@ -273,7 +315,7 @@ Hailo8 supports all models in the Hailo Model Zoo that include HailoRT post-proc
## OpenVINO Detector ## OpenVINO Detector
The OpenVINO detector type runs an OpenVINO IR model on AMD and Intel CPUs, Intel GPUs and Intel NPUs. To configure an OpenVINO detector, set the `"type"` attribute to `"openvino"`. The OpenVINO detector type runs an OpenVINO IR model on AMD and Intel CPUs, Intel GPUs and Intel NPUs. To use it, prefix a model's device with `openvino`.
The OpenVINO device to be used is specified using the `"device"` attribute according to the naming conventions in the [Device Documentation](https://docs.openvino.ai/2025/openvino-workflow/running-inference/inference-devices-and-modes.html). The most common devices are `CPU`, `GPU`, or `NPU`. The OpenVINO device to be used is specified using the `"device"` attribute according to the naming conventions in the [Device Documentation](https://docs.openvino.ai/2025/openvino-workflow/running-inference/inference-devices-and-modes.html). The most common devices are `CPU`, `GPU`, or `NPU`.
@@ -286,13 +328,10 @@ OpenVINO is supported on 6th Gen Intel platforms (Skylake) and newer. It will al
When using many cameras one detector may not be enough to keep up. Multiple detectors can be defined assuming GPU resources are available. An example configuration would be: When using many cameras one detector may not be enough to keep up. Multiple detectors can be defined assuming GPU resources are available. An example configuration would be:
```yaml ```yaml
detectors: models:
ov_0: - devices:
type: openvino - openvino:GPU # or NPU
device: GPU # or NPU - openvino:GPU # or NPU
ov_1:
type: openvino
device: GPU # or NPU
``` ```
::: :::
@@ -313,6 +352,12 @@ Intel NPUs cannot be used under Home Assistant OS, which does not include the NP
## Apple Silicon detector ## Apple Silicon detector
:::warning
The network-based detectors (Deepstack, DeGirum, and the Apple Silicon client) are being reworked. Their extra options no longer have a place in the config, so only the endpoint carried in the device string is honored right now: Deepstack ignores `api_key` and `api_timeout`, DeGirum ignores `zoo` and `token`, and the Apple Silicon client ignores `request_timeout_ms` and `linger_ms`. Anything else is dropped when your config is migrated.
:::
The NPU in Apple Silicon can't be accessed from within a container, so the [Apple Silicon detector client](https://github.com/frigate-nvr/apple-silicon-detector) must first be setup. It is recommended to use the Frigate docker image with `-standard-arm64` suffix, for example `ghcr.io/blakeblackshear/frigate:stable-standard-arm64`. The NPU in Apple Silicon can't be accessed from within a container, so the [Apple Silicon detector client](https://github.com/frigate-nvr/apple-silicon-detector) must first be setup. It is recommended to use the Frigate docker image with `-standard-arm64` suffix, for example `ghcr.io/blakeblackshear/frigate:stable-standard-arm64`.
### Setup {#setup-apple-silicon} ### Setup {#setup-apple-silicon}
@@ -453,11 +498,10 @@ If the correct build is used for your GPU then the GPU will be detected and used
When using many cameras one detector may not be enough to keep up. Multiple detectors can be defined assuming GPU resources are available. An example configuration would be: When using many cameras one detector may not be enough to keep up. Multiple detectors can be defined assuming GPU resources are available. An example configuration would be:
```yaml ```yaml
detectors: models:
onnx_0: - devices:
type: onnx - onnx
onnx_1: - onnx
type: onnx
``` ```
::: :::
@@ -470,7 +514,7 @@ detectors:
## CPU Detector (not recommended) ## CPU Detector (not recommended)
The CPU detector type runs a TensorFlow Lite model utilizing the CPU without hardware acceleration. It is recommended to use a hardware accelerated detector type instead for better performance. To configure a CPU based detector, set the `"type"` attribute to `"cpu"`. The CPU detector type runs a TensorFlow Lite model utilizing the CPU without hardware acceleration. It is recommended to use a hardware accelerated detector type instead for better performance. To use it, set a model's device to `cpu`.
:::danger :::danger
@@ -480,7 +524,7 @@ The CPU detector is not recommended for general use. If you do not have GPU or E
The number of threads used by the interpreter can be specified using the `"num_threads"` attribute, and defaults to `3.` The number of threads used by the interpreter can be specified using the `"num_threads"` attribute, and defaults to `3.`
A TensorFlow Lite model is provided in the container at `/cpu_model.tflite` and is used by this detector type by default. To provide your own model, bind mount the file into the container and provide the path with `model.path`. A TensorFlow Lite model is provided in the container at `/cpu_model.tflite` and is used by this detector type by default. To provide your own model, bind mount the file into the container and provide the path with the model's `path`.
### Configuration {#configuration-cpu} ### Configuration {#configuration-cpu}
@@ -490,6 +534,12 @@ When using CPU detectors, you can add one CPU detector per camera. Adding more d
## Deepstack / CodeProject.AI Server Detector ## Deepstack / CodeProject.AI Server Detector
:::warning
The network-based detectors (Deepstack, DeGirum, and the Apple Silicon client) are being reworked. Their extra options no longer have a place in the config, so only the endpoint carried in the device string is honored right now: Deepstack ignores `api_key` and `api_timeout`, DeGirum ignores `zoo` and `token`, and the Apple Silicon client ignores `request_timeout_ms` and `linger_ms`. Anything else is dropped when your config is migrated.
:::
The Deepstack / CodeProject.AI Server detector for Frigate allows you to integrate Deepstack and CodeProject.AI object detection capabilities into Frigate. CodeProject.AI and DeepStack are open-source AI platforms that can be run on various devices such as the Raspberry Pi, Nvidia Jetson, and other compatible hardware. It is important to note that the integration is performed over the network, so the inference times may not be as fast as native Frigate detectors, but it still provides an efficient and reliable solution for object detection and tracking. The Deepstack / CodeProject.AI Server detector for Frigate allows you to integrate Deepstack and CodeProject.AI object detection capabilities into Frigate. CodeProject.AI and DeepStack are open-source AI platforms that can be run on various devices such as the Raspberry Pi, Nvidia Jetson, and other compatible hardware. It is important to note that the integration is performed over the network, so the inference times may not be as fast as native Frigate detectors, but it still provides an efficient and reliable solution for object detection and tracking.
### Setup {#setup-deepstack} ### Setup {#setup-deepstack}
@@ -552,7 +602,7 @@ For detailed instructions on compiling models, refer to the [MemryX Compiler](ht
3. Depending on the model, the compiler may also generate a cropped post-processing network. If present, it will be named with the suffix `_post.onnx`. 3. Depending on the model, the compiler may also generate a cropped post-processing network. If present, it will be named with the suffix `_post.onnx`.
4. Bind-mount the `.zip` file into the container and specify its path using `model.path` in your config. 4. Bind-mount the `.zip` file into the container and specify its path using the model's `path` in your config.
5. Update `labelmap_path` to match your custom model's labels. 5. Update `labelmap_path` to match your custom model's labels.
@@ -682,13 +732,10 @@ If no custom model is provided, the RKNN detector downloads a default model from
When using many cameras one detector may not be enough to keep up. Multiple detectors can be defined assuming NPU resources are available. An example configuration would be: When using many cameras one detector may not be enough to keep up. Multiple detectors can be defined assuming NPU resources are available. An example configuration would be:
```yaml ```yaml
detectors: models:
rknn_0: - devices:
type: rknn - rknn:0
num_cores: 0 - rknn:0
rknn_1:
type: rknn
num_cores: 0
``` ```
::: :::
@@ -762,6 +809,101 @@ Explanation of the parameters:
- **example**: Specifying `output_name = "frigate-{quant}-{input_basename}-{soc}-v{tk_version}"` could result in a model called `frigate-i8-my_model-rk3588-v2.3.0.rknn`. - **example**: Specifying `output_name = "frigate-{quant}-{input_basename}-{soc}-v{tk_version}"` could result in a model called `frigate-i8-my_model-rk3588-v2.3.0.rknn`.
- `config`: Configuration passed to `rknn-toolkit2` for model conversion. For an explanation of all available parameters have a look at section "2.2. Model configuration" of [this manual](https://github.com/MarcA711/rknn-toolkit2/releases/download/v2.3.2/03_Rockchip_RKNPU_API_Reference_RKNN_Toolkit2_V2.3.2_EN.pdf). - `config`: Configuration passed to `rknn-toolkit2` for model conversion. For an explanation of all available parameters have a look at section "2.2. Model configuration" of [this manual](https://github.com/MarcA711/rknn-toolkit2/releases/download/v2.3.2/03_Rockchip_RKNPU_API_Reference_RKNN_Toolkit2_V2.3.2_EN.pdf).
<<<<<<< HEAD
=======
## DeGirum
:::warning
The network-based detectors (Deepstack, DeGirum, and the Apple Silicon client) are being reworked. Their extra options no longer have a place in the config, so only the endpoint carried in the device string is honored right now: Deepstack ignores `api_key` and `api_timeout`, DeGirum ignores `zoo` and `token`, and the Apple Silicon client ignores `request_timeout_ms` and `linger_ms`. Anything else is dropped when your config is migrated.
:::
DeGirum is a detector that can use any type of hardware listed on [their website](https://hub.degirum.com). DeGirum can be used with local hardware through a DeGirum AI Server, or through the use of `@local`. You can also connect directly to DeGirum's AI Hub to run inferences. **Please Note:** This detector _cannot_ be used for commercial purposes.
### Configuration {#configuration-degirum}
#### AI Server Inference
Before starting with the config file for this section, you must first launch an AI server. DeGirum has an AI server ready to use as a docker container. Add this to your `docker-compose.yml` to get started:
```yaml
degirum_detector:
container_name: degirum
image: degirum/aiserver:latest
privileged: true
ports:
- "8778:8778"
```
All supported hardware will automatically be found on your AI server host as long as relevant runtimes and drivers are properly installed on your machine. Refer to [DeGirum's docs site](https://docs.degirum.com/pysdk/runtimes-and-drivers) if you have any trouble.
Once completed, configure the detector as follows:
<ModelConfigDropdown detectorTitle="DeGirum" models={objectDetectorsModels.degirumAiServer.models} />
The model is set on the same `models` entry as the DeGirum device. You can set it to:
- A model listed on the [AI Hub](https://hub.degirum.com)
- If this is what you choose to do, the correct model will be downloaded onto your machine before running.
- A local directory acting as a zoo. See DeGirum's docs site [for more information](https://docs.degirum.com/pysdk/user-guide-pysdk/organizing-models#model-zoo-directory-structure).
- A path to some model.json.
```yaml
models:
- devices:
- degirum:<location>
path: ./mobilenet_v2_ssd_coco--300x300_quant_n2x_orca1_1 # directory to model .json and file
width: 300 # width is in the model name as the first number in the "int"x"int" section
height: 300 # height is in the model name as the second number in the "int"x"int" section
input_pixel_format: rgb/bgr # look at the model.json to figure out which to put here
```
#### Local Inference
It is also possible to eliminate the need for an AI server and run the hardware directly. The benefit of this approach is that you eliminate any bottlenecks that occur when transferring prediction results from the AI server docker container to the frigate one. However, the method of implementing local inference is different for every device and hardware combination, so it's usually more trouble than it's worth. A general guideline to achieve this would be:
1. Ensuring that the frigate docker container has the runtime you want to use. So for instance, running `@local` for Hailo means making sure the container you're using has the Hailo runtime installed.
2. To double check the runtime is detected by the DeGirum detector, make sure the `degirum sys-info` command properly shows whatever runtimes you mean to install.
3. Create a DeGirum detector in your configuration.
<ModelConfigDropdown detectorTitle="DeGirum" models={objectDetectorsModels.degirumLocal.models} />
Once the DeGirum device is set up, you can choose a model on the same `models` entry in the `config.yml` file.
```yaml
models:
- devices:
- degirum:<location>
path: mobilenet_v2_ssd_coco--300x300_quant_n2x_orca1_1
width: 300 # width is in the model name as the first number in the "int"x"int" section
height: 300 # height is in the model name as the second number in the "int"x"int" section
input_pixel_format: rgb/bgr # look at the model.json to figure out which to put here
```
#### AI Hub Cloud Inference
If you do not possess whatever hardware you want to run, there's also the option to run cloud inferences. Do note that your detection fps might need to be lowered as network latency does significantly slow down this method of detection. For use with Frigate, we highly recommend using a local AI server as described above. To set up cloud inferences,
1. Sign up at [DeGirum's AI Hub](https://hub.degirum.com).
2. Get an access token.
3. Create a DeGirum detector in your configuration.
<ModelConfigDropdown detectorTitle="DeGirum" models={objectDetectorsModels.degirumCloud.models} />
Once the DeGirum device is set up, you can choose a model on the same `models` entry in the `config.yml` file.
```yaml
models:
- devices:
- degirum:<location>
path: mobilenet_v2_ssd_coco--300x300_quant_n2x_orca1_1
width: 300 # width is in the model name as the first number in the "int"x"int" section
height: 300 # height is in the model name as the second number in the "int"x"int" section
input_pixel_format: rgb/bgr # look at the model.json to figure out which to put here
```
>>>>>>> 34363affa (Refactor detector and model management)
## AXERA ## AXERA
Hardware accelerated object detection is supported on the following SoCs: Hardware accelerated object detection is supported on the following SoCs:
+10 -15
View File
@@ -222,13 +222,10 @@ You need to refer to **Configure hardware acceleration** above to enable the con
```yaml {3-6,9-15,20-21} ```yaml {3-6,9-15,20-21}
mqtt: ... mqtt: ...
detectors: # <---- add detectors models: # <---- add models
ov: - devices:
type: openvino # <---- use openvino detector - openvino:GPU # <---- use the openvino detector on the GPU
device: GPU
# We will use the default MobileNet_v2 model from OpenVINO. # We will use the default MobileNet_v2 model from OpenVINO.
model:
width: 300 width: 300
height: 300 height: 300
input_tensor: nhwc input_tensor: nhwc
@@ -281,10 +278,9 @@ Navigate to <NavPath path="Settings > System > Detectors and model" /> and add a
```yaml {3-6,11-12} ```yaml {3-6,11-12}
mqtt: ... mqtt: ...
detectors: # <---- add detectors models: # <---- add models
coral: - devices:
type: edgetpu - edgetpu:usb
device: usb
cameras: cameras:
name_of_your_camera: name_of_your_camera:
@@ -321,10 +317,9 @@ If you are using YAML to configure Frigate instead of the UI, your configuration
mqtt: mqtt:
enabled: False enabled: False
detectors: models:
coral: - devices:
type: edgetpu - edgetpu:usb
device: usb
cameras: cameras:
name_of_your_camera: name_of_your_camera:
@@ -357,7 +352,7 @@ In order to review activity in the Frigate UI, recordings need to be enabled.
```yaml {16-17} ```yaml {16-17}
mqtt: ... mqtt: ...
detectors: ... models: ...
cameras: cameras:
name_of_your_camera: name_of_your_camera:
+7 -6
View File
@@ -555,20 +555,21 @@ Topic with current state of Birdseye for a camera. Published values are `ON` and
### `frigate/<camera_name>/birdseye_mode/set` ### `frigate/<camera_name>/birdseye_mode/set`
Topic to set Birdseye mode for a camera. Birdseye offers different modes to customize under which circumstances the camera is shown. Topic to set the Birdseye activity types for a camera. Send one uppercase activity type or combine multiple types with commas, for example `MOTION,OBJECTS,STATIONARY_OBJECTS`.
_Note: Changing the value from `CONTINUOUS` -> `MOTION | OBJECTS` will take up to 30 seconds for _Note: Changing the value from `CONTINUOUS` to non-continuous activity types will take up to 30 seconds for
the camera to be removed from the view._ the camera to be removed from the view._
| Command | Description | | Command | Description |
| ------------ | ----------------------------------------------------------------- | | -------------------- | ---------------------------------------------------------------- |
| `CONTINUOUS` | Always included | | `CONTINUOUS` | Always included |
| `MOTION` | Show when detected motion within the last 30 seconds are included | | `MOTION` | Shown if motion was detected within the last 30 seconds |
| `OBJECTS` | Shown if an active object tracked within the last 30 seconds | | `OBJECTS` | Shown if an active object was tracked within the last 30 seconds |
| `STATIONARY_OBJECTS` | Shown while a stationary object is tracked |
### `frigate/<camera_name>/birdseye_mode/state` ### `frigate/<camera_name>/birdseye_mode/state`
Topic with current state of the Birdseye mode for a camera. Published values are `CONTINUOUS`, `MOTION`, `OBJECTS`. Topic with the current Birdseye activity types for a camera. Multiple enabled types are published as a comma-separated value in the order `OBJECTS`, `MOTION`, `STATIONARY_OBJECTS`, `CONTINUOUS`.
### `frigate/<camera_name>/notifications/set` ### `frigate/<camera_name>/notifications/set`
+4 -4
View File
@@ -62,9 +62,8 @@ Once you have [requested your first model](../plus/first_model.md) and gotten yo
You can either choose the new model from the <NavPath path="Settings > System > Detectors and model" /> pane in the Frigate UI (the **Frigate+ Model** tab), or manually set the model at the root level in your config: You can either choose the new model from the <NavPath path="Settings > System > Detectors and model" /> pane in the Frigate UI (the **Frigate+ Model** tab), or manually set the model at the root level in your config:
```yaml ```yaml
detectors: ... models:
- devices: ...
model:
path: plus://<your_model_id> path: plus://<your_model_id>
``` ```
@@ -79,7 +78,8 @@ Models are downloaded into the `/config/model_cache` folder and only downloaded
If needed, you can override the labelmap for Frigate+ models. This is not recommended as renaming labels will break the Submit to Frigate+ feature if the labels are not available in Frigate+. If needed, you can override the labelmap for Frigate+ models. This is not recommended as renaming labels will break the Submit to Frigate+ feature if the labels are not available in Frigate+.
```yaml ```yaml
model: models:
- devices: ...
path: plus://<your_model_id> path: plus://<your_model_id>
labelmap: labelmap:
3: animal 3: animal
+2 -3
View File
@@ -36,9 +36,8 @@ Navigate to <NavPath path="Settings > System > Detectors and model" />. In the *
<TabItem value="yaml"> <TabItem value="yaml">
```yaml ```yaml
detectors: ... models:
- devices: ...
model:
path: plus://<your_model_id> path: plus://<your_model_id>
``` ```
+38
View File
@@ -2946,6 +2946,44 @@ paths:
- frigateUserAuth: [] - frigateUserAuth: []
x-required-role: any x-required-role: any
description: '**Access:** Any authenticated user.' description: '**Access:** Any authenticated user.'
/categorized_object_names:
get:
tags:
- App
summary: Get known object names by object type
description: |-
**Access:** Any authenticated user.
Returns the sub labels and attributes this install can attach,
grouped by object type. Unlike /sub_labels, which reflects what has already been
detected, this reads the config and model files, so it covers recognized face
names, named license plates, custom object classification categories, and the
detector attributes of tracked objects.
operationId: categorized_object_names_categorized_object_names_get
parameters:
- name: object_type
in: query
required: false
schema:
anyOf:
- type: string
- type: 'null'
title: Object Type
responses:
'200':
description: Successful Response
content:
application/json:
schema: {}
'422':
description: Validation Error
content:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
security:
- frigateUserAuth: []
x-required-role: any
/audio_labels: /audio_labels:
get: get:
tags: tags:
+46 -27
View File
@@ -71,6 +71,7 @@ from frigate.util.config import (
find_config_file, find_config_file,
redact_credential, redact_credential,
) )
from frigate.util.object_names import get_categorized_object_names
from frigate.util.schema import get_config_schema from frigate.util.schema import get_config_schema
from frigate.util.services import ( from frigate.util.services import (
get_nvidia_driver_info, get_nvidia_driver_info,
@@ -291,10 +292,6 @@ def config(request: Request):
config: dict[str, dict[str, Any]] = config_obj.model_dump( config: dict[str, dict[str, Any]] = config_obj.model_dump(
mode="json", warnings="none", exclude_none=True mode="json", warnings="none", exclude_none=True
) )
config["detectors"] = {
name: detector.model_dump(mode="json", warnings="none", exclude_none=True)
for name, detector in config_obj.detectors.items()
}
# remove environment_vars for non-admin users # remove environment_vars for non-admin users
if request.headers.get("remote-role") != "admin": if request.headers.get("remote-role") != "admin":
@@ -375,31 +372,28 @@ def config(request: Request):
config["go2rtc"]["streams"][stream_name] = cleaned config["go2rtc"]["streams"][stream_name] = cleaned
config["plus"] = {"enabled": request.app.frigate_config.plus_api.is_active()} config["plus"] = {"enabled": request.app.frigate_config.plus_api.is_active()}
config["model"]["colormap"] = config_obj.model.colormap
config["model"]["all_attributes"] = config_obj.model.all_attributes for index, model in enumerate(config_obj.models):
config["model"]["non_logo_attributes"] = config_obj.model.non_logo_attributes model_dict = config["models"][index]
model_dict["colormap"] = model.colormap
model_dict["all_attributes"] = model.all_attributes
model_dict["non_logo_attributes"] = model.non_logo_attributes
model_dict["labelmap"] = model.merged_labelmap
if not config["plus"]["enabled"]:
continue
# Add model plus data if plus is enabled # Add model plus data if plus is enabled
if config["plus"]["enabled"]: model_dict["plus"] = None
model_path = config.get("model", {}).get("path")
if model_path: if model.path:
model_json_path = FilePath(model_path).with_suffix(".json") model_json_path = FilePath(model.path).with_suffix(".json")
try: try:
with open(model_json_path) as f: with open(model_json_path) as f:
model_plus_data = json.load(f) model_dict["plus"] = json.load(f)
config["model"]["plus"] = model_plus_data except (FileNotFoundError, json.JSONDecodeError):
except FileNotFoundError: pass
config["model"]["plus"] = None
except json.JSONDecodeError:
config["model"]["plus"] = None
else:
config["model"]["plus"] = None
# use merged labelamp
for detector_config in config["detectors"].values():
detector_config["model"]["labelmap"] = (
request.app.frigate_config.model.merged_labelmap
)
return JSONResponse(content=config) return JSONResponse(content=config)
@@ -1313,6 +1307,28 @@ def get_sub_labels(
return JSONResponse(content=sub_labels) return JSONResponse(content=sub_labels)
@router.get(
"/categorized_object_names",
dependencies=[Depends(allow_any_authenticated())],
summary="Get known object names by object type",
description="""Returns the sub labels and attributes this install can attach,
grouped by object type. Unlike /sub_labels, which reflects what has already been
detected, this reads the config and model files, so it covers recognized face
names, named license plates, custom object classification categories, and the
detector attributes of tracked objects.""",
)
def categorized_object_names(
request: Request,
object_type: str | None = None,
allowed_cameras: list[str] = Depends(get_allowed_cameras_for_filter),
):
return JSONResponse(
content=get_categorized_object_names(
request.app.frigate_config, allowed_cameras, object_type
)
)
@router.get("/audio_labels", dependencies=[Depends(allow_any_authenticated())]) @router.get("/audio_labels", dependencies=[Depends(allow_any_authenticated())])
def get_audio_labels(): def get_audio_labels():
labels = load_labels("/audio-labelmap.txt", prefill=521) labels = load_labels("/audio-labelmap.txt", prefill=521)
@@ -1337,11 +1353,14 @@ def plusModels(request: Request, filterByCurrentModelDetector: bool = False):
modelList = models["list"] modelList = models["list"]
config: FrigateConfig = request.app.frigate_config
primary_model = config.primary_model
# current model type # current model type
modelType = request.app.frigate_config.model.model_type modelType = primary_model.model_type
# current detectorType for comparing to supportedDetectors # current detectorType for comparing to supportedDetectors
detectorType = list(request.app.frigate_config.detectors.values())[0].type detectorType = config.devices_for_model(primary_model)[0].detector
validModels = [] validModels = []
+1
View File
@@ -83,6 +83,7 @@ def require_admin_by_default():
"/nvinfo", "/nvinfo",
"/labels", "/labels",
"/sub_labels", "/sub_labels",
"/categorized_object_names",
"/plus/models", "/plus/models",
"/recognized_license_plates", "/recognized_license_plates",
"/timeline", "/timeline",
+25 -2
View File
@@ -50,6 +50,7 @@ from frigate.jobs.vlm_watch import (
stop_vlm_watch_job, stop_vlm_watch_job,
) )
from frigate.models import Event from frigate.models import Event
from frigate.util.object_names import get_categorized_object_names
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -539,6 +540,11 @@ async def execute_tool(
if tool_name == "search_objects": if tool_name == "search_objects":
return await _execute_search_objects(request, arguments, allowed_cameras) return await _execute_search_objects(request, arguments, allowed_cameras)
if tool_name == "get_categorized_object_names":
return JSONResponse(
content=_execute_get_categorized_object_names(request, allowed_cameras)
)
if tool_name == "find_similar_objects": if tool_name == "find_similar_objects":
result = await _execute_find_similar_objects( result = await _execute_find_similar_objects(
request, arguments, allowed_cameras request, arguments, allowed_cameras
@@ -717,6 +723,21 @@ async def _execute_set_camera_state(
return {"success": True, "camera": camera, "feature": feature, "value": value} return {"success": True, "camera": camera, "feature": feature, "value": value}
def _execute_get_categorized_object_names(
request: Request,
allowed_cameras: list[str],
) -> dict[str, Any]:
names = get_categorized_object_names(request.app.frigate_config, allowed_cameras)
if not names:
return {
"names": {},
"message": "No names configured; search by label or semantic_query.",
}
return {"names": names}
async def _execute_tool_internal( async def _execute_tool_internal(
tool_name: str, tool_name: str,
arguments: dict[str, Any], arguments: dict[str, Any],
@@ -741,6 +762,8 @@ async def _execute_tool_internal(
except (json.JSONDecodeError, AttributeError) as e: except (json.JSONDecodeError, AttributeError) as e:
logger.warning(f"Failed to extract tool result: {e}") logger.warning(f"Failed to extract tool result: {e}")
return {"error": "Failed to parse tool result"} return {"error": "Failed to parse tool result"}
elif tool_name == "get_categorized_object_names":
return _execute_get_categorized_object_names(request, allowed_cameras)
elif tool_name == "find_similar_objects": elif tool_name == "find_similar_objects":
return await _execute_find_similar_objects(request, arguments, allowed_cameras) return await _execute_find_similar_objects(request, arguments, allowed_cameras)
elif tool_name == "set_camera_state": elif tool_name == "set_camera_state":
@@ -773,8 +796,8 @@ async def _execute_tool_internal(
else: else:
logger.error( logger.error(
"Tool call failed: unknown tool %r. Expected one of: search_objects, find_similar_objects, " "Tool call failed: unknown tool %r. Expected one of: search_objects, find_similar_objects, "
"get_live_context, start_camera_watch, stop_camera_watch, get_profile_status, get_recap. " "get_categorized_object_names, get_live_context, start_camera_watch, stop_camera_watch, "
"Arguments received: %s", "get_profile_status, get_recap. Arguments received: %s",
tool_name, tool_name,
json.dumps(arguments), json.dumps(arguments),
) )
+5 -5
View File
@@ -575,11 +575,11 @@ async def vod_ts(
Recordings.start_time, Recordings.start_time,
) )
.where( .where(
Recordings.start_time.between(start_ts, end_ts) Recordings.camera == camera_name,
| Recordings.end_time.between(start_ts, end_ts) Recordings.start_time >= start_ts - MAX_SEGMENT_DURATION,
| ((start_ts > Recordings.start_time) & (end_ts < Recordings.end_time)) Recordings.start_time <= end_ts,
Recordings.end_time >= start_ts,
) )
.where(Recordings.camera == camera_name)
.order_by(Recordings.start_time.asc()) .order_by(Recordings.start_time.asc())
.iterator() .iterator()
) )
@@ -814,7 +814,7 @@ async def event_snapshot(
timestamp_style=request.app.frigate_config.cameras[ timestamp_style=request.app.frigate_config.cameras[
event.camera event.camera
].timestamp_style, ].timestamp_style,
colormap=request.app.frigate_config.model.colormap, colormap=request.app.frigate_config.model_for_camera(event.camera).colormap,
) )
except DoesNotExist: except DoesNotExist:
# see if the object is currently being tracked # see if the object is currently being tracked
+2 -1
View File
@@ -25,7 +25,7 @@ from frigate.api.defs.query.recordings_query_parameters import (
) )
from frigate.api.defs.response.generic_response import GenericResponse from frigate.api.defs.response.generic_response import GenericResponse
from frigate.api.defs.tags import Tags from frigate.api.defs.tags import Tags
from frigate.const import RECORD_DIR from frigate.const import MAX_SEGMENT_DURATION, RECORD_DIR
from frigate.models import Event, Recordings from frigate.models import Event, Recordings
from frigate.util.time import get_dst_transitions from frigate.util.time import get_dst_transitions
@@ -243,6 +243,7 @@ async def recordings(
) )
.where( .where(
Recordings.camera == camera_name, Recordings.camera == camera_name,
Recordings.start_time >= after - MAX_SEGMENT_DURATION,
Recordings.end_time >= after, Recordings.end_time >= after,
Recordings.start_time <= before, Recordings.start_time <= before,
) )
+34 -17
View File
@@ -49,6 +49,8 @@ from frigate.debug_replay import (
DebugReplayManager, DebugReplayManager,
cleanup_replay_cameras, cleanup_replay_cameras,
) )
from frigate.detectors.detector_config import SceneEnum
from frigate.detectors.device import build_detector_config, runner_names
from frigate.embeddings import EmbeddingProcess, EmbeddingsContext from frigate.embeddings import EmbeddingProcess, EmbeddingsContext
from frigate.events.audio import AudioProcessor from frigate.events.audio import AudioProcessor
from frigate.events.cleanup import EventCleanup from frigate.events.cleanup import EventCleanup
@@ -69,6 +71,7 @@ from frigate.models import (
User, User,
) )
from frigate.object_detection.base import ObjectDetectProcess from frigate.object_detection.base import ObjectDetectProcess
from frigate.object_detection.util import detection_frame_size
from frigate.output.output import OutputProcess from frigate.output.output import OutputProcess
from frigate.ptz.autotrack import PtzAutoTrackerThread from frigate.ptz.autotrack import PtzAutoTrackerThread
from frigate.ptz.onvif import OnvifController from frigate.ptz.onvif import OnvifController
@@ -98,7 +101,9 @@ class FrigateApp:
self.metrics_manager = manager self.metrics_manager = manager
self.audio_process: mp.Process | None = None self.audio_process: mp.Process | None = None
self.stop_event = stop_event self.stop_event = stop_event
self.detection_queue: Queue = mp.Queue() self.detection_queues: dict[SceneEnum, Queue] = {
model.scene: mp.Queue() for model in config.models
}
self.detectors: dict[str, ObjectDetectProcess] = {} self.detectors: dict[str, ObjectDetectProcess] = {}
self.detection_shms: list[mp.shared_memory.SharedMemory] = [] self.detection_shms: list[mp.shared_memory.SharedMemory] = []
self.log_queue: Queue = mp.Queue() self.log_queue: Queue = mp.Queue()
@@ -343,20 +348,19 @@ class FrigateApp:
self.dispatcher.profile_manager = self.profile_manager self.dispatcher.profile_manager = self.profile_manager
def start_detectors(self) -> None: def start_detectors(self) -> None:
model_cameras: dict[SceneEnum, list[str]] = {
model.scene: [] for model in self.config.models
}
for name in self.config.cameras.keys(): for name in self.config.cameras.keys():
model = self.config.model_for_camera(name)
model_cameras[model.scene].append(name)
try: try:
largest_frame = max(
[
det.model.height * det.model.width * 3
if det.model is not None
else 320
for det in self.config.detectors.values()
]
)
shm_in = UntrackedSharedMemory( shm_in = UntrackedSharedMemory(
name=name, name=name,
create=True, create=True,
size=largest_frame, size=detection_frame_size(model),
) )
except FileExistsError: except FileExistsError:
shm_in = UntrackedSharedMemory(name=name) shm_in = UntrackedSharedMemory(name=name)
@@ -371,13 +375,24 @@ class FrigateApp:
self.detection_shms.append(shm_in) self.detection_shms.append(shm_in)
self.detection_shms.append(shm_out) self.detection_shms.append(shm_out)
for name, detector_config in self.config.detectors.items(): # a device may be listed more than once to run additional inference
# processes on it, so names are only unique once de-duplicated
all_devices = [
device
for model in self.config.models
for device in self.config.devices_for_model(model)
]
names = iter(runner_names(all_devices))
for model in self.config.models:
for device in self.config.devices_for_model(model):
name = next(names)
self.detectors[name] = ObjectDetectProcess( self.detectors[name] = ObjectDetectProcess(
name, name,
self.detection_queue, self.detection_queues[model.scene],
list(self.config.cameras.keys()), model_cameras[model.scene],
self.config, self.config,
detector_config, build_detector_config(device, model),
self.stop_event, self.stop_event,
) )
@@ -410,7 +425,7 @@ class FrigateApp:
def start_camera_processor(self) -> None: def start_camera_processor(self) -> None:
self.camera_maintainer = CameraMaintainer( self.camera_maintainer = CameraMaintainer(
self.config, self.config,
self.detection_queue, self.detection_queues,
self.detected_frames_queue, self.detected_frames_queue,
self.camera_metrics, self.camera_metrics,
self.ptz_metrics, self.ptz_metrics,
@@ -674,8 +689,10 @@ class FrigateApp:
for detector in self.detectors.values(): for detector in self.detectors.values():
detector.stop() detector.stop()
empty_and_close_queue(self.detection_queue) for detection_queue in self.detection_queues.values():
logger.info("Detection queue closed") empty_and_close_queue(detection_queue)
logger.info("Detection queues closed")
self.detected_frames_processor.join() self.detected_frames_processor.join()
empty_and_close_queue(self.detected_frames_queue) empty_and_close_queue(self.detected_frames_queue)
+2 -1
View File
@@ -18,6 +18,7 @@ from frigate.config.camera.updater import (
CameraConfigUpdateEnum, CameraConfigUpdateEnum,
CameraConfigUpdateSubscriber, CameraConfigUpdateSubscriber,
) )
from frigate.detectors.detector_config import NON_LOGO_ATTRIBUTES
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -178,7 +179,7 @@ class CameraActivityManager:
return return
for label in camera_config.objects.track: for label in camera_config.objects.track:
if label in self.config.model.non_logo_attributes: if label in NON_LOGO_ATTRIBUTES:
continue continue
new_count = all_objects[label] new_count = all_objects[label]
+12 -16
View File
@@ -15,7 +15,9 @@ from frigate.config.camera.updater import (
CameraConfigUpdateSubscriber, CameraConfigUpdateSubscriber,
) )
from frigate.const import REPLAY_CAMERA_PREFIX from frigate.const import REPLAY_CAMERA_PREFIX
from frigate.detectors.detector_config import SceneEnum
from frigate.models import Regions from frigate.models import Regions
from frigate.object_detection.util import detection_frame_size
from frigate.util.builtin import empty_and_close_queue from frigate.util.builtin import empty_and_close_queue
from frigate.util.image import SharedMemoryFrameManager, UntrackedSharedMemory from frigate.util.image import SharedMemoryFrameManager, UntrackedSharedMemory
from frigate.util.object import get_camera_regions_grid from frigate.util.object import get_camera_regions_grid
@@ -29,7 +31,7 @@ class CameraMaintainer(threading.Thread):
def __init__( def __init__(
self, self,
config: FrigateConfig, config: FrigateConfig,
detection_queue: Queue, detection_queues: dict[SceneEnum, Queue],
detected_frames_queue: Queue, detected_frames_queue: Queue,
camera_metrics: DictProxy, camera_metrics: DictProxy,
ptz_metrics: dict[str, PTZMetrics], ptz_metrics: dict[str, PTZMetrics],
@@ -38,7 +40,7 @@ class CameraMaintainer(threading.Thread):
): ):
super().__init__(name="camera_processor") super().__init__(name="camera_processor")
self.config = config self.config = config
self.detection_queue = detection_queue self.detection_queues = detection_queues
self.detected_frames_queue = detected_frames_queue self.detected_frames_queue = detected_frames_queue
self.stop_event = stop_event self.stop_event = stop_event
self.camera_metrics = camera_metrics self.camera_metrics = camera_metrics
@@ -79,10 +81,11 @@ class CameraMaintainer(threading.Thread):
# create or update region grids for each camera # create or update region grids for each camera
for camera in self.config.cameras.values(): for camera in self.config.cameras.values():
assert camera.name is not None assert camera.name is not None
model = self.config.model_for_camera(camera.name)
self.region_grids[camera.name] = get_camera_regions_grid( self.region_grids[camera.name] = get_camera_regions_grid(
camera.name, camera.name,
camera.detect, camera.detect,
max(self.config.model.width, self.config.model.height), max(model.width, model.height),
) )
def __calculate_shm_frame_count(self) -> int: def __calculate_shm_frame_count(self) -> int:
@@ -114,6 +117,7 @@ class CameraMaintainer(threading.Thread):
return return
camera_stop_event = self.__ensure_camera_stop_event(name) camera_stop_event = self.__ensure_camera_stop_event(name)
model = self.config.model_for_camera(name)
if runtime: if runtime:
self.camera_metrics[name] = CameraMetrics(self.metrics_manager) self.camera_metrics[name] = CameraMetrics(self.metrics_manager)
@@ -123,32 +127,24 @@ class CameraMaintainer(threading.Thread):
self.region_grids[name] = get_camera_regions_grid( self.region_grids[name] = get_camera_regions_grid(
name, name,
config.detect, config.detect,
max(self.config.model.width, self.config.model.height), max(model.width, model.height),
) )
try: try:
largest_frame = max(
[
det.model.height * det.model.width * 3
if det.model is not None
else 320
for det in self.config.detectors.values()
]
)
UntrackedSharedMemory(name=f"out-{name}", create=True, size=20 * 6 * 4) UntrackedSharedMemory(name=f"out-{name}", create=True, size=20 * 6 * 4)
UntrackedSharedMemory( UntrackedSharedMemory(
name=name, name=name,
create=True, create=True,
size=largest_frame, size=detection_frame_size(model),
) )
except FileExistsError: except FileExistsError:
pass pass
camera_process = CameraTracker( camera_process = CameraTracker(
config, config,
self.config.model, model,
self.config.model.merged_labelmap, model.merged_labelmap,
self.detection_queue, self.detection_queues[model.scene],
self.detected_frames_queue, self.detected_frames_queue,
self.camera_metrics[name], self.camera_metrics[name],
self.ptz_metrics[name], self.ptz_metrics[name],
+6 -11
View File
@@ -40,6 +40,7 @@ class CameraState:
self.name = name self.name = name
self.config = config self.config = config
self.camera_config = config.cameras[name] self.camera_config = config.cameras[name]
self.model = config.model_for_camera(name)
self.frame_manager = frame_manager self.frame_manager = frame_manager
self.best_objects: dict[str, TrackedObject] = {} self.best_objects: dict[str, TrackedObject] = {}
self.tracked_objects: dict[str, TrackedObject] = {} self.tracked_objects: dict[str, TrackedObject] = {}
@@ -101,9 +102,7 @@ class CameraState:
thickness = 1 thickness = 1
else: else:
thickness = 2 thickness = 2
color = self.config.model.colormap.get( color = self.model.colormap.get(obj["label"], (255, 255, 255))
obj["label"], (255, 255, 255)
)
else: else:
thickness = 1 thickness = 1
color = (255, 0, 0) color = (255, 0, 0)
@@ -125,9 +124,7 @@ class CameraState:
and obj["frame_time"] == frame_time and obj["frame_time"] == frame_time
): ):
thickness = 5 thickness = 5
color = self.config.model.colormap.get( color = self.model.colormap.get(obj["label"], (255, 255, 255))
obj["label"], (255, 255, 255)
)
# debug autotracking zooming - show the zoom factor box # debug autotracking zooming - show the zoom factor box
if ( if (
@@ -261,9 +258,7 @@ class CameraState:
if draw_options.get("paths"): if draw_options.get("paths"):
for obj in tracked_objects.values(): for obj in tracked_objects.values():
if obj["frame_time"] == frame_time and obj["path_data"]: if obj["frame_time"] == frame_time and obj["path_data"]:
color = self.config.model.colormap.get( color = self.model.colormap.get(obj["label"], (255, 255, 255))
obj["label"], (255, 255, 255)
)
path_points = [ path_points = [
( (
@@ -366,7 +361,7 @@ class CameraState:
for id in new_ids: for id in new_ids:
logger.debug(f"{self.name}: New tracked object ID: {id}") logger.debug(f"{self.name}: New tracked object ID: {id}")
new_obj = tracked_objects[id] = TrackedObject( new_obj = tracked_objects[id] = TrackedObject(
self.config.model, self.model,
self.camera_config, self.camera_config,
self.config.ui, self.config.ui,
self.frame_cache, self.frame_cache,
@@ -510,7 +505,7 @@ class CameraState:
sub_label = None sub_label = None
if obj.obj_data.get("sub_label"): if obj.obj_data.get("sub_label"):
if obj.obj_data["sub_label"][0] in self.config.model.all_attributes: if obj.obj_data["sub_label"][0] in self.model.all_attributes:
label = obj.obj_data["sub_label"][0] label = obj.obj_data["sub_label"][0]
else: else:
label = f"{object_type}-verified" label = f"{object_type}-verified"
+10 -6
View File
@@ -11,7 +11,7 @@ from frigate.camera.activity_manager import AudioActivityManager, CameraActivity
from frigate.comms.base_communicator import Communicator from frigate.comms.base_communicator import Communicator
from frigate.comms.runtime_state import RuntimeStatePersistence from frigate.comms.runtime_state import RuntimeStatePersistence
from frigate.comms.webpush import WebPushClient from frigate.comms.webpush import WebPushClient
from frigate.config import BirdseyeModeEnum, FrigateConfig from frigate.config import BirdseyeModeConfig, FrigateConfig
from frigate.config.camera.updater import ( from frigate.config.camera.updater import (
CameraConfigUpdateEnum, CameraConfigUpdateEnum,
CameraConfigUpdatePublisher, CameraConfigUpdatePublisher,
@@ -156,10 +156,11 @@ class Dispatcher:
if camera not in self.config.cameras: if camera not in self.config.cameras:
return None return None
model = self.config.model_for_camera(camera)
grid = get_camera_regions_grid( grid = get_camera_regions_grid(
camera, camera,
self.config.cameras[camera].detect, self.config.cameras[camera].detect,
max(self.config.model.width, self.config.model.height), max(model.width, model.height),
) )
return grid return grid
@@ -882,8 +883,9 @@ class Dispatcher:
def _on_birdseye_mode_command(self, camera_name: str, payload: str) -> None: def _on_birdseye_mode_command(self, camera_name: str, payload: str) -> None:
"""Callback for birdseye mode topic.""" """Callback for birdseye mode topic."""
if payload not in ["CONTINUOUS", "MOTION", "OBJECTS"]: mode = BirdseyeModeConfig.from_mqtt_payload(payload)
logger.info(f"Invalid birdseye_mode command: {payload}") if mode is None:
logger.info("Invalid birdseye_mode command: %s", payload)
return return
birdseye_settings = self.config.cameras[camera_name].birdseye birdseye_settings = self.config.cameras[camera_name].birdseye
@@ -892,7 +894,7 @@ class Dispatcher:
logger.info(f"Birdseye mode not enabled for {camera_name}") logger.info(f"Birdseye mode not enabled for {camera_name}")
return return
birdseye_settings.mode = BirdseyeModeEnum(payload.lower()) birdseye_settings.mode = mode
logger.info( logger.info(
f"Setting birdseye mode for {camera_name} to {birdseye_settings.mode}" f"Setting birdseye mode for {camera_name} to {birdseye_settings.mode}"
) )
@@ -901,7 +903,9 @@ class Dispatcher:
CameraConfigUpdateTopic(CameraConfigUpdateEnum.birdseye, camera_name), CameraConfigUpdateTopic(CameraConfigUpdateEnum.birdseye, camera_name),
birdseye_settings, birdseye_settings,
) )
self.publish(f"{camera_name}/birdseye_mode/state", payload, retain=True) self.publish(
f"{camera_name}/birdseye_mode/state", mode.to_mqtt_payload(), retain=True
)
def _on_camera_notification_command(self, camera_name: str, payload: str) -> None: def _on_camera_notification_command(self, camera_name: str, payload: str) -> None:
"""Callback for camera level notifications topic.""" """Callback for camera level notifications topic."""
+1 -1
View File
@@ -125,7 +125,7 @@ class MqttClient(Communicator):
self.publish( self.publish(
f"{camera_name}/birdseye_mode/state", f"{camera_name}/birdseye_mode/state",
( (
camera.birdseye.mode.value.upper() camera.birdseye.mode.to_mqtt_payload()
if camera.birdseye.enabled if camera.birdseye.enabled
else "OFF" else "OFF"
), ),
+74 -20
View File
@@ -1,5 +1,3 @@
from enum import Enum
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from ..base import FrigateBaseModel from ..base import FrigateBaseModel
@@ -8,22 +6,78 @@ __all__ = [
"BirdseyeCameraConfig", "BirdseyeCameraConfig",
"BirdseyeConfig", "BirdseyeConfig",
"BirdseyeLayoutConfig", "BirdseyeLayoutConfig",
"BirdseyeModeEnum", "BirdseyeModeConfig",
] ]
BIRDSEYE_ACTIVITY_TYPES = (
"objects",
"motion",
"stationary_objects",
"continuous",
)
class BirdseyeModeEnum(str, Enum):
objects = "objects" class BirdseyeModeConfig(FrigateBaseModel):
motion = "motion" continuous: bool = Field(
continuous = "continuous" default=False,
title="Continuous",
description="Always include the camera in Birdseye.",
)
motion: bool = Field(
default=False,
title="Motion",
description="Include the camera in Birdseye when motion is detected.",
)
objects: bool = Field(
default=False,
title="Active objects",
description="Include the camera in Birdseye while an active object is tracked.",
)
stationary_objects: bool = Field(
default=False,
title="Stationary objects",
description="Include the camera in Birdseye while a stationary object is tracked.",
)
@classmethod @classmethod
def get_index(cls, type): def from_mqtt_payload(cls, payload: str) -> "BirdseyeModeConfig | None":
return list(cls).index(type) """Create mode options from an uppercase MQTT payload."""
raw_modes = payload.split(",")
if not raw_modes or any(not mode for mode in raw_modes):
return None
@classmethod modes = [mode.lower() for mode in raw_modes]
def get(cls, index): if any(
return list(cls)[index] raw_mode != mode.upper() or mode not in BIRDSEYE_ACTIVITY_TYPES
for raw_mode, mode in zip(raw_modes, modes)
):
return None
if len(modes) != len(set(modes)):
return None
return cls(**{mode: True for mode in modes})
def has_enabled_activity(self) -> bool:
"""Return whether at least one activity type is enabled."""
return any(getattr(self, activity) for activity in BIRDSEYE_ACTIVITY_TYPES)
def to_mqtt_payload(self) -> str:
"""Serialize enabled mode options for MQTT state topics."""
payload = ",".join(
activity.upper()
for activity in BIRDSEYE_ACTIVITY_TYPES
if getattr(self, activity)
)
if not payload:
raise ValueError("At least one Birdseye activity type must be enabled")
return payload
def default_birdseye_mode() -> BirdseyeModeConfig:
"""Return the default Birdseye mode configuration."""
return BirdseyeModeConfig(objects=True)
class BirdseyeLayoutConfig(FrigateBaseModel): class BirdseyeLayoutConfig(FrigateBaseModel):
@@ -47,10 +101,10 @@ class BirdseyeConfig(FrigateBaseModel):
title="Enable Birdseye", title="Enable Birdseye",
description="Enable or disable the Birdseye view feature.", description="Enable or disable the Birdseye view feature.",
) )
mode: BirdseyeModeEnum = Field( mode: BirdseyeModeConfig = Field(
default=BirdseyeModeEnum.objects, default_factory=default_birdseye_mode,
title="Tracking mode", title="Activity types",
description="Mode for including cameras in Birdseye: 'objects', 'motion', or 'continuous'.", description="Activity types that include cameras in Birdseye.",
) )
restream: bool = Field( restream: bool = Field(
@@ -102,10 +156,10 @@ class BirdseyeCameraConfig(BaseModel):
title="Enable Birdseye", title="Enable Birdseye",
description="Enable or disable the Birdseye view feature.", description="Enable or disable the Birdseye view feature.",
) )
mode: BirdseyeModeEnum = Field( mode: BirdseyeModeConfig = Field(
default=BirdseyeModeEnum.objects, default_factory=default_birdseye_mode,
title="Tracking mode", title="Activity types",
description="Mode for including cameras in Birdseye: 'objects', 'motion', or 'continuous'.", description="Activity types that include cameras in Birdseye.",
) )
order: int = Field( order: int = Field(
+7
View File
@@ -1,5 +1,7 @@
from pydantic import Field, model_validator from pydantic import Field, model_validator
from frigate.detectors.detector_config import SceneEnum
from ..base import FrigateBaseModel from ..base import FrigateBaseModel
__all__ = ["DetectConfig", "StationaryConfig", "StationaryMaxFramesConfig"] __all__ = ["DetectConfig", "StationaryConfig", "StationaryMaxFramesConfig"]
@@ -60,6 +62,11 @@ class DetectConfig(FrigateBaseModel):
title="Detect width", title="Detect width",
description="Width (pixels) of frames used for the detect stream; leave empty to use the native stream resolution.", description="Width (pixels) of frames used for the detect stream; leave empty to use the native stream resolution.",
) )
scene: SceneEnum | None = Field(
default=None,
title="Detect scene",
description="The environment this camera looks at, used to pick which of the configured models runs on it. Defaults to the model with a scene of 'all'.",
)
fps: int = Field( fps: int = Field(
default=5, default=5,
title="Detect FPS", title="Detect FPS",
+244 -61
View File
@@ -11,7 +11,6 @@ from pydantic import (
BaseModel, BaseModel,
ConfigDict, ConfigDict,
Field, Field,
TypeAdapter,
ValidationInfo, ValidationInfo,
field_validator, field_validator,
model_validator, model_validator,
@@ -19,8 +18,9 @@ from pydantic import (
from ruamel.yaml import YAML from ruamel.yaml import YAML
from frigate.const import REGEX_JSON from frigate.const import REGEX_JSON
from frigate.detectors import DetectorConfig, ModelConfig from frigate.detectors import ModelConfig
from frigate.detectors.detector_config import BaseDetectorConfig from frigate.detectors.detector_config import SceneEnum
from frigate.detectors.device import DeviceParseError, DeviceSpec, parse_device
from frigate.plus import PlusApi from frigate.plus import PlusApi
from frigate.util.builtin import ( from frigate.util.builtin import (
deep_merge, deep_merge,
@@ -41,7 +41,7 @@ from .auth import AuthConfig
from .base import FrigateBaseModel from .base import FrigateBaseModel
from .camera import CameraConfig, CameraLiveConfig from .camera import CameraConfig, CameraLiveConfig
from .camera.audio import AudioConfig, AudioFilterConfig from .camera.audio import AudioConfig, AudioFilterConfig
from .camera.birdseye import BirdseyeConfig from .camera.birdseye import BirdseyeConfig, BirdseyeModeConfig
from .camera.detect import DetectConfig from .camera.detect import DetectConfig
from .camera.ffmpeg import FfmpegConfig from .camera.ffmpeg import FfmpegConfig
from .camera.genai import GenAIConfig, GenAIRoleEnum from .camera.genai import GenAIConfig, GenAIRoleEnum
@@ -79,9 +79,14 @@ logger = logging.getLogger(__name__)
yaml = YAML() yaml = YAML()
# Pydantic field default applied when an existing config omits `detectors:`. # Pydantic field default applied when an existing config omits `models:`.
# Kept as cpu tflite for backwards compatibility with 0.17 configs. # Kept as cpu tflite for backwards compatibility with 0.17 configs.
DEFAULT_DETECTORS = {"cpu": {"type": "cpu"}} DEFAULT_MODELS = [{"devices": ["cpu"]}]
def _default_models() -> list[ModelConfig]:
return [ModelConfig.model_validate(model) for model in DEFAULT_MODELS]
# Used by the openvino branch below and rendered into the new-config YAML # Used by the openvino branch below and rendered into the new-config YAML
# template so first-time setups default to openvino on CPU. # template so first-time setups default to openvino on CPU.
@@ -93,7 +98,7 @@ DEFAULT_MODEL = {
"path": "/openvino-model/ssdlite_mobilenet_v2.xml", "path": "/openvino-model/ssdlite_mobilenet_v2.xml",
"labelmap_path": "/openvino-model/coco_91cl_bkgr.txt", "labelmap_path": "/openvino-model/coco_91cl_bkgr.txt",
} }
NEW_CONFIG_DETECTORS = {"ov": {"type": "openvino", "device": "CPU"}} NEW_CONFIG_MODELS = [{"devices": ["openvino:CPU"], **DEFAULT_MODEL}]
DEFAULT_DETECT_DIMENSIONS = {"width": 1280, "height": 720} DEFAULT_DETECT_DIMENSIONS = {"width": 1280, "height": 720}
@@ -109,7 +114,7 @@ DEFAULT_CONFIG = f"""
mqtt: mqtt:
enabled: False enabled: False
{_render_default_yaml({"detectors": NEW_CONFIG_DETECTORS, "model": DEFAULT_MODEL})} {_render_default_yaml({"models": NEW_CONFIG_MODELS})}
cameras: {{}} # No cameras defined, UI wizard should be used cameras: {{}} # No cameras defined, UI wizard should be used
version: {CURRENT_CONFIG_VERSION} version: {CURRENT_CONFIG_VERSION}
""" """
@@ -326,8 +331,20 @@ def verify_required_zones_exist(camera_config: CameraConfig) -> None:
def verify_profile_overrides_match_base(camera_config: CameraConfig) -> None: def verify_profile_overrides_match_base(camera_config: CameraConfig) -> None:
"""Verify that profile zone and mask IDs reference entries defined on the base camera.""" """Verify profile overrides against the resolved base camera configuration."""
for profile_name, profile in camera_config.profiles.items(): for profile_name, profile in camera_config.profiles.items():
if profile.birdseye is not None:
overrides = profile.birdseye.mode.model_dump(exclude_unset=True)
base_mode = camera_config.birdseye.mode.model_dump()
resolved_mode = BirdseyeModeConfig.model_validate(
deep_merge(overrides, base_mode)
)
if not resolved_mode.has_enabled_activity():
raise ValueError(
f"Camera '{camera_config.name}' profile '{profile_name}' must "
"enable at least one Birdseye activity type"
)
if profile.zones: if profile.zones:
for zone_name in profile.zones: for zone_name in profile.zones:
if zone_name not in camera_config.zones: if zone_name not in camera_config.zones:
@@ -497,16 +514,11 @@ class FrigateConfig(FrigateBaseModel):
description="User interface preferences such as timezone, time/date formatting, and units.", description="User interface preferences such as timezone, time/date formatting, and units.",
) )
# Detector config # Detection model config
detectors: dict[str, BaseDetectorConfig] = Field( models: list[ModelConfig] = Field(
default=DEFAULT_DETECTORS, default_factory=_default_models,
title="Detector hardware", title="Detection models",
description="Configuration for object detectors (CPU, GPU, ONNX backends) and any detector-specific model settings.", description="Object detection models and the hardware each one runs on. Cameras pick a model by matching their detect.scene against a model's scene.",
)
model: ModelConfig = Field(
default_factory=ModelConfig,
title="Detection model",
description="Settings to configure a custom object detection model and its input shape.",
) )
# GenAI config (named provider configs: name -> GenAIConfig) # GenAI config (named provider configs: name -> GenAIConfig)
@@ -621,11 +633,202 @@ class FrigateConfig(FrigateBaseModel):
) )
_plus_api: PlusApi _plus_api: PlusApi
_model_devices: dict[SceneEnum, list[DeviceSpec]]
_camera_models: dict[str, ModelConfig]
_all_attributes: list[str]
_all_attribute_logos: list[str]
_all_attributes_map: dict[str, list[str]]
_all_labels: set[str]
@property @property
def plus_api(self) -> PlusApi: def plus_api(self) -> PlusApi:
return self._plus_api return self._plus_api
@property
def all_attributes(self) -> list[str]:
"""Every attribute label across all configured models."""
return self._all_attributes
@property
def all_attribute_logos(self) -> list[str]:
"""Every logo attribute label across all configured models."""
return self._all_attribute_logos
@property
def all_attributes_map(self) -> dict[str, list[str]]:
"""Object label to attribute labels, merged across all configured models."""
return self._all_attributes_map
@property
def all_labels(self) -> set[str]:
"""Every object label across all configured models."""
return self._all_labels
@property
def primary_model(self) -> ModelConfig:
"""The model used when no specific camera is in play."""
for model in self.models:
if model.scene == SceneEnum.all:
return model
return self.models[0]
def model_for_camera(self, camera_name: str) -> ModelConfig:
"""Get the detection model a camera runs on.
Args:
camera_name: Name of the camera
Returns:
The model matching the camera's detect scene
"""
return self._camera_models[camera_name]
def devices_for_model(self, model: ModelConfig) -> list[DeviceSpec]:
"""Get the parsed hardware devices a model runs on.
Args:
model: One of the configured models
Returns:
The parsed device specs, in config order
"""
return self._model_devices[model.scene]
def _load_model(self, model: ModelConfig, detector: str) -> ModelConfig:
"""Apply detector specific defaults to a model and load its weights and labels.
Args:
model: The configured model
detector: The detector type the model runs on
Returns:
The loaded model
"""
model_config = model.model_dump(exclude_unset=True, warnings="none")
if "path" not in model_config:
if detector == "cpu" or detector.endswith("_tfl"):
model_config["path"] = "/cpu_model.tflite"
elif detector == "edgetpu":
model_config["path"] = "/edgetpu_model.tflite"
elif detector == "openvino":
for default_key, default_value in DEFAULT_MODEL.items():
model_config.setdefault(default_key, default_value)
loaded = ModelConfig.model_validate(model_config)
loaded.check_and_load_plus_model(self.plus_api, detector)
loaded.compute_model_hash()
return loaded
def _load_models(self) -> None:
"""Validate the configured models and load each one."""
if not self.models:
raise ValueError("At least one model must be configured under models")
model_devices: dict[SceneEnum, list[DeviceSpec]] = {}
# device string -> the scene of the model that already claimed it
claimed_devices: dict[str, SceneEnum] = {}
for index, model in enumerate(self.models):
scene = model.scene.value
if model.scene in model_devices:
raise ValueError(
f"Multiple models are configured with a scene of '{scene}'. Each model must use a different scene."
)
if not model.devices:
raise ValueError(
f"Model '{scene}' must list at least one entry under devices."
)
try:
devices = [parse_device(device) for device in model.devices]
except DeviceParseError as err:
raise ValueError(
f"Model '{scene}' has an invalid device: {err}"
) from err
detectors = {device.detector for device in devices}
if len(detectors) > 1:
raise ValueError(
f"Model '{scene}' mixes the {', '.join(sorted(detectors))} detectors. All of a model's devices must use the same detector."
)
for device in devices:
if device.raw in claimed_devices and not device.shareable:
other = claimed_devices[device.raw]
where = (
f"twice by model '{scene}'"
if other == model.scene
else f"by both the '{other.value}' and '{scene}' models"
)
raise ValueError(
f"Device '{device.raw}' is used {where}, but it can only run one detection process."
)
claimed_devices[device.raw] = model.scene
self.models[index] = self._load_model(model, devices[0].detector)
model_devices[model.scene] = devices
attributes: set[str] = set()
attribute_logos: set[str] = set()
attributes_map: dict[str, set[str]] = {}
labels: set[str] = set()
for model in self.models:
attributes.update(model.all_attributes)
attribute_logos.update(model.all_attribute_logos)
labels.update(model.merged_labelmap.values())
for label, label_attributes in model.attributes_map.items():
attributes_map.setdefault(label, set()).update(label_attributes)
self._model_devices = model_devices
self._all_attributes = sorted(attributes)
self._all_attribute_logos = sorted(attribute_logos)
self._all_attributes_map = {
label: sorted(label_attributes)
for label, label_attributes in sorted(attributes_map.items())
}
self._all_labels = labels
def _resolve_camera_model(self, name: str, scene: SceneEnum | None) -> ModelConfig:
"""Resolve which model a camera runs on.
Args:
name: Name of the camera
scene: The camera's configured detect scene, if any
Returns:
The model the camera runs on
"""
by_scene = {model.scene: model for model in self.models}
if scene is not None:
model = by_scene.get(scene)
if model is None:
raise ValueError(
f"Camera '{name}' has a detect scene of '{scene.value}', but no model is configured for that scene."
)
return model
default = by_scene.get(SceneEnum.all) or (
self.models[0] if len(self.models) == 1 else None
)
if default is None:
raise ValueError(
f"Camera '{name}' must set detect -> scene, because more than one model is configured and none of them uses a scene of 'all'."
)
return default
@model_validator(mode="after") @model_validator(mode="after")
def post_validation(self, info: ValidationInfo) -> Self: def post_validation(self, info: ValidationInfo) -> Self:
# Load plus api from context, if possible. # Load plus api from context, if possible.
@@ -670,8 +873,10 @@ class FrigateConfig(FrigateBaseModel):
"'embeddings' in its roles for semantic search." "'embeddings' in its roles for semantic search."
) )
self._load_models()
# set default min_score for object attributes # set default min_score for object attributes
for attribute in self.model.all_attributes: for attribute in self.all_attributes:
existing = self.objects.filters.get(attribute) existing = self.objects.filters.get(attribute)
if existing is None: if existing is None:
self.objects.filters[attribute] = FilterConfig(min_score=0.7) self.objects.filters[attribute] = FilterConfig(min_score=0.7)
@@ -721,44 +926,7 @@ class FrigateConfig(FrigateBaseModel):
exclude_unset=True, exclude_unset=True,
) )
for key, detector in self.detectors.items(): self._camera_models = {}
adapter = TypeAdapter(DetectorConfig)
model_dict = (
detector
if isinstance(detector, dict)
else detector.model_dump(warnings="none")
)
detector_config: BaseDetectorConfig = adapter.validate_python(model_dict)
# users should not set model themselves
if detector_config.model:
logger.warning(
"The model key should be specified at the root level of the config, not under detectors. The nested model key will be ignored."
)
detector_config.model = None
model_config = self.model.model_dump(exclude_unset=True, warnings="none")
if detector_config.model_path:
model_config["path"] = detector_config.model_path
if "path" not in model_config:
if detector_config.type == "cpu" or detector_config.type.endswith(
"_tfl"
):
model_config["path"] = "/cpu_model.tflite"
elif detector_config.type == "edgetpu":
model_config["path"] = "/edgetpu_model.tflite"
elif detector_config.type == "openvino":
for default_key, default_value in DEFAULT_MODEL.items():
model_config.setdefault(default_key, default_value)
model = ModelConfig.model_validate(model_config)
model.check_and_load_plus_model(self.plus_api, detector_config.type)
model.compute_model_hash()
labelmap_objects = model.merged_labelmap.values()
detector_config.model = model
self.detectors[key] = detector_config
for name, camera in self.cameras.items(): for name, camera in self.cameras.items():
modified_global_config = global_config.copy() modified_global_config = global_config.copy()
@@ -785,6 +953,9 @@ class FrigateConfig(FrigateBaseModel):
{"name": name, **merged_config} {"name": name, **merged_config}
) )
camera_model = self._resolve_camera_model(name, camera_config.detect.scene)
self._camera_models[name] = camera_model
if camera_config.ffmpeg.hwaccel_args == "auto": if camera_config.ffmpeg.hwaccel_args == "auto":
camera_config.ffmpeg.hwaccel_args = self.ffmpeg.hwaccel_args camera_config.ffmpeg.hwaccel_args = self.ffmpeg.hwaccel_args
@@ -998,6 +1169,10 @@ class FrigateConfig(FrigateBaseModel):
self.cameras[name] = camera_config self.cameras[name] = camera_config
verify_config_roles(camera_config) verify_config_roles(camera_config)
if not camera_config.birdseye.mode.has_enabled_activity():
raise ValueError(
f"Camera '{name}' must enable at least one Birdseye activity type"
)
verify_valid_live_stream_names(self, camera_config) verify_valid_live_stream_names(self, camera_config)
verify_recording_segments_setup_with_reasonable_time(camera_config) verify_recording_segments_setup_with_reasonable_time(camera_config)
verify_zone_objects_are_tracked(camera_config) verify_zone_objects_are_tracked(camera_config)
@@ -1005,7 +1180,7 @@ class FrigateConfig(FrigateBaseModel):
verify_profile_overrides_match_base(camera_config) verify_profile_overrides_match_base(camera_config)
verify_autotrack_zones(camera_config) verify_autotrack_zones(camera_config)
verify_motion_and_detect(camera_config) verify_motion_and_detect(camera_config)
verify_objects_track(camera_config, labelmap_objects) verify_objects_track(camera_config, camera_model.merged_labelmap.values())
verify_lpr_and_face(self, camera_config) verify_lpr_and_face(self, camera_config)
# Validate camera profiles reference top-level profile definitions # Validate camera profiles reference top-level profile definitions
@@ -1022,8 +1197,16 @@ class FrigateConfig(FrigateBaseModel):
config.name = name config.name = name
self.objects.parse_all_objects(self.cameras) self.objects.parse_all_objects(self.cameras)
self.model.create_colormap(sorted(self.objects.all_objects))
self.model.check_and_load_plus_model(self.plus_api) # every model shares one colormap so a label is drawn the same color no
# matter which model detected it, so filter attributes across all models
# rather than letting each model filter with only its own
colored_labels = sorted(
set(self.objects.all_objects) - set(self.all_attributes)
)
for model in self.models:
model.create_colormap(colored_labels)
# Check audio transcription and audio detection requirements # Check audio transcription and audio detection requirements
if self.audio_transcription.enabled: if self.audio_transcription.enabled:
+3 -1
View File
@@ -43,7 +43,9 @@ SECTION_STATE_TOPICS: dict[str, list[tuple[str, Callable[[Any], Any]]]] = {
("birdseye", lambda c: "ON" if c.birdseye.enabled else "OFF"), ("birdseye", lambda c: "ON" if c.birdseye.enabled else "OFF"),
( (
"birdseye_mode", "birdseye_mode",
lambda c: c.birdseye.mode.value.upper() if c.birdseye.enabled else "OFF", lambda c: (
c.birdseye.mode.to_mqtt_payload() if c.birdseye.enabled else "OFF"
),
), ),
], ],
"detect": [("detect", lambda c: "ON" if c.detect.enabled else "OFF")], "detect": [("detect", lambda c: "ON" if c.detect.enabled else "OFF")],
@@ -72,7 +72,7 @@ class LicensePlateProcessingMixin:
# Object config # Object config
self.lp_objects: list[str] = [] self.lp_objects: list[str] = []
for obj, attributes in self.config.model.attributes_map.items(): for obj, attributes in self.config.all_attributes_map.items():
if "license_plate" in attributes: if "license_plate" in attributes:
self.lp_objects.append(obj) self.lp_objects.append(obj)
@@ -231,8 +231,8 @@ class ReviewDescriptionProcessor(PostProcessorApi):
final_data, final_data,
thumbs, thumbs,
camera_config.review.genai, camera_config.review.genai,
list(self.config.model.merged_labelmap.values()), sorted(self.config.all_labels),
self.config.model.all_attributes, self.config.all_attributes,
), ),
).start() ).start()
+34 -5
View File
@@ -3,7 +3,7 @@ import json
import logging import logging
import os import os
from enum import Enum from enum import Enum
from typing import Any from typing import Any, ClassVar
import requests import requests
from pydantic import BaseModel, ConfigDict, Field from pydantic import BaseModel, ConfigDict, Field
@@ -15,6 +15,9 @@ from frigate.util.builtin import generate_color_palette, load_labels
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# attributes that are recognized rather than shown as a logo
NON_LOGO_ATTRIBUTES = ["face", "license_plate"]
class PixelFormatEnum(str, Enum): class PixelFormatEnum(str, Enum):
rgb = "rgb" rgb = "rgb"
@@ -44,7 +47,27 @@ class ModelTypeEnum(str, Enum):
yologeneric = "yolo-generic" yologeneric = "yolo-generic"
class SceneEnum(str, Enum):
"""The camera environment a detection model is intended for."""
all = "all"
indoor = "indoor"
outdoor = "outdoor"
indoor_thermal = "indoor_thermal"
outdoor_thermal = "outdoor_thermal"
class ModelConfig(BaseModel): class ModelConfig(BaseModel):
scene: SceneEnum = Field(
default=SceneEnum.all,
title="Model scene",
description="The camera environment this model is used for. Cameras select a model by setting detect.scene to a matching value, and 'all' is used by any camera that does not set one.",
)
devices: list[str] = Field(
default_factory=list,
title="Detection hardware",
description="Hardware this model runs on, as '<detector>' or '<detector>:<device>' (for example 'edgetpu:pci:0' or 'openvino:GPU'). Listing the same device more than once runs additional inference processes on it.",
)
path: str | None = Field( path: str | None = Field(
None, None,
title="Custom object detector model path", title="Custom object detector model path",
@@ -111,7 +134,7 @@ class ModelConfig(BaseModel):
@property @property
def non_logo_attributes(self) -> list[str]: def non_logo_attributes(self) -> list[str]:
return ["face", "license_plate"] return NON_LOGO_ATTRIBUTES
@property @property
def all_attributes(self) -> list[str]: def all_attributes(self) -> list[str]:
@@ -201,9 +224,7 @@ class ModelConfig(BaseModel):
unique_attributes.update(attributes) unique_attributes.update(attributes)
self._all_attributes = list(unique_attributes) self._all_attributes = list(unique_attributes)
self._all_attribute_logos = list( self._all_attribute_logos = list(unique_attributes - set(NON_LOGO_ATTRIBUTES))
unique_attributes - set(["face", "license_plate"])
)
self._merged_labelmap = { self._merged_labelmap = {
**{int(key): val for key, val in model_info["labelMap"].items()}, **{int(key): val for key, val in model_info["labelMap"].items()},
@@ -234,6 +255,14 @@ class ModelConfig(BaseModel):
class BaseDetectorConfig(BaseModel): class BaseDetectorConfig(BaseModel):
# how the trailing part of a device string ("openvino:GPU" -> "GPU") maps onto
# this detector's fields, and whether the same device may be listed more than
# once to run additional inference processes against it. Most accelerators
# multiplex fine, so this is opt-out rather than opt-in.
device_spec_field: ClassVar[str] = "device"
device_spec_type: ClassVar[type] = str
shareable: ClassVar[bool] = True
# the type field must be defined in all subclasses # the type field must be defined in all subclasses
type: str = Field( type: str = Field(
default="cpu", default="cpu",
+19 -1
View File
@@ -2,7 +2,7 @@ import importlib
import logging import logging
import pkgutil import pkgutil
from enum import Enum from enum import Enum
from typing import Annotated, Union from typing import Annotated, Union, get_args
from pydantic import Field from pydantic import Field
@@ -39,3 +39,21 @@ DetectorConfig = Annotated[
Union[tuple(BaseDetectorConfig.__subclasses__())], # noqa: UP007 Union[tuple(BaseDetectorConfig.__subclasses__())], # noqa: UP007
Field(discriminator="type"), Field(discriminator="type"),
] ]
def _discriminator_value(config_class: type[BaseDetectorConfig]) -> str | None:
"""Read the Literal value of a detector config class' type field."""
field = config_class.model_fields.get("type")
if field is None:
return None
values = get_args(field.annotation)
return values[0] if values else None
config_types: dict[str, type[BaseDetectorConfig]] = {
key: config_class
for config_class in BaseDetectorConfig.__subclasses__()
if (key := _discriminator_value(config_class)) is not None
}
+113
View File
@@ -0,0 +1,113 @@
"""Parsing of detection hardware device strings."""
import logging
from dataclasses import dataclass
from pydantic import TypeAdapter, ValidationError
from frigate.detectors.detector_config import BaseDetectorConfig, ModelConfig
from frigate.detectors.detector_types import DetectorConfig, config_types
logger = logging.getLogger(__name__)
_detector_adapter: TypeAdapter[BaseDetectorConfig] = TypeAdapter(DetectorConfig)
@dataclass(frozen=True)
class DeviceSpec:
"""A parsed `<detector>` or `<detector>:<device>` string."""
raw: str
detector: str
device: str | None
@property
def shareable(self) -> bool:
"""Whether this device may be listed more than once."""
return config_types[self.detector].shareable
class DeviceParseError(ValueError):
pass
def parse_device(raw: str) -> DeviceSpec:
"""Parse a device string into its detector type and detector specific device.
Args:
raw: The configured device string, for example 'edgetpu:pci:0'
Returns:
The parsed spec
Raises:
DeviceParseError: If the detector type is unknown or the device is not
valid for that detector
"""
detector, separator, device = raw.partition(":")
if detector not in config_types:
raise DeviceParseError(
f"'{raw}' does not name a known detector. Available detectors are {', '.join(sorted(config_types))}"
)
spec = DeviceSpec(raw=raw, detector=detector, device=device if separator else None)
# surface a bad device now rather than when the detection process starts
build_detector_config(spec, None)
return spec
def build_detector_config(
spec: DeviceSpec, model: ModelConfig | None
) -> BaseDetectorConfig:
"""Build the detector config a device string describes.
Args:
spec: The parsed device spec
model: The model this detector runs, if it has been resolved yet
Returns:
The validated detector config
Raises:
DeviceParseError: If the device is not valid for this detector type
"""
config: dict[str, object] = {"type": spec.detector, "model": model}
if spec.device is not None:
config_class = config_types[spec.detector]
try:
config[config_class.device_spec_field] = config_class.device_spec_type(
spec.device
)
except ValueError as err:
raise DeviceParseError(
f"'{spec.raw}' is not a valid {spec.detector} device: {err}"
) from err
try:
return _detector_adapter.validate_python(config)
except ValidationError as err:
raise DeviceParseError(f"'{spec.raw}' is not a valid device: {err}") from err
def runner_names(devices: list[DeviceSpec]) -> list[str]:
"""Build a unique name for each device, since a shareable device may repeat.
Args:
devices: Every device spec across every configured model, in config order
Returns:
A name per device, suffixed with '#2', '#3', etc. on repeats
"""
names: list[str] = []
seen: dict[str, int] = {}
for spec in devices:
count = seen.get(spec.raw, 0) + 1
seen[spec.raw] = count
names.append(spec.raw if count == 1 else f"{spec.raw}#{count}")
return names
+4 -1
View File
@@ -1,5 +1,5 @@
import logging import logging
from typing import Literal from typing import ClassVar, Literal
from pydantic import ConfigDict, Field from pydantic import ConfigDict, Field
@@ -27,6 +27,9 @@ class CpuDetectorConfig(BaseDetectorConfig):
title="CPU", title="CPU",
) )
device_spec_field: ClassVar[str] = "num_threads"
device_spec_type: ClassVar[type] = int
type: Literal[DETECTOR_KEY] type: Literal[DETECTOR_KEY]
num_threads: int = Field( num_threads: int = Field(
default=3, default=3,
+4 -1
View File
@@ -1,7 +1,7 @@
import logging import logging
import math import math
import os import os
from typing import Literal from typing import ClassVar, Literal
import cv2 import cv2
import numpy as np import numpy as np
@@ -28,6 +28,9 @@ class EdgeTpuDetectorConfig(BaseDetectorConfig):
title="EdgeTPU", title="EdgeTPU",
) )
# a TPU can only be opened by one process
shareable: ClassVar[bool] = False
type: Literal[DETECTOR_KEY] type: Literal[DETECTOR_KEY]
device: str = Field( device: str = Field(
default=None, default=None,
+4 -1
View File
@@ -5,7 +5,7 @@ import shutil
import urllib.request import urllib.request
import zipfile import zipfile
from queue import Queue from queue import Queue
from typing import Literal from typing import ClassVar, Literal
import cv2 import cv2
import numpy as np import numpy as np
@@ -37,6 +37,9 @@ class MemryXDetectorConfig(BaseDetectorConfig):
title="MemryX", title="MemryX",
) )
# an accelerator can only be opened by one process
shareable: ClassVar[bool] = False
type: Literal[DETECTOR_KEY] type: Literal[DETECTOR_KEY]
device: str = Field( device: str = Field(
default="PCIe", default="PCIe",
+1 -1
View File
@@ -28,7 +28,7 @@ class OvDetectorConfig(BaseDetectorConfig):
type: Literal[DETECTOR_KEY] type: Literal[DETECTOR_KEY]
device: str = Field( device: str = Field(
default=None, default="AUTO",
title="Device Type", title="Device Type",
description="The device to use for OpenVINO inference (e.g. 'CPU', 'GPU', 'NPU').", description="The device to use for OpenVINO inference (e.g. 'CPU', 'GPU', 'NPU').",
) )
+4 -1
View File
@@ -2,7 +2,7 @@ import logging
import os.path import os.path
import re import re
import urllib.request import urllib.request
from typing import Literal from typing import ClassVar, Literal
import cv2 import cv2
import numpy as np import numpy as np
@@ -35,6 +35,9 @@ class RknnDetectorConfig(BaseDetectorConfig):
title="RKNN", title="RKNN",
) )
device_spec_field: ClassVar[str] = "num_cores"
device_spec_type: ClassVar[type] = int
type: Literal[DETECTOR_KEY] type: Literal[DETECTOR_KEY]
num_cores: int = Field( num_cores: int = Field(
default=0, default=0,
+3 -1
View File
@@ -14,7 +14,7 @@ try:
except ModuleNotFoundError: except ModuleNotFoundError:
TRT_SUPPORT = False TRT_SUPPORT = False
from typing import Literal from typing import ClassVar, Literal
from pydantic import ConfigDict, Field from pydantic import ConfigDict, Field
@@ -53,6 +53,8 @@ class TensorRTDetectorConfig(BaseDetectorConfig):
title="TensorRT", title="TensorRT",
) )
device_spec_type: ClassVar[type] = int
type: Literal[DETECTOR_KEY] type: Literal[DETECTOR_KEY]
device: int = Field( device: int = Field(
default=0, title="GPU Device Index", description="The GPU device index to use." default=0, title="GPU Device Index", description="The GPU device index to use."
+5 -8
View File
@@ -159,7 +159,8 @@ class EventProcessor(threading.Thread):
if width is None or height is None: if width is None or height is None:
return return
first_detector = list(self.config.detectors.values())[0] camera_model = self.config.model_for_camera(camera)
camera_detector = self.config.devices_for_model(camera_model)[0].detector
start_time = event_data["start_time"] start_time = event_data["start_time"]
end_time = ( end_time = (
@@ -229,13 +230,9 @@ class EventProcessor(threading.Thread):
Event.thumbnail: event_data.get("thumbnail"), Event.thumbnail: event_data.get("thumbnail"),
Event.has_clip: event_data["has_clip"], Event.has_clip: event_data["has_clip"],
Event.has_snapshot: event_data["has_snapshot"], Event.has_snapshot: event_data["has_snapshot"],
Event.model_hash: first_detector.model.model_hash Event.model_hash: camera_model.model_hash,
if first_detector.model Event.model_type: camera_model.model_type,
else None, Event.detector_type: camera_detector,
Event.model_type: first_detector.model.model_type
if first_detector.model
else None,
Event.detector_type: first_detector.type,
Event.data: { Event.data: {
"box": box, "box": box,
"region": region, "region": region,
+63 -119
View File
@@ -262,6 +262,10 @@ def get_tool_definitions(
`attribute` parameter is exposed for filtering by their labels. When the `attribute` parameter is exposed for filtering by their labels. When the
embeddings model only understands English (JinaV1), the `semantic_query` embeddings model only understands English (JinaV1), the `semantic_query`
description instructs the model to write the query in English. description instructs the model to write the query in English.
Descriptions here stay mechanical: which tool to reach for, and how the
filters relate to each other, is stated once in the system prompt so the
guidance is not paid for twice on every request.
""" """
search_objects_properties: dict[str, Any] = { search_objects_properties: dict[str, Any] = {
"camera": { "camera": {
@@ -270,26 +274,13 @@ def get_tool_definitions(
}, },
"label": { "label": {
"type": "string", "type": "string",
"description": ( "description": "Tracked object class to filter by.",
"Generic object class to filter by — one of the tracked detector "
"labels such as 'person', 'package', 'car', 'dog', 'bird'. Use "
"this for broad queries like 'show me all cars today'. Combine "
"with semantic_query when the user also describes appearance or "
"behavior (e.g. label='person', semantic_query='riding a lawn "
"mower')."
),
}, },
"sub_label": { "sub_label": {
"type": "string", "type": "string",
"description": ( "description": (
"Filter by a DISCRETE NAMED entity recognized in the detection. " "Name recognized in the detection: a person, delivery company, "
"Use this for: a known person's name ('John'), a delivery " "animal species or breed, or license plate."
"company ('Amazon', 'UPS'), a recognized animal species or "
"breed ('blue jay', 'cardinal', 'golden retriever'), or a "
"license plate string. When filtering by a specific name, set "
"only sub_label and leave label unset. Do NOT use sub_label "
"for descriptions of appearance, clothing, or actions — those "
"belong in semantic_query."
), ),
}, },
"after": { "after": {
@@ -313,20 +304,11 @@ def get_tool_definitions(
} }
if attribute_classifications: if attribute_classifications:
model_outline = "; ".join(
f"{m['name']} (applies to {', '.join(m['objects']) or 'any object'})"
for m in attribute_classifications
)
search_objects_properties["attribute"] = { search_objects_properties["attribute"] = {
"type": "string", "type": "string",
"description": ( "description": (
"Filter by a classification attribute label produced by a " "Attribute label produced by a configured classification model "
"configured attribute classification model. Use this INSTEAD " "(case-sensitive)."
"of semantic_query when the user's request matches one of "
"these classifications. Configured models: "
f"{model_outline}. "
"Set the value to the attribute label that matches the user's "
"phrasing (case-sensitive)."
), ),
} }
@@ -334,29 +316,12 @@ def get_tool_definitions(
search_objects_properties["semantic_query"] = { search_objects_properties["semantic_query"] = {
"type": "string", "type": "string",
"description": ( "description": (
"Optional natural-language description of a PHYSICAL " "Description of an appearance or activity, used to semantically "
"CHARACTERISTIC, APPEARANCE, or ACTIVITY the user mentioned, " "narrow results."
"used to semantically narrow results. Only set this when the "
"user describes something beyond what label and sub_label can "
"express on their own.\n"
"USE for descriptive phrases like: 'riding a lawn mower', "
"'wearing a red jacket', 'carrying a package', 'walking a "
"dog', 'on a bicycle', 'holding an umbrella'.\n"
"DO NOT USE for:\n"
"- specific named people, pets, or delivery companies → use sub_label\n"
"- animal species or breed names like 'blue jay', 'cardinal', "
"'golden retriever' → use sub_label\n"
"- license plate strings → use sub_label\n"
"- generic object queries like 'all cars today' or 'every "
"person' → use label alone with no semantic_query\n"
"When set, combine with label/time/camera/zone filters as "
"usual (e.g. label='person', semantic_query='riding a lawn "
"mower', after='2024-05-01T00:00:00Z')."
+ ( + (
" The configured embeddings model only understands " " The configured embeddings model only understands English, so "
"English, so always write semantic_query in English, " "always write this in English, translating the user's "
"translating the user's description if they phrased it " "description if they phrased it in another language."
"in another language."
if embeddings_language == "english" if embeddings_language == "english"
else "" else ""
) )
@@ -364,25 +329,9 @@ def get_tool_definitions(
} }
search_objects_description = ( search_objects_description = (
"Search the historical record of detected objects in Frigate. " "Search the historical record of tracked detections. Use this ONLY for "
"Use this ONLY for questions about the PAST — e.g. 'did anyone come by today?', " "questions about the PAST, e.g. 'did anyone come by today?', 'when was the "
"'when was the last car?', 'show me detections from yesterday'. " "last car?'. For alerting on future events use start_camera_watch instead."
"Do NOT use this for monitoring or alerting requests about future events — "
"use start_camera_watch instead for those. "
"An 'object' in Frigate represents a tracked detection (e.g., a person, package, car).\n\n"
"Choose filters based on what the user is asking for:\n"
"- Generic class query ('show me all cars today'): set `label` only.\n"
"- Specific NAMED entity (known person, delivery company, animal "
"species/breed like 'blue jay' or 'golden retriever', license "
"plate): set `sub_label` only and leave `label` unset.\n"
)
if semantic_search_enabled:
search_objects_description += (
"- Physical CHARACTERISTIC, APPEARANCE, or ACTIVITY that is not a "
"discrete name ('person riding a lawn mower', 'someone in a red "
"jacket', 'person carrying a package'): set `semantic_query` with "
"the descriptive phrase, optionally alongside `label` for the "
"object class. Do NOT put descriptive phrases in sub_label."
) )
return [ return [
@@ -398,20 +347,30 @@ def get_tool_definitions(
"required": [], "required": [],
}, },
}, },
{
"type": "function",
"function": {
"name": "get_categorized_object_names",
"description": (
"Every name that can be attached as a sub_label, grouped by object "
"type: recognized faces, named license plates, classification "
"categories, and delivery logos. Takes no arguments and always "
"returns the complete map."
),
"parameters": {
"type": "object",
"properties": {},
"required": [],
},
},
},
{ {
"type": "function", "type": "function",
"function": { "function": {
"name": "find_similar_objects", "name": "find_similar_objects",
"description": ( "description": (
"Find tracked objects that are visually and semantically similar " "Find tracked objects visually and semantically similar to a "
"to a specific past event. Use this when the user references a " "specific past event. Requires semantic search to be enabled."
"particular object they have seen and wants to find other "
"sightings of the same or similar one ('that green car', 'the "
"person in the red jacket', 'the package that was delivered'). "
"Prefer this over search_objects whenever the user's intent is "
"'find more like this specific one.' Use search_objects first "
"only if you need to locate the anchor event. Requires semantic "
"search to be enabled."
), ),
"parameters": { "parameters": {
"type": "object", "type": "object",
@@ -473,9 +432,8 @@ def get_tool_definitions(
"function": { "function": {
"name": "set_camera_state", "name": "set_camera_state",
"description": ( "description": (
"Change a camera's feature state (e.g., turn detection on/off, enable/disable recordings). " "Change a camera's feature state, e.g. turn detection on or off. "
"Use camera='*' to apply to all cameras at once. " "Only call this when the user explicitly asks to change a setting. "
"Only call this tool when the user explicitly asks to change a camera setting. "
"Requires admin privileges." "Requires admin privileges."
), ),
"parameters": { "parameters": {
@@ -510,14 +468,14 @@ def get_tool_definitions(
], ],
"description": ( "description": (
"The feature to change. Most features accept ON or OFF. " "The feature to change. Most features accept ON or OFF. "
"birdseye_mode accepts CONTINUOUS, MOTION, or OBJECTS. " "birdseye_mode accepts CONTINUOUS, MOTION, OBJECTS, STATIONARY_OBJECTS, or a comma-separated combination. "
"motion_contour_area and motion_threshold accept a number. " "motion_contour_area and motion_threshold accept a number. "
"profile accepts a profile name or 'none' to deactivate (requires camera='*')." "profile accepts a profile name or 'none' to deactivate (requires camera='*')."
), ),
}, },
"value": { "value": {
"type": "string", "type": "string",
"description": "The value to set. ON or OFF for toggles, a number for thresholds, a profile name or 'none' for profile.", "description": "The value to set, as accepted by the chosen feature.",
}, },
}, },
"required": ["camera", "feature", "value"], "required": ["camera", "feature", "value"],
@@ -529,11 +487,9 @@ def get_tool_definitions(
"function": { "function": {
"name": "get_live_context", "name": "get_live_context",
"description": ( "description": (
"Get the current live image and detection information for a single camera: objects being tracked, " "Current live image and detections (tracked objects, zones, "
"zones, timestamps. Use this to understand what is visible in the live view. " "timestamps) for one camera. Use this for questions about what is "
"Call this when answering questions about what is happening right now on a specific camera. " "happening right now. Call it again for each additional camera."
"Operates on one camera at a time; call the tool again for each additional camera. "
"Wildcards and empty values are not accepted."
), ),
"parameters": { "parameters": {
"type": "object", "type": "object",
@@ -541,8 +497,8 @@ def get_tool_definitions(
"camera": { "camera": {
"type": "string", "type": "string",
"description": ( "description": (
"Exact name of a single camera to get live context for. " "Exact name of a single camera. Wildcards (e.g. '*', "
"Wildcards (e.g. '*', 'all') and empty strings are not accepted." "'all') and empty strings are not accepted."
), ),
}, },
}, },
@@ -555,10 +511,9 @@ def get_tool_definitions(
"function": { "function": {
"name": "start_camera_watch", "name": "start_camera_watch",
"description": ( "description": (
"Start a continuous VLM watch job that monitors a camera and sends a notification " "Start a continuous watch job that monitors a camera and notifies "
"when a specified condition is met. Use this when the user wants to be alerted about " "the user when a condition is met, e.g. 'tell me when guests "
"a future event, e.g. 'tell me when guests arrive' or 'notify me when the package is picked up'. " "arrive'. Only one watch job can run at a time. Returns a job ID."
"Only one watch job can run at a time. Returns a job ID."
), ),
"parameters": { "parameters": {
"type": "object", "type": "object",
@@ -598,10 +553,7 @@ def get_tool_definitions(
"type": "function", "type": "function",
"function": { "function": {
"name": "stop_camera_watch", "name": "stop_camera_watch",
"description": ( "description": "Cancel the currently running watch job.",
"Cancel the currently running VLM watch job. Use this when the user wants to "
"stop a previously started watch, e.g. 'stop watching the front door'."
),
"parameters": { "parameters": {
"type": "object", "type": "object",
"properties": {}, "properties": {},
@@ -614,11 +566,9 @@ def get_tool_definitions(
"function": { "function": {
"name": "get_profile_status", "name": "get_profile_status",
"description": ( "description": (
"Get the current profile status including the active profile and " "Get the active profile and when each profile was last activated. "
"timestamps of when each profile was last activated. Use this to " "Call this before get_recap to derive the time window for requests "
"determine time periods for recap requests — e.g. when the user asks " "like 'what happened while I was away?'."
"'what happened while I was away?', call this first to find the relevant "
"time window based on profile activation history."
), ),
"parameters": { "parameters": {
"type": "object", "type": "object",
@@ -632,11 +582,9 @@ def get_tool_definitions(
"function": { "function": {
"name": "get_recap", "name": "get_recap",
"description": ( "description": (
"Get a recap of all activity (alerts and detections) for a given time period. " "Get all activity (alerts and detections) for a time period, as a "
"Use this after calling get_profile_status to retrieve what happened during " "chronological list with camera, objects, zones, and descriptions "
"a specific window — e.g. 'what happened while I was away?'. Returns a " "when available. Summarize the results for the user."
"chronological list of activity with camera, objects, zones, and GenAI-generated "
"descriptions when available. Summarize the results for the user."
), ),
"parameters": { "parameters": {
"type": "object", "type": "object",
@@ -723,14 +671,13 @@ def build_chat_system_prompt(
) )
speed_units_section = f"\n\nReport object speeds to the user in {speed_unit}." speed_units_section = f"\n\nReport object speeds to the user in {speed_unit}."
semantic_search_section = "" filter_routing_section = (
if semantic_search_enabled:
semantic_search_section = (
"\n\nWhen routing a search_objects call, pick filters by the shape of the user's request:\n" "\n\nWhen routing a search_objects call, pick filters by the shape of the user's request:\n"
"- Generic class ('show me all cars today'): set `label` only.\n" "- Generic class ('show me all cars today'): set `label` only.\n"
"- Specific named entity — a known person ('John'), delivery company ('Amazon'), animal species/breed ('blue jay', 'cardinal', 'golden retriever'), or license plate: set `sub_label` only and leave `label` unset.\n" "- Specific named entity — a known person ('John'), delivery company ('Amazon'), animal species/breed ('blue jay', 'golden retriever'), or license plate: set `sub_label` only and leave `label` unset. Call get_categorized_object_names first and use the exact spelling it returns; a guessed spelling matches nothing. If the name is absent, say it is not configured rather than searching for it."
"- Physical characteristic, appearance, or activity that is NOT a discrete name ('find me people riding a lawn mower', 'someone in a red jacket', 'a person carrying a package'): set `semantic_query` with the descriptive phrase, optionally combined with `label` for the object class. Never put descriptive phrases in `sub_label`."
) )
if semantic_search_enabled:
filter_routing_section += "\n- Physical characteristic, appearance, or activity that is NOT a discrete name ('riding a lawn mower', 'someone in a red jacket'): set `semantic_query` with the descriptive phrase, optionally combined with `label`. Never put descriptive phrases in `sub_label`."
attribute_classification_section = "" attribute_classification_section = ""
if attribute_classifications: if attribute_classifications:
@@ -739,9 +686,9 @@ def build_chat_system_prompt(
for m in attribute_classifications for m in attribute_classifications
) )
attribute_classification_section = ( attribute_classification_section = (
"\n\nAttribute classification models are configured for the following object types:\n" "\n\nConfigured attribute classification models:\n"
f"{model_lines}\n" f"{model_lines}\n"
"When the user's request matches one of these classifications, set the search_objects `attribute` field to the matching label rather than using `semantic_query`. Reserve `semantic_query` for descriptive phrases that fall outside the configured attribute labels." "When the user's request matches one of these classifications, set the search_objects `attribute` field to the matching label (case-sensitive) rather than using `semantic_query`. Reserve `semantic_query` for descriptive phrases outside the configured attribute labels."
) )
return f"""You are a helpful assistant for Frigate, a security camera NVR system. You help users answer questions about their cameras, detected objects, and events. return f"""You are a helpful assistant for Frigate, a security camera NVR system. You help users answer questions about their cameras, detected objects, and events.
@@ -750,9 +697,6 @@ Current server local date and time: {current_date_str} at {current_time_str}
Do not start your response with phrases like "I will check...", "Let me see...", or "Let me look...". Answer directly. Do not start your response with phrases like "I will check...", "Let me see...", or "Let me look...". Answer directly.
Always present times to the user in the server's local timezone. When tool results include start_time_local and end_time_local, use those exact strings when listing or describing detection times—do not convert or invent timestamps. Do not use UTC or ISO format with Z for the user-facing answer unless the tool result only provides Unix timestamps without local time fields. Always present times in the server's local timezone. When tool results include start_time_local and end_time_local, quote those strings exactly; never convert or invent timestamps, and fall back to UTC or ISO format only when a result has no local time fields. Resolve relative dates like "today" or "this week" against the current date above, and pass dates to tools in ISO 8601 (e.g. {current_date_str}T00:00:00Z for the start of today).
When users ask about "today", "yesterday", "this week", etc., use the current date above as reference.
When searching for objects or events, use ISO 8601 format for dates (e.g., {current_date_str}T00:00:00Z for the start of today).
Always be accurate with time calculations based on the current date provided.
When a user refers to a specific object they have seen or describe with identifying details ("that green car", "the person in the red jacket", "a package left today"), prefer the find_similar_objects tool over search_objects. Use search_objects first only to locate the anchor event, then pass its id to find_similar_objects. For generic queries like "show me all cars today", keep using search_objects. If a user message begins with [attached_event:<id>], treat that event id as the anchor for any similarity or "tell me more" request in the same message and call find_similar_objects with that id.{semantic_search_section}{attribute_classification_section}{cameras_section}{speed_units_section}""" When the user refers to a specific object they have seen ("that green car", "the person in the red jacket", "a package left today"), prefer find_similar_objects over search_objects, using search_objects only to locate the anchor event and passing its id along. Keep search_objects for generic queries like "show me all cars today". If a user message begins with [attached_event:<id>], treat that id as the anchor for any similarity or "tell me more" request in the same message.{filter_routing_section}{attribute_classification_section}{cameras_section}{speed_units_section}"""
+13 -1
View File
@@ -5,7 +5,19 @@ import threading
from numpy import ndarray from numpy import ndarray
from frigate.detectors.detector_config import InputTensorEnum from frigate.detectors.detector_config import InputTensorEnum, ModelConfig
def detection_frame_size(model: ModelConfig) -> int:
"""Get the shared memory size a camera needs to hand frames to a model.
Args:
model: The model the camera runs on
Returns:
Size in bytes of one model input frame
"""
return model.height * model.width * 3
class RequestStore: class RequestStore:
+118 -109
View File
@@ -9,6 +9,7 @@ import queue
import subprocess as sp import subprocess as sp
import threading import threading
import traceback import traceback
from dataclasses import dataclass
from multiprocessing.synchronize import Event as MpEvent from multiprocessing.synchronize import Event as MpEvent
from typing import Any from typing import Any
@@ -16,7 +17,7 @@ import cv2
import numpy as np import numpy as np
from frigate.comms.inter_process import InterProcessRequestor from frigate.comms.inter_process import InterProcessRequestor
from frigate.config import BirdseyeModeEnum, FfmpegConfig, FrigateConfig from frigate.config import BirdseyeModeConfig, FfmpegConfig, FrigateConfig
from frigate.const import BASE_DIR, BIRDSEYE_PIPE, INSTALL_DIR, UPDATE_BIRDSEYE_LAYOUT from frigate.const import BASE_DIR, BIRDSEYE_PIPE, INSTALL_DIR, UPDATE_BIRDSEYE_LAYOUT
from frigate.output.ws_auth import ws_has_camera_access from frigate.output.ws_auth import ws_has_camera_access
from frigate.util.image import ( from frigate.util.image import (
@@ -28,6 +29,15 @@ from frigate.util.image import (
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@dataclass(frozen=True, slots=True)
class BirdseyeActivity:
"""Activity signals used to decide whether a camera is shown in Birdseye."""
has_active_object: bool
has_stationary_object: bool
has_motion: bool
def get_standard_aspect_ratio(width: int, height: int) -> tuple[int, int]: def get_standard_aspect_ratio(width: int, height: int) -> tuple[int, int]:
"""Ensure that only standard aspect ratios are used.""" """Ensure that only standard aspect ratios are used."""
# it is important that all ratios have the same scale # it is important that all ratios have the same scale
@@ -409,18 +419,16 @@ class BirdsEyeFrameManager:
) )
def camera_active( def camera_active(
self, mode: Any, object_box_count: int, motion_box_count: int self,
mode: BirdseyeModeConfig,
activity: BirdseyeActivity,
) -> bool: ) -> bool:
if mode == BirdseyeModeEnum.continuous: return (
return True mode.continuous
or (mode.motion and activity.has_motion)
if mode == BirdseyeModeEnum.motion and motion_box_count > 0: or (mode.objects and activity.has_active_object)
return True or (mode.stationary_objects and activity.has_stationary_object)
)
if mode == BirdseyeModeEnum.objects and object_box_count > 0:
return True
return False
def get_camera_coordinates(self) -> dict[str, dict[str, int]]: def get_camera_coordinates(self) -> dict[str, dict[str, int]]:
"""Return the coordinates of each camera in the current layout.""" """Return the coordinates of each camera in the current layout."""
@@ -604,112 +612,92 @@ class BirdsEyeFrameManager:
) -> list[list[Any]] | None: ) -> list[list[Any]] | None:
"""Calculate the optimal layout for 2+ cameras.""" """Calculate the optimal layout for 2+ cameras."""
def map_layout( def find_available_x(
camera_layout: list[list[Any]], row_height: int current_x: int,
) -> tuple[int, int, list[list[Any]] | None]: width: int,
"""Map the calculated layout.""" reserved_ranges: list[tuple[int, int]],
candidate_layout = [] max_width: int,
starting_x = 0 ) -> int | None:
x = 0 """Find the first horizontal slot that does not collide with reservations."""
x = current_x
for reserved_start, reserved_end in sorted(reserved_ranges):
if x >= reserved_end:
continue
if x + width <= reserved_start:
return x
x = max(x, reserved_end)
if x + width <= max_width:
return x
return None
def map_layout(row_height: int) -> tuple[int, int, list[list[Any]] | None]:
"""Lay out cameras row by row while reserving portrait spans for the next row."""
candidate_layout: list[list[Any]] = []
reserved_ranges: dict[int, list[tuple[int, int]]] = {}
current_row: list[Any] = []
row_index = 0
row_y = 0
row_x = 0
max_width = 0 max_width = 0
y = 0 max_height = 0
for row in camera_layout:
final_row = []
max_width = max(max_width, x)
x = starting_x
for cameras in row:
camera_dims = self.cameras[cameras[0]]["dimensions"].copy()
camera_aspect = cameras[1]
if camera_dims[1] > camera_dims[0]:
scaled_height = int(row_height * 2)
scaled_width = int(scaled_height * camera_aspect)
starting_x = scaled_width
else:
scaled_height = row_height
scaled_width = int(scaled_height * camera_aspect)
# layout is too large
if (
x + scaled_width > self.canvas.width
or y + scaled_height > self.canvas.height
):
return x + scaled_width, y + scaled_height, None
final_row.append((cameras[0], (x, y, scaled_width, scaled_height)))
x += scaled_width
y += row_height
candidate_layout.append(final_row)
if max_width == 0:
max_width = x
return max_width, y, candidate_layout
canvas_aspect_x, canvas_aspect_y = self.canvas.get_aspect(coefficient)
camera_layout: list[list[Any]] = []
camera_layout.append([])
starting_x = 0
x = starting_x
y = 0
y_i = 0
max_y = 0
for camera in cameras_to_add: for camera in cameras_to_add:
camera_dims = self.cameras[camera]["dimensions"].copy() camera_dims = self.cameras[camera]["dimensions"].copy()
camera_aspect_x, camera_aspect_y = self.canvas.get_camera_aspect( camera_aspect_x, camera_aspect_y = self.canvas.get_camera_aspect(
camera, camera_dims[0], camera_dims[1] camera, camera_dims[0], camera_dims[1]
) )
portrait = camera_dims[1] > camera_dims[0]
scaled_height = row_height * 2 if portrait else row_height
scaled_width = int(scaled_height * (camera_aspect_x / camera_aspect_y))
if camera_dims[1] > camera_dims[0]: while True:
portrait = True x = find_available_x(
else: row_x,
portrait = False scaled_width,
reserved_ranges.get(row_index, []),
self.canvas.width,
)
if (x + camera_aspect_x) <= canvas_aspect_x: if x is not None and row_y + scaled_height <= self.canvas.height:
# insert if camera can fit on current row current_row.append(
camera_layout[y_i].append( (camera, (x, row_y, scaled_width, scaled_height))
(
camera,
camera_aspect_x / camera_aspect_y,
)
) )
row_x = x + scaled_width
max_width = max(max_width, row_x)
max_height = max(max_height, row_y + scaled_height)
if portrait: if portrait:
starting_x = camera_aspect_x reserved_ranges.setdefault(row_index + 1, []).append(
else: (x, row_x)
max_y = max(
max_y,
camera_aspect_y,
) )
x += camera_aspect_x break
else:
# move on to the next row and insert
y += max_y
y_i += 1
camera_layout.append([])
x = starting_x
if x + camera_aspect_x > canvas_aspect_x: if current_row:
return None candidate_layout.append(current_row)
current_row = []
camera_layout[y_i].append( row_index += 1
( row_y = row_index * row_height
camera, row_x = 0
camera_aspect_x / camera_aspect_y,
)
)
x += camera_aspect_x
if y + max_y > canvas_aspect_y: if row_y + scaled_height > self.canvas.height:
return None overflow_width = max(max_width, scaled_width)
overflow_height = row_y + scaled_height
return overflow_width, overflow_height, None
row_height = int(self.canvas.height / coefficient) if current_row:
total_width, total_height, standard_candidate_layout = map_layout( candidate_layout.append(current_row)
camera_layout, row_height
) return max_width, max_height, candidate_layout
row_height = max(1, int(self.canvas.height / coefficient))
total_width, total_height, standard_candidate_layout = map_layout(row_height)
if not standard_candidate_layout: if not standard_candidate_layout:
# if standard layout didn't work # if standard layout didn't work
@@ -718,9 +706,9 @@ class BirdsEyeFrameManager:
total_width / self.canvas.width, total_width / self.canvas.width,
total_height / self.canvas.height, total_height / self.canvas.height,
) )
row_height = int(row_height / scale_down_percent) row_height = max(1, int(row_height / scale_down_percent))
total_width, total_height, standard_candidate_layout = map_layout( total_width, total_height, standard_candidate_layout = map_layout(
camera_layout, row_height row_height
) )
if not standard_candidate_layout: if not standard_candidate_layout:
@@ -734,8 +722,8 @@ class BirdsEyeFrameManager:
1 / (total_width / self.canvas.width), 1 / (total_width / self.canvas.width),
1 / (total_height / self.canvas.height), 1 / (total_height / self.canvas.height),
) )
row_height = int(row_height * scale_up_percent) row_height = max(1, int(row_height * scale_up_percent))
_, _, scaled_layout = map_layout(camera_layout, row_height) _, _, scaled_layout = map_layout(row_height)
if scaled_layout: if scaled_layout:
return scaled_layout return scaled_layout
@@ -745,8 +733,7 @@ class BirdsEyeFrameManager:
def update( def update(
self, self,
camera: str, camera: str,
object_count: int, activity: BirdseyeActivity,
motion_count: int,
frame_time: float, frame_time: float,
frame: np.ndarray, frame: np.ndarray,
) -> tuple[bool, bool]: ) -> tuple[bool, bool]:
@@ -774,7 +761,10 @@ class BirdsEyeFrameManager:
# update the last active frame for the camera # update the last active frame for the camera
self.cameras[camera]["current_frame"] = frame.copy() self.cameras[camera]["current_frame"] = frame.copy()
self.cameras[camera]["current_frame_time"] = frame_time self.cameras[camera]["current_frame_time"] = frame_time
if self.camera_active(camera_config.birdseye.mode, object_count, motion_count): if self.camera_active(
camera_config.birdseye.mode,
activity,
):
self.cameras[camera]["last_active_frame"] = frame_time self.cameras[camera]["last_active_frame"] = frame_time
now = datetime.datetime.now().timestamp() now = datetime.datetime.now().timestamp()
@@ -882,10 +872,29 @@ class Birdseye:
frame_time: float, frame_time: float,
frame: np.ndarray, frame: np.ndarray,
) -> None: ) -> None:
has_active_object = False
has_stationary_object = False
for tracked_object in current_tracked_objects:
if tracked_object["stationary"]:
if not tracked_object["false_positive"]:
has_stationary_object = True
else:
# Preserve the existing objects activity behavior, which includes
# non-stationary trackers before they are confirmed.
has_active_object = True
if has_active_object and has_stationary_object:
break
activity = BirdseyeActivity(
has_active_object=has_active_object,
has_stationary_object=has_stationary_object,
has_motion=bool(motion_boxes),
)
frame_changed, frame_layout_changed = self.birdseye_manager.update( frame_changed, frame_layout_changed = self.birdseye_manager.update(
camera, camera,
len([o for o in current_tracked_objects if not o["stationary"]]), activity,
len(motion_boxes),
frame_time, frame_time,
frame, frame,
) )
+2 -2
View File
@@ -476,7 +476,7 @@ class ReviewSegmentMaintainer(threading.Thread):
if not object["sub_label"]: if not object["sub_label"]:
segment.detections[object["id"]] = object["label"] segment.detections[object["id"]] = object["label"]
elif object["sub_label"][0] in self.config.model.all_attributes: elif object["sub_label"][0] in self.config.all_attributes:
segment.detections[object["id"]] = object["sub_label"][0] segment.detections[object["id"]] = object["sub_label"][0]
else: else:
segment.detections[object["id"]] = f"{object['label']}-verified" segment.detections[object["id"]] = f"{object['label']}-verified"
@@ -614,7 +614,7 @@ class ReviewSegmentMaintainer(threading.Thread):
for object in activity.get_all_objects(): for object in activity.get_all_objects():
if not object["sub_label"]: if not object["sub_label"]:
detections[object["id"]] = object["label"] detections[object["id"]] = object["label"]
elif object["sub_label"][0] in self.config.model.all_attributes: elif object["sub_label"][0] in self.config.all_attributes:
detections[object["id"]] = object["sub_label"][0] detections[object["id"]] = object["sub_label"][0]
else: else:
detections[object["id"]] = f"{object['label']}-verified" detections[object["id"]] = f"{object['label']}-verified"
+5 -4
View File
@@ -322,16 +322,17 @@ async def set_gpu_stats(
async def set_npu_usages(config: FrigateConfig, all_stats: dict[str, Any]) -> None: async def set_npu_usages(config: FrigateConfig, all_stats: dict[str, Any]) -> None:
stats: dict[str, dict] = {} stats: dict[str, dict] = {}
for detector in config.detectors.values(): for model in config.models:
if detector.type == "rknn": for device in config.devices_for_model(model):
if device.detector == "rknn":
# Rockchip NPU usage # Rockchip NPU usage
rk_usage = get_rockchip_npu_stats() rk_usage = get_rockchip_npu_stats()
stats["rockchip"] = rk_usage stats["rockchip"] = rk_usage
elif detector.type == "openvino" and detector.device == "NPU": elif device.detector == "openvino" and device.device == "NPU":
# OpenVINO NPU usage # OpenVINO NPU usage
ov_usage = get_openvino_npu_stats() ov_usage = get_openvino_npu_stats()
stats["openvino"] = ov_usage stats["openvino"] = ov_usage
elif detector.type == "axengine": elif device.detector == "axengine":
# AXERA NPU usage # AXERA NPU usage
axcl_usage = get_axcl_npu_stats() axcl_usage = get_axcl_npu_stats()
stats["axengine"] = axcl_usage stats["axengine"] = axcl_usage
+29 -6
View File
@@ -386,9 +386,19 @@ class TestConfigSetWildcardPropagation(BaseTestHttp):
guess (mode still equals the previous global) wrongly claims a camera guess (mode still equals the previous global) wrongly claims a camera
whose explicit yaml mode happens to match. whose explicit yaml mode happens to match.
""" """
self.minimal_config["birdseye"] = {"enabled": True, "mode": "motion"} self.minimal_config["birdseye"] = {
"enabled": True,
"mode": {"motion": True},
}
# explicit override that matches the global value being replaced # explicit override that matches the global value being replaced
self.minimal_config["cameras"]["front_door"]["birdseye"] = {"mode": "motion"} self.minimal_config["cameras"]["front_door"]["birdseye"] = {
"mode": {
"continuous": False,
"motion": True,
"objects": False,
"stationary_objects": False,
}
}
config_path = self._write_config_file() config_path = self._write_config_file()
mock_find_config.return_value = config_path mock_find_config.return_value = config_path
@@ -399,7 +409,16 @@ class TestConfigSetWildcardPropagation(BaseTestHttp):
resp = client.put( resp = client.put(
"/config/set", "/config/set",
json={ json={
"config_data": {"birdseye": {"mode": "continuous"}}, "config_data": {
"birdseye": {
"mode": {
"continuous": True,
"motion": False,
"objects": False,
"stationary_objects": False,
}
}
},
"update_topic": "config/birdseye", "update_topic": "config/birdseye",
"requires_restart": 0, "requires_restart": 0,
}, },
@@ -411,7 +430,7 @@ class TestConfigSetWildcardPropagation(BaseTestHttp):
mock_publisher.publisher.publish.assert_called_once() mock_publisher.publisher.publish.assert_called_once()
topic, settings = mock_publisher.publisher.publish.call_args[0] topic, settings = mock_publisher.publisher.publish.call_args[0]
self.assertEqual(topic, "config/birdseye") self.assertEqual(topic, "config/birdseye")
self.assertEqual(settings.mode.value, "continuous") self.assertEqual(settings.mode.to_mqtt_payload(), "CONTINUOUS")
published = { published = {
call[0][0].camera: call[0][1] call[0][0].camera: call[0][1]
@@ -425,8 +444,12 @@ class TestConfigSetWildcardPropagation(BaseTestHttp):
) )
# the override survives, the inheriting camera follows global # the override survives, the inheriting camera follows global
self.assertEqual(published["front_door"].mode.value, "motion") self.assertEqual(
self.assertEqual(published["back_yard"].mode.value, "continuous") published["front_door"].mode.to_mqtt_payload(), "MOTION"
)
self.assertEqual(
published["back_yard"].mode.to_mqtt_payload(), "CONTINUOUS"
)
finally: finally:
os.unlink(config_path) os.unlink(config_path)
+174
View File
@@ -1,15 +1,73 @@
"""Unit tests for recordings/media API endpoints.""" """Unit tests for recordings/media API endpoints."""
from dataclasses import dataclass
from datetime import UTC, datetime from datetime import UTC, datetime
from unittest.mock import patch
import pytz import pytz
from fastapi import Request from fastapi import Request
from frigate.api.auth import get_allowed_cameras_for_filter, get_current_user from frigate.api.auth import get_allowed_cameras_for_filter, get_current_user
from frigate.const import MAX_SEGMENT_DURATION
from frigate.models import Recordings from frigate.models import Recordings
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
@dataclass(frozen=True)
class RangeCase:
"""Expected behavior for one segment relative to the requested range.
Offsets are seconds from REQUEST_START; the request ends at +100 seconds.
"""
name: str
start_offset: float
end_offset: float
included_in_recordings: bool
vod_clip_from_ms: int | None = None
vod_duration_ms: int | None = None
REQUEST_START = 1000
REQUEST_END = 1100
RANGE_CASES = (
RangeCase("before", -MAX_SEGMENT_DURATION + 1, -1, False),
RangeCase("meets_start", -10, 0, True),
RangeCase(
"overlaps_start",
-MAX_SEGMENT_DURATION + 0.5,
0.25,
True,
vod_clip_from_ms=599500,
vod_duration_ms=250,
),
RangeCase("starts_at_start", 0, 10, True, vod_duration_ms=10000),
RangeCase("inside", 20, 80, True, vod_duration_ms=60000),
RangeCase("ends_at_end", 90, 100, True, vod_duration_ms=10000),
RangeCase("matches_range", 0, 100, True, vod_duration_ms=100000),
RangeCase("starts_with_range", 0, 110, True, vod_duration_ms=100000),
RangeCase(
"covers_range",
-20,
120,
True,
vod_clip_from_ms=20000,
vod_duration_ms=100000,
),
RangeCase(
"ends_with_range",
-10,
100,
True,
vod_clip_from_ms=10000,
vod_duration_ms=100000,
),
RangeCase("overlaps_end", 95, 105, True, vod_duration_ms=5000),
RangeCase("starts_at_end", 100, 110, True),
RangeCase("after", 101, 110, False),
)
class TestHttpMedia(BaseTestHttp): class TestHttpMedia(BaseTestHttp):
"""Test media API endpoints, particularly recordings with DST handling.""" """Test media API endpoints, particularly recordings with DST handling."""
@@ -44,6 +102,26 @@ class TestHttpMedia(BaseTestHttp):
self.app.dependency_overrides.clear() self.app.dependency_overrides.clear()
super().tearDown() super().tearDown()
def _assert_vod_response(
self,
response,
expected_clips: list[tuple[str, int | None, int]],
) -> None:
"""Assert VOD clip metadata and its derived duration fields."""
assert response.status_code == 200
vod = response.json()
assert [
(
clip["path"],
clip.get("clipFrom"),
clip["keyFrameDurations"][0],
)
for clip in vod["sequences"][0]["clips"]
] == expected_clips
expected_durations = [clip[2] for clip in expected_clips]
assert vod["durations"] == expected_durations
assert vod["segment_duration"] == max(expected_durations)
def test_recordings_summary_across_dst_spring_forward(self): def test_recordings_summary_across_dst_spring_forward(self):
""" """
Test recordings summary across spring DST transition (spring forward). Test recordings summary across spring DST transition (spring forward).
@@ -404,6 +482,102 @@ class TestHttpMedia(BaseTestHttp):
assert "2024-03-10" in summary assert "2024-03-10" in summary
assert summary["2024-03-10"] is True assert summary["2024-03-10"] is True
def test_recordings_handles_all_range_relations(self):
"""Recordings return every interval relation that touches the range."""
with AuthTestClient(self.app) as client:
for case in RANGE_CASES:
with self.subTest(case=case.name):
Recordings.delete().execute()
super().insert_mock_recording(
case.name,
REQUEST_START + case.start_offset,
REQUEST_START + case.end_offset,
)
response = client.get(
"/front_door/recordings",
params={"after": REQUEST_START, "before": REQUEST_END},
)
assert response.status_code == 200
expected_ids = [case.name] if case.included_in_recordings else []
assert [
recording["id"] for recording in response.json()
] == expected_ids
def test_vod_handles_all_range_relations(self):
"""VOD clips every interval relation with positive playback duration."""
with (
AuthTestClient(self.app) as client,
patch(
"frigate.api.media.get_keyframe_before",
side_effect=lambda _path, offset: offset,
),
):
for case in RANGE_CASES:
with self.subTest(case=case.name):
Recordings.delete().execute()
super().insert_mock_recording(
case.name,
REQUEST_START + case.start_offset,
REQUEST_START + case.end_offset,
)
response = client.get(
f"/vod/front_door/start/{REQUEST_START}/end/{REQUEST_END}"
)
if case.vod_duration_ms is None:
assert response.status_code == 404
continue
self._assert_vod_response(
response,
[
(
case.name,
case.vod_clip_from_ms,
case.vod_duration_ms,
)
],
)
def test_vod_handles_segment_ending_at_start_with_keyframe_fallbacks(self):
"""VOD keeps a boundary segment when keyframe lookup extends it."""
def keyframe_before(path: str, offset: int) -> int | None:
return offset - 1000 if path == "previous_keyframe" else None
with (
AuthTestClient(self.app) as client,
patch(
"frigate.api.media.get_keyframe_before",
side_effect=keyframe_before,
),
):
super().insert_mock_recording(
"previous_keyframe",
REQUEST_START - 10,
REQUEST_START,
)
super().insert_mock_recording(
"missing_keyframe",
REQUEST_START - 5,
REQUEST_START,
)
response = client.get(
f"/vod/front_door/start/{REQUEST_START}/end/{REQUEST_END}"
)
self._assert_vod_response(
response,
[
("previous_keyframe", 9000, 1000),
("missing_keyframe", None, 5000),
],
)
def test_recordings_unavailable_reports_gap_between_recordings(self): def test_recordings_unavailable_reports_gap_between_recordings(self):
"""A gap between two recordings is reported as an unavailable segment.""" """A gap between two recordings is reported as an unavailable segment."""
with AuthTestClient(self.app) as client: with AuthTestClient(self.app) as client:
+267 -4
View File
@@ -1,13 +1,70 @@
"""Test camera user and password cleanup.""" """Tests for Birdseye canvas sizing and layout behavior."""
import multiprocessing as mp import multiprocessing as mp
import unittest import unittest
from unittest.mock import Mock
from frigate.config import FrigateConfig from frigate.config import BirdseyeModeConfig, FrigateConfig
from frigate.output.birdseye import BirdsEyeFrameManager, get_canvas_shape from frigate.output.birdseye import (
Birdseye,
BirdseyeActivity,
BirdsEyeFrameManager,
get_canvas_shape,
)
class TestBirdseye(unittest.TestCase): class TestBirdseye(unittest.TestCase):
def _build_manager(
self, camera_dimensions: dict[str, tuple[int, int]]
) -> BirdsEyeFrameManager:
config = {
"mqtt": {"host": "mqtt"},
"birdseye": {"width": 1280, "height": 720},
"cameras": {},
}
for order, (camera, dimensions) in enumerate(
camera_dimensions.items(), start=1
):
config["cameras"][camera] = {
"ffmpeg": {
"inputs": [
{
"path": f"rtsp://10.0.0.1:554/{camera}",
"roles": ["detect"],
}
]
},
"detect": {
"width": dimensions[0],
"height": dimensions[1],
"fps": 5,
},
"birdseye": {"order": order},
}
return BirdsEyeFrameManager(FrigateConfig(**config), mp.Event())
def _assert_no_overlaps(
self, layout: list[list[tuple[str, tuple[int, int, int, int]]]]
):
rectangles = [position for row in layout for _, position in row]
for index, rect in enumerate(rectangles):
x1, y1, width1, height1 = rect
for other in rectangles[index + 1 :]:
x2, y2, width2, height2 = other
overlap = (
x1 < x2 + width2
and x2 < x1 + width1
and y1 < y2 + height2
and y2 < y1 + height1
)
self.assertFalse(
overlap,
msg=f"Overlapping rectangles found: {rect} and {other}",
)
def test_16x9(self): def test_16x9(self):
"""Test 16x9 aspect ratio works as expected for birdseye.""" """Test 16x9 aspect ratio works as expected for birdseye."""
width = 1280 width = 1280
@@ -48,6 +105,212 @@ class TestBirdseye(unittest.TestCase):
assert canvas_width == width # width will be the same assert canvas_width == width # width will be the same
assert canvas_height != height assert canvas_height != height
def test_portrait_camera_does_not_overlap_next_row(self):
"""Portrait cameras should reserve their real horizontal position on the next row."""
manager = self._build_manager(
{
"cam_a": (1280, 720),
"cam_p": (360, 640),
"cam_b": (1280, 720),
"cam_c": (640, 480),
}
)
layout = manager.calculate_layout(["cam_a", "cam_p", "cam_b", "cam_c"], 3)
self.assertIsNotNone(layout)
assert layout is not None
self._assert_no_overlaps(layout)
cam_c = [
position for row in layout for camera, position in row if camera == "cam_c"
][0]
self.assertEqual(cam_c[0], 0)
def test_portrait_reservation_only_applies_to_next_row(self):
"""Portrait reservations should not push later rows after the span ends."""
manager = self._build_manager(
{
"cam_a": (1280, 720),
"cam_p": (360, 640),
"cam_b": (1280, 720),
"cam_c": (1280, 720),
"cam_d": (1280, 720),
"cam_e": (1280, 720),
}
)
layout = manager.calculate_layout(
["cam_a", "cam_p", "cam_b", "cam_c", "cam_d", "cam_e"],
3,
)
self.assertIsNotNone(layout)
assert layout is not None
self._assert_no_overlaps(layout)
cam_e = [
position for row in layout for camera, position in row if camera == "cam_e"
][0]
self.assertEqual(cam_e[0], 0)
def test_multiple_portraits_reserve_distinct_ranges(self):
"""Multiple portrait cameras in one row should reserve separate spans below them."""
manager = self._build_manager(
{
"cam_a": (640, 480),
"cam_p1": (360, 640),
"cam_p2": (360, 640),
"cam_b": (640, 480),
"cam_c": (1280, 720),
"cam_d": (640, 480),
}
)
layout = manager.calculate_layout(
["cam_a", "cam_p1", "cam_p2", "cam_b", "cam_c", "cam_d"],
4,
)
self.assertIsNotNone(layout)
assert layout is not None
self._assert_no_overlaps(layout)
def test_two_landscapes_then_portrait_then_two_landscapes(self):
"""A portrait after two landscapes should reserve only its own tail span."""
manager = self._build_manager(
{
"cam_a": (1280, 720),
"cam_b": (1280, 720),
"cam_p": (360, 640),
"cam_c": (1280, 720),
"cam_d": (1280, 720),
}
)
layout = manager.calculate_layout(
["cam_a", "cam_b", "cam_p", "cam_c", "cam_d"],
3,
)
self.assertIsNotNone(layout)
assert layout is not None
self._assert_no_overlaps(layout)
cam_c = [
position for row in layout for camera, position in row if camera == "cam_c"
][0]
cam_d = [
position for row in layout for camera, position in row if camera == "cam_d"
][0]
self.assertEqual(cam_c[0], 0)
self.assertEqual(cam_d[0], cam_c[0] + cam_c[2])
class TestBirdseyeActivity(unittest.TestCase):
"""Test which camera activity is included in each Birdseye mode."""
def setUp(self):
config = {
"mqtt": {"enabled": False},
"birdseye": {
"enabled": True,
"mode": {
"motion": True,
"objects": True,
"stationary_objects": True,
},
},
"cameras": {
"front": {
"ffmpeg": {
"inputs": [
{"path": "rtsp://10.0.0.1:554/video", "roles": ["detect"]}
]
},
"detect": {"height": 1080, "width": 1920, "fps": 5},
}
},
}
self.manager = BirdsEyeFrameManager(FrigateConfig(**config), mp.Event())
def test_existing_modes_keep_their_activity_rules(self):
continuous = BirdseyeModeConfig(continuous=True)
motion = BirdseyeModeConfig(motion=True)
objects = BirdseyeModeConfig(objects=True)
no_activity = BirdseyeActivity(False, False, False)
motion_activity = BirdseyeActivity(False, False, True)
stationary_activity = BirdseyeActivity(False, True, False)
active_object_activity = BirdseyeActivity(True, False, False)
assert self.manager.camera_active(continuous, no_activity)
assert self.manager.camera_active(motion, motion_activity)
assert not self.manager.camera_active(motion, stationary_activity)
assert self.manager.camera_active(objects, active_object_activity)
assert not self.manager.camera_active(objects, stationary_activity)
def test_modes_can_be_combined(self):
mode = BirdseyeModeConfig(motion=True, stationary_objects=True)
assert self.manager.camera_active(mode, BirdseyeActivity(False, False, True))
assert self.manager.camera_active(mode, BirdseyeActivity(False, True, False))
assert not self.manager.camera_active(
mode, BirdseyeActivity(False, False, False)
)
def test_stationary_objects_are_independent_from_active_objects(self):
stationary_objects = BirdseyeModeConfig(stationary_objects=True)
assert self.manager.camera_active(
stationary_objects, BirdseyeActivity(False, True, False)
)
assert not self.manager.camera_active(
stationary_objects, BirdseyeActivity(True, False, False)
)
def test_write_data_preserves_active_and_confirms_stationary_activity(self):
birdseye = Birdseye.__new__(Birdseye)
birdseye.birdseye_manager = Mock()
birdseye.birdseye_manager.update.return_value = (False, False)
birdseye._idle_interval = None
frame = Mock()
birdseye.write_data(
"front",
[
{"stationary": True, "false_positive": True},
{"stationary": False, "false_positive": True},
{"stationary": True, "false_positive": False},
],
[[0, 0, 10, 10]],
1.0,
frame,
)
birdseye.birdseye_manager.update.assert_called_once_with(
"front", BirdseyeActivity(True, True, True), 1.0, frame
)
def test_stationary_false_positive_does_not_activate_birdseye(self):
birdseye = Birdseye.__new__(Birdseye)
birdseye.birdseye_manager = Mock()
birdseye.birdseye_manager.update.return_value = (False, False)
birdseye._idle_interval = None
frame = Mock()
birdseye.write_data(
"front",
[{"stationary": True, "false_positive": True}],
[],
1.0,
frame,
)
birdseye.birdseye_manager.update.assert_called_once_with(
"front", BirdseyeActivity(False, False, False), 1.0, frame
)
class TestBirdseyeCameraOrder(unittest.TestCase): class TestBirdseyeCameraOrder(unittest.TestCase):
"""Test that birdseye reacts to camera order changes without a restart.""" """Test that birdseye reacts to camera order changes without a restart."""
@@ -55,7 +318,7 @@ class TestBirdseyeCameraOrder(unittest.TestCase):
def setUp(self): def setUp(self):
config = { config = {
"mqtt": {"enabled": False}, "mqtt": {"enabled": False},
"birdseye": {"enabled": True, "mode": "continuous"}, "birdseye": {"enabled": True, "mode": {"continuous": True}},
"cameras": { "cameras": {
camera: { camera: {
"ffmpeg": { "ffmpeg": {
+262 -48
View File
@@ -7,9 +7,11 @@ import numpy as np
from pydantic import ValidationError from pydantic import ValidationError
from ruamel.yaml.constructor import DuplicateKeyError from ruamel.yaml.constructor import DuplicateKeyError
from frigate.config import BirdseyeModeEnum, FrigateConfig from frigate.config import FrigateConfig
from frigate.const import MODEL_CACHE_DIR from frigate.const import MODEL_CACHE_DIR
from frigate.detectors import DetectorTypeEnum from frigate.detectors import DetectorTypeEnum
from frigate.detectors.detector_config import SceneEnum
from frigate.detectors.device import build_detector_config, runner_names
from frigate.util.builtin import deep_merge from frigate.util.builtin import deep_merge
@@ -64,49 +66,171 @@ class TestConfig(unittest.TestCase):
def test_config_class(self): def test_config_class(self):
frigate_config = FrigateConfig(**self.minimal) frigate_config = FrigateConfig(**self.minimal)
assert "cpu" in frigate_config.detectors.keys() model = frigate_config.primary_model
assert frigate_config.detectors["cpu"].type == DetectorTypeEnum.cpu assert model.scene == SceneEnum.all
assert frigate_config.detectors["cpu"].model.width == 320 assert model.width == 320
assert frigate_config.devices_for_model(model)[0].detector == (
DetectorTypeEnum.cpu
)
@patch("frigate.detectors.detector_config.load_labels") @patch("frigate.detectors.detector_config.load_labels")
def test_detector_custom_model_path(self, mock_labels): def test_model_custom_path(self, mock_labels):
mock_labels.return_value = {} mock_labels.return_value = {}
config = { config = {
"detectors": { "models": [
"cpu": {
"type": "cpu",
"model_path": "/cpu_model.tflite",
},
"edgetpu": {
"type": "edgetpu",
"model_path": "/edgetpu_model.tflite",
},
"openvino": {
"type": "openvino",
},
},
# needs to be a file that will exist, doesn't matter what # needs to be a file that will exist, doesn't matter what
"model": {"path": "/etc/hosts", "width": 512}, {"path": "/etc/hosts", "width": 512, "devices": ["openvino:GPU"]},
],
}
frigate_config = FrigateConfig(**(deep_merge(config, self.minimal)))
model = frigate_config.primary_model
assert model.path == "/etc/hosts"
assert model.width == 512
detector_config = build_detector_config(
frigate_config.devices_for_model(model)[0], model
)
assert detector_config.type == DetectorTypeEnum.openvino
assert detector_config.device == "GPU"
assert detector_config.model.path == "/etc/hosts"
@patch("frigate.detectors.detector_config.load_labels")
def test_model_default_paths_per_detector(self, mock_labels):
mock_labels.return_value = {}
for devices, expected in (
(["cpu"], "/cpu_model.tflite"),
(["edgetpu:pci:0"], "/edgetpu_model.tflite"),
(["openvino:CPU"], "/openvino-model/ssdlite_mobilenet_v2.xml"),
):
config = {"models": [{"devices": devices}]}
frigate_config = FrigateConfig(**(deep_merge(config, self.minimal)))
assert frigate_config.primary_model.path == expected
@patch("frigate.detectors.detector_config.load_labels")
def test_camera_picks_model_by_scene(self, mock_labels):
mock_labels.return_value = {}
config = {
"models": [
{"scene": "outdoor", "devices": ["cpu"], "width": 320},
{"scene": "indoor", "devices": ["openvino:CPU"], "width": 300},
],
"cameras": {
"back": {
"detect": {"scene": "outdoor"},
"ffmpeg": {
"inputs": [
{"path": "rtsp://10.0.0.1:554/video", "roles": ["detect"]},
]
},
},
"front": {
"detect": {"scene": "indoor"},
"ffmpeg": {
"inputs": [
{"path": "rtsp://10.0.0.2:554/video", "roles": ["detect"]},
]
},
},
},
} }
frigate_config = FrigateConfig(**(deep_merge(config, self.minimal))) frigate_config = FrigateConfig(**(deep_merge(config, self.minimal)))
assert "cpu" in frigate_config.detectors.keys() assert frigate_config.model_for_camera("back").scene == SceneEnum.outdoor
assert "edgetpu" in frigate_config.detectors.keys() assert frigate_config.model_for_camera("front").scene == SceneEnum.indoor
assert "openvino" in frigate_config.detectors.keys() assert frigate_config.model_for_camera("back").width == 320
assert frigate_config.model_for_camera("front").width == 300
assert frigate_config.detectors["cpu"].type == DetectorTypeEnum.cpu @patch("frigate.detectors.detector_config.load_labels")
assert frigate_config.detectors["edgetpu"].type == DetectorTypeEnum.edgetpu def test_camera_requires_a_scene_without_a_default(self, mock_labels):
assert frigate_config.detectors["openvino"].type == DetectorTypeEnum.openvino mock_labels.return_value = {}
config = {
"models": [
{"scene": "outdoor", "devices": ["cpu"]},
{"scene": "indoor", "devices": ["openvino:CPU"]},
],
}
assert frigate_config.detectors["cpu"].num_threads == 3 with self.assertRaises(ValidationError):
assert frigate_config.detectors["edgetpu"].device is None FrigateConfig(**(deep_merge(config, self.minimal)))
assert frigate_config.detectors["openvino"].device is None
assert frigate_config.model.path == "/etc/hosts" @patch("frigate.detectors.detector_config.load_labels")
assert frigate_config.detectors["cpu"].model.path == "/cpu_model.tflite" def test_camera_scene_must_match_a_model(self, mock_labels):
assert frigate_config.detectors["edgetpu"].model.path == "/edgetpu_model.tflite" mock_labels.return_value = {}
assert frigate_config.detectors["openvino"].model.path == "/etc/hosts" config = {
"models": [{"devices": ["cpu"]}],
"cameras": {
"back": {
"detect": {"scene": "outdoor"},
"ffmpeg": {
"inputs": [
{"path": "rtsp://10.0.0.1:554/video", "roles": ["detect"]},
]
},
},
},
}
with self.assertRaises(ValidationError):
FrigateConfig(**(deep_merge(config, self.minimal)))
@patch("frigate.detectors.detector_config.load_labels")
def test_models_must_use_unique_scenes(self, mock_labels):
mock_labels.return_value = {}
config = {
"models": [
{"scene": "outdoor", "devices": ["cpu"]},
{"scene": "outdoor", "devices": ["openvino:CPU"]},
],
}
with self.assertRaises(ValidationError):
FrigateConfig(**(deep_merge(config, self.minimal)))
@patch("frigate.detectors.detector_config.load_labels")
def test_model_devices_must_share_a_detector(self, mock_labels):
mock_labels.return_value = {}
config = {"models": [{"devices": ["cpu", "openvino:CPU"]}]}
with self.assertRaises(ValidationError):
FrigateConfig(**(deep_merge(config, self.minimal)))
@patch("frigate.detectors.detector_config.load_labels")
def test_model_requires_a_known_detector(self, mock_labels):
mock_labels.return_value = {}
config = {"models": [{"devices": ["not_a_detector:0"]}]}
with self.assertRaises(ValidationError):
FrigateConfig(**(deep_merge(config, self.minimal)))
@patch("frigate.detectors.detector_config.load_labels")
def test_model_requires_a_device(self, mock_labels):
mock_labels.return_value = {}
config = {"models": [{"devices": []}]}
with self.assertRaises(ValidationError):
FrigateConfig(**(deep_merge(config, self.minimal)))
@patch("frigate.detectors.detector_config.load_labels")
def test_shareable_devices_may_repeat(self, mock_labels):
mock_labels.return_value = {}
config = {"models": [{"devices": ["openvino:GPU", "openvino:GPU"]}]}
frigate_config = FrigateConfig(**(deep_merge(config, self.minimal)))
devices = frigate_config.devices_for_model(frigate_config.primary_model)
assert runner_names(devices) == ["openvino:GPU", "openvino:GPU#2"]
@patch("frigate.detectors.detector_config.load_labels")
def test_exclusive_devices_may_not_repeat(self, mock_labels):
mock_labels.return_value = {}
config = {"models": [{"devices": ["edgetpu:pci:0", "edgetpu:pci:0"]}]}
with self.assertRaises(ValidationError):
FrigateConfig(**(deep_merge(config, self.minimal)))
def test_invalid_mqtt_config(self): def test_invalid_mqtt_config(self):
config = { config = {
@@ -170,7 +294,7 @@ class TestConfig(unittest.TestCase):
def test_override_birdseye(self): def test_override_birdseye(self):
config = { config = {
"mqtt": {"host": "mqtt"}, "mqtt": {"host": "mqtt"},
"birdseye": {"enabled": True, "mode": "continuous"}, "birdseye": {"enabled": True, "mode": {"continuous": True}},
"cameras": { "cameras": {
"back": { "back": {
"ffmpeg": { "ffmpeg": {
@@ -183,19 +307,30 @@ class TestConfig(unittest.TestCase):
"width": 1920, "width": 1920,
"fps": 5, "fps": 5,
}, },
"birdseye": {"enabled": False, "mode": "motion"}, "birdseye": {
"enabled": False,
"mode": {"continuous": False, "motion": True},
},
} }
}, },
} }
frigate_config = FrigateConfig(**config) frigate_config = FrigateConfig(**config)
assert not frigate_config.cameras["back"].birdseye.enabled assert not frigate_config.cameras["back"].birdseye.enabled
assert frigate_config.cameras["back"].birdseye.mode is BirdseyeModeEnum.motion mode = frigate_config.cameras["back"].birdseye.mode
assert mode.motion
assert not mode.continuous
assert not mode.objects
assert not mode.stationary_objects
def test_override_birdseye_non_inheritable(self): def test_override_birdseye_non_inheritable(self):
config = { config = {
"mqtt": {"host": "mqtt"}, "mqtt": {"host": "mqtt"},
"birdseye": {"enabled": True, "mode": "continuous", "height": 1920}, "birdseye": {
"enabled": True,
"mode": {"continuous": True},
"height": 1920,
},
"cameras": { "cameras": {
"back": { "back": {
"ffmpeg": { "ffmpeg": {
@@ -218,7 +353,7 @@ class TestConfig(unittest.TestCase):
def test_inherit_birdseye(self): def test_inherit_birdseye(self):
config = { config = {
"mqtt": {"host": "mqtt"}, "mqtt": {"host": "mqtt"},
"birdseye": {"enabled": True, "mode": "continuous"}, "birdseye": {"enabled": True, "mode": {"continuous": True}},
"cameras": { "cameras": {
"back": { "back": {
"ffmpeg": { "ffmpeg": {
@@ -237,9 +372,89 @@ class TestConfig(unittest.TestCase):
frigate_config = FrigateConfig(**config) frigate_config = FrigateConfig(**config)
assert frigate_config.cameras["back"].birdseye.enabled assert frigate_config.cameras["back"].birdseye.enabled
assert ( mode = frigate_config.cameras["back"].birdseye.mode
frigate_config.cameras["back"].birdseye.mode is BirdseyeModeEnum.continuous assert mode.continuous
) assert not mode.motion
assert not mode.objects
assert not mode.stationary_objects
def test_combine_birdseye_activity_types(self):
config = {
**self.minimal,
"birdseye": {
"mode": {
"motion": True,
"stationary_objects": True,
}
},
}
frigate_config = FrigateConfig(**config)
mode = frigate_config.cameras["back"].birdseye.mode
assert mode.motion
assert mode.stationary_objects
assert not mode.continuous
assert not mode.objects
def test_birdseye_requires_an_activity_type(self):
config = {
**self.minimal,
"birdseye": {
"mode": {
"continuous": False,
"motion": False,
"objects": False,
"stationary_objects": False,
}
},
}
with self.assertRaisesRegex(
ValidationError, "must enable at least one Birdseye activity type"
):
FrigateConfig(**config)
def test_camera_can_disable_an_inherited_activity_type(self):
config = {
**self.minimal,
"birdseye": {"mode": {"motion": True, "objects": True}},
}
config["cameras"]["back"]["birdseye"] = {"mode": {"motion": False}}
frigate_config = FrigateConfig(**config)
mode = frigate_config.cameras["back"].birdseye.mode
assert not mode.motion
assert mode.objects
def test_profile_must_leave_an_activity_type_enabled(self):
config = {
**self.minimal,
"profiles": {"away": {"friendly_name": "Away"}},
"birdseye": {"mode": {"objects": True}},
}
config["cameras"]["back"]["profiles"] = {
"away": {"birdseye": {"mode": {"objects": False}}}
}
with self.assertRaisesRegex(
ValidationError, "must enable at least one Birdseye activity type"
):
FrigateConfig(**config)
def test_camera_birdseye_activity_types_override_global_values(self):
config = {
**self.minimal,
"birdseye": {"mode": {"motion": True, "objects": True}},
}
config["cameras"]["back"]["birdseye"] = {
"mode": {"motion": False, "stationary_objects": True}
}
frigate_config = FrigateConfig(**config)
mode = frigate_config.cameras["back"].birdseye.mode
assert not mode.motion
assert mode.objects
assert mode.stationary_objects
def test_override_tracked_objects(self): def test_override_tracked_objects(self):
config = { config = {
@@ -956,7 +1171,7 @@ class TestConfig(unittest.TestCase):
def test_merge_labelmap(self): def test_merge_labelmap(self):
config = { config = {
"mqtt": {"host": "mqtt"}, "mqtt": {"host": "mqtt"},
"model": {"labelmap": {7: "truck"}}, "models": [{"labelmap": {7: "truck"}, "devices": ["cpu"]}],
"cameras": { "cameras": {
"back": { "back": {
"ffmpeg": { "ffmpeg": {
@@ -977,7 +1192,7 @@ class TestConfig(unittest.TestCase):
} }
frigate_config = FrigateConfig(**config) frigate_config = FrigateConfig(**config)
assert frigate_config.model.merged_labelmap[7] == "truck" assert frigate_config.primary_model.merged_labelmap[7] == "truck"
def test_default_labelmap_empty(self): def test_default_labelmap_empty(self):
config = { config = {
@@ -1002,12 +1217,12 @@ class TestConfig(unittest.TestCase):
} }
frigate_config = FrigateConfig(**config) frigate_config = FrigateConfig(**config)
assert frigate_config.model.merged_labelmap[0] == "person" assert frigate_config.primary_model.merged_labelmap[0] == "person"
def test_default_labelmap(self): def test_default_labelmap(self):
config = { config = {
"mqtt": {"host": "mqtt"}, "mqtt": {"host": "mqtt"},
"model": {"width": 320, "height": 320}, "models": [{"width": 320, "height": 320, "devices": ["cpu"]}],
"cameras": { "cameras": {
"back": { "back": {
"ffmpeg": { "ffmpeg": {
@@ -1028,7 +1243,7 @@ class TestConfig(unittest.TestCase):
} }
frigate_config = FrigateConfig(**config) frigate_config = FrigateConfig(**config)
assert frigate_config.model.merged_labelmap[0] == "person" assert frigate_config.primary_model.merged_labelmap[0] == "person"
def test_plus_labelmap(self): def test_plus_labelmap(self):
with open(os.path.join(MODEL_CACHE_DIR, "test"), "w") as f: with open(os.path.join(MODEL_CACHE_DIR, "test"), "w") as f:
@@ -1038,8 +1253,7 @@ class TestConfig(unittest.TestCase):
config = { config = {
"mqtt": {"host": "mqtt"}, "mqtt": {"host": "mqtt"},
"detectors": {"cpu": {"type": "cpu"}}, "models": [{"path": "plus://test", "devices": ["cpu"]}],
"model": {"path": "plus://test"},
"cameras": { "cameras": {
"back": { "back": {
"ffmpeg": { "ffmpeg": {
@@ -1060,7 +1274,7 @@ class TestConfig(unittest.TestCase):
} }
frigate_config = FrigateConfig(**config) frigate_config = FrigateConfig(**config)
assert frigate_config.model.merged_labelmap[0] == "amazon" assert frigate_config.primary_model.merged_labelmap[0] == "amazon"
def test_fails_on_invalid_role(self): def test_fails_on_invalid_role(self):
config = { config = {
+225
View File
@@ -0,0 +1,225 @@
"""Tests for migrating detectors and model into the models list."""
import logging
import os
import tempfile
import unittest
from unittest.mock import patch
from ruamel.yaml import YAML
from frigate.util.config import (
CURRENT_CONFIG_VERSION,
migrate_frigate_config,
migrate_models,
)
class TestMigrateModels(unittest.TestCase):
def test_single_cpu_detector(self):
migrated = migrate_models({"detectors": {"cpu": {"type": "cpu"}}})
self.assertEqual(migrated["models"], [{"scene": "all", "devices": ["cpu"]}])
self.assertNotIn("detectors", migrated)
def test_model_settings_are_carried_over(self):
migrated = migrate_models(
{
"detectors": {"coral": {"type": "edgetpu", "device": "pci:0"}},
"model": {"path": "plus://abc", "width": 320},
}
)
self.assertEqual(
migrated["models"],
[
{
"scene": "all",
"path": "plus://abc",
"width": 320,
"devices": ["edgetpu:pci:0"],
}
],
)
self.assertNotIn("model", migrated)
def test_multiple_corals_become_multiple_devices(self):
migrated = migrate_models(
{
"detectors": {
"coral1": {"type": "edgetpu", "device": "pci:0"},
"coral2": {"type": "edgetpu", "device": "pci:1"},
}
}
)
self.assertEqual(
migrated["models"][0]["devices"], ["edgetpu:pci:0", "edgetpu:pci:1"]
)
def test_several_detectors_on_one_device_stay_separate(self):
# a repeated device is now what running two inference processes on one
# piece of hardware looks like
migrated = migrate_models(
{
"detectors": {
"ov_0": {"type": "openvino", "device": "GPU"},
"ov_1": {"type": "openvino", "device": "GPU"},
}
}
)
self.assertEqual(
migrated["models"][0]["devices"], ["openvino:GPU", "openvino:GPU"]
)
def test_repeated_exclusive_devices_are_collapsed(self):
# two detectors both grabbing the first TPU was never really two TPUs
migrated = migrate_models(
{
"detectors": {
"coral_0": {"type": "edgetpu", "device": "usb"},
"coral_1": {"type": "edgetpu", "device": "usb"},
}
}
)
self.assertEqual(migrated["models"][0]["devices"], ["edgetpu:usb"])
def test_detectors_that_named_the_device_field_differently(self):
migrated = migrate_models(
{
"detectors": {
"rk": {"type": "rknn", "num_cores": 2},
}
}
)
self.assertEqual(migrated["models"][0]["devices"], ["rknn:2"])
def test_empty_edgetpu_device_is_kept(self):
# an empty device selects a native Coral, which is not the same as
# letting the delegate pick
migrated = migrate_models(
{"detectors": {"coral": {"type": "edgetpu", "device": ""}}}
)
self.assertEqual(migrated["models"][0]["devices"], ["edgetpu:"])
def test_model_path_overrides_the_model(self):
migrated = migrate_models(
{
"detectors": {
"coral": {"type": "edgetpu", "model_path": "/custom.tflite"}
},
"model": {"path": "/ignored.tflite", "width": 320},
}
)
self.assertEqual(migrated["models"][0]["path"], "/custom.tflite")
def test_no_detectors_falls_back_to_cpu(self):
migrated = migrate_models({"model": {"width": 320}})
self.assertEqual(migrated["models"][0]["devices"], ["cpu"])
def test_dropped_remote_detector_options_are_logged(self):
with self.assertLogs("frigate.util.config", level=logging.ERROR) as logs:
migrated = migrate_models(
{
"detectors": {
"ds": {
"type": "deepstack",
"api_url": "http://host:5000/v1/vision/detection",
"api_key": "secret",
}
}
}
)
self.assertEqual(
migrated["models"][0]["devices"],
["deepstack:http://host:5000/v1/vision/detection"],
)
self.assertTrue(any("api_key" in message for message in logs.output))
def test_mixed_detector_types_are_logged(self):
with self.assertLogs("frigate.util.config", level=logging.ERROR) as logs:
migrate_models(
{
"detectors": {
"ov": {"type": "openvino", "device": "GPU"},
"coral": {"type": "edgetpu", "device": "pci:0"},
}
}
)
self.assertTrue(any("more than one type" in message for message in logs.output))
def test_other_keys_are_untouched(self):
migrated = migrate_models(
{"mqtt": {"host": "mqtt"}, "detectors": {"cpu": {"type": "cpu"}}}
)
self.assertEqual(migrated["mqtt"], {"host": "mqtt"})
class TestMigrateConfigFile(unittest.TestCase):
"""The full file migration, which is gated on shape as well as version."""
def setUp(self):
self.temp_dir = tempfile.TemporaryDirectory()
self.addCleanup(self.temp_dir.cleanup)
self.config_file = os.path.join(self.temp_dir.name, "config.yml")
patcher = patch("frigate.util.config.CONFIG_DIR", self.temp_dir.name)
patcher.start()
self.addCleanup(patcher.stop)
def _migrate(self, config: str) -> dict:
with open(self.config_file, "w") as f:
f.write(config)
migrate_frigate_config(self.config_file)
with open(self.config_file) as f:
return YAML().load(f)
def test_migrates_a_config_already_stamped_with_the_current_version(self):
# 0.19 is unreleased, so a dev config can be current and still use
# the pre-models keys
migrated = self._migrate(
"mqtt:\n"
" enabled: false\n"
"detectors:\n"
" ov:\n"
" type: openvino\n"
" device: GPU\n"
"cameras: {}\n"
f"version: {CURRENT_CONFIG_VERSION}\n"
)
self.assertEqual(migrated["models"][0]["devices"], ["openvino:GPU"])
self.assertNotIn("detectors", migrated)
def test_a_migrated_config_is_left_alone(self):
migrated = self._migrate(
"mqtt:\n"
" enabled: false\n"
"models:\n"
" - scene: all\n"
" devices:\n"
" - openvino:GPU\n"
"cameras: {}\n"
f"version: {CURRENT_CONFIG_VERSION}\n"
)
self.assertEqual(
migrated["models"], [{"scene": "all", "devices": ["openvino:GPU"]}]
)
self.assertFalse(
os.path.exists(os.path.join(self.temp_dir.name, "backup_config.yaml"))
)
if __name__ == "__main__":
unittest.main(verbosity=2)
+94
View File
@@ -0,0 +1,94 @@
"""Tests for parsing detection hardware device strings."""
import unittest
from frigate.detectors.detector_config import ModelConfig
from frigate.detectors.device import (
DeviceParseError,
build_detector_config,
parse_device,
runner_names,
)
class TestParseDevice(unittest.TestCase):
def test_bare_detector_has_no_device(self):
spec = parse_device("cpu")
self.assertEqual(spec.detector, "cpu")
self.assertIsNone(spec.device)
def test_device_is_everything_after_the_first_colon(self):
spec = parse_device("edgetpu:pci:0")
self.assertEqual(spec.detector, "edgetpu")
self.assertEqual(spec.device, "pci:0")
def test_trailing_colon_keeps_an_empty_device(self):
# an empty edgetpu device selects a native Coral
spec = parse_device("edgetpu:")
self.assertEqual(spec.detector, "edgetpu")
self.assertEqual(spec.device, "")
def test_unknown_detector_is_rejected(self):
with self.assertRaises(DeviceParseError):
parse_device("not_a_detector:0")
def test_device_that_the_detector_cannot_use_is_rejected(self):
# tensorrt takes a gpu index
with self.assertRaises(DeviceParseError):
parse_device("tensorrt:the-fast-one")
class TestBuildDetectorConfig(unittest.TestCase):
def _build(self, raw: str):
return build_detector_config(parse_device(raw), ModelConfig())
def test_device_lands_on_the_detector_field(self):
for raw, expected in (
("edgetpu:usb", "usb"),
("edgetpu:pci:1", "pci:1"),
("openvino:GPU.1", "GPU.1"),
("onnx:CPU", "CPU"),
("memryx:PCIe:0", "PCIe:0"),
):
with self.subTest(raw=raw):
self.assertEqual(self._build(raw).device, expected)
def test_detectors_that_name_the_field_something_else(self):
self.assertEqual(self._build("cpu:4").num_threads, 4)
self.assertEqual(self._build("rknn:2").num_cores, 2)
def test_device_is_coerced_to_the_detector_field_type(self):
self.assertEqual(self._build("tensorrt:1").device, 1)
def test_omitted_device_falls_back_to_the_detector_default(self):
self.assertEqual(self._build("cpu").num_threads, 3)
self.assertEqual(self._build("rknn").num_cores, 0)
self.assertEqual(self._build("openvino").device, "AUTO")
self.assertIsNone(self._build("edgetpu").device)
def test_the_model_is_attached(self):
model = ModelConfig(path="/cpu_model.tflite")
self.assertIs(build_detector_config(parse_device("cpu"), model).model, model)
class TestRunnerNames(unittest.TestCase):
def test_unique_devices_keep_their_name(self):
devices = [parse_device("edgetpu:pci:0"), parse_device("edgetpu:pci:1")]
self.assertEqual(runner_names(devices), ["edgetpu:pci:0", "edgetpu:pci:1"])
def test_repeated_devices_are_numbered(self):
devices = [parse_device("openvino:GPU")] * 3
self.assertEqual(
runner_names(devices),
["openvino:GPU", "openvino:GPU#2", "openvino:GPU#3"],
)
if __name__ == "__main__":
unittest.main(verbosity=2)
@@ -8,6 +8,7 @@ from unittest.mock import MagicMock, patch
from frigate.app import FrigateApp from frigate.app import FrigateApp
from frigate.comms.dispatcher import Dispatcher from frigate.comms.dispatcher import Dispatcher
from frigate.comms.runtime_state import RuntimeStatePersistence from frigate.comms.runtime_state import RuntimeStatePersistence
from frigate.config import BirdseyeModeConfig
def _make_camera_mock( def _make_camera_mock(
@@ -51,6 +52,58 @@ def _build_dispatcher(cameras: dict[str, MagicMock]) -> Dispatcher:
return Dispatcher(config, config_updater, onvif, ptz_metrics, communicators) return Dispatcher(config, config_updater, onvif, ptz_metrics, communicators)
class TestBirdseyeModeCommands(unittest.TestCase):
"""Verify Birdseye mode commands use the boolean mode contract."""
def setUp(self) -> None:
self.camera = _make_camera_mock()
self.camera.birdseye.enabled = True
self.dispatcher = _build_dispatcher({"front_door": self.camera})
self.dispatcher.publish = MagicMock()
def test_combined_modes_are_accepted(self) -> None:
self.dispatcher._on_birdseye_mode_command(
"front_door", "STATIONARY_OBJECTS,MOTION"
)
self.assertEqual(
self.camera.birdseye.mode,
BirdseyeModeConfig(motion=True, stationary_objects=True),
)
self.dispatcher.config_updater.publish_update.assert_called_once()
self.dispatcher.publish.assert_called_once_with(
"front_door/birdseye_mode/state",
"MOTION,STATIONARY_OBJECTS",
retain=True,
)
def test_single_activity_type_is_accepted(self) -> None:
self.dispatcher._on_birdseye_mode_command("front_door", "OBJECTS")
self.assertEqual(
self.camera.birdseye.mode,
BirdseyeModeConfig(objects=True),
)
self.dispatcher.publish.assert_called_once_with(
"front_door/birdseye_mode/state", "OBJECTS", retain=True
)
def test_unknown_mode_is_rejected(self) -> None:
for payload in (
"UNKNOWN",
"motion",
"MOTION_OBJECTS",
"NONE",
"NONE,MOTION",
"MOTION,MOTION",
"MOTION,",
):
with self.subTest(payload=payload):
self.dispatcher._on_birdseye_mode_command("front_door", payload)
self.dispatcher.config_updater.publish_update.assert_not_called()
class TestRestoreRuntimeState(unittest.TestCase): class TestRestoreRuntimeState(unittest.TestCase):
"""Verify replay routes through handlers and tolerates missing entries.""" """Verify replay routes through handlers and tolerates missing entries."""
+88 -1
View File
@@ -1,7 +1,12 @@
import unittest import unittest
from io import StringIO
from unittest.mock import MagicMock, patch from unittest.mock import MagicMock, patch
from frigate.util.services import get_amd_gpu_stats, get_intel_gpu_stats from frigate.util.services import (
get_amd_gpu_stats,
get_intel_gpu_stats,
get_openvino_npu_stats,
)
class TestGpuStats(unittest.TestCase): class TestGpuStats(unittest.TestCase):
@@ -17,6 +22,88 @@ class TestGpuStats(unittest.TestCase):
amd_stats = get_amd_gpu_stats() amd_stats = get_amd_gpu_stats()
assert amd_stats == {"gpu": "4.17%", "mem": "60.37%"} assert amd_stats == {"gpu": "4.17%", "mem": "60.37%"}
@patch("frigate.util.services.time.sleep")
@patch("frigate.util.services.time.time", side_effect=[0.0, 1.0])
@patch(
"frigate.util.services.os.readlink",
return_value="/sys/bus/pci/drivers/intel_vpu",
)
@patch(
"frigate.util.services.glob.glob",
return_value=["/sys/class/accel/accel0"],
)
@patch(
"builtins.open",
side_effect=[StringIO("1000"), StringIO("1250")],
)
def test_openvino_npu_stats_discovers_accel0(
self, open_file, glob, readlink, time, sleep
):
assert get_openvino_npu_stats() == {"npu": "25.0", "mem": "-%"}
open_file.assert_any_call(
"/sys/class/accel/accel0/device/power/runtime_active_time"
)
@patch("frigate.util.services.time.sleep")
@patch("frigate.util.services.time.time", side_effect=[0.0, 1.0])
@patch(
"frigate.util.services.os.readlink",
side_effect=[
"/sys/bus/pci/drivers/other",
"/sys/bus/pci/drivers/intel_vpu",
],
)
@patch(
"frigate.util.services.glob.glob",
return_value=[
"/sys/class/accel/accel0",
"/sys/class/accel/accel1",
],
)
@patch(
"builtins.open",
side_effect=[StringIO("1000"), StringIO("1250")],
)
def test_openvino_npu_stats_skips_non_intel_accelerator(
self, open_file, glob, readlink, time, sleep
):
assert get_openvino_npu_stats() == {"npu": "25.0", "mem": "-%"}
open_file.assert_any_call(
"/sys/class/accel/accel1/device/power/runtime_active_time"
)
@patch(
"frigate.util.services.os.readlink",
return_value="/sys/bus/pci/drivers/other",
)
@patch(
"frigate.util.services.glob.glob",
return_value=["/sys/class/accel/accel0"],
)
@patch("builtins.open")
def test_openvino_npu_stats_no_intel_accelerator(self, open_file, glob, readlink):
assert get_openvino_npu_stats() is None
open_file.assert_not_called()
@patch(
"frigate.util.services.os.readlink",
return_value="/sys/bus/pci/drivers/intel_vpu",
)
@patch(
"frigate.util.services.glob.glob",
return_value=["/sys/class/accel/accel0"],
)
@patch("builtins.open", side_effect=FileNotFoundError)
def test_openvino_npu_stats_runtime_counter_unavailable(
self, open_file, glob, readlink
):
assert get_openvino_npu_stats() is None
open_file.assert_called_once_with(
"/sys/class/accel/accel0/device/power/runtime_active_time"
)
@patch("frigate.stats.intel_gpu_info.intel_gpu_name_resolver.get_names") @patch("frigate.stats.intel_gpu_info.intel_gpu_name_resolver.get_names")
@patch("frigate.util.services.time.sleep") @patch("frigate.util.services.time.sleep")
@patch("frigate.util.services.time.monotonic") @patch("frigate.util.services.time.monotonic")
+19
View File
@@ -560,6 +560,25 @@ class TestProfileManager(unittest.TestCase):
assert err is None assert err is None
assert self.config.cameras["front"].enabled is False assert self.config.cameras["front"].enabled is False
@patch.object(ProfileManager, "_persist_active_profile")
def test_profile_can_disable_inherited_birdseye_activity(self, mock_persist):
"""A false-only mode override inherits the other base activity types."""
self.config.profiles["away"] = ProfileDefinitionConfig(friendly_name="Away")
base_mode = self.config.cameras["front"].birdseye.mode
base_mode.motion = True
base_mode.objects = True
self.config.cameras["front"].profiles["away"] = CameraProfileConfig(
birdseye={"mode": {"motion": False}}
)
self.manager = ProfileManager(self.config, self.mock_updater)
err = self.manager.activate_profile("away")
assert err is None
mode = self.config.cameras["front"].birdseye.mode
assert not mode.motion
assert mode.objects
@patch.object(ProfileManager, "_persist_active_profile") @patch.object(ProfileManager, "_persist_active_profile")
def test_deactivate_restores_enabled(self, mock_persist): def test_deactivate_restores_enabled(self, mock_persist):
"""Deactivating a profile restores the camera's base enabled state.""" """Deactivating a profile restores the camera's base enabled state."""
+1 -1
View File
@@ -209,7 +209,7 @@ class TrackedObjectProcessor(threading.Thread):
if obj.obj_data.get("sub_label"): if obj.obj_data.get("sub_label"):
sub_label = obj.obj_data["sub_label"][0] sub_label = obj.obj_data["sub_label"][0]
if sub_label in self.config.model.all_attribute_logos: if sub_label in self.config.all_attribute_logos:
self.dispatcher.publish( self.dispatcher.publish(
f"{camera}/{sub_label}/snapshot", f"{camera}/{sub_label}/snapshot",
jpg_bytes, jpg_bytes,
+157 -2
View File
@@ -20,9 +20,28 @@ from frigate.util.services import get_video_properties
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
CURRENT_CONFIG_VERSION = "0.18-0" CURRENT_CONFIG_VERSION = "0.19-0"
DEFAULT_CONFIG_FILE = os.path.join(CONFIG_DIR, "config.yml") DEFAULT_CONFIG_FILE = os.path.join(CONFIG_DIR, "config.yml")
# the detector field that used to hold the device, for detectors that named it
# something other than "device"
DETECTOR_DEVICE_FIELDS = {
"cpu": "num_threads",
"rknn": "num_cores",
"deepstack": "api_url",
"degirum": "location",
"zmq": "endpoint",
}
# detector options that have no equivalent in a device string. The remote
# detectors that use them are being reworked, so they are dropped rather than
# carried over.
DROPPED_DETECTOR_OPTIONS = {
"deepstack": ["api_timeout", "api_key"],
"degirum": ["zoo", "token"],
"zmq": ["request_timeout_ms", "linger_ms"],
}
def resolve_ffmpeg_path(path: str, binary: str = "ffmpeg") -> str: def resolve_ffmpeg_path(path: str, binary: str = "ffmpeg") -> str:
"""Resolve an ffmpeg version alias or custom path to a binary path. """Resolve an ffmpeg version alias or custom path to a binary path.
@@ -87,12 +106,17 @@ def migrate_frigate_config(config_file: str):
previous_version = str(config.get("version", "0.13")) previous_version = str(config.get("version", "0.13"))
if previous_version == CURRENT_CONFIG_VERSION: # 0.19 is unreleased, so a config may already be stamped with the current
# version and still use the pre-models detectors and model keys
needs_models = "detectors" in config or "model" in config
if previous_version == CURRENT_CONFIG_VERSION and not needs_models:
logger.info("frigate config does not need migration...") logger.info("frigate config does not need migration...")
return return
logger.info("copying config as backup...") logger.info("copying config as backup...")
shutil.copy(config_file, os.path.join(CONFIG_DIR, "backup_config.yaml")) shutil.copy(config_file, os.path.join(CONFIG_DIR, "backup_config.yaml"))
new_config = config
if previous_version < "0.14": if previous_version < "0.14":
logger.info(f"Migrating frigate config from {previous_version} to 0.14...") logger.info(f"Migrating frigate config from {previous_version} to 0.14...")
@@ -147,6 +171,19 @@ def migrate_frigate_config(config_file: str):
yaml.dump(new_config, f) yaml.dump(new_config, f)
previous_version = "0.18-0" previous_version = "0.18-0"
if previous_version < "0.19-0":
logger.info(f"Migrating frigate config from {previous_version} to 0.19-0...")
new_config = migrate_019_0(new_config)
with open(config_file, "w") as f:
yaml.dump(new_config, f)
previous_version = "0.19-0"
if needs_models:
logger.info("Migrating frigate detectors and model to models...")
new_config = migrate_models(new_config)
with open(config_file, "w") as f:
yaml.dump(new_config, f)
logger.info("Finished frigate config migration...") logger.info("Finished frigate config migration...")
@@ -525,6 +562,21 @@ def _convert_legacy_mask_to_dict(
return result return result
def _migrate_birdseye_mode(birdseye: dict[str, Any] | None) -> None:
"""Convert a scalar Birdseye mode to composable activity types."""
if not birdseye or not isinstance(birdseye.get("mode"), str):
return
legacy_mode = birdseye["mode"]
activity_types = ("continuous", "motion", "objects", "stationary_objects")
if legacy_mode not in activity_types:
return
birdseye["mode"] = {
activity_type: activity_type == legacy_mode for activity_type in activity_types
}
def migrate_018_0(config: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]]: def migrate_018_0(config: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]]:
"""Handle migrating frigate config to 0.18-0""" """Handle migrating frigate config to 0.18-0"""
new_config = config.copy() new_config = config.copy()
@@ -658,6 +710,109 @@ def migrate_018_0(config: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]
return new_config return new_config
def migrate_019_0(config: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]]:
"""Handle migrating Frigate config to 0.19-0."""
new_config = config.copy()
_migrate_birdseye_mode(new_config.get("birdseye"))
for name, camera in new_config.get("cameras", {}).items():
camera_config: dict[str, dict[str, Any]] = camera.copy()
_migrate_birdseye_mode(camera_config.get("birdseye"))
for profile in camera_config.get("profiles", {}).values():
if isinstance(profile, dict):
_migrate_birdseye_mode(profile.get("birdseye"))
new_config["cameras"][name] = camera_config
new_config["version"] = "0.19-0"
return new_config
def migrate_models(config: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]]:
"""Merge the detectors and model keys into a single models list.
Every config before this change ran one model across all of its detectors,
so this always produces exactly one model.
Args:
config: The loaded config
Returns:
The config with a models list in place of detectors and model
"""
# imported lazily so loading the detector plugins is not a cost of importing
# this module
from frigate.detectors.detector_types import config_types
new_config = config.copy()
detectors: dict[str, Any] = new_config.pop("detectors", None) or {}
model: dict[str, Any] = new_config.pop("model", None) or {}
devices: list[str] = []
model_path: str | None = None
for name, detector in detectors.items():
detector = detector or {}
detector_type = detector.get("type", "cpu")
device = detector.get(DETECTOR_DEVICE_FIELDS.get(detector_type, "device"))
device_string = detector_type if device is None else f"{detector_type}:{device}"
# repeating a device now means running an extra inference process on it,
# which is what several detectors on one device used to mean. Only
# collapse repeats of hardware that can serve a single process.
config_class = config_types.get(detector_type)
shareable = config_class.shareable if config_class else True
if shareable or device_string not in devices:
devices.append(device_string)
dropped = [
option
for option in DROPPED_DETECTOR_OPTIONS.get(detector_type, [])
if option in detector
]
if dropped:
logger.error(
"Detector '%s' had the %s options set, which are no longer supported and have been removed",
name,
", ".join(dropped),
)
detector_model_path = detector.get("model_path")
if detector_model_path:
if model_path is None:
model_path = detector_model_path
elif model_path != detector_model_path:
logger.warning(
"Detector '%s' set a different model_path than an earlier detector, using '%s' for the migrated model",
name,
model_path,
)
detector_types = {device.partition(":")[0] for device in devices}
if len(detector_types) > 1:
logger.error(
"Detectors of more than one type (%s) were configured. A model now runs on one detector type, so the migrated config will need to be corrected by hand",
", ".join(sorted(detector_types)),
)
entry: dict[str, Any] = {"scene": "all", **model}
if model_path:
entry["path"] = model_path
# a config with no detectors ran a single cpu detector
entry["devices"] = devices or ["cpu"]
new_config["models"] = [entry]
return new_config
def get_relative_coordinates( def get_relative_coordinates(
mask: str | list | None, mask: str | list | None,
frame_shape: tuple[int, int], frame_shape: tuple[int, int],
+209
View File
@@ -0,0 +1,209 @@
"""Aggregation of the known sub label names an object can be tagged with."""
import logging
import os
from pathvalidate import sanitize_filename
from frigate.config import FrigateConfig
from frigate.config.classification import ObjectClassificationType
from frigate.const import CLIPS_DIR, FACE_DIR, MODEL_CACHE_DIR
from frigate.util.builtin import load_labels
logger = logging.getLogger(__name__)
# subdirectory of FACE_DIR holding unassigned training images, not a face name
FACE_TRAIN_DIR = "train"
# category used by classification models for "no match", never attached to an object
CLASSIFICATION_NONE_CATEGORY = "none"
def get_categorized_object_names(
config: FrigateConfig,
allowed_cameras: list[str],
object_type: str | None = None,
) -> dict[str, list[str]]:
"""Collect every sub label name this install can attach, by object type.
Unlike the database-backed /sub_labels endpoint, this reads the config and
model files, so it also covers names that are configured but have not been
detected yet. Names come from the detector's logo attributes (limited to
objects the allowed cameras actually track), LPR known plate names,
registered face names, and custom object classification categories.
Structural attributes such as `face` and `license_plate` are excluded: they
describe a part of an object rather than naming it, and are never attached
as a sub label.
Args:
config: The running Frigate config
allowed_cameras: Cameras the requesting user may see
object_type: Optional object label to restrict the result to
Returns:
Mapping of object label to its known sub label names, sorted and
deduplicated. Object types with no known names are omitted.
"""
tracked_objects = _get_tracked_objects(config, allowed_cameras)
names: dict[str, set[str]] = {}
logos = set(config.all_attribute_logos)
# 1. detector logo attributes, only for objects that are actually tracked
for label, label_attributes in config.all_attributes_map.items():
if label not in tracked_objects:
continue
label_logos = logos.intersection(label_attributes)
if label_logos:
names.setdefault(label, set()).update(label_logos)
# 2. LPR known plate names, for objects that can carry a plate
if config.lpr.known_plates and _lpr_enabled(config, allowed_cameras):
known_plates = set(config.lpr.known_plates)
for label in _objects_with_attribute(config, tracked_objects, "license_plate"):
names.setdefault(label, set()).update(known_plates)
# 3. registered face names, for objects that can carry a face
if _face_recognition_enabled(config, allowed_cameras):
face_names = _get_face_names()
if face_names:
for label in _objects_with_attribute(config, tracked_objects, "face"):
names.setdefault(label, set()).update(face_names)
# 4. custom object classification categories
for model_key, model_config in config.classification.custom.items():
if not model_config.enabled or model_config.object_config is None:
continue
if (
model_config.object_config.classification_type
!= ObjectClassificationType.sub_label
):
continue
categories = _get_classification_categories(model_key)
if not categories:
continue
for label in model_config.object_config.objects:
names.setdefault(label, set()).update(categories)
return {
label: sorted(label_names)
for label, label_names in sorted(names.items())
if label_names and (object_type is None or label == object_type)
}
def _get_tracked_objects(config: FrigateConfig, allowed_cameras: list[str]) -> set[str]:
"""Get the union of objects tracked by the cameras the user can see."""
tracked: set[str] = set()
for camera_name in allowed_cameras:
camera_config = config.cameras.get(camera_name)
if camera_config is None:
continue
tracked.update(camera_config.objects.track)
return tracked
def _objects_with_attribute(
config: FrigateConfig, tracked_objects: set[str], attribute: str
) -> set[str]:
"""Get the tracked objects that a given attribute can be recognized on.
The attribute may also be tracked as an object in its own right, as
`license_plate` is on a dedicated LPR camera, in which case the name is
attached to that object directly.
"""
objects = {
label
for label, label_attributes in config.all_attributes_map.items()
if attribute in label_attributes and label in tracked_objects
}
if attribute in tracked_objects:
objects.add(attribute)
return objects
def _lpr_enabled(config: FrigateConfig, allowed_cameras: list[str]) -> bool:
return any(
config.cameras[camera_name].lpr.enabled
for camera_name in allowed_cameras
if camera_name in config.cameras
)
def _face_recognition_enabled(
config: FrigateConfig, allowed_cameras: list[str]
) -> bool:
return any(
config.cameras[camera_name].face_recognition.enabled
for camera_name in allowed_cameras
if camera_name in config.cameras
)
def _get_face_names() -> set[str]:
"""Get the names of every registered face collection."""
if not os.path.exists(FACE_DIR):
return set()
try:
entries = os.listdir(FACE_DIR)
except OSError:
logger.debug("Failed to read face directory %s", FACE_DIR)
return set()
return {
name
for name in entries
if name != FACE_TRAIN_DIR and os.path.isdir(os.path.join(FACE_DIR, name))
}
def _get_classification_categories(model_key: str) -> set[str]:
"""Get the categories a custom classification model can output.
The trained labelmap is authoritative, but it only exists once the model
has been trained, so fall back to the dataset directories that will become
the labelmap on the next training run.
"""
safe_key = sanitize_filename(model_key)
categories: set[str] = set()
labelmap_path = os.path.join(MODEL_CACHE_DIR, safe_key, "labelmap.txt")
if os.path.exists(labelmap_path):
try:
labelmap = load_labels(labelmap_path, prefill=0, indexed=False)
except OSError:
logger.debug("Failed to read labelmap %s", labelmap_path)
labelmap = {}
categories.update(label for label in labelmap.values() if label)
dataset_dir = os.path.join(CLIPS_DIR, safe_key, "dataset")
if os.path.exists(dataset_dir):
try:
entries = os.listdir(dataset_dir)
except OSError:
logger.debug("Failed to read dataset directory %s", dataset_dir)
entries = []
categories.update(
name for name in entries if os.path.isdir(os.path.join(dataset_dir, name))
)
categories.discard(CLASSIFICATION_NONE_CATEGORY)
return categories
+9 -38
View File
@@ -2,45 +2,16 @@
from typing import Any from typing import Any
from pydantic import BaseModel, TypeAdapter from pydantic import BaseModel
def get_config_schema(config_class: type[BaseModel]) -> dict[str, Any]: def get_config_schema(config_class: type[BaseModel]) -> dict[str, Any]:
"""Get the JSON schema for FrigateConfig.
Args:
config_class: The config model to describe
Returns:
The JSON schema
""" """
Returns the JSON schema for FrigateConfig with polymorphic detectors. return config_class.model_json_schema()
This utility patches the FrigateConfig schema to include the full polymorphic
definitions for detectors. By default, Pydantic's schema for Dict[str, BaseDetectorConfig]
only includes the base class fields. This function replaces it with a reference
to the DetectorConfig union, which includes all available detector subclasses.
"""
# Import here to ensure all detector plugins are loaded through the detectors module
from frigate.detectors import DetectorConfig
# Get the base schema for FrigateConfig
schema = config_class.model_json_schema()
# Get the schema for the polymorphic DetectorConfig union
detector_adapter: TypeAdapter = TypeAdapter(DetectorConfig)
detector_schema = detector_adapter.json_schema()
# Ensure $defs exists in FrigateConfig schema
if "$defs" not in schema:
schema["$defs"] = {}
# Merge $defs from DetectorConfig into FrigateConfig schema
# This includes the specific schemas for each detector plugin (OvDetectorConfig, etc.)
if "$defs" in detector_schema:
schema["$defs"].update(detector_schema["$defs"])
# Extract the union schema (oneOf/discriminator) and add it as a definition
detector_union_schema = {k: v for k, v in detector_schema.items() if k != "$defs"}
schema["$defs"]["DetectorConfig"] = detector_union_schema
# Update the 'detectors' property to use the polymorphic DetectorConfig definition
if "detectors" in schema.get("properties", {}):
schema["properties"]["detectors"]["additionalProperties"] = {
"$ref": "#/$defs/DetectorConfig"
}
return schema
+18 -3
View File
@@ -1,6 +1,7 @@
"""Utilities for services.""" """Utilities for services."""
import asyncio import asyncio
import glob
import json import json
import logging import logging
import os import os
@@ -670,19 +671,33 @@ def get_intel_gpu_stats(
def get_openvino_npu_stats() -> dict[str, str] | None: def get_openvino_npu_stats() -> dict[str, str] | None:
"""Get NPU stats using openvino.""" """Get NPU stats using openvino."""
NPU_RUNTIME_PATH = "/sys/devices/pci0000:00/0000:00:0b.0/power/runtime_active_time" for accel_path in sorted(glob.glob("/sys/class/accel/accel*")):
try:
driver = os.path.basename(os.readlink(f"{accel_path}/device/driver"))
except OSError:
continue
if driver != "intel_vpu":
continue
try: try:
with open(NPU_RUNTIME_PATH) as f: runtime_path = f"{accel_path}/device/power/runtime_active_time"
with open(runtime_path) as f:
initial_runtime = float(f.read().strip()) initial_runtime = float(f.read().strip())
break
except (FileNotFoundError, PermissionError, ValueError):
continue
else:
return None
try:
initial_time = time.time() initial_time = time.time()
# Sleep for 1 second to get an accurate reading # Sleep for 1 second to get an accurate reading
time.sleep(1.0) time.sleep(1.0)
# Read runtime value again # Read runtime value again
with open(NPU_RUNTIME_PATH) as f: with open(runtime_path) as f:
current_runtime = float(f.read().strip()) current_runtime = float(f.read().strip())
current_time = time.time() current_time = time.time()
+6 -85
View File
@@ -210,78 +210,6 @@ def generate_section_translation(config_class: type) -> dict[str, Any]:
return extract_translations_from_schema(schema) return extract_translations_from_schema(schema)
def get_detector_translations(
config_schema: dict[str, Any],
) -> tuple[dict[str, Any], dict[str, Any], set[str]]:
"""Build detector type translations with nested fields based on schema definitions.
Returns a tuple of (type_translations, shared_fields, nested_field_keys).
Shared fields (identical across all detector types) are returned separately
to avoid duplication in the output.
"""
defs = config_schema.get("$defs", {})
detector_schema = defs.get("DetectorConfig", {})
discriminator = detector_schema.get("discriminator", {})
mapping = discriminator.get("mapping", {})
# First pass: collect all nested fields per detector type
all_nested: dict[str, dict[str, Any]] = {}
type_meta: dict[str, dict[str, str]] = {}
for detector_type, ref in mapping.items():
if not isinstance(ref, str) or not ref.startswith("#/$defs/"):
continue
ref_name = ref.split("/")[-1]
ref_schema = defs.get(ref_name, {})
if not ref_schema:
continue
meta: dict[str, str] = {}
title = ref_schema.get("title")
description = ref_schema.get("description")
if title:
meta["label"] = title
if description:
meta["description"] = description
type_meta[detector_type] = meta
nested = extract_translations_from_schema(ref_schema, defs=defs)
all_nested[detector_type] = {
k: v for k, v in nested.items() if k not in ("label", "description")
}
# Find fields that are identical across all types that have them
shared_fields: dict[str, Any] = {}
if all_nested:
# Collect all field keys across all types
all_keys: set[str] = set()
for nested in all_nested.values():
all_keys.update(nested.keys())
for key in all_keys:
values = [nested[key] for nested in all_nested.values() if key in nested]
if len(values) == len(all_nested) and all(v == values[0] for v in values):
shared_fields[key] = values[0]
# Build per-type translations with only unique (non-shared) fields
type_translations: dict[str, Any] = {}
nested_field_keys: set[str] = set()
for detector_type, nested in all_nested.items():
type_entry: dict[str, Any] = {}
type_entry.update(type_meta.get(detector_type, {}))
unique_fields = {k: v for k, v in nested.items() if k not in shared_fields}
if unique_fields:
type_entry.update(unique_fields)
nested_field_keys.update(unique_fields.keys())
if type_entry:
type_translations[detector_type] = type_entry
return type_translations, shared_fields, nested_field_keys
def main(): def main():
"""Main function to generate config translations.""" """Main function to generate config translations."""
@@ -337,6 +265,12 @@ def main():
if args and len(args) > 1: if args and len(args) > 1:
field_type = args[1] # Get value type from Dict[key, value] field_type = args[1] # Get value type from Dict[key, value]
# Handle List[SomeModel] - extract the item type
if origin is list:
args = get_args(field_type)
if args:
field_type = args[0]
# Start with field's top-level metadata (label, description) # Start with field's top-level metadata (label, description)
section_data = get_field_translations(field_info) section_data = get_field_translations(field_info)
@@ -351,19 +285,6 @@ def main():
} }
section_data.update(nested_without_root) section_data.update(nested_without_root)
if field_name == "detectors":
detector_types, shared_fields, detector_field_keys = (
get_detector_translations(config_schema)
)
# Add shared fields at the base detectors level
section_data.update(shared_fields)
# Add per-type translations (only unique fields per type)
section_data.update(detector_types)
for key in detector_field_keys:
if key == "type":
continue
section_data.pop(key, None)
if field_name == "objects": if field_name == "objects":
# Produce a parallel `filters_attribute` block alongside `filters`, # Produce a parallel `filters_attribute` block alongside `filters`,
# with object-wording rewritten for attribute filters (face, # with object-wording rewritten for attribute filters (face,
+2 -2
View File
@@ -122,7 +122,7 @@ class ProcessClip:
self.camera_name, self.camera_name,
self.frame_queue, self.frame_queue,
self.frame_shape, self.frame_shape,
self.config.model, self.config.model_for_camera(self.camera_name),
self.camera_config.detect, self.camera_config.detect,
self.frame_manager, self.frame_manager,
motion_detector, motion_detector,
@@ -248,7 +248,7 @@ def process(path, label, output, debug_path):
json_config = { json_config = {
"mqtt": {"enabled": False}, "mqtt": {"enabled": False},
"detectors": {"coral": {"type": "edgetpu", "device": "usb"}}, "models": [{"devices": ["edgetpu:usb"]}],
"cameras": { "cameras": {
"camera": { "camera": {
"ffmpeg": { "ffmpeg": {
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -102,11 +102,12 @@ def generate_config():
snapshot = config.model_dump() snapshot = config.model_dump()
# Runtime-computed fields not in the Pydantic dump # Runtime-computed fields not in the Pydantic dump
for model in snapshot.get("models", []):
all_attrs = set() all_attrs = set()
for attrs in snapshot.get("model", {}).get("attributes_map", {}).values(): for attrs in model.get("attributes_map", {}).values():
all_attrs.update(attrs) all_attrs.update(attrs)
snapshot["model"]["all_attributes"] = sorted(all_attrs) model["all_attributes"] = sorted(all_attrs)
snapshot["model"]["colormap"] = {} model["colormap"] = {}
return snapshot return snapshot
+22 -2
View File
@@ -71,8 +71,24 @@
"description": "Enable or disable the Birdseye view feature." "description": "Enable or disable the Birdseye view feature."
}, },
"mode": { "mode": {
"label": "Tracking mode", "label": "Activity types",
"description": "Mode for including cameras in Birdseye: 'objects', 'motion', or 'continuous'." "description": "Activity types that include cameras in Birdseye.",
"continuous": {
"label": "Continuous",
"description": "Always include the camera in Birdseye."
},
"motion": {
"label": "Motion",
"description": "Include the camera in Birdseye when motion is detected."
},
"objects": {
"label": "Active objects",
"description": "Include the camera in Birdseye while an active object is tracked."
},
"stationary_objects": {
"label": "Stationary objects",
"description": "Include the camera in Birdseye while a stationary object is tracked."
}
}, },
"order": { "order": {
"label": "Position", "label": "Position",
@@ -94,6 +110,10 @@
"label": "Detect width", "label": "Detect width",
"description": "Width (pixels) of frames used for the detect stream; leave empty to use the native stream resolution." "description": "Width (pixels) of frames used for the detect stream; leave empty to use the native stream resolution."
}, },
"scene": {
"label": "Detect scene",
"description": "The environment this camera looks at, used to pick which of the configured models runs on it. Defaults to the model with a scene of 'all'."
},
"fps": { "fps": {
"label": "Detect FPS", "label": "Detect FPS",
"description": "Desired frames per second to run detection on; lower values reduce CPU usage (recommended value is 5, only set higher - at most 10 - if tracking extremely fast moving objects)." "description": "Desired frames per second to run detection on; lower values reduce CPU usage (recommended value is 5, only set higher - at most 10 - if tracking extremely fast moving objects)."
+31 -166
View File
@@ -275,172 +275,17 @@
"description": "Unit system for display (metric or imperial) used in the UI and MQTT." "description": "Unit system for display (metric or imperial) used in the UI and MQTT."
} }
}, },
"detectors": { "models": {
"label": "Detector hardware", "label": "Detection models",
"description": "Configuration for object detectors (CPU, GPU, ONNX backends) and any detector-specific model settings.", "description": "Object detection models and the hardware each one runs on. Cameras pick a model by matching their detect.scene against a model's scene.",
"type": { "scene": {
"label": "Type" "label": "Model scene",
"description": "The camera environment this model is used for. Cameras select a model by setting detect.scene to a matching value, and 'all' is used by any camera that does not set one."
}, },
"model": { "devices": {
"label": "Detector specific model configuration", "label": "Detection hardware",
"description": "Detector-specific model configuration options (path, input size, etc.).", "description": "Hardware this model runs on, as '<detector>' or '<detector>:<device>' (for example 'edgetpu:pci:0' or 'openvino:GPU'). Listing the same device more than once runs additional inference processes on it."
"path": {
"label": "Custom object detector model path",
"description": "Path to a custom detection model file (or plus://<model_id> for Frigate+ models)."
}, },
"labelmap_path": {
"label": "Label map for custom object detector",
"description": "Path to a labelmap file that maps numeric classes to string labels for the detector."
},
"width": {
"label": "Object detection model input width",
"description": "Width of the model input tensor in pixels."
},
"height": {
"label": "Object detection model input height",
"description": "Height of the model input tensor in pixels."
},
"labelmap": {
"label": "Labelmap customization",
"description": "Overrides or remapping entries to merge into the standard labelmap."
},
"attributes_map": {
"label": "Map of object labels to their attribute labels",
"description": "Mapping from object labels to attribute labels used to attach metadata (for example 'car' -> ['license_plate'])."
},
"input_tensor": {
"label": "Model Input Tensor Shape",
"description": "Tensor format expected by the model: 'nhwc' or 'nchw'."
},
"input_pixel_format": {
"label": "Model Input Pixel Color Format",
"description": "Pixel colorspace expected by the model: 'rgb', 'bgr', or 'yuv'."
},
"input_dtype": {
"label": "Model Input D Type",
"description": "Data type of the model input tensor (for example 'float32')."
},
"model_type": {
"label": "Object Detection Model Type",
"description": "Detector model architecture type (ssd, yolox, yolonas, yolo-generic, rfdetr, dfine) used by some detectors for optimization."
}
},
"model_path": {
"label": "Detector specific model path",
"description": "File path to the detector model binary if required by the chosen detector."
},
"axengine": {
"label": "AXEngine NPU",
"description": "AXERA AX650N/AX8850N NPU detector running compiled .axmodel files via the AXEngine runtime."
},
"cpu": {
"label": "CPU",
"description": "CPU TFLite detector that runs TensorFlow Lite models on the host CPU without hardware acceleration. Not recommended.",
"num_threads": {
"label": "Number of detection threads",
"description": "The number of threads used for CPU-based inference."
}
},
"deepstack": {
"label": "DeepStack",
"description": "DeepStack/CodeProject.AI detector that sends images to a remote DeepStack HTTP API for inference. Not recommended.",
"api_url": {
"label": "DeepStack API URL",
"description": "The URL of the DeepStack API."
},
"api_timeout": {
"label": "DeepStack API timeout (in seconds)",
"description": "Maximum time allowed for a DeepStack API request."
},
"api_key": {
"label": "DeepStack API key (if required)",
"description": "Optional API key for authenticated DeepStack services."
}
},
"edgetpu": {
"label": "EdgeTPU",
"description": "EdgeTPU detector that runs TensorFlow Lite models compiled for Coral EdgeTPU using the EdgeTPU delegate.",
"device": {
"label": "Device Type",
"description": "The device to use for EdgeTPU inference (e.g. 'usb', 'pci')."
}
},
"hailo8l": {
"label": "Hailo-8/Hailo-8L",
"description": "Hailo-8/Hailo-8L detector using HEF models and the HailoRT SDK for inference on Hailo hardware.",
"device": {
"label": "Device Type",
"description": "The device to use for Hailo inference (e.g. 'PCIe', 'M.2')."
}
},
"memryx": {
"label": "MemryX",
"description": "MemryX MX3 detector that runs compiled DFP models on MemryX accelerators.",
"device": {
"label": "Device Path",
"description": "The device to use for MemryX inference (e.g. 'PCIe')."
}
},
"onnx": {
"label": "ONNX",
"description": "ONNX detector for running ONNX models; will use available acceleration backends (CUDA/ROCm/OpenVINO) when available.",
"device": {
"label": "Device Type",
"description": "The device to use for ONNX inference (e.g. 'AUTO', 'CPU', 'GPU')."
}
},
"openvino": {
"label": "OpenVINO",
"description": "OpenVINO detector for AMD and Intel CPUs, Intel GPUs and Intel VPU hardware.",
"device": {
"label": "Device Type",
"description": "The device to use for OpenVINO inference (e.g. 'CPU', 'GPU', 'NPU')."
}
},
"rknn": {
"label": "RKNN",
"description": "RKNN detector for Rockchip NPUs; runs compiled RKNN models on Rockchip hardware.",
"num_cores": {
"label": "Number of NPU cores to use.",
"description": "The number of NPU cores to use (0 for auto)."
}
},
"synaptics": {
"label": "Synaptics",
"description": "Synaptics NPU detector for models in .synap format using the Synap SDK on Synaptics hardware."
},
"teflon_tfl": {
"label": "Teflon",
"description": "Teflon delegate detector for TFLite using Mesa Teflon delegate library to accelerate inference on supported GPUs."
},
"tensorrt": {
"label": "TensorRT",
"description": "TensorRT detector for Nvidia Jetson devices using serialized TensorRT engines for accelerated inference.",
"device": {
"label": "GPU Device Index",
"description": "The GPU device index to use."
}
},
"zmq": {
"label": "ZMQ IPC",
"description": "ZMQ IPC detector that offloads inference to an external process via a ZeroMQ IPC endpoint.",
"endpoint": {
"label": "ZMQ IPC endpoint",
"description": "The ZMQ endpoint to connect to."
},
"request_timeout_ms": {
"label": "ZMQ request timeout in milliseconds",
"description": "Timeout for ZMQ requests in milliseconds."
},
"linger_ms": {
"label": "ZMQ socket linger in milliseconds",
"description": "Socket linger period in milliseconds."
}
}
},
"model": {
"label": "Detection model",
"description": "Settings to configure a custom object detection model and its input shape.",
"path": { "path": {
"label": "Custom object detector model path", "label": "Custom object detector model path",
"description": "Path to a custom detection model file (or plus://<model_id> for Frigate+ models)." "description": "Path to a custom detection model file (or plus://<model_id> for Frigate+ models)."
@@ -558,8 +403,24 @@
"description": "Enable or disable the Birdseye view feature." "description": "Enable or disable the Birdseye view feature."
}, },
"mode": { "mode": {
"label": "Tracking mode", "label": "Activity types",
"description": "Mode for including cameras in Birdseye: 'objects', 'motion', or 'continuous'." "description": "Activity types that include cameras in Birdseye.",
"continuous": {
"label": "Continuous",
"description": "Always include the camera in Birdseye."
},
"motion": {
"label": "Motion",
"description": "Include the camera in Birdseye when motion is detected."
},
"objects": {
"label": "Active objects",
"description": "Include the camera in Birdseye while an active object is tracked."
},
"stationary_objects": {
"label": "Stationary objects",
"description": "Include the camera in Birdseye while a stationary object is tracked."
}
}, },
"restream": { "restream": {
"label": "Restream RTSP", "label": "Restream RTSP",
@@ -617,6 +478,10 @@
"label": "Detect width", "label": "Detect width",
"description": "Width (pixels) of frames used for the detect stream; leave empty to use the native stream resolution." "description": "Width (pixels) of frames used for the detect stream; leave empty to use the native stream resolution."
}, },
"scene": {
"label": "Detect scene",
"description": "The environment this camera looks at, used to pick which of the configured models runs on it. Defaults to the model with a scene of 'all'."
},
"fps": { "fps": {
"label": "Detect FPS", "label": "Detect FPS",
"description": "Desired frames per second to run detection on; lower values reduce CPU usage (recommended value is 5, only set higher - at most 10 - if tracking extremely fast moving objects)." "description": "Desired frames per second to run detection on; lower values reduce CPU usage (recommended value is 5, only set higher - at most 10 - if tracking extremely fast moving objects)."
+1 -1
View File
@@ -1955,7 +1955,7 @@
"noRecordRole": "No streams have the record role defined. Recording will not function." "noRecordRole": "No streams have the record role defined. Recording will not function."
}, },
"birdseye": { "birdseye": {
"objectsModeDetectDisabled": "Birdseye is set to 'objects' mode, but object detection is disabled for this camera. The camera will not appear in Birdseye." "objectTrackingDetectDisabled": "Birdseye includes tracked objects, but object detection is disabled for this camera. The camera will not appear in Birdseye."
}, },
"snapshots": { "snapshots": {
"detectDisabled": "Object detection is disabled. Snapshots are generated from tracked objects and will not be created." "detectDisabled": "Object detection is disabled. Snapshots are generated from tracked objects and will not be created."
@@ -5,13 +5,18 @@ const birdseye: SectionConfigOverrides = {
sectionDocs: "/configuration/birdseye", sectionDocs: "/configuration/birdseye",
messages: [ messages: [
{ {
key: "objects-mode-detect-disabled", key: "object-tracking-detect-disabled",
messageKey: "configMessages.birdseye.objectsModeDetectDisabled", messageKey: "configMessages.birdseye.objectTrackingDetectDisabled",
severity: "info", severity: "info",
condition: (ctx) => { condition: (ctx) => {
if (ctx.level !== "camera" || !ctx.fullCameraConfig) return false; if (ctx.level !== "camera" || !ctx.fullCameraConfig) return false;
const mode = ctx.formData?.mode;
if (!mode || typeof mode !== "object" || Array.isArray(mode)) {
return false;
}
return ( return (
ctx.formData?.mode === "objects" && (mode.objects === true || mode.stationary_objects === true) &&
ctx.fullCameraConfig.detect?.enabled === false ctx.fullCameraConfig.detect?.enabled === false
); );
}, },
@@ -24,10 +29,10 @@ const birdseye: SectionConfigOverrides = {
overrideFields: ["enabled", "mode"], overrideFields: ["enabled", "mode"],
uiSchema: { uiSchema: {
mode: { mode: {
"ui:size": "xs", continuous: { "ui:size": "xs" },
"ui:options": { motion: { "ui:size": "xs" },
enumI18nPrefix: "birdseye.trackingMode", objects: { "ui:size": "xs" },
}, stationary_objects: { "ui:size": "xs" },
}, },
}, },
}, },
@@ -55,7 +60,6 @@ const birdseye: SectionConfigOverrides = {
], ],
uiSchema: { uiSchema: {
mode: { mode: {
"ui:size": "xs",
"ui:after": { render: "BirdseyeCameraReorder" }, "ui:after": { render: "BirdseyeCameraReorder" },
}, },
}, },
+9 -2
View File
@@ -13,12 +13,19 @@ export interface UiConfig {
export interface BirdseyeConfig { export interface BirdseyeConfig {
enabled: boolean; enabled: boolean;
height: number; height: number;
mode: "objects" | "continuous" | "motion"; mode: BirdseyeModeConfig;
quality: number; quality: number;
restream: boolean; restream: boolean;
width: number; width: number;
} }
export interface BirdseyeModeConfig {
continuous: boolean;
motion: boolean;
objects: boolean;
stationary_objects: boolean;
}
export interface FaceRecognitionConfig { export interface FaceRecognitionConfig {
enabled: boolean; enabled: boolean;
model_size: SearchModelSize; model_size: SearchModelSize;
@@ -49,7 +56,7 @@ export interface CameraConfig {
best_image_timeout: number; best_image_timeout: number;
birdseye: { birdseye: {
enabled: boolean; enabled: boolean;
mode: "objects" | "continuous" | "motion"; mode: BirdseyeModeConfig;
order: number; order: number;
}; };
detect: { detect: {