mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-11-24 22:37:08 +03:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
130815ac70 |
@@ -1,4 +1,4 @@
|
|||||||
ruff == 0.17.5
|
ruff == 0.17.4
|
||||||
|
|
||||||
# types
|
# types
|
||||||
types-peewee == 4.0.*
|
types-peewee == 4.0.*
|
||||||
|
|||||||
@@ -4,14 +4,14 @@ click == 8.5.*
|
|||||||
aiohttp == 3.14.*
|
aiohttp == 3.14.*
|
||||||
starlette == 1.10.*
|
starlette == 1.10.*
|
||||||
starlette-context == 0.5.*
|
starlette-context == 0.5.*
|
||||||
fastapi[standard-no-fastapi-cloud-cli] == 0.165.*
|
fastapi[standard-no-fastapi-cloud-cli] == 0.162.*
|
||||||
uvicorn == 0.54.*
|
uvicorn == 0.54.*
|
||||||
slowapi == 0.1.*
|
slowapi == 0.1.*
|
||||||
joserfc == 1.8.*
|
joserfc == 1.8.*
|
||||||
cryptography == 50.0.*
|
cryptography == 50.0.*
|
||||||
pathvalidate == 3.3.*
|
pathvalidate == 3.3.*
|
||||||
markupsafe == 3.0.*
|
markupsafe == 3.0.*
|
||||||
python-multipart == 0.0.34
|
python-multipart == 0.0.33
|
||||||
# Classification Model Training
|
# Classification Model Training
|
||||||
tensorflow == 2.19.* ; platform_machine == 'aarch64'
|
tensorflow == 2.19.* ; platform_machine == 'aarch64'
|
||||||
tensorflow-cpu == 2.21.* ; platform_machine == 'x86_64'
|
tensorflow-cpu == 2.21.* ; platform_machine == 'x86_64'
|
||||||
@@ -43,13 +43,13 @@ opencv-contrib-python == 4.11.0.*
|
|||||||
scipy == 1.17.*
|
scipy == 1.17.*
|
||||||
# OpenVino & ONNX
|
# OpenVino & ONNX
|
||||||
openvino == 2026.4.*
|
openvino == 2026.4.*
|
||||||
onnxruntime == 1.32.*
|
onnxruntime == 1.31.*
|
||||||
# Embeddings
|
# Embeddings
|
||||||
transformers == 5.22.*
|
transformers == 5.22.*
|
||||||
# Generative AI
|
# Generative AI
|
||||||
google-genai == 3.6.*
|
google-genai == 3.2.*
|
||||||
ollama == 0.6.*
|
ollama == 0.6.*
|
||||||
openai == 3.55.*
|
openai == 3.49.*
|
||||||
# push notifications
|
# push notifications
|
||||||
py-vapid == 1.9.6
|
py-vapid == 1.9.6
|
||||||
pywebpush == 2.5.*
|
pywebpush == 2.5.*
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ echo "[INFO] Starting go2rtc healthcheck service..."
|
|||||||
|
|
||||||
while sleep 30s; do
|
while sleep 30s; do
|
||||||
# Check if the service is running
|
# Check if the service is running
|
||||||
if ! curl --connect-timeout 10 --max-time 15 --fail --silent --show-error --output /dev/null http://127.0.0.1:1984/api/streams 2>&1; then
|
if ! curl --connect-timeout 10 --fail --silent --show-error --output /dev/null http://127.0.0.1:1984/api/streams 2>&1; then
|
||||||
echo "[ERROR] The go2rtc service is not responding to ping, restarting..."
|
echo "[ERROR] The go2rtc service is not responding to ping, restarting..."
|
||||||
# We can also use -r instead of -t to send kill signal rather than term
|
# We can also use -r instead of -t to send kill signal rather than term
|
||||||
s6-svc -t /var/run/service/go2rtc 2>&1
|
s6-svc -t /var/run/service/go2rtc 2>&1
|
||||||
|
|||||||
@@ -152,24 +152,13 @@ if [[ "$(id -u)" -eq 0 && "$runs_as_root" -eq 0 ]]; then
|
|||||||
# nginx reopens /dev/stdout by path for its logs, and s6 made the pipe
|
# nginx reopens /dev/stdout by path for its logs, and s6 made the pipe
|
||||||
# root-owned 0600; without this the non-root master exits EACCES
|
# root-owned 0600; without this the non-root master exits EACCES
|
||||||
chown frigate /dev/stdout
|
chown frigate /dev/stdout
|
||||||
fi
|
# Only mounted certs need handing over; the self-signed pair is already
|
||||||
|
# owned by the runtime user that generated it. Never chown the /config copy:
|
||||||
# Mounted certs are never chowned: chown follows symlinks, and the runtime user
|
# chown follows symlinks, so it would retarget onto any root file the
|
||||||
# may control the mounted folder. The key's group and group read survive certbot
|
# runtime user pointed it at. Tolerant because mounted certs may be :ro.
|
||||||
# renewals, so the host grants access once.
|
if [ "$cert_path" = "$letsencrypt_path" ] && [ -f "$cert_path/privkey.pem" ]; then
|
||||||
if [[ "$cert_path" == "$letsencrypt_path" && "$runs_as_root" -eq 0 ]] &&
|
chown frigate:frigate "$cert_path/privkey.pem" "$cert_path/fullchain.pem" 2>/dev/null || true
|
||||||
[[ "$(echo "$nginx_settings" | jq -r .tls.enabled)" == "true" ]]; then
|
|
||||||
as_runtime=()
|
|
||||||
if [[ "$(id -u)" -eq 0 ]]; then
|
|
||||||
as_runtime=(s6-setuidgid frigate)
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
for file in privkey.pem fullchain.pem; do
|
|
||||||
if ! "${as_runtime[@]}" test -r "$cert_path/$file"; then
|
|
||||||
runtime_gid=$("${as_runtime[@]}" id -g)
|
|
||||||
echo "[ERROR] The mounted ${file} is not readable by the runtime user; on the host, give it group ${runtime_gid} with read access and let that group enter the folders above it" >&2
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Replace the bash process with the NGINX process, redirecting stderr to stdout
|
# Replace the bash process with the NGINX process, redirecting stderr to stdout
|
||||||
|
|||||||
@@ -22,6 +22,3 @@ add_header Set-Cookie $auth_cookie;
|
|||||||
## Pass the location header back up if it exists
|
## Pass the location header back up if it exists
|
||||||
auth_request_set $redirection_url $upstream_http_location;
|
auth_request_set $redirection_url $upstream_http_location;
|
||||||
add_header Location $redirection_url;
|
add_header Location $redirection_url;
|
||||||
|
|
||||||
## The add_header lines above stop this location inheriting server-level headers
|
|
||||||
include security_headers.conf;
|
|
||||||
|
|||||||
@@ -152,6 +152,7 @@ http {
|
|||||||
sub_filter '.m4s' '.m4s$is_args$args';
|
sub_filter '.m4s' '.m4s$is_args$args';
|
||||||
sub_filter '.mp4"' '.mp4$is_args$args"';
|
sub_filter '.mp4"' '.mp4$is_args$args"';
|
||||||
|
|
||||||
|
include security_headers.conf;
|
||||||
add_header Cache-Control "no-store";
|
add_header Cache-Control "no-store";
|
||||||
expires off;
|
expires off;
|
||||||
|
|
||||||
@@ -160,6 +161,7 @@ http {
|
|||||||
|
|
||||||
location /stream/ {
|
location /stream/ {
|
||||||
include auth_request.conf;
|
include auth_request.conf;
|
||||||
|
include security_headers.conf;
|
||||||
add_header Cache-Control "no-store";
|
add_header Cache-Control "no-store";
|
||||||
expires off;
|
expires off;
|
||||||
|
|
||||||
@@ -183,6 +185,7 @@ http {
|
|||||||
}
|
}
|
||||||
|
|
||||||
expires 7d;
|
expires 7d;
|
||||||
|
include security_headers.conf;
|
||||||
add_header Cache-Control "public";
|
add_header Cache-Control "public";
|
||||||
autoindex on;
|
autoindex on;
|
||||||
root /media/frigate;
|
root /media/frigate;
|
||||||
@@ -223,7 +226,7 @@ http {
|
|||||||
|
|
||||||
location /ws {
|
location /ws {
|
||||||
include auth_request.conf;
|
include auth_request.conf;
|
||||||
proxy_pass http://mqtt_ws;
|
proxy_pass http://mqtt_ws/;
|
||||||
include proxy.conf;
|
include proxy.conf;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -287,6 +290,7 @@ http {
|
|||||||
|
|
||||||
location /api/ {
|
location /api/ {
|
||||||
include auth_request.conf;
|
include auth_request.conf;
|
||||||
|
include security_headers.conf;
|
||||||
add_header Cache-Control "no-store";
|
add_header Cache-Control "no-store";
|
||||||
expires off;
|
expires off;
|
||||||
proxy_pass http://frigate_api/;
|
proxy_pass http://frigate_api/;
|
||||||
|
|||||||
@@ -102,7 +102,7 @@ proxy:
|
|||||||
# Optional: Auth secret that is checked against the X-Proxy-Secret header sent from
|
# Optional: Auth secret that is checked against the X-Proxy-Secret header sent from
|
||||||
# the proxy. If not set, all requests are trusted regardless of origin.
|
# the proxy. If not set, all requests are trusted regardless of origin.
|
||||||
auth_secret: None
|
auth_secret: None
|
||||||
# Optional: The default role to use for proxy auth. Must be "admin", "viewer", a custom role, or "none" to deny
|
# Optional: The default role to use for proxy auth. Must be "admin" or "viewer"
|
||||||
default_role: viewer
|
default_role: viewer
|
||||||
# Optional: The character used to separate multiple values in the proxy headers. (default: shown below)
|
# Optional: The character used to separate multiple values in the proxy headers. (default: shown below)
|
||||||
separator: ","
|
separator: ","
|
||||||
|
|||||||
@@ -234,8 +234,6 @@ proxy:
|
|||||||
|
|
||||||
Setting `default_role` to `none` denies access instead of falling back to a role. Any proxy-authenticated user whose headers do not match an explicit `role_map` entry receives a 403 response. This is useful when the upstream proxy authenticates a broader set of users than should reach Frigate, so that only mapped groups are allowed in.
|
Setting `default_role` to `none` denies access instead of falling back to a role. Any proxy-authenticated user whose headers do not match an explicit `role_map` entry receives a 403 response. This is useful when the upstream proxy authenticates a broader set of users than should reach Frigate, so that only mapped groups are allowed in.
|
||||||
|
|
||||||
A `default_role` that does not name a configured role is treated as `none`.
|
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
proxy:
|
proxy:
|
||||||
...
|
...
|
||||||
@@ -268,8 +266,7 @@ In this example:
|
|||||||
- If the proxy passes a role header containing `camera-viewer`, the user is assigned the `viewer` role.
|
- If the proxy passes a role header containing `camera-viewer`, the user is assigned the `viewer` role.
|
||||||
- If the proxy passes a role header containing `operators`, the user is assigned the `operator` custom role.
|
- If the proxy passes a role header containing `operators`, the user is assigned the `operator` custom role.
|
||||||
- If no mapping matches, Frigate falls back to `default_role` if configured, or denies access if `default_role` is `none`.
|
- If no mapping matches, Frigate falls back to `default_role` if configured, or denies access if `default_role` is `none`.
|
||||||
- If a group matches but its mapped role no longer exists (for example, a deleted custom role), access is denied.
|
- If `role_map` is not defined, Frigate assumes the role header directly contains `admin`, `viewer`, or a custom role name.
|
||||||
- If `role_map` is not defined, Frigate assumes the role header directly contains `admin`, `viewer`, or a custom role name, matched without regard to case.
|
|
||||||
|
|
||||||
**Note on matching semantics:**
|
**Note on matching semantics:**
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import NavPath from "@site/src/components/NavPath";
|
|||||||
|
|
||||||
# Metrics
|
# Metrics
|
||||||
|
|
||||||
Frigate exposes Prometheus metrics at the `/api/metrics` endpoint that can be used to monitor the performance and health of your Frigate instance. On the authenticated port (8971), the endpoint requires an admin user, so point scrapers at the internal port (5000) as shown below.
|
Frigate exposes Prometheus metrics at the `/api/metrics` endpoint that can be used to monitor the performance and health of your Frigate instance.
|
||||||
|
|
||||||
## Enabling Telemetry
|
## Enabling Telemetry
|
||||||
|
|
||||||
|
|||||||
@@ -389,7 +389,7 @@ Rockchip NPU and GPU usage come from `/sys/kernel/debug`, which the kernel makes
|
|||||||
|
|
||||||
go2rtc's ffmpeg processes no longer appear in Intel GPU stats. Frigate reads per-process GPU usage from `/proc/<pid>/fdinfo`, which the kernel won't let one user read for another user's processes, so anything go2rtc spawns is invisible to it. Overall GPU utilization is unaffected.
|
go2rtc's ffmpeg processes no longer appear in Intel GPU stats. Frigate reads per-process GPU usage from `/proc/<pid>/fdinfo`, which the kernel won't let one user read for another user's processes, so anything go2rtc spawns is invisible to it. Overall GPU utilization is unaffected.
|
||||||
|
|
||||||
If you mount your own TLS certificate at `/etc/letsencrypt/live/frigate`, the key and the certificate have to be readable by the runtime user, which runs nginx, and that user has to be able to enter the folders above them. Frigate doesn't change ownership of mounted certificates, so give the key to the runtime user's group (gid 1000, your `PGID`, or the group in Docker's `user:`) with group read on the host. certbot keeps the key's group and group read on renewal, so this is a one-time step.
|
If you mount your own TLS certificate at `/etc/letsencrypt/live/frigate`, the private key has to be readable by the runtime user, which runs nginx. Frigate hands the key to that user at startup if the mount is writable; on a read-only mount, make the key readable by uid 1000 (or your `PUID`) yourself.
|
||||||
|
|
||||||
If you're debugging nginx, run the config check as the runtime user with stdout discarded:
|
If you're debugging nginx, run the config check as the runtime user with stdout discarded:
|
||||||
|
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ frigate:
|
|||||||
|
|
||||||
Within the folder, the private key is expected to be named `privkey.pem` and the certificate is expected to be named `fullchain.pem`. Mounted certificates take precedence over the self signed pair in `/config/tls`.
|
Within the folder, the private key is expected to be named `privkey.pem` and the certificate is expected to be named `fullchain.pem`. Mounted certificates take precedence over the self signed pair in `/config/tls`.
|
||||||
|
|
||||||
`privkey.pem` and `fullchain.pem` must be readable by the runtime user that runs NGINX, and that user must be able to enter the folders above them. Frigate doesn't change ownership of mounted certificates, so give the key to the runtime user's group (gid 1000, your `PGID`, or the group in Docker's `user:`) with group read on the host, for example `chgrp 1000 privkey.pem && chmod g+r privkey.pem`. certbot keeps the key's group and group read on renewal, so this is a one-time step. See [Running as a non-root user](/configuration/non_root).
|
`privkey.pem` must be readable by the runtime user that runs NGINX. Frigate hands it over at startup when the mount is writable; on a `:ro` mount, make it readable by uid 1000 (or your `PUID`) yourself. See [Running as a non-root user](/configuration/non_root).
|
||||||
|
|
||||||
Note that certbot uses symlinks, and those can't be followed by the container unless it has access to the targets as well, so if using certbot you'll also have to mount the `archive` folder for your domain, e.g.:
|
Note that certbot uses symlinks, and those can't be followed by the container unless it has access to the targets as well, so if using certbot you'll also have to mount the `archive` folder for your domain, e.g.:
|
||||||
|
|
||||||
|
|||||||
Vendored
+3
-5
@@ -2546,7 +2546,7 @@ paths:
|
|||||||
- App
|
- App
|
||||||
summary: Metrics
|
summary: Metrics
|
||||||
description: |-
|
description: |-
|
||||||
**Access:** Admin role required.
|
**Access:** Any authenticated user.
|
||||||
|
|
||||||
Expose Prometheus metrics endpoint and update metrics with latest stats
|
Expose Prometheus metrics endpoint and update metrics with latest stats
|
||||||
operationId: metrics_metrics_get
|
operationId: metrics_metrics_get
|
||||||
@@ -2557,8 +2557,8 @@ paths:
|
|||||||
application/json:
|
application/json:
|
||||||
schema: {}
|
schema: {}
|
||||||
security:
|
security:
|
||||||
- frigateAdminAuth: []
|
- frigateUserAuth: []
|
||||||
x-required-role: admin
|
x-required-role: any
|
||||||
/genai/models:
|
/genai/models:
|
||||||
get:
|
get:
|
||||||
tags:
|
tags:
|
||||||
@@ -9630,8 +9630,6 @@ components:
|
|||||||
title: Condition
|
title: Condition
|
||||||
max_duration_minutes:
|
max_duration_minutes:
|
||||||
type: integer
|
type: integer
|
||||||
maximum: 1440.0
|
|
||||||
minimum: 1.0
|
|
||||||
title: Max Duration Minutes
|
title: Max Duration Minutes
|
||||||
default: 60
|
default: 60
|
||||||
labels:
|
labels:
|
||||||
|
|||||||
+61
-95
@@ -40,7 +40,6 @@ from frigate.api.defs.request.app_body import (
|
|||||||
MediaSyncBody,
|
MediaSyncBody,
|
||||||
)
|
)
|
||||||
from frigate.api.defs.tags import Tags
|
from frigate.api.defs.tags import Tags
|
||||||
from frigate.api.plus_util import plus_rate_limited_response
|
|
||||||
from frigate.config import FrigateConfig, GenAIConfig, GenAIProviderEnum
|
from frigate.config import FrigateConfig, GenAIConfig, GenAIProviderEnum
|
||||||
from frigate.config.camera.updater import (
|
from frigate.config.camera.updater import (
|
||||||
CameraConfigUpdateEnum,
|
CameraConfigUpdateEnum,
|
||||||
@@ -55,7 +54,7 @@ from frigate.jobs.media_sync import (
|
|||||||
start_media_sync_job,
|
start_media_sync_job,
|
||||||
)
|
)
|
||||||
from frigate.models import Event, Timeline
|
from frigate.models import Event, Timeline
|
||||||
from frigate.plus import PlusKeyStatus, PlusRateLimitError, load_plus_model_info
|
from frigate.plus import PlusKeyStatus, load_plus_model_info
|
||||||
from frigate.stats.prometheus import get_metrics, update_metrics
|
from frigate.stats.prometheus import get_metrics, update_metrics
|
||||||
from frigate.types import JobStatusTypesEnum
|
from frigate.types import JobStatusTypesEnum
|
||||||
from frigate.util.builtin import (
|
from frigate.util.builtin import (
|
||||||
@@ -65,7 +64,6 @@ from frigate.util.builtin import (
|
|||||||
is_masked_camera_path,
|
is_masked_camera_path,
|
||||||
load_labels,
|
load_labels,
|
||||||
process_config_query_string,
|
process_config_query_string,
|
||||||
scope_stats_for_non_admin,
|
|
||||||
split_config_key_path,
|
split_config_key_path,
|
||||||
update_yaml_file_bulk,
|
update_yaml_file_bulk,
|
||||||
)
|
)
|
||||||
@@ -74,7 +72,7 @@ from frigate.util.config import (
|
|||||||
find_config_file,
|
find_config_file,
|
||||||
redact_credential,
|
redact_credential,
|
||||||
)
|
)
|
||||||
from frigate.util.env import candidate_env_vars, substitute_frigate_vars
|
from frigate.util.env import substitute_frigate_vars
|
||||||
from frigate.util.live_streams import (
|
from frigate.util.live_streams import (
|
||||||
generated_transcode_streams,
|
generated_transcode_streams,
|
||||||
sync_transcode_streams,
|
sync_transcode_streams,
|
||||||
@@ -133,12 +131,37 @@ def stats(
|
|||||||
):
|
):
|
||||||
stats_data = request.app.stats_emitter.get_latest_stats()
|
stats_data = request.app.stats_emitter.get_latest_stats()
|
||||||
|
|
||||||
|
# Admins see the full snapshot
|
||||||
if request.headers.get("remote-role") == "admin":
|
if request.headers.get("remote-role") == "admin":
|
||||||
return JSONResponse(content=stats_data)
|
return JSONResponse(content=stats_data)
|
||||||
|
|
||||||
return JSONResponse(
|
allowed_set = set(allowed_cameras)
|
||||||
content=scope_stats_for_non_admin(stats_data, set(allowed_cameras))
|
|
||||||
)
|
# Shallow-copy so we don't mutate the cached stats history entry.
|
||||||
|
filtered = {**stats_data}
|
||||||
|
|
||||||
|
cameras = stats_data.get("cameras")
|
||||||
|
if cameras is not None:
|
||||||
|
filtered["cameras"] = {
|
||||||
|
name: data for name, data in cameras.items() if name in allowed_set
|
||||||
|
}
|
||||||
|
|
||||||
|
bandwidth = stats_data.get("bandwidth_usages")
|
||||||
|
if bandwidth is not None:
|
||||||
|
filtered["bandwidth_usages"] = {
|
||||||
|
name: data for name, data in bandwidth.items() if name in allowed_set
|
||||||
|
}
|
||||||
|
|
||||||
|
# cmdline can leak camera URLs/paths; strip but keep cpu/mem so
|
||||||
|
# client-side problem heuristics still work.
|
||||||
|
cpu_usages = stats_data.get("cpu_usages")
|
||||||
|
if cpu_usages is not None:
|
||||||
|
filtered["cpu_usages"] = {
|
||||||
|
pid: {k: v for k, v in usage.items() if k != "cmdline"}
|
||||||
|
for pid, usage in cpu_usages.items()
|
||||||
|
}
|
||||||
|
|
||||||
|
return JSONResponse(content=filtered)
|
||||||
|
|
||||||
|
|
||||||
@router.get("/stats/history", dependencies=[Depends(require_role(["admin"]))])
|
@router.get("/stats/history", dependencies=[Depends(require_role(["admin"]))])
|
||||||
@@ -149,7 +172,7 @@ def stats_history(request: Request, keys: str = None):
|
|||||||
return JSONResponse(content=request.app.stats_emitter.get_stats_history(keys))
|
return JSONResponse(content=request.app.stats_emitter.get_stats_history(keys))
|
||||||
|
|
||||||
|
|
||||||
@router.get("/metrics", dependencies=[Depends(require_role(["admin"]))])
|
@router.get("/metrics", dependencies=[Depends(allow_any_authenticated())])
|
||||||
def metrics(request: Request):
|
def metrics(request: Request):
|
||||||
"""Expose Prometheus metrics endpoint and update metrics with latest stats"""
|
"""Expose Prometheus metrics endpoint and update metrics with latest stats"""
|
||||||
# Retrieve the latest statistics and update the Prometheus metrics
|
# Retrieve the latest statistics and update the Prometheus metrics
|
||||||
@@ -297,12 +320,10 @@ def config(request: Request):
|
|||||||
|
|
||||||
is_admin = request.headers.get("remote-role") == "admin"
|
is_admin = request.headers.get("remote-role") == "admin"
|
||||||
|
|
||||||
# hide environment_vars, the notification email and ffmpeg args (which
|
# hide environment_vars and the notification email from non-admin users
|
||||||
# can carry auth headers) from non-admin users
|
|
||||||
if not is_admin:
|
if not is_admin:
|
||||||
config.pop("environment_vars", None)
|
config.pop("environment_vars", None)
|
||||||
redact_credential(config["notifications"], "email")
|
redact_credential(config["notifications"], "email")
|
||||||
_drop_ffmpeg_args(config.get("ffmpeg", {}))
|
|
||||||
|
|
||||||
# redact mqtt credentials
|
# redact mqtt credentials
|
||||||
redact_credential(config["mqtt"], "password")
|
redact_credential(config["mqtt"], "password")
|
||||||
@@ -310,15 +331,11 @@ def config(request: Request):
|
|||||||
# redact proxy secret
|
# redact proxy secret
|
||||||
redact_credential(config["proxy"], "auth_secret")
|
redact_credential(config["proxy"], "auth_secret")
|
||||||
|
|
||||||
# redact genai api keys; base_url and provider_options can carry proxy auth
|
# redact genai api keys
|
||||||
for _genai_name, genai_cfg in config.get("genai", {}).items():
|
for _genai_name, genai_cfg in config.get("genai", {}).items():
|
||||||
if isinstance(genai_cfg, dict):
|
if isinstance(genai_cfg, dict):
|
||||||
redact_credential(genai_cfg, "api_key")
|
redact_credential(genai_cfg, "api_key")
|
||||||
|
|
||||||
if not is_admin:
|
|
||||||
genai_cfg.pop("base_url", None)
|
|
||||||
genai_cfg.pop("provider_options", None)
|
|
||||||
|
|
||||||
for camera_name, camera in request.app.frigate_config.cameras.items():
|
for camera_name, camera in request.app.frigate_config.cameras.items():
|
||||||
camera_dict = config["cameras"][camera_name]
|
camera_dict = config["cameras"][camera_name]
|
||||||
|
|
||||||
@@ -336,19 +353,6 @@ def config(request: Request):
|
|||||||
for cmd in camera_dict["ffmpeg_cmds"]:
|
for cmd in camera_dict["ffmpeg_cmds"]:
|
||||||
cmd["cmd"] = clean_camera_user_pass(" ".join(cmd["cmd"]))
|
cmd["cmd"] = clean_camera_user_pass(" ".join(cmd["cmd"]))
|
||||||
|
|
||||||
# masking misses vendor-specific credentials in paths and args, and the
|
|
||||||
# non-admin UI never reads them
|
|
||||||
if not is_admin:
|
|
||||||
ffmpeg = camera_dict.get("ffmpeg", {})
|
|
||||||
_drop_ffmpeg_args(ffmpeg)
|
|
||||||
|
|
||||||
for input in ffmpeg.get("inputs", []):
|
|
||||||
input["path"] = ""
|
|
||||||
_drop_ffmpeg_args(input)
|
|
||||||
|
|
||||||
camera_dict["ffmpeg_cmds"] = []
|
|
||||||
camera_dict.pop("webui_url", None)
|
|
||||||
|
|
||||||
# ensure that zones are relative
|
# ensure that zones are relative
|
||||||
for zone_name, zone in config_obj.cameras[camera_name].zones.items():
|
for zone_name, zone in config_obj.cameras[camera_name].zones.items():
|
||||||
camera_dict["zones"][zone_name]["color"] = zone.color
|
camera_dict["zones"][zone_name]["color"] = zone.color
|
||||||
@@ -359,13 +363,11 @@ def config(request: Request):
|
|||||||
# over the camera's actual base values (e.g. threshold=20).
|
# over the camera's actual base values (e.g. threshold=20).
|
||||||
if camera.profiles:
|
if camera.profiles:
|
||||||
for profile_name, profile_config in camera.profiles.items():
|
for profile_name, profile_config in camera.profiles.items():
|
||||||
profile_dict = profile_config.model_dump(
|
camera_dict.setdefault("profiles", {})[profile_name] = (
|
||||||
mode="json", warnings="none", exclude_unset=True
|
profile_config.model_dump(
|
||||||
|
mode="json", warnings="none", exclude_unset=True
|
||||||
|
)
|
||||||
)
|
)
|
||||||
camera_dict.setdefault("profiles", {})[profile_name] = profile_dict
|
|
||||||
|
|
||||||
if not is_admin:
|
|
||||||
redact_credential(profile_dict.get("notifications") or {}, "email")
|
|
||||||
|
|
||||||
# When a profile is active, the top-level camera sections contain
|
# When a profile is active, the top-level camera sections contain
|
||||||
# profile-merged (effective) values. Include the original base
|
# profile-merged (effective) values. Include the original base
|
||||||
@@ -407,15 +409,6 @@ def config(request: Request):
|
|||||||
|
|
||||||
_redact_go2rtc_credentials(config["go2rtc"])
|
_redact_go2rtc_credentials(config["go2rtc"])
|
||||||
|
|
||||||
if not is_admin:
|
|
||||||
# go2rtc allows arbitrary extra keys, so non-admins get only what the
|
|
||||||
# UI reads: stream names, and webrtc, whose ice_servers credentials
|
|
||||||
# the browser needs
|
|
||||||
config["go2rtc"] = {
|
|
||||||
"streams": {name: [] for name in config["go2rtc"].get("streams", {})},
|
|
||||||
"webrtc": config["go2rtc"].get("webrtc", {}),
|
|
||||||
}
|
|
||||||
|
|
||||||
config["plus"] = {"enabled": request.app.frigate_config.plus_api.is_active()}
|
config["plus"] = {"enabled": request.app.frigate_config.plus_api.is_active()}
|
||||||
|
|
||||||
for index, model in enumerate(config_obj.models):
|
for index, model in enumerate(config_obj.models):
|
||||||
@@ -442,11 +435,6 @@ def config(request: Request):
|
|||||||
return JSONResponse(content=config)
|
return JSONResponse(content=config)
|
||||||
|
|
||||||
|
|
||||||
def _drop_ffmpeg_args(ffmpeg: dict[str, Any]) -> None:
|
|
||||||
for key in ("global_args", "input_args", "output_args"):
|
|
||||||
ffmpeg.pop(key, None)
|
|
||||||
|
|
||||||
|
|
||||||
def _redact_go2rtc_credentials(go2rtc: dict[str, Any]) -> None:
|
def _redact_go2rtc_credentials(go2rtc: dict[str, Any]) -> None:
|
||||||
"""Redact go2rtc secrets outside of stream URLs, in place."""
|
"""Redact go2rtc secrets outside of stream URLs, in place."""
|
||||||
for section in ("rtsp", "api", "mqtt"):
|
for section in ("rtsp", "api", "mqtt"):
|
||||||
@@ -589,18 +577,14 @@ def config_raw():
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _go2rtc_config(raw_config: str) -> tuple[dict[str, Any], Any]:
|
def _go2rtc_config(raw_config: str) -> dict[str, Any]:
|
||||||
"""Load the go2rtc section and environment_vars with the same loader Frigate
|
"""Load the go2rtc section with the same loader Frigate and go2rtc startup use.
|
||||||
and go2rtc startup use.
|
|
||||||
|
|
||||||
Raises ruamel.yaml.YAMLError when the config cannot be parsed.
|
Raises ruamel.yaml.YAMLError when the config cannot be parsed.
|
||||||
"""
|
"""
|
||||||
loaded = ruamel.yaml.YAML().load(raw_config)
|
loaded = ruamel.yaml.YAML().load(raw_config)
|
||||||
if not isinstance(loaded, dict):
|
go2rtc = loaded.get("go2rtc") if isinstance(loaded, dict) else None
|
||||||
return {}, None
|
return go2rtc if isinstance(go2rtc, dict) else {}
|
||||||
|
|
||||||
go2rtc = loaded.get("go2rtc")
|
|
||||||
return go2rtc if isinstance(go2rtc, dict) else {}, loaded.get("environment_vars")
|
|
||||||
|
|
||||||
|
|
||||||
def _restricted_go2rtc_response(
|
def _restricted_go2rtc_response(
|
||||||
@@ -612,7 +596,7 @@ def _restricted_go2rtc_response(
|
|||||||
otherwise load them from the saved config on the next restart.
|
otherwise load them from the saved config on the next restart.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
new_go2rtc, new_env_vars = _go2rtc_config(new_raw_config)
|
new_go2rtc = _go2rtc_config(new_raw_config)
|
||||||
except ruamel.yaml.YAMLError:
|
except ruamel.yaml.YAMLError:
|
||||||
logger.warning("Rejected config change that could not be parsed")
|
logger.warning("Rejected config change that could not be parsed")
|
||||||
return JSONResponse(
|
return JSONResponse(
|
||||||
@@ -621,13 +605,13 @@ def _restricted_go2rtc_response(
|
|||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
old_go2rtc, _ = _go2rtc_config(old_raw_config)
|
old_go2rtc = _go2rtc_config(old_raw_config)
|
||||||
except ruamel.yaml.YAMLError:
|
except ruamel.yaml.YAMLError:
|
||||||
# with no readable saved config, every source is treated as new
|
# with no readable saved config, every source is treated as new
|
||||||
old_go2rtc = {}
|
old_go2rtc = {}
|
||||||
|
|
||||||
issues = find_restricted_go2rtc_stream_changes(
|
issues = find_restricted_go2rtc_stream_changes(
|
||||||
old_go2rtc.get("streams"), new_go2rtc.get("streams"), new_env_vars
|
old_go2rtc.get("streams"), new_go2rtc.get("streams")
|
||||||
)
|
)
|
||||||
exec_keys = find_restricted_go2rtc_exec_changes(old_go2rtc, new_go2rtc)
|
exec_keys = find_restricted_go2rtc_exec_changes(old_go2rtc, new_go2rtc)
|
||||||
if not issues and not exec_keys:
|
if not issues and not exec_keys:
|
||||||
@@ -791,20 +775,16 @@ def config_save(save_option: str, body: Any = Body(media_type="text/plain")):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _restore_masked_camera_paths(
|
def _restore_masked_camera_paths(config_data: dict, saved: dict) -> str | None:
|
||||||
config_data: dict, saved: dict, shown_env_vars: dict[str, str]
|
|
||||||
) -> str | None:
|
|
||||||
"""Substitute incoming masked camera paths with the saved ones.
|
"""Substitute incoming masked camera paths with the saved ones.
|
||||||
|
|
||||||
The /config response masks ffmpeg input credentials, so the settings UI
|
The /config response masks ffmpeg input credentials, so the settings UI
|
||||||
sends the masked path back when sibling fields (e.g. hwaccel_args) are
|
sends the masked path back when sibling fields (e.g. hwaccel_args) are
|
||||||
edited. Each masked path is matched to the saved input that masks to the
|
edited. Each masked path is matched to the saved input that masks to the
|
||||||
same value, with roles breaking a tie, so deleting or reordering inputs
|
same value, with roles breaking a tie, so deleting or reordering inputs
|
||||||
keeps each path's own credentials. Saved paths resolve with
|
keeps each path's own credentials. The saved path is restored as written,
|
||||||
`shown_env_vars`, the block the running config and /config used. The saved
|
keeping any {FRIGATE_*} placeholder. Mutates `config_data` in place and
|
||||||
path is restored as written, keeping any {FRIGATE_*} placeholder. Mutates
|
returns an error message when a masked path has no single match.
|
||||||
`config_data` in place and returns an error message when a masked path has
|
|
||||||
no single match.
|
|
||||||
"""
|
"""
|
||||||
cameras = config_data.get("cameras")
|
cameras = config_data.get("cameras")
|
||||||
if not isinstance(cameras, dict):
|
if not isinstance(cameras, dict):
|
||||||
@@ -840,13 +820,11 @@ def _restore_masked_camera_paths(
|
|||||||
path = input_obj.get("path")
|
path = input_obj.get("path")
|
||||||
if not isinstance(path, str) or not is_masked_camera_path(path):
|
if not isinstance(path, str) or not is_masked_camera_path(path):
|
||||||
continue
|
continue
|
||||||
with candidate_env_vars(shown_env_vars):
|
candidates = [
|
||||||
candidates = [
|
inp
|
||||||
inp
|
for inp in saved_inputs
|
||||||
for inp in saved_inputs
|
if clean_camera_user_pass(_resolve_frigate_vars(inp["path"])) == path
|
||||||
if clean_camera_user_pass(_resolve_frigate_vars(inp["path"]))
|
]
|
||||||
== path
|
|
||||||
]
|
|
||||||
if len({inp["path"] for inp in candidates}) > 1:
|
if len({inp["path"] for inp in candidates}) > 1:
|
||||||
candidates = [
|
candidates = [
|
||||||
inp
|
inp
|
||||||
@@ -890,14 +868,14 @@ def _saved_config_from_memory(config: FrigateConfig) -> dict[str, Any]:
|
|||||||
|
|
||||||
|
|
||||||
def _config_data_to_updates(
|
def _config_data_to_updates(
|
||||||
config_data: dict, saved: dict[str, Any], running: FrigateConfig
|
config_data: dict, saved: dict[str, Any]
|
||||||
) -> tuple[dict[str, Any], str | None]:
|
) -> tuple[dict[str, Any], str | None]:
|
||||||
"""Flatten a /config/set payload after restoring masked credentials.
|
"""Flatten a /config/set payload after restoring masked credentials.
|
||||||
|
|
||||||
`saved` is the config the masked values were taken from. Returns the flat
|
`saved` is the config the masked values were taken from. Returns the flat
|
||||||
updates, or an error message when a masked value can't be restored.
|
updates, or an error message when a masked value can't be restored.
|
||||||
"""
|
"""
|
||||||
error = _restore_masked_camera_paths(config_data, saved, running.environment_vars)
|
error = _restore_masked_camera_paths(config_data, saved)
|
||||||
if error:
|
if error:
|
||||||
return {}, error
|
return {}, error
|
||||||
|
|
||||||
@@ -951,9 +929,7 @@ def _config_set_in_memory(request: Request, body: AppConfigSetBody) -> JSONRespo
|
|||||||
updates = {}
|
updates = {}
|
||||||
if body.config_data:
|
if body.config_data:
|
||||||
updates, error = _config_data_to_updates(
|
updates, error = _config_data_to_updates(
|
||||||
body.config_data,
|
body.config_data, _saved_config_from_memory(request.app.frigate_config)
|
||||||
_saved_config_from_memory(request.app.frigate_config),
|
|
||||||
request.app.frigate_config,
|
|
||||||
)
|
)
|
||||||
if error:
|
if error:
|
||||||
return JSONResponse(
|
return JSONResponse(
|
||||||
@@ -1134,7 +1110,6 @@ def config_set(request: Request, body: AppConfigSetBody):
|
|||||||
updates, error = _config_data_to_updates(
|
updates, error = _config_data_to_updates(
|
||||||
body.config_data,
|
body.config_data,
|
||||||
saved_config if isinstance(saved_config, dict) else {},
|
saved_config if isinstance(saved_config, dict) else {},
|
||||||
request.app.frigate_config,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if error:
|
if error:
|
||||||
@@ -1679,10 +1654,7 @@ def plusModels(request: Request, filterByCurrentModelDetector: bool = False):
|
|||||||
status_code=400,
|
status_code=400,
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
models: dict[Any, Any] = request.app.frigate_config.plus_api.get_models()
|
||||||
models: dict[Any, Any] = request.app.frigate_config.plus_api.get_models()
|
|
||||||
except PlusRateLimitError as err:
|
|
||||||
return plus_rate_limited_response(err)
|
|
||||||
|
|
||||||
if not models["list"]:
|
if not models["list"]:
|
||||||
return JSONResponse(
|
return JSONResponse(
|
||||||
@@ -1722,17 +1694,11 @@ def plusModels(request: Request, filterByCurrentModelDetector: bool = False):
|
|||||||
@router.post("/plus/validate", dependencies=[Depends(require_role(["admin"]))])
|
@router.post("/plus/validate", dependencies=[Depends(require_role(["admin"]))])
|
||||||
async def validate_plus_key(request: Request):
|
async def validate_plus_key(request: Request):
|
||||||
"""Validate the configured Frigate+ API key with the Frigate+ server."""
|
"""Validate the configured Frigate+ API key with the Frigate+ server."""
|
||||||
plus_api = request.app.frigate_config.plus_api
|
status = await request.app.frigate_config.plus_api.validate_key()
|
||||||
status = await plus_api.validate_key()
|
|
||||||
content: dict[str, Any] = {
|
|
||||||
"success": status == PlusKeyStatus.valid,
|
|
||||||
"status": status.value,
|
|
||||||
}
|
|
||||||
|
|
||||||
if status == PlusKeyStatus.rate_limited:
|
return JSONResponse(
|
||||||
content["retry_after"] = plus_api.rate_limit_remaining()
|
content={"success": status == PlusKeyStatus.valid, "status": status.value}
|
||||||
|
)
|
||||||
return JSONResponse(content=content)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
|
|||||||
+18
-16
@@ -81,11 +81,10 @@ def require_admin_by_default():
|
|||||||
"/",
|
"/",
|
||||||
"/version",
|
"/version",
|
||||||
"/config/schema.json",
|
"/config/schema.json",
|
||||||
# Admin endpoints that enforce require_role on the route
|
|
||||||
"/metrics",
|
|
||||||
"/stats/history",
|
|
||||||
# Authenticated user endpoints (allow_any_authenticated)
|
# Authenticated user endpoints (allow_any_authenticated)
|
||||||
|
"/metrics",
|
||||||
"/stats",
|
"/stats",
|
||||||
|
"/stats/history",
|
||||||
"/config",
|
"/config",
|
||||||
"/vainfo",
|
"/vainfo",
|
||||||
"/nvinfo",
|
"/nvinfo",
|
||||||
@@ -581,9 +580,8 @@ def resolve_role(
|
|||||||
(split by proxy_config.separator) and map to roles.
|
(split by proxy_config.separator) and map to roles.
|
||||||
Admin matches short-circuit to admin.
|
Admin matches short-circuit to admin.
|
||||||
- If no role_map is configured, treat the header as role names directly.
|
- If no role_map is configured, treat the header as role names directly.
|
||||||
2. If no valid role is found, return proxy_config.default_role if it's valid in config_roles, else 'none'.
|
2. If no valid role is found, return proxy_config.default_role if it's valid in config_roles, else 'viewer'.
|
||||||
The literal value 'none' means access should be denied.
|
The literal value 'none' is a valid default and means access should be denied.
|
||||||
A role_map match whose mapped roles no longer exist in config_roles also resolves to 'none'.
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
headers (dict): Incoming request headers (case-insensitive).
|
headers (dict): Incoming request headers (case-insensitive).
|
||||||
@@ -596,11 +594,17 @@ def resolve_role(
|
|||||||
default_role = proxy_config.default_role
|
default_role = proxy_config.default_role
|
||||||
role_header = proxy_config.header_map.role
|
role_header = proxy_config.header_map.role
|
||||||
|
|
||||||
# Role names match case-insensitively, as header values are lowercased.
|
# Validate default_role against config; fallback to 'viewer' if invalid.
|
||||||
# "none" is the deny sentinel; an unknown or missing default also denies,
|
# "none" is a sentinel meaning "deny access when no mapping matches"; it is
|
||||||
# since falling back to viewer would grant every camera.
|
# reserved in AuthConfig.validate_roles so it is never a configured role.
|
||||||
roles_by_name = {r.lower(): r for r in config_roles}
|
validated_default = (
|
||||||
validated_default = roles_by_name.get((default_role or "").lower(), "none")
|
default_role
|
||||||
|
if default_role in config_roles or default_role == "none"
|
||||||
|
else "viewer"
|
||||||
|
)
|
||||||
|
if not config_roles:
|
||||||
|
# Edge case: no roles defined
|
||||||
|
validated_default = "none" if default_role == "none" else "viewer"
|
||||||
|
|
||||||
if not role_header:
|
if not role_header:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
@@ -627,7 +631,7 @@ def resolve_role(
|
|||||||
logger.debug("Parsed groups from role header: %s", groups)
|
logger.debug("Parsed groups from role header: %s", groups)
|
||||||
|
|
||||||
matched_roles = {
|
matched_roles = {
|
||||||
role_name.lower()
|
role_name
|
||||||
for role_name, required_groups in proxy_config.header_map.role_map.items()
|
for role_name, required_groups in proxy_config.header_map.role_map.items()
|
||||||
if any(group in groups for group in required_groups)
|
if any(group in groups for group in required_groups)
|
||||||
}
|
}
|
||||||
@@ -639,11 +643,9 @@ def resolve_role(
|
|||||||
logger.debug("Resolved role (with role_map) to 'admin'.")
|
logger.debug("Resolved role (with role_map) to 'admin'.")
|
||||||
return "admin"
|
return "admin"
|
||||||
|
|
||||||
# A mapped role that was deleted or renamed denies rather than
|
|
||||||
# widening to the default role
|
|
||||||
if matched_roles:
|
if matched_roles:
|
||||||
resolved = next(
|
resolved = next(
|
||||||
(r for r in config_roles if r.lower() in matched_roles), "none"
|
(r for r in config_roles if r in matched_roles), validated_default
|
||||||
)
|
)
|
||||||
logger.debug("Resolved role (with role_map) to '%s'.", resolved)
|
logger.debug("Resolved role (with role_map) to '%s'.", resolved)
|
||||||
return resolved
|
return resolved
|
||||||
@@ -662,7 +664,7 @@ def resolve_role(
|
|||||||
logger.debug("Parsed roles directly from header: %s", roles_from_header)
|
logger.debug("Parsed roles directly from header: %s", roles_from_header)
|
||||||
|
|
||||||
resolved = next(
|
resolved = next(
|
||||||
(r for r in config_roles if r.lower() in roles_from_header),
|
(r for r in config_roles if r in roles_from_header),
|
||||||
validated_default,
|
validated_default,
|
||||||
)
|
)
|
||||||
if resolved == validated_default and roles_from_header:
|
if resolved == validated_default and roles_from_header:
|
||||||
|
|||||||
+8
-24
@@ -6,7 +6,6 @@ import logging
|
|||||||
import re
|
import re
|
||||||
from importlib.util import find_spec
|
from importlib.util import find_spec
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
|
||||||
from urllib.parse import quote_plus
|
from urllib.parse import quote_plus
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
@@ -83,23 +82,6 @@ def _is_valid_host(host: str) -> bool:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def _clean_stream(request: Request, stream: dict[str, Any]) -> dict[str, Any]:
|
|
||||||
"""Mask producer urls for admins; others get only producer medias.
|
|
||||||
|
|
||||||
Producer and consumer urls and sources can carry credentials that masking
|
|
||||||
misses, and the non-admin UI only reads producer medias.
|
|
||||||
"""
|
|
||||||
producers = stream.get("producers") or []
|
|
||||||
|
|
||||||
if request.headers.get("remote-role") != "admin":
|
|
||||||
return {"producers": [{"medias": p.get("medias")} for p in producers]}
|
|
||||||
|
|
||||||
for producer in producers:
|
|
||||||
producer["url"] = clean_camera_user_pass(producer.get("url", ""))
|
|
||||||
|
|
||||||
return stream
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/go2rtc/streams", dependencies=[Depends(allow_any_authenticated())])
|
@router.get("/go2rtc/streams", dependencies=[Depends(allow_any_authenticated())])
|
||||||
async def go2rtc_streams(request: Request):
|
async def go2rtc_streams(request: Request):
|
||||||
try:
|
try:
|
||||||
@@ -132,11 +114,10 @@ async def go2rtc_streams(request: Request):
|
|||||||
if _get_stream_owner_cameras(request, name) & allowed_cameras
|
if _get_stream_owner_cameras(request, name) & allowed_cameras
|
||||||
}
|
}
|
||||||
|
|
||||||
return JSONResponse(
|
for data in stream_data.values():
|
||||||
content={
|
for producer in data.get("producers") or []:
|
||||||
name: _clean_stream(request, data) for name, data in stream_data.items()
|
producer["url"] = clean_camera_user_pass(producer.get("url", ""))
|
||||||
}
|
return JSONResponse(content=stream_data)
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
@@ -174,7 +155,10 @@ def go2rtc_camera_stream(request: Request, stream_name: str):
|
|||||||
content=({"success": False, "message": "Error fetching stream data"}),
|
content=({"success": False, "message": "Error fetching stream data"}),
|
||||||
status_code=500,
|
status_code=500,
|
||||||
)
|
)
|
||||||
return JSONResponse(content=_clean_stream(request, r.json()))
|
stream_data = r.json()
|
||||||
|
for producer in stream_data.get("producers", []):
|
||||||
|
producer["url"] = clean_camera_user_pass(producer.get("url", ""))
|
||||||
|
return JSONResponse(content=stream_data)
|
||||||
|
|
||||||
|
|
||||||
@router.put(
|
@router.put(
|
||||||
|
|||||||
+4
-22
@@ -6,7 +6,6 @@ import json
|
|||||||
import logging
|
import logging
|
||||||
import operator
|
import operator
|
||||||
import time
|
import time
|
||||||
import uuid
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from functools import reduce
|
from functools import reduce
|
||||||
from typing import Any, Literal
|
from typing import Any, Literal
|
||||||
@@ -15,7 +14,7 @@ import cv2
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
from fastapi import APIRouter, Body, Depends, HTTPException, Request
|
from fastapi import APIRouter, Body, Depends, HTTPException, Request
|
||||||
from fastapi.responses import JSONResponse, StreamingResponse
|
from fastapi.responses import JSONResponse, StreamingResponse
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel
|
||||||
|
|
||||||
from frigate.api.auth import (
|
from frigate.api.auth import (
|
||||||
allow_any_authenticated,
|
allow_any_authenticated,
|
||||||
@@ -57,7 +56,6 @@ from frigate.genai.utils import (
|
|||||||
)
|
)
|
||||||
from frigate.jobs.export import ExportQueueFullError, start_export_job
|
from frigate.jobs.export import ExportQueueFullError, start_export_job
|
||||||
from frigate.jobs.vlm_watch import (
|
from frigate.jobs.vlm_watch import (
|
||||||
MAX_WATCH_MINUTES,
|
|
||||||
VLMWatchJob,
|
VLMWatchJob,
|
||||||
get_vlm_watch_job,
|
get_vlm_watch_job,
|
||||||
start_vlm_watch_job,
|
start_vlm_watch_job,
|
||||||
@@ -90,7 +88,7 @@ class VLMMonitorRequest(BaseModel):
|
|||||||
|
|
||||||
camera: str
|
camera: str
|
||||||
condition: str
|
condition: str
|
||||||
max_duration_minutes: int = Field(default=60, ge=1, le=MAX_WATCH_MINUTES)
|
max_duration_minutes: int = 60
|
||||||
labels: list[str] = []
|
labels: list[str] = []
|
||||||
zones: list[str] = []
|
zones: list[str] = []
|
||||||
|
|
||||||
@@ -1032,17 +1030,12 @@ async def _execute_start_camera_watch(
|
|||||||
camera = arguments.get("camera", "").strip()
|
camera = arguments.get("camera", "").strip()
|
||||||
condition = arguments.get("condition", "").strip()
|
condition = arguments.get("condition", "").strip()
|
||||||
max_duration_minutes = int(arguments.get("max_duration_minutes", 60))
|
max_duration_minutes = int(arguments.get("max_duration_minutes", 60))
|
||||||
max_duration_minutes = max(1, min(MAX_WATCH_MINUTES, max_duration_minutes))
|
|
||||||
labels = arguments.get("labels") or []
|
labels = arguments.get("labels") or []
|
||||||
zones = arguments.get("zones") or []
|
zones = arguments.get("zones") or []
|
||||||
|
|
||||||
if not camera or not condition:
|
if not camera or not condition:
|
||||||
return {"error": "camera and condition are required."}
|
return {"error": "camera and condition are required."}
|
||||||
|
|
||||||
for value in (labels, zones):
|
|
||||||
if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
|
|
||||||
return {"error": "labels and zones must be lists of strings."}
|
|
||||||
|
|
||||||
config = request.app.frigate_config
|
config = request.app.frigate_config
|
||||||
if camera not in config.cameras:
|
if camera not in config.cameras:
|
||||||
return {"error": f"Camera '{camera}' not found."}
|
return {"error": f"Camera '{camera}' not found."}
|
||||||
@@ -1281,14 +1274,6 @@ def _pending_tool_calls_from_tail(
|
|||||||
return parse_tool_calls_from_message(tail)
|
return parse_tool_calls_from_message(tail)
|
||||||
|
|
||||||
|
|
||||||
def _with_server_ids(tool_calls: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
||||||
"""Give each model tool call a unique id.
|
|
||||||
|
|
||||||
Approvals are keyed by id, and some providers reuse ids across calls.
|
|
||||||
"""
|
|
||||||
return [{**tc, "id": uuid.uuid4().hex[:9]} for tc in tool_calls]
|
|
||||||
|
|
||||||
|
|
||||||
def _tool_calls_awaiting_approval(
|
def _tool_calls_awaiting_approval(
|
||||||
pending_tool_calls: list[dict[str, Any]],
|
pending_tool_calls: list[dict[str, Any]],
|
||||||
body: ChatCompletionRequest,
|
body: ChatCompletionRequest,
|
||||||
@@ -1614,7 +1599,6 @@ async def chat_completion(
|
|||||||
return
|
return
|
||||||
requested = msg.get("tool_calls")
|
requested = msg.get("tool_calls")
|
||||||
if requested:
|
if requested:
|
||||||
requested = _with_server_ids(requested)
|
|
||||||
stream_iterations += 1
|
stream_iterations += 1
|
||||||
conversation.append(
|
conversation.append(
|
||||||
build_assistant_message_for_conversation(
|
build_assistant_message_for_conversation(
|
||||||
@@ -1700,15 +1684,13 @@ async def chat_completion(
|
|||||||
status_code=500,
|
status_code=500,
|
||||||
)
|
)
|
||||||
|
|
||||||
pending_tool_calls = response.get("tool_calls")
|
|
||||||
if pending_tool_calls:
|
|
||||||
pending_tool_calls = _with_server_ids(pending_tool_calls)
|
|
||||||
conversation.append(
|
conversation.append(
|
||||||
build_assistant_message_for_conversation(
|
build_assistant_message_for_conversation(
|
||||||
response.get("content"), pending_tool_calls
|
response.get("content"), response.get("tool_calls")
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
pending_tool_calls = response.get("tool_calls")
|
||||||
if not pending_tool_calls:
|
if not pending_tool_calls:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
f"Chat completion finished with final answer (iterations: {tool_iterations})"
|
f"Chat completion finished with final answer (iterations: {tool_iterations})"
|
||||||
|
|||||||
@@ -216,28 +216,26 @@ def train_face(request: Request, name: str, body: dict = None):
|
|||||||
status_code=404,
|
status_code=404,
|
||||||
)
|
)
|
||||||
|
|
||||||
attributes = (event.data or {}).get("attributes") or []
|
snapshot = get_event_snapshot(event)
|
||||||
snapshot = get_event_snapshot(event) if attributes else None
|
face_box = event.data["attributes"][0]["box"]
|
||||||
success = False
|
detect_config: DetectConfig = request.app.frigate_config.cameras[
|
||||||
|
event.camera
|
||||||
|
].detect
|
||||||
|
|
||||||
if snapshot is not None:
|
# crop onto the face box minus the bounding box itself
|
||||||
face_box = attributes[0]["box"]
|
x1 = int(face_box[0] * detect_config.width) + 2
|
||||||
detect_config: DetectConfig = request.app.frigate_config.cameras[
|
y1 = int(face_box[1] * detect_config.height) + 2
|
||||||
event.camera
|
x2 = x1 + int(face_box[2] * detect_config.width) - 4
|
||||||
].detect
|
y2 = y1 + int(face_box[3] * detect_config.height) - 4
|
||||||
|
face = snapshot[y1:y2, x1:x2]
|
||||||
|
success = True
|
||||||
|
|
||||||
# crop onto the face box minus the bounding box itself
|
if face.size > 0:
|
||||||
x1 = int(face_box[0] * detect_config.width) + 2
|
try:
|
||||||
y1 = int(face_box[1] * detect_config.height) + 2
|
cv2.imwrite(os.path.join(new_file_folder, new_name), face)
|
||||||
x2 = x1 + int(face_box[2] * detect_config.width) - 4
|
success = True
|
||||||
y2 = y1 + int(face_box[3] * detect_config.height) - 4
|
except Exception:
|
||||||
face = snapshot[y1:y2, x1:x2]
|
pass
|
||||||
|
|
||||||
if face.size > 0:
|
|
||||||
try:
|
|
||||||
success = cv2.imwrite(os.path.join(new_file_folder, new_name), face)
|
|
||||||
except cv2.error:
|
|
||||||
logger.exception("Failed to save face image for %s", event_id)
|
|
||||||
|
|
||||||
if not success:
|
if not success:
|
||||||
return JSONResponse(
|
return JSONResponse(
|
||||||
@@ -1275,10 +1273,7 @@ async def generate_state_examples(request: Request, body: GenerateStateExamplesB
|
|||||||
if camera_name in request.app.frigate_config.cameras
|
if camera_name in request.app.frigate_config.cameras
|
||||||
}
|
}
|
||||||
|
|
||||||
async with example_collection_lock:
|
collect_state_classification_examples(model_name, cameras_normalized)
|
||||||
await asyncio.to_thread(
|
|
||||||
collect_state_classification_examples, model_name, cameras_normalized
|
|
||||||
)
|
|
||||||
|
|
||||||
return JSONResponse(
|
return JSONResponse(
|
||||||
content={"success": True, "message": "Example generation completed"},
|
content={"success": True, "message": "Example generation completed"},
|
||||||
|
|||||||
@@ -41,9 +41,6 @@ def swap_runtime_config(app: FastAPI, config: FrigateConfig) -> None:
|
|||||||
"""
|
"""
|
||||||
app.frigate_config = config
|
app.frigate_config = config
|
||||||
|
|
||||||
if app.replay_manager is not None:
|
|
||||||
app.replay_manager.update_config(config)
|
|
||||||
|
|
||||||
if app.config_holder is not None:
|
if app.config_holder is not None:
|
||||||
app.config_holder.set(config)
|
app.config_holder.set(config)
|
||||||
|
|
||||||
|
|||||||
@@ -9,8 +9,8 @@ class MediaRecordingsSummaryQueryParams(BaseModel):
|
|||||||
|
|
||||||
class MediaRecordingsAvailabilityQueryParams(BaseModel):
|
class MediaRecordingsAvailabilityQueryParams(BaseModel):
|
||||||
cameras: str = "all"
|
cameras: str = "all"
|
||||||
before: float | SkipJsonSchema[None] = Field(default=None, allow_inf_nan=False)
|
before: float | SkipJsonSchema[None] = None
|
||||||
after: float | SkipJsonSchema[None] = Field(default=None, allow_inf_nan=False)
|
after: float | SkipJsonSchema[None] = None
|
||||||
scale: int = Field(default=30, ge=1)
|
scale: int = Field(default=30, ge=1)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+35
-61
@@ -53,13 +53,11 @@ from frigate.api.defs.response.event_response 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.api.plus_util import plus_rate_limited_response
|
|
||||||
from frigate.comms.event_metadata_updater import EventMetadataTypeEnum
|
from frigate.comms.event_metadata_updater import EventMetadataTypeEnum
|
||||||
from frigate.config.classification import ObjectClassificationType
|
from frigate.config.classification import ObjectClassificationType
|
||||||
from frigate.const import CLIPS_DIR
|
from frigate.const import CLIPS_DIR
|
||||||
from frigate.embeddings import EmbeddingsContext
|
from frigate.embeddings import EmbeddingsContext
|
||||||
from frigate.models import Event, ReviewSegment, Timeline, Trigger
|
from frigate.models import Event, ReviewSegment, Timeline, Trigger
|
||||||
from frigate.plus import PlusRateLimitError
|
|
||||||
from frigate.track.object_processing import TrackedObject
|
from frigate.track.object_processing import TrackedObject
|
||||||
from frigate.util.file import get_event_thumbnail_bytes, load_event_snapshot_image
|
from frigate.util.file import get_event_thumbnail_bytes, load_event_snapshot_image
|
||||||
from frigate.util.path import get_trigger_thumbnail_path, safe_join
|
from frigate.util.path import get_trigger_thumbnail_path, safe_join
|
||||||
@@ -69,9 +67,6 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
router = APIRouter(tags=[Tags.events])
|
router = APIRouter(tags=[Tags.events])
|
||||||
|
|
||||||
# event.data key holding a Frigate+ image id until its annotation is uploaded
|
|
||||||
PLUS_PENDING_ID_KEY = "plus_pending_id"
|
|
||||||
|
|
||||||
|
|
||||||
def _build_attribute_filter_clause(attributes: str):
|
def _build_attribute_filter_clause(attributes: str):
|
||||||
filtered_attributes = [
|
filtered_attributes = [
|
||||||
@@ -1117,55 +1112,43 @@ async def send_to_plus(request: Request, event_id: str, body: SubmitPlusBody = N
|
|||||||
content=({"success": False, "message": message}), status_code=400
|
content=({"success": False, "message": message}), status_code=400
|
||||||
)
|
)
|
||||||
|
|
||||||
# an image uploaded by an earlier attempt whose annotation failed, so a
|
try:
|
||||||
# retry finishes that submission instead of uploading the image again
|
image, is_clean_snapshot = load_event_snapshot_image(event, clean_only=True)
|
||||||
plus_id = event.data.get(PLUS_PENDING_ID_KEY)
|
except Exception:
|
||||||
|
logger.error(f"Unable to load clean snapshot for event: {event.id}")
|
||||||
|
return JSONResponse(
|
||||||
|
content=(
|
||||||
|
{"success": False, "message": "Unable to load clean snapshot for event"}
|
||||||
|
),
|
||||||
|
status_code=400,
|
||||||
|
)
|
||||||
|
|
||||||
if plus_id is None:
|
if not is_clean_snapshot or image is None or image.size == 0:
|
||||||
try:
|
logger.error(f"Unable to find clean snapshot for event: {event.id}")
|
||||||
image, is_clean_snapshot = load_event_snapshot_image(event, clean_only=True)
|
return JSONResponse(
|
||||||
except Exception:
|
content=(
|
||||||
logger.error(f"Unable to load clean snapshot for event: {event.id}")
|
{
|
||||||
return JSONResponse(
|
"success": False,
|
||||||
content=(
|
"message": "Unable to find clean snapshot for event",
|
||||||
{
|
}
|
||||||
"success": False,
|
),
|
||||||
"message": "Unable to load clean snapshot for event",
|
status_code=400,
|
||||||
}
|
)
|
||||||
),
|
|
||||||
status_code=400,
|
|
||||||
)
|
|
||||||
|
|
||||||
if not is_clean_snapshot or image is None or image.size == 0:
|
try:
|
||||||
logger.error(f"Unable to find clean snapshot for event: {event.id}")
|
plus_id = await asyncio.to_thread(
|
||||||
return JSONResponse(
|
request.app.frigate_config.plus_api.upload_image, image, event.camera
|
||||||
content=(
|
)
|
||||||
{
|
except Exception as ex:
|
||||||
"success": False,
|
logger.exception(ex)
|
||||||
"message": "Unable to find clean snapshot for event",
|
return JSONResponse(
|
||||||
}
|
content=({"success": False, "message": "Error uploading image"}),
|
||||||
),
|
status_code=400,
|
||||||
status_code=400,
|
)
|
||||||
)
|
|
||||||
|
|
||||||
try:
|
# store image id in the database
|
||||||
plus_id = await asyncio.to_thread(
|
event.plus_id = plus_id
|
||||||
request.app.frigate_config.plus_api.upload_image, image, event.camera
|
event.save()
|
||||||
)
|
|
||||||
except PlusRateLimitError as err:
|
|
||||||
return plus_rate_limited_response(err)
|
|
||||||
except Exception as ex:
|
|
||||||
logger.exception(ex)
|
|
||||||
return JSONResponse(
|
|
||||||
content=({"success": False, "message": "Error uploading image"}),
|
|
||||||
status_code=400,
|
|
||||||
)
|
|
||||||
|
|
||||||
if include_annotation is not None:
|
|
||||||
# the image isn't marked submitted until its annotation is, or a
|
|
||||||
# failed annotation could never be retried
|
|
||||||
event.data[PLUS_PENDING_ID_KEY] = plus_id
|
|
||||||
event.save()
|
|
||||||
|
|
||||||
if include_annotation is not None:
|
if include_annotation is not None:
|
||||||
box = event.data["box"]
|
box = event.data["box"]
|
||||||
@@ -1173,12 +1156,10 @@ async def send_to_plus(request: Request, event_id: str, body: SubmitPlusBody = N
|
|||||||
try:
|
try:
|
||||||
await asyncio.to_thread(
|
await asyncio.to_thread(
|
||||||
request.app.frigate_config.plus_api.add_annotation,
|
request.app.frigate_config.plus_api.add_annotation,
|
||||||
plus_id,
|
event.plus_id,
|
||||||
box,
|
box,
|
||||||
event.label,
|
event.label,
|
||||||
)
|
)
|
||||||
except PlusRateLimitError as err:
|
|
||||||
return plus_rate_limited_response(err)
|
|
||||||
except ValueError:
|
except ValueError:
|
||||||
message = "Error uploading annotation, unsupported label provided."
|
message = "Error uploading annotation, unsupported label provided."
|
||||||
logger.error(message)
|
logger.error(message)
|
||||||
@@ -1193,11 +1174,6 @@ async def send_to_plus(request: Request, event_id: str, body: SubmitPlusBody = N
|
|||||||
status_code=400,
|
status_code=400,
|
||||||
)
|
)
|
||||||
|
|
||||||
# store image id in the database
|
|
||||||
event.plus_id = plus_id
|
|
||||||
event.data.pop(PLUS_PENDING_ID_KEY, None)
|
|
||||||
event.save()
|
|
||||||
|
|
||||||
return JSONResponse(
|
return JSONResponse(
|
||||||
content=({"success": True, "plus_id": plus_id}), status_code=200
|
content=({"success": True, "plus_id": plus_id}), status_code=200
|
||||||
)
|
)
|
||||||
@@ -1280,8 +1256,6 @@ async def false_positive(request: Request, event_id: str):
|
|||||||
event.model_type,
|
event.model_type,
|
||||||
event.detector_type,
|
event.detector_type,
|
||||||
)
|
)
|
||||||
except PlusRateLimitError as err:
|
|
||||||
return plus_rate_limited_response(err)
|
|
||||||
except ValueError:
|
except ValueError:
|
||||||
message = "Error uploading false positive, unsupported label provided."
|
message = "Error uploading false positive, unsupported label provided."
|
||||||
logger.error(message)
|
logger.error(message)
|
||||||
|
|||||||
@@ -88,7 +88,7 @@ def create_fastapi_app(
|
|||||||
logger.info("FastAPI started")
|
logger.info("FastAPI started")
|
||||||
asyncio.create_task(
|
asyncio.create_task(
|
||||||
debug_replay_auto_stop_watchdog(
|
debug_replay_auto_stop_watchdog(
|
||||||
replay_manager, lambda: app.frigate_config, config_publisher
|
replay_manager, frigate_config, config_publisher
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
yield
|
yield
|
||||||
|
|||||||
+11
-22
@@ -36,7 +36,6 @@ from frigate.api.defs.query.media_query_parameters import (
|
|||||||
MediaMjpegFeedQueryParams,
|
MediaMjpegFeedQueryParams,
|
||||||
)
|
)
|
||||||
from frigate.api.defs.tags import Tags
|
from frigate.api.defs.tags import Tags
|
||||||
from frigate.api.plus_util import plus_rate_limited_response
|
|
||||||
from frigate.camera.state import CameraState
|
from frigate.camera.state import CameraState
|
||||||
from frigate.config import FrigateConfig
|
from frigate.config import FrigateConfig
|
||||||
from frigate.config.camera.snapshots import SnapshotsConfig
|
from frigate.config.camera.snapshots import SnapshotsConfig
|
||||||
@@ -48,11 +47,7 @@ from frigate.const import (
|
|||||||
STREAM_TYPE_SUB,
|
STREAM_TYPE_SUB,
|
||||||
)
|
)
|
||||||
from frigate.models import Event, Previews, Recordings, Regions, ReviewSegment
|
from frigate.models import Event, Previews, Recordings, Regions, ReviewSegment
|
||||||
from frigate.output.preview import (
|
from frigate.output.preview import get_most_recent_preview_frame
|
||||||
get_most_recent_preview_frame,
|
|
||||||
is_camera_preview_frame,
|
|
||||||
)
|
|
||||||
from frigate.plus import PlusRateLimitError
|
|
||||||
from frigate.track.object_processing import TrackedObjectProcessor
|
from frigate.track.object_processing import TrackedObjectProcessor
|
||||||
from frigate.util.ffmpeg import terminate_ffmpeg_stream
|
from frigate.util.ffmpeg import terminate_ffmpeg_stream
|
||||||
from frigate.util.file import (
|
from frigate.util.file import (
|
||||||
@@ -171,13 +166,10 @@ def imagestream(
|
|||||||
time.sleep(1 / fps)
|
time.sleep(1 / fps)
|
||||||
frame = detected_frames_processor.get_current_frame(camera_name, draw_options)
|
frame = detected_frames_processor.get_current_frame(camera_name, draw_options)
|
||||||
if frame is None:
|
if frame is None:
|
||||||
frame = np.zeros((360, 640, 3), np.uint8)
|
frame = np.zeros((height, int(height * 16 / 9), 3), np.uint8)
|
||||||
|
|
||||||
frame_height = min(height, frame.shape[0])
|
width = int(height * frame.shape[1] / frame.shape[0])
|
||||||
width = int(frame_height * frame.shape[1] / frame.shape[0])
|
frame = cv2.resize(frame, dsize=(width, height), interpolation=cv2.INTER_LINEAR)
|
||||||
frame = cv2.resize(
|
|
||||||
frame, dsize=(width, frame_height), interpolation=cv2.INTER_LINEAR
|
|
||||||
)
|
|
||||||
|
|
||||||
ret, jpg = cv2.imencode(".jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), 70])
|
ret, jpg = cv2.imencode(".jpg", frame, [int(cv2.IMWRITE_JPEG_QUALITY), 70])
|
||||||
yield (
|
yield (
|
||||||
@@ -286,7 +278,7 @@ async def latest_frame(
|
|||||||
status_code=500,
|
status_code=500,
|
||||||
)
|
)
|
||||||
|
|
||||||
height = min(params.height or frame.shape[0], frame.shape[0])
|
height = int(params.height or str(frame.shape[0]))
|
||||||
width = int(height * frame.shape[1] / frame.shape[0])
|
width = int(height * frame.shape[1] / frame.shape[0])
|
||||||
|
|
||||||
if height < 1 or width < 1:
|
if height < 1 or width < 1:
|
||||||
@@ -328,7 +320,7 @@ async def latest_frame(
|
|||||||
|
|
||||||
frame = cv2.cvtColor(frame, cv2.COLOR_YUV2BGR_I420)
|
frame = cv2.cvtColor(frame, cv2.COLOR_YUV2BGR_I420)
|
||||||
|
|
||||||
height = min(params.height or frame.shape[0], frame.shape[0])
|
height = int(params.height or str(frame.shape[0]))
|
||||||
width = int(height * frame.shape[1] / frame.shape[0])
|
width = int(height * frame.shape[1] / frame.shape[0])
|
||||||
|
|
||||||
frame = cv2.resize(frame, dsize=(width, height), interpolation=cv2.INTER_AREA)
|
frame = cv2.resize(frame, dsize=(width, height), interpolation=cv2.INTER_AREA)
|
||||||
@@ -481,12 +473,9 @@ async def submit_recording_snapshot_to_plus(
|
|||||||
)
|
)
|
||||||
|
|
||||||
nd = cv2.imdecode(np.frombuffer(image_data, dtype=np.int8), cv2.IMREAD_COLOR)
|
nd = cv2.imdecode(np.frombuffer(image_data, dtype=np.int8), cv2.IMREAD_COLOR)
|
||||||
try:
|
await asyncio.to_thread(
|
||||||
await asyncio.to_thread(
|
request.app.frigate_config.plus_api.upload_image, nd, camera_name
|
||||||
request.app.frigate_config.plus_api.upload_image, nd, camera_name
|
)
|
||||||
)
|
|
||||||
except PlusRateLimitError as err:
|
|
||||||
return plus_rate_limited_response(err)
|
|
||||||
|
|
||||||
return JSONResponse(
|
return JSONResponse(
|
||||||
content={
|
content={
|
||||||
@@ -1614,7 +1603,7 @@ async def preview_gif(
|
|||||||
camera_files = [
|
camera_files = [
|
||||||
entry.name
|
entry.name
|
||||||
for entry in os.scandir(preview_dir)
|
for entry in os.scandir(preview_dir)
|
||||||
if is_camera_preview_frame(entry.name, camera_name)
|
if entry.name.startswith(file_start)
|
||||||
]
|
]
|
||||||
camera_files.sort()
|
camera_files.sort()
|
||||||
|
|
||||||
@@ -1805,7 +1794,7 @@ async def preview_mp4(
|
|||||||
camera_files = [
|
camera_files = [
|
||||||
entry.name
|
entry.name
|
||||||
for entry in os.scandir(preview_dir)
|
for entry in os.scandir(preview_dir)
|
||||||
if is_camera_preview_frame(entry.name, camera_name)
|
if entry.name.startswith(file_start)
|
||||||
]
|
]
|
||||||
camera_files.sort()
|
camera_files.sort()
|
||||||
|
|
||||||
|
|||||||
@@ -17,10 +17,10 @@ import re
|
|||||||
from enum import Enum
|
from enum import Enum
|
||||||
from urllib.parse import unquote
|
from urllib.parse import unquote
|
||||||
|
|
||||||
from peewee import DoesNotExist, Field
|
from peewee import DoesNotExist
|
||||||
|
|
||||||
from frigate.config import FrigateConfig
|
from frigate.config import FrigateConfig
|
||||||
from frigate.const import CLIPS_DIR, EXPORT_DIR
|
from frigate.const import EXPORT_DIR
|
||||||
from frigate.models import Export, User
|
from frigate.models import Export, User
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -151,7 +151,6 @@ def _resolve_clip(
|
|||||||
# /clips/thumbs/{cam}/... → camera
|
# /clips/thumbs/{cam}/... → camera
|
||||||
# /clips/previews/{cam}/... → camera
|
# /clips/previews/{cam}/... → camera
|
||||||
# /clips/review/thumb-{cam}-{review_id}.webp → camera (parsed)
|
# /clips/review/thumb-{cam}-{review_id}.webp → camera (parsed)
|
||||||
# /clips/export/{export_id}.{ext} → camera (DB lookup)
|
|
||||||
# /clips/faces/... → admin-only
|
# /clips/faces/... → admin-only
|
||||||
# /clips/genai-requests/... → admin-only
|
# /clips/genai-requests/... → admin-only
|
||||||
# /clips/preview_restart_cache/... → admin-only
|
# /clips/preview_restart_cache/... → admin-only
|
||||||
@@ -176,11 +175,6 @@ def _resolve_clip(
|
|||||||
return MediaAuthResolution.CAMERA, camera
|
return MediaAuthResolution.CAMERA, camera
|
||||||
return MediaAuthResolution.UNRESOLVED_MEDIA, None
|
return MediaAuthResolution.UNRESOLVED_MEDIA, None
|
||||||
|
|
||||||
if second == "export" and len(parts) == 3:
|
|
||||||
return _export_camera(
|
|
||||||
Export.thumb_path, os.path.join(CLIPS_DIR, "export", parts[2])
|
|
||||||
)
|
|
||||||
|
|
||||||
if second in ("faces", "genai-requests", "preview_restart_cache"):
|
if second in ("faces", "genai-requests", "preview_restart_cache"):
|
||||||
return MediaAuthResolution.ADMIN_ONLY, None
|
return MediaAuthResolution.ADMIN_ONLY, None
|
||||||
|
|
||||||
@@ -240,19 +234,15 @@ def _resolve_export(
|
|||||||
if len(parts) != 2:
|
if len(parts) != 2:
|
||||||
return MediaAuthResolution.UNRESOLVED_MEDIA, None
|
return MediaAuthResolution.UNRESOLVED_MEDIA, None
|
||||||
|
|
||||||
return _export_camera(Export.video_path, os.path.join(EXPORT_DIR, parts[1]))
|
filename = parts[1]
|
||||||
|
full_path = os.path.join(EXPORT_DIR, filename)
|
||||||
|
|
||||||
def _export_camera(
|
|
||||||
field: Field, full_path: str
|
|
||||||
) -> tuple[MediaAuthResolution, str | None]:
|
|
||||||
try:
|
try:
|
||||||
export = Export.get(field == full_path)
|
export = Export.get(Export.video_path == full_path)
|
||||||
return MediaAuthResolution.CAMERA, export.camera
|
return MediaAuthResolution.CAMERA, export.camera
|
||||||
except DoesNotExist:
|
except DoesNotExist:
|
||||||
return MediaAuthResolution.UNRESOLVED_MEDIA, None
|
return MediaAuthResolution.UNRESOLVED_MEDIA, None
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning("Export DB lookup failed for %s: %s", full_path, e)
|
logger.warning("Export DB lookup failed for %s: %s", filename, e)
|
||||||
return MediaAuthResolution.UNRESOLVED_MEDIA, None
|
return MediaAuthResolution.UNRESOLVED_MEDIA, None
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,31 +0,0 @@
|
|||||||
"""Shared responses for endpoints that call Frigate+."""
|
|
||||||
|
|
||||||
from fastapi.responses import JSONResponse
|
|
||||||
|
|
||||||
from frigate.plus import PlusRateLimitError
|
|
||||||
|
|
||||||
|
|
||||||
def plus_rate_limited_response(err: PlusRateLimitError) -> JSONResponse:
|
|
||||||
"""Tell the client Frigate+ is rate limiting requests and how long to wait.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
err: The rate limit raised by the Frigate+ client
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
A 429 response with the wait in retry_after (and the Retry-After
|
|
||||||
header) when Frigate+ provided one
|
|
||||||
"""
|
|
||||||
headers = None
|
|
||||||
|
|
||||||
if err.retry_after is not None:
|
|
||||||
headers = {"Retry-After": str(err.retry_after)}
|
|
||||||
|
|
||||||
return JSONResponse(
|
|
||||||
content={
|
|
||||||
"success": False,
|
|
||||||
"message": "Frigate+ is rate limiting requests, try again later",
|
|
||||||
"retry_after": err.retry_after,
|
|
||||||
},
|
|
||||||
status_code=429,
|
|
||||||
headers=headers,
|
|
||||||
)
|
|
||||||
@@ -22,7 +22,6 @@ from frigate.api.defs.response.preview_response import (
|
|||||||
from frigate.api.defs.tags import Tags
|
from frigate.api.defs.tags import Tags
|
||||||
from frigate.const import BASE_DIR, CACHE_DIR, PREVIEW_FRAME_TYPE
|
from frigate.const import BASE_DIR, CACHE_DIR, PREVIEW_FRAME_TYPE
|
||||||
from frigate.models import Previews
|
from frigate.models import Previews
|
||||||
from frigate.output.preview import is_camera_preview_frame
|
|
||||||
from frigate.util.time import get_normalized_tz_name
|
from frigate.util.time import get_normalized_tz_name
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -188,7 +187,7 @@ def get_preview_frames_from_cache(camera_name: str, start_ts: float, end_ts: flo
|
|||||||
left = bisect.bisect_left(files, start_file)
|
left = bisect.bisect_left(files, start_file)
|
||||||
right = bisect.bisect_right(files, end_file)
|
right = bisect.bisect_right(files, end_file)
|
||||||
selected_previews = [
|
selected_previews = [
|
||||||
file for file in files[left:right] if is_camera_preview_frame(file, camera_name)
|
file for file in files[left:right] if file.startswith(file_start)
|
||||||
]
|
]
|
||||||
|
|
||||||
return JSONResponse(
|
return JSONResponse(
|
||||||
|
|||||||
+35
-29
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
import datetime as dt
|
import datetime as dt
|
||||||
import logging
|
import logging
|
||||||
import math
|
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from functools import reduce
|
from functools import reduce
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -444,38 +443,45 @@ async def no_recordings(
|
|||||||
else:
|
else:
|
||||||
covered.append((rec_start, rec_end))
|
covered.append((rec_start, rec_end))
|
||||||
|
|
||||||
# A scale-sized bucket counts as empty when it fits inside a gap between
|
# Iterate through time segments and check if each has any recording
|
||||||
# covered intervals. Walking the gaps keeps the work proportional to the
|
no_recording_segments = []
|
||||||
# recordings found rather than to the requested span.
|
current = after
|
||||||
bucket_count = math.ceil((before - after) / scale)
|
current_gap_start = None
|
||||||
gaps: list[list[float]] = []
|
idx = 0
|
||||||
free_start = -math.inf
|
covered_count = len(covered)
|
||||||
|
|
||||||
for rec_start, rec_end in covered + [(math.inf, math.inf)]:
|
while current < before:
|
||||||
first = 0 if free_start <= after else math.ceil((free_start - after) / scale)
|
segment_end = min(current + scale, before)
|
||||||
|
|
||||||
if rec_start >= before:
|
# Advance past covered intervals that end before this segment begins;
|
||||||
last = bucket_count - 1
|
# they cannot overlap this or any later segment.
|
||||||
|
while idx < covered_count and covered[idx][1] <= current:
|
||||||
|
idx += 1
|
||||||
|
|
||||||
|
# A covered interval overlaps the segment when it starts before the
|
||||||
|
# segment ends (its end is already known to be > current).
|
||||||
|
has_recording = idx < covered_count and covered[idx][0] < segment_end
|
||||||
|
|
||||||
|
if not has_recording:
|
||||||
|
# This segment has no recordings
|
||||||
|
if current_gap_start is None:
|
||||||
|
current_gap_start = current # Start a new gap
|
||||||
else:
|
else:
|
||||||
last = min(math.floor((rec_start - after) / scale), bucket_count) - 1
|
# This segment has recordings
|
||||||
|
if current_gap_start is not None:
|
||||||
|
# End the current gap and append it
|
||||||
|
no_recording_segments.append(
|
||||||
|
{"start_time": int(current_gap_start), "end_time": int(current)}
|
||||||
|
)
|
||||||
|
current_gap_start = None
|
||||||
|
|
||||||
if first <= last:
|
current = segment_end
|
||||||
gap_start = after + first * scale
|
|
||||||
gap_end = before if last == bucket_count - 1 else after + (last + 1) * scale
|
|
||||||
|
|
||||||
if gaps and gaps[-1][1] == gap_start:
|
# Append the last gap if it exists
|
||||||
gaps[-1][1] = gap_end
|
if current_gap_start is not None:
|
||||||
else:
|
no_recording_segments.append(
|
||||||
gaps.append([gap_start, gap_end])
|
{"start_time": int(current_gap_start), "end_time": int(before)}
|
||||||
|
)
|
||||||
free_start = rec_end
|
|
||||||
if free_start >= before:
|
|
||||||
break
|
|
||||||
|
|
||||||
no_recording_segments = [
|
|
||||||
{"start_time": int(gap_start), "end_time": int(gap_end)}
|
|
||||||
for gap_start, gap_end in gaps
|
|
||||||
]
|
|
||||||
|
|
||||||
return JSONResponse(content=no_recording_segments)
|
return JSONResponse(content=no_recording_segments)
|
||||||
|
|
||||||
@@ -489,7 +495,7 @@ async def no_recordings(
|
|||||||
Recordings can be filtered by cameras and kept based on motion, objects, or audio attributes.
|
Recordings can be filtered by cameras and kept based on motion, objects, or audio attributes.
|
||||||
""",
|
""",
|
||||||
)
|
)
|
||||||
def delete_recordings(
|
async def delete_recordings(
|
||||||
start: float = PathParam(..., description="Start timestamp (unix)"),
|
start: float = PathParam(..., description="Start timestamp (unix)"),
|
||||||
end: float = PathParam(..., description="End timestamp (unix)"),
|
end: float = PathParam(..., description="End timestamp (unix)"),
|
||||||
params: RecordingsDeleteQueryParams = Depends(),
|
params: RecordingsDeleteQueryParams = Depends(),
|
||||||
|
|||||||
@@ -581,7 +581,6 @@ class WebPushClient(Communicator):
|
|||||||
sorted_objects.add(obj)
|
sorted_objects.add(obj)
|
||||||
|
|
||||||
sorted_objects.update(payload["after"]["data"]["sub_labels"])
|
sorted_objects.update(payload["after"]["data"]["sub_labels"])
|
||||||
sorted_objects.update(payload["after"]["data"]["audio"])
|
|
||||||
|
|
||||||
image = f"{payload['after']['thumb_path'].replace(BASE_DIR, '')}"
|
image = f"{payload['after']['thumb_path'].replace(BASE_DIR, '')}"
|
||||||
ended = state == "end" or state == "genai"
|
ended = state == "end" or state == "genai"
|
||||||
@@ -618,14 +617,7 @@ class WebPushClient(Communicator):
|
|||||||
else:
|
else:
|
||||||
formatted_zone_names.append(titlecase(zone_name.replace("_", " ")))
|
formatted_zone_names.append(titlecase(zone_name.replace("_", " ")))
|
||||||
|
|
||||||
object_names = titlecase(
|
title = f"{titlecase(', '.join(sorted_objects).replace('_', ' '))}{' was' if state == 'end' else ''} detected in {', '.join(formatted_zone_names)}"
|
||||||
", ".join(sorted(sorted_objects)).replace("_", " ")
|
|
||||||
)
|
|
||||||
title = f"{object_names}{' was' if state == 'end' else ''} detected"
|
|
||||||
|
|
||||||
if formatted_zone_names:
|
|
||||||
title += f" in {', '.join(formatted_zone_names)}"
|
|
||||||
|
|
||||||
message = f"Detected on {camera_name}"
|
message = f"Detected on {camera_name}"
|
||||||
|
|
||||||
if ended:
|
if ended:
|
||||||
|
|||||||
+12
-7
@@ -40,7 +40,6 @@ from frigate.const import (
|
|||||||
)
|
)
|
||||||
from frigate.models import User
|
from frigate.models import User
|
||||||
from frigate.output.ws_auth import ws_has_camera_access
|
from frigate.output.ws_auth import ws_has_camera_access
|
||||||
from frigate.util.builtin import scope_stats_for_non_admin
|
|
||||||
from frigate.util.origin import origin_allowed
|
from frigate.util.origin import origin_allowed
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -211,7 +210,7 @@ _WS_RESHAPE_JOB_STATE_TOPICS = frozenset(
|
|||||||
|
|
||||||
# Topics whose payload mixes global aggregates with a ``cameras`` sub-dict
|
# Topics whose payload mixes global aggregates with a ``cameras`` sub-dict
|
||||||
# keyed by camera name. Aggregates and detector data stay; per-camera entries
|
# keyed by camera name. Aggregates and detector data stay; per-camera entries
|
||||||
# are filtered and process cmdlines are stripped for non-admins.
|
# are filtered.
|
||||||
_WS_RESHAPE_STATS_TOPICS = frozenset(
|
_WS_RESHAPE_STATS_TOPICS = frozenset(
|
||||||
{
|
{
|
||||||
"stats",
|
"stats",
|
||||||
@@ -456,14 +455,20 @@ def _materialize_for_ws(
|
|||||||
return _wrap_envelope(topic, filtered_jobs)
|
return _wrap_envelope(topic, filtered_jobs)
|
||||||
|
|
||||||
if kind == "reshape_stats":
|
if kind == "reshape_stats":
|
||||||
if "admin" in _ws_valid_roles(ws, config):
|
if _ws_is_unrestricted(ws, config):
|
||||||
return full_message
|
return full_message
|
||||||
if not isinstance(parsed_payload, dict):
|
if not isinstance(parsed_payload, dict):
|
||||||
return None
|
return None
|
||||||
return _wrap_envelope(
|
allowed = _ws_allowed_cameras(ws, config)
|
||||||
topic,
|
cameras_block = parsed_payload.get("cameras")
|
||||||
scope_stats_for_non_admin(parsed_payload, _ws_allowed_cameras(ws, config)),
|
if isinstance(cameras_block, dict):
|
||||||
)
|
filtered_cameras = {
|
||||||
|
name: data for name, data in cameras_block.items() if name in allowed
|
||||||
|
}
|
||||||
|
reshaped = dict(parsed_payload)
|
||||||
|
reshaped["cameras"] = filtered_cameras
|
||||||
|
return _wrap_envelope(topic, reshaped)
|
||||||
|
return full_message
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|||||||
@@ -88,17 +88,16 @@ class AuthConfig(FrigateBaseModel):
|
|||||||
f"Invalid role name '{role}'. Must be alphanumeric with underscores."
|
f"Invalid role name '{role}'. Must be alphanumeric with underscores."
|
||||||
)
|
)
|
||||||
|
|
||||||
# Proxy role headers match role names case-insensitively, so reserved
|
# 'none' is the deny sentinel for proxy.default_role, where it is matched
|
||||||
# names are reserved in every casing and names must differ beyond case
|
# case-insensitively, so every casing of it has to be reserved here
|
||||||
used_reserved = sorted(r for r in v if r.lower() in ("admin", "viewer", "none"))
|
used_reserved = sorted(
|
||||||
|
r for r in v if r in ("admin", "viewer") or r.lower() == "none"
|
||||||
|
)
|
||||||
if used_reserved:
|
if used_reserved:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
f"Reserved role name(s) {', '.join(used_reserved)} cannot be used as custom roles."
|
f"Reserved role name(s) {', '.join(used_reserved)} cannot be used as custom roles."
|
||||||
)
|
)
|
||||||
|
|
||||||
if len({r.lower() for r in v}) != len(v):
|
|
||||||
raise ValueError("Role names must be unique regardless of letter case.")
|
|
||||||
|
|
||||||
# Ensure no role has an empty camera list
|
# Ensure no role has an empty camera list
|
||||||
for role, allowed_cameras in v.items():
|
for role, allowed_cameras in v.items():
|
||||||
if not allowed_cameras:
|
if not allowed_cameras:
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import io
|
|||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
from collections.abc import Mapping
|
|
||||||
from typing import Any, Self
|
from typing import Any, Self
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
@@ -35,7 +34,7 @@ from frigate.util.config import (
|
|||||||
get_relative_coordinates,
|
get_relative_coordinates,
|
||||||
migrate_frigate_config,
|
migrate_frigate_config,
|
||||||
)
|
)
|
||||||
from frigate.util.env import EnvVars, candidate_env_vars, reload_sources
|
from frigate.util.env import EnvVars, reload_sources
|
||||||
from frigate.util.image import create_mask
|
from frigate.util.image import create_mask
|
||||||
from frigate.util.live_streams import (
|
from frigate.util.live_streams import (
|
||||||
default_transcode_source,
|
default_transcode_source,
|
||||||
@@ -1042,15 +1041,6 @@ class FrigateConfig(FrigateBaseModel):
|
|||||||
# set notifications state
|
# set notifications state
|
||||||
self.notifications.enabled_in_config = self.notifications.enabled
|
self.notifications.enabled_in_config = self.notifications.enabled
|
||||||
|
|
||||||
default_role = (self.proxy.default_role or "").lower()
|
|
||||||
if default_role != "none" and default_role not in {
|
|
||||||
r.lower() for r in self.auth.roles
|
|
||||||
}:
|
|
||||||
logger.warning(
|
|
||||||
"proxy.default_role '%s' is not a configured role, so proxy users without a matching role are denied",
|
|
||||||
self.proxy.default_role,
|
|
||||||
)
|
|
||||||
|
|
||||||
# validate genai: each role (chat, descriptions, embeddings, transcribe) at most once
|
# validate genai: each role (chat, descriptions, embeddings, transcribe) at most once
|
||||||
role_to_name: dict[GenAIRoleEnum, str] = {}
|
role_to_name: dict[GenAIRoleEnum, str] = {}
|
||||||
for name, genai_cfg in self.genai.items():
|
for name, genai_cfg in self.genai.items():
|
||||||
@@ -1567,12 +1557,6 @@ class FrigateConfig(FrigateBaseModel):
|
|||||||
def parse_object(
|
def parse_object(
|
||||||
cls, obj: Any, *, plus_api: PlusApi | None = None, install: bool = False
|
cls, obj: Any, *, plus_api: PlusApi | None = None, install: bool = False
|
||||||
):
|
):
|
||||||
context = {"plus_api": plus_api, "install": install}
|
return cls.model_validate(
|
||||||
|
obj, context={"plus_api": plus_api, "install": install}
|
||||||
if install:
|
)
|
||||||
return cls.model_validate(obj, context=context)
|
|
||||||
|
|
||||||
# a candidate config resolves placeholders against its own block
|
|
||||||
env_vars = obj.get("environment_vars") if isinstance(obj, Mapping) else None
|
|
||||||
with candidate_env_vars(env_vars):
|
|
||||||
return cls.model_validate(obj, context=context)
|
|
||||||
|
|||||||
@@ -55,9 +55,10 @@ class ProxyConfig(FrigateBaseModel):
|
|||||||
@field_validator("default_role", mode="before")
|
@field_validator("default_role", mode="before")
|
||||||
@classmethod
|
@classmethod
|
||||||
def normalize_deny_sentinel(cls, v):
|
def normalize_deny_sentinel(cls, v):
|
||||||
# Fail closed: "none" in any casing and a null default both deny.
|
# Fail closed on capitalization: an unnormalized "None" would miss the
|
||||||
# Normalizing null keeps the value through /config, which drops nulls
|
# sentinel and fall back to viewer, granting the access it was meant to
|
||||||
if v is None or (isinstance(v, str) and v.strip().lower() == "none"):
|
# deny. Other role names stay case-sensitive.
|
||||||
|
if isinstance(v, str) and v.strip().lower() == "none":
|
||||||
return "none"
|
return "none"
|
||||||
return v
|
return v
|
||||||
|
|
||||||
|
|||||||
+14
-31
@@ -11,11 +11,10 @@ import os
|
|||||||
import shutil
|
import shutil
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
from collections.abc import Callable
|
|
||||||
|
|
||||||
from ruamel.yaml import YAML
|
from ruamel.yaml import YAML
|
||||||
|
|
||||||
from frigate.config import CameraConfig, FrigateConfig
|
from frigate.config import FrigateConfig
|
||||||
from frigate.config.camera.updater import (
|
from frigate.config.camera.updater import (
|
||||||
CameraConfigUpdateEnum,
|
CameraConfigUpdateEnum,
|
||||||
CameraConfigUpdatePublisher,
|
CameraConfigUpdatePublisher,
|
||||||
@@ -62,7 +61,6 @@ class DebugReplayManager:
|
|||||||
self.start_ts: float | None = None
|
self.start_ts: float | None = None
|
||||||
self.end_ts: float | None = None
|
self.end_ts: float | None = None
|
||||||
self.session_started_at: float | None = None
|
self.session_started_at: float | None = None
|
||||||
self._published_camera: CameraConfig | None = None
|
|
||||||
self._job_state_publisher = JobStatePublisher()
|
self._job_state_publisher = JobStatePublisher()
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@@ -111,13 +109,6 @@ class DebugReplayManager:
|
|||||||
self.start_ts = None
|
self.start_ts = None
|
||||||
self.end_ts = None
|
self.end_ts = None
|
||||||
self.session_started_at = None
|
self.session_started_at = None
|
||||||
self._published_camera = None
|
|
||||||
|
|
||||||
def update_config(self, config: FrigateConfig) -> None:
|
|
||||||
"""Carry the published replay camera into a newly swapped-in config."""
|
|
||||||
with self._lock:
|
|
||||||
if self._published_camera is not None and self.replay_camera_name:
|
|
||||||
config.cameras[self.replay_camera_name] = self._published_camera
|
|
||||||
|
|
||||||
def publish_camera(
|
def publish_camera(
|
||||||
self,
|
self,
|
||||||
@@ -126,11 +117,10 @@ class DebugReplayManager:
|
|||||||
clip_path: str,
|
clip_path: str,
|
||||||
frigate_config: FrigateConfig,
|
frigate_config: FrigateConfig,
|
||||||
config_publisher: CameraConfigUpdatePublisher,
|
config_publisher: CameraConfigUpdatePublisher,
|
||||||
) -> bool:
|
) -> None:
|
||||||
"""Build the in-memory replay camera config and publish the add event.
|
"""Build the in-memory replay camera config and publish the add event.
|
||||||
|
|
||||||
Called by the job runner during the starting_camera phase. Returns
|
Called by the job runner during the starting_camera phase.
|
||||||
False without publishing if the session was stopped meanwhile.
|
|
||||||
"""
|
"""
|
||||||
source_config = frigate_config.cameras[source_camera]
|
source_config = frigate_config.cameras[source_camera]
|
||||||
camera_dict = self._build_camera_config_dict(
|
camera_dict = self._build_camera_config_dict(
|
||||||
@@ -150,21 +140,12 @@ class DebugReplayManager:
|
|||||||
new_config = FrigateConfig.parse_object(config_data)
|
new_config = FrigateConfig.parse_object(config_data)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise RuntimeError(f"Failed to validate replay camera config: {e}") from e
|
raise RuntimeError(f"Failed to validate replay camera config: {e}") from e
|
||||||
|
frigate_config.cameras[replay_name] = new_config.cameras[replay_name]
|
||||||
|
|
||||||
camera_config = new_config.cameras[replay_name]
|
config_publisher.publish_update(
|
||||||
|
CameraConfigUpdateTopic(CameraConfigUpdateEnum.add, replay_name),
|
||||||
with self._lock:
|
new_config.cameras[replay_name],
|
||||||
if self.replay_camera_name != replay_name:
|
)
|
||||||
return False
|
|
||||||
|
|
||||||
frigate_config.cameras[replay_name] = camera_config
|
|
||||||
self._published_camera = camera_config
|
|
||||||
config_publisher.publish_update(
|
|
||||||
CameraConfigUpdateTopic(CameraConfigUpdateEnum.add, replay_name),
|
|
||||||
camera_config,
|
|
||||||
)
|
|
||||||
|
|
||||||
return True
|
|
||||||
|
|
||||||
def stop(
|
def stop(
|
||||||
self,
|
self,
|
||||||
@@ -186,10 +167,12 @@ class DebugReplayManager:
|
|||||||
replay_name = self.replay_camera_name
|
replay_name = self.replay_camera_name
|
||||||
source_camera = self.source_camera
|
source_camera = self.source_camera
|
||||||
|
|
||||||
if replay_name is not None and self._published_camera is not None:
|
# Only publish remove if the camera was actually added to the live
|
||||||
|
# config (i.e. the runner reached the starting_camera phase).
|
||||||
|
if replay_name is not None and replay_name in frigate_config.cameras:
|
||||||
config_publisher.publish_update(
|
config_publisher.publish_update(
|
||||||
CameraConfigUpdateTopic(CameraConfigUpdateEnum.remove, replay_name),
|
CameraConfigUpdateTopic(CameraConfigUpdateEnum.remove, replay_name),
|
||||||
self._published_camera,
|
frigate_config.cameras[replay_name],
|
||||||
)
|
)
|
||||||
frigate_config.cameras.pop(replay_name, None)
|
frigate_config.cameras.pop(replay_name, None)
|
||||||
|
|
||||||
@@ -379,7 +362,7 @@ def cleanup_replay_cameras() -> None:
|
|||||||
|
|
||||||
async def debug_replay_auto_stop_watchdog(
|
async def debug_replay_auto_stop_watchdog(
|
||||||
manager: DebugReplayManager,
|
manager: DebugReplayManager,
|
||||||
get_config: Callable[[], FrigateConfig],
|
frigate_config: FrigateConfig,
|
||||||
config_publisher: CameraConfigUpdatePublisher,
|
config_publisher: CameraConfigUpdatePublisher,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Auto-stop debug replay sessions that exceed MAX_SESSION_DURATION_SECONDS.
|
"""Auto-stop debug replay sessions that exceed MAX_SESSION_DURATION_SECONDS.
|
||||||
@@ -401,7 +384,7 @@ async def debug_replay_auto_stop_watchdog(
|
|||||||
replay_name = manager.replay_camera_name
|
replay_name = manager.replay_camera_name
|
||||||
await asyncio.to_thread(
|
await asyncio.to_thread(
|
||||||
manager.stop,
|
manager.stop,
|
||||||
frigate_config=get_config(),
|
frigate_config=frigate_config,
|
||||||
config_publisher=config_publisher,
|
config_publisher=config_publisher,
|
||||||
)
|
)
|
||||||
logger.info(
|
logger.info(
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ from pydantic import BaseModel, ConfigDict, Field
|
|||||||
from pydantic.fields import PrivateAttr
|
from pydantic.fields import PrivateAttr
|
||||||
|
|
||||||
from frigate.const import DEFAULT_ATTRIBUTE_LABEL_MAP, MODEL_CACHE_DIR
|
from frigate.const import DEFAULT_ATTRIBUTE_LABEL_MAP, MODEL_CACHE_DIR
|
||||||
from frigate.plus import PlusApi, PlusRateLimitError, load_plus_model_info
|
from frigate.plus import PlusApi, load_plus_model_info
|
||||||
from frigate.util.builtin import generate_color_palette, load_labels
|
from frigate.util.builtin import generate_color_palette, load_labels
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -52,16 +52,6 @@ DEFAULT_SCENE = "default"
|
|||||||
SCENE_PATTERN = r"^[A-Za-z0-9_-]+$"
|
SCENE_PATTERN = r"^[A-Za-z0-9_-]+$"
|
||||||
|
|
||||||
|
|
||||||
def _rate_limited_message(model_id: str, err: PlusRateLimitError) -> str:
|
|
||||||
"""Explain a rate limited Frigate+ model download, with the wait if known."""
|
|
||||||
message = f"Frigate+ is rate limiting requests, unable to download model {model_id}"
|
|
||||||
|
|
||||||
if err.retry_after is not None:
|
|
||||||
return f"{message}. Try again in {err.retry_after} seconds"
|
|
||||||
|
|
||||||
return f"{message}. Try again later"
|
|
||||||
|
|
||||||
|
|
||||||
class ModelConfig(BaseModel):
|
class ModelConfig(BaseModel):
|
||||||
scene: str = Field(
|
scene: str = Field(
|
||||||
default=DEFAULT_SCENE,
|
default=DEFAULT_SCENE,
|
||||||
@@ -203,16 +193,6 @@ class ModelConfig(BaseModel):
|
|||||||
raise ValueError(
|
raise ValueError(
|
||||||
f"Unable to connect to Frigate+ to download model {model_id}"
|
f"Unable to connect to Frigate+ to download model {model_id}"
|
||||||
) from e
|
) from e
|
||||||
except PlusRateLimitError as e:
|
|
||||||
raise ValueError(_rate_limited_message(model_id, e)) from e
|
|
||||||
|
|
||||||
# an error body written here would be mistaken for the model on
|
|
||||||
# every later start, since only the file's existence is checked
|
|
||||||
if not r.ok:
|
|
||||||
raise ValueError(
|
|
||||||
f"Unable to download model {model_id} from Frigate+ "
|
|
||||||
f"(HTTP {r.status_code})"
|
|
||||||
)
|
|
||||||
|
|
||||||
with open(self.path, "wb") as f:
|
with open(self.path, "wb") as f:
|
||||||
f.write(r.content)
|
f.write(r.content)
|
||||||
@@ -225,8 +205,6 @@ class ModelConfig(BaseModel):
|
|||||||
raise ValueError(
|
raise ValueError(
|
||||||
f"Unable to connect to Frigate+ to download model info for {model_id}"
|
f"Unable to connect to Frigate+ to download model info for {model_id}"
|
||||||
) from e
|
) from e
|
||||||
except PlusRateLimitError as e:
|
|
||||||
raise ValueError(_rate_limited_message(model_id, e)) from e
|
|
||||||
|
|
||||||
with open(model_info_path, "w") as f:
|
with open(model_info_path, "w") as f:
|
||||||
json.dump(model_info, f)
|
json.dump(model_info, f)
|
||||||
|
|||||||
+80
-61
@@ -2,11 +2,14 @@
|
|||||||
|
|
||||||
import datetime
|
import datetime
|
||||||
import logging
|
import logging
|
||||||
|
import os
|
||||||
import threading
|
import threading
|
||||||
from multiprocessing.synchronize import Event as MpEvent
|
from multiprocessing.synchronize import Event as MpEvent
|
||||||
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from frigate.config import FrigateConfig
|
from frigate.config import FrigateConfig
|
||||||
|
from frigate.const import CLIPS_DIR
|
||||||
from frigate.db.sqlitevecq import SqliteVecQueueDatabase
|
from frigate.db.sqlitevecq import SqliteVecQueueDatabase
|
||||||
from frigate.models import Event, Timeline
|
from frigate.models import Event, Timeline
|
||||||
from frigate.util.file import delete_event_snapshot, delete_event_thumbnail
|
from frigate.util.file import delete_event_snapshot, delete_event_thumbnail
|
||||||
@@ -140,7 +143,7 @@ class EventCleanup(threading.Thread):
|
|||||||
events_to_update = []
|
events_to_update = []
|
||||||
|
|
||||||
## Expire events from cameras based on the camera config
|
## Expire events from cameras based on the camera config
|
||||||
for name, camera in list(self.config.cameras.items()):
|
for name, camera in self.config.cameras.items():
|
||||||
retain_config = camera.snapshots.retain
|
retain_config = camera.snapshots.retain
|
||||||
|
|
||||||
# get distinct objects in database for this camera
|
# get distinct objects in database for this camera
|
||||||
@@ -202,18 +205,54 @@ class EventCleanup(threading.Thread):
|
|||||||
self.config.record.effective_alert_days,
|
self.config.record.effective_alert_days,
|
||||||
self.config.record.effective_detection_days,
|
self.config.record.effective_detection_days,
|
||||||
)
|
)
|
||||||
|
file_extension = None # mp4 clips are no longer stored in /clips
|
||||||
update_params = {"has_clip": False}
|
update_params = {"has_clip": False}
|
||||||
|
|
||||||
|
# get expiration time for this label
|
||||||
|
|
||||||
expire_after = (
|
expire_after = (
|
||||||
datetime.datetime.now() - datetime.timedelta(days=expire_days)
|
datetime.datetime.now() - datetime.timedelta(days=expire_days)
|
||||||
).timestamp()
|
).timestamp()
|
||||||
|
# grab all events after specific time
|
||||||
|
expired_events: list[Event] = list(
|
||||||
|
Event.select(
|
||||||
|
Event.id,
|
||||||
|
Event.camera,
|
||||||
|
)
|
||||||
|
.where(
|
||||||
|
Event.camera.not_in(self.camera_keys),
|
||||||
|
Event.start_time < expire_after,
|
||||||
|
Event.retain_indefinitely == False,
|
||||||
|
)
|
||||||
|
.namedtuples()
|
||||||
|
.iterator()
|
||||||
|
)
|
||||||
|
logger.debug(f"{len(expired_events)} events can be expired")
|
||||||
|
# delete the media from disk
|
||||||
|
for expired in expired_events:
|
||||||
|
media_name = f"{expired.camera}-{expired.id}"
|
||||||
|
media_path = Path(f"{os.path.join(CLIPS_DIR, media_name)}.{file_extension}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
media_path.unlink(missing_ok=True)
|
||||||
|
if file_extension == "jpg":
|
||||||
|
media_path = Path( # type: ignore[unreachable]
|
||||||
|
f"{os.path.join(CLIPS_DIR, media_name)}-clean.webp"
|
||||||
|
)
|
||||||
|
media_path.unlink(missing_ok=True)
|
||||||
|
# Also delete clean.png (legacy) for backward compatibility
|
||||||
|
media_path = Path(
|
||||||
|
f"{os.path.join(CLIPS_DIR, media_name)}-clean.png"
|
||||||
|
)
|
||||||
|
media_path.unlink(missing_ok=True)
|
||||||
|
except OSError as e:
|
||||||
|
logger.warning(f"Unable to delete event images: {e}")
|
||||||
|
|
||||||
# update the clips attribute for the db entry
|
# update the clips attribute for the db entry
|
||||||
query = Event.select(Event.id).where(
|
query = Event.select(Event.id).where(
|
||||||
Event.camera.not_in(self.camera_keys),
|
Event.camera.not_in(self.camera_keys),
|
||||||
Event.start_time < expire_after,
|
Event.start_time < expire_after,
|
||||||
Event.retain_indefinitely == False,
|
Event.retain_indefinitely == False,
|
||||||
Event.has_clip == True,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
events_to_update = []
|
events_to_update = []
|
||||||
@@ -241,7 +280,7 @@ class EventCleanup(threading.Thread):
|
|||||||
now = datetime.datetime.now()
|
now = datetime.datetime.now()
|
||||||
|
|
||||||
## Expire events from cameras based on the camera config
|
## Expire events from cameras based on the camera config
|
||||||
for name, camera in list(self.config.cameras.items()):
|
for name, camera in self.config.cameras.items():
|
||||||
# effective days cover the sub window, keeping tracked objects
|
# effective days cover the sub window, keeping tracked objects
|
||||||
# in Explore while sub recordings and review items still exist
|
# in Explore while sub recordings and review items still exist
|
||||||
alert_expire_date = (
|
alert_expire_date = (
|
||||||
@@ -259,7 +298,6 @@ class EventCleanup(threading.Thread):
|
|||||||
.where(
|
.where(
|
||||||
Event.camera == name,
|
Event.camera == name,
|
||||||
Event.retain_indefinitely == False,
|
Event.retain_indefinitely == False,
|
||||||
Event.has_clip == True,
|
|
||||||
(
|
(
|
||||||
(
|
(
|
||||||
(Event.data["max_severity"] != "detection")
|
(Event.data["max_severity"] != "detection")
|
||||||
@@ -297,62 +335,43 @@ class EventCleanup(threading.Thread):
|
|||||||
|
|
||||||
# only expire events every 5 minutes
|
# only expire events every 5 minutes
|
||||||
while not self.stop_event.wait(300):
|
while not self.stop_event.wait(300):
|
||||||
try:
|
events_with_expired_clips = self.expire_clips()
|
||||||
self.expire_events()
|
|
||||||
except Exception:
|
# delete timeline entries for events that have expired recordings
|
||||||
logger.exception("Event cleanup failed, retrying next cycle")
|
# delete up to 100,000 at a time
|
||||||
|
max_deletes = 100000
|
||||||
|
deleted_events_list = list(events_with_expired_clips)
|
||||||
|
for i in range(0, len(deleted_events_list), max_deletes):
|
||||||
|
Timeline.delete().where(
|
||||||
|
Timeline.source_id << deleted_events_list[i : i + max_deletes]
|
||||||
|
).execute()
|
||||||
|
|
||||||
|
self.expire_snapshots()
|
||||||
|
|
||||||
|
# drop events from db where has_clip and has_snapshot are false
|
||||||
|
events = (
|
||||||
|
Event.select()
|
||||||
|
.where(Event.has_clip == False, Event.has_snapshot == False)
|
||||||
|
.iterator()
|
||||||
|
)
|
||||||
|
events_to_delete: list[Event] = [e for e in events]
|
||||||
|
|
||||||
|
for e in events_to_delete:
|
||||||
|
delete_event_thumbnail(e)
|
||||||
|
|
||||||
|
logger.debug(f"Found {len(events_to_delete)} events that can be expired")
|
||||||
|
if len(events_to_delete) > 0:
|
||||||
|
ids_to_delete = [str(e.id) for e in events_to_delete]
|
||||||
|
for i in range(0, len(ids_to_delete), CHUNK_SIZE):
|
||||||
|
chunk = ids_to_delete[i : i + CHUNK_SIZE]
|
||||||
|
logger.debug(f"Deleting {len(chunk)} events from the database")
|
||||||
|
Event.delete().where(Event.id << chunk).execute()
|
||||||
|
Timeline.delete().where(Timeline.source_id << chunk).execute()
|
||||||
|
|
||||||
|
# embeddings are always cleaned up, even when semantic search
|
||||||
|
# is disabled, so that they don't outlive their events
|
||||||
|
self.db.delete_embeddings_description(event_ids=chunk)
|
||||||
|
self.db.delete_embeddings_thumbnail(event_ids=chunk)
|
||||||
|
logger.debug(f"Deleted {len(chunk)} embeddings")
|
||||||
|
|
||||||
logger.info("Exiting event cleanup...")
|
logger.info("Exiting event cleanup...")
|
||||||
|
|
||||||
def refresh_camera_keys(self) -> None:
|
|
||||||
"""Track cameras added or removed at runtime."""
|
|
||||||
camera_keys = list(self.config.cameras)
|
|
||||||
|
|
||||||
if set(camera_keys) != set(self.camera_keys):
|
|
||||||
self.camera_keys = camera_keys
|
|
||||||
self.removed_camera_labels = None
|
|
||||||
|
|
||||||
def expire_events(self) -> None:
|
|
||||||
"""Run one cleanup cycle: expire clips and snapshots, then drop dead events."""
|
|
||||||
self.refresh_camera_keys()
|
|
||||||
events_with_expired_clips = self.expire_clips()
|
|
||||||
|
|
||||||
# delete timeline entries for events that have expired recordings
|
|
||||||
# delete up to 100,000 at a time
|
|
||||||
max_deletes = 100000
|
|
||||||
deleted_events_list = list(events_with_expired_clips)
|
|
||||||
for i in range(0, len(deleted_events_list), max_deletes):
|
|
||||||
Timeline.delete().where(
|
|
||||||
Timeline.source_id << deleted_events_list[i : i + max_deletes]
|
|
||||||
).execute()
|
|
||||||
|
|
||||||
self.expire_snapshots()
|
|
||||||
|
|
||||||
# drop events from db where has_clip and has_snapshot are false
|
|
||||||
events = (
|
|
||||||
Event.select()
|
|
||||||
.where(Event.has_clip == False, Event.has_snapshot == False)
|
|
||||||
.iterator()
|
|
||||||
)
|
|
||||||
events_to_delete: list[Event] = [e for e in events]
|
|
||||||
|
|
||||||
for e in events_to_delete:
|
|
||||||
if not delete_event_thumbnail(e):
|
|
||||||
logger.warning(
|
|
||||||
f"Unable to delete event thumbnail for {e.camera}: {e.id}"
|
|
||||||
)
|
|
||||||
|
|
||||||
logger.debug(f"Found {len(events_to_delete)} events that can be expired")
|
|
||||||
if len(events_to_delete) > 0:
|
|
||||||
ids_to_delete = [str(e.id) for e in events_to_delete]
|
|
||||||
for i in range(0, len(ids_to_delete), CHUNK_SIZE):
|
|
||||||
chunk = ids_to_delete[i : i + CHUNK_SIZE]
|
|
||||||
logger.debug(f"Deleting {len(chunk)} events from the database")
|
|
||||||
Event.delete().where(Event.id << chunk).execute()
|
|
||||||
Timeline.delete().where(Timeline.source_id << chunk).execute()
|
|
||||||
|
|
||||||
# embeddings are always cleaned up, even when semantic search
|
|
||||||
# is disabled, so that they don't outlive their events
|
|
||||||
self.db.delete_embeddings_description(event_ids=chunk)
|
|
||||||
self.db.delete_embeddings_thumbnail(event_ids=chunk)
|
|
||||||
logger.debug(f"Deleted {len(chunk)} embeddings")
|
|
||||||
|
|||||||
@@ -42,7 +42,6 @@ def should_update_db(prev_event: dict[str, Any], current_event: dict[str, Any])
|
|||||||
or prev_event["recognized_license_plate"]
|
or prev_event["recognized_license_plate"]
|
||||||
!= current_event["recognized_license_plate"]
|
!= current_event["recognized_license_plate"]
|
||||||
or prev_event["path_data"] != current_event["path_data"]
|
or prev_event["path_data"] != current_event["path_data"]
|
||||||
or prev_event["max_severity"] != current_event["max_severity"]
|
|
||||||
):
|
):
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|||||||
@@ -67,17 +67,6 @@ def _decode_data_uri(url: str) -> tuple[str, bytes] | None:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _tool_names_by_id(messages: list[dict[str, Any]]) -> dict[str, str]:
|
|
||||||
"""Map each assistant tool call id to its function name."""
|
|
||||||
return {
|
|
||||||
tc["id"]: (tc.get("function") or {}).get("name") or ""
|
|
||||||
for msg in messages
|
|
||||||
if msg.get("role") == "assistant"
|
|
||||||
for tc in msg.get("tool_calls") or []
|
|
||||||
if tc.get("id")
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _parts_from_content(content: Any) -> list[types.Part]:
|
def _parts_from_content(content: Any) -> list[types.Part]:
|
||||||
"""Convert OpenAI-style message content (str or multimodal list) to Gemini parts."""
|
"""Convert OpenAI-style message content (str or multimodal list) to Gemini parts."""
|
||||||
if isinstance(content, list):
|
if isinstance(content, list):
|
||||||
@@ -469,7 +458,6 @@ class GeminiClient(GenAIClient):
|
|||||||
try:
|
try:
|
||||||
# Convert messages to Gemini format
|
# Convert messages to Gemini format
|
||||||
gemini_messages: list[types.Content] = []
|
gemini_messages: list[types.Content] = []
|
||||||
tool_names = _tool_names_by_id(messages)
|
|
||||||
for msg in messages:
|
for msg in messages:
|
||||||
role = msg.get("role", "user")
|
role = msg.get("role", "user")
|
||||||
content = msg.get("content", "")
|
content = msg.get("content", "")
|
||||||
@@ -532,7 +520,6 @@ class GeminiClient(GenAIClient):
|
|||||||
parts=[
|
parts=[
|
||||||
types.Part.from_function_response(
|
types.Part.from_function_response(
|
||||||
name=msg.get("name")
|
name=msg.get("name")
|
||||||
or tool_names.get(msg.get("tool_call_id") or "")
|
|
||||||
or msg.get("tool_call_id")
|
or msg.get("tool_call_id")
|
||||||
or "",
|
or "",
|
||||||
response=response_payload,
|
response=response_payload,
|
||||||
@@ -727,7 +714,6 @@ class GeminiClient(GenAIClient):
|
|||||||
try:
|
try:
|
||||||
# Convert messages to Gemini format
|
# Convert messages to Gemini format
|
||||||
gemini_messages: list[types.Content] = []
|
gemini_messages: list[types.Content] = []
|
||||||
tool_names = _tool_names_by_id(messages)
|
|
||||||
for msg in messages:
|
for msg in messages:
|
||||||
role = msg.get("role", "user")
|
role = msg.get("role", "user")
|
||||||
content = msg.get("content", "")
|
content = msg.get("content", "")
|
||||||
@@ -790,7 +776,6 @@ class GeminiClient(GenAIClient):
|
|||||||
parts=[
|
parts=[
|
||||||
types.Part.from_function_response(
|
types.Part.from_function_response(
|
||||||
name=msg.get("name")
|
name=msg.get("name")
|
||||||
or tool_names.get(msg.get("tool_call_id") or "")
|
|
||||||
or msg.get("tool_call_id")
|
or msg.get("tool_call_id")
|
||||||
or "",
|
or "",
|
||||||
response=response_payload,
|
response=response_payload,
|
||||||
|
|||||||
@@ -110,13 +110,6 @@ class LlamaCppClient(GenAIClient):
|
|||||||
"""POST with the configured auth headers injected."""
|
"""POST with the configured auth headers injected."""
|
||||||
return requests.post(url, headers=self._auth_headers(), **kwargs)
|
return requests.post(url, headers=self._auth_headers(), **kwargs)
|
||||||
|
|
||||||
def _server_url(self) -> str | None:
|
|
||||||
"""Return the configured base_url without a trailing slash or /v1."""
|
|
||||||
if not self.genai_config.base_url:
|
|
||||||
return None
|
|
||||||
|
|
||||||
return self.genai_config.base_url.rstrip("/").removesuffix("/v1")
|
|
||||||
|
|
||||||
def _fetch_llama_props(self, base_url: str, model: str) -> dict[str, Any]:
|
def _fetch_llama_props(self, base_url: str, model: str) -> dict[str, Any]:
|
||||||
"""Fetch /props from a llama.cpp server, with llama-swap fallback.
|
"""Fetch /props from a llama.cpp server, with llama-swap fallback.
|
||||||
|
|
||||||
@@ -150,10 +143,16 @@ class LlamaCppClient(GenAIClient):
|
|||||||
self._supports_tools = False
|
self._supports_tools = False
|
||||||
self._supports_reasoning = False
|
self._supports_reasoning = False
|
||||||
|
|
||||||
base_url = self._server_url()
|
base_url = (
|
||||||
|
self.genai_config.base_url.rstrip("/")
|
||||||
|
if self.genai_config.base_url
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
|
||||||
if base_url is None:
|
if base_url is None:
|
||||||
return None
|
return None
|
||||||
|
else:
|
||||||
|
base_url = base_url.replace("/v1", "") # Strip /v1 if included in base_url
|
||||||
|
|
||||||
if not self.validate_model:
|
if not self.validate_model:
|
||||||
# Probe path
|
# Probe path
|
||||||
@@ -507,7 +506,11 @@ class LlamaCppClient(GenAIClient):
|
|||||||
|
|
||||||
def _fetch_models_data(self) -> list[dict[str, Any]]:
|
def _fetch_models_data(self) -> list[dict[str, Any]]:
|
||||||
"""Return the raw /v1/models entries, or an empty list if unreachable."""
|
"""Return the raw /v1/models entries, or an empty list if unreachable."""
|
||||||
base_url = self.provider or self._server_url()
|
base_url = self.provider or (
|
||||||
|
self.genai_config.base_url.rstrip("/")
|
||||||
|
if self.genai_config.base_url
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
|
||||||
if base_url is None:
|
if base_url is None:
|
||||||
return []
|
return []
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ from collections.abc import AsyncGenerator
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
from httpx import HTTPError
|
from httpx import RemoteProtocolError, TimeoutException
|
||||||
from ollama import AsyncClient as OllamaAsyncClient
|
from ollama import AsyncClient as OllamaAsyncClient
|
||||||
from ollama import Client as ApiClient
|
from ollama import Client as ApiClient
|
||||||
from ollama import ResponseError
|
from ollama import ResponseError
|
||||||
@@ -282,7 +282,12 @@ class OllamaClient(GenAIClient):
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
response = self.provider.chat(**request_params)
|
response = self.provider.chat(**request_params)
|
||||||
except (HTTPError, ResponseError, ConnectionError) as e:
|
except (
|
||||||
|
TimeoutException,
|
||||||
|
ResponseError,
|
||||||
|
RemoteProtocolError,
|
||||||
|
ConnectionError,
|
||||||
|
) as e:
|
||||||
logger.warning("Ollama returned an error: %s", str(e))
|
logger.warning("Ollama returned an error: %s", str(e))
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -401,7 +406,13 @@ class OllamaClient(GenAIClient):
|
|||||||
# image items have to bypass it and post the JSON directly.
|
# image items have to bypass it and post the JSON directly.
|
||||||
response = self.provider._request_raw("POST", "/api/embed", json=payload)
|
response = self.provider._request_raw("POST", "/api/embed", json=payload)
|
||||||
body = response.json()
|
body = response.json()
|
||||||
except (HTTPError, ResponseError, ConnectionError, ValueError) as e:
|
except (
|
||||||
|
TimeoutException,
|
||||||
|
ResponseError,
|
||||||
|
RemoteProtocolError,
|
||||||
|
ConnectionError,
|
||||||
|
ValueError,
|
||||||
|
) as e:
|
||||||
logger.warning("Ollama embeddings error: %s", str(e))
|
logger.warning("Ollama embeddings error: %s", str(e))
|
||||||
return []
|
return []
|
||||||
|
|
||||||
@@ -542,7 +553,7 @@ class OllamaClient(GenAIClient):
|
|||||||
)
|
)
|
||||||
response = self.provider.chat(**request_params)
|
response = self.provider.chat(**request_params)
|
||||||
return self._message_from_response(response)
|
return self._message_from_response(response)
|
||||||
except (HTTPError, ResponseError, ConnectionError) as e:
|
except (TimeoutException, ResponseError, ConnectionError) as e:
|
||||||
logger.warning("Ollama returned an error: %s", str(e))
|
logger.warning("Ollama returned an error: %s", str(e))
|
||||||
return {
|
return {
|
||||||
"content": None,
|
"content": None,
|
||||||
@@ -674,7 +685,7 @@ class OllamaClient(GenAIClient):
|
|||||||
"finish_reason": "stop",
|
"finish_reason": "stop",
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
except (HTTPError, ResponseError, ConnectionError) as e:
|
except (TimeoutException, ResponseError, ConnectionError) as e:
|
||||||
logger.warning("Ollama streaming error: %s", str(e))
|
logger.warning("Ollama streaming error: %s", str(e))
|
||||||
yield (
|
yield (
|
||||||
"message",
|
"message",
|
||||||
|
|||||||
@@ -187,35 +187,16 @@ def build_review_description_response_format(concerns: list[str]) -> dict[str, A
|
|||||||
|
|
||||||
Strips the `time` field (populated server-side) and drops
|
Strips the `time` field (populated server-side) and drops
|
||||||
`other_concerns` when no concerns are configured.
|
`other_concerns` when no concerns are configured.
|
||||||
|
|
||||||
Every remaining property must be listed in `required` because strict
|
|
||||||
providers (OpenAI) reject a schema with any optional property.
|
|
||||||
"""
|
"""
|
||||||
schema = ReviewMetadata.model_json_schema()
|
schema = ReviewMetadata.model_json_schema()
|
||||||
properties = schema.setdefault("properties", {})
|
schema.get("properties", {}).pop("time", None)
|
||||||
required = schema.setdefault("required", [])
|
|
||||||
properties.pop("time", None)
|
|
||||||
|
|
||||||
if "time" in required:
|
if "time" in schema.get("required", []):
|
||||||
required.remove("time")
|
schema["required"].remove("time")
|
||||||
|
if not concerns:
|
||||||
if concerns:
|
schema.get("properties", {}).pop("other_concerns", None)
|
||||||
# The model field is nullable with a default so stored metadata
|
if "other_concerns" in schema.get("required", []):
|
||||||
# without concerns still parses. For generation, require a plain list
|
schema["required"].remove("other_concerns")
|
||||||
# instead; the model returns an empty list when no concern applies.
|
|
||||||
properties["other_concerns"] = {
|
|
||||||
"type": "array",
|
|
||||||
"items": {"type": "string"},
|
|
||||||
"description": properties["other_concerns"]["description"],
|
|
||||||
}
|
|
||||||
|
|
||||||
if "other_concerns" not in required:
|
|
||||||
required.append("other_concerns")
|
|
||||||
else:
|
|
||||||
properties.pop("other_concerns", None)
|
|
||||||
|
|
||||||
if "other_concerns" in required:
|
|
||||||
required.remove("other_concerns")
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"type": "json_schema",
|
"type": "json_schema",
|
||||||
|
|||||||
@@ -376,16 +376,13 @@ class DebugReplayJobRunner(threading.Thread):
|
|||||||
self._finalize_cancelled(clip_path)
|
self._finalize_cancelled(clip_path)
|
||||||
return
|
return
|
||||||
|
|
||||||
if not self.replay_manager.publish_camera(
|
self.replay_manager.publish_camera(
|
||||||
source_camera=self.job.source_camera,
|
source_camera=self.job.source_camera,
|
||||||
replay_name=replay_name,
|
replay_name=replay_name,
|
||||||
clip_path=clip_path,
|
clip_path=clip_path,
|
||||||
frigate_config=self.frigate_config,
|
frigate_config=self.frigate_config,
|
||||||
config_publisher=self.config_publisher,
|
config_publisher=self.config_publisher,
|
||||||
):
|
)
|
||||||
self._finalize_cancelled(clip_path)
|
|
||||||
return
|
|
||||||
|
|
||||||
self.replay_manager.mark_session_ready(clip_path)
|
self.replay_manager.mark_session_ready(clip_path)
|
||||||
|
|
||||||
self.job.status = JobStatusTypesEnum.success
|
self.job.status = JobStatusTypesEnum.success
|
||||||
|
|||||||
@@ -487,9 +487,6 @@ def get_export_job_manager(config: FrigateConfig) -> ExportJobManager:
|
|||||||
with _job_manager_lock:
|
with _job_manager_lock:
|
||||||
if _job_manager is None:
|
if _job_manager is None:
|
||||||
_job_manager = ExportJobManager(config, _get_max_concurrent(config))
|
_job_manager = ExportJobManager(config, _get_max_concurrent(config))
|
||||||
|
|
||||||
# callers pass the live config, which a save replaces
|
|
||||||
_job_manager.config = config
|
|
||||||
_job_manager.ensure_started()
|
_job_manager.ensure_started()
|
||||||
return _job_manager
|
return _job_manager
|
||||||
|
|
||||||
|
|||||||
@@ -6,10 +6,8 @@ import threading
|
|||||||
import time
|
import time
|
||||||
from collections.abc import Callable, Generator, Iterable
|
from collections.abc import Callable, Generator, Iterable
|
||||||
from concurrent.futures import Future, ThreadPoolExecutor, as_completed
|
from concurrent.futures import Future, ThreadPoolExecutor, as_completed
|
||||||
from contextlib import closing
|
|
||||||
from dataclasses import asdict, dataclass, field
|
from dataclasses import asdict, dataclass, field
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from itertools import islice
|
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import cv2
|
import cv2
|
||||||
@@ -613,49 +611,24 @@ class MotionSearchRunner(threading.Thread):
|
|||||||
|
|
||||||
def _detect_with_progress(
|
def _detect_with_progress(
|
||||||
self,
|
self,
|
||||||
frames: Iterable[np.ndarray],
|
indexed_frames: list[tuple[int, np.ndarray]],
|
||||||
timestamp_fn: Callable[[int], float],
|
timestamp_fn: Callable[[int], float],
|
||||||
) -> tuple[list[MotionSearchResult], int]:
|
) -> list[MotionSearchResult]:
|
||||||
"""Run detection while firing throttled progress as frames are scanned.
|
"""Run detection while firing throttled progress as frames are scanned."""
|
||||||
|
|
||||||
Returns ``(results, frame_count)``.
|
|
||||||
"""
|
|
||||||
frame_count = 0
|
|
||||||
|
|
||||||
def _gen() -> Generator[tuple[int, np.ndarray], None, None]:
|
def _gen() -> Generator[tuple[int, np.ndarray], None, None]:
|
||||||
nonlocal frame_count
|
for i, frame in indexed_frames:
|
||||||
for i, frame in enumerate(frames):
|
|
||||||
frame_count = i + 1
|
|
||||||
if not self._should_stop():
|
if not self._should_stop():
|
||||||
self._emit_progress(timestamp_fn(i))
|
self._emit_progress(timestamp_fn(i))
|
||||||
yield i, frame
|
yield i, frame
|
||||||
|
|
||||||
results = detect_motion_scaled(
|
return detect_motion_scaled(
|
||||||
_gen(),
|
_gen(),
|
||||||
self.scaled_mask,
|
self.scaled_mask,
|
||||||
self.job.threshold,
|
self.job.threshold,
|
||||||
self.job.min_area,
|
self.job.min_area,
|
||||||
timestamp_fn,
|
timestamp_fn,
|
||||||
)
|
)
|
||||||
return results, frame_count
|
|
||||||
|
|
||||||
def _decode_vod(
|
|
||||||
self, vod_url: str, keyframes: bool
|
|
||||||
) -> Generator[np.ndarray, None, None]:
|
|
||||||
return iter_vod_frames(
|
|
||||||
self.ffmpeg_path,
|
|
||||||
vod_url,
|
|
||||||
self.scaled[0],
|
|
||||||
self.scaled[1],
|
|
||||||
self.channels,
|
|
||||||
self.decode_args,
|
|
||||||
self.crop,
|
|
||||||
self.scaled,
|
|
||||||
True,
|
|
||||||
self._should_stop,
|
|
||||||
skip_nonkey=keyframes,
|
|
||||||
fps_rate=None if keyframes else self.fps_rate,
|
|
||||||
)
|
|
||||||
|
|
||||||
def _process_run(
|
def _process_run(
|
||||||
self, run: list[Recordings]
|
self, run: list[Recordings]
|
||||||
@@ -666,8 +639,7 @@ class MotionSearchRunner(threading.Thread):
|
|||||||
are all decoded anyway) paired with its probed PTS; if the decoded and
|
are all decoded anyway) paired with its probed PTS; if the decoded and
|
||||||
probed counts disagree (the decoder ignored ``-skip_frame nokey`` or the
|
probed counts disagree (the decoder ignored ``-skip_frame nokey`` or the
|
||||||
stream is corrupt) this run re-runs in the fixed-cadence fallback.
|
stream is corrupt) this run re-runs in the fixed-cadence fallback.
|
||||||
Frames stream through detection, so a run never holds more than the
|
Returns ``(results, frame_count)``.
|
||||||
current and previous frame. Returns ``(results, frame_count)``.
|
|
||||||
"""
|
"""
|
||||||
run_start: float = run[0].start_time # type: ignore[assignment]
|
run_start: float = run[0].start_time # type: ignore[assignment]
|
||||||
run_end: float = run[-1].end_time # type: ignore[assignment]
|
run_end: float = run[-1].end_time # type: ignore[assignment]
|
||||||
@@ -678,21 +650,35 @@ class MotionSearchRunner(threading.Thread):
|
|||||||
kf_pts = probe_vod_keyframe_pts(
|
kf_pts = probe_vod_keyframe_pts(
|
||||||
self.ffprobe_path, vod_url, self._should_stop
|
self.ffprobe_path, vod_url, self._should_stop
|
||||||
)
|
)
|
||||||
|
frames = list(
|
||||||
if kf_pts:
|
iter_vod_frames(
|
||||||
|
self.ffmpeg_path,
|
||||||
|
vod_url,
|
||||||
|
self.scaled[0],
|
||||||
|
self.scaled[1],
|
||||||
|
self.channels,
|
||||||
|
self.decode_args,
|
||||||
|
self.crop,
|
||||||
|
self.scaled,
|
||||||
|
True,
|
||||||
|
self._should_stop,
|
||||||
|
skip_nonkey=True,
|
||||||
|
fps_rate=None,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if kf_pts and len(frames) == len(kf_pts):
|
||||||
abs_times = [stream_time_to_absolute(time_map, p) for p in kf_pts]
|
abs_times = [stream_time_to_absolute(time_map, p) for p in kf_pts]
|
||||||
|
indexed = list(enumerate(frames))
|
||||||
|
|
||||||
with closing(self._decode_vod(vod_url, keyframes=True)) as frames:
|
def _ts_kf(i: int) -> float:
|
||||||
results, frame_count = self._detect_with_progress(
|
return abs_times[i]
|
||||||
islice(frames, len(abs_times)), abs_times.__getitem__
|
|
||||||
)
|
|
||||||
extra_frames = next(frames, None) is not None
|
|
||||||
|
|
||||||
if frame_count == len(abs_times) and not extra_frames:
|
results = self._detect_with_progress(indexed, _ts_kf)
|
||||||
return results, frame_count
|
return results, len(frames)
|
||||||
|
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"Keyframe decode did not match %d probed keyframes, using cadence",
|
"Keyframe count mismatch (%d decoded vs %d probed), using cadence",
|
||||||
|
len(frames),
|
||||||
len(kf_pts),
|
len(kf_pts),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -702,12 +688,29 @@ class MotionSearchRunner(threading.Thread):
|
|||||||
self, vod_url: str, time_map: list[tuple[float, float, float]]
|
self, vod_url: str, time_map: list[tuple[float, float, float]]
|
||||||
) -> tuple[list[MotionSearchResult], int]:
|
) -> tuple[list[MotionSearchResult], int]:
|
||||||
"""Fixed-cadence fallback: fps-filtered VOD decode, evenly spaced times."""
|
"""Fixed-cadence fallback: fps-filtered VOD decode, evenly spaced times."""
|
||||||
|
frames = list(
|
||||||
|
iter_vod_frames(
|
||||||
|
self.ffmpeg_path,
|
||||||
|
vod_url,
|
||||||
|
self.scaled[0],
|
||||||
|
self.scaled[1],
|
||||||
|
self.channels,
|
||||||
|
self.decode_args,
|
||||||
|
self.crop,
|
||||||
|
self.scaled,
|
||||||
|
True,
|
||||||
|
self._should_stop,
|
||||||
|
skip_nonkey=False,
|
||||||
|
fps_rate=self.fps_rate,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
indexed = list(enumerate(frames))
|
||||||
|
|
||||||
def _ts_fps(i: int) -> float:
|
def _ts_fps(i: int) -> float:
|
||||||
return stream_time_to_absolute(time_map, i / self.fps_rate)
|
return stream_time_to_absolute(time_map, i / self.fps_rate)
|
||||||
|
|
||||||
with closing(self._decode_vod(vod_url, keyframes=False)) as frames:
|
results = self._detect_with_progress(indexed, _ts_fps)
|
||||||
return self._detect_with_progress(frames, _ts_fps)
|
return results, len(frames)
|
||||||
|
|
||||||
def _merge_run(
|
def _merge_run(
|
||||||
self,
|
self,
|
||||||
|
|||||||
+17
-27
@@ -28,8 +28,6 @@ _MAX_INTERVAL = 300
|
|||||||
# Minimum seconds between VLM iterations when woken by detections (no zone filter)
|
# Minimum seconds between VLM iterations when woken by detections (no zone filter)
|
||||||
_DETECTION_COOLDOWN_WITHOUT_ZONE = 10
|
_DETECTION_COOLDOWN_WITHOUT_ZONE = 10
|
||||||
|
|
||||||
MAX_WATCH_MINUTES = 1440
|
|
||||||
|
|
||||||
# Max user/assistant turn pairs to keep in conversation history
|
# Max user/assistant turn pairs to keep in conversation history
|
||||||
_MAX_HISTORY = 10
|
_MAX_HISTORY = 10
|
||||||
|
|
||||||
@@ -77,17 +75,15 @@ class VLMWatchRunner(threading.Thread):
|
|||||||
self.conversation: list[dict[str, Any]] = []
|
self.conversation: list[dict[str, Any]] = []
|
||||||
|
|
||||||
def run(self) -> None:
|
def run(self) -> None:
|
||||||
|
self.job.status = JobStatusTypesEnum.running
|
||||||
|
self.job.start_time = time.time()
|
||||||
|
self._broadcast_status()
|
||||||
|
self.conversation = [{"role": "system", "content": self._build_system_prompt()}]
|
||||||
|
|
||||||
|
# monotonic so a wall clock step can't end the job early or let it overrun
|
||||||
|
max_end_time = time.monotonic() + self.job.max_duration_minutes * 60
|
||||||
|
|
||||||
try:
|
try:
|
||||||
self.job.status = JobStatusTypesEnum.running
|
|
||||||
self.job.start_time = time.time()
|
|
||||||
self._broadcast_status()
|
|
||||||
self.conversation = [
|
|
||||||
{"role": "system", "content": self._build_system_prompt()}
|
|
||||||
]
|
|
||||||
|
|
||||||
# monotonic so a wall clock step can't end the job early or let it overrun
|
|
||||||
max_end_time = time.monotonic() + self.job.max_duration_minutes * 60
|
|
||||||
|
|
||||||
while not self.cancel_event.is_set():
|
while not self.cancel_event.is_set():
|
||||||
if time.monotonic() > max_end_time:
|
if time.monotonic() > max_end_time:
|
||||||
logger.debug(
|
logger.debug(
|
||||||
@@ -208,13 +204,7 @@ class VLMWatchRunner(threading.Thread):
|
|||||||
)
|
)
|
||||||
reasoning = str(parsed.get("reasoning", ""))
|
reasoning = str(parsed.get("reasoning", ""))
|
||||||
notification_message = str(parsed.get("notification_message", ""))
|
notification_message = str(parsed.get("notification_message", ""))
|
||||||
except (
|
except (json.JSONDecodeError, ValueError, TypeError) as e:
|
||||||
json.JSONDecodeError,
|
|
||||||
ValueError,
|
|
||||||
TypeError,
|
|
||||||
AttributeError,
|
|
||||||
OverflowError,
|
|
||||||
) as e:
|
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"VLM watch job %s: failed to parse VLM response: %s", self.job.id, e
|
"VLM watch job %s: failed to parse VLM response: %s", self.job.id, e
|
||||||
)
|
)
|
||||||
@@ -413,17 +403,17 @@ def start_vlm_watch_job(
|
|||||||
username=username,
|
username=username,
|
||||||
)
|
)
|
||||||
cancel_ev = threading.Event()
|
cancel_ev = threading.Event()
|
||||||
runner = VLMWatchRunner(
|
|
||||||
job=job,
|
|
||||||
config=config,
|
|
||||||
cancel_event=cancel_ev,
|
|
||||||
frame_processor=frame_processor,
|
|
||||||
genai_manager=genai_manager,
|
|
||||||
dispatcher=dispatcher,
|
|
||||||
)
|
|
||||||
_current_job = job
|
_current_job = job
|
||||||
_cancel_event = cancel_ev
|
_cancel_event = cancel_ev
|
||||||
|
|
||||||
|
runner = VLMWatchRunner(
|
||||||
|
job=job,
|
||||||
|
config=config,
|
||||||
|
cancel_event=cancel_ev,
|
||||||
|
frame_processor=frame_processor,
|
||||||
|
genai_manager=genai_manager,
|
||||||
|
dispatcher=dispatcher,
|
||||||
|
)
|
||||||
runner.start()
|
runner.start()
|
||||||
|
|
||||||
logger.debug(
|
logger.debug(
|
||||||
|
|||||||
+10
-14
@@ -789,16 +789,16 @@ class BirdsEyeFrameManager:
|
|||||||
force_update = True
|
force_update = True
|
||||||
else:
|
else:
|
||||||
return False, False
|
return False, False
|
||||||
else:
|
|
||||||
# update the last active frame for the camera
|
|
||||||
camera_state["current_frame"] = frame.copy()
|
|
||||||
camera_state["current_frame_time"] = frame_time
|
|
||||||
modes = camera_config.birdseye.modes
|
|
||||||
|
|
||||||
if self.camera_threshold_active(modes, activity):
|
# update the last active frame for the camera
|
||||||
camera_state["last_active_frame"] = frame_time
|
camera_state["current_frame"] = frame.copy()
|
||||||
|
camera_state["current_frame_time"] = frame_time
|
||||||
|
modes = camera_config.birdseye.modes
|
||||||
|
|
||||||
camera_state["live_active"] = self.camera_live_active(modes, activity)
|
if self.camera_threshold_active(modes, activity):
|
||||||
|
camera_state["last_active_frame"] = frame_time
|
||||||
|
|
||||||
|
camera_state["live_active"] = self.camera_live_active(modes, activity)
|
||||||
|
|
||||||
# monotonic so a backward wall clock step can't freeze the output
|
# monotonic so a backward wall clock step can't freeze the output
|
||||||
now = time.monotonic()
|
now = time.monotonic()
|
||||||
@@ -865,10 +865,7 @@ class Birdseye:
|
|||||||
(1.0 / self.idle_fps) if self.idle_fps > 0 else None
|
(1.0 / self.idle_fps) if self.idle_fps > 0 else None
|
||||||
)
|
)
|
||||||
|
|
||||||
# restream changes need a restart, so the buffer exists only if it did at init
|
if config.birdseye.restream:
|
||||||
self.restream = config.birdseye.restream
|
|
||||||
|
|
||||||
if self.restream:
|
|
||||||
self.birdseye_buffer: Any = self.frame_manager.create(
|
self.birdseye_buffer: Any = self.frame_manager.create(
|
||||||
"birdseye",
|
"birdseye",
|
||||||
self.birdseye_manager.yuv_shape[0] * self.birdseye_manager.yuv_shape[1],
|
self.birdseye_manager.yuv_shape[0] * self.birdseye_manager.yuv_shape[1],
|
||||||
@@ -880,7 +877,7 @@ class Birdseye:
|
|||||||
def __send_new_frame(self) -> None:
|
def __send_new_frame(self) -> None:
|
||||||
frame_bytes = self.birdseye_manager.frame.tobytes()
|
frame_bytes = self.birdseye_manager.frame.tobytes()
|
||||||
|
|
||||||
if self.restream:
|
if self.config.birdseye.restream:
|
||||||
self.birdseye_buffer[:] = frame_bytes
|
self.birdseye_buffer[:] = frame_bytes
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -957,7 +954,6 @@ class Birdseye:
|
|||||||
>= self._idle_interval
|
>= self._idle_interval
|
||||||
):
|
):
|
||||||
self.__send_new_frame()
|
self.__send_new_frame()
|
||||||
self.birdseye_manager.last_output_time = now
|
|
||||||
|
|
||||||
def stop(self) -> None:
|
def stop(self) -> None:
|
||||||
self.review_subscriber.stop()
|
self.review_subscriber.stop()
|
||||||
|
|||||||
@@ -379,7 +379,7 @@ def move_preview_frames(loc: str) -> None:
|
|||||||
src,
|
src,
|
||||||
dst,
|
dst,
|
||||||
)
|
)
|
||||||
except OSError:
|
except shutil.Error:
|
||||||
logger.error(
|
logger.error(
|
||||||
"Failed to move preview restart cache from %s to %s",
|
"Failed to move preview restart cache from %s to %s",
|
||||||
src,
|
src,
|
||||||
|
|||||||
+14
-135
@@ -1,12 +1,8 @@
|
|||||||
import datetime
|
import datetime
|
||||||
import email.utils
|
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import math
|
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import threading
|
|
||||||
import time
|
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, TypeGuard
|
from typing import Any, TypeGuard
|
||||||
@@ -25,11 +21,6 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
PLUS_VALIDATE_TIMEOUT = 10
|
PLUS_VALIDATE_TIMEOUT = 10
|
||||||
|
|
||||||
# Requests run on several threads, and a reply that arrives late must not
|
|
||||||
# shorten a wait recorded from another one. The lock is kept out of PlusApi
|
|
||||||
# because the client is pickled with the config to start worker processes.
|
|
||||||
_rate_limit_lock = threading.Lock()
|
|
||||||
|
|
||||||
|
|
||||||
class PlusKeyStatus(str, Enum):
|
class PlusKeyStatus(str, Enum):
|
||||||
"""Result of validating a Frigate+ API key with the server."""
|
"""Result of validating a Frigate+ API key with the server."""
|
||||||
@@ -37,7 +28,6 @@ class PlusKeyStatus(str, Enum):
|
|||||||
valid = "valid"
|
valid = "valid"
|
||||||
invalid = "invalid"
|
invalid = "invalid"
|
||||||
unreachable = "unreachable"
|
unreachable = "unreachable"
|
||||||
rate_limited = "rate_limited"
|
|
||||||
not_set = "not_set"
|
not_set = "not_set"
|
||||||
|
|
||||||
|
|
||||||
@@ -80,51 +70,6 @@ def load_plus_model_info(model_id: str) -> dict[str, Any] | None:
|
|||||||
return add_hailo_alias(model_info)
|
return add_hailo_alias(model_info)
|
||||||
|
|
||||||
|
|
||||||
class PlusRateLimitError(Exception):
|
|
||||||
"""Frigate+ rejected a request because too many requests were made."""
|
|
||||||
|
|
||||||
def __init__(self, retry_after: int | None) -> None:
|
|
||||||
self.retry_after = retry_after
|
|
||||||
super().__init__(
|
|
||||||
f"Rate limited by Frigate+, retry in {retry_after} seconds"
|
|
||||||
if retry_after is not None
|
|
||||||
else "Rate limited by Frigate+"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def parse_retry_after(value: str | None) -> int | None:
|
|
||||||
"""Read the number of seconds to wait from a Retry-After header.
|
|
||||||
|
|
||||||
The header (RFC 9110 section 10.2.3) is either a number of seconds or an
|
|
||||||
HTTP date to retry after.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
value: The raw header value
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Whole seconds to wait, or None when the header is missing or invalid
|
|
||||||
"""
|
|
||||||
if not value:
|
|
||||||
return None
|
|
||||||
|
|
||||||
value = value.strip()
|
|
||||||
|
|
||||||
if value.isdigit():
|
|
||||||
return int(value)
|
|
||||||
|
|
||||||
try:
|
|
||||||
retry_at = email.utils.parsedate_to_datetime(value)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
return None
|
|
||||||
|
|
||||||
# HTTP dates are always GMT, but "-0000" parses as a naive datetime
|
|
||||||
if retry_at.tzinfo is None:
|
|
||||||
retry_at = retry_at.replace(tzinfo=datetime.UTC)
|
|
||||||
|
|
||||||
remaining = (retry_at - datetime.datetime.now(datetime.UTC)).total_seconds()
|
|
||||||
return max(0, math.ceil(remaining))
|
|
||||||
|
|
||||||
|
|
||||||
def get_jpg_bytes(image: ndarray, max_dim: int, quality: int) -> bytes:
|
def get_jpg_bytes(image: ndarray, max_dim: int, quality: int) -> bytes:
|
||||||
if image.shape[1] >= image.shape[0]:
|
if image.shape[1] >= image.shape[0]:
|
||||||
width = min(max_dim, image.shape[1])
|
width = min(max_dim, image.shape[1])
|
||||||
@@ -183,62 +128,14 @@ class PlusApi:
|
|||||||
|
|
||||||
self._is_active: bool = self.key is not None
|
self._is_active: bool = self.key is not None
|
||||||
self._token_data: dict = {}
|
self._token_data: dict = {}
|
||||||
# when Frigate+ last asked us to back off, requests are refused locally
|
|
||||||
# until this time instead of being sent to the server again
|
|
||||||
self._rate_limited_until: float | None = None
|
|
||||||
|
|
||||||
# Retry connection failures so a network that comes up late at startup
|
# Retry connection failures so a network that comes up late at startup
|
||||||
# doesn't fail the Frigate+ model download. Retry-After is not honored
|
# doesn't fail the Frigate+ model download
|
||||||
# here, since urllib3 would block the calling thread for as long as the
|
|
||||||
# server asks; a 429 is raised to the caller as PlusRateLimitError.
|
|
||||||
self._session = requests.Session()
|
self._session = requests.Session()
|
||||||
self._session.mount(
|
self._session.mount(
|
||||||
self.host,
|
self.host, HTTPAdapter(max_retries=Retry(connect=5, backoff_factor=1))
|
||||||
HTTPAdapter(
|
|
||||||
max_retries=Retry(
|
|
||||||
connect=5, backoff_factor=1, respect_retry_after_header=False
|
|
||||||
)
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
def rate_limit_remaining(self) -> int | None:
|
|
||||||
"""Seconds until Frigate+ accepts requests again, or None if not limited."""
|
|
||||||
rate_limited_until = self._rate_limited_until
|
|
||||||
|
|
||||||
if rate_limited_until is None:
|
|
||||||
return None
|
|
||||||
|
|
||||||
remaining = math.ceil(rate_limited_until - time.time())
|
|
||||||
return remaining if remaining > 0 else None
|
|
||||||
|
|
||||||
def _note_rate_limit(self, retry_after: int | None) -> None:
|
|
||||||
"""Remember how long Frigate+ asked us to wait."""
|
|
||||||
logger.warning(
|
|
||||||
"Frigate+ rate limit reached, retry after %s seconds",
|
|
||||||
retry_after if retry_after is not None else "unknown",
|
|
||||||
)
|
|
||||||
|
|
||||||
if retry_after is None:
|
|
||||||
return
|
|
||||||
|
|
||||||
until = time.time() + retry_after
|
|
||||||
|
|
||||||
with _rate_limit_lock:
|
|
||||||
if self._rate_limited_until is None or until > self._rate_limited_until:
|
|
||||||
self._rate_limited_until = until
|
|
||||||
|
|
||||||
def _raise_if_rate_limited(self) -> None:
|
|
||||||
remaining = self.rate_limit_remaining()
|
|
||||||
|
|
||||||
if remaining is not None:
|
|
||||||
raise PlusRateLimitError(remaining)
|
|
||||||
|
|
||||||
def _check_rate_limit(self, r: Response) -> None:
|
|
||||||
if r.status_code == 429:
|
|
||||||
retry_after = parse_retry_after(r.headers.get("Retry-After"))
|
|
||||||
self._note_rate_limit(retry_after)
|
|
||||||
raise PlusRateLimitError(retry_after)
|
|
||||||
|
|
||||||
def _refresh_token_if_needed(self) -> None:
|
def _refresh_token_if_needed(self) -> None:
|
||||||
if (
|
if (
|
||||||
self._token_data.get("expires") is None
|
self._token_data.get("expires") is None
|
||||||
@@ -248,12 +145,10 @@ class PlusApi:
|
|||||||
raise Exception(
|
raise Exception(
|
||||||
"Plus API key not set. See https://docs.frigate.video/integrations/plus#set-your-api-key"
|
"Plus API key not set. See https://docs.frigate.video/integrations/plus#set-your-api-key"
|
||||||
)
|
)
|
||||||
self._raise_if_rate_limited()
|
|
||||||
parts = self.key.split(":")
|
parts = self.key.split(":")
|
||||||
r = self._session.get(
|
r = self._session.get(
|
||||||
f"{self.host}/v1/auth/token", auth=(parts[0], parts[1])
|
f"{self.host}/v1/auth/token", auth=(parts[0], parts[1])
|
||||||
)
|
)
|
||||||
self._check_rate_limit(r)
|
|
||||||
if not r.ok:
|
if not r.ok:
|
||||||
raise Exception(f"Unable to refresh API token: {r.text}")
|
raise Exception(f"Unable to refresh API token: {r.text}")
|
||||||
self._token_data = r.json()
|
self._token_data = r.json()
|
||||||
@@ -262,30 +157,24 @@ class PlusApi:
|
|||||||
self._refresh_token_if_needed()
|
self._refresh_token_if_needed()
|
||||||
return {"authorization": f"Bearer {self._token_data.get('accessToken')}"}
|
return {"authorization": f"Bearer {self._token_data.get('accessToken')}"}
|
||||||
|
|
||||||
def _request(self, method: str, path: str, data: dict | None = None) -> Response:
|
def _get(self, path: str) -> Response:
|
||||||
"""Make an authenticated Frigate+ request.
|
return self._session.get(
|
||||||
|
f"{self.host}/v1/{path}", headers=self._get_authorization_header()
|
||||||
|
)
|
||||||
|
|
||||||
Raises:
|
def _post(self, path: str, data: dict) -> Response:
|
||||||
PlusRateLimitError: Frigate+ is rate limiting requests
|
return self._session.post(
|
||||||
"""
|
|
||||||
self._raise_if_rate_limited()
|
|
||||||
r = self._session.request(
|
|
||||||
method,
|
|
||||||
f"{self.host}/v1/{path}",
|
f"{self.host}/v1/{path}",
|
||||||
headers=self._get_authorization_header(),
|
headers=self._get_authorization_header(),
|
||||||
json=data,
|
json=data,
|
||||||
)
|
)
|
||||||
self._check_rate_limit(r)
|
|
||||||
return r
|
|
||||||
|
|
||||||
def _get(self, path: str) -> Response:
|
|
||||||
return self._request("GET", path)
|
|
||||||
|
|
||||||
def _post(self, path: str, data: dict) -> Response:
|
|
||||||
return self._request("POST", path, data)
|
|
||||||
|
|
||||||
def _put(self, path: str, data: dict) -> Response:
|
def _put(self, path: str, data: dict) -> Response:
|
||||||
return self._request("PUT", path, data)
|
return self._session.put(
|
||||||
|
f"{self.host}/v1/{path}",
|
||||||
|
headers=self._get_authorization_header(),
|
||||||
|
json=data,
|
||||||
|
)
|
||||||
|
|
||||||
def is_active(self) -> bool:
|
def is_active(self) -> bool:
|
||||||
return self._is_active
|
return self._is_active
|
||||||
@@ -298,16 +187,11 @@ class PlusApi:
|
|||||||
result reflects the key's current state rather than a cached token.
|
result reflects the key's current state rather than a cached token.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
The key's status as reported by the Frigate+ server. When it is
|
The key's status as reported by the Frigate+ server
|
||||||
rate_limited, rate_limit_remaining() gives the wait if known.
|
|
||||||
"""
|
"""
|
||||||
if self.key is None:
|
if self.key is None:
|
||||||
return PlusKeyStatus.not_set
|
return PlusKeyStatus.not_set
|
||||||
|
|
||||||
# asking again before the wait is over would only be refused again
|
|
||||||
if self.rate_limit_remaining() is not None:
|
|
||||||
return PlusKeyStatus.rate_limited
|
|
||||||
|
|
||||||
key_id, _, secret = self.key.partition(":")
|
key_id, _, secret = self.key.partition(":")
|
||||||
|
|
||||||
# Use a single request with a timeout instead of the retrying session,
|
# Use a single request with a timeout instead of the retrying session,
|
||||||
@@ -323,7 +207,6 @@ class PlusApi:
|
|||||||
auth=aiohttp.BasicAuth(key_id, secret),
|
auth=aiohttp.BasicAuth(key_id, secret),
|
||||||
) as r:
|
) as r:
|
||||||
status = r.status
|
status = r.status
|
||||||
retry_after = parse_retry_after(r.headers.get("Retry-After"))
|
|
||||||
token_data = await r.json(content_type=None) if r.ok else None
|
token_data = await r.json(content_type=None) if r.ok else None
|
||||||
except (aiohttp.ClientError, TimeoutError) as err:
|
except (aiohttp.ClientError, TimeoutError) as err:
|
||||||
logger.warning("Unable to reach Frigate+ to validate API key: %s", err)
|
logger.warning("Unable to reach Frigate+ to validate API key: %s", err)
|
||||||
@@ -335,10 +218,6 @@ class PlusApi:
|
|||||||
if status in (401, 403):
|
if status in (401, 403):
|
||||||
return PlusKeyStatus.invalid
|
return PlusKeyStatus.invalid
|
||||||
|
|
||||||
if status == 429:
|
|
||||||
self._note_rate_limit(retry_after)
|
|
||||||
return PlusKeyStatus.rate_limited
|
|
||||||
|
|
||||||
if status >= 400:
|
if status >= 400:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"Unexpected response validating Frigate+ API key: %s", status
|
"Unexpected response validating Frigate+ API key: %s", status
|
||||||
|
|||||||
+15
-27
@@ -301,13 +301,13 @@ class OnvifController:
|
|||||||
logger.debug(f"Imaging service not supported for {camera_name}: {e}")
|
logger.debug(f"Imaging service not supported for {camera_name}: {e}")
|
||||||
imaging = None
|
imaging = None
|
||||||
cam["imaging"] = imaging
|
cam["imaging"] = imaging
|
||||||
cam["video_source_token"] = None
|
|
||||||
try:
|
try:
|
||||||
video_sources = await media.GetVideoSources()
|
video_sources = await media.GetVideoSources()
|
||||||
if video_sources and len(video_sources) > 0:
|
if video_sources and len(video_sources) > 0:
|
||||||
cam["video_source_token"] = video_sources[0].token
|
cam["video_source_token"] = video_sources[0].token
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.debug(f"Unable to get video sources for {camera_name}: {e}")
|
logger.debug(f"Unable to get video sources for {camera_name}: {e}")
|
||||||
|
cam["video_source_token"] = None
|
||||||
|
|
||||||
# setup continuous moving request
|
# setup continuous moving request
|
||||||
move_request = ptz.create_type("ContinuousMove")
|
move_request = ptz.create_type("ContinuousMove")
|
||||||
@@ -660,15 +660,12 @@ class OnvifController:
|
|||||||
move_request = cam["move_request"]
|
move_request = cam["move_request"]
|
||||||
preset_token = cam["presets"][preset]
|
preset_token = cam["presets"][preset]
|
||||||
|
|
||||||
try:
|
await cam["ptz"].GotoPreset(
|
||||||
await cam["ptz"].GotoPreset(
|
{
|
||||||
{
|
"ProfileToken": move_request.ProfileToken,
|
||||||
"ProfileToken": move_request.ProfileToken,
|
"PresetToken": preset_token,
|
||||||
"PresetToken": preset_token,
|
}
|
||||||
}
|
)
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning(f"Onvif sending preset request to {camera_name} failed: {e}")
|
|
||||||
|
|
||||||
cam["active"] = False
|
cam["active"] = False
|
||||||
|
|
||||||
@@ -693,11 +690,7 @@ class OnvifController:
|
|||||||
elif command == OnvifCommandEnum.zoom_out:
|
elif command == OnvifCommandEnum.zoom_out:
|
||||||
move_request.Velocity = {"Zoom": {"x": -0.5}}
|
move_request.Velocity = {"Zoom": {"x": -0.5}}
|
||||||
|
|
||||||
try:
|
await cam["ptz"].ContinuousMove(move_request)
|
||||||
await cam["ptz"].ContinuousMove(move_request)
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning(f"Onvif sending zoom request to {camera_name} failed: {e}")
|
|
||||||
cam["active"] = False
|
|
||||||
|
|
||||||
async def _zoom_absolute(self, camera_name: str, zoom, speed) -> None:
|
async def _zoom_absolute(self, camera_name: str, zoom, speed) -> None:
|
||||||
cam = self.cams[camera_name]
|
cam = self.cams[camera_name]
|
||||||
@@ -736,18 +729,13 @@ class OnvifController:
|
|||||||
|
|
||||||
logger.debug(f"{camera_name}: Absolute zoom: {zoom}")
|
logger.debug(f"{camera_name}: Absolute zoom: {zoom}")
|
||||||
|
|
||||||
try:
|
await cam["ptz"].AbsoluteMove(
|
||||||
await cam["ptz"].AbsoluteMove(
|
{
|
||||||
{
|
"ProfileToken": cam["move_request"].ProfileToken,
|
||||||
"ProfileToken": cam["move_request"].ProfileToken,
|
"Position": {"Zoom": zoom},
|
||||||
"Position": {"Zoom": zoom},
|
"Speed": {"Zoom": speed},
|
||||||
"Speed": {"Zoom": speed},
|
}
|
||||||
}
|
)
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning(
|
|
||||||
f"Onvif sending absolute zoom request to {camera_name} failed: {e}"
|
|
||||||
)
|
|
||||||
|
|
||||||
cam["active"] = False
|
cam["active"] = False
|
||||||
|
|
||||||
|
|||||||
@@ -261,18 +261,6 @@ def validate_ffmpeg_args(args: str) -> tuple[bool, str]:
|
|||||||
return True, ""
|
return True, ""
|
||||||
|
|
||||||
|
|
||||||
def normalize_ffmpeg_args(args: str | None) -> str | None:
|
|
||||||
"""Rejoin args with single spaces.
|
|
||||||
|
|
||||||
validate_ffmpeg_args tokenizes on any whitespace, while export commands are
|
|
||||||
built with split(" "). Normalizing keeps the two token lists identical.
|
|
||||||
"""
|
|
||||||
if args is None:
|
|
||||||
return None
|
|
||||||
|
|
||||||
return " ".join(args.split())
|
|
||||||
|
|
||||||
|
|
||||||
class PlaybackSourceEnum(str, Enum):
|
class PlaybackSourceEnum(str, Enum):
|
||||||
recordings = "recordings"
|
recordings = "recordings"
|
||||||
preview = "preview"
|
preview = "preview"
|
||||||
@@ -339,8 +327,8 @@ class RecordingExporter(threading.Thread):
|
|||||||
self.end_time = end_time
|
self.end_time = end_time
|
||||||
self.playback_source = playback_source
|
self.playback_source = playback_source
|
||||||
self.export_case_id = export_case_id
|
self.export_case_id = export_case_id
|
||||||
self.ffmpeg_input_args = normalize_ffmpeg_args(ffmpeg_input_args)
|
self.ffmpeg_input_args = ffmpeg_input_args
|
||||||
self.ffmpeg_output_args = normalize_ffmpeg_args(ffmpeg_output_args)
|
self.ffmpeg_output_args = ffmpeg_output_args
|
||||||
self.cpu_fallback = cpu_fallback
|
self.cpu_fallback = cpu_fallback
|
||||||
self.chapters = chapters
|
self.chapters = chapters
|
||||||
self.stream = stream
|
self.stream = stream
|
||||||
@@ -1345,7 +1333,7 @@ class RecordingExporter(threading.Thread):
|
|||||||
end_file = f"{file_start}{self.end_time}.{PREVIEW_FRAME_TYPE}"
|
end_file = f"{file_start}{self.end_time}.{PREVIEW_FRAME_TYPE}"
|
||||||
|
|
||||||
for file in sorted(os.listdir(preview_dir)):
|
for file in sorted(os.listdir(preview_dir)):
|
||||||
if not is_camera_preview_frame(file, self.camera):
|
if not file.startswith(file_start):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if file < start_file:
|
if file < start_file:
|
||||||
|
|||||||
@@ -30,7 +30,6 @@ from frigate.const import (
|
|||||||
UPSERT_REVIEW_SEGMENT,
|
UPSERT_REVIEW_SEGMENT,
|
||||||
)
|
)
|
||||||
from frigate.models import ReviewSegment
|
from frigate.models import ReviewSegment
|
||||||
from frigate.review.severity import get_review_severity
|
|
||||||
from frigate.review.types import SeverityEnum
|
from frigate.review.types import SeverityEnum
|
||||||
from frigate.track.object_processing import ManualEventState
|
from frigate.track.object_processing import ManualEventState
|
||||||
from frigate.util.image import SharedMemoryFrameManager, calculate_16_9_crop
|
from frigate.util.image import SharedMemoryFrameManager, calculate_16_9_crop
|
||||||
@@ -218,21 +217,57 @@ class ActiveObjects:
|
|||||||
}
|
}
|
||||||
|
|
||||||
for o in all_objects:
|
for o in all_objects:
|
||||||
severity = get_review_severity(
|
if (
|
||||||
camera_config,
|
o["motionless_count"] >= camera_config.detect.stationary.threshold
|
||||||
label=o["label"],
|
and not o["pending_loitering"]
|
||||||
current_zones=o["current_zones"],
|
):
|
||||||
false_positive=o["false_positive"],
|
# no stationary objects unless loitering
|
||||||
detected=o["frame_time"] == frame_time,
|
continue
|
||||||
position_changes=o["position_changes"],
|
|
||||||
motionless_count=o["motionless_count"],
|
|
||||||
pending_loitering=o["pending_loitering"],
|
|
||||||
)
|
|
||||||
|
|
||||||
if severity == SeverityEnum.alert:
|
if o["position_changes"] == 0:
|
||||||
|
# object must have moved at least once
|
||||||
|
continue
|
||||||
|
|
||||||
|
if o["frame_time"] != frame_time:
|
||||||
|
# object must be detected in this frame
|
||||||
|
continue
|
||||||
|
|
||||||
|
if o["false_positive"]:
|
||||||
|
# object must not be a false positive
|
||||||
|
continue
|
||||||
|
|
||||||
|
if (
|
||||||
|
o["label"] in camera_config.review.alerts.labels
|
||||||
|
and (
|
||||||
|
not camera_config.review.alerts.required_zones
|
||||||
|
or (
|
||||||
|
len(o["current_zones"]) > 0
|
||||||
|
and set(o["current_zones"])
|
||||||
|
& set(camera_config.review.alerts.required_zones)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
and camera_config.review.alerts.enabled
|
||||||
|
):
|
||||||
self.categorized_objects["alerts"].append(o)
|
self.categorized_objects["alerts"].append(o)
|
||||||
elif severity == SeverityEnum.detection:
|
continue
|
||||||
|
|
||||||
|
if (
|
||||||
|
(
|
||||||
|
camera_config.review.detections.labels is None
|
||||||
|
or o["label"] in camera_config.review.detections.labels
|
||||||
|
)
|
||||||
|
and (
|
||||||
|
not camera_config.review.detections.required_zones
|
||||||
|
or (
|
||||||
|
len(o["current_zones"]) > 0
|
||||||
|
and set(o["current_zones"])
|
||||||
|
& set(camera_config.review.detections.required_zones)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
and camera_config.review.detections.enabled
|
||||||
|
):
|
||||||
self.categorized_objects["detections"].append(o)
|
self.categorized_objects["detections"].append(o)
|
||||||
|
continue
|
||||||
|
|
||||||
def has_active_objects(self) -> bool:
|
def has_active_objects(self) -> bool:
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -1,80 +0,0 @@
|
|||||||
"""Rules for which review severity a tracked object qualifies for."""
|
|
||||||
|
|
||||||
from typing import cast
|
|
||||||
|
|
||||||
from frigate.config import CameraConfig
|
|
||||||
from frigate.review.types import SeverityEnum
|
|
||||||
|
|
||||||
|
|
||||||
def get_review_severity(
|
|
||||||
camera_config: CameraConfig,
|
|
||||||
*,
|
|
||||||
label: str,
|
|
||||||
current_zones: list[str],
|
|
||||||
false_positive: bool,
|
|
||||||
detected: bool,
|
|
||||||
position_changes: int,
|
|
||||||
motionless_count: int,
|
|
||||||
pending_loitering: bool,
|
|
||||||
) -> SeverityEnum | None:
|
|
||||||
"""Get the review severity a tracked object qualifies for on the current frame.
|
|
||||||
|
|
||||||
Review segments and a tracked object's max_severity both use this, so an
|
|
||||||
object is only reported as an alert or detection when it could actually
|
|
||||||
create or extend a review segment of that severity.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
camera_config: Config for the camera the object is on
|
|
||||||
label: The object's label
|
|
||||||
current_zones: Zones the object is in on the current frame
|
|
||||||
false_positive: Whether the object is still considered a false positive
|
|
||||||
detected: Whether the object was detected on the current frame
|
|
||||||
position_changes: Number of times the object has changed position
|
|
||||||
motionless_count: Number of frames the object has not moved
|
|
||||||
pending_loitering: Whether the object is in a loitering zone but has
|
|
||||||
not met the loitering time yet
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
The severity the object qualifies for, or None if it does not qualify
|
|
||||||
"""
|
|
||||||
# always populated from detect fps when the config is loaded
|
|
||||||
stationary_threshold = cast(int, camera_config.detect.stationary.threshold)
|
|
||||||
|
|
||||||
# stationary objects don't count unless they are loitering
|
|
||||||
if motionless_count >= stationary_threshold and not pending_loitering:
|
|
||||||
return None
|
|
||||||
|
|
||||||
# object must have moved at least once
|
|
||||||
if position_changes == 0:
|
|
||||||
return None
|
|
||||||
|
|
||||||
if not detected or false_positive:
|
|
||||||
return None
|
|
||||||
|
|
||||||
review_config = camera_config.review
|
|
||||||
zones = set(current_zones)
|
|
||||||
|
|
||||||
if (
|
|
||||||
review_config.alerts.enabled
|
|
||||||
and label in review_config.alerts.labels
|
|
||||||
and (
|
|
||||||
not review_config.alerts.required_zones
|
|
||||||
or zones & set(review_config.alerts.required_zones)
|
|
||||||
)
|
|
||||||
):
|
|
||||||
return SeverityEnum.alert
|
|
||||||
|
|
||||||
if (
|
|
||||||
review_config.detections.enabled
|
|
||||||
and (
|
|
||||||
review_config.detections.labels is None
|
|
||||||
or label in review_config.detections.labels
|
|
||||||
)
|
|
||||||
and (
|
|
||||||
not review_config.detections.required_zones
|
|
||||||
or zones & set(review_config.detections.required_zones)
|
|
||||||
)
|
|
||||||
):
|
|
||||||
return SeverityEnum.detection
|
|
||||||
|
|
||||||
return None
|
|
||||||
+6
-3
@@ -137,7 +137,7 @@ class StorageMaintainer(threading.Thread):
|
|||||||
|
|
||||||
def calculate_camera_bandwidth(self) -> None:
|
def calculate_camera_bandwidth(self) -> None:
|
||||||
"""Calculate an average MB/hr for each camera."""
|
"""Calculate an average MB/hr for each camera."""
|
||||||
for camera in list(self.config.cameras):
|
for camera in self.config.cameras.keys():
|
||||||
# Skip replay cameras
|
# Skip replay cameras
|
||||||
if camera.startswith(REPLAY_CAMERA_PREFIX):
|
if camera.startswith(REPLAY_CAMERA_PREFIX):
|
||||||
continue
|
continue
|
||||||
@@ -186,7 +186,7 @@ class StorageMaintainer(threading.Thread):
|
|||||||
"""Calculate the storage usage of each camera."""
|
"""Calculate the storage usage of each camera."""
|
||||||
usages: dict[str, dict] = {}
|
usages: dict[str, dict] = {}
|
||||||
|
|
||||||
for camera in list(self.config.cameras):
|
for camera in self.config.cameras.keys():
|
||||||
# Skip replay cameras
|
# Skip replay cameras
|
||||||
if camera.startswith(REPLAY_CAMERA_PREFIX):
|
if camera.startswith(REPLAY_CAMERA_PREFIX):
|
||||||
continue
|
continue
|
||||||
@@ -208,7 +208,10 @@ class StorageMaintainer(threading.Thread):
|
|||||||
"bandwidth_by_stream", {}
|
"bandwidth_by_stream", {}
|
||||||
)
|
)
|
||||||
|
|
||||||
usages[camera] = {
|
camera_key = (
|
||||||
|
getattr(self.config.cameras[camera], "friendly_name", None) or camera
|
||||||
|
)
|
||||||
|
usages[camera_key] = {
|
||||||
"usage": sum(stream_usages.values()),
|
"usage": sum(stream_usages.values()),
|
||||||
"bandwidth": self.camera_storage_stats.get(camera, {}).get(
|
"bandwidth": self.camera_storage_stats.get(camera, {}).get(
|
||||||
"bandwidth", 0
|
"bandwidth", 0
|
||||||
|
|||||||
@@ -1,11 +1,9 @@
|
|||||||
import copy
|
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
from unittest.mock import Mock, patch
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
import frigate.genai
|
import frigate.genai
|
||||||
from frigate.config import GenAIProviderEnum
|
from frigate.config import GenAIProviderEnum
|
||||||
from frigate.config.config import RuntimeFilterConfig
|
|
||||||
from frigate.const import MODEL_CACHE_DIR, REDACTED_CREDENTIAL_SENTINEL
|
from frigate.const import MODEL_CACHE_DIR, REDACTED_CREDENTIAL_SENTINEL
|
||||||
from frigate.genai import GenAIClient
|
from frigate.genai import GenAIClient
|
||||||
from frigate.models import Event, Recordings, ReviewSegment
|
from frigate.models import Event, Recordings, ReviewSegment
|
||||||
@@ -32,23 +30,6 @@ class TestHttpApp(BaseTestHttp):
|
|||||||
response_json = response.json()
|
response_json = response.json()
|
||||||
assert response_json == self.test_stats
|
assert response_json == self.test_stats
|
||||||
|
|
||||||
def test_stats_endpoint_strips_cmdline_for_viewers(self):
|
|
||||||
stats = Mock(spec=StatsEmitter)
|
|
||||||
stats.get_latest_stats.return_value = {
|
|
||||||
**self.test_stats,
|
|
||||||
"cpu_usages": {"52": {"cpu": "1.0", "cmdline": "ffmpeg -i rtsp://"}},
|
|
||||||
"bandwidth_usages": {"52": {"bandwidth": 1.0}},
|
|
||||||
}
|
|
||||||
app = super().create_app(stats)
|
|
||||||
|
|
||||||
with AuthTestClient(app) as client:
|
|
||||||
response = client.get(
|
|
||||||
"/stats",
|
|
||||||
headers={"remote-user": "viewer", "remote-role": "viewer"},
|
|
||||||
)
|
|
||||||
assert response.json()["cpu_usages"] == {"52": {"cpu": "1.0"}}
|
|
||||||
assert "bandwidth_usages" not in response.json()
|
|
||||||
|
|
||||||
def test_recordings_storage_requires_admin(self):
|
def test_recordings_storage_requires_admin(self):
|
||||||
stats = Mock(spec=StatsEmitter)
|
stats = Mock(spec=StatsEmitter)
|
||||||
stats.get_latest_stats.return_value = self.test_stats
|
stats.get_latest_stats.return_value = self.test_stats
|
||||||
@@ -117,32 +98,6 @@ class TestHttpApp(BaseTestHttp):
|
|||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
assert app.frigate_config.cameras["front_door"].objects.track == ["person"]
|
assert app.frigate_config.cameras["front_door"].objects.track == ["person"]
|
||||||
|
|
||||||
def test_config_set_in_memory_adds_filters_for_new_tracked_labels(self):
|
|
||||||
self.minimal_config["cameras"]["front_door"]["objects"] = {
|
|
||||||
"track": ["person"],
|
|
||||||
}
|
|
||||||
app = super().create_app()
|
|
||||||
app.config_publisher = Mock()
|
|
||||||
|
|
||||||
with AuthTestClient(app) as client:
|
|
||||||
response = client.put(
|
|
||||||
"/config/set",
|
|
||||||
json={
|
|
||||||
"requires_restart": 0,
|
|
||||||
"skip_save": True,
|
|
||||||
"update_topic": "config/cameras/front_door/objects",
|
|
||||||
"config_data": {
|
|
||||||
"cameras": {
|
|
||||||
"front_door": {"objects": {"track": ["person", "cat"]}}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
assert response.status_code == 200
|
|
||||||
filters = app.frigate_config.cameras["front_door"].objects.filters
|
|
||||||
assert isinstance(filters["cat"], RuntimeFilterConfig)
|
|
||||||
|
|
||||||
@patch("frigate.detectors.detector_config.load_labels")
|
@patch("frigate.detectors.detector_config.load_labels")
|
||||||
def test_config_set_in_memory_rebinds_replay_model_on_scene_change(
|
def test_config_set_in_memory_rebinds_replay_model_on_scene_change(
|
||||||
self, mock_labels
|
self, mock_labels
|
||||||
@@ -199,10 +154,6 @@ class TestHttpApp(BaseTestHttp):
|
|||||||
|
|
||||||
def test_config_response_hides_notification_email_from_viewers(self):
|
def test_config_response_hides_notification_email_from_viewers(self):
|
||||||
self.minimal_config["notifications"] = {"email": "{FRIGATE_TEST_EMAIL}"}
|
self.minimal_config["notifications"] = {"email": "{FRIGATE_TEST_EMAIL}"}
|
||||||
self.minimal_config["profiles"] = {"away": {"friendly_name": "Away"}}
|
|
||||||
self.minimal_config["cameras"]["front_door"]["profiles"] = {
|
|
||||||
"away": {"notifications": {"email": "{FRIGATE_TEST_EMAIL}"}}
|
|
||||||
}
|
|
||||||
|
|
||||||
with patch.dict(FRIGATE_ENV_VARS, {"FRIGATE_TEST_EMAIL": "me@example.com"}):
|
with patch.dict(FRIGATE_ENV_VARS, {"FRIGATE_TEST_EMAIL": "me@example.com"}):
|
||||||
app = super().create_app()
|
app = super().create_app()
|
||||||
@@ -221,165 +172,10 @@ class TestHttpApp(BaseTestHttp):
|
|||||||
config["cameras"]["front_door"]["notifications"]["email"]
|
config["cameras"]["front_door"]["notifications"]["email"]
|
||||||
== REDACTED_CREDENTIAL_SENTINEL
|
== REDACTED_CREDENTIAL_SENTINEL
|
||||||
)
|
)
|
||||||
assert (
|
|
||||||
config["cameras"]["front_door"]["profiles"]["away"]["notifications"][
|
|
||||||
"email"
|
|
||||||
]
|
|
||||||
== REDACTED_CREDENTIAL_SENTINEL
|
|
||||||
)
|
|
||||||
|
|
||||||
response = client.get("/config")
|
response = client.get("/config")
|
||||||
assert response.json()["notifications"]["email"] == "me@example.com"
|
assert response.json()["notifications"]["email"] == "me@example.com"
|
||||||
|
|
||||||
def test_config_response_limits_urls_and_go2rtc_for_viewers(self):
|
|
||||||
secret_path = "rtsp://10.0.0.1:554/user=admin_password=hunter2_channel=1"
|
|
||||||
self.minimal_config["cameras"]["front_door"]["ffmpeg"]["inputs"][0]["path"] = (
|
|
||||||
secret_path
|
|
||||||
)
|
|
||||||
auth_header = "-headers 'Authorization: Basic c2VjcmV0'"
|
|
||||||
args = {
|
|
||||||
"global_args": auth_header,
|
|
||||||
"input_args": auth_header,
|
|
||||||
"output_args": {"detect": auth_header},
|
|
||||||
}
|
|
||||||
self.minimal_config["ffmpeg"] = dict(args)
|
|
||||||
front_door = self.minimal_config["cameras"]["front_door"]
|
|
||||||
front_door["ffmpeg"].update(args)
|
|
||||||
front_door["ffmpeg"]["inputs"][0].update(
|
|
||||||
global_args=auth_header, input_args=auth_header
|
|
||||||
)
|
|
||||||
front_door["webui_url"] = "http://admin:hunter2@10.0.0.1/"
|
|
||||||
self.minimal_config["go2rtc"] = {
|
|
||||||
"streams": {"front_door": [secret_path, "ffmpeg:front_door#audio=opus"]},
|
|
||||||
"webrtc": {"candidates": ["10.0.0.2:8555"]},
|
|
||||||
"webtorrent": {"shares": {"share": {"src": "front_door", "pwd": "x"}}},
|
|
||||||
}
|
|
||||||
app = super().create_app()
|
|
||||||
|
|
||||||
with AuthTestClient(app) as client:
|
|
||||||
response = client.get(
|
|
||||||
"/config",
|
|
||||||
headers={"remote-user": "viewer", "remote-role": "viewer"},
|
|
||||||
)
|
|
||||||
assert response.status_code == 200
|
|
||||||
config = response.json()
|
|
||||||
camera = config["cameras"]["front_door"]
|
|
||||||
assert camera["ffmpeg"]["inputs"][0]["path"] == ""
|
|
||||||
assert camera["ffmpeg_cmds"] == []
|
|
||||||
assert "webui_url" not in camera
|
|
||||||
assert "hunter2" not in response.text
|
|
||||||
assert "c2VjcmV0" not in response.text
|
|
||||||
assert config["go2rtc"] == {
|
|
||||||
"streams": {"front_door": []},
|
|
||||||
"webrtc": {"candidates": ["10.0.0.2:8555"]},
|
|
||||||
}
|
|
||||||
|
|
||||||
config = client.get("/config").json()
|
|
||||||
camera = config["cameras"]["front_door"]
|
|
||||||
assert camera["ffmpeg"]["inputs"][0]["path"] == secret_path
|
|
||||||
assert camera["ffmpeg"]["inputs"][0]["input_args"] == auth_header
|
|
||||||
assert camera["ffmpeg"]["input_args"] == auth_header
|
|
||||||
assert camera["ffmpeg_cmds"]
|
|
||||||
assert config["go2rtc"]["streams"]["front_door"][0] == secret_path
|
|
||||||
assert "webtorrent" in config["go2rtc"]
|
|
||||||
|
|
||||||
def test_config_response_hides_genai_endpoint_from_viewers(self):
|
|
||||||
self.minimal_config["genai"] = {
|
|
||||||
"local": {
|
|
||||||
"provider": "ollama",
|
|
||||||
"model": "llava",
|
|
||||||
"base_url": "http://user:pass@ollama:11434",
|
|
||||||
"provider_options": {"keep_alive": -1},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
app = super().create_app()
|
|
||||||
|
|
||||||
with AuthTestClient(app) as client:
|
|
||||||
genai = client.get(
|
|
||||||
"/config",
|
|
||||||
headers={"remote-user": "viewer", "remote-role": "viewer"},
|
|
||||||
).json()["genai"]["local"]
|
|
||||||
assert "base_url" not in genai
|
|
||||||
assert "provider_options" not in genai
|
|
||||||
assert genai["provider"] == "ollama"
|
|
||||||
|
|
||||||
genai = client.get("/config").json()["genai"]["local"]
|
|
||||||
assert genai["base_url"] == "http://user:pass@ollama:11434"
|
|
||||||
|
|
||||||
def test_metrics_requires_admin(self):
|
|
||||||
stats = Mock(spec=StatsEmitter)
|
|
||||||
stats.get_latest_stats.return_value = self.test_stats
|
|
||||||
app = super().create_app(stats)
|
|
||||||
|
|
||||||
with AuthTestClient(app) as client:
|
|
||||||
response = client.get(
|
|
||||||
"/metrics",
|
|
||||||
headers={"remote-user": "viewer", "remote-role": "viewer"},
|
|
||||||
)
|
|
||||||
assert response.status_code == 403
|
|
||||||
|
|
||||||
assert client.get("/metrics").status_code == 200
|
|
||||||
|
|
||||||
def test_config_response_allows_null_profile_notifications(self):
|
|
||||||
self.minimal_config["profiles"] = {"away": {"friendly_name": "Away"}}
|
|
||||||
self.minimal_config["cameras"]["front_door"]["profiles"] = {
|
|
||||||
"away": {"notifications": None}
|
|
||||||
}
|
|
||||||
app = super().create_app()
|
|
||||||
|
|
||||||
with AuthTestClient(app) as client:
|
|
||||||
response = client.get(
|
|
||||||
"/config",
|
|
||||||
headers={"remote-user": "viewer", "remote-role": "viewer"},
|
|
||||||
)
|
|
||||||
assert response.status_code == 200
|
|
||||||
|
|
||||||
def test_go2rtc_stream_producer_sources_hidden_from_viewers(self):
|
|
||||||
secret_url = "ffmpeg:rtsp://admin:hunter2@10.0.0.1:554/live"
|
|
||||||
stream = {
|
|
||||||
"producers": [
|
|
||||||
{
|
|
||||||
"url": secret_url,
|
|
||||||
"source": "ffmpeg -i rtsp://admin:hunter2@10.0.0.1:554/live",
|
|
||||||
"medias": ["video, recvonly, H264"],
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"consumers": [{"url": "rtmp://a.rtmp.youtube.com/live2/hunter2"}],
|
|
||||||
}
|
|
||||||
app = super().create_app()
|
|
||||||
viewer = {"remote-user": "viewer", "remote-role": "viewer"}
|
|
||||||
|
|
||||||
with (
|
|
||||||
patch("frigate.api.camera.requests.get") as get,
|
|
||||||
AuthTestClient(app) as client,
|
|
||||||
):
|
|
||||||
get.return_value.json.side_effect = lambda: copy.deepcopy(stream)
|
|
||||||
|
|
||||||
viewer_stream = {"producers": [{"medias": ["video, recvonly, H264"]}]}
|
|
||||||
|
|
||||||
response = client.get("/go2rtc/streams/front_door", headers=viewer)
|
|
||||||
assert response.json() == viewer_stream
|
|
||||||
|
|
||||||
producer = client.get("/go2rtc/streams/front_door").json()["producers"][0]
|
|
||||||
assert producer["medias"] == ["video, recvonly, H264"]
|
|
||||||
assert "hunter2" not in producer["url"]
|
|
||||||
|
|
||||||
get.return_value.json.side_effect = lambda: {
|
|
||||||
"front_door": copy.deepcopy(stream)
|
|
||||||
}
|
|
||||||
response = client.get("/go2rtc/streams", headers=viewer)
|
|
||||||
assert response.json() == {"front_door": viewer_stream}
|
|
||||||
|
|
||||||
# unconnected streams have url-only producers and null consumers
|
|
||||||
get.return_value.json.side_effect = lambda: {
|
|
||||||
"front_door": {"producers": [{"url": secret_url}], "consumers": None}
|
|
||||||
}
|
|
||||||
response = client.get("/go2rtc/streams")
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert "hunter2" not in response.text
|
|
||||||
response = client.get("/go2rtc/streams", headers=viewer)
|
|
||||||
assert response.json() == {"front_door": {"producers": [{"medias": None}]}}
|
|
||||||
|
|
||||||
def test_config_response_keeps_plus_model_reference(self):
|
def test_config_response_keeps_plus_model_reference(self):
|
||||||
model_id = "test_plus_reference"
|
model_id = "test_plus_reference"
|
||||||
model_path = os.path.join(MODEL_CACHE_DIR, model_id)
|
model_path = os.path.join(MODEL_CACHE_DIR, model_id)
|
||||||
|
|||||||
@@ -10,13 +10,7 @@ import ruamel.yaml
|
|||||||
|
|
||||||
from frigate.models import Event, Recordings, ReviewSegment
|
from frigate.models import Event, Recordings, ReviewSegment
|
||||||
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
|
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
|
||||||
from frigate.util.env import (
|
from frigate.util.env import _CONTAINER_ENV, FRIGATE_ENV_VARS, reload_sources
|
||||||
_CONFIG_ENV_VARS,
|
|
||||||
_CONTAINER_ENV,
|
|
||||||
FRIGATE_ENV_VARS,
|
|
||||||
apply_config_env_vars,
|
|
||||||
reload_sources,
|
|
||||||
)
|
|
||||||
|
|
||||||
# shape of the source in GHSA-qjjw-3v66-279f, with the payload replaced
|
# shape of the source in GHSA-qjjw-3v66-279f, with the payload replaced
|
||||||
_INJECTED_SRC = "ffmpeg:#input='-f''h264''-i''data:placeholder''-c''copy'"
|
_INJECTED_SRC = "ffmpeg:#input='-f''h264''-i''data:placeholder''-c''copy'"
|
||||||
@@ -24,8 +18,6 @@ _INJECTED_SRC = "ffmpeg:#input='-f''h264''-i''data:placeholder''-c''copy'"
|
|||||||
# an unrestricted ffmpeg: source the operator already has in the file on disk
|
# an unrestricted ffmpeg: source the operator already has in the file on disk
|
||||||
_EXISTING_SRC = "ffmpeg:rtsp://10.0.0.1:554/video#raw=-vn"
|
_EXISTING_SRC = "ffmpeg:rtsp://10.0.0.1:554/video#raw=-vn"
|
||||||
|
|
||||||
_PLACEHOLDER_SRC = "ffmpeg:rtsp://10.0.0.1:554/{FRIGATE_CAM_PATH}"
|
|
||||||
|
|
||||||
_CONFIG = {
|
_CONFIG = {
|
||||||
"mqtt": {"host": "mqtt"},
|
"mqtt": {"host": "mqtt"},
|
||||||
"go2rtc": {"streams": {"front_door": [_EXISTING_SRC]}},
|
"go2rtc": {"streams": {"front_door": [_EXISTING_SRC]}},
|
||||||
@@ -119,28 +111,6 @@ class TestConfigGo2rtcStreamRestrictions(BaseTestHttp):
|
|||||||
headers={"Content-Type": "text/plain"},
|
headers={"Content-Type": "text/plain"},
|
||||||
)
|
)
|
||||||
|
|
||||||
def _save(self, config: dict):
|
|
||||||
with AuthTestClient(self.app) as client:
|
|
||||||
return client.post(
|
|
||||||
"/config/save?save_option=saveonly",
|
|
||||||
content=_dump(config),
|
|
||||||
headers={"Content-Type": "text/plain"},
|
|
||||||
)
|
|
||||||
|
|
||||||
def _start_with_placeholder_source(self) -> dict:
|
|
||||||
"""Write and install a config whose stream reads FRIGATE_CAM_PATH from
|
|
||||||
environment_vars, as if Frigate had started with it."""
|
|
||||||
config = copy.deepcopy(_CONFIG)
|
|
||||||
config["environment_vars"] = {"FRIGATE_CAM_PATH": "video"}
|
|
||||||
config["go2rtc"]["streams"]["front_door"].append(_PLACEHOLDER_SRC)
|
|
||||||
with open(self.config_path, "w") as f:
|
|
||||||
f.write(_dump(config))
|
|
||||||
|
|
||||||
apply_config_env_vars(config["environment_vars"])
|
|
||||||
self.addCleanup(reload_sources, warn=False)
|
|
||||||
self.addCleanup(_CONFIG_ENV_VARS.clear)
|
|
||||||
return config
|
|
||||||
|
|
||||||
# --- config/set ---
|
# --- config/set ---
|
||||||
|
|
||||||
def test_set_rejects_injected_ffmpeg_source(self):
|
def test_set_rejects_injected_ffmpeg_source(self):
|
||||||
@@ -285,52 +255,6 @@ class TestConfigGo2rtcStreamRestrictions(BaseTestHttp):
|
|||||||
assert resp.status_code == 200, resp.text
|
assert resp.status_code == 200, resp.text
|
||||||
assert src in self._read_config()
|
assert src in self._read_config()
|
||||||
|
|
||||||
def test_save_rejects_changed_env_var_in_existing_source(self):
|
|
||||||
config = self._start_with_placeholder_source()
|
|
||||||
before = self._read_config()
|
|
||||||
config["environment_vars"]["FRIGATE_CAM_PATH"] = "video#raw=-vn"
|
|
||||||
resp = self._save(config)
|
|
||||||
assert resp.status_code == 400
|
|
||||||
assert "Restricted go2rtc stream source" in resp.json()["message"]
|
|
||||||
assert self._read_config() == before
|
|
||||||
|
|
||||||
def test_save_allows_safe_env_var_change_in_existing_source(self):
|
|
||||||
config = self._start_with_placeholder_source()
|
|
||||||
config["environment_vars"]["FRIGATE_CAM_PATH"] = "video2"
|
|
||||||
resp = self._save(config)
|
|
||||||
assert resp.status_code == 200, resp.text
|
|
||||||
|
|
||||||
def test_save_resubmitting_placeholder_source_allowed(self):
|
|
||||||
config = self._start_with_placeholder_source()
|
|
||||||
resp = self._save(config)
|
|
||||||
assert resp.status_code == 200, resp.text
|
|
||||||
|
|
||||||
def test_save_rejects_removed_env_var_in_existing_source(self):
|
|
||||||
config = self._start_with_placeholder_source()
|
|
||||||
before = self._read_config()
|
|
||||||
del config["environment_vars"]
|
|
||||||
resp = self._save(config)
|
|
||||||
assert resp.status_code == 400
|
|
||||||
assert self._read_config() == before
|
|
||||||
|
|
||||||
def test_save_allows_env_var_added_with_its_source(self):
|
|
||||||
config = copy.deepcopy(_CONFIG)
|
|
||||||
config["environment_vars"] = {"FRIGATE_NEW_PATH": "video"}
|
|
||||||
config["go2rtc"]["streams"]["new_stream"] = (
|
|
||||||
"ffmpeg:rtsp://10.0.0.2:554/{FRIGATE_NEW_PATH}"
|
|
||||||
)
|
|
||||||
resp = self._save(config)
|
|
||||||
assert resp.status_code == 200, resp.text
|
|
||||||
|
|
||||||
def test_save_rejects_unsafe_env_var_added_with_its_source(self):
|
|
||||||
config = copy.deepcopy(_CONFIG)
|
|
||||||
config["environment_vars"] = {"FRIGATE_NEW_PATH": "video#raw=-vn"}
|
|
||||||
config["go2rtc"]["streams"]["new_stream"] = (
|
|
||||||
"ffmpeg:rtsp://10.0.0.2:554/{FRIGATE_NEW_PATH}"
|
|
||||||
)
|
|
||||||
resp = self._save(config)
|
|
||||||
assert resp.status_code == 400
|
|
||||||
|
|
||||||
# --- go2rtc ffmpeg and ngrok options ---
|
# --- go2rtc ffmpeg and ngrok options ---
|
||||||
|
|
||||||
def test_save_rejects_ffmpeg_bin_override(self):
|
def test_save_rejects_ffmpeg_bin_override(self):
|
||||||
|
|||||||
@@ -624,96 +624,6 @@ class TestConfigSetWildcardPropagation(BaseTestHttp):
|
|||||||
finally:
|
finally:
|
||||||
os.unlink(config_path)
|
os.unlink(config_path)
|
||||||
|
|
||||||
@patch.dict("frigate.util.env._CONFIG_ENV_VARS", {"FRIGATE_CAM_HOST": "10.0.0.1"})
|
|
||||||
@patch.dict("frigate.util.env.FRIGATE_ENV_VARS", {"FRIGATE_CAM_HOST": "10.0.0.1"})
|
|
||||||
@patch("frigate.api.app.find_config_file")
|
|
||||||
def test_masked_path_matches_after_saved_env_var_swap(self, mock_find_config):
|
|
||||||
"""A no-restart update swaps in a config resolved with the saved
|
|
||||||
environment_vars, so /config shows the saved value until a restart."""
|
|
||||||
path = "rtsp://admin:pw@{FRIGATE_CAM_HOST}:554/live"
|
|
||||||
self._set_inputs([(path, "detect")])
|
|
||||||
self.minimal_config["environment_vars"] = {"FRIGATE_CAM_HOST": "10.0.0.2"}
|
|
||||||
config_path = self._write_config_file()
|
|
||||||
mock_find_config.return_value = config_path
|
|
||||||
|
|
||||||
try:
|
|
||||||
app, _ = self._create_app_with_publisher()
|
|
||||||
|
|
||||||
with AuthTestClient(app) as client:
|
|
||||||
resp = self._save(
|
|
||||||
client, {"cameras": {"front_door": {"detect": {"fps": 6}}}}
|
|
||||||
)
|
|
||||||
self.assertEqual(resp.status_code, 200, resp.text)
|
|
||||||
|
|
||||||
camera = client.get("/config").json()["cameras"]["front_door"]
|
|
||||||
inputs = camera["ffmpeg"]["inputs"]
|
|
||||||
self.assertIn("10.0.0.2", inputs[0]["path"])
|
|
||||||
|
|
||||||
resp = self._save(
|
|
||||||
client,
|
|
||||||
{
|
|
||||||
"cameras": {
|
|
||||||
"front_door": {
|
|
||||||
"ffmpeg": {"inputs": inputs},
|
|
||||||
"detect": {"fps": 7},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
)
|
|
||||||
self.assertEqual(resp.status_code, 200, resp.text)
|
|
||||||
|
|
||||||
_, saved = self._read_config_file(config_path)
|
|
||||||
self.assertEqual(
|
|
||||||
saved["cameras"]["front_door"]["ffmpeg"]["inputs"][0]["path"], path
|
|
||||||
)
|
|
||||||
finally:
|
|
||||||
os.unlink(config_path)
|
|
||||||
|
|
||||||
@patch.dict(
|
|
||||||
"frigate.util.env._CONFIG_ENV_VARS",
|
|
||||||
{"FRIGATE_HOST_A": "10.0.0.1", "FRIGATE_HOST_B": "10.0.0.2"},
|
|
||||||
)
|
|
||||||
@patch.dict(
|
|
||||||
"frigate.util.env.FRIGATE_ENV_VARS",
|
|
||||||
{"FRIGATE_HOST_A": "10.0.0.1", "FRIGATE_HOST_B": "10.0.0.2"},
|
|
||||||
)
|
|
||||||
@patch("frigate.api.app.find_config_file")
|
|
||||||
def test_masked_paths_match_running_env_vars(self, mock_find_config):
|
|
||||||
"""A saved but not yet applied environment_vars change must not make
|
|
||||||
one input's masked path match another's."""
|
|
||||||
path_a = "rtsp://admin:pw@{FRIGATE_HOST_A}:554/live"
|
|
||||||
path_b = "rtsp://admin:pw@{FRIGATE_HOST_B}:554/live"
|
|
||||||
self._set_inputs([(path_a, "detect"), (path_b, "record")])
|
|
||||||
self.minimal_config["environment_vars"] = {
|
|
||||||
"FRIGATE_HOST_A": "10.0.0.1",
|
|
||||||
"FRIGATE_HOST_B": "10.0.0.2",
|
|
||||||
}
|
|
||||||
app, _ = self._create_app_with_publisher()
|
|
||||||
|
|
||||||
self.minimal_config["environment_vars"]["FRIGATE_HOST_A"] = "10.0.0.2"
|
|
||||||
config_path = self._write_config_file()
|
|
||||||
mock_find_config.return_value = config_path
|
|
||||||
|
|
||||||
try:
|
|
||||||
with AuthTestClient(app) as client:
|
|
||||||
camera = client.get("/config").json()["cameras"]["front_door"]
|
|
||||||
inputs = camera["ffmpeg"]["inputs"]
|
|
||||||
inputs[0]["roles"], inputs[1]["roles"] = ["record"], ["detect"]
|
|
||||||
|
|
||||||
resp = self._save(
|
|
||||||
client, {"cameras": {"front_door": {"ffmpeg": {"inputs": inputs}}}}
|
|
||||||
)
|
|
||||||
self.assertEqual(resp.status_code, 200, resp.text)
|
|
||||||
|
|
||||||
_, saved = self._read_config_file(config_path)
|
|
||||||
saved_inputs = saved["cameras"]["front_door"]["ffmpeg"]["inputs"]
|
|
||||||
self.assertEqual(
|
|
||||||
[(inp["path"], inp["roles"]) for inp in saved_inputs],
|
|
||||||
[(path_a, ["record"]), (path_b, ["detect"])],
|
|
||||||
)
|
|
||||||
finally:
|
|
||||||
os.unlink(config_path)
|
|
||||||
|
|
||||||
@patch("frigate.api.app.find_config_file")
|
@patch("frigate.api.app.find_config_file")
|
||||||
def test_over_masked_path_round_trips(self, mock_find_config):
|
def test_over_masked_path_round_trips(self, mock_find_config):
|
||||||
path = "rtsp://10.0.0.1:554/live?x=a@b"
|
path = "rtsp://10.0.0.1:554/live?x=a@b"
|
||||||
|
|||||||
@@ -4,17 +4,14 @@ import threading
|
|||||||
from concurrent.futures import ThreadPoolExecutor
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import UTC, datetime, timedelta
|
from datetime import UTC, datetime, timedelta
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import patch
|
||||||
from zoneinfo import ZoneInfo
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
import cv2
|
|
||||||
import numpy as np
|
|
||||||
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.const import MAX_SEGMENT_DURATION
|
||||||
from frigate.models import Event, Recordings
|
from frigate.models import Event, Recordings
|
||||||
from frigate.plus import PlusRateLimitError
|
|
||||||
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
|
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
|
||||||
|
|
||||||
|
|
||||||
@@ -591,47 +588,6 @@ class TestHttpMedia(BaseTestHttp):
|
|||||||
response = client.get("/recordings/unavailable", params={"scale": 0})
|
response = client.get("/recordings/unavailable", params={"scale": 0})
|
||||||
assert response.status_code == 422
|
assert response.status_code == 422
|
||||||
|
|
||||||
def test_recordings_unavailable_large_span(self):
|
|
||||||
"""A wide span at a fine scale returns its gaps without stepping per bucket."""
|
|
||||||
with AuthTestClient(self.app) as client:
|
|
||||||
self._insert_recording("only", 1000, 1100)
|
|
||||||
|
|
||||||
response = client.get(
|
|
||||||
"/recordings/unavailable",
|
|
||||||
params={"after": 1, "before": 10**12, "scale": 1},
|
|
||||||
)
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert response.json() == [
|
|
||||||
{"start_time": 1, "end_time": 1000},
|
|
||||||
{"start_time": 1100, "end_time": 10**12},
|
|
||||||
]
|
|
||||||
|
|
||||||
for param in ("before", "after"):
|
|
||||||
for bound in ("inf", "-inf", "nan"):
|
|
||||||
response = client.get(
|
|
||||||
"/recordings/unavailable", params={param: bound}
|
|
||||||
)
|
|
||||||
assert response.status_code == 422
|
|
||||||
|
|
||||||
def test_latest_frame_height_capped_at_source(self):
|
|
||||||
"""A requested height above the frame height returns the frame unscaled."""
|
|
||||||
frame = np.zeros((90, 160, 3), np.uint8)
|
|
||||||
processor = MagicMock()
|
|
||||||
processor.get_current_frame.return_value = frame
|
|
||||||
processor.get_current_frame_time.return_value = datetime.now().timestamp()
|
|
||||||
self.app.detected_frames_processor = processor
|
|
||||||
|
|
||||||
with AuthTestClient(self.app) as client:
|
|
||||||
for height, expected in ((45, (45, 80)), (5000, (90, 160))):
|
|
||||||
response = client.get(
|
|
||||||
"/front_door/latest.jpg", params={"height": height}
|
|
||||||
)
|
|
||||||
assert response.status_code == 200
|
|
||||||
image = cv2.imdecode(
|
|
||||||
np.frombuffer(response.content, np.uint8), cv2.IMREAD_COLOR
|
|
||||||
)
|
|
||||||
assert image.shape[:2] == expected
|
|
||||||
|
|
||||||
def test_recordings_summary_day_attribution_by_start_time(self):
|
def test_recordings_summary_day_attribution_by_start_time(self):
|
||||||
"""
|
"""
|
||||||
A recording spanning midnight marks only its start day.
|
A recording spanning midnight marks only its start day.
|
||||||
@@ -2145,22 +2101,3 @@ class TestHttpMedia(BaseTestHttp):
|
|||||||
|
|
||||||
self.assertEqual(response.status_code, 200)
|
self.assertEqual(response.status_code, 200)
|
||||||
upload.assert_called_once_with("frame", "front_door")
|
upload.assert_called_once_with("frame", "front_door")
|
||||||
|
|
||||||
def test_plus_snapshot_rate_limited(self):
|
|
||||||
self._insert_recording("snapshot", 1000, 1010)
|
|
||||||
|
|
||||||
with (
|
|
||||||
AuthTestClient(self.app) as client,
|
|
||||||
patch("frigate.api.media.get_image_from_recording", return_value=b"png"),
|
|
||||||
patch("frigate.api.media.cv2.imdecode", return_value="frame"),
|
|
||||||
patch.object(
|
|
||||||
self.app.frigate_config.plus_api,
|
|
||||||
"upload_image",
|
|
||||||
side_effect=PlusRateLimitError(60),
|
|
||||||
),
|
|
||||||
):
|
|
||||||
response = client.post("/front_door/plus/1005")
|
|
||||||
|
|
||||||
self.assertEqual(response.status_code, 429)
|
|
||||||
self.assertEqual(response.json()["retry_after"], 60)
|
|
||||||
self.assertEqual(response.headers["Retry-After"], "60")
|
|
||||||
|
|||||||
@@ -3,10 +3,8 @@
|
|||||||
import unittest
|
import unittest
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
|
|
||||||
from frigate.models import Event
|
from frigate.models import Event
|
||||||
from frigate.plus import PlusKeyStatus, PlusRateLimitError
|
from frigate.plus import PlusKeyStatus
|
||||||
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
|
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
|
||||||
|
|
||||||
|
|
||||||
@@ -14,13 +12,11 @@ class TestHttpPlusValidate(BaseTestHttp):
|
|||||||
def setUp(self):
|
def setUp(self):
|
||||||
super().setUp([Event])
|
super().setUp([Event])
|
||||||
|
|
||||||
def _validate(self, status: PlusKeyStatus, retry_after: int | None = None) -> dict:
|
def _validate(self, status: PlusKeyStatus) -> dict:
|
||||||
app = self.create_app()
|
app = self.create_app()
|
||||||
plus_api = app.frigate_config.plus_api
|
|
||||||
|
|
||||||
with (
|
with patch.object(
|
||||||
patch.object(plus_api, "validate_key", return_value=status),
|
app.frigate_config.plus_api, "validate_key", return_value=status
|
||||||
patch.object(plus_api, "rate_limit_remaining", return_value=retry_after),
|
|
||||||
):
|
):
|
||||||
with AuthTestClient(app) as client:
|
with AuthTestClient(app) as client:
|
||||||
response = client.post("/plus/validate")
|
response = client.post("/plus/validate")
|
||||||
@@ -39,12 +35,6 @@ class TestHttpPlusValidate(BaseTestHttp):
|
|||||||
{"success": False, "status": "invalid"},
|
{"success": False, "status": "invalid"},
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_a_rate_limited_key_includes_the_wait(self):
|
|
||||||
self.assertEqual(
|
|
||||||
self._validate(PlusKeyStatus.rate_limited, 90),
|
|
||||||
{"success": False, "status": "rate_limited", "retry_after": 90},
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_viewers_cannot_validate(self):
|
def test_viewers_cannot_validate(self):
|
||||||
app = self.create_app()
|
app = self.create_app()
|
||||||
|
|
||||||
@@ -57,111 +47,5 @@ class TestHttpPlusValidate(BaseTestHttp):
|
|||||||
self.assertEqual(response.status_code, 403)
|
self.assertEqual(response.status_code, 403)
|
||||||
|
|
||||||
|
|
||||||
class TestHttpPlusRateLimit(BaseTestHttp):
|
|
||||||
"""A Frigate+ rate limit reaches the client as a 429 with the wait."""
|
|
||||||
|
|
||||||
def setUp(self):
|
|
||||||
super().setUp([Event])
|
|
||||||
self.app = self.create_app()
|
|
||||||
self.plus_api = self.app.frigate_config.plus_api
|
|
||||||
patcher = patch.object(self.plus_api, "is_active", return_value=True)
|
|
||||||
patcher.start()
|
|
||||||
self.addCleanup(patcher.stop)
|
|
||||||
|
|
||||||
def _assert_rate_limited(self, response, retry_after: int | None) -> None:
|
|
||||||
self.assertEqual(response.status_code, 429)
|
|
||||||
self.assertEqual(response.json()["retry_after"], retry_after)
|
|
||||||
self.assertFalse(response.json()["success"])
|
|
||||||
self.assertEqual(
|
|
||||||
response.headers.get("Retry-After"),
|
|
||||||
None if retry_after is None else str(retry_after),
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_listing_models(self):
|
|
||||||
for retry_after in (30, None):
|
|
||||||
with (
|
|
||||||
self.subTest(retry_after=retry_after),
|
|
||||||
patch.object(
|
|
||||||
self.plus_api,
|
|
||||||
"get_models",
|
|
||||||
side_effect=PlusRateLimitError(retry_after),
|
|
||||||
),
|
|
||||||
AuthTestClient(self.app) as client,
|
|
||||||
):
|
|
||||||
self._assert_rate_limited(client.get("/plus/models"), retry_after)
|
|
||||||
|
|
||||||
def test_submitting_an_event(self):
|
|
||||||
self.insert_mock_event("event", data={"box": [0, 0, 1, 1]})
|
|
||||||
|
|
||||||
with (
|
|
||||||
patch(
|
|
||||||
"frigate.api.event.load_event_snapshot_image",
|
|
||||||
return_value=(np.ones((10, 10, 3), np.uint8), True),
|
|
||||||
),
|
|
||||||
patch.object(
|
|
||||||
self.plus_api, "upload_image", side_effect=PlusRateLimitError(30)
|
|
||||||
),
|
|
||||||
AuthTestClient(self.app) as client,
|
|
||||||
):
|
|
||||||
response = client.post("/events/event/plus", json={})
|
|
||||||
|
|
||||||
self._assert_rate_limited(response, 30)
|
|
||||||
self.assertIsNone(Event.get(Event.id == "event").plus_id)
|
|
||||||
|
|
||||||
def test_a_rate_limited_annotation_can_be_retried(self):
|
|
||||||
self.insert_mock_event("event", data={"box": [0, 0, 1, 1]})
|
|
||||||
snapshot = patch(
|
|
||||||
"frigate.api.event.load_event_snapshot_image",
|
|
||||||
return_value=(np.ones((10, 10, 3), np.uint8), True),
|
|
||||||
)
|
|
||||||
|
|
||||||
with (
|
|
||||||
snapshot,
|
|
||||||
patch.object(self.plus_api, "upload_image", return_value="img") as upload,
|
|
||||||
patch.object(
|
|
||||||
self.plus_api,
|
|
||||||
"add_annotation",
|
|
||||||
side_effect=[PlusRateLimitError(30), None],
|
|
||||||
) as annotate,
|
|
||||||
AuthTestClient(self.app) as client,
|
|
||||||
):
|
|
||||||
first = client.post("/events/event/plus", json={"include_annotation": 1})
|
|
||||||
# the image isn't marked submitted while its annotation is missing
|
|
||||||
self.assertIsNone(Event.get(Event.id == "event").plus_id)
|
|
||||||
|
|
||||||
retry = client.post("/events/event/plus", json={"include_annotation": 1})
|
|
||||||
|
|
||||||
self._assert_rate_limited(first, 30)
|
|
||||||
self.assertEqual(retry.status_code, 200)
|
|
||||||
self.assertEqual(retry.json()["plus_id"], "img")
|
|
||||||
upload.assert_called_once()
|
|
||||||
self.assertEqual(
|
|
||||||
[call.args[0] for call in annotate.call_args_list], ["img", "img"]
|
|
||||||
)
|
|
||||||
|
|
||||||
event = Event.get(Event.id == "event")
|
|
||||||
self.assertEqual(event.plus_id, "img")
|
|
||||||
self.assertNotIn("plus_pending_id", event.data)
|
|
||||||
|
|
||||||
def test_submitting_a_false_positive(self):
|
|
||||||
self.insert_mock_event(
|
|
||||||
"event", data={"box": [0, 0, 1, 1], "region": [0, 0, 1, 1], "score": 0.9}
|
|
||||||
)
|
|
||||||
Event.update(plus_id="plus").where(Event.id == "event").execute()
|
|
||||||
|
|
||||||
with (
|
|
||||||
patch.object(
|
|
||||||
self.plus_api,
|
|
||||||
"add_false_positive",
|
|
||||||
side_effect=PlusRateLimitError(45),
|
|
||||||
),
|
|
||||||
AuthTestClient(self.app) as client,
|
|
||||||
):
|
|
||||||
response = client.put("/events/event/false_positive")
|
|
||||||
|
|
||||||
self._assert_rate_limited(response, 45)
|
|
||||||
self.assertFalse(Event.get(Event.id == "event").false_positive)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main(verbosity=2)
|
unittest.main(verbosity=2)
|
||||||
|
|||||||
@@ -1,98 +0,0 @@
|
|||||||
"""Current-hour preview frame routes only return the requested camera's frames."""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import shutil
|
|
||||||
import tempfile
|
|
||||||
import time
|
|
||||||
from unittest.mock import MagicMock, patch
|
|
||||||
|
|
||||||
from frigate.const import PREVIEW_FRAME_TYPE
|
|
||||||
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
|
|
||||||
|
|
||||||
CAMERA = "front_door"
|
|
||||||
|
|
||||||
# camera names that extend CAMERA with "-" share its file name prefix
|
|
||||||
SIBLINGS = (f"{CAMERA}-2", f"{CAMERA}-door")
|
|
||||||
|
|
||||||
|
|
||||||
class TestHttpPreviewFrames(BaseTestHttp):
|
|
||||||
def setUp(self):
|
|
||||||
super().setUp([])
|
|
||||||
self.app = super().create_app()
|
|
||||||
|
|
||||||
self.cache_dir = tempfile.mkdtemp()
|
|
||||||
self.addCleanup(shutil.rmtree, self.cache_dir, ignore_errors=True)
|
|
||||||
self.preview_dir = os.path.join(self.cache_dir, "preview_frames")
|
|
||||||
os.makedirs(self.preview_dir)
|
|
||||||
|
|
||||||
for target, value in (
|
|
||||||
("frigate.api.media.CACHE_DIR", self.cache_dir),
|
|
||||||
("frigate.api.preview.CACHE_DIR", self.cache_dir),
|
|
||||||
("frigate.api.preview._preview_listing_cache", (-1.0, [])),
|
|
||||||
):
|
|
||||||
patcher = patch(target, value)
|
|
||||||
patcher.start()
|
|
||||||
self.addCleanup(patcher.stop)
|
|
||||||
|
|
||||||
# ahead of now so the media routes never fall back to stored previews
|
|
||||||
|
|
||||||
self.start_ts = time.time() + 60
|
|
||||||
self._write_frame(CAMERA, self.start_ts - 10)
|
|
||||||
self.own_frames = [self._write_frame(CAMERA, self.start_ts + 1)]
|
|
||||||
|
|
||||||
for sibling in SIBLINGS:
|
|
||||||
self._write_frame(sibling, self.start_ts + 1)
|
|
||||||
|
|
||||||
def _write_frame(self, camera: str, frame_time: float) -> str:
|
|
||||||
name = f"preview_{camera}-{frame_time}.{PREVIEW_FRAME_TYPE}"
|
|
||||||
with open(os.path.join(self.preview_dir, name), "wb") as f:
|
|
||||||
f.write(b"frame")
|
|
||||||
return name
|
|
||||||
|
|
||||||
def _concat_files(self, mock_run: MagicMock) -> set[str]:
|
|
||||||
concat = mock_run.call_args.kwargs["input"].decode()
|
|
||||||
return {
|
|
||||||
os.path.basename(line.split("'")[1])
|
|
||||||
for line in concat.splitlines()
|
|
||||||
if line.startswith("file ")
|
|
||||||
}
|
|
||||||
|
|
||||||
def test_frames_listing_excludes_sibling_camera(self):
|
|
||||||
with AuthTestClient(self.app) as client:
|
|
||||||
response = client.get(
|
|
||||||
f"/preview/{CAMERA}/start/{self.start_ts}/end/inf/frames"
|
|
||||||
)
|
|
||||||
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert response.json() == self.own_frames
|
|
||||||
|
|
||||||
def test_preview_gif_excludes_sibling_camera(self):
|
|
||||||
result = MagicMock(returncode=0, stdout=b"GIF89a")
|
|
||||||
|
|
||||||
with (
|
|
||||||
patch("frigate.api.media.sp.run", return_value=result) as mock_run,
|
|
||||||
AuthTestClient(self.app) as client,
|
|
||||||
):
|
|
||||||
response = client.get(
|
|
||||||
f"/{CAMERA}/start/{self.start_ts}/end/inf/preview.gif"
|
|
||||||
)
|
|
||||||
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert self._concat_files(mock_run) == set(self.own_frames)
|
|
||||||
|
|
||||||
def test_preview_mp4_excludes_sibling_camera(self):
|
|
||||||
def fake_run(cmd, **kwargs):
|
|
||||||
with open(cmd[-1], "wb") as f:
|
|
||||||
f.write(b"mp4")
|
|
||||||
return MagicMock(returncode=0)
|
|
||||||
|
|
||||||
with (
|
|
||||||
patch("frigate.api.media.sp.run", side_effect=fake_run) as mock_run,
|
|
||||||
AuthTestClient(self.app) as client,
|
|
||||||
):
|
|
||||||
response = client.get(
|
|
||||||
f"/{CAMERA}/start/{self.start_ts}/end/inf/preview.mp4"
|
|
||||||
)
|
|
||||||
|
|
||||||
assert response.status_code == 200
|
|
||||||
assert self._concat_files(mock_run) == set(self.own_frames)
|
|
||||||
@@ -2,9 +2,7 @@
|
|||||||
|
|
||||||
import multiprocessing as mp
|
import multiprocessing as mp
|
||||||
import unittest
|
import unittest
|
||||||
from unittest.mock import Mock, patch
|
from unittest.mock import Mock
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
|
|
||||||
from frigate.config import (
|
from frigate.config import (
|
||||||
BirdseyeModeEnum,
|
BirdseyeModeEnum,
|
||||||
@@ -609,72 +607,6 @@ class TestBirdseyeModePayload(unittest.TestCase):
|
|||||||
assert birdseye_modes_from_mqtt_payload(payload) is None
|
assert birdseye_modes_from_mqtt_payload(payload) is None
|
||||||
|
|
||||||
|
|
||||||
class TestBirdseyeRuntimeToggles(unittest.TestCase):
|
|
||||||
"""Runtime config changes must not crash or overdrive Birdseye."""
|
|
||||||
|
|
||||||
def setUp(self):
|
|
||||||
config = {
|
|
||||||
"mqtt": {"enabled": False},
|
|
||||||
"birdseye": {"enabled": True, "modes": ["continuous"]},
|
|
||||||
"cameras": {
|
|
||||||
"front": {
|
|
||||||
"ffmpeg": {
|
|
||||||
"inputs": [
|
|
||||||
{"path": "rtsp://10.0.0.1:554/video", "roles": ["detect"]}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"detect": {"height": 1080, "width": 1920, "fps": 5},
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
self.config = FrigateConfig(**config)
|
|
||||||
self.manager = BirdsEyeFrameManager(self.config, mp.Event())
|
|
||||||
self.frame = np.zeros((1620, 1920), np.uint8)
|
|
||||||
self.activity = BirdseyeActivity(
|
|
||||||
has_object=True, has_motion=True, severity=None
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_disabled_camera_forces_one_update_only(self):
|
|
||||||
self.manager.update("front", self.activity, 1000.0, self.frame)
|
|
||||||
self.config.cameras["front"].birdseye.enabled = False
|
|
||||||
|
|
||||||
changed, _ = self.manager.update("front", self.activity, 1000.2, self.frame)
|
|
||||||
assert changed
|
|
||||||
|
|
||||||
changed, _ = self.manager.update("front", self.activity, 1000.4, self.frame)
|
|
||||||
assert not changed
|
|
||||||
|
|
||||||
def test_enabling_restream_at_runtime_does_not_write_missing_buffer(self):
|
|
||||||
birdseye = Birdseye.__new__(Birdseye)
|
|
||||||
birdseye.restream = False
|
|
||||||
birdseye.config = self.config
|
|
||||||
birdseye.birdseye_manager = self.manager
|
|
||||||
birdseye.input = Mock()
|
|
||||||
self.config.birdseye.restream = True
|
|
||||||
|
|
||||||
birdseye._Birdseye__send_new_frame()
|
|
||||||
|
|
||||||
birdseye.input.put_nowait.assert_called_once()
|
|
||||||
|
|
||||||
def test_idle_heartbeat_waits_a_full_interval_between_sends(self):
|
|
||||||
birdseye = Birdseye.__new__(Birdseye)
|
|
||||||
birdseye.review_severity = {}
|
|
||||||
birdseye.birdseye_manager = Mock()
|
|
||||||
birdseye.birdseye_manager.update.return_value = (False, False)
|
|
||||||
birdseye.birdseye_manager.camera_layout = []
|
|
||||||
birdseye.birdseye_manager.last_output_time = 0.0
|
|
||||||
birdseye._idle_interval = 0.2
|
|
||||||
|
|
||||||
with (
|
|
||||||
patch.object(Birdseye, "_Birdseye__send_new_frame") as send,
|
|
||||||
patch("frigate.output.birdseye.time.monotonic", side_effect=[10.0, 10.1]),
|
|
||||||
):
|
|
||||||
birdseye.write_data("front", [], [], 1.0, Mock())
|
|
||||||
birdseye.write_data("front", [], [], 1.1, Mock())
|
|
||||||
|
|
||||||
assert send.call_count == 1
|
|
||||||
|
|
||||||
|
|
||||||
class TestBirdseyeReviewSeverity(unittest.TestCase):
|
class TestBirdseyeReviewSeverity(unittest.TestCase):
|
||||||
"""Test that review updates drive the per-camera severity map."""
|
"""Test that review updates drive the per-camera severity map."""
|
||||||
|
|
||||||
|
|||||||
@@ -264,41 +264,3 @@ class TestCameraFileCleanup(unittest.TestCase):
|
|||||||
]
|
]
|
||||||
|
|
||||||
self.assertEqual(remaining, other)
|
self.assertEqual(remaining, other)
|
||||||
|
|
||||||
def test_delete_removes_recordings_and_keeps_colliding_dirs(self):
|
|
||||||
own = [
|
|
||||||
"recordings/2026-11-22/10/front/00.00.mp4",
|
|
||||||
"recordings/2026-11-22/10/front@sub/00.00.mp4",
|
|
||||||
"recordings/2026-11-23/03/front/10.00.mp4",
|
|
||||||
"clips/thumbs/front/a.webp",
|
|
||||||
"clips/previews/front/1.mp4",
|
|
||||||
"clips/lpr/front/a/1.jpg",
|
|
||||||
"clips/triggers/front/t.webp",
|
|
||||||
]
|
|
||||||
other = [
|
|
||||||
"recordings/2026-11-22/10/front_door/00.00.mp4",
|
|
||||||
"recordings/front/keep.mp4",
|
|
||||||
"clips/front/dataset/a.jpg",
|
|
||||||
"clips/thumbs/front_door/b.webp",
|
|
||||||
]
|
|
||||||
|
|
||||||
with tempfile.TemporaryDirectory() as root:
|
|
||||||
for name in own + other:
|
|
||||||
path = os.path.join(root, name)
|
|
||||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
||||||
open(path, "w").close()
|
|
||||||
|
|
||||||
clips = os.path.join(root, "clips")
|
|
||||||
with patch.multiple(
|
|
||||||
camera_cleanup,
|
|
||||||
CLIPS_DIR=clips,
|
|
||||||
RECORD_DIR=os.path.join(root, "recordings"),
|
|
||||||
THUMB_DIR=os.path.join(clips, "thumbs"),
|
|
||||||
):
|
|
||||||
camera_cleanup.cleanup_camera_files("front")
|
|
||||||
|
|
||||||
remaining = [
|
|
||||||
n for n in own + other if os.path.exists(os.path.join(root, n))
|
|
||||||
]
|
|
||||||
|
|
||||||
self.assertEqual(remaining, other)
|
|
||||||
|
|||||||
@@ -1,14 +1,12 @@
|
|||||||
"""Tests for camera watch ownership in the chat tools."""
|
"""Tests for camera watch ownership in the chat tools."""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import threading
|
|
||||||
import unittest
|
import unittest
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
from unittest.mock import AsyncMock, MagicMock, patch
|
from unittest.mock import AsyncMock, MagicMock, patch
|
||||||
|
|
||||||
from frigate.api.chat import _execute_start_camera_watch, _execute_stop_camera_watch
|
from frigate.api.chat import _execute_start_camera_watch, _execute_stop_camera_watch
|
||||||
from frigate.jobs.vlm_watch import MAX_WATCH_MINUTES, VLMWatchJob, VLMWatchRunner
|
from frigate.jobs.vlm_watch import VLMWatchJob
|
||||||
from frigate.types import JobStatusTypesEnum
|
|
||||||
|
|
||||||
|
|
||||||
def _request(user: str, role: str) -> SimpleNamespace:
|
def _request(user: str, role: str) -> SimpleNamespace:
|
||||||
@@ -60,51 +58,6 @@ class TestStartCameraWatch(unittest.TestCase):
|
|||||||
|
|
||||||
self.assertEqual(start.call_args.kwargs["username"], "alice")
|
self.assertEqual(start.call_args.kwargs["username"], "alice")
|
||||||
|
|
||||||
@patch("frigate.api.chat.require_camera_access", new_callable=AsyncMock)
|
|
||||||
@patch("frigate.api.chat.start_vlm_watch_job", return_value="job1")
|
|
||||||
def test_rejects_non_string_labels_and_clamps_duration(self, start, _access):
|
|
||||||
request = _request("alice", "viewer")
|
|
||||||
request.app = MagicMock()
|
|
||||||
request.app.frigate_config.cameras = {"front": None}
|
|
||||||
request.app.genai_manager.chat_client.supports_vision = True
|
|
||||||
arguments = {"camera": "front", "condition": "person"}
|
|
||||||
|
|
||||||
result = asyncio.run(
|
|
||||||
_execute_start_camera_watch(request, {**arguments, "labels": [1]})
|
|
||||||
)
|
|
||||||
self.assertIn("error", result)
|
|
||||||
start.assert_not_called()
|
|
||||||
|
|
||||||
asyncio.run(
|
|
||||||
_execute_start_camera_watch(
|
|
||||||
request, {**arguments, "max_duration_minutes": 1e308}
|
|
||||||
)
|
|
||||||
)
|
|
||||||
self.assertEqual(
|
|
||||||
start.call_args.kwargs["max_duration_minutes"], MAX_WATCH_MINUTES
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class TestWatchRunnerSetup(unittest.TestCase):
|
|
||||||
@patch("frigate.jobs.vlm_watch.DetectionSubscriber")
|
|
||||||
@patch("frigate.jobs.vlm_watch.InterProcessRequestor")
|
|
||||||
def test_setup_error_fails_job_and_closes_sockets(self, requestor, subscriber):
|
|
||||||
job = VLMWatchJob(camera="front", condition="person", labels=[1])
|
|
||||||
runner = VLMWatchRunner(
|
|
||||||
job=job,
|
|
||||||
config=MagicMock(),
|
|
||||||
cancel_event=threading.Event(),
|
|
||||||
frame_processor=MagicMock(),
|
|
||||||
genai_manager=MagicMock(),
|
|
||||||
dispatcher=MagicMock(),
|
|
||||||
)
|
|
||||||
|
|
||||||
runner.run()
|
|
||||||
|
|
||||||
self.assertEqual(job.status, JobStatusTypesEnum.failed)
|
|
||||||
requestor.return_value.stop.assert_called_once()
|
|
||||||
subscriber.return_value.stop.assert_called_once()
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -22,7 +22,6 @@ from frigate.api.chat import (
|
|||||||
_execute_pending_tools,
|
_execute_pending_tools,
|
||||||
_pending_tool_calls_from_tail,
|
_pending_tool_calls_from_tail,
|
||||||
_tool_calls_awaiting_approval,
|
_tool_calls_awaiting_approval,
|
||||||
_with_server_ids,
|
|
||||||
)
|
)
|
||||||
from frigate.api.defs.request.chat_body import ChatCompletionRequest
|
from frigate.api.defs.request.chat_body import ChatCompletionRequest
|
||||||
from frigate.genai.prompts import (
|
from frigate.genai.prompts import (
|
||||||
@@ -153,22 +152,6 @@ class TestApprovalHelpers(unittest.TestCase):
|
|||||||
body = _body(tool_decisions={"c2": "approve", "c3": "reject"})
|
body = _body(tool_decisions={"c2": "approve", "c3": "reject"})
|
||||||
self.assertEqual(_tool_calls_awaiting_approval(pending, body, WRITE_TOOLS), [])
|
self.assertEqual(_tool_calls_awaiting_approval(pending, body, WRITE_TOOLS), [])
|
||||||
|
|
||||||
def test_repeated_provider_ids_get_unique_server_ids(self):
|
|
||||||
calls = [
|
|
||||||
{"id": "set_camera_state", "name": "set_camera_state", "arguments": {}},
|
|
||||||
{"id": "set_camera_state", "name": "set_camera_state", "arguments": {}},
|
|
||||||
]
|
|
||||||
renamed = _with_server_ids(calls)
|
|
||||||
self.assertEqual(len({tc["id"] for tc in renamed}), 2)
|
|
||||||
self.assertNotIn("set_camera_state", {tc["id"] for tc in renamed})
|
|
||||||
|
|
||||||
# A later call to the same tool is not covered by an earlier decision.
|
|
||||||
body = _body(tool_decisions={renamed[0]["id"]: "approve"})
|
|
||||||
later = _with_server_ids(calls[:1])
|
|
||||||
self.assertEqual(
|
|
||||||
len(_tool_calls_awaiting_approval(later, body, WRITE_TOOLS)), 1
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class TestExecutePendingTools(unittest.TestCase):
|
class TestExecutePendingTools(unittest.TestCase):
|
||||||
def test_rejected_call_is_not_executed(self):
|
def test_rejected_call_is_not_executed(self):
|
||||||
|
|||||||
@@ -7,10 +7,7 @@ from unittest.mock import patch
|
|||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
from frigate.util.classification import (
|
from frigate.util.classification import _extract_event_thumbnails
|
||||||
_extract_event_thumbnails,
|
|
||||||
_select_balanced_timestamps,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class TestExtractEventThumbnails(unittest.TestCase):
|
class TestExtractEventThumbnails(unittest.TestCase):
|
||||||
@@ -32,17 +29,5 @@ class TestExtractEventThumbnails(unittest.TestCase):
|
|||||||
self.assertEqual(load.call_count, 7)
|
self.assertEqual(load.call_count, 7)
|
||||||
|
|
||||||
|
|
||||||
class TestSelectBalancedTimestamps(unittest.TestCase):
|
|
||||||
def test_terminates_when_items_cannot_fill_target(self):
|
|
||||||
items = [
|
|
||||||
SimpleNamespace(camera="front", start_time=1000.0, end_time=1000.0),
|
|
||||||
SimpleNamespace(camera="front", start_time=2000.0, end_time=2001.0),
|
|
||||||
]
|
|
||||||
|
|
||||||
timestamps = _select_balanced_timestamps(items, target_count=100)
|
|
||||||
|
|
||||||
self.assertEqual(len(timestamps), 1)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import pickle
|
|
||||||
import tempfile
|
import tempfile
|
||||||
import unittest
|
import unittest
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import requests
|
import requests
|
||||||
@@ -15,7 +14,6 @@ from frigate.config import BirdseyeModeEnum, FrigateConfig, RetainModeEnum
|
|||||||
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.device import build_detector_config, runner_names
|
from frigate.detectors.device import build_detector_config, runner_names
|
||||||
from frigate.plus import PlusApi, PlusRateLimitError
|
|
||||||
from frigate.util.builtin import deep_merge
|
from frigate.util.builtin import deep_merge
|
||||||
from frigate.util.config import resolve_ffmpeg_path
|
from frigate.util.config import resolve_ffmpeg_path
|
||||||
|
|
||||||
@@ -1639,60 +1637,6 @@ class TestConfig(unittest.TestCase):
|
|||||||
with self.assertRaisesRegex(ValidationError, "Unable to connect to Frigate+"):
|
with self.assertRaisesRegex(ValidationError, "Unable to connect to Frigate+"):
|
||||||
FrigateConfig(**config)
|
FrigateConfig(**config)
|
||||||
|
|
||||||
def _plus_model_config(self, model_id: str) -> dict:
|
|
||||||
return {
|
|
||||||
"mqtt": {"host": "mqtt"},
|
|
||||||
"models": [{"path": f"plus://{model_id}", "devices": ["cpu"]}],
|
|
||||||
"cameras": {
|
|
||||||
"back": {
|
|
||||||
"ffmpeg": {
|
|
||||||
"inputs": [
|
|
||||||
{
|
|
||||||
"path": "rtsp://10.0.0.1:554/video",
|
|
||||||
"roles": ["detect"],
|
|
||||||
},
|
|
||||||
]
|
|
||||||
},
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
@patch("frigate.detectors.detector_config.requests.get")
|
|
||||||
@patch(
|
|
||||||
"frigate.plus.PlusApi.get_model_download_url",
|
|
||||||
return_value="https://download.invalid/model",
|
|
||||||
)
|
|
||||||
def test_plus_model_error_response_is_not_saved(self, _, download):
|
|
||||||
model_id = "error_response_model"
|
|
||||||
model_path = os.path.join(MODEL_CACHE_DIR, model_id)
|
|
||||||
download.return_value = MagicMock(ok=False, status_code=429, content=b"busy")
|
|
||||||
|
|
||||||
with self.assertRaisesRegex(ValidationError, r"HTTP 429"):
|
|
||||||
FrigateConfig(**self._plus_model_config(model_id))
|
|
||||||
|
|
||||||
self.assertFalse(os.path.exists(model_path))
|
|
||||||
|
|
||||||
def test_config_can_be_sent_to_a_worker_process(self):
|
|
||||||
# worker processes start from the forkserver, which pickles the config
|
|
||||||
# along with the Frigate+ client it holds
|
|
||||||
frigate_config = FrigateConfig(**self.minimal)
|
|
||||||
|
|
||||||
copy = pickle.loads(pickle.dumps(frigate_config))
|
|
||||||
|
|
||||||
self.assertIsInstance(copy.plus_api, PlusApi)
|
|
||||||
|
|
||||||
def test_plus_rate_limit_is_validation_error(self):
|
|
||||||
for retry_after, message in ((45, "Try again in 45 seconds"), (None, "later")):
|
|
||||||
with (
|
|
||||||
self.subTest(retry_after=retry_after),
|
|
||||||
patch(
|
|
||||||
"frigate.plus.PlusApi.get_model_download_url",
|
|
||||||
side_effect=PlusRateLimitError(retry_after),
|
|
||||||
),
|
|
||||||
self.assertRaisesRegex(ValidationError, f"rate limiting.*{message}"),
|
|
||||||
):
|
|
||||||
FrigateConfig(**self._plus_model_config("rate_limited_model"))
|
|
||||||
|
|
||||||
def test_fails_on_invalid_role(self):
|
def test_fails_on_invalid_role(self):
|
||||||
config = {
|
config = {
|
||||||
"mqtt": {"host": "mqtt"},
|
"mqtt": {"host": "mqtt"},
|
||||||
|
|||||||
@@ -24,7 +24,6 @@ class TestSwapRuntimeConfig(unittest.TestCase):
|
|||||||
|
|
||||||
self.assertIs(app.frigate_config, config)
|
self.assertIs(app.frigate_config, config)
|
||||||
app.genai_manager.update_config.assert_called_once_with(config)
|
app.genai_manager.update_config.assert_called_once_with(config)
|
||||||
app.replay_manager.update_config.assert_called_once_with(config)
|
|
||||||
app.profile_manager.update_config.assert_called_once_with(config)
|
app.profile_manager.update_config.assert_called_once_with(config)
|
||||||
self.assertIs(app.stats_emitter.config, config)
|
self.assertIs(app.stats_emitter.config, config)
|
||||||
app.stats_emitter.hardware_stats.set_config.assert_called_once_with(config)
|
app.stats_emitter.hardware_stats.set_config.assert_called_once_with(config)
|
||||||
|
|||||||
@@ -101,7 +101,6 @@ class TestDebugReplayManagerStop(unittest.TestCase):
|
|||||||
manager.mark_session_ready("/tmp/replay/_replay_front.mp4")
|
manager.mark_session_ready("/tmp/replay/_replay_front.mp4")
|
||||||
|
|
||||||
camera_config = MagicMock()
|
camera_config = MagicMock()
|
||||||
manager._published_camera = camera_config
|
|
||||||
frigate_config = MagicMock()
|
frigate_config = MagicMock()
|
||||||
frigate_config.cameras = {"_replay_front": camera_config}
|
frigate_config.cameras = {"_replay_front": camera_config}
|
||||||
publisher = MagicMock()
|
publisher = MagicMock()
|
||||||
@@ -170,7 +169,6 @@ class TestDebugReplayManagerPublishCamera(unittest.TestCase):
|
|||||||
from frigate.debug_replay import DebugReplayManager
|
from frigate.debug_replay import DebugReplayManager
|
||||||
|
|
||||||
manager = DebugReplayManager()
|
manager = DebugReplayManager()
|
||||||
manager.mark_starting("front", "_replay_front", 100.0, 200.0)
|
|
||||||
|
|
||||||
source_config = MagicMock()
|
source_config = MagicMock()
|
||||||
new_camera_config = MagicMock()
|
new_camera_config = MagicMock()
|
||||||
@@ -248,103 +246,5 @@ class TestDebugReplayManagerPublishCamera(unittest.TestCase):
|
|||||||
publisher.publish_update.assert_not_called()
|
publisher.publish_update.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
class TestDebugReplayManagerLifecycle(unittest.TestCase):
|
|
||||||
def setUp(self) -> None:
|
|
||||||
patcher = patch("frigate.debug_replay.JobStatePublisher")
|
|
||||||
patcher.start()
|
|
||||||
self.addCleanup(patcher.stop)
|
|
||||||
|
|
||||||
def _publish(self, manager, frigate_config, publisher) -> bool:
|
|
||||||
from frigate.debug_replay import DebugReplayManager
|
|
||||||
|
|
||||||
parsed = MagicMock()
|
|
||||||
parsed.cameras = {"_replay_front": MagicMock(name="replay_camera")}
|
|
||||||
|
|
||||||
with (
|
|
||||||
patch.object(
|
|
||||||
DebugReplayManager,
|
|
||||||
"_build_camera_config_dict",
|
|
||||||
return_value={"enabled": True},
|
|
||||||
),
|
|
||||||
patch("frigate.debug_replay.find_config_file", return_value="/cfg.yml"),
|
|
||||||
patch("frigate.debug_replay.YAML") as yaml_cls,
|
|
||||||
patch(
|
|
||||||
"frigate.debug_replay.FrigateConfig.parse_object",
|
|
||||||
return_value=parsed,
|
|
||||||
),
|
|
||||||
patch("builtins.open", unittest.mock.mock_open(read_data="cameras:\n")),
|
|
||||||
):
|
|
||||||
yaml_cls.return_value.load.return_value = {"cameras": {}}
|
|
||||||
return manager.publish_camera(
|
|
||||||
source_camera="front",
|
|
||||||
replay_name="_replay_front",
|
|
||||||
clip_path="/tmp/clip.mp4",
|
|
||||||
frigate_config=frigate_config,
|
|
||||||
config_publisher=publisher,
|
|
||||||
)
|
|
||||||
|
|
||||||
def _config(self, name: str) -> MagicMock:
|
|
||||||
config = MagicMock(name=name)
|
|
||||||
config.cameras = {"front": MagicMock()}
|
|
||||||
return config
|
|
||||||
|
|
||||||
def _stop(self, manager, frigate_config, publisher) -> None:
|
|
||||||
with (
|
|
||||||
patch.object(manager, "_cleanup_db"),
|
|
||||||
patch.object(manager, "_cleanup_files"),
|
|
||||||
patch("frigate.debug_replay.cancel_debug_replay_job", return_value=False),
|
|
||||||
):
|
|
||||||
manager.stop(frigate_config=frigate_config, config_publisher=publisher)
|
|
||||||
|
|
||||||
def test_publish_after_stop_is_skipped(self) -> None:
|
|
||||||
from frigate.debug_replay import DebugReplayManager
|
|
||||||
|
|
||||||
manager = DebugReplayManager()
|
|
||||||
manager.mark_starting("front", "_replay_front", 100.0, 200.0)
|
|
||||||
config = self._config("live")
|
|
||||||
publisher = MagicMock()
|
|
||||||
|
|
||||||
self._stop(manager, config, publisher)
|
|
||||||
|
|
||||||
self.assertFalse(self._publish(manager, config, publisher))
|
|
||||||
self.assertNotIn("_replay_front", config.cameras)
|
|
||||||
publisher.publish_update.assert_not_called()
|
|
||||||
|
|
||||||
def test_config_swap_keeps_replay_camera_and_stop_removes_it(self) -> None:
|
|
||||||
from frigate.config.camera.updater import CameraConfigUpdateEnum
|
|
||||||
from frigate.debug_replay import DebugReplayManager
|
|
||||||
|
|
||||||
manager = DebugReplayManager()
|
|
||||||
manager.mark_starting("front", "_replay_front", 100.0, 200.0)
|
|
||||||
boot = self._config("boot")
|
|
||||||
publisher = MagicMock()
|
|
||||||
self.assertTrue(self._publish(manager, boot, publisher))
|
|
||||||
|
|
||||||
swapped = self._config("swapped")
|
|
||||||
manager.update_config(swapped)
|
|
||||||
self.assertIn("_replay_front", swapped.cameras)
|
|
||||||
|
|
||||||
self._stop(manager, swapped, publisher)
|
|
||||||
|
|
||||||
topic = publisher.publish_update.call_args.args[0]
|
|
||||||
self.assertEqual(topic.update_type, CameraConfigUpdateEnum.remove)
|
|
||||||
self.assertNotIn("_replay_front", swapped.cameras)
|
|
||||||
|
|
||||||
def test_stop_with_stale_config_still_publishes_remove(self) -> None:
|
|
||||||
from frigate.config.camera.updater import CameraConfigUpdateEnum
|
|
||||||
from frigate.debug_replay import DebugReplayManager
|
|
||||||
|
|
||||||
manager = DebugReplayManager()
|
|
||||||
manager.mark_starting("front", "_replay_front", 100.0, 200.0)
|
|
||||||
live = self._config("live")
|
|
||||||
publisher = MagicMock()
|
|
||||||
self.assertTrue(self._publish(manager, live, publisher))
|
|
||||||
|
|
||||||
self._stop(manager, self._config("stale"), publisher)
|
|
||||||
|
|
||||||
topic = publisher.publish_update.call_args.args[0]
|
|
||||||
self.assertEqual(topic.update_type, CameraConfigUpdateEnum.remove)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -302,7 +302,7 @@ class TestRunnerHappyPath(unittest.TestCase):
|
|||||||
patch.object(
|
patch.object(
|
||||||
self.manager,
|
self.manager,
|
||||||
"publish_camera",
|
"publish_camera",
|
||||||
side_effect=lambda *a, **kw: captured.append("published") or True,
|
side_effect=lambda *a, **kw: captured.append("published"),
|
||||||
),
|
),
|
||||||
patch("os.path.exists", return_value=True),
|
patch("os.path.exists", return_value=True),
|
||||||
patch("os.makedirs"),
|
patch("os.makedirs"),
|
||||||
|
|||||||
@@ -518,47 +518,11 @@ class TestSecretsReload(unittest.TestCase):
|
|||||||
"""
|
"""
|
||||||
env.apply_config_env_vars({"FRIGATE_MQTT_HOST": "from_config"})
|
env.apply_config_env_vars({"FRIGATE_MQTT_HOST": "from_config"})
|
||||||
config = FrigateConfig.parse_yaml(
|
config = FrigateConfig.parse_yaml(
|
||||||
"environment_vars:\n FRIGATE_MQTT_HOST: from_config\n"
|
|
||||||
'mqtt:\n host: "{FRIGATE_MQTT_HOST}"\ncameras: {}\n'
|
'mqtt:\n host: "{FRIGATE_MQTT_HOST}"\ncameras: {}\n'
|
||||||
)
|
)
|
||||||
self.assertEqual(config.mqtt.host, "from_config")
|
self.assertEqual(config.mqtt.host, "from_config")
|
||||||
self.assertEqual(env._CONFIG_ENV_VARS["FRIGATE_MQTT_HOST"], "from_config")
|
self.assertEqual(env._CONFIG_ENV_VARS["FRIGATE_MQTT_HOST"], "from_config")
|
||||||
|
|
||||||
def test_candidate_env_var_resolves_before_install(self):
|
|
||||||
"""A non-install parse resolves against the candidate's own block, so
|
|
||||||
an entry can be added and referenced in the same save."""
|
|
||||||
env.apply_config_env_vars({"FRIGATE_MQTT_HOST": "running"})
|
|
||||||
config = FrigateConfig.parse_yaml(
|
|
||||||
"environment_vars:\n FRIGATE_MQTT_HOST: candidate\n"
|
|
||||||
" FRIGATE_MQTT_USER: added\n"
|
|
||||||
'mqtt:\n host: "{FRIGATE_MQTT_HOST}"\n'
|
|
||||||
' user: "{FRIGATE_MQTT_USER}"\n password: secret\ncameras: {}\n'
|
|
||||||
)
|
|
||||||
self.assertEqual(config.mqtt.host, "candidate")
|
|
||||||
self.assertEqual(config.mqtt.user, "added")
|
|
||||||
self.assertEqual(env._CONFIG_ENV_VARS, {"FRIGATE_MQTT_HOST": "running"})
|
|
||||||
self.assertNotIn("FRIGATE_MQTT_USER", os.environ)
|
|
||||||
|
|
||||||
def test_removed_candidate_env_var_fails_validation(self):
|
|
||||||
"""Removing an entry that is still referenced fails now, not at the
|
|
||||||
next start."""
|
|
||||||
env.apply_config_env_vars({"FRIGATE_MQTT_HOST": "running"})
|
|
||||||
with self.assertRaises(ValidationError):
|
|
||||||
FrigateConfig.parse_yaml(
|
|
||||||
'mqtt:\n host: "{FRIGATE_MQTT_HOST}"\ncameras: {}\n'
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_candidate_env_var_keeps_lowest_precedence(self):
|
|
||||||
"""secrets.yaml still outranks the candidate's block."""
|
|
||||||
with open(os.path.join(self._dir.name, "secrets.yaml"), "w") as f:
|
|
||||||
f.write("FRIGATE_MQTT_HOST: from_secrets\n")
|
|
||||||
|
|
||||||
config = FrigateConfig.parse_yaml(
|
|
||||||
"environment_vars:\n FRIGATE_MQTT_HOST: candidate\n"
|
|
||||||
'mqtt:\n host: "{FRIGATE_MQTT_HOST}"\ncameras: {}\n'
|
|
||||||
)
|
|
||||||
self.assertEqual(config.mqtt.host, "from_secrets")
|
|
||||||
|
|
||||||
|
|
||||||
class TestSourceRobustness(unittest.TestCase):
|
class TestSourceRobustness(unittest.TestCase):
|
||||||
"""Reload behavior, bad input, and the os.environ export."""
|
"""Reload behavior, bad input, and the os.environ export."""
|
||||||
|
|||||||
@@ -1,141 +0,0 @@
|
|||||||
"""Tests for the event cleanup cycle and runtime camera changes."""
|
|
||||||
|
|
||||||
import datetime
|
|
||||||
import unittest
|
|
||||||
from unittest.mock import MagicMock, patch
|
|
||||||
|
|
||||||
from peewee import SqliteDatabase
|
|
||||||
|
|
||||||
from frigate.config import FrigateConfig
|
|
||||||
from frigate.events.cleanup import EventCleanup
|
|
||||||
from frigate.models import Event, Timeline
|
|
||||||
from frigate.util.file import delete_event_thumbnail
|
|
||||||
|
|
||||||
|
|
||||||
def _camera(path: str, record_days: int) -> dict:
|
|
||||||
return {
|
|
||||||
"ffmpeg": {"inputs": [{"path": path, "roles": ["detect", "record"]}]},
|
|
||||||
"record": {
|
|
||||||
"enabled": True,
|
|
||||||
"alerts": {"retain": {"days": record_days}},
|
|
||||||
"detections": {"retain": {"days": record_days}},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class TestEventCleanup(unittest.TestCase):
|
|
||||||
def setUp(self):
|
|
||||||
self.db = SqliteDatabase(":memory:")
|
|
||||||
models = [Event, Timeline]
|
|
||||||
self.db.bind(models)
|
|
||||||
self.db.create_tables(models)
|
|
||||||
|
|
||||||
config = FrigateConfig(
|
|
||||||
**{
|
|
||||||
"mqtt": {"host": "mqtt"},
|
|
||||||
"record": {
|
|
||||||
"alerts": {"retain": {"days": 10}},
|
|
||||||
"detections": {"retain": {"days": 10}},
|
|
||||||
},
|
|
||||||
"cameras": {"front_door": _camera("rtsp://10.0.0.1:554/video", 10)},
|
|
||||||
}
|
|
||||||
)
|
|
||||||
self.config = config
|
|
||||||
self.cleanup = EventCleanup(config, MagicMock(), MagicMock())
|
|
||||||
|
|
||||||
def tearDown(self):
|
|
||||||
self.db.close()
|
|
||||||
|
|
||||||
def _insert_event(
|
|
||||||
self, id: str, camera: str, age_days: float, has_clip: bool = True
|
|
||||||
) -> None:
|
|
||||||
end_time = (
|
|
||||||
datetime.datetime.now() - datetime.timedelta(days=age_days)
|
|
||||||
).timestamp()
|
|
||||||
Event.create(
|
|
||||||
id=id,
|
|
||||||
label="person",
|
|
||||||
camera=camera,
|
|
||||||
start_time=end_time - 10,
|
|
||||||
end_time=end_time,
|
|
||||||
top_score=0.9,
|
|
||||||
score=0.9,
|
|
||||||
false_positive=False,
|
|
||||||
zones=[],
|
|
||||||
thumbnail="",
|
|
||||||
has_clip=has_clip,
|
|
||||||
has_snapshot=True,
|
|
||||||
region=[],
|
|
||||||
box=[],
|
|
||||||
area=0,
|
|
||||||
retain_indefinitely=False,
|
|
||||||
plus_id="",
|
|
||||||
model_hash="",
|
|
||||||
detector_type="cpu",
|
|
||||||
model_type="ssd",
|
|
||||||
data={"max_severity": "alert"},
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_runtime_added_camera_keeps_its_own_retention(self):
|
|
||||||
added = FrigateConfig(
|
|
||||||
**{
|
|
||||||
"mqtt": {"host": "mqtt"},
|
|
||||||
"cameras": {"garage": _camera("rtsp://10.0.0.2:554/video", 30)},
|
|
||||||
}
|
|
||||||
).cameras["garage"]
|
|
||||||
self.config.cameras["garage"] = added
|
|
||||||
self._insert_event("garage-event", "garage", age_days=20)
|
|
||||||
|
|
||||||
self.cleanup.expire_events()
|
|
||||||
|
|
||||||
assert Event.get(Event.id == "garage-event").has_clip is True
|
|
||||||
|
|
||||||
def test_runtime_removed_camera_gets_global_retention(self):
|
|
||||||
self._insert_event("front-event", "front_door", age_days=20)
|
|
||||||
self.cleanup.camera_keys = ["front_door"]
|
|
||||||
self.cleanup.removed_camera_labels = []
|
|
||||||
del self.config.cameras["front_door"]
|
|
||||||
|
|
||||||
self.cleanup.expire_events()
|
|
||||||
|
|
||||||
# clip and snapshot both expire under the global retention
|
|
||||||
assert self.cleanup.camera_keys == []
|
|
||||||
assert not Event.select().where(Event.id == "front-event").exists()
|
|
||||||
|
|
||||||
def test_expired_clips_are_only_selected_once(self):
|
|
||||||
self._insert_event("pending", "front_door", age_days=20)
|
|
||||||
self._insert_event("expired", "front_door", age_days=20, has_clip=False)
|
|
||||||
self._insert_event("removed-pending", "removed", age_days=20)
|
|
||||||
self._insert_event("removed-expired", "removed", age_days=20, has_clip=False)
|
|
||||||
|
|
||||||
assert self.cleanup.expire_clips() == ["pending"]
|
|
||||||
assert not Event.select().where(Event.has_clip == True).exists()
|
|
||||||
|
|
||||||
with patch.object(Event, "update", wraps=Event.update) as update:
|
|
||||||
assert self.cleanup.expire_clips() == []
|
|
||||||
|
|
||||||
update.assert_not_called()
|
|
||||||
|
|
||||||
def test_cycle_failure_does_not_stop_the_thread(self):
|
|
||||||
self.cleanup.stop_event.wait.side_effect = [False, False, True]
|
|
||||||
|
|
||||||
with patch.object(
|
|
||||||
self.cleanup, "expire_events", side_effect=[RuntimeError, None]
|
|
||||||
) as expire_events:
|
|
||||||
self.cleanup.run()
|
|
||||||
|
|
||||||
assert expire_events.call_count == 2
|
|
||||||
|
|
||||||
def test_thumbnail_unlink_error_is_reported(self):
|
|
||||||
event = MagicMock(thumbnail="", camera="front_door", id="e1")
|
|
||||||
|
|
||||||
with patch(
|
|
||||||
"frigate.util.file.Path.unlink", side_effect=PermissionError
|
|
||||||
) as unlink:
|
|
||||||
assert delete_event_thumbnail(event) is False
|
|
||||||
|
|
||||||
unlink.assert_called_once()
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
"""When tracked object updates are written to the database."""
|
|
||||||
|
|
||||||
import unittest
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
from frigate.events.maintainer import should_update_db
|
|
||||||
|
|
||||||
|
|
||||||
def _event(**overrides: Any) -> dict[str, Any]:
|
|
||||||
return {
|
|
||||||
"end_time": None,
|
|
||||||
"has_clip": False,
|
|
||||||
"has_snapshot": True,
|
|
||||||
"top_score": 0.8,
|
|
||||||
"entered_zones": ["porch"],
|
|
||||||
"average_estimated_speed": 0,
|
|
||||||
"velocity_angle": 0,
|
|
||||||
"recognized_license_plate": None,
|
|
||||||
"path_data": [],
|
|
||||||
"max_severity": None,
|
|
||||||
**overrides,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class TestShouldUpdateDb(unittest.TestCase):
|
|
||||||
def test_unchanged_saved_event_is_not_updated(self):
|
|
||||||
self.assertFalse(should_update_db(_event(), _event()))
|
|
||||||
|
|
||||||
def test_max_severity_change_updates_saved_event(self):
|
|
||||||
self.assertTrue(should_update_db(_event(), _event(max_severity="alert")))
|
|
||||||
|
|
||||||
def test_max_severity_change_ignored_when_not_saved(self):
|
|
||||||
self.assertFalse(
|
|
||||||
should_update_db(
|
|
||||||
_event(has_snapshot=False),
|
|
||||||
_event(has_snapshot=False, max_severity="alert"),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
@@ -143,37 +143,6 @@ class TestValidateFfmpegArgs(unittest.TestCase):
|
|||||||
self.assertRejected("-metadata comment=x")
|
self.assertRejected("-metadata comment=x")
|
||||||
|
|
||||||
|
|
||||||
class TestCustomArgsTokenization(unittest.TestCase):
|
|
||||||
"""The built command must contain exactly the tokens the validator checked."""
|
|
||||||
|
|
||||||
def test_irregular_whitespace_does_not_shift_tokens(self) -> None:
|
|
||||||
output_args = "-c:v libx264\t-crf 23\n -r 25 "
|
|
||||||
self.assertTrue(validate_ffmpeg_args(output_args)[0])
|
|
||||||
|
|
||||||
with patch("frigate.record.export.Path.mkdir"):
|
|
||||||
exporter = RecordingExporter(
|
|
||||||
MagicMock(),
|
|
||||||
"front_abc123",
|
|
||||||
"front",
|
|
||||||
None,
|
|
||||||
None,
|
|
||||||
1_000,
|
|
||||||
2_000,
|
|
||||||
PlaybackSourceEnum.recordings,
|
|
||||||
ffmpeg_input_args=" -an ",
|
|
||||||
ffmpeg_output_args=output_args,
|
|
||||||
)
|
|
||||||
exporter.config.ffmpeg.ffmpeg_path = "ffmpeg"
|
|
||||||
exporter.staged_runs = ["/cache/stage_0.mp4"]
|
|
||||||
|
|
||||||
cmd, _ = exporter.get_record_export_command("/exports/out.mp4")
|
|
||||||
|
|
||||||
for token in cmd[: cmd.index("-metadata")]:
|
|
||||||
self.assertNotEqual(token, "")
|
|
||||||
self.assertEqual(token.split(), [token])
|
|
||||||
self.assertIn("-c:v libx264 -crf 23 -r 25", " ".join(cmd))
|
|
||||||
|
|
||||||
|
|
||||||
class TestExportVideoPath(unittest.TestCase):
|
class TestExportVideoPath(unittest.TestCase):
|
||||||
"""Tests for the file path an export takes once the user names it."""
|
"""Tests for the file path an export takes once the user names it."""
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
"""Tests for export progress tracking, broadcast, and FFmpeg parsing."""
|
"""Tests for export progress tracking, broadcast, and FFmpeg parsing."""
|
||||||
|
|
||||||
import datetime
|
|
||||||
import io
|
import io
|
||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
@@ -8,14 +7,11 @@ import tempfile
|
|||||||
import unittest
|
import unittest
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
from peewee import SqliteDatabase
|
|
||||||
|
|
||||||
from frigate.jobs.export import (
|
from frigate.jobs.export import (
|
||||||
PROGRESS_BROADCAST_MIN_INTERVAL,
|
PROGRESS_BROADCAST_MIN_INTERVAL,
|
||||||
ExportJob,
|
ExportJob,
|
||||||
ExportJobManager,
|
ExportJobManager,
|
||||||
)
|
)
|
||||||
from frigate.models import Previews
|
|
||||||
from frigate.record.export import (
|
from frigate.record.export import (
|
||||||
ExportStreamEnum,
|
ExportStreamEnum,
|
||||||
PlaybackSourceEnum,
|
PlaybackSourceEnum,
|
||||||
@@ -225,24 +221,6 @@ class TestFfmpegProgressParsing(unittest.TestCase):
|
|||||||
assert any(abs(p - (30 / 90 * 100)) < 0.01 for p in encoding_percents)
|
assert any(abs(p - (30 / 90 * 100)) < 0.01 for p in encoding_percents)
|
||||||
|
|
||||||
|
|
||||||
class TestExportJobManagerConfig(unittest.TestCase):
|
|
||||||
def test_manager_follows_the_config_passed_by_callers(self) -> None:
|
|
||||||
import frigate.jobs.export as export_jobs
|
|
||||||
|
|
||||||
boot = MagicMock(name="boot")
|
|
||||||
swapped = MagicMock(name="swapped")
|
|
||||||
|
|
||||||
with (
|
|
||||||
patch.object(export_jobs, "_job_manager", None),
|
|
||||||
patch.object(export_jobs.ExportJobManager, "ensure_started"),
|
|
||||||
patch.object(export_jobs, "_get_max_concurrent", return_value=1),
|
|
||||||
):
|
|
||||||
export_jobs.get_export_job_manager(boot)
|
|
||||||
manager = export_jobs.get_export_job_manager(swapped)
|
|
||||||
|
|
||||||
self.assertIs(manager.config, swapped)
|
|
||||||
|
|
||||||
|
|
||||||
class TestBroadcastAggregation(unittest.TestCase):
|
class TestBroadcastAggregation(unittest.TestCase):
|
||||||
"""Verify ExportJobManager broadcast payload shape and throttling."""
|
"""Verify ExportJobManager broadcast payload shape and throttling."""
|
||||||
|
|
||||||
@@ -579,38 +557,5 @@ class TestChapterMetadataInProgressReview(unittest.TestCase):
|
|||||||
assert "title=Alert: person" in content
|
assert "title=Alert: person" in content
|
||||||
|
|
||||||
|
|
||||||
class TestPreviewExportCommandCameraMatch(unittest.TestCase):
|
|
||||||
def setUp(self) -> None:
|
|
||||||
self.cache_dir = tempfile.mkdtemp(prefix="frigate_preview_export_test_")
|
|
||||||
self.addCleanup(shutil.rmtree, self.cache_dir, ignore_errors=True)
|
|
||||||
self.preview_dir = os.path.join(self.cache_dir, "preview_frames")
|
|
||||||
os.makedirs(self.preview_dir)
|
|
||||||
|
|
||||||
def _write_frame(self, camera: str, frame_time: float) -> str:
|
|
||||||
path = os.path.join(self.preview_dir, f"preview_{camera}-{frame_time}.webp")
|
|
||||||
with open(path, "wb") as f:
|
|
||||||
f.write(b"fake-webp-bytes")
|
|
||||||
return path
|
|
||||||
|
|
||||||
def test_current_hour_playlist_excludes_sibling_camera(self) -> None:
|
|
||||||
exporter = _make_exporter()
|
|
||||||
exporter.playback_source = PlaybackSourceEnum.preview
|
|
||||||
exporter.start_time = datetime.datetime.now(datetime.UTC).timestamp()
|
|
||||||
exporter.end_time = 9_999_999_999
|
|
||||||
own = self._write_frame(exporter.camera, exporter.start_time + 1)
|
|
||||||
self._write_frame(f"{exporter.camera}-2", exporter.start_time + 1)
|
|
||||||
|
|
||||||
db = SqliteDatabase(":memory:")
|
|
||||||
with (
|
|
||||||
patch("frigate.record.export.CACHE_DIR", self.cache_dir),
|
|
||||||
db.bind_ctx([Previews]),
|
|
||||||
):
|
|
||||||
Previews.create_table()
|
|
||||||
_, playlist_lines = exporter.get_preview_export_command("out.mp4")
|
|
||||||
|
|
||||||
files = {line for line in playlist_lines if line.startswith("file ")}
|
|
||||||
assert files == {f"file '{own}'"}
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -7,47 +7,11 @@ from frigate.genai.prompts import (
|
|||||||
REVIEW_DESCRIPTION_FIELD_GUIDELINES,
|
REVIEW_DESCRIPTION_FIELD_GUIDELINES,
|
||||||
REVIEW_RESPONSE_STYLES,
|
REVIEW_RESPONSE_STYLES,
|
||||||
build_review_description_prompt,
|
build_review_description_prompt,
|
||||||
build_review_description_response_format,
|
|
||||||
build_review_summary_prompt,
|
build_review_summary_prompt,
|
||||||
get_review_field_guidelines,
|
get_review_field_guidelines,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class TestReviewDescriptionResponseFormat(unittest.TestCase):
|
|
||||||
def _schema(self, concerns: list[str]) -> dict:
|
|
||||||
response_format = build_review_description_response_format(concerns)
|
|
||||||
self.assertTrue(response_format["json_schema"]["strict"])
|
|
||||||
return response_format["json_schema"]["schema"]
|
|
||||||
|
|
||||||
def test_every_property_is_required_for_strict_mode(self):
|
|
||||||
for concerns in ([], ["a person loitering near the gate"]):
|
|
||||||
with self.subTest(concerns=concerns):
|
|
||||||
schema = self._schema(concerns)
|
|
||||||
self.assertEqual(set(schema["properties"]), set(schema["required"]))
|
|
||||||
|
|
||||||
def test_time_is_never_requested(self):
|
|
||||||
schema = self._schema(["a person loitering near the gate"])
|
|
||||||
self.assertNotIn("time", schema["properties"])
|
|
||||||
self.assertNotIn("time", schema["required"])
|
|
||||||
|
|
||||||
def test_concerns_omitted_when_not_configured(self):
|
|
||||||
schema = self._schema([])
|
|
||||||
self.assertNotIn("other_concerns", schema["properties"])
|
|
||||||
self.assertNotIn("other_concerns", schema["required"])
|
|
||||||
|
|
||||||
def test_concerns_requested_as_plain_list_when_configured(self):
|
|
||||||
schema = self._schema(["a person loitering near the gate"])
|
|
||||||
concerns = schema["properties"]["other_concerns"]
|
|
||||||
self.assertEqual(concerns["type"], "array")
|
|
||||||
self.assertEqual(concerns["items"], {"type": "string"})
|
|
||||||
self.assertNotIn("anyOf", concerns)
|
|
||||||
self.assertNotIn("default", concerns)
|
|
||||||
|
|
||||||
def test_schema_is_not_shared_between_calls(self):
|
|
||||||
self._schema(["a person loitering near the gate"])
|
|
||||||
self.assertNotIn("other_concerns", self._schema([])["properties"])
|
|
||||||
|
|
||||||
|
|
||||||
class TestReviewResponseStyle(unittest.TestCase):
|
class TestReviewResponseStyle(unittest.TestCase):
|
||||||
def _build_prompt(self, response_style: str = "default") -> str:
|
def _build_prompt(self, response_style: str = "default") -> str:
|
||||||
review_data = {
|
review_data = {
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ import unittest
|
|||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
from unittest.mock import AsyncMock, MagicMock, patch
|
from unittest.mock import AsyncMock, MagicMock, patch
|
||||||
|
|
||||||
import httpx
|
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
from frigate.config import GenAIConfig, GenAIProviderEnum
|
from frigate.config import GenAIConfig, GenAIProviderEnum
|
||||||
@@ -501,42 +500,6 @@ class TestGeminiProvider(unittest.TestCase):
|
|||||||
final = _final_message(_collect(client, MULTIMODAL_MESSAGES))
|
final = _final_message(_collect(client, MULTIMODAL_MESSAGES))
|
||||||
self.assertEqual(final["content"], "ok")
|
self.assertEqual(final["content"], "ok")
|
||||||
|
|
||||||
def test_tool_response_name_resolves_from_call_id(self):
|
|
||||||
from google.genai.types import FinishReason
|
|
||||||
|
|
||||||
client = self._client()
|
|
||||||
self._patch_stream(
|
|
||||||
client,
|
|
||||||
[
|
|
||||||
_gemini_chunk(
|
|
||||||
parts=[_gemini_part(text="ok")], finish_reason=FinishReason.STOP
|
|
||||||
)
|
|
||||||
],
|
|
||||||
)
|
|
||||||
messages = [
|
|
||||||
{"role": "user", "content": "turn off recordings"},
|
|
||||||
{
|
|
||||||
"role": "assistant",
|
|
||||||
"content": None,
|
|
||||||
"tool_calls": [
|
|
||||||
{
|
|
||||||
"id": "call_abc",
|
|
||||||
"type": "function",
|
|
||||||
"function": {"name": "set_camera_state", "arguments": "{}"},
|
|
||||||
}
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{"role": "tool", "tool_call_id": "call_abc", "content": "{}"},
|
|
||||||
]
|
|
||||||
_collect(client, messages)
|
|
||||||
|
|
||||||
contents = client.provider.aio.models.generate_content_stream.call_args.kwargs[
|
|
||||||
"contents"
|
|
||||||
]
|
|
||||||
self.assertEqual(
|
|
||||||
contents[-1].parts[0].function_response.name, "set_camera_state"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class TestGeminiImageTokens(unittest.TestCase):
|
class TestGeminiImageTokens(unittest.TestCase):
|
||||||
def _client(self, count_tokens):
|
def _client(self, count_tokens):
|
||||||
@@ -858,13 +821,6 @@ class TestOllamaProvider(unittest.TestCase):
|
|||||||
|
|
||||||
self.assertEqual(client.embed(images=[self._webp_bytes()]), [])
|
self.assertEqual(client.embed(images=[self._webp_bytes()]), [])
|
||||||
|
|
||||||
def test_embed_transport_error_returns_empty(self):
|
|
||||||
client = self._client()
|
|
||||||
client.provider = MagicMock()
|
|
||||||
client.provider._request_raw.side_effect = httpx.ReadError("reset")
|
|
||||||
|
|
||||||
self.assertEqual(client.embed(texts=["a person"]), [])
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# llama.cpp
|
# llama.cpp
|
||||||
@@ -1019,23 +975,6 @@ class TestLlamaCppProvider(unittest.TestCase):
|
|||||||
client = self._validated_client(4096, {"context_size": 32768})
|
client = self._validated_client(4096, {"context_size": 32768})
|
||||||
self.assertEqual(client.get_context_size(), 32768)
|
self.assertEqual(client.get_context_size(), 32768)
|
||||||
|
|
||||||
def test_base_url_strips_only_trailing_v1(self):
|
|
||||||
client = _make_client(
|
|
||||||
"llamacpp", model="m", base_url="http://v1-gpu.lan:8080/v1/"
|
|
||||||
)
|
|
||||||
self.assertEqual(client.provider, "http://v1-gpu.lan:8080")
|
|
||||||
|
|
||||||
def test_models_url_strips_v1_when_init_failed(self):
|
|
||||||
client = self._client()
|
|
||||||
client.provider = None
|
|
||||||
client.genai_config.base_url = "http://host:8080/v1"
|
|
||||||
|
|
||||||
with patch.object(client, "_get") as get:
|
|
||||||
get.return_value.json.return_value = {"data": []}
|
|
||||||
client._fetch_models_data()
|
|
||||||
|
|
||||||
self.assertEqual(get.call_args.args[0], "http://host:8080/v1/models")
|
|
||||||
|
|
||||||
def test_list_models_dedupes_alias_matching_id(self):
|
def test_list_models_dedupes_alias_matching_id(self):
|
||||||
client = self._client()
|
client = self._client()
|
||||||
models_data = [
|
models_data = [
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ from frigate.api.media_auth import (
|
|||||||
resolve_media_uri,
|
resolve_media_uri,
|
||||||
)
|
)
|
||||||
from frigate.config import FrigateConfig
|
from frigate.config import FrigateConfig
|
||||||
from frigate.const import CLIPS_DIR, EXPORT_DIR
|
from frigate.const import EXPORT_DIR
|
||||||
from frigate.models import Event, Export, Recordings, ReviewSegment
|
from frigate.models import Event, Export, Recordings, ReviewSegment
|
||||||
from frigate.test.const import TEST_DB, TEST_DB_CLEANUPS, TEST_DB_PRAGMAS
|
from frigate.test.const import TEST_DB, TEST_DB_CLEANUPS, TEST_DB_PRAGMAS
|
||||||
|
|
||||||
@@ -247,7 +247,7 @@ class TestExportResolution(unittest.TestCase):
|
|||||||
name=f"export-{export_id}",
|
name=f"export-{export_id}",
|
||||||
date=int(datetime.datetime.now().timestamp()),
|
date=int(datetime.datetime.now().timestamp()),
|
||||||
video_path=os.path.join(EXPORT_DIR, filename),
|
video_path=os.path.join(EXPORT_DIR, filename),
|
||||||
thumb_path=os.path.join(CLIPS_DIR, "export", f"{export_id}.webp"),
|
thumb_path=os.path.join(EXPORT_DIR, f"{filename}.jpg"),
|
||||||
in_progress=False,
|
in_progress=False,
|
||||||
).execute()
|
).execute()
|
||||||
|
|
||||||
@@ -280,34 +280,6 @@ class TestExportResolution(unittest.TestCase):
|
|||||||
resolution, _ = resolve_media_uri("/exports/clip.mp4", self.config)
|
resolution, _ = resolve_media_uri("/exports/clip.mp4", self.config)
|
||||||
self.assertEqual(resolution, MediaAuthResolution.UNRESOLVED_MEDIA)
|
self.assertEqual(resolution, MediaAuthResolution.UNRESOLVED_MEDIA)
|
||||||
|
|
||||||
def test_export_thumbnail_resolves_camera(self):
|
|
||||||
self._insert_export("back_door_abc123", "back_door", "back_door_clip.mp4")
|
|
||||||
resolution, camera = resolve_media_uri(
|
|
||||||
"/clips/export/back_door_abc123.webp", self.config
|
|
||||||
)
|
|
||||||
self.assertEqual(resolution, MediaAuthResolution.CAMERA)
|
|
||||||
self.assertEqual(camera, "back_door")
|
|
||||||
|
|
||||||
def test_unknown_export_thumbnail_is_unresolved(self):
|
|
||||||
resolution, _ = resolve_media_uri("/clips/export/missing.webp", self.config)
|
|
||||||
self.assertEqual(resolution, MediaAuthResolution.UNRESOLVED_MEDIA)
|
|
||||||
|
|
||||||
def test_export_thumbnail_gated_by_camera_access(self):
|
|
||||||
self._insert_export("back_door_abc123", "back_door", "back_door_clip.mp4")
|
|
||||||
self._insert_export("front_door_def456", "front_door", "front_door_clip.mp4")
|
|
||||||
url = "/clips/export/{}.webp"
|
|
||||||
self.assertIsNone(
|
|
||||||
deny_response_for_media_uri(
|
|
||||||
url.format("front_door_def456"), "limited_user", self.config
|
|
||||||
)
|
|
||||||
)
|
|
||||||
self.assertEqual(
|
|
||||||
deny_response_for_media_uri(
|
|
||||||
url.format("back_door_abc123"), "limited_user", self.config
|
|
||||||
),
|
|
||||||
403,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class TestDenyResponseForMediaUri(unittest.TestCase):
|
class TestDenyResponseForMediaUri(unittest.TestCase):
|
||||||
"""End-to-end decision check used by /auth."""
|
"""End-to-end decision check used by /auth."""
|
||||||
|
|||||||
@@ -135,31 +135,6 @@ class TestModelDownloadState(unittest.TestCase):
|
|||||||
self.assertEqual(states[-1]["state"], "error")
|
self.assertEqual(states[-1]["state"], "error")
|
||||||
self.assertEqual(states[-1]["model"], "facedet-facedet.onnx")
|
self.assertEqual(states[-1]["model"], "facedet-facedet.onnx")
|
||||||
|
|
||||||
def test_raising_download_releases_waiters(self):
|
|
||||||
def failing(path: str) -> None:
|
|
||||||
raise RuntimeError("boom")
|
|
||||||
|
|
||||||
model_downloader = self._downloader(failing)
|
|
||||||
|
|
||||||
with self.assertRaises(RuntimeError):
|
|
||||||
model_downloader._download_models()
|
|
||||||
|
|
||||||
self.assertTrue(model_downloader.download_complete.is_set())
|
|
||||||
model_downloader.requestor.stop.assert_called_once()
|
|
||||||
|
|
||||||
def test_lock_timeout_releases_waiters(self):
|
|
||||||
model_downloader = self._downloader(lambda path: None)
|
|
||||||
|
|
||||||
with patch("frigate.util.downloader.FileLock") as file_lock:
|
|
||||||
file_lock.return_value.__enter__.side_effect = TimeoutError("lock")
|
|
||||||
|
|
||||||
with self.assertRaises(TimeoutError):
|
|
||||||
model_downloader._download_models()
|
|
||||||
|
|
||||||
self.assertTrue(model_downloader.download_complete.is_set())
|
|
||||||
states = self._state_calls(model_downloader.requestor)
|
|
||||||
self.assertEqual([s["state"] for s in states], ["error"])
|
|
||||||
|
|
||||||
def test_missing_file_marks_error(self):
|
def test_missing_file_marks_error(self):
|
||||||
def swallowing(path: str) -> None:
|
def swallowing(path: str) -> None:
|
||||||
pass
|
pass
|
||||||
|
|||||||
@@ -1,67 +0,0 @@
|
|||||||
import unittest
|
|
||||||
from unittest.mock import patch
|
|
||||||
|
|
||||||
from frigate.config import FrigateConfig
|
|
||||||
from frigate.util.object_names import get_categorized_object_names
|
|
||||||
|
|
||||||
|
|
||||||
class TestCategorizedObjectNames(unittest.TestCase):
|
|
||||||
def setUp(self):
|
|
||||||
self.config = FrigateConfig(
|
|
||||||
**{
|
|
||||||
"mqtt": {"host": "mqtt"},
|
|
||||||
"cameras": {
|
|
||||||
"front_door": {
|
|
||||||
"ffmpeg": {
|
|
||||||
"inputs": [
|
|
||||||
{
|
|
||||||
"path": "rtsp://10.0.0.1:554/video",
|
|
||||||
"roles": ["detect"],
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"detect": {"height": 1080, "width": 1920, "fps": 5},
|
|
||||||
"objects": {"track": ["person"]},
|
|
||||||
},
|
|
||||||
"yard": {
|
|
||||||
"ffmpeg": {
|
|
||||||
"inputs": [
|
|
||||||
{
|
|
||||||
"path": "rtsp://10.0.0.2:554/video",
|
|
||||||
"roles": ["detect"],
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"detect": {"height": 1080, "width": 1920, "fps": 5},
|
|
||||||
"objects": {"track": ["person", "dog"]},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
"classification": {
|
|
||||||
"custom": {
|
|
||||||
"pets": {
|
|
||||||
"object_config": {
|
|
||||||
"objects": ["dog"],
|
|
||||||
"classification_type": "sub_label",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
@patch(
|
|
||||||
"frigate.util.object_names._get_classification_categories",
|
|
||||||
return_value={"rex"},
|
|
||||||
)
|
|
||||||
def test_classification_categories_limited_to_tracked_objects(self, _categories):
|
|
||||||
names = get_categorized_object_names(self.config, ["front_door"])
|
|
||||||
self.assertNotIn("dog", names)
|
|
||||||
|
|
||||||
self.assertNotIn("dog", get_categorized_object_names(self.config, []))
|
|
||||||
|
|
||||||
names = get_categorized_object_names(self.config, ["yard"])
|
|
||||||
self.assertEqual(names["dog"], ["rex"])
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
+4
-218
@@ -1,15 +1,9 @@
|
|||||||
"""Tests for Frigate+ model metadata."""
|
"""Tests for Frigate+ model metadata."""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import datetime
|
|
||||||
import email.utils
|
|
||||||
import http.server
|
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import pickle
|
|
||||||
import tempfile
|
import tempfile
|
||||||
import threading
|
|
||||||
import time
|
|
||||||
import unittest
|
import unittest
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
@@ -17,16 +11,7 @@ import aiohttp
|
|||||||
from aiohttp import web
|
from aiohttp import web
|
||||||
from aiohttp.test_utils import TestServer
|
from aiohttp.test_utils import TestServer
|
||||||
|
|
||||||
from frigate.const import PLUS_ENV_VAR
|
from frigate.plus import PlusApi, PlusKeyStatus, load_plus_model_info
|
||||||
from frigate.plus import (
|
|
||||||
PlusApi,
|
|
||||||
PlusKeyStatus,
|
|
||||||
PlusRateLimitError,
|
|
||||||
load_plus_model_info,
|
|
||||||
parse_retry_after,
|
|
||||||
)
|
|
||||||
|
|
||||||
TEST_PLUS_KEY = f"{'a' * 8}-{'b' * 4}-{'c' * 4}-{'d' * 4}-{'e' * 12}:{'f' * 40}"
|
|
||||||
|
|
||||||
|
|
||||||
class TestHailoAlias(unittest.TestCase):
|
class TestHailoAlias(unittest.TestCase):
|
||||||
@@ -114,26 +99,18 @@ class TestValidateKey(unittest.IsolatedAsyncioTestCase):
|
|||||||
api.host = host
|
api.host = host
|
||||||
api.key = key
|
api.key = key
|
||||||
api._token_data = dict(self.CACHED_TOKEN)
|
api._token_data = dict(self.CACHED_TOKEN)
|
||||||
api._rate_limited_until = None
|
|
||||||
return api
|
return api
|
||||||
|
|
||||||
async def _validate(self, handler) -> tuple[PlusKeyStatus, PlusApi]:
|
async def _validate(self, handler) -> tuple[PlusKeyStatus, PlusApi]:
|
||||||
api = self._api(await self._serve(handler))
|
api = self._api(await self._serve(handler))
|
||||||
return await api.validate_key(), api
|
return await api.validate_key(), api
|
||||||
|
|
||||||
def _replies(
|
def _replies(self, status: int = 200, body: object = None, text: str | None = None):
|
||||||
self,
|
|
||||||
status: int = 200,
|
|
||||||
body: object = None,
|
|
||||||
text: str | None = None,
|
|
||||||
headers: dict[str, str] | None = None,
|
|
||||||
):
|
|
||||||
async def handler(request: web.Request) -> web.Response:
|
async def handler(request: web.Request) -> web.Response:
|
||||||
self.auth = request.headers.get("Authorization")
|
self.auth = request.headers.get("Authorization")
|
||||||
self.requests_seen = getattr(self, "requests_seen", 0) + 1
|
|
||||||
if text is not None:
|
if text is not None:
|
||||||
return web.Response(status=status, text=text, headers=headers)
|
return web.Response(status=status, text=text)
|
||||||
return web.json_response(body, status=status, headers=headers)
|
return web.json_response(body, status=status)
|
||||||
|
|
||||||
return handler
|
return handler
|
||||||
|
|
||||||
@@ -157,25 +134,6 @@ class TestValidateKey(unittest.IsolatedAsyncioTestCase):
|
|||||||
|
|
||||||
self.assertEqual(status, PlusKeyStatus.unreachable)
|
self.assertEqual(status, PlusKeyStatus.unreachable)
|
||||||
|
|
||||||
async def test_a_rate_limited_key_is_not_reported_as_invalid(self):
|
|
||||||
api = self._api(
|
|
||||||
await self._serve(self._replies(429, {}, headers={"Retry-After": "120"}))
|
|
||||||
)
|
|
||||||
|
|
||||||
self.assertEqual(await api.validate_key(), PlusKeyStatus.rate_limited)
|
|
||||||
self.assertAlmostEqual(api.rate_limit_remaining(), 120, delta=1)
|
|
||||||
self.assertEqual(api._token_data, self.CACHED_TOKEN)
|
|
||||||
|
|
||||||
# validating again during the wait doesn't ask the server
|
|
||||||
self.assertEqual(await api.validate_key(), PlusKeyStatus.rate_limited)
|
|
||||||
self.assertEqual(self.requests_seen, 1)
|
|
||||||
|
|
||||||
async def test_a_rate_limit_without_retry_after(self):
|
|
||||||
status, api = await self._validate(self._replies(429, {}))
|
|
||||||
|
|
||||||
self.assertEqual(status, PlusKeyStatus.rate_limited)
|
|
||||||
self.assertIsNone(api.rate_limit_remaining())
|
|
||||||
|
|
||||||
async def test_unusable_replies_keep_the_cached_token(self):
|
async def test_unusable_replies_keep_the_cached_token(self):
|
||||||
# a successful reply without a usable token must not replace one that
|
# a successful reply without a usable token must not replace one that
|
||||||
# later Frigate+ requests depend on
|
# later Frigate+ requests depend on
|
||||||
@@ -254,177 +212,5 @@ class TestValidateKey(unittest.IsolatedAsyncioTestCase):
|
|||||||
self.assertEqual(requests_seen, [])
|
self.assertEqual(requests_seen, [])
|
||||||
|
|
||||||
|
|
||||||
class TestParseRetryAfter(unittest.TestCase):
|
|
||||||
def test_delay_seconds(self):
|
|
||||||
self.assertEqual(parse_retry_after("120"), 120)
|
|
||||||
self.assertEqual(parse_retry_after(" 0 "), 0)
|
|
||||||
|
|
||||||
def test_an_http_date(self):
|
|
||||||
retry_at = datetime.datetime.now(datetime.UTC) + datetime.timedelta(seconds=90)
|
|
||||||
header = email.utils.format_datetime(retry_at, usegmt=True)
|
|
||||||
|
|
||||||
self.assertAlmostEqual(parse_retry_after(header), 90, delta=2)
|
|
||||||
|
|
||||||
def test_a_date_in_the_past_is_no_wait(self):
|
|
||||||
self.assertEqual(parse_retry_after("Wed, 21 Oct 2015 07:28:00 GMT"), 0)
|
|
||||||
|
|
||||||
def test_missing_or_invalid_values(self):
|
|
||||||
for value in (None, "", "soon", "-5", "1.5"):
|
|
||||||
with self.subTest(value=value):
|
|
||||||
self.assertIsNone(parse_retry_after(value))
|
|
||||||
|
|
||||||
|
|
||||||
class TestRateLimit(unittest.TestCase):
|
|
||||||
"""A 429 from Frigate+ is raised at once instead of blocking on Retry-After."""
|
|
||||||
|
|
||||||
def setUp(self):
|
|
||||||
self.hits: list[str] = []
|
|
||||||
self.status = 429
|
|
||||||
self.headers: dict[str, str] = {"Retry-After": "30"}
|
|
||||||
test = self
|
|
||||||
|
|
||||||
class Handler(http.server.BaseHTTPRequestHandler):
|
|
||||||
def _reply(self):
|
|
||||||
test.hits.append(f"{self.command} {self.path}")
|
|
||||||
length = int(self.headers.get("Content-Length") or 0)
|
|
||||||
self.rfile.read(length)
|
|
||||||
|
|
||||||
if self.path == "/v1/auth/token":
|
|
||||||
status, body = (
|
|
||||||
200,
|
|
||||||
json.dumps({"accessToken": "t", "expires": time.time() + 3600}),
|
|
||||||
)
|
|
||||||
headers = {}
|
|
||||||
else:
|
|
||||||
status, body, headers = test.status, "{}", test.headers
|
|
||||||
|
|
||||||
self.send_response(status)
|
|
||||||
for name, value in headers.items():
|
|
||||||
self.send_header(name, value)
|
|
||||||
self.send_header("Content-Length", str(len(body)))
|
|
||||||
self.end_headers()
|
|
||||||
self.wfile.write(body.encode())
|
|
||||||
|
|
||||||
do_GET = do_PUT = do_POST = _reply
|
|
||||||
|
|
||||||
def log_message(self, *args):
|
|
||||||
pass
|
|
||||||
|
|
||||||
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
|
||||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
|
||||||
self.addCleanup(server.server_close)
|
|
||||||
self.addCleanup(server.shutdown)
|
|
||||||
|
|
||||||
host = f"http://127.0.0.1:{server.server_port}"
|
|
||||||
with (
|
|
||||||
patch("frigate.plus.PLUS_API_HOST", host),
|
|
||||||
patch.dict(os.environ, {PLUS_ENV_VAR: TEST_PLUS_KEY}),
|
|
||||||
):
|
|
||||||
self.api = PlusApi()
|
|
||||||
|
|
||||||
def _api_hits(self) -> list[str]:
|
|
||||||
return [hit for hit in self.hits if hit != "GET /v1/auth/token"]
|
|
||||||
|
|
||||||
def test_a_429_is_raised_without_retrying(self):
|
|
||||||
for call in (
|
|
||||||
lambda: self.api.get_models(),
|
|
||||||
lambda: self.api.add_annotation("img", [0, 0, 1, 1], "person"),
|
|
||||||
lambda: self.api._post("image/create", {}),
|
|
||||||
):
|
|
||||||
with self.subTest(call=call):
|
|
||||||
self.hits.clear()
|
|
||||||
self.api._rate_limited_until = None
|
|
||||||
start = time.monotonic()
|
|
||||||
|
|
||||||
with self.assertRaises(PlusRateLimitError) as ctx:
|
|
||||||
call()
|
|
||||||
|
|
||||||
self.assertEqual(ctx.exception.retry_after, 30)
|
|
||||||
self.assertEqual(len(self._api_hits()), 1)
|
|
||||||
self.assertLess(time.monotonic() - start, 5)
|
|
||||||
|
|
||||||
def test_requests_are_refused_locally_until_retry_after_passes(self):
|
|
||||||
with self.assertRaises(PlusRateLimitError):
|
|
||||||
self.api.get_models()
|
|
||||||
|
|
||||||
self.assertAlmostEqual(self.api.rate_limit_remaining(), 30, delta=1)
|
|
||||||
self.hits.clear()
|
|
||||||
|
|
||||||
with self.assertRaises(PlusRateLimitError) as ctx:
|
|
||||||
self.api.get_model_info("abc")
|
|
||||||
|
|
||||||
self.assertAlmostEqual(ctx.exception.retry_after, 30, delta=1)
|
|
||||||
self.assertEqual(self.hits, [])
|
|
||||||
|
|
||||||
# once the wait has passed, requests go to the server again
|
|
||||||
self.api._rate_limited_until = time.time() - 1
|
|
||||||
self.status = 200
|
|
||||||
|
|
||||||
self.assertEqual(self.api.get_model_info("abc"), {})
|
|
||||||
self.assertIsNone(self.api.rate_limit_remaining())
|
|
||||||
|
|
||||||
def test_a_shorter_wait_arriving_later_keeps_the_longer_one(self):
|
|
||||||
# two requests in flight are both refused, and the reply with the
|
|
||||||
# longer wait is handled first
|
|
||||||
self.api._note_rate_limit(120)
|
|
||||||
self.api._note_rate_limit(10)
|
|
||||||
|
|
||||||
self.assertAlmostEqual(self.api.rate_limit_remaining(), 120, delta=1)
|
|
||||||
|
|
||||||
# a longer wait still extends it
|
|
||||||
self.api._note_rate_limit(300)
|
|
||||||
|
|
||||||
self.assertAlmostEqual(self.api.rate_limit_remaining(), 300, delta=1)
|
|
||||||
|
|
||||||
def test_concurrent_replies_keep_the_longest_wait(self):
|
|
||||||
waits = list(range(1, 201))
|
|
||||||
threads = [
|
|
||||||
threading.Thread(target=self.api._note_rate_limit, args=(wait,))
|
|
||||||
for wait in waits
|
|
||||||
]
|
|
||||||
|
|
||||||
with patch("frigate.plus.logger"):
|
|
||||||
for thread in threads:
|
|
||||||
thread.start()
|
|
||||||
for thread in threads:
|
|
||||||
thread.join()
|
|
||||||
|
|
||||||
self.assertAlmostEqual(self.api.rate_limit_remaining(), max(waits), delta=1)
|
|
||||||
|
|
||||||
def test_the_client_can_be_sent_to_a_worker_process(self):
|
|
||||||
# worker processes start from the forkserver, which pickles the
|
|
||||||
# config and the Frigate+ client it holds
|
|
||||||
self.api._note_rate_limit(60)
|
|
||||||
|
|
||||||
copy = pickle.loads(pickle.dumps(self.api))
|
|
||||||
|
|
||||||
self.assertAlmostEqual(copy.rate_limit_remaining(), 60, delta=1)
|
|
||||||
copy._note_rate_limit(120)
|
|
||||||
self.assertAlmostEqual(copy.rate_limit_remaining(), 120, delta=1)
|
|
||||||
|
|
||||||
def test_a_429_without_retry_after_is_not_remembered(self):
|
|
||||||
self.headers = {}
|
|
||||||
|
|
||||||
with self.assertRaises(PlusRateLimitError) as ctx:
|
|
||||||
self.api.get_models()
|
|
||||||
|
|
||||||
self.assertIsNone(ctx.exception.retry_after)
|
|
||||||
self.assertIsNone(self.api.rate_limit_remaining())
|
|
||||||
|
|
||||||
def test_a_rate_limited_token_refresh(self):
|
|
||||||
self.api._token_data = {}
|
|
||||||
|
|
||||||
with patch.object(
|
|
||||||
self.api._session,
|
|
||||||
"get",
|
|
||||||
return_value=MagicMock(status_code=429, headers={"Retry-After": "60"}),
|
|
||||||
):
|
|
||||||
with self.assertRaises(PlusRateLimitError) as ctx:
|
|
||||||
self.api.get_models()
|
|
||||||
|
|
||||||
self.assertEqual(ctx.exception.retry_after, 60)
|
|
||||||
self.assertAlmostEqual(self.api.rate_limit_remaining(), 60, delta=1)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main(verbosity=2)
|
unittest.main(verbosity=2)
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ from unittest.mock import MagicMock, patch
|
|||||||
|
|
||||||
from frigate.config import BirdseyeModeEnum, FrigateConfig
|
from frigate.config import BirdseyeModeEnum, FrigateConfig
|
||||||
from frigate.config.camera.profile import CameraProfileConfig
|
from frigate.config.camera.profile import CameraProfileConfig
|
||||||
from frigate.config.config import RuntimeFilterConfig
|
|
||||||
from frigate.config.profile import ProfileDefinitionConfig
|
from frigate.config.profile import ProfileDefinitionConfig
|
||||||
from frigate.config.profile_manager import PERSISTENCE_FILE, ProfileManager
|
from frigate.config.profile_manager import PERSISTENCE_FILE, ProfileManager
|
||||||
from frigate.const import MODEL_CACHE_DIR
|
from frigate.const import MODEL_CACHE_DIR
|
||||||
@@ -503,16 +502,6 @@ class TestProfileManager(unittest.TestCase):
|
|||||||
back = self.config.cameras["back"]
|
back = self.config.cameras["back"]
|
||||||
assert back.notifications.enabled is True
|
assert back.notifications.enabled is True
|
||||||
|
|
||||||
@patch.object(ProfileManager, "_persist_active_profile")
|
|
||||||
def test_activate_profile_adds_filters_for_new_tracked_labels(self, mock_persist):
|
|
||||||
"""Labels a profile adds to objects.track get default filters."""
|
|
||||||
err = self.manager.activate_profile("armed")
|
|
||||||
assert err is None
|
|
||||||
|
|
||||||
filters = self.config.cameras["front"].objects.filters
|
|
||||||
for label in ["person", "car", "package"]:
|
|
||||||
assert isinstance(filters[label], RuntimeFilterConfig)
|
|
||||||
|
|
||||||
@patch.object(ProfileManager, "_persist_active_profile")
|
@patch.object(ProfileManager, "_persist_active_profile")
|
||||||
def test_deactivate_profile(self, mock_persist):
|
def test_deactivate_profile(self, mock_persist):
|
||||||
"""Deactivating a profile restores base config."""
|
"""Deactivating a profile restores base config."""
|
||||||
|
|||||||
@@ -95,42 +95,6 @@ class TestProxyRoleResolution(unittest.TestCase):
|
|||||||
role = resolve_role(headers, self.proxy_config, self.config_roles)
|
role = resolve_role(headers, self.proxy_config, self.config_roles)
|
||||||
self.assertEqual(role, self.proxy_config.default_role)
|
self.assertEqual(role, self.proxy_config.default_role)
|
||||||
|
|
||||||
def test_custom_role_direct_header_ignores_case(self):
|
|
||||||
config = self.proxy_config
|
|
||||||
config.header_map.role_map = None
|
|
||||||
headers = {"x-remote-role": "garage"}
|
|
||||||
role = resolve_role(headers, config, ["admin", "viewer", "Garage"])
|
|
||||||
self.assertEqual(role, "Garage")
|
|
||||||
|
|
||||||
def test_role_map_to_missing_role_denies(self):
|
|
||||||
"""A group mapped to a deleted role must not widen to default_role."""
|
|
||||||
self.proxy_config.header_map.role_map = {"garage": ["group_garage"]}
|
|
||||||
headers = {"x-remote-role": "group_garage"}
|
|
||||||
role = resolve_role(headers, self.proxy_config, self.config_roles)
|
|
||||||
self.assertEqual(role, "none")
|
|
||||||
|
|
||||||
def test_unknown_default_role_denies(self):
|
|
||||||
for default in ("operatr", None):
|
|
||||||
with self.subTest(default_role=default):
|
|
||||||
config = ProxyConfig(
|
|
||||||
default_role=default,
|
|
||||||
header_map=HeaderMappingConfig(role="x-remote-role"),
|
|
||||||
)
|
|
||||||
role = resolve_role({}, config, self.config_roles)
|
|
||||||
self.assertEqual(role, "none")
|
|
||||||
|
|
||||||
def test_default_role_and_role_map_ignore_case(self):
|
|
||||||
roles = ["admin", "viewer", "Garage"]
|
|
||||||
config = ProxyConfig(
|
|
||||||
default_role="garage",
|
|
||||||
header_map=HeaderMappingConfig(
|
|
||||||
role="x-remote-role", role_map={"GARAGE": ["group_garage"]}
|
|
||||||
),
|
|
||||||
)
|
|
||||||
self.assertEqual(resolve_role({}, config, roles), "Garage")
|
|
||||||
headers = {"x-remote-role": "group_garage"}
|
|
||||||
self.assertEqual(resolve_role(headers, config, roles), "Garage")
|
|
||||||
|
|
||||||
|
|
||||||
class TestDefaultRoleNone(unittest.TestCase):
|
class TestDefaultRoleNone(unittest.TestCase):
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
@@ -226,9 +190,6 @@ class TestDefaultRoleNone(unittest.TestCase):
|
|||||||
)
|
)
|
||||||
self.assertEqual(role, "none")
|
self.assertEqual(role, "none")
|
||||||
|
|
||||||
def test_null_default_role_normalizes_to_none(self):
|
|
||||||
self.assertEqual(ProxyConfig(default_role=None).default_role, "none")
|
|
||||||
|
|
||||||
def test_other_role_names_stay_case_sensitive(self):
|
def test_other_role_names_stay_case_sensitive(self):
|
||||||
"""Only the deny sentinel is normalized; role names are untouched."""
|
"""Only the deny sentinel is normalized; role names are untouched."""
|
||||||
config = ProxyConfig(default_role="Operator")
|
config = ProxyConfig(default_role="Operator")
|
||||||
@@ -260,18 +221,8 @@ class TestReservedRoleNames(unittest.TestCase):
|
|||||||
with self.assertRaises(ValidationError):
|
with self.assertRaises(ValidationError):
|
||||||
AuthConfig(roles={name: ["front_door"]})
|
AuthConfig(roles={name: ["front_door"]})
|
||||||
|
|
||||||
def test_admin_and_viewer_reserved_in_every_casing(self):
|
|
||||||
for name in ("Admin", "VIEWER"):
|
|
||||||
with self.subTest(role=name):
|
|
||||||
with self.assertRaises(ValidationError):
|
|
||||||
AuthConfig(roles={name: ["front_door"]})
|
|
||||||
|
|
||||||
def test_role_names_differing_only_by_case_rejected(self):
|
|
||||||
with self.assertRaises(ValidationError):
|
|
||||||
AuthConfig(roles={"garage": ["front_door"], "Garage": ["back"]})
|
|
||||||
|
|
||||||
def test_case_variant_of_a_normal_role_still_allowed(self):
|
def test_case_variant_of_a_normal_role_still_allowed(self):
|
||||||
"""A mixed-case custom name is fine when it is not reserved."""
|
"""Only 'none' folds case; other role names are untouched."""
|
||||||
config = AuthConfig(roles={"Operator": ["front_door"]})
|
config = AuthConfig(roles={"Operator": ["front_door"]})
|
||||||
self.assertEqual(config.roles["Operator"], ["front_door"])
|
self.assertEqual(config.roles["Operator"], ["front_door"])
|
||||||
|
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ from unittest.mock import AsyncMock, MagicMock
|
|||||||
from frigate.camera import PTZMetrics
|
from frigate.camera import PTZMetrics
|
||||||
from frigate.config import FrigateConfig
|
from frigate.config import FrigateConfig
|
||||||
from frigate.ptz.autotrack import ptz_moving_at_frame_time
|
from frigate.ptz.autotrack import ptz_moving_at_frame_time
|
||||||
from frigate.ptz.onvif import OnvifCommandEnum, OnvifController
|
from frigate.ptz.onvif import OnvifController
|
||||||
|
|
||||||
CAMERA = "ptz_cam"
|
CAMERA = "ptz_cam"
|
||||||
|
|
||||||
@@ -157,14 +157,6 @@ class TestOnvifInitRequests(unittest.IsolatedAsyncioTestCase):
|
|||||||
ptz.GetServiceCapabilities.assert_not_called()
|
ptz.GetServiceCapabilities.assert_not_called()
|
||||||
ptz.GetStatus.assert_not_called()
|
ptz.GetStatus.assert_not_called()
|
||||||
|
|
||||||
async def test_init_completes_without_video_sources(self) -> None:
|
|
||||||
controller = _make_controller(autotracking_enabled=False)
|
|
||||||
media = await controller.cams[CAMERA]["onvif"].create_media_service()
|
|
||||||
media.GetVideoSources.return_value = []
|
|
||||||
|
|
||||||
self.assertTrue(await controller._init_onvif(CAMERA))
|
|
||||||
self.assertIsNone(controller.cams[CAMERA]["video_source_token"])
|
|
||||||
|
|
||||||
|
|
||||||
class TestManualRelativeMoveMetrics(unittest.IsolatedAsyncioTestCase):
|
class TestManualRelativeMoveMetrics(unittest.IsolatedAsyncioTestCase):
|
||||||
"""A manual move from the UI (click to move, drag to zoom) sends move_relative
|
"""A manual move from the UI (click to move, drag to zoom) sends move_relative
|
||||||
@@ -212,39 +204,6 @@ class TestManualRelativeMoveMetrics(unittest.IsolatedAsyncioTestCase):
|
|||||||
|
|
||||||
self.assertFalse(controller.cams[CAMERA]["active"])
|
self.assertFalse(controller.cams[CAMERA]["active"])
|
||||||
|
|
||||||
async def test_failed_preset_and_zoom_moves_do_not_raise(self) -> None:
|
|
||||||
# camera_maintenance and the move queue consumer end on an exception
|
|
||||||
controller = _make_move_controller(autotracking_enabled=True)
|
|
||||||
cam = controller.cams[CAMERA]
|
|
||||||
cam["features"] += ["zoom", "zoom-a"]
|
|
||||||
cam["presets"] = {"home": "token_1"}
|
|
||||||
cam["move_request"] = MagicMock()
|
|
||||||
cam["absolute_zoom_range"] = {"XRange": {"Min": 0.0, "Max": 1.0}}
|
|
||||||
cam["ptz"].GotoPreset = AsyncMock(side_effect=TimeoutError)
|
|
||||||
cam["ptz"].ContinuousMove = AsyncMock(side_effect=TimeoutError)
|
|
||||||
cam["ptz"].AbsoluteMove = AsyncMock(side_effect=TimeoutError)
|
|
||||||
|
|
||||||
moves = {
|
|
||||||
"preset": (
|
|
||||||
controller._move_to_preset(CAMERA, "home"),
|
|
||||||
cam["ptz"].GotoPreset,
|
|
||||||
),
|
|
||||||
"zoom": (
|
|
||||||
controller._zoom(CAMERA, OnvifCommandEnum.zoom_in),
|
|
||||||
cam["ptz"].ContinuousMove,
|
|
||||||
),
|
|
||||||
"zoom_absolute": (
|
|
||||||
controller._zoom_absolute(CAMERA, 0.5, 1),
|
|
||||||
cam["ptz"].AbsoluteMove,
|
|
||||||
),
|
|
||||||
}
|
|
||||||
|
|
||||||
for name, (move, request) in moves.items():
|
|
||||||
with self.subTest(move=name):
|
|
||||||
await move
|
|
||||||
request.assert_awaited_once()
|
|
||||||
self.assertFalse(cam["active"])
|
|
||||||
|
|
||||||
async def test_metrics_written_when_autotracking_enabled(self) -> None:
|
async def test_metrics_written_when_autotracking_enabled(self) -> None:
|
||||||
# get_camera_status resets stop_time once the camera reports IDLE, so the
|
# get_camera_status resets stop_time once the camera reports IDLE, so the
|
||||||
# autotracking path keeps its motion estimation timestamps
|
# autotracking path keeps its motion estimation timestamps
|
||||||
|
|||||||
@@ -1,253 +0,0 @@
|
|||||||
"""Review severity rules shared by review segments and tracked objects."""
|
|
||||||
|
|
||||||
import unittest
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
from frigate.config import FrigateConfig
|
|
||||||
from frigate.review.maintainer import ActiveObjects
|
|
||||||
from frigate.review.severity import get_review_severity
|
|
||||||
from frigate.review.types import SeverityEnum
|
|
||||||
from frigate.track.tracked_object import TrackedObject
|
|
||||||
|
|
||||||
CAMERA = "cam"
|
|
||||||
FPS = 5
|
|
||||||
ZONE = "porch"
|
|
||||||
INSIDE_X = 480
|
|
||||||
OUTSIDE_X = 160
|
|
||||||
|
|
||||||
|
|
||||||
def _config(alerts_enabled: bool = True) -> FrigateConfig:
|
|
||||||
return FrigateConfig(
|
|
||||||
**{
|
|
||||||
"mqtt": {"enabled": False},
|
|
||||||
"cameras": {
|
|
||||||
CAMERA: {
|
|
||||||
"ffmpeg": {
|
|
||||||
"inputs": [
|
|
||||||
{"path": "rtsp://10.0.0.1:554/video", "roles": ["detect"]}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"detect": {"width": 640, "height": 480, "fps": FPS},
|
|
||||||
"objects": {"track": ["person"]},
|
|
||||||
"zones": {ZONE: {"coordinates": "0.5,0,1,0,1,1,0.5,1"}},
|
|
||||||
"review": {
|
|
||||||
"alerts": {
|
|
||||||
"enabled": alerts_enabled,
|
|
||||||
"required_zones": [ZONE],
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class TestGetReviewSeverity(unittest.TestCase):
|
|
||||||
def setUp(self):
|
|
||||||
self.camera_config = _config().cameras[CAMERA]
|
|
||||||
self.stationary_threshold = self.camera_config.detect.stationary.threshold
|
|
||||||
|
|
||||||
def _severity(self, camera_config=None, **overrides: Any) -> SeverityEnum | None:
|
|
||||||
kwargs = {
|
|
||||||
"label": "person",
|
|
||||||
"current_zones": [ZONE],
|
|
||||||
"false_positive": False,
|
|
||||||
"detected": True,
|
|
||||||
"position_changes": 1,
|
|
||||||
"motionless_count": 0,
|
|
||||||
"pending_loitering": False,
|
|
||||||
**overrides,
|
|
||||||
}
|
|
||||||
return get_review_severity(camera_config or self.camera_config, **kwargs)
|
|
||||||
|
|
||||||
def test_alert_in_required_zone(self):
|
|
||||||
self.assertEqual(self._severity(), SeverityEnum.alert)
|
|
||||||
|
|
||||||
def test_detection_outside_alert_required_zone(self):
|
|
||||||
self.assertEqual(self._severity(current_zones=[]), SeverityEnum.detection)
|
|
||||||
|
|
||||||
def test_detection_when_alerts_disabled(self):
|
|
||||||
camera_config = _config(alerts_enabled=False).cameras[CAMERA]
|
|
||||||
self.assertEqual(
|
|
||||||
self._severity(camera_config=camera_config), SeverityEnum.detection
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_stationary_object_does_not_qualify(self):
|
|
||||||
self.assertIsNone(self._severity(motionless_count=self.stationary_threshold))
|
|
||||||
|
|
||||||
def test_stationary_loitering_object_qualifies(self):
|
|
||||||
self.assertEqual(
|
|
||||||
self._severity(
|
|
||||||
motionless_count=self.stationary_threshold, pending_loitering=True
|
|
||||||
),
|
|
||||||
SeverityEnum.alert,
|
|
||||||
)
|
|
||||||
|
|
||||||
def test_object_that_never_moved_does_not_qualify(self):
|
|
||||||
self.assertIsNone(self._severity(position_changes=0))
|
|
||||||
|
|
||||||
def test_undetected_object_does_not_qualify(self):
|
|
||||||
self.assertIsNone(self._severity(detected=False))
|
|
||||||
|
|
||||||
def test_false_positive_does_not_qualify(self):
|
|
||||||
self.assertIsNone(self._severity(false_positive=True))
|
|
||||||
|
|
||||||
|
|
||||||
class TestTrackedObjectMaxSeverity(unittest.TestCase):
|
|
||||||
"""max_severity must match what review segments would have been created."""
|
|
||||||
|
|
||||||
def setUp(self):
|
|
||||||
config = _config()
|
|
||||||
self.camera_config = config.cameras[CAMERA]
|
|
||||||
self.stationary_threshold = self.camera_config.detect.stationary.threshold
|
|
||||||
self.frame = 0
|
|
||||||
self.position_changes = 0
|
|
||||||
self.motionless_count = 0
|
|
||||||
self.last_detection = self._obj_data(OUTSIDE_X, 0.6, 1000.0)
|
|
||||||
self.obj = TrackedObject(
|
|
||||||
config.model_for_camera(CAMERA),
|
|
||||||
self.camera_config,
|
|
||||||
config.ui,
|
|
||||||
{},
|
|
||||||
{**self.last_detection, "score_history": [0.6]},
|
|
||||||
)
|
|
||||||
|
|
||||||
def _obj_data(self, x: int, score: float, frame_time: float) -> dict[str, Any]:
|
|
||||||
return {
|
|
||||||
"id": "1000.0-abcdef",
|
|
||||||
"label": "person",
|
|
||||||
"frame_time": frame_time,
|
|
||||||
"start_time": 1000.0,
|
|
||||||
"score": score,
|
|
||||||
"box": (x - 40, 200, x + 40, 360),
|
|
||||||
"area": 12800,
|
|
||||||
"ratio": 0.5,
|
|
||||||
"region": (0, 0, 640, 480),
|
|
||||||
"centroid": (x, 280),
|
|
||||||
"position_changes": self.position_changes,
|
|
||||||
"motionless_count": self.motionless_count,
|
|
||||||
"attributes": [],
|
|
||||||
"sub_label": None,
|
|
||||||
}
|
|
||||||
|
|
||||||
def _step(
|
|
||||||
self, x: int, score: float, moved: bool, detected: bool = True
|
|
||||||
) -> SeverityEnum | None:
|
|
||||||
"""Advance one frame and return the severity review segments would see."""
|
|
||||||
self.frame += 1
|
|
||||||
frame_time = 1000.0 + self.frame / FPS
|
|
||||||
|
|
||||||
if detected:
|
|
||||||
# mirror the tracker, which counts the first move and any move
|
|
||||||
# after the object was stationary as a position change
|
|
||||||
if moved:
|
|
||||||
if (
|
|
||||||
self.position_changes == 0
|
|
||||||
or self.motionless_count >= self.stationary_threshold
|
|
||||||
):
|
|
||||||
self.position_changes += 1
|
|
||||||
self.motionless_count = 0
|
|
||||||
else:
|
|
||||||
self.motionless_count += 1
|
|
||||||
|
|
||||||
self.last_detection = self._obj_data(x, score, frame_time)
|
|
||||||
|
|
||||||
_, self.last_significant, _, _ = self.obj.update(
|
|
||||||
frame_time, dict(self.last_detection), False
|
|
||||||
)
|
|
||||||
activity = ActiveObjects(frame_time, self.camera_config, [self.obj.to_dict()])
|
|
||||||
|
|
||||||
if activity.has_activity_category(SeverityEnum.alert):
|
|
||||||
return SeverityEnum.alert
|
|
||||||
|
|
||||||
if activity.has_activity_category(SeverityEnum.detection):
|
|
||||||
return SeverityEnum.detection
|
|
||||||
|
|
||||||
return None
|
|
||||||
|
|
||||||
def test_object_confirmed_while_stationary_in_zone_has_no_severity(self):
|
|
||||||
"""An object that only becomes a true positive after it stopped moving
|
|
||||||
never creates a review, so it must not be reported as an alert even
|
|
||||||
though it entered a required zone."""
|
|
||||||
review_severities = []
|
|
||||||
|
|
||||||
# walks into the zone with a low score, so it is a false positive
|
|
||||||
for i in range(10):
|
|
||||||
review_severities.append(self._step(OUTSIDE_X + i * 40, 0.6, moved=True))
|
|
||||||
|
|
||||||
# sits still until it is stationary
|
|
||||||
for _ in range(self.stationary_threshold):
|
|
||||||
review_severities.append(self._step(INSIDE_X, 0.6, moved=False))
|
|
||||||
|
|
||||||
# a re-detection while still stationary confirms it as a true positive
|
|
||||||
for _ in range(10):
|
|
||||||
review_severities.append(self._step(INSIDE_X, 0.9, moved=False))
|
|
||||||
|
|
||||||
# leaves and is no longer detected
|
|
||||||
for _ in range(10):
|
|
||||||
review_severities.append(self._step(INSIDE_X, 0.9, False, detected=False))
|
|
||||||
|
|
||||||
self.assertFalse(self.obj.false_positive)
|
|
||||||
self.assertEqual(self.obj.obj_data["position_changes"], 1)
|
|
||||||
self.assertEqual(self.obj.entered_zones, [ZONE])
|
|
||||||
self.assertEqual(set(review_severities), {None})
|
|
||||||
self.assertIsNone(self.obj.max_severity)
|
|
||||||
self.assertIsNone(self.obj.to_dict()["max_severity"])
|
|
||||||
|
|
||||||
def test_severity_change_is_significant(self):
|
|
||||||
"""Confirming an object already moving in the zone changes nothing else
|
|
||||||
that is watched, but the new severity still has to be published."""
|
|
||||||
for i in range(10):
|
|
||||||
self._step(OUTSIDE_X + i * 40, 0.6, moved=True)
|
|
||||||
|
|
||||||
self.assertEqual(self.obj.current_zones, [ZONE])
|
|
||||||
self.assertIsNone(self.obj.max_severity)
|
|
||||||
|
|
||||||
for i in range(10):
|
|
||||||
self._step(INSIDE_X + (i % 2) * 10, 0.9, moved=True)
|
|
||||||
|
|
||||||
if self.obj.max_severity is not None:
|
|
||||||
break
|
|
||||||
|
|
||||||
self.assertEqual(self.obj.max_severity, SeverityEnum.alert)
|
|
||||||
self.assertTrue(self.last_significant)
|
|
||||||
|
|
||||||
self._step(INSIDE_X, 0.9, moved=True)
|
|
||||||
self.assertFalse(self.last_significant)
|
|
||||||
|
|
||||||
def test_alert_is_kept_after_object_stops_qualifying(self):
|
|
||||||
for i in range(10):
|
|
||||||
self._step(OUTSIDE_X + i * 40, 0.9, moved=True)
|
|
||||||
|
|
||||||
self.assertEqual(self.obj.current_zones, [ZONE])
|
|
||||||
self.assertEqual(self.obj.max_severity, SeverityEnum.alert)
|
|
||||||
|
|
||||||
for _ in range(self.stationary_threshold + 5):
|
|
||||||
self._step(INSIDE_X, 0.9, moved=False)
|
|
||||||
|
|
||||||
self.assertTrue(self.obj.is_stationary())
|
|
||||||
self.assertEqual(self.obj.max_severity, SeverityEnum.alert)
|
|
||||||
|
|
||||||
def test_detection_upgrades_to_alert_and_is_not_downgraded(self):
|
|
||||||
review_severities = []
|
|
||||||
|
|
||||||
for _ in range(8):
|
|
||||||
review_severities.append(self._step(OUTSIDE_X, 0.9, moved=True))
|
|
||||||
|
|
||||||
self.assertEqual(self.obj.max_severity, SeverityEnum.detection)
|
|
||||||
|
|
||||||
for _ in range(5):
|
|
||||||
review_severities.append(self._step(INSIDE_X, 0.9, moved=True))
|
|
||||||
|
|
||||||
self.assertEqual(self.obj.max_severity, SeverityEnum.alert)
|
|
||||||
|
|
||||||
for _ in range(5):
|
|
||||||
review_severities.append(self._step(OUTSIDE_X, 0.9, moved=True))
|
|
||||||
|
|
||||||
self.assertEqual(review_severities[-1], SeverityEnum.detection)
|
|
||||||
self.assertEqual(self.obj.max_severity, SeverityEnum.alert)
|
|
||||||
self.assertIn(SeverityEnum.alert, review_severities)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
@@ -440,36 +440,6 @@ class TestHttp(unittest.TestCase):
|
|||||||
assert usages["front_door"]["usage"] == 0
|
assert usages["front_door"]["usage"] == 0
|
||||||
assert usages["front_door"]["streams"] == {}
|
assert usages["front_door"]["streams"] == {}
|
||||||
|
|
||||||
def test_camera_usages_keyed_by_camera_id(self):
|
|
||||||
"""Cameras sharing a friendly name keep separate usage entries."""
|
|
||||||
self.double_cam_config["cameras"]["front_door"]["friendly_name"] = "Door"
|
|
||||||
self.double_cam_config["cameras"]["back_door"]["friendly_name"] = "Door"
|
|
||||||
config = FrigateConfig(**self.double_cam_config)
|
|
||||||
storage = StorageMaintainer(config, MagicMock())
|
|
||||||
|
|
||||||
time_keep = datetime.datetime.now().timestamp()
|
|
||||||
_insert_mock_recording(
|
|
||||||
"1234567.frontdoor",
|
|
||||||
os.path.join(self.test_dir, "front.tmp"),
|
|
||||||
time_keep,
|
|
||||||
time_keep + 10,
|
|
||||||
seg_size=20,
|
|
||||||
)
|
|
||||||
_insert_mock_recording(
|
|
||||||
"1234568.backdoor",
|
|
||||||
os.path.join(self.test_dir, "back.tmp"),
|
|
||||||
time_keep,
|
|
||||||
time_keep + 10,
|
|
||||||
camera="back_door",
|
|
||||||
seg_size=5,
|
|
||||||
)
|
|
||||||
|
|
||||||
storage.calculate_camera_bandwidth()
|
|
||||||
usages = storage.calculate_camera_usages()
|
|
||||||
|
|
||||||
assert usages["front_door"]["usage"] == 20
|
|
||||||
assert usages["back_door"]["usage"] == 5
|
|
||||||
|
|
||||||
def test_storage_cleanup(self):
|
def test_storage_cleanup(self):
|
||||||
"""Ensure that all recordings are cleaned up when necessary."""
|
"""Ensure that all recordings are cleaned up when necessary."""
|
||||||
config = FrigateConfig(**self.minimal_config)
|
config = FrigateConfig(**self.minimal_config)
|
||||||
@@ -541,33 +511,55 @@ class TestHttp(unittest.TestCase):
|
|||||||
Recordings.get(Recordings.id == rec_d3_id)
|
Recordings.get(Recordings.id == rec_d3_id)
|
||||||
|
|
||||||
def test_storage_cleanup_keeps_retained(self):
|
def test_storage_cleanup_keeps_retained(self):
|
||||||
"""Ensure cleanup steps over retained segments to reach newer ones."""
|
"""Ensure that all recordings are cleaned up when necessary."""
|
||||||
config = FrigateConfig(**self.minimal_config)
|
config = FrigateConfig(**self.minimal_config)
|
||||||
storage = StorageMaintainer(config, MagicMock())
|
storage = StorageMaintainer(config, MagicMock())
|
||||||
|
|
||||||
seg_len = 600
|
id = "123456.keep"
|
||||||
base = datetime.datetime.now().timestamp() - 7200
|
time_keep = datetime.datetime.now().timestamp()
|
||||||
_insert_mock_event("123456.keep", base, base + 2.5 * seg_len, True)
|
_insert_mock_event(
|
||||||
|
id,
|
||||||
|
time_keep,
|
||||||
|
time_keep + 30,
|
||||||
|
True,
|
||||||
|
)
|
||||||
|
rec_k_id = "1234567.keep"
|
||||||
|
rec_k2_id = "1234568.keep"
|
||||||
|
rec_k3_id = "1234569.keep"
|
||||||
|
_insert_mock_recording(
|
||||||
|
rec_k_id,
|
||||||
|
os.path.join(self.test_dir, f"{rec_k_id}.tmp"),
|
||||||
|
time_keep,
|
||||||
|
time_keep + 10,
|
||||||
|
)
|
||||||
|
_insert_mock_recording(
|
||||||
|
rec_k2_id,
|
||||||
|
os.path.join(self.test_dir, f"{rec_k2_id}.tmp"),
|
||||||
|
time_keep + 10,
|
||||||
|
time_keep + 20,
|
||||||
|
)
|
||||||
|
_insert_mock_recording(
|
||||||
|
rec_k3_id,
|
||||||
|
os.path.join(self.test_dir, f"{rec_k3_id}.tmp"),
|
||||||
|
time_keep + 20,
|
||||||
|
time_keep + 30,
|
||||||
|
)
|
||||||
|
|
||||||
paths = {}
|
time_delete = datetime.datetime.now().timestamp() - 7200
|
||||||
for i in range(10):
|
for i in range(0, 59):
|
||||||
rec_id = f"segment-{i}"
|
id = f"{123456 + i}.delete"
|
||||||
paths[rec_id] = os.path.join(self.test_dir, f"{rec_id}.tmp")
|
|
||||||
_insert_mock_recording(
|
_insert_mock_recording(
|
||||||
rec_id, paths[rec_id], base + i * seg_len, base + (i + 1) * seg_len
|
id,
|
||||||
|
os.path.join(self.test_dir, f"{id}.tmp"),
|
||||||
|
time_delete,
|
||||||
|
time_delete + 600,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Hourly bandwidth is 48 MB, so cleanup needs all 56 MB of unretained
|
|
||||||
# segments and must pass the older retained ones to get there.
|
|
||||||
storage.calculate_camera_bandwidth()
|
storage.calculate_camera_bandwidth()
|
||||||
storage.reduce_storage_consumption()
|
storage.reduce_storage_consumption()
|
||||||
|
assert Recordings.get(Recordings.id == rec_k_id)
|
||||||
retained = {"segment-0", "segment-1", "segment-2"}
|
assert Recordings.get(Recordings.id == rec_k2_id)
|
||||||
remaining = {r.id for r in Recordings.select(Recordings.id)}
|
assert Recordings.get(Recordings.id == rec_k3_id)
|
||||||
on_disk = {rec_id for rec_id, path in paths.items() if os.path.exists(path)}
|
|
||||||
self.assertEqual(remaining, retained)
|
|
||||||
self.assertEqual(on_disk, retained)
|
|
||||||
self.assertFalse(storage.retention_unmet)
|
|
||||||
|
|
||||||
def test_unmet_retention_sets_the_live_flag(self):
|
def test_unmet_retention_sets_the_live_flag(self):
|
||||||
config = FrigateConfig(**self.minimal_config)
|
config = FrigateConfig(**self.minimal_config)
|
||||||
|
|||||||
@@ -1,36 +0,0 @@
|
|||||||
import unittest
|
|
||||||
|
|
||||||
import cv2
|
|
||||||
import numpy as np
|
|
||||||
|
|
||||||
from frigate.util.image import get_snapshot_bytes
|
|
||||||
|
|
||||||
|
|
||||||
class TestSnapshotBytes(unittest.TestCase):
|
|
||||||
def snapshot_shape(self, height: int, crop: bool = False) -> tuple[int, int]:
|
|
||||||
jpg, _ = get_snapshot_bytes(
|
|
||||||
np.zeros((90, 160, 3), np.uint8),
|
|
||||||
0.0,
|
|
||||||
"jpg",
|
|
||||||
crop=crop,
|
|
||||||
height=height,
|
|
||||||
label="person",
|
|
||||||
box=(70, 35, 90, 55),
|
|
||||||
score=None,
|
|
||||||
area=None,
|
|
||||||
attributes=None,
|
|
||||||
color=(255, 255, 255),
|
|
||||||
)
|
|
||||||
image = cv2.imdecode(np.frombuffer(jpg, np.uint8), cv2.IMREAD_COLOR)
|
|
||||||
return image.shape[:2]
|
|
||||||
|
|
||||||
def test_height_capped_at_frame_height(self):
|
|
||||||
self.assertEqual(self.snapshot_shape(45), (45, 80))
|
|
||||||
self.assertEqual(self.snapshot_shape(5000), (90, 160))
|
|
||||||
|
|
||||||
def test_crop_can_scale_up_to_frame_height(self):
|
|
||||||
self.assertEqual(self.snapshot_shape(5000, crop=True)[0], 90)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
@@ -517,8 +517,6 @@ class TestMaterializeForWs(unittest.TestCase):
|
|||||||
"garage": {"camera_fps": 5.0, "pid": 1236},
|
"garage": {"camera_fps": 5.0, "pid": 1236},
|
||||||
},
|
},
|
||||||
"detectors": {"cpu": {"detection_start": 0.0, "inference_speed": 10}},
|
"detectors": {"cpu": {"detection_start": 0.0, "inference_speed": 10}},
|
||||||
"cpu_usages": {"1234": {"cpu": "1.0", "cmdline": "ffmpeg -i rtsp://"}},
|
|
||||||
"bandwidth_usages": {"1234": {"bandwidth": 1.0}},
|
|
||||||
"service": {"uptime": 12345, "version": "0.16.0"},
|
"service": {"uptime": 12345, "version": "0.16.0"},
|
||||||
"camera_fps": 15.0,
|
"camera_fps": 15.0,
|
||||||
"detection_fps": 6.0,
|
"detection_fps": 6.0,
|
||||||
@@ -542,17 +540,6 @@ class TestMaterializeForWs(unittest.TestCase):
|
|||||||
self.assertIn("detectors", inner)
|
self.assertIn("detectors", inner)
|
||||||
self.assertIn("service", inner)
|
self.assertIn("service", inner)
|
||||||
|
|
||||||
def test_stats_non_admin_gets_no_cmdline(self):
|
|
||||||
for role in ("viewer", "house_only"):
|
|
||||||
message = self._materialize(_ws(role), "stats", self._stats_payload())
|
|
||||||
inner = json.loads(json.loads(message)["payload"]) # type: ignore[arg-type]
|
|
||||||
self.assertEqual(inner["cpu_usages"], {"1234": {"cpu": "1.0"}})
|
|
||||||
self.assertNotIn("bandwidth_usages", inner)
|
|
||||||
|
|
||||||
message = self._materialize(_ws("viewer"), "stats", self._stats_payload())
|
|
||||||
inner = json.loads(json.loads(message)["payload"]) # type: ignore[arg-type]
|
|
||||||
self.assertIn("garage", inner["cameras"])
|
|
||||||
|
|
||||||
def test_stats_restricted_with_no_allowed_cameras_still_sends_aggregates(self):
|
def test_stats_restricted_with_no_allowed_cameras_still_sends_aggregates(self):
|
||||||
"""A restricted role whose allow-list contains only nonexistent cameras
|
"""A restricted role whose allow-list contains only nonexistent cameras
|
||||||
still gets the global aggregates and service block."""
|
still gets the global aggregates and service block."""
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ from frigate.config import (
|
|||||||
)
|
)
|
||||||
from frigate.const import CLIPS_DIR, REPLAY_CAMERA_PREFIX, THUMB_DIR
|
from frigate.const import CLIPS_DIR, REPLAY_CAMERA_PREFIX, THUMB_DIR
|
||||||
from frigate.detectors.detector_config import ModelConfig
|
from frigate.detectors.detector_config import ModelConfig
|
||||||
from frigate.review.severity import get_review_severity
|
|
||||||
from frigate.review.types import SeverityEnum
|
from frigate.review.types import SeverityEnum
|
||||||
from frigate.util.builtin import sanitize_float
|
from frigate.util.builtin import sanitize_float
|
||||||
from frigate.util.image import (
|
from frigate.util.image import (
|
||||||
@@ -70,8 +69,6 @@ class TrackedObject:
|
|||||||
self.new_zone_entered: bool = False
|
self.new_zone_entered: bool = False
|
||||||
self.attributes: dict[str, float] = defaultdict(float)
|
self.attributes: dict[str, float] = defaultdict(float)
|
||||||
self.false_positive = True
|
self.false_positive = True
|
||||||
# highest review severity the object qualified for on any frame
|
|
||||||
self.max_severity: SeverityEnum | None = None
|
|
||||||
self.has_clip = False
|
self.has_clip = False
|
||||||
self.has_snapshot = False
|
self.has_snapshot = False
|
||||||
self.top_score = self.computed_score = 0.0
|
self.top_score = self.computed_score = 0.0
|
||||||
@@ -88,6 +85,36 @@ class TrackedObject:
|
|||||||
self.path_data: list[tuple[Any, float]] = []
|
self.path_data: list[tuple[Any, float]] = []
|
||||||
self.previous = self.to_dict()
|
self.previous = self.to_dict()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def max_severity(self) -> str | None:
|
||||||
|
review_config = self.camera_config.review
|
||||||
|
|
||||||
|
if (
|
||||||
|
self.camera_config.review.alerts.enabled
|
||||||
|
and self.obj_data["label"] in review_config.alerts.labels
|
||||||
|
and (
|
||||||
|
not review_config.alerts.required_zones
|
||||||
|
or set(self.entered_zones) & set(review_config.alerts.required_zones)
|
||||||
|
)
|
||||||
|
):
|
||||||
|
return SeverityEnum.alert
|
||||||
|
|
||||||
|
if (
|
||||||
|
self.camera_config.review.detections.enabled
|
||||||
|
and (
|
||||||
|
not review_config.detections.labels
|
||||||
|
or self.obj_data["label"] in review_config.detections.labels
|
||||||
|
)
|
||||||
|
and (
|
||||||
|
not review_config.detections.required_zones
|
||||||
|
or set(self.entered_zones)
|
||||||
|
& set(review_config.detections.required_zones)
|
||||||
|
)
|
||||||
|
):
|
||||||
|
return SeverityEnum.detection
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
def _is_false_positive(self) -> bool:
|
def _is_false_positive(self) -> bool:
|
||||||
# once a true positive, always a true positive
|
# once a true positive, always a true positive
|
||||||
if not self.false_positive:
|
if not self.false_positive:
|
||||||
@@ -359,28 +386,6 @@ class TrackedObject:
|
|||||||
|
|
||||||
self.obj_data.update(obj_data)
|
self.obj_data.update(obj_data)
|
||||||
self.current_zones = current_zones
|
self.current_zones = current_zones
|
||||||
|
|
||||||
# use the same per-frame rules as review segments, so max_severity is
|
|
||||||
# never alert or detection unless the object could create that review
|
|
||||||
severity = get_review_severity(
|
|
||||||
self.camera_config,
|
|
||||||
label=self.obj_data["label"],
|
|
||||||
current_zones=current_zones,
|
|
||||||
false_positive=self.false_positive,
|
|
||||||
detected=detected,
|
|
||||||
position_changes=self.obj_data["position_changes"],
|
|
||||||
motionless_count=self.obj_data["motionless_count"],
|
|
||||||
pending_loitering=self.pending_loitering,
|
|
||||||
)
|
|
||||||
|
|
||||||
if severity != self.max_severity and (
|
|
||||||
severity == SeverityEnum.alert
|
|
||||||
or (severity == SeverityEnum.detection and self.max_severity is None)
|
|
||||||
):
|
|
||||||
self.max_severity = severity
|
|
||||||
# max_severity is saved with the event, so publish the change
|
|
||||||
significant_change = True
|
|
||||||
|
|
||||||
logger.debug(
|
logger.debug(
|
||||||
f"{self.camera_config.name}: Updating {obj_data['id']}: thumb update? {thumb_update}, significant change? {significant_change}, path update? {path_update}, autotracker update? {autotracker_update} "
|
f"{self.camera_config.name}: Updating {obj_data['id']}: thumb update? {thumb_update}, significant change? {significant_change}, path update? {path_update}, autotracker update? {autotracker_update} "
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -131,34 +131,6 @@ def clean_camera_user_pass(line: str) -> str:
|
|||||||
return re.sub(REGEX_CREDENTIAL_QUERY_PARAM, r"\1*", line)
|
return re.sub(REGEX_CREDENTIAL_QUERY_PARAM, r"\1*", line)
|
||||||
|
|
||||||
|
|
||||||
def scope_stats_for_non_admin(
|
|
||||||
stats: dict[str, Any], allowed_cameras: set[str]
|
|
||||||
) -> dict[str, Any]:
|
|
||||||
"""Return a copy of stats limited to allowed_cameras, without process cmdlines.
|
|
||||||
|
|
||||||
cmdline can leak camera URLs and paths. cpu and mem stay so client-side
|
|
||||||
problem heuristics still work. bandwidth_usages is keyed by pid and can't
|
|
||||||
be scoped to cameras.
|
|
||||||
"""
|
|
||||||
scoped = {**stats}
|
|
||||||
scoped.pop("bandwidth_usages", None)
|
|
||||||
|
|
||||||
if stats.get("cameras") is not None:
|
|
||||||
scoped["cameras"] = {
|
|
||||||
name: data
|
|
||||||
for name, data in stats["cameras"].items()
|
|
||||||
if name in allowed_cameras
|
|
||||||
}
|
|
||||||
|
|
||||||
if stats.get("cpu_usages") is not None:
|
|
||||||
scoped["cpu_usages"] = {
|
|
||||||
pid: {k: v for k, v in usage.items() if k != "cmdline"}
|
|
||||||
for pid, usage in stats["cpu_usages"].items()
|
|
||||||
}
|
|
||||||
|
|
||||||
return scoped
|
|
||||||
|
|
||||||
|
|
||||||
def _mask_userinfo(match: re.Match[str]) -> str:
|
def _mask_userinfo(match: re.Match[str]) -> str:
|
||||||
# A credential key in the userinfo means a query password holds "@" or a
|
# A credential key in the userinfo means a query password holds "@" or a
|
||||||
# password holds a query key. Neither split is safe, so mask the whole URL.
|
# password holds a query key. Neither split is safe, so mask the whole URL.
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
"""Utilities for cleaning up camera data from database and filesystem."""
|
"""Utilities for cleaning up camera data from database and filesystem."""
|
||||||
|
|
||||||
import glob
|
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import shutil
|
import shutil
|
||||||
|
|
||||||
from frigate.const import CLIPS_DIR, RECORD_DIR, SUB_CACHE_TAG, THUMB_DIR
|
from frigate.const import CLIPS_DIR, RECORD_DIR, THUMB_DIR
|
||||||
from frigate.models import (
|
from frigate.models import (
|
||||||
Event,
|
Event,
|
||||||
Export,
|
Export,
|
||||||
@@ -113,18 +112,12 @@ def cleanup_camera_files(
|
|||||||
export_paths: Optional list of export file paths to remove
|
export_paths: Optional list of export file paths to remove
|
||||||
"""
|
"""
|
||||||
dirs_to_clean = [
|
dirs_to_clean = [
|
||||||
|
os.path.join(RECORD_DIR, camera_name),
|
||||||
|
os.path.join(CLIPS_DIR, camera_name),
|
||||||
os.path.join(THUMB_DIR, camera_name),
|
os.path.join(THUMB_DIR, camera_name),
|
||||||
os.path.join(CLIPS_DIR, "previews", camera_name),
|
os.path.join(CLIPS_DIR, "previews", camera_name),
|
||||||
os.path.join(CLIPS_DIR, "lpr", camera_name),
|
|
||||||
os.path.join(CLIPS_DIR, "triggers", camera_name),
|
|
||||||
]
|
]
|
||||||
|
|
||||||
# recordings live at RECORD_DIR/<date>/<hour>/<camera>
|
|
||||||
for name in (camera_name, f"{camera_name}{SUB_CACHE_TAG}"):
|
|
||||||
dirs_to_clean.extend(
|
|
||||||
glob.glob(os.path.join(glob.escape(RECORD_DIR), "*", "*", name))
|
|
||||||
)
|
|
||||||
|
|
||||||
for dir_path in dirs_to_clean:
|
for dir_path in dirs_to_clean:
|
||||||
if os.path.exists(dir_path):
|
if os.path.exists(dir_path):
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -414,6 +414,7 @@ def collect_state_classification_examples(
|
|||||||
cameras: Dict mapping camera names to normalized crop coordinates [x1, y1, x2, y2] (0-1)
|
cameras: Dict mapping camera names to normalized crop coordinates [x1, y1, x2, y2] (0-1)
|
||||||
"""
|
"""
|
||||||
model_name = model_name.strip()
|
model_name = model_name.strip()
|
||||||
|
dataset_dir = os.path.join(CLIPS_DIR, model_name, "dataset")
|
||||||
|
|
||||||
# Step 1: Get review items for the cameras
|
# Step 1: Get review items for the cameras
|
||||||
camera_names = list(cameras.keys())
|
camera_names = list(cameras.keys())
|
||||||
@@ -428,31 +429,29 @@ def collect_state_classification_examples(
|
|||||||
logger.warning(f"No review items found for cameras: {camera_names}")
|
logger.warning(f"No review items found for cameras: {camera_names}")
|
||||||
return
|
return
|
||||||
|
|
||||||
|
# The temp directory is only created when there are review_items.
|
||||||
|
temp_dir = os.path.join(dataset_dir, "temp")
|
||||||
|
os.makedirs(temp_dir, exist_ok=True)
|
||||||
|
|
||||||
# Step 2: Create balanced timestamp selection (100 samples)
|
# Step 2: Create balanced timestamp selection (100 samples)
|
||||||
timestamps = _select_balanced_timestamps(review_items, target_count=100)
|
timestamps = _select_balanced_timestamps(review_items, target_count=100)
|
||||||
|
|
||||||
with tempfile.TemporaryDirectory() as temp_dir:
|
# Step 3: Extract keyframes from recordings with crops applied
|
||||||
# Step 3: Extract keyframes from recordings with crops applied
|
keyframes = _extract_keyframes(
|
||||||
keyframes = _extract_keyframes(
|
"/usr/lib/ffmpeg/8.0/bin/ffmpeg", timestamps, temp_dir, cameras
|
||||||
"/usr/lib/ffmpeg/8.0/bin/ffmpeg", timestamps, temp_dir, cameras
|
)
|
||||||
)
|
|
||||||
|
|
||||||
# Step 4: Select 24 most visually distinct images (they're already cropped)
|
# Step 4: Select 24 most visually distinct images (they're already cropped)
|
||||||
distinct_images = _select_distinct_images(keyframes, target_count=24)
|
distinct_images = _select_distinct_images(keyframes, target_count=24)
|
||||||
|
|
||||||
# Step 5: Save to train directory for later classification
|
# Step 5: Save to train directory for later classification
|
||||||
_save_train_examples(model_name, distinct_images)
|
|
||||||
|
|
||||||
|
|
||||||
def _save_train_examples(model_name: str, image_paths: list[str]) -> int:
|
|
||||||
"""Replace the model's train directory with the given images."""
|
|
||||||
train_dir = os.path.join(CLIPS_DIR, model_name, "train")
|
train_dir = os.path.join(CLIPS_DIR, model_name, "train")
|
||||||
if os.path.exists(train_dir):
|
if os.path.exists(train_dir):
|
||||||
shutil.rmtree(train_dir)
|
shutil.rmtree(train_dir)
|
||||||
os.makedirs(train_dir, exist_ok=True)
|
os.makedirs(train_dir, exist_ok=True)
|
||||||
|
|
||||||
saved_count = 0
|
saved_count = 0
|
||||||
for idx, image_path in enumerate(image_paths):
|
for idx, image_path in enumerate(distinct_images):
|
||||||
dest_path = os.path.join(train_dir, f"example_{idx:03d}.jpg")
|
dest_path = os.path.join(train_dir, f"example_{idx:03d}.jpg")
|
||||||
try:
|
try:
|
||||||
img = cv2.imread(image_path)
|
img = cv2.imread(image_path)
|
||||||
@@ -463,7 +462,10 @@ def _save_train_examples(model_name: str, image_paths: list[str]) -> int:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to save image {image_path}: {e}")
|
logger.error(f"Failed to save image {image_path}: {e}")
|
||||||
|
|
||||||
return saved_count
|
try:
|
||||||
|
shutil.rmtree(temp_dir)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"Failed to clean up temp directory: {e}")
|
||||||
|
|
||||||
|
|
||||||
def _select_balanced_timestamps(
|
def _select_balanced_timestamps(
|
||||||
@@ -522,20 +524,13 @@ def _select_balanced_timestamps(
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
# Sample more from larger groups. Zero-length items and timestamps too
|
# If we don't have enough, sample more from larger groups
|
||||||
# close to an existing one never add a sample, so attempts are capped.
|
while len(timestamps) < target_count and len(timestamps) < len(review_items):
|
||||||
max_attempts = target_count * 10
|
|
||||||
attempts = 0
|
|
||||||
while (
|
|
||||||
len(timestamps) < target_count
|
|
||||||
and len(timestamps) < len(review_items)
|
|
||||||
and attempts < max_attempts
|
|
||||||
):
|
|
||||||
for group_items in grouped.values():
|
for group_items in grouped.values():
|
||||||
if len(timestamps) >= target_count or attempts >= max_attempts:
|
if len(timestamps) >= target_count:
|
||||||
break
|
break
|
||||||
|
|
||||||
attempts += 1
|
# Pick a random item not already sampled
|
||||||
item = random.choice(group_items)
|
item = random.choice(group_items)
|
||||||
duration = item.end_time - item.start_time
|
duration = item.end_time - item.start_time
|
||||||
if duration <= 0:
|
if duration <= 0:
|
||||||
@@ -775,6 +770,9 @@ def collect_object_classification_examples(
|
|||||||
label: Object label to collect (e.g., "person", "car")
|
label: Object label to collect (e.g., "person", "car")
|
||||||
"""
|
"""
|
||||||
model_name = model_name.strip()
|
model_name = model_name.strip()
|
||||||
|
dataset_dir = os.path.join(CLIPS_DIR, model_name, "dataset")
|
||||||
|
temp_dir = os.path.join(dataset_dir, "temp")
|
||||||
|
os.makedirs(temp_dir, exist_ok=True)
|
||||||
|
|
||||||
# Step 1: Query events for the specified label and cameras
|
# Step 1: Query events for the specified label and cameras
|
||||||
events = list(
|
events = list(
|
||||||
@@ -796,21 +794,41 @@ def collect_object_classification_examples(
|
|||||||
selected_ids = {e.id for e in selected_events}
|
selected_ids = {e.id for e in selected_events}
|
||||||
remaining_events = [e for e in events if e.id not in selected_ids]
|
remaining_events = [e for e in events if e.id not in selected_ids]
|
||||||
random.shuffle(remaining_events)
|
random.shuffle(remaining_events)
|
||||||
|
thumbnails = _extract_event_thumbnails(
|
||||||
|
selected_events + remaining_events, temp_dir, target_count=100
|
||||||
|
)
|
||||||
|
logger.debug(f"Successfully extracted {len(thumbnails)} thumbnails")
|
||||||
|
|
||||||
with tempfile.TemporaryDirectory() as temp_dir:
|
# Step 4: Select 24 most visually distinct thumbnails
|
||||||
thumbnails = _extract_event_thumbnails(
|
distinct_images = _select_distinct_images(thumbnails, target_count=24)
|
||||||
selected_events + remaining_events, temp_dir, target_count=100
|
logger.debug(f"Selected {len(distinct_images)} distinct images")
|
||||||
)
|
|
||||||
logger.debug(f"Successfully extracted {len(thumbnails)} thumbnails")
|
|
||||||
|
|
||||||
# Step 4: Select 24 most visually distinct thumbnails
|
# Step 5: Save to train directory for later classification
|
||||||
distinct_images = _select_distinct_images(thumbnails, target_count=24)
|
train_dir = os.path.join(CLIPS_DIR, model_name, "train")
|
||||||
logger.debug(f"Selected {len(distinct_images)} distinct images")
|
if os.path.exists(train_dir):
|
||||||
|
shutil.rmtree(train_dir)
|
||||||
|
os.makedirs(train_dir, exist_ok=True)
|
||||||
|
|
||||||
# Step 5: Save to train directory for later classification
|
saved_count = 0
|
||||||
saved_count = _save_train_examples(model_name, distinct_images)
|
for idx, image_path in enumerate(distinct_images):
|
||||||
|
dest_path = os.path.join(train_dir, f"example_{idx:03d}.jpg")
|
||||||
|
try:
|
||||||
|
img = cv2.imread(image_path)
|
||||||
|
|
||||||
logger.debug(f"Successfully collected {saved_count} classification examples")
|
if img is not None:
|
||||||
|
cv2.imwrite(dest_path, img)
|
||||||
|
saved_count += 1
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to save image {image_path}: {e}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
shutil.rmtree(temp_dir)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"Failed to clean up temp directory: {e}")
|
||||||
|
|
||||||
|
logger.debug(
|
||||||
|
f"Successfully collected {saved_count} classification examples in {train_dir}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _select_balanced_events(
|
def _select_balanced_events(
|
||||||
|
|||||||
@@ -1191,11 +1191,7 @@ def apply_section_update(camera_config, section: str, update: dict) -> str | Non
|
|||||||
Returns:
|
Returns:
|
||||||
None on success, or an error message string on failure.
|
None on success, or an error message string on failure.
|
||||||
"""
|
"""
|
||||||
from frigate.config.config import (
|
from frigate.config.config import RuntimeFilterConfig, RuntimeMotionConfig
|
||||||
FilterConfig,
|
|
||||||
RuntimeFilterConfig,
|
|
||||||
RuntimeMotionConfig,
|
|
||||||
)
|
|
||||||
|
|
||||||
current = getattr(camera_config, section, None)
|
current = getattr(camera_config, section, None)
|
||||||
if current is None:
|
if current is None:
|
||||||
@@ -1228,9 +1224,6 @@ def apply_section_update(camera_config, section: str, update: dict) -> str | Non
|
|||||||
except AttributeError:
|
except AttributeError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
for label in new_objects.track:
|
|
||||||
new_objects.filters.setdefault(label, FilterConfig())
|
|
||||||
|
|
||||||
# Rebuild RuntimeFilterConfig with merged global + per-object masks
|
# Rebuild RuntimeFilterConfig with merged global + per-object masks
|
||||||
for obj_name, filt in new_objects.filters.items():
|
for obj_name, filt in new_objects.filters.items():
|
||||||
merged_mask = dict(filt.mask)
|
merged_mask = dict(filt.mask)
|
||||||
|
|||||||
+17
-21
@@ -85,35 +85,28 @@ class ModelDownloader:
|
|||||||
)
|
)
|
||||||
|
|
||||||
def _download_models(self):
|
def _download_models(self):
|
||||||
try:
|
|
||||||
self._download_files()
|
|
||||||
finally:
|
|
||||||
self.download_complete.set()
|
|
||||||
self.requestor.stop()
|
|
||||||
|
|
||||||
def _download_files(self):
|
|
||||||
for file_name in self.file_names:
|
for file_name in self.file_names:
|
||||||
path = os.path.join(self.download_path, file_name)
|
path = os.path.join(self.download_path, file_name)
|
||||||
lock_path = f"{path}.lock"
|
lock_path = f"{path}.lock"
|
||||||
lock = FileLock(lock_path, cleanup_stale_on_init=True)
|
lock = FileLock(lock_path, cleanup_stale_on_init=True)
|
||||||
|
|
||||||
if not os.path.exists(path):
|
if not os.path.exists(path):
|
||||||
try:
|
with lock:
|
||||||
with lock:
|
if not os.path.exists(path):
|
||||||
if not os.path.exists(path):
|
try:
|
||||||
self.download_func(path)
|
self.download_func(path)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self._report_failure(file_name, _first_line(e))
|
self._report_failure(file_name, _first_line(e))
|
||||||
self._send_state(file_name, ModelStatusTypesEnum.error)
|
self._send_state(file_name, ModelStatusTypesEnum.error)
|
||||||
raise
|
raise
|
||||||
|
|
||||||
if not os.path.exists(path):
|
if not os.path.exists(path):
|
||||||
self._report_failure(
|
self._report_failure(
|
||||||
file_name,
|
file_name,
|
||||||
last_download_error.pop(path, "download failed"),
|
last_download_error.pop(path, "download failed"),
|
||||||
)
|
)
|
||||||
self._send_state(file_name, ModelStatusTypesEnum.error)
|
self._send_state(file_name, ModelStatusTypesEnum.error)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
self._resolve_failure(file_name)
|
self._resolve_failure(file_name)
|
||||||
self._send_state(file_name, ModelStatusTypesEnum.downloaded)
|
self._send_state(file_name, ModelStatusTypesEnum.downloaded)
|
||||||
@@ -121,6 +114,9 @@ class ModelDownloader:
|
|||||||
if self.complete_func:
|
if self.complete_func:
|
||||||
self.complete_func()
|
self.complete_func()
|
||||||
|
|
||||||
|
self.requestor.stop()
|
||||||
|
self.download_complete.set()
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def download_from_url(url: str, save_path: str, silent: bool = False) -> Path:
|
def download_from_url(url: str, save_path: str, silent: bool = False) -> Path:
|
||||||
temporary_filename = Path(save_path).with_name(
|
temporary_filename = Path(save_path).with_name(
|
||||||
|
|||||||
+4
-40
@@ -3,9 +3,7 @@
|
|||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
from collections.abc import Iterator, Mapping
|
from collections.abc import Mapping
|
||||||
from contextlib import contextmanager
|
|
||||||
from contextvars import ContextVar
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Annotated, Any
|
from typing import Annotated, Any
|
||||||
|
|
||||||
@@ -248,35 +246,6 @@ def apply_config_env_vars(values: Mapping[str, object]) -> None:
|
|||||||
reload_sources(warn=False)
|
reload_sources(warn=False)
|
||||||
|
|
||||||
|
|
||||||
_CANDIDATE_ENV_VARS: ContextVar[dict[str, str] | None] = ContextVar(
|
|
||||||
"candidate_env_vars", default=None
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@contextmanager
|
|
||||||
def candidate_env_vars(values: object) -> Iterator[None]:
|
|
||||||
"""Resolve placeholders against a candidate config's environment_vars.
|
|
||||||
|
|
||||||
Its FRIGATE_ keys replace the installed block at the same lowest
|
|
||||||
precedence. Nothing is installed or exported to os.environ.
|
|
||||||
"""
|
|
||||||
merged = {
|
|
||||||
str(key): str(value)
|
|
||||||
for key, value in (values.items() if isinstance(values, Mapping) else ())
|
|
||||||
if str(key).startswith("FRIGATE_")
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, source in _SOURCES:
|
|
||||||
if source is not _CONFIG_ENV_VARS:
|
|
||||||
merged.update(source)
|
|
||||||
|
|
||||||
token = _CANDIDATE_ENV_VARS.set(merged)
|
|
||||||
try:
|
|
||||||
yield
|
|
||||||
finally:
|
|
||||||
_CANDIDATE_ENV_VARS.reset(token)
|
|
||||||
|
|
||||||
|
|
||||||
# Matches a FRIGATE_* identifier following an opening brace.
|
# Matches a FRIGATE_* identifier following an opening brace.
|
||||||
_FRIGATE_IDENT_RE = re.compile(r"FRIGATE_[A-Za-z0-9_]+")
|
_FRIGATE_IDENT_RE = re.compile(r"FRIGATE_[A-Za-z0-9_]+")
|
||||||
|
|
||||||
@@ -289,8 +258,7 @@ def substitute_frigate_vars(value: str) -> str:
|
|||||||
(e.g. ffmpeg `%{localtime\\:...}` expressions) untouched:
|
(e.g. ffmpeg `%{localtime\\:...}` expressions) untouched:
|
||||||
|
|
||||||
* `{{` and `}}` collapse to literal `{` / `}` (the documented escape).
|
* `{{` and `}}` collapse to literal `{` / `}` (the documented escape).
|
||||||
* `{FRIGATE_NAME}` is replaced from `FRIGATE_ENV_VARS`, or from the
|
* `{FRIGATE_NAME}` is replaced from `FRIGATE_ENV_VARS`; an unknown name
|
||||||
sources set by `candidate_env_vars`; an unknown name
|
|
||||||
raises `UnknownVariableError` to preserve the existing "Invalid
|
raises `UnknownVariableError` to preserve the existing "Invalid
|
||||||
substitution" error path.
|
substitution" error path.
|
||||||
* A `{` that begins `{FRIGATE_` but is not a well-formed
|
* A `{` that begins `{FRIGATE_` but is not a well-formed
|
||||||
@@ -300,10 +268,6 @@ def substitute_frigate_vars(value: str) -> str:
|
|||||||
error.
|
error.
|
||||||
* Any other `{` or `}` is treated as a literal and passed through.
|
* Any other `{` or `}` is treated as a literal and passed through.
|
||||||
"""
|
"""
|
||||||
env_vars = _CANDIDATE_ENV_VARS.get()
|
|
||||||
if env_vars is None:
|
|
||||||
env_vars = FRIGATE_ENV_VARS
|
|
||||||
|
|
||||||
out: list[str] = []
|
out: list[str] = []
|
||||||
i = 0
|
i = 0
|
||||||
n = len(value)
|
n = len(value)
|
||||||
@@ -324,12 +288,12 @@ def substitute_frigate_vars(value: str) -> str:
|
|||||||
and value[ident_match.end()] == "}"
|
and value[ident_match.end()] == "}"
|
||||||
):
|
):
|
||||||
key = ident_match.group(0)
|
key = ident_match.group(0)
|
||||||
if key not in env_vars:
|
if key not in FRIGATE_ENV_VARS:
|
||||||
raise UnknownVariableError(
|
raise UnknownVariableError(
|
||||||
f"{key} is not defined in the environment, "
|
f"{key} is not defined in the environment, "
|
||||||
"secrets.yaml, or the environment_vars config"
|
"secrets.yaml, or the environment_vars config"
|
||||||
)
|
)
|
||||||
out.append(env_vars[key])
|
out.append(FRIGATE_ENV_VARS[key])
|
||||||
i = ident_match.end() + 1
|
i = ident_match.end() + 1
|
||||||
continue
|
continue
|
||||||
# Looks like a FRIGATE placeholder but is malformed
|
# Looks like a FRIGATE placeholder but is malformed
|
||||||
|
|||||||
@@ -262,15 +262,11 @@ def delete_event_snapshot(event: Event) -> bool:
|
|||||||
def delete_event_thumbnail(event: Event) -> bool:
|
def delete_event_thumbnail(event: Event) -> bool:
|
||||||
if event.thumbnail:
|
if event.thumbnail:
|
||||||
return True
|
return True
|
||||||
|
else:
|
||||||
try:
|
|
||||||
Path(os.path.join(THUMB_DIR, event.camera, f"{event.id}.webp")).unlink(
|
Path(os.path.join(THUMB_DIR, event.camera, f"{event.id}.webp")).unlink(
|
||||||
missing_ok=True
|
missing_ok=True
|
||||||
)
|
)
|
||||||
except OSError:
|
return True
|
||||||
return False
|
|
||||||
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
### Training Images
|
### Training Images
|
||||||
|
|||||||
@@ -458,7 +458,6 @@ def get_snapshot_bytes(
|
|||||||
best_frame = best_frame[region[1] : region[3], region[0] : region[2]]
|
best_frame = best_frame[region[1] : region[3], region[0] : region[2]]
|
||||||
|
|
||||||
if height:
|
if height:
|
||||||
height = min(height, frame.shape[0])
|
|
||||||
width = int(height * best_frame.shape[1] / best_frame.shape[0])
|
width = int(height * best_frame.shape[1] / best_frame.shape[0])
|
||||||
best_frame = cv2.resize(
|
best_frame = cv2.resize(
|
||||||
best_frame, dsize=(width, height), interpolation=cv2.INTER_AREA
|
best_frame, dsize=(width, height), interpolation=cv2.INTER_AREA
|
||||||
@@ -1276,7 +1275,7 @@ def run_ffmpeg_snapshot(
|
|||||||
|
|
||||||
if height is not None:
|
if height is not None:
|
||||||
ffmpeg_cmd.insert(-3, "-vf")
|
ffmpeg_cmd.insert(-3, "-vf")
|
||||||
ffmpeg_cmd.insert(-3, f"scale=-1:'min({height},ih)'")
|
ffmpeg_cmd.insert(-3, f"scale=-1:{height}")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
process = sp.run(
|
process = sp.run(
|
||||||
@@ -1299,17 +1298,11 @@ def get_image_from_recording(
|
|||||||
relative_frame_time: float,
|
relative_frame_time: float,
|
||||||
codec: str,
|
codec: str,
|
||||||
height: int | None = None,
|
height: int | None = None,
|
||||||
timeout: int = 30,
|
|
||||||
) -> Any | None:
|
) -> Any | None:
|
||||||
"""retrieve a frame from given time in recording file."""
|
"""retrieve a frame from given time in recording file."""
|
||||||
|
|
||||||
image_data, _ = run_ffmpeg_snapshot(
|
image_data, _ = run_ffmpeg_snapshot(
|
||||||
ffmpeg,
|
ffmpeg, file_path, codec, seek_time=relative_frame_time, height=height
|
||||||
file_path,
|
|
||||||
codec,
|
|
||||||
seek_time=relative_frame_time,
|
|
||||||
height=height,
|
|
||||||
timeout=timeout,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
return image_data
|
return image_data
|
||||||
|
|||||||
@@ -91,8 +91,7 @@ def get_categorized_object_names(
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
for label in model_config.object_config.objects:
|
for label in model_config.object_config.objects:
|
||||||
if label in tracked_objects:
|
names.setdefault(label, set()).update(categories)
|
||||||
names.setdefault(label, set()).update(categories)
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
label: sorted(label_names)
|
label: sorted(label_names)
|
||||||
|
|||||||
+14
-31
@@ -30,11 +30,7 @@ from frigate.const import (
|
|||||||
SHM_FRAMES_VAR,
|
SHM_FRAMES_VAR,
|
||||||
)
|
)
|
||||||
from frigate.util.builtin import clean_camera_user_pass, escape_special_characters
|
from frigate.util.builtin import clean_camera_user_pass, escape_special_characters
|
||||||
from frigate.util.env import (
|
from frigate.util.env import UnknownVariableError, substitute_frigate_vars
|
||||||
UnknownVariableError,
|
|
||||||
candidate_env_vars,
|
|
||||||
substitute_frigate_vars,
|
|
||||||
)
|
|
||||||
from frigate.util.live_streams import is_valid_go2rtc_stream_name
|
from frigate.util.live_streams import is_valid_go2rtc_stream_name
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -1232,27 +1228,16 @@ class Go2rtcStreamIssue(str, Enum):
|
|||||||
invalid_name = "invalid_name"
|
invalid_name = "invalid_name"
|
||||||
|
|
||||||
|
|
||||||
def _resolve_running_frigate_vars(source: str) -> str | None:
|
|
||||||
try:
|
|
||||||
return substitute_frigate_vars(source)
|
|
||||||
except ValueError:
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def find_restricted_go2rtc_stream_changes(
|
def find_restricted_go2rtc_stream_changes(
|
||||||
old_streams: dict[str, Any] | None,
|
old_streams: dict[str, Any] | None, new_streams: dict[str, Any] | None
|
||||||
new_streams: dict[str, Any] | None,
|
|
||||||
new_env_vars: object,
|
|
||||||
) -> dict[str, Go2rtcStreamIssue]:
|
) -> dict[str, Go2rtcStreamIssue]:
|
||||||
"""Return the go2rtc streams with new sources that must be rejected.
|
"""Return the go2rtc streams with new sources that must be rejected.
|
||||||
|
|
||||||
Used when the config is changed through the API. Every source must resolve
|
Used when the config is changed through the API. A source that is already
|
||||||
its {FRIGATE_*} placeholders against the new config's environment_vars. A
|
in the saved config for the same stream is left alone, so streams the
|
||||||
source that is already in the saved config for the same stream and
|
operator configured on disk keep working; any other source must resolve
|
||||||
resolves to the same value as it does now is left alone, so streams the
|
its {FRIGATE_*} placeholders and pass `is_restricted_go2rtc_api_source`.
|
||||||
operator configured on disk keep working; any other source must pass
|
New stream names must pass `is_valid_go2rtc_stream_name`.
|
||||||
`is_restricted_go2rtc_api_source`. New stream names must pass
|
|
||||||
`is_valid_go2rtc_stream_name`.
|
|
||||||
"""
|
"""
|
||||||
old_streams = old_streams if isinstance(old_streams, dict) else {}
|
old_streams = old_streams if isinstance(old_streams, dict) else {}
|
||||||
new_streams = new_streams if isinstance(new_streams, dict) else {}
|
new_streams = new_streams if isinstance(new_streams, dict) else {}
|
||||||
@@ -1266,17 +1251,20 @@ def find_restricted_go2rtc_stream_changes(
|
|||||||
existing = _go2rtc_stream_sources(old_streams.get(name))
|
existing = _go2rtc_stream_sources(old_streams.get(name))
|
||||||
|
|
||||||
for source in _go2rtc_stream_sources(stream):
|
for source in _go2rtc_stream_sources(stream):
|
||||||
|
if source in existing:
|
||||||
|
continue
|
||||||
|
|
||||||
if not isinstance(source, str):
|
if not isinstance(source, str):
|
||||||
# the map form is only usable with arbitrary exec enabled
|
# the map form is only usable with arbitrary exec enabled
|
||||||
if source in existing or is_go2rtc_arbitrary_exec_allowed():
|
if is_go2rtc_arbitrary_exec_allowed():
|
||||||
continue
|
continue
|
||||||
issues[name] = Go2rtcStreamIssue.restricted
|
issues[name] = Go2rtcStreamIssue.restricted
|
||||||
break
|
break
|
||||||
|
|
||||||
# the resolved value checked below is what go2rtc loads at startup
|
# only sources whose placeholders resolve here are accepted, so the
|
||||||
|
# resolved value checked below is what go2rtc loads at startup
|
||||||
try:
|
try:
|
||||||
with candidate_env_vars(new_env_vars):
|
resolved_source = substitute_frigate_vars(source)
|
||||||
resolved_source = substitute_frigate_vars(source)
|
|
||||||
except UnknownVariableError:
|
except UnknownVariableError:
|
||||||
issues[name] = Go2rtcStreamIssue.unknown_variable
|
issues[name] = Go2rtcStreamIssue.unknown_variable
|
||||||
break
|
break
|
||||||
@@ -1284,11 +1272,6 @@ def find_restricted_go2rtc_stream_changes(
|
|||||||
issues[name] = Go2rtcStreamIssue.invalid_placeholder
|
issues[name] = Go2rtcStreamIssue.invalid_placeholder
|
||||||
break
|
break
|
||||||
|
|
||||||
if source in existing and resolved_source == (
|
|
||||||
_resolve_running_frigate_vars(source)
|
|
||||||
):
|
|
||||||
continue
|
|
||||||
|
|
||||||
if is_restricted_go2rtc_api_source(
|
if is_restricted_go2rtc_api_source(
|
||||||
source
|
source
|
||||||
) or is_restricted_go2rtc_api_source(resolved_source):
|
) or is_restricted_go2rtc_api_source(resolved_source):
|
||||||
|
|||||||
@@ -342,37 +342,4 @@ test.describe("Explore — Frigate+ submission (desktop) @high", () => {
|
|||||||
dialog.getByRole("button", { name: "Yes", exact: true }),
|
dialog.getByRole("button", { name: "Yes", exact: true }),
|
||||||
).toBeVisible();
|
).toBeVisible();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("a rate limited submission says how long to wait", async ({
|
|
||||||
frigateApp,
|
|
||||||
}) => {
|
|
||||||
await frigateApp.installDefaults({ config: { plus: { enabled: true } } });
|
|
||||||
const page = frigateApp.page;
|
|
||||||
await page.route("**/api/events/*/plus", (route) =>
|
|
||||||
route.fulfill({
|
|
||||||
status: 429,
|
|
||||||
headers: { "Retry-After": "90" },
|
|
||||||
json: { success: false, retry_after: 90 },
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
|
|
||||||
await frigateApp.goto("/explore?labels=person");
|
|
||||||
|
|
||||||
const firstResult = page.locator("[data-start]").first();
|
|
||||||
await expect(firstResult).toBeVisible({ timeout: 10_000 });
|
|
||||||
await firstResult.click();
|
|
||||||
|
|
||||||
const dialog = page.getByRole("dialog");
|
|
||||||
await dialog.getByRole("button", { name: "Yes", exact: true }).click();
|
|
||||||
|
|
||||||
await expect(
|
|
||||||
page.getByText(
|
|
||||||
"Frigate+ is rate limiting requests. Try again in 1 minute, 30 seconds.",
|
|
||||||
),
|
|
||||||
).toBeVisible();
|
|
||||||
// the object can be submitted again once the wait is over
|
|
||||||
await expect(
|
|
||||||
dialog.getByRole("button", { name: "Yes", exact: true }),
|
|
||||||
).toBeVisible();
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -459,36 +459,6 @@ test.describe("Detection models settings @high", () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("a Frigate+ rate limit says how long to wait, including days", async ({
|
|
||||||
frigateApp,
|
|
||||||
}) => {
|
|
||||||
await installRoutes(
|
|
||||||
frigateApp.page,
|
|
||||||
[
|
|
||||||
{
|
|
||||||
scene: "default",
|
|
||||||
devices: ["openvino:GPU.0"],
|
|
||||||
path: "plus://abc123",
|
|
||||||
plus: PLUS_MODEL,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
true,
|
|
||||||
);
|
|
||||||
// registered last, so it takes precedence over the models route above
|
|
||||||
await frigateApp.page.route("**/api/plus/models", (route) =>
|
|
||||||
route.fulfill({
|
|
||||||
status: 429,
|
|
||||||
headers: { "Retry-After": "90000" },
|
|
||||||
json: { success: false, retry_after: 90000 },
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
await openPage(frigateApp);
|
|
||||||
|
|
||||||
await expect(frigateApp.page.locator("#pageRoot")).toContainText(
|
|
||||||
"Frigate+ is rate limiting requests. Try again in 1 day, 1 hour.",
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("picking a Frigate+ model stays on the tab and saves a plus path", async ({
|
test("picking a Frigate+ model stays on the tab and saves a plus path", async ({
|
||||||
frigateApp,
|
frigateApp,
|
||||||
}) => {
|
}) => {
|
||||||
|
|||||||
Generated
+171
-233
@@ -10,7 +10,7 @@
|
|||||||
"hasInstallScript": true,
|
"hasInstallScript": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@cycjimmy/jsmpeg-player": "^7.0.0",
|
"@cycjimmy/jsmpeg-player": "^7.0.0",
|
||||||
"@hookform/resolvers": "^7.0.7",
|
"@hookform/resolvers": "^7.0.6",
|
||||||
"@radix-ui/react-alert-dialog": "^1.2.1",
|
"@radix-ui/react-alert-dialog": "^1.2.1",
|
||||||
"@radix-ui/react-aspect-ratio": "^1.2.0",
|
"@radix-ui/react-aspect-ratio": "^1.2.0",
|
||||||
"@radix-ui/react-checkbox": "^1.4.1",
|
"@radix-ui/react-checkbox": "^1.4.1",
|
||||||
@@ -37,7 +37,7 @@
|
|||||||
"@rjsf/shadcn": "^6.11.1",
|
"@rjsf/shadcn": "^6.11.1",
|
||||||
"@rjsf/utils": "^6.10.1",
|
"@rjsf/utils": "^6.10.1",
|
||||||
"@rjsf/validator-ajv8": "^6.11.1",
|
"@rjsf/validator-ajv8": "^6.11.1",
|
||||||
"apexcharts": "^8.9.1",
|
"apexcharts": "^8.8.1",
|
||||||
"axios": "^1.21.1",
|
"axios": "^1.21.1",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
@@ -45,50 +45,50 @@
|
|||||||
"copy-to-clipboard": "^4.0.2",
|
"copy-to-clipboard": "^4.0.2",
|
||||||
"date-fns": "^4.4.0",
|
"date-fns": "^4.4.0",
|
||||||
"date-fns-tz": "^3.2.0",
|
"date-fns-tz": "^3.2.0",
|
||||||
"framer-motion": "^14.14.0",
|
"framer-motion": "^14.12.0",
|
||||||
"heic-to": "^1.6.7",
|
"heic-to": "^1.6.7",
|
||||||
"hls.js": "^1.7.4",
|
"hls.js": "^1.7.4",
|
||||||
"i18next": "^27.2.2",
|
"i18next": "^27.1.1",
|
||||||
"i18next-http-backend": "^4.1.0",
|
"i18next-http-backend": "^4.0.10",
|
||||||
"idb-keyval": "^6.3.0",
|
"idb-keyval": "^6.3.0",
|
||||||
"js-yaml": "^5.5.0",
|
"js-yaml": "^5.5.0",
|
||||||
"konva": "^10.9.1",
|
"konva": "^10.9.1",
|
||||||
"lodash": "^4.18.1",
|
"lodash": "^4.18.1",
|
||||||
"lucide-react": "^1.76.0",
|
"lucide-react": "^1.72.0",
|
||||||
"monaco-yaml": "^5.5.1",
|
"monaco-yaml": "^5.5.1",
|
||||||
"next-themes": "^0.4.6",
|
"next-themes": "^0.4.6",
|
||||||
"nosleep.js": "^0.12.0",
|
"nosleep.js": "^0.12.0",
|
||||||
"react": "^19.3.1",
|
"react": "^19.3.1",
|
||||||
"react-apexcharts": "^2.2.1",
|
"react-apexcharts": "^2.2.0",
|
||||||
"react-day-picker": "^10.0.2",
|
"react-day-picker": "^10.0.2",
|
||||||
"react-device-detect": "^2.2.3",
|
"react-device-detect": "^2.2.3",
|
||||||
"react-dom": "^19.3.1",
|
"react-dom": "^19.3.1",
|
||||||
"react-dropzone": "^20.2.1",
|
"react-dropzone": "^20.2.0",
|
||||||
"react-grid-layout": "^2.3.0",
|
"react-grid-layout": "^2.3.0",
|
||||||
"react-hook-form": "^7.92.0",
|
"react-hook-form": "^7.92.0",
|
||||||
"react-i18next": "^18.0.3",
|
"react-i18next": "^18.0.1",
|
||||||
"react-icons": "^5.7.0",
|
"react-icons": "^5.7.0",
|
||||||
"react-konva": "^19.3.2",
|
"react-konva": "^19.3.2",
|
||||||
"react-markdown": "^10.1.0",
|
"react-markdown": "^10.1.0",
|
||||||
"react-router-dom": "^7.18.6",
|
"react-router-dom": "^7.18.5",
|
||||||
"react-swipeable": "^7.0.2",
|
"react-swipeable": "^7.0.2",
|
||||||
"react-zoom-pan-pinch": "3.4.4",
|
"react-zoom-pan-pinch": "3.4.4",
|
||||||
"remark-gfm": "^4.0.0",
|
"remark-gfm": "^4.0.0",
|
||||||
"scroll-into-view-if-needed": "^3.2.1",
|
"scroll-into-view-if-needed": "^3.2.0",
|
||||||
"sonner": "^2.0.8",
|
"sonner": "^2.0.8",
|
||||||
"swr": "^2.5.1",
|
"swr": "^2.5.1",
|
||||||
"tailwind-merge": "^2.6.2",
|
"tailwind-merge": "^2.6.1",
|
||||||
"tailwind-scrollbar": "^3.1.0",
|
"tailwind-scrollbar": "^3.1.0",
|
||||||
"tailwindcss-animate": "^1.0.7",
|
"tailwindcss-animate": "^1.0.7",
|
||||||
"use-long-press": "^3.3.0",
|
"use-long-press": "^3.3.0",
|
||||||
"vaul": "^1.1.2",
|
"vaul": "^1.1.2",
|
||||||
"virtua": "^0.55.0",
|
"virtua": "^0.54.2",
|
||||||
"vite-plugin-monaco-editor": "^1.1.0",
|
"vite-plugin-monaco-editor": "^1.1.0",
|
||||||
"zod": "^4.6.7"
|
"zod": "^4.6.7"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^10.0.1",
|
"@eslint/js": "^10.0.1",
|
||||||
"@playwright/test": "^1.65.1",
|
"@playwright/test": "^1.65.0",
|
||||||
"@types/js-yaml": "^4.0.9",
|
"@types/js-yaml": "^4.0.9",
|
||||||
"@types/lodash": "^4.17.27",
|
"@types/lodash": "^4.17.27",
|
||||||
"@types/node": "^26.6.6",
|
"@types/node": "^26.6.6",
|
||||||
@@ -97,21 +97,21 @@
|
|||||||
"@vitejs/plugin-react": "^6.3.0",
|
"@vitejs/plugin-react": "^6.3.0",
|
||||||
"autoprefixer": "^10.6.2",
|
"autoprefixer": "^10.6.2",
|
||||||
"esbuild": "^0.28.2",
|
"esbuild": "^0.28.2",
|
||||||
"eslint": "^10.15.0",
|
"eslint": "^10.14.0",
|
||||||
"eslint-config-prettier": "^10.1.8",
|
"eslint-config-prettier": "^10.1.8",
|
||||||
"eslint-plugin-prettier": "^5.5.7",
|
"eslint-plugin-prettier": "^5.5.7",
|
||||||
"eslint-plugin-react-hooks": "^7.1.1",
|
"eslint-plugin-react-hooks": "^7.1.1",
|
||||||
"eslint-plugin-react-refresh": "^0.5.8",
|
"eslint-plugin-react-refresh": "^0.5.7",
|
||||||
"globals": "^17.14.0",
|
"globals": "^17.14.0",
|
||||||
"i18next-cli": "^1.5.11",
|
"i18next-cli": "^1.5.11",
|
||||||
"monaco-editor": "^0.53.0",
|
"monaco-editor": "^0.53.0",
|
||||||
"patch-package": "^8.0.1",
|
"patch-package": "^8.0.1",
|
||||||
"postcss": "^8.5.33",
|
"postcss": "^8.5.32",
|
||||||
"prettier": "^3.10.1",
|
"prettier": "^3.10.1",
|
||||||
"prettier-plugin-tailwindcss": "^0.8.1",
|
"prettier-plugin-tailwindcss": "^0.8.1",
|
||||||
"tailwindcss": "^3.4.19",
|
"tailwindcss": "^3.4.19",
|
||||||
"typescript": "^6.0.3",
|
"typescript": "^6.0.3",
|
||||||
"typescript-eslint": "^8.73.0",
|
"typescript-eslint": "^8.72.2",
|
||||||
"vite": "^8.3.8"
|
"vite": "^8.3.8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -971,37 +971,20 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@eslint/config-array": {
|
"node_modules/@eslint/config-array": {
|
||||||
"version": "0.23.6",
|
"version": "0.23.5",
|
||||||
"resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.6.tgz",
|
"resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.5.tgz",
|
||||||
"integrity": "sha512-WrTH7nioI9QPY4NZGnsywmecswJdgeq4BCM76qok9VgjTO29ZgUzUvcuJLVPYVQM4uDbaPBU0M33R9DIxI8X3w==",
|
"integrity": "sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@eslint/object-schema": "^3.0.5",
|
"@eslint/object-schema": "^3.0.5",
|
||||||
"debug": "^4.3.1",
|
"debug": "^4.3.1",
|
||||||
"minimatch": "^11.0.5"
|
"minimatch": "^10.2.4"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "^20.19.0 || ^22.13.0 || >=24"
|
"node": "^20.19.0 || ^22.13.0 || >=24"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@eslint/config-array/node_modules/minimatch": {
|
|
||||||
"version": "11.0.9",
|
|
||||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz",
|
|
||||||
"integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==",
|
|
||||||
"dev": true,
|
|
||||||
"license": "BlueOak-1.0.0",
|
|
||||||
"dependencies": {
|
|
||||||
"@isaacs/nonrecursive-glob-match": "^1.1.0",
|
|
||||||
"brace-expansion": "^5.0.12"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": "20 || >=22"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/isaacs"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@eslint/config-helpers": {
|
"node_modules/@eslint/config-helpers": {
|
||||||
"version": "0.7.0",
|
"version": "0.7.0",
|
||||||
"resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.7.0.tgz",
|
"resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.7.0.tgz",
|
||||||
@@ -1112,9 +1095,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@hookform/resolvers": {
|
"node_modules/@hookform/resolvers": {
|
||||||
"version": "7.0.7",
|
"version": "7.0.6",
|
||||||
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-7.0.7.tgz",
|
"resolved": "https://registry.npmjs.org/@hookform/resolvers/-/resolvers-7.0.6.tgz",
|
||||||
"integrity": "sha512-sxiEGu5dhg6gMEsGznEQ/++634YiRLmxclw+/B1+yNN9uuhKIfNCRTE4xwqkRcKNqBPwtmDXg5oDhLw3i/wklw==",
|
"integrity": "sha512-LSTMwW4tmRWtM7pS5HkSqahi71USbhrmjc9pNHNa7UyYTbKIK/e0G1EAw6xsEnp9GahTjXhunxRJp0Bd8E6NZA==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@standard-schema/utils": "^0.3.0"
|
"@standard-schema/utils": "^0.3.0"
|
||||||
@@ -1642,13 +1625,6 @@
|
|||||||
"node": ">=18"
|
"node": ">=18"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@isaacs/nonrecursive-glob-match": {
|
|
||||||
"version": "1.1.0",
|
|
||||||
"resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz",
|
|
||||||
"integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==",
|
|
||||||
"dev": true,
|
|
||||||
"license": "BlueOak-1.0.0"
|
|
||||||
},
|
|
||||||
"node_modules/@jridgewell/gen-mapping": {
|
"node_modules/@jridgewell/gen-mapping": {
|
||||||
"version": "0.3.13",
|
"version": "0.3.13",
|
||||||
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
|
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
|
||||||
@@ -1796,13 +1772,13 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@playwright/test": {
|
"node_modules/@playwright/test": {
|
||||||
"version": "1.65.1",
|
"version": "1.65.0",
|
||||||
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.65.1.tgz",
|
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.65.0.tgz",
|
||||||
"integrity": "sha512-y+NCIRm2LvY4slUVWvGh1nujJ8RF/hEisIsq2mtUPgdQC4L701bq5hZGMhrpeXjACvwvO9tj5dJqhvM6TP9lbw==",
|
"integrity": "sha512-iGURLGuKDLakSEl7Pgfv8h7f+XLT+V861Wfhz0zlEl5nyFuKUopdkFBPKqTllTUp06aOwPuH8iuUEb3yp3MpbQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"playwright": "1.65.1"
|
"playwright": "1.65.0"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
"playwright": "cli.js"
|
"playwright": "cli.js"
|
||||||
@@ -3769,17 +3745,17 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@typescript-eslint/eslint-plugin": {
|
"node_modules/@typescript-eslint/eslint-plugin": {
|
||||||
"version": "8.73.0",
|
"version": "8.72.2",
|
||||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.73.0.tgz",
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.72.2.tgz",
|
||||||
"integrity": "sha512-UkygMFer53Yzn29MCYFTHf34hGXf5KJhiDWfIm1tXtXRrym1CS6l5H9Y3yCtPWChpC0/f93H88gdj8tN0dd4kw==",
|
"integrity": "sha512-222PKFXKihmFpi/pS5njoBgdAqsPhj2/GBmFbrNw8Tq8gEG9Sv+kSlKFy4u2q+mJv9ZzJgM2Gkv/bUzRZwZw5g==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@eslint-community/regexpp": "^4.12.2",
|
"@eslint-community/regexpp": "^4.12.2",
|
||||||
"@typescript-eslint/scope-manager": "8.73.0",
|
"@typescript-eslint/scope-manager": "8.72.2",
|
||||||
"@typescript-eslint/type-utils": "8.73.0",
|
"@typescript-eslint/type-utils": "8.72.2",
|
||||||
"@typescript-eslint/utils": "8.73.0",
|
"@typescript-eslint/utils": "8.72.2",
|
||||||
"@typescript-eslint/visitor-keys": "8.73.0",
|
"@typescript-eslint/visitor-keys": "8.72.2",
|
||||||
"ignore": "^7.0.5",
|
"ignore": "^7.0.5",
|
||||||
"natural-compare": "^1.4.0",
|
"natural-compare": "^1.4.0",
|
||||||
"ts-api-utils": "^2.5.0"
|
"ts-api-utils": "^2.5.0"
|
||||||
@@ -3792,15 +3768,15 @@
|
|||||||
"url": "https://opencollective.com/typescript-eslint"
|
"url": "https://opencollective.com/typescript-eslint"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@typescript-eslint/parser": "^8.73.0",
|
"@typescript-eslint/parser": "^8.72.2",
|
||||||
"eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
|
"eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
|
||||||
"typescript": ">=4.8.4 <6.1.0"
|
"typescript": ">=4.8.4 <6.1.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": {
|
"node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": {
|
||||||
"version": "7.0.16",
|
"version": "7.0.14",
|
||||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.16.tgz",
|
"resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.14.tgz",
|
||||||
"integrity": "sha512-52N+Y4HRMOJmbLmr+DqO4iSRyyB7N52gm7PWCT6h0p978+oKbqHCB7gIJIwZvBUsjlSdWbrBFqUSmIFNZMpn0A==",
|
"integrity": "sha512-wCBiZ77u1tuWde6G/nfOtLaCTYcFDU5yCzARzK10y+rLhzYoL7a7yEemcopcc2Mzow7gZOIjnV2ym1NYmdiJOQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -3808,16 +3784,16 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@typescript-eslint/parser": {
|
"node_modules/@typescript-eslint/parser": {
|
||||||
"version": "8.73.0",
|
"version": "8.72.2",
|
||||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.73.0.tgz",
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.72.2.tgz",
|
||||||
"integrity": "sha512-AuL45bVcmssHfZ3Di3cs9Q0l4gBm4ZFVrJOQEE7VpqW+PVgQaEwSwazz4TVIiFabXkk6U51EprYDwqw+HR8ePw==",
|
"integrity": "sha512-llP+T1YuJOLlxEciP6OyQGtz5SMxyn+9LA2BvZw5RmToGVa1y4beEDVQL6Gje7T5WFYh19WREjDCN9Ev4gm5AA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@typescript-eslint/scope-manager": "8.73.0",
|
"@typescript-eslint/scope-manager": "8.72.2",
|
||||||
"@typescript-eslint/types": "8.73.0",
|
"@typescript-eslint/types": "8.72.2",
|
||||||
"@typescript-eslint/typescript-estree": "8.73.0",
|
"@typescript-eslint/typescript-estree": "8.72.2",
|
||||||
"@typescript-eslint/visitor-keys": "8.73.0",
|
"@typescript-eslint/visitor-keys": "8.72.2",
|
||||||
"debug": "^4.4.3"
|
"debug": "^4.4.3"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -3833,14 +3809,14 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@typescript-eslint/project-service": {
|
"node_modules/@typescript-eslint/project-service": {
|
||||||
"version": "8.73.0",
|
"version": "8.72.2",
|
||||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.73.0.tgz",
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.72.2.tgz",
|
||||||
"integrity": "sha512-/pEf8Rc4Mjk+qJnY0uO1+Gadeal8uv50xpuic+srG2vIVatA0XxvWMUeMtFvs6OCHqftiQ7/+qH4aehG5stzIA==",
|
"integrity": "sha512-6y5dLTZdHhI8Eh3yIQ/bfQhRKwn5e+TpJj64o18Cngc0iW/BCrVvrr6zGYqXPnYH31u6YXAYiFh0+qxX5mybJw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@typescript-eslint/tsconfig-utils": "^8.73.0",
|
"@typescript-eslint/tsconfig-utils": "^8.72.2",
|
||||||
"@typescript-eslint/types": "^8.73.0",
|
"@typescript-eslint/types": "^8.72.2",
|
||||||
"debug": "^4.4.3"
|
"debug": "^4.4.3"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -3855,14 +3831,14 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@typescript-eslint/scope-manager": {
|
"node_modules/@typescript-eslint/scope-manager": {
|
||||||
"version": "8.73.0",
|
"version": "8.72.2",
|
||||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.73.0.tgz",
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.72.2.tgz",
|
||||||
"integrity": "sha512-/TjD738Iq2rzj5z0ixVOi+TsvgjAzZPLPaH1yWdDBytR/HTR5gMpyYWZeCe5WTQZLwk3ho8AV7U3muoQCRtXBQ==",
|
"integrity": "sha512-iIoMJ6/8c1/QpFNyFjU0d1YzPco4MsZjQw0k3V+vfzNWAFmUmvhlyMoYEoYYDQZXc+J6Gi1X5XcxlzW2taIIGQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@typescript-eslint/types": "8.73.0",
|
"@typescript-eslint/types": "8.72.2",
|
||||||
"@typescript-eslint/visitor-keys": "8.73.0"
|
"@typescript-eslint/visitor-keys": "8.72.2"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||||
@@ -3873,9 +3849,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@typescript-eslint/tsconfig-utils": {
|
"node_modules/@typescript-eslint/tsconfig-utils": {
|
||||||
"version": "8.73.0",
|
"version": "8.72.2",
|
||||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.73.0.tgz",
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.72.2.tgz",
|
||||||
"integrity": "sha512-lmtCFOfYaJfpqZywGuXi4FpNtE+NQ+YLe3T0K9rtEDcW8ZuGWvfI++pj8r05sYMI8vWT2CYK4rWyedmD6Rp4og==",
|
"integrity": "sha512-+h3iCgZXuTNtoLXcnnjP12ZUHLMqoUcIHPfQrFEXTUqvb9dF8QK9b5nv5VtSo5fLkdHuks8ehbTzZj3rImAm9w==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -3890,15 +3866,15 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@typescript-eslint/type-utils": {
|
"node_modules/@typescript-eslint/type-utils": {
|
||||||
"version": "8.73.0",
|
"version": "8.72.2",
|
||||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.73.0.tgz",
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.72.2.tgz",
|
||||||
"integrity": "sha512-MOC9i4xy1F7KcDde7Ip8jf1SrRiALb2Km4UWxGNjUE2YlhjIEo1ayE27GHIwIQyfWuHTmEonQT14uyurlyC6aA==",
|
"integrity": "sha512-STfkR38qIdhfkLpgtXnUjAzsNy4xouqiBO0lrVc/Wpk9Kem5/aHXUx1J8dGC16zpdYN1+yc2ILQ28er1kXX7ag==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@typescript-eslint/types": "8.73.0",
|
"@typescript-eslint/types": "8.72.2",
|
||||||
"@typescript-eslint/typescript-estree": "8.73.0",
|
"@typescript-eslint/typescript-estree": "8.72.2",
|
||||||
"@typescript-eslint/utils": "8.73.0",
|
"@typescript-eslint/utils": "8.72.2",
|
||||||
"debug": "^4.4.3",
|
"debug": "^4.4.3",
|
||||||
"ts-api-utils": "^2.5.0"
|
"ts-api-utils": "^2.5.0"
|
||||||
},
|
},
|
||||||
@@ -3915,9 +3891,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@typescript-eslint/types": {
|
"node_modules/@typescript-eslint/types": {
|
||||||
"version": "8.73.0",
|
"version": "8.72.2",
|
||||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.73.0.tgz",
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.72.2.tgz",
|
||||||
"integrity": "sha512-O/1ytYzflF16QDKXx4/qOXg1IuZp+n7hr9t+S0nv7N/2Tl8rJiNCshztV1gcSUvHbPtoX3+zmNbtSAyVbzxVfw==",
|
"integrity": "sha512-Xfn37OLZx03+PCU7qWx9DTv2FCRh1E6fk2+wONeNY15HXIwtcwuveaSwVpGAUptkNmPQegRxW5JyRel9T7wrog==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -3929,18 +3905,18 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@typescript-eslint/typescript-estree": {
|
"node_modules/@typescript-eslint/typescript-estree": {
|
||||||
"version": "8.73.0",
|
"version": "8.72.2",
|
||||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.73.0.tgz",
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.72.2.tgz",
|
||||||
"integrity": "sha512-InjlBkSdWceIwIBWSwS3ENUp+i0O02PGX3Zv2wnihWJC1WDVGvG7mTHuf8b57uAaITj94d6tRPDH+sUEtXdRQQ==",
|
"integrity": "sha512-pQEGqIK/cqEvKivVWaFLYpe7XYejFxfuAOi4mu1oAWFvIo36aRHI9esRFTUxcIy/z8N482RJyH+LpZB0ZIU7Ow==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@typescript-eslint/project-service": "8.73.0",
|
"@typescript-eslint/project-service": "8.72.2",
|
||||||
"@typescript-eslint/tsconfig-utils": "8.73.0",
|
"@typescript-eslint/tsconfig-utils": "8.72.2",
|
||||||
"@typescript-eslint/types": "8.73.0",
|
"@typescript-eslint/types": "8.72.2",
|
||||||
"@typescript-eslint/visitor-keys": "8.73.0",
|
"@typescript-eslint/visitor-keys": "8.72.2",
|
||||||
"debug": "^4.4.3",
|
"debug": "^4.4.3",
|
||||||
"minimatch": "^11.0.1",
|
"minimatch": "^10.2.2",
|
||||||
"semver": "^7.7.3",
|
"semver": "^7.7.3",
|
||||||
"tinyglobby": "^0.2.15",
|
"tinyglobby": "^0.2.15",
|
||||||
"ts-api-utils": "^2.5.0"
|
"ts-api-utils": "^2.5.0"
|
||||||
@@ -3953,43 +3929,20 @@
|
|||||||
"url": "https://opencollective.com/typescript-eslint"
|
"url": "https://opencollective.com/typescript-eslint"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@typescript/native": "npm:typescript@>=7.1.0-dev.20261009.1 || >=7.1.0-beta <7.1.0-dev",
|
|
||||||
"typescript": ">=4.8.4 <6.1.0"
|
"typescript": ">=4.8.4 <6.1.0"
|
||||||
},
|
|
||||||
"peerDependenciesMeta": {
|
|
||||||
"@typescript/native": {
|
|
||||||
"optional": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": {
|
|
||||||
"version": "11.0.9",
|
|
||||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz",
|
|
||||||
"integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==",
|
|
||||||
"dev": true,
|
|
||||||
"license": "BlueOak-1.0.0",
|
|
||||||
"dependencies": {
|
|
||||||
"@isaacs/nonrecursive-glob-match": "^1.1.0",
|
|
||||||
"brace-expansion": "^5.0.12"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": "20 || >=22"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/isaacs"
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@typescript-eslint/utils": {
|
"node_modules/@typescript-eslint/utils": {
|
||||||
"version": "8.73.0",
|
"version": "8.72.2",
|
||||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.73.0.tgz",
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.72.2.tgz",
|
||||||
"integrity": "sha512-j2SVJJvVkXdUL0WcEzo4vEH1mO1vIi8KlVukcYA2MgMZvYN2LlZR4PmsW+GTSxSW24j6Q/EP7+MOifLtg5hmsA==",
|
"integrity": "sha512-hv3eRYbpPbbpezuax1EfGrzpa3C4ySgNZkPUkLOWOAjU8HsOKowEDAr8C7nsNl1C+SBSKDpvno6VKHnlhvp9iA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@eslint-community/eslint-utils": "^4.9.1",
|
"@eslint-community/eslint-utils": "^4.9.1",
|
||||||
"@typescript-eslint/scope-manager": "8.73.0",
|
"@typescript-eslint/scope-manager": "8.72.2",
|
||||||
"@typescript-eslint/types": "8.73.0",
|
"@typescript-eslint/types": "8.72.2",
|
||||||
"@typescript-eslint/typescript-estree": "8.73.0"
|
"@typescript-eslint/typescript-estree": "8.72.2"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||||
@@ -4004,13 +3957,13 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@typescript-eslint/visitor-keys": {
|
"node_modules/@typescript-eslint/visitor-keys": {
|
||||||
"version": "8.73.0",
|
"version": "8.72.2",
|
||||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.73.0.tgz",
|
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.72.2.tgz",
|
||||||
"integrity": "sha512-k4lsFVpRZICbltkIEEH4hZRkwXkqDF1GHBpClKQOHQY+RkoZAAuyc1ci3I6p+CB6v3U4jaHIUshc4RzzQXZWLg==",
|
"integrity": "sha512-NAGrjn0Pitjqzq/GkgMC4kBYm233PQ8GffyQ9+kTA3AlNQYEzOf25EIM02BAHZv5FRJSpHpJk+OGUxVkOB93GQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@typescript-eslint/types": "8.73.0",
|
"@typescript-eslint/types": "8.72.2",
|
||||||
"eslint-visitor-keys": "^5.0.0"
|
"eslint-visitor-keys": "^5.0.0"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
@@ -4192,18 +4145,18 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/apex-commons": {
|
"node_modules/apex-commons": {
|
||||||
"version": "0.11.0",
|
"version": "0.10.0",
|
||||||
"resolved": "https://registry.npmjs.org/apex-commons/-/apex-commons-0.11.0.tgz",
|
"resolved": "https://registry.npmjs.org/apex-commons/-/apex-commons-0.10.0.tgz",
|
||||||
"integrity": "sha512-r0t1hq4eNzjqRHlf0qG9jiwhd3g/68A9QvgVyjres4oif72NWA1pcvFizpx7gjc/SPECALq0KkL5f12ODIDBPA==",
|
"integrity": "sha512-mBXqK6wykMnWV4TzT9636k4aaeEvE8PmBIfa2bHx91eQoit8RjJrOlBpGxNGz1Bmt6gq2U3CoqPAUZftBbYdLQ==",
|
||||||
"license": "SEE LICENSE IN LICENSE.md"
|
"license": "SEE LICENSE IN LICENSE.md"
|
||||||
},
|
},
|
||||||
"node_modules/apexcharts": {
|
"node_modules/apexcharts": {
|
||||||
"version": "8.9.1",
|
"version": "8.8.1",
|
||||||
"resolved": "https://registry.npmjs.org/apexcharts/-/apexcharts-8.9.1.tgz",
|
"resolved": "https://registry.npmjs.org/apexcharts/-/apexcharts-8.8.1.tgz",
|
||||||
"integrity": "sha512-0SsOUfiEsJblL9tB8IoHfpSMq1cxBnA3v8TNDPA9zfe7gDUVXEfNQte1kdVztsWVQuNPIoZZ3/591LkEwgxuLA==",
|
"integrity": "sha512-Aeha39Wdrg4pTdJTpM+QsQemLoCRpwC5tEgwHYzbvtRxo4E9EmQ6zdTZbhcYia24HyPhqx3IATd1evgS0lRtzw==",
|
||||||
"license": "SEE LICENSE IN LICENSE.md",
|
"license": "SEE LICENSE IN LICENSE.md",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"apex-commons": "^0.11.0"
|
"apex-commons": "^0.10.0"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
|
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
|
||||||
@@ -4775,10 +4728,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/compute-scroll-into-view": {
|
"node_modules/compute-scroll-into-view": {
|
||||||
"version": "3.2.2",
|
"version": "3.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/compute-scroll-into-view/-/compute-scroll-into-view-3.2.2.tgz",
|
"resolved": "https://registry.npmjs.org/compute-scroll-into-view/-/compute-scroll-into-view-3.1.0.tgz",
|
||||||
"integrity": "sha512-X+jf3y2j3TbtxA3fq3/kBNiSnD1QlIChiIQdAc2Yo1LtOc0yjO1TzgxWJf8PwtKPGgSvSfWUlVvrb7vGx1eYWA==",
|
"integrity": "sha512-rj8l8pD4bJ1nx+dAkMhV1xB5RuZEyVysfxJqB1pRchh1KVvwOv9b7CGB8ZfjTImVv2oF+sYMUkMZq6Na5Ftmbg=="
|
||||||
"license": "MIT"
|
|
||||||
},
|
},
|
||||||
"node_modules/convert-source-map": {
|
"node_modules/convert-source-map": {
|
||||||
"version": "2.0.0",
|
"version": "2.0.0",
|
||||||
@@ -5104,9 +5056,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/eslint": {
|
"node_modules/eslint": {
|
||||||
"version": "10.15.0",
|
"version": "10.14.0",
|
||||||
"resolved": "https://registry.npmjs.org/eslint/-/eslint-10.15.0.tgz",
|
"resolved": "https://registry.npmjs.org/eslint/-/eslint-10.14.0.tgz",
|
||||||
"integrity": "sha512-+5Wg4p+ze3sG1WErYgUO/3H1IQIfFBymVUA0Fo/XTeBOLS6UQIUekpSJ8sdRkn7O7wjh84b55w/roqavH2aScg==",
|
"integrity": "sha512-T0pNsxkb9IKmtQjhpK3d7nWOpFv+YHuMbTJnSVMoQblF0onvXfErrtp4V1jHtsQPan7dKaGVD0q1WCXnzMF31A==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"workspaces": [
|
"workspaces": [
|
||||||
@@ -5115,7 +5067,7 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@eslint-community/eslint-utils": "^4.8.0",
|
"@eslint-community/eslint-utils": "^4.8.0",
|
||||||
"@eslint-community/regexpp": "^4.12.2",
|
"@eslint-community/regexpp": "^4.12.2",
|
||||||
"@eslint/config-array": "^0.23.6",
|
"@eslint/config-array": "^0.23.5",
|
||||||
"@eslint/config-helpers": "^0.7.0",
|
"@eslint/config-helpers": "^0.7.0",
|
||||||
"@eslint/core": "^1.2.1",
|
"@eslint/core": "^1.2.1",
|
||||||
"@eslint/plugin-kit": "^0.7.3",
|
"@eslint/plugin-kit": "^0.7.3",
|
||||||
@@ -5140,7 +5092,7 @@
|
|||||||
"imurmurhash": "^0.1.4",
|
"imurmurhash": "^0.1.4",
|
||||||
"is-glob": "^4.0.0",
|
"is-glob": "^4.0.0",
|
||||||
"json-stable-stringify-without-jsonify": "^1.0.1",
|
"json-stable-stringify-without-jsonify": "^1.0.1",
|
||||||
"minimatch": "^11.0.5",
|
"minimatch": "^10.2.6",
|
||||||
"natural-compare": "^1.4.0",
|
"natural-compare": "^1.4.0",
|
||||||
"optionator": "^0.9.3"
|
"optionator": "^0.9.3"
|
||||||
},
|
},
|
||||||
@@ -5243,9 +5195,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/eslint-plugin-react-refresh": {
|
"node_modules/eslint-plugin-react-refresh": {
|
||||||
"version": "0.5.8",
|
"version": "0.5.7",
|
||||||
"resolved": "https://registry.npmjs.org/eslint-plugin-react-refresh/-/eslint-plugin-react-refresh-0.5.8.tgz",
|
"resolved": "https://registry.npmjs.org/eslint-plugin-react-refresh/-/eslint-plugin-react-refresh-0.5.7.tgz",
|
||||||
"integrity": "sha512-VYgz1iCC5LxeAd6YRz5ATfg8WKrNb1ulHMpCe4pQpn3CS9DiYpZi5wcag73O8iChLhrl/CmlGMmzA6eXZ2cX4Q==",
|
"integrity": "sha512-XhJSzLljuYD4UjNuFGJu2v7aD3sqNVK12w5/DCUfrNfHWegZo2+TsavNx8MuxMwEquuFAzNbNfXKU0WoZ+YUIg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
@@ -5308,23 +5260,6 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/eslint/node_modules/minimatch": {
|
|
||||||
"version": "11.0.9",
|
|
||||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.9.tgz",
|
|
||||||
"integrity": "sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==",
|
|
||||||
"dev": true,
|
|
||||||
"license": "BlueOak-1.0.0",
|
|
||||||
"dependencies": {
|
|
||||||
"@isaacs/nonrecursive-glob-match": "^1.1.0",
|
|
||||||
"brace-expansion": "^5.0.12"
|
|
||||||
},
|
|
||||||
"engines": {
|
|
||||||
"node": "20 || >=22"
|
|
||||||
},
|
|
||||||
"funding": {
|
|
||||||
"url": "https://github.com/sponsors/isaacs"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"node_modules/espree": {
|
"node_modules/espree": {
|
||||||
"version": "11.2.0",
|
"version": "11.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/espree/-/espree-11.2.0.tgz",
|
"resolved": "https://registry.npmjs.org/espree/-/espree-11.2.0.tgz",
|
||||||
@@ -5598,9 +5533,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/file-selector": {
|
"node_modules/file-selector": {
|
||||||
"version": "5.0.3",
|
"version": "5.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/file-selector/-/file-selector-5.0.3.tgz",
|
"resolved": "https://registry.npmjs.org/file-selector/-/file-selector-5.0.1.tgz",
|
||||||
"integrity": "sha512-d15nlW+KKq82TlItRvCHtJ8NXCX0nwz2SEUR1MOT8W50c5q2se551ZFdhITFrWohl/5wbRPfMMF9jq4Oj1xRGQ==",
|
"integrity": "sha512-v0g/PTeuQgvKCBrVRsfVudvwXlRHSWHEQkVgKawgCGHkEpKA1clp3Om5jvEVhz8G9W/mOYjJH9FhkH4C888PgQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">= 22"
|
"node": ">= 22"
|
||||||
@@ -5731,12 +5666,12 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/framer-motion": {
|
"node_modules/framer-motion": {
|
||||||
"version": "14.14.0",
|
"version": "14.12.0",
|
||||||
"resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-14.14.0.tgz",
|
"resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-14.12.0.tgz",
|
||||||
"integrity": "sha512-fidRX0VzkZdA9OovFiBSzJtt9/jLcJpna78Z+KCqQQZIWoIpN3tOhEXAhhAw/FObUUh+o3Y18yx1F4BP0mVJ8Q==",
|
"integrity": "sha512-4m+10xYan0ic8nFI8zyB5hJkW5F8F4Rer617UecOs8esw0he9unDgXaEZ0rUX7oztz1w4iuvyPWhk4jltMX5iw==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"motion-dom": "14.14.0",
|
"motion-dom": "14.12.0",
|
||||||
"motion-utils": "14.7.0",
|
"motion-utils": "14.7.0",
|
||||||
"tslib": "^2.4.0"
|
"tslib": "^2.4.0"
|
||||||
},
|
},
|
||||||
@@ -6150,9 +6085,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/i18next": {
|
"node_modules/i18next": {
|
||||||
"version": "27.2.2",
|
"version": "27.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/i18next/-/i18next-27.2.2.tgz",
|
"resolved": "https://registry.npmjs.org/i18next/-/i18next-27.1.1.tgz",
|
||||||
"integrity": "sha512-1/AJgz/bpE/YL6tqekQlZAzDhkmrUBbgU8+Xon/Lwv6c5WdYuyFZ9mb86OVfR2C2XujUDT7Rz23Ydaq4l981lA==",
|
"integrity": "sha512-Qq3aJizS3RXQ30crhx9BKQLrHoa6GKpgrOJjVZ9vgj3EBxAddrmVfDNUrAMxSUimw5Jc+ld4SSZUAzf1q4nGyQ==",
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
"type": "individual",
|
"type": "individual",
|
||||||
@@ -6268,9 +6203,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/i18next-http-backend": {
|
"node_modules/i18next-http-backend": {
|
||||||
"version": "4.1.0",
|
"version": "4.0.10",
|
||||||
"resolved": "https://registry.npmjs.org/i18next-http-backend/-/i18next-http-backend-4.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/i18next-http-backend/-/i18next-http-backend-4.0.10.tgz",
|
||||||
"integrity": "sha512-OY3KA8s6WUfUCviw+6VA79148bYaws+FEOZD6MNeZ8Tw1ocfu1j1Qp3ROYNMikzNv1gyTBgzHbWMP/rfZDSp1g==",
|
"integrity": "sha512-CfdQuwIVijbrS/fmiTAQYcYyje4nMbH9aIjKYhhm5bgVmWKWLOM1F7qrA1o63Jl1JxQcRjdtWhKlvDzyqV9aPg==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=18"
|
"node": ">=18"
|
||||||
@@ -7140,9 +7075,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/lucide-react": {
|
"node_modules/lucide-react": {
|
||||||
"version": "1.76.0",
|
"version": "1.72.0",
|
||||||
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.76.0.tgz",
|
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.72.0.tgz",
|
||||||
"integrity": "sha512-wRVHt2Xf64GXndB4rQOY9+3Wy9oJ59HDMYv6vwhT0hpSwUxQhG/RM9YijnOmvmIQ+VI/n+1V/FKd6gP4XL2aBQ==",
|
"integrity": "sha512-fbF5i1GU8GODETa3Q7rXqrJrcx3iPYrQtxthom103zGx+Z0BGwKYAW9s+9435ohYJ7hQm0av0PoZcqI1CRwNrg==",
|
||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@types/react": "*",
|
"@types/react": "*",
|
||||||
@@ -8217,9 +8152,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/motion-dom": {
|
"node_modules/motion-dom": {
|
||||||
"version": "14.14.0",
|
"version": "14.12.0",
|
||||||
"resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-14.14.0.tgz",
|
"resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-14.12.0.tgz",
|
||||||
"integrity": "sha512-IAxcKhYkuQA2W0Tlx1AvVgImfqEoF3/t3IovbPQJlYkefmGsmrXjn967lMII5VmFmLpQEab4+ZkHo/ijJ4Esig==",
|
"integrity": "sha512-YnAY17g8mXRVoXGZbH+v/O2SkNBJqz2TMuqL9yek9Omfhsdjw7gJwNgI5nsGZFpbbm3vINyOo+VtGPryIslatw==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"motion-utils": "14.7.0"
|
"motion-utils": "14.7.0"
|
||||||
@@ -8681,13 +8616,13 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/playwright": {
|
"node_modules/playwright": {
|
||||||
"version": "1.65.1",
|
"version": "1.65.0",
|
||||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.1.tgz",
|
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.0.tgz",
|
||||||
"integrity": "sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==",
|
"integrity": "sha512-F3AMWcR44qMBt4kq+6Kb6mX7bjGXshktKFOPULd7reED6ZJWevjbNRqysP7q+AATE9kdPEZBibex1BYsvpVoeA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"playwright-core": "1.65.1"
|
"playwright-core": "1.65.0"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
"playwright": "cli.js"
|
"playwright": "cli.js"
|
||||||
@@ -8697,9 +8632,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/playwright-core": {
|
"node_modules/playwright-core": {
|
||||||
"version": "1.65.1",
|
"version": "1.65.0",
|
||||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz",
|
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.0.tgz",
|
||||||
"integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==",
|
"integrity": "sha512-vNSKgH6YqtN7cdT/L334zo0a+YwkrpicyrHJlWWPIm/Q+Nn2SWInil01oT0mbu96U4GgoRtCYQD9CzJQgju+lA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"bin": {
|
"bin": {
|
||||||
@@ -8710,9 +8645,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/postcss": {
|
"node_modules/postcss": {
|
||||||
"version": "8.5.33",
|
"version": "8.5.32",
|
||||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz",
|
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz",
|
||||||
"integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==",
|
"integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==",
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
"type": "opencollective",
|
"type": "opencollective",
|
||||||
@@ -9082,9 +9017,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/react-apexcharts": {
|
"node_modules/react-apexcharts": {
|
||||||
"version": "2.2.1",
|
"version": "2.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/react-apexcharts/-/react-apexcharts-2.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/react-apexcharts/-/react-apexcharts-2.2.0.tgz",
|
||||||
"integrity": "sha512-cRx+RpRk6WG0SZelOvqDOqbJOWoUSHWAreAkgpNJwsG9axV+uEtTh8zOATW2uK0IjfmFZA8KenSIipslbras4g==",
|
"integrity": "sha512-MEiH/T65ooUNf8V7Cq7fCu1femP3+lN9Svzsv+jNNS6AcRSciyA1LLvc1VETWqAiqMxQyX8NYEhZxOYnMf262g==",
|
||||||
"license": "SEE LICENSE IN LICENSE.md",
|
"license": "SEE LICENSE IN LICENSE.md",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"prop-types": "^15.8.1"
|
"prop-types": "^15.8.1"
|
||||||
@@ -9159,13 +9094,13 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/react-dropzone": {
|
"node_modules/react-dropzone": {
|
||||||
"version": "20.2.1",
|
"version": "20.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/react-dropzone/-/react-dropzone-20.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/react-dropzone/-/react-dropzone-20.2.0.tgz",
|
||||||
"integrity": "sha512-8ldzI42a+iz6jlC5t0HoOO5ce65dU8ZGo8ZpesL2E57JByC8LBUieMrkGj97YYfgMaYKwkhpkfYxKOCKAekywA==",
|
"integrity": "sha512-FRlcSp6UFT9Etg57U4+g6O6qF/jH7sUh2Hz67lQlrZJa/3FjfAFvw7DwDSItiG2vBUXTdh2wroEwXPPg7o/jkg==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"attr-accept": "^4.0.1",
|
"attr-accept": "^4.0.1",
|
||||||
"file-selector": "^5.0.2"
|
"file-selector": "^5.0.1"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">= 22"
|
"node": ">= 22"
|
||||||
@@ -9221,9 +9156,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/react-i18next": {
|
"node_modules/react-i18next": {
|
||||||
"version": "18.0.3",
|
"version": "18.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-18.0.3.tgz",
|
"resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-18.0.1.tgz",
|
||||||
"integrity": "sha512-S84rtVuaKuiRtoCOspbGEaDlFjka+KvK/A5YCOr4LQ41XF3iJOrJ5rqQTD/jJHFVUf6X1i4ZMN5PGGgpz8NN6g==",
|
"integrity": "sha512-kPWXI0E/lrPj3+/umcKNzYZVnWmEedLiamMzDIHfbs+5ANf6yzvlZsjKou8f7kaGkfMMDLIZBejV+4aSN1CyBw==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"html-parse-stringify": "^4.0.1"
|
"html-parse-stringify": "^4.0.1"
|
||||||
@@ -9396,9 +9331,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/react-router": {
|
"node_modules/react-router": {
|
||||||
"version": "7.18.6",
|
"version": "7.18.5",
|
||||||
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.6.tgz",
|
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.5.tgz",
|
||||||
"integrity": "sha512-SP8KqKfRLlJzqzPseC+r6yYFsqPEavtQCC4BKV810tBGijjESLtwVPam+gPOO+wYeXrYN/TNy2CAykQVcNg4iQ==",
|
"integrity": "sha512-dTgvcXDOrLPrlLHrcZAqWveiK1hMSqN+rGAJzegP8HtmNkfRxOoshGWBNX3ZJ0cZjOHkRdlUJtaIhZMLLyGyPw==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"cookie": "^1.0.1",
|
"cookie": "^1.0.1",
|
||||||
@@ -9418,12 +9353,12 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/react-router-dom": {
|
"node_modules/react-router-dom": {
|
||||||
"version": "7.18.6",
|
"version": "7.18.5",
|
||||||
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.6.tgz",
|
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.5.tgz",
|
||||||
"integrity": "sha512-a8JzFsKEY3EY9QL7t4T1b1OhuY0ngEfwMzXQNgBO/2cuIW9028JbVq3uk2rKnjLredzcIoDKLzUkguIq6fnkFA==",
|
"integrity": "sha512-9HcfDMU6JJ/fp6gJZYGwNE6RknVGS4kBjH1HkNw959mCJi70TVwdipQWv2FEol9uGpi+SZTFtVpJPtEQfayeOw==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"react-router": "7.18.6"
|
"react-router": "7.18.5"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20.0.0"
|
"node": ">=20.0.0"
|
||||||
@@ -9727,12 +9662,15 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/scroll-into-view-if-needed": {
|
"node_modules/scroll-into-view-if-needed": {
|
||||||
"version": "3.2.1",
|
"version": "3.2.0",
|
||||||
"resolved": "https://registry.npmjs.org/scroll-into-view-if-needed/-/scroll-into-view-if-needed-3.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/scroll-into-view-if-needed/-/scroll-into-view-if-needed-3.2.0.tgz",
|
||||||
"integrity": "sha512-dgeJvJhSV9MY6hyhtsivbSxHoZVm+lumsWTObtUdAchJflwOGmKKHNkEpU8pVYMomZ8h/yrfzVQkcPlObQNDWQ==",
|
"integrity": "sha512-mnlrulRcw9gQR/HI0SlT56kmyCS/Z1tH/By43m8v8kHBjD8XecscweRcjKAk3kt4WLeyJQaSSQ8efy5f+r/dqA==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"compute-scroll-into-view": "^3.2.2"
|
"compute-scroll-into-view": "^3.0.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=26"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/semver": {
|
"node_modules/semver": {
|
||||||
@@ -10000,9 +9938,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/tailwind-merge": {
|
"node_modules/tailwind-merge": {
|
||||||
"version": "2.6.2",
|
"version": "2.6.1",
|
||||||
"resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-2.6.2.tgz",
|
"resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-2.6.1.tgz",
|
||||||
"integrity": "sha512-o2TX9QB8K2cfaJYgMwv96uAUQK5SqpRJHD2vGDK5nyF/tk9PQTZFpwgsDsySQjlIbYdZ6ZDkk5W+bSuWSe92AA==",
|
"integrity": "sha512-Oo6tHdpZsGpkKG88HJ8RR1rg/RdnEkQEfMoEk2x1XRI3F1AxeU+ijRXpiVUF4UbLfcxxRGw6TbUINKYdWVsQTQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"funding": {
|
"funding": {
|
||||||
"type": "github",
|
"type": "github",
|
||||||
@@ -10225,16 +10163,16 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/typescript-eslint": {
|
"node_modules/typescript-eslint": {
|
||||||
"version": "8.73.0",
|
"version": "8.72.2",
|
||||||
"resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.73.0.tgz",
|
"resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.72.2.tgz",
|
||||||
"integrity": "sha512-+EnKy9rkYPun4l+kG2bDuYWQ6y1tGVgdR/tY1U9AC6h21CjEwOoc7gsjwe0FXB8uWFzk4QiCFbuRWgX758PiAg==",
|
"integrity": "sha512-c/+AKMW1KB81r28Sp0AAdcyXj5dzNmAsZFcsrxKbZTKmcBK2xIwBR31dcSYSDu3bKmzXe8GKrSxO+eDQ401Uzg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@typescript-eslint/eslint-plugin": "8.73.0",
|
"@typescript-eslint/eslint-plugin": "8.72.2",
|
||||||
"@typescript-eslint/parser": "8.73.0",
|
"@typescript-eslint/parser": "8.72.2",
|
||||||
"@typescript-eslint/typescript-estree": "8.73.0",
|
"@typescript-eslint/typescript-estree": "8.72.2",
|
||||||
"@typescript-eslint/utils": "8.73.0"
|
"@typescript-eslint/utils": "8.72.2"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
|
||||||
@@ -10527,9 +10465,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/virtua": {
|
"node_modules/virtua": {
|
||||||
"version": "0.55.0",
|
"version": "0.54.2",
|
||||||
"resolved": "https://registry.npmjs.org/virtua/-/virtua-0.55.0.tgz",
|
"resolved": "https://registry.npmjs.org/virtua/-/virtua-0.54.2.tgz",
|
||||||
"integrity": "sha512-w79kvcw7PwXFmo+MSENbgy3XL61OfStJm7FPtJwZey1EsK0F0gDXmgGHvblS/iebDcg+K5J1ddlUGJ5dXGo4lA==",
|
"integrity": "sha512-lYCAxyXCGkhXVvuKv8a+LklZquy0E9dIObYcOUyo6nP4VSvLeiIsiz94mA3ZKYuM5egkke5RIi2nXi5OIATc7A==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@angular/common": ">=20.0.0",
|
"@angular/common": ">=20.0.0",
|
||||||
|
|||||||
+18
-18
@@ -22,7 +22,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@cycjimmy/jsmpeg-player": "^7.0.0",
|
"@cycjimmy/jsmpeg-player": "^7.0.0",
|
||||||
"@hookform/resolvers": "^7.0.7",
|
"@hookform/resolvers": "^7.0.6",
|
||||||
"@radix-ui/react-alert-dialog": "^1.2.1",
|
"@radix-ui/react-alert-dialog": "^1.2.1",
|
||||||
"@radix-ui/react-aspect-ratio": "^1.2.0",
|
"@radix-ui/react-aspect-ratio": "^1.2.0",
|
||||||
"@radix-ui/react-checkbox": "^1.4.1",
|
"@radix-ui/react-checkbox": "^1.4.1",
|
||||||
@@ -49,7 +49,7 @@
|
|||||||
"@rjsf/shadcn": "^6.11.1",
|
"@rjsf/shadcn": "^6.11.1",
|
||||||
"@rjsf/utils": "^6.10.1",
|
"@rjsf/utils": "^6.10.1",
|
||||||
"@rjsf/validator-ajv8": "^6.11.1",
|
"@rjsf/validator-ajv8": "^6.11.1",
|
||||||
"apexcharts": "^8.9.1",
|
"apexcharts": "^8.8.1",
|
||||||
"axios": "^1.21.1",
|
"axios": "^1.21.1",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
@@ -57,50 +57,50 @@
|
|||||||
"copy-to-clipboard": "^4.0.2",
|
"copy-to-clipboard": "^4.0.2",
|
||||||
"date-fns": "^4.4.0",
|
"date-fns": "^4.4.0",
|
||||||
"date-fns-tz": "^3.2.0",
|
"date-fns-tz": "^3.2.0",
|
||||||
"framer-motion": "^14.14.0",
|
"framer-motion": "^14.12.0",
|
||||||
"heic-to": "^1.6.7",
|
"heic-to": "^1.6.7",
|
||||||
"hls.js": "^1.7.4",
|
"hls.js": "^1.7.4",
|
||||||
"i18next": "^27.2.2",
|
"i18next": "^27.1.1",
|
||||||
"i18next-http-backend": "^4.1.0",
|
"i18next-http-backend": "^4.0.10",
|
||||||
"idb-keyval": "^6.3.0",
|
"idb-keyval": "^6.3.0",
|
||||||
"js-yaml": "^5.5.0",
|
"js-yaml": "^5.5.0",
|
||||||
"konva": "^10.9.1",
|
"konva": "^10.9.1",
|
||||||
"lodash": "^4.18.1",
|
"lodash": "^4.18.1",
|
||||||
"lucide-react": "^1.76.0",
|
"lucide-react": "^1.72.0",
|
||||||
"monaco-yaml": "^5.5.1",
|
"monaco-yaml": "^5.5.1",
|
||||||
"next-themes": "^0.4.6",
|
"next-themes": "^0.4.6",
|
||||||
"nosleep.js": "^0.12.0",
|
"nosleep.js": "^0.12.0",
|
||||||
"react": "^19.3.1",
|
"react": "^19.3.1",
|
||||||
"react-apexcharts": "^2.2.1",
|
"react-apexcharts": "^2.2.0",
|
||||||
"react-day-picker": "^10.0.2",
|
"react-day-picker": "^10.0.2",
|
||||||
"react-device-detect": "^2.2.3",
|
"react-device-detect": "^2.2.3",
|
||||||
"react-dom": "^19.3.1",
|
"react-dom": "^19.3.1",
|
||||||
"react-dropzone": "^20.2.1",
|
"react-dropzone": "^20.2.0",
|
||||||
"react-grid-layout": "^2.3.0",
|
"react-grid-layout": "^2.3.0",
|
||||||
"react-hook-form": "^7.92.0",
|
"react-hook-form": "^7.92.0",
|
||||||
"react-i18next": "^18.0.3",
|
"react-i18next": "^18.0.1",
|
||||||
"react-icons": "^5.7.0",
|
"react-icons": "^5.7.0",
|
||||||
"react-konva": "^19.3.2",
|
"react-konva": "^19.3.2",
|
||||||
"react-markdown": "^10.1.0",
|
"react-markdown": "^10.1.0",
|
||||||
"react-router-dom": "^7.18.6",
|
"react-router-dom": "^7.18.5",
|
||||||
"react-swipeable": "^7.0.2",
|
"react-swipeable": "^7.0.2",
|
||||||
"react-zoom-pan-pinch": "3.4.4",
|
"react-zoom-pan-pinch": "3.4.4",
|
||||||
"remark-gfm": "^4.0.0",
|
"remark-gfm": "^4.0.0",
|
||||||
"scroll-into-view-if-needed": "^3.2.1",
|
"scroll-into-view-if-needed": "^3.2.0",
|
||||||
"sonner": "^2.0.8",
|
"sonner": "^2.0.8",
|
||||||
"swr": "^2.5.1",
|
"swr": "^2.5.1",
|
||||||
"tailwind-merge": "^2.6.2",
|
"tailwind-merge": "^2.6.1",
|
||||||
"tailwind-scrollbar": "^3.1.0",
|
"tailwind-scrollbar": "^3.1.0",
|
||||||
"tailwindcss-animate": "^1.0.7",
|
"tailwindcss-animate": "^1.0.7",
|
||||||
"use-long-press": "^3.3.0",
|
"use-long-press": "^3.3.0",
|
||||||
"vaul": "^1.1.2",
|
"vaul": "^1.1.2",
|
||||||
"virtua": "^0.55.0",
|
"virtua": "^0.54.2",
|
||||||
"vite-plugin-monaco-editor": "^1.1.0",
|
"vite-plugin-monaco-editor": "^1.1.0",
|
||||||
"zod": "^4.6.7"
|
"zod": "^4.6.7"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^10.0.1",
|
"@eslint/js": "^10.0.1",
|
||||||
"@playwright/test": "^1.65.1",
|
"@playwright/test": "^1.65.0",
|
||||||
"@types/js-yaml": "^4.0.9",
|
"@types/js-yaml": "^4.0.9",
|
||||||
"@types/lodash": "^4.17.27",
|
"@types/lodash": "^4.17.27",
|
||||||
"@types/node": "^26.6.6",
|
"@types/node": "^26.6.6",
|
||||||
@@ -109,21 +109,21 @@
|
|||||||
"@vitejs/plugin-react": "^6.3.0",
|
"@vitejs/plugin-react": "^6.3.0",
|
||||||
"autoprefixer": "^10.6.2",
|
"autoprefixer": "^10.6.2",
|
||||||
"esbuild": "^0.28.2",
|
"esbuild": "^0.28.2",
|
||||||
"eslint": "^10.15.0",
|
"eslint": "^10.14.0",
|
||||||
"eslint-config-prettier": "^10.1.8",
|
"eslint-config-prettier": "^10.1.8",
|
||||||
"eslint-plugin-prettier": "^5.5.7",
|
"eslint-plugin-prettier": "^5.5.7",
|
||||||
"eslint-plugin-react-hooks": "^7.1.1",
|
"eslint-plugin-react-hooks": "^7.1.1",
|
||||||
"eslint-plugin-react-refresh": "^0.5.8",
|
"eslint-plugin-react-refresh": "^0.5.7",
|
||||||
"globals": "^17.14.0",
|
"globals": "^17.14.0",
|
||||||
"i18next-cli": "^1.5.11",
|
"i18next-cli": "^1.5.11",
|
||||||
"monaco-editor": "^0.53.0",
|
"monaco-editor": "^0.53.0",
|
||||||
"patch-package": "^8.0.1",
|
"patch-package": "^8.0.1",
|
||||||
"postcss": "^8.5.33",
|
"postcss": "^8.5.32",
|
||||||
"prettier": "^3.10.1",
|
"prettier": "^3.10.1",
|
||||||
"prettier-plugin-tailwindcss": "^0.8.1",
|
"prettier-plugin-tailwindcss": "^0.8.1",
|
||||||
"tailwindcss": "^3.4.19",
|
"tailwindcss": "^3.4.19",
|
||||||
"typescript": "^6.0.3",
|
"typescript": "^6.0.3",
|
||||||
"typescript-eslint": "^8.73.0",
|
"typescript-eslint": "^8.72.2",
|
||||||
"vite": "^8.3.8"
|
"vite": "^8.3.8"
|
||||||
},
|
},
|
||||||
"overrides": {
|
"overrides": {
|
||||||
|
|||||||
@@ -327,10 +327,6 @@
|
|||||||
"copyDetails": "Copy details",
|
"copyDetails": "Copy details",
|
||||||
"copyFailed": "Could not copy details to clipboard"
|
"copyFailed": "Could not copy details to clipboard"
|
||||||
},
|
},
|
||||||
"plusRateLimited": {
|
|
||||||
"retryIn": "Frigate+ is rate limiting requests. Try again in {{duration}}.",
|
|
||||||
"retryLater": "Frigate+ is rate limiting requests. Try again later."
|
|
||||||
},
|
|
||||||
"selectItem": "Select {{item}}",
|
"selectItem": "Select {{item}}",
|
||||||
"readTheDocumentation": "Read the documentation",
|
"readTheDocumentation": "Read the documentation",
|
||||||
"information": {
|
"information": {
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user