mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-11-24 22:37:08 +03:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
40f6b5f545 | ||
|
|
3a1f4eca4c | ||
|
|
3ad3802988 |
@@ -12,7 +12,7 @@ echo "[INFO] Starting go2rtc healthcheck service..."
|
||||
|
||||
while sleep 30s; do
|
||||
# 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..."
|
||||
# We can also use -r instead of -t to send kill signal rather than term
|
||||
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
|
||||
# root-owned 0600; without this the non-root master exits EACCES
|
||||
chown frigate /dev/stdout
|
||||
fi
|
||||
|
||||
# Mounted certs are never chowned: chown follows symlinks, and the runtime user
|
||||
# may control the mounted folder. The key's group and group read survive certbot
|
||||
# renewals, so the host grants access once.
|
||||
if [[ "$cert_path" == "$letsencrypt_path" && "$runs_as_root" -eq 0 ]] &&
|
||||
[[ "$(echo "$nginx_settings" | jq -r .tls.enabled)" == "true" ]]; then
|
||||
as_runtime=()
|
||||
if [[ "$(id -u)" -eq 0 ]]; then
|
||||
as_runtime=(s6-setuidgid frigate)
|
||||
# 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:
|
||||
# chown follows symlinks, so it would retarget onto any root file the
|
||||
# runtime user pointed it at. Tolerant because mounted certs may be :ro.
|
||||
if [ "$cert_path" = "$letsencrypt_path" ] && [ -f "$cert_path/privkey.pem" ]; then
|
||||
chown frigate:frigate "$cert_path/privkey.pem" "$cert_path/fullchain.pem" 2>/dev/null || true
|
||||
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
|
||||
|
||||
# Replace the bash process with the NGINX process, redirecting stderr to stdout
|
||||
|
||||
@@ -102,7 +102,7 @@ proxy:
|
||||
# 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.
|
||||
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
|
||||
# Optional: The character used to separate multiple values in the proxy headers. (default: shown below)
|
||||
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.
|
||||
|
||||
A `default_role` that does not name a configured role is treated as `none`.
|
||||
|
||||
```yaml
|
||||
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 `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 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, matched without regard to case.
|
||||
- If `role_map` is not defined, Frigate assumes the role header directly contains `admin`, `viewer`, or a custom role name.
|
||||
|
||||
**Note on matching semantics:**
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import NavPath from "@site/src/components/NavPath";
|
||||
|
||||
# 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
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
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:
|
||||
|
||||
|
||||
@@ -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`.
|
||||
|
||||
`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.:
|
||||
|
||||
|
||||
Vendored
+3
-5
@@ -2546,7 +2546,7 @@ paths:
|
||||
- App
|
||||
summary: Metrics
|
||||
description: |-
|
||||
**Access:** Admin role required.
|
||||
**Access:** Any authenticated user.
|
||||
|
||||
Expose Prometheus metrics endpoint and update metrics with latest stats
|
||||
operationId: metrics_metrics_get
|
||||
@@ -2557,8 +2557,8 @@ paths:
|
||||
application/json:
|
||||
schema: {}
|
||||
security:
|
||||
- frigateAdminAuth: []
|
||||
x-required-role: admin
|
||||
- frigateUserAuth: []
|
||||
x-required-role: any
|
||||
/genai/models:
|
||||
get:
|
||||
tags:
|
||||
@@ -9630,8 +9630,6 @@ components:
|
||||
title: Condition
|
||||
max_duration_minutes:
|
||||
type: integer
|
||||
maximum: 1440.0
|
||||
minimum: 1.0
|
||||
title: Max Duration Minutes
|
||||
default: 60
|
||||
labels:
|
||||
|
||||
+35
-46
@@ -64,7 +64,6 @@ from frigate.util.builtin import (
|
||||
is_masked_camera_path,
|
||||
load_labels,
|
||||
process_config_query_string,
|
||||
scope_stats_for_non_admin,
|
||||
split_config_key_path,
|
||||
update_yaml_file_bulk,
|
||||
)
|
||||
@@ -132,12 +131,37 @@ def stats(
|
||||
):
|
||||
stats_data = request.app.stats_emitter.get_latest_stats()
|
||||
|
||||
# Admins see the full snapshot
|
||||
if request.headers.get("remote-role") == "admin":
|
||||
return JSONResponse(content=stats_data)
|
||||
|
||||
return JSONResponse(
|
||||
content=scope_stats_for_non_admin(stats_data, set(allowed_cameras))
|
||||
)
|
||||
allowed_set = 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"]))])
|
||||
@@ -148,7 +172,7 @@ def stats_history(request: Request, keys: str = None):
|
||||
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):
|
||||
"""Expose Prometheus metrics endpoint and update metrics with latest stats"""
|
||||
# Retrieve the latest statistics and update the Prometheus metrics
|
||||
@@ -296,12 +320,10 @@ def config(request: Request):
|
||||
|
||||
is_admin = request.headers.get("remote-role") == "admin"
|
||||
|
||||
# hide environment_vars, the notification email and ffmpeg args (which
|
||||
# can carry auth headers) from non-admin users
|
||||
# hide environment_vars and the notification email from non-admin users
|
||||
if not is_admin:
|
||||
config.pop("environment_vars", None)
|
||||
redact_credential(config["notifications"], "email")
|
||||
_drop_ffmpeg_args(config.get("ffmpeg", {}))
|
||||
|
||||
# redact mqtt credentials
|
||||
redact_credential(config["mqtt"], "password")
|
||||
@@ -309,15 +331,11 @@ def config(request: Request):
|
||||
# redact proxy 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():
|
||||
if isinstance(genai_cfg, dict):
|
||||
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():
|
||||
camera_dict = config["cameras"][camera_name]
|
||||
|
||||
@@ -335,19 +353,6 @@ def config(request: Request):
|
||||
for cmd in camera_dict["ffmpeg_cmds"]:
|
||||
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
|
||||
for zone_name, zone in config_obj.cameras[camera_name].zones.items():
|
||||
camera_dict["zones"][zone_name]["color"] = zone.color
|
||||
@@ -358,13 +363,11 @@ def config(request: Request):
|
||||
# over the camera's actual base values (e.g. threshold=20).
|
||||
if camera.profiles:
|
||||
for profile_name, profile_config in camera.profiles.items():
|
||||
profile_dict = profile_config.model_dump(
|
||||
mode="json", warnings="none", exclude_unset=True
|
||||
camera_dict.setdefault("profiles", {})[profile_name] = (
|
||||
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
|
||||
# profile-merged (effective) values. Include the original base
|
||||
@@ -406,15 +409,6 @@ def config(request: Request):
|
||||
|
||||
_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()}
|
||||
|
||||
for index, model in enumerate(config_obj.models):
|
||||
@@ -441,11 +435,6 @@ def config(request: Request):
|
||||
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:
|
||||
"""Redact go2rtc secrets outside of stream URLs, in place."""
|
||||
for section in ("rtsp", "api", "mqtt"):
|
||||
|
||||
+18
-16
@@ -81,11 +81,10 @@ def require_admin_by_default():
|
||||
"/",
|
||||
"/version",
|
||||
"/config/schema.json",
|
||||
# Admin endpoints that enforce require_role on the route
|
||||
"/metrics",
|
||||
"/stats/history",
|
||||
# Authenticated user endpoints (allow_any_authenticated)
|
||||
"/metrics",
|
||||
"/stats",
|
||||
"/stats/history",
|
||||
"/config",
|
||||
"/vainfo",
|
||||
"/nvinfo",
|
||||
@@ -581,9 +580,8 @@ def resolve_role(
|
||||
(split by proxy_config.separator) and map to roles.
|
||||
Admin matches short-circuit to admin.
|
||||
- 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'.
|
||||
The literal value 'none' means access should be denied.
|
||||
A role_map match whose mapped roles no longer exist in config_roles also resolves to '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' is a valid default and means access should be denied.
|
||||
|
||||
Args:
|
||||
headers (dict): Incoming request headers (case-insensitive).
|
||||
@@ -596,11 +594,17 @@ def resolve_role(
|
||||
default_role = proxy_config.default_role
|
||||
role_header = proxy_config.header_map.role
|
||||
|
||||
# Role names match case-insensitively, as header values are lowercased.
|
||||
# "none" is the deny sentinel; an unknown or missing default also denies,
|
||||
# since falling back to viewer would grant every camera.
|
||||
roles_by_name = {r.lower(): r for r in config_roles}
|
||||
validated_default = roles_by_name.get((default_role or "").lower(), "none")
|
||||
# Validate default_role against config; fallback to 'viewer' if invalid.
|
||||
# "none" is a sentinel meaning "deny access when no mapping matches"; it is
|
||||
# reserved in AuthConfig.validate_roles so it is never a configured role.
|
||||
validated_default = (
|
||||
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:
|
||||
logger.debug(
|
||||
@@ -627,7 +631,7 @@ def resolve_role(
|
||||
logger.debug("Parsed groups from role header: %s", groups)
|
||||
|
||||
matched_roles = {
|
||||
role_name.lower()
|
||||
role_name
|
||||
for role_name, required_groups in proxy_config.header_map.role_map.items()
|
||||
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'.")
|
||||
return "admin"
|
||||
|
||||
# A mapped role that was deleted or renamed denies rather than
|
||||
# widening to the default role
|
||||
if matched_roles:
|
||||
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)
|
||||
return resolved
|
||||
@@ -662,7 +664,7 @@ def resolve_role(
|
||||
logger.debug("Parsed roles directly from header: %s", roles_from_header)
|
||||
|
||||
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,
|
||||
)
|
||||
if resolved == validated_default and roles_from_header:
|
||||
|
||||
+8
-24
@@ -6,7 +6,6 @@ import logging
|
||||
import re
|
||||
from importlib.util import find_spec
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import quote_plus
|
||||
|
||||
import httpx
|
||||
@@ -83,23 +82,6 @@ def _is_valid_host(host: str) -> bool:
|
||||
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())])
|
||||
async def go2rtc_streams(request: Request):
|
||||
try:
|
||||
@@ -132,11 +114,10 @@ async def go2rtc_streams(request: Request):
|
||||
if _get_stream_owner_cameras(request, name) & allowed_cameras
|
||||
}
|
||||
|
||||
return JSONResponse(
|
||||
content={
|
||||
name: _clean_stream(request, data) for name, data in stream_data.items()
|
||||
}
|
||||
)
|
||||
for data in stream_data.values():
|
||||
for producer in data.get("producers") or []:
|
||||
producer["url"] = clean_camera_user_pass(producer.get("url", ""))
|
||||
return JSONResponse(content=stream_data)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -174,7 +155,10 @@ def go2rtc_camera_stream(request: Request, stream_name: str):
|
||||
content=({"success": False, "message": "Error fetching stream data"}),
|
||||
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(
|
||||
|
||||
+4
-22
@@ -6,7 +6,6 @@ import json
|
||||
import logging
|
||||
import operator
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from functools import reduce
|
||||
from typing import Any, Literal
|
||||
@@ -15,7 +14,7 @@ import cv2
|
||||
import numpy as np
|
||||
from fastapi import APIRouter, Body, Depends, HTTPException, Request
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel
|
||||
|
||||
from frigate.api.auth import (
|
||||
allow_any_authenticated,
|
||||
@@ -57,7 +56,6 @@ from frigate.genai.utils import (
|
||||
)
|
||||
from frigate.jobs.export import ExportQueueFullError, start_export_job
|
||||
from frigate.jobs.vlm_watch import (
|
||||
MAX_WATCH_MINUTES,
|
||||
VLMWatchJob,
|
||||
get_vlm_watch_job,
|
||||
start_vlm_watch_job,
|
||||
@@ -90,7 +88,7 @@ class VLMMonitorRequest(BaseModel):
|
||||
|
||||
camera: str
|
||||
condition: str
|
||||
max_duration_minutes: int = Field(default=60, ge=1, le=MAX_WATCH_MINUTES)
|
||||
max_duration_minutes: int = 60
|
||||
labels: list[str] = []
|
||||
zones: list[str] = []
|
||||
|
||||
@@ -1032,17 +1030,12 @@ async def _execute_start_camera_watch(
|
||||
camera = arguments.get("camera", "").strip()
|
||||
condition = arguments.get("condition", "").strip()
|
||||
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 []
|
||||
zones = arguments.get("zones") or []
|
||||
|
||||
if not camera or not condition:
|
||||
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
|
||||
if camera not in config.cameras:
|
||||
return {"error": f"Camera '{camera}' not found."}
|
||||
@@ -1281,14 +1274,6 @@ def _pending_tool_calls_from_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(
|
||||
pending_tool_calls: list[dict[str, Any]],
|
||||
body: ChatCompletionRequest,
|
||||
@@ -1614,7 +1599,6 @@ async def chat_completion(
|
||||
return
|
||||
requested = msg.get("tool_calls")
|
||||
if requested:
|
||||
requested = _with_server_ids(requested)
|
||||
stream_iterations += 1
|
||||
conversation.append(
|
||||
build_assistant_message_for_conversation(
|
||||
@@ -1700,15 +1684,13 @@ async def chat_completion(
|
||||
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(
|
||||
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:
|
||||
logger.debug(
|
||||
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,
|
||||
)
|
||||
|
||||
attributes = (event.data or {}).get("attributes") or []
|
||||
snapshot = get_event_snapshot(event) if attributes else None
|
||||
success = False
|
||||
snapshot = get_event_snapshot(event)
|
||||
face_box = event.data["attributes"][0]["box"]
|
||||
detect_config: DetectConfig = request.app.frigate_config.cameras[
|
||||
event.camera
|
||||
].detect
|
||||
|
||||
if snapshot is not None:
|
||||
face_box = attributes[0]["box"]
|
||||
detect_config: DetectConfig = request.app.frigate_config.cameras[
|
||||
event.camera
|
||||
].detect
|
||||
# crop onto the face box minus the bounding box itself
|
||||
x1 = int(face_box[0] * detect_config.width) + 2
|
||||
y1 = int(face_box[1] * detect_config.height) + 2
|
||||
x2 = x1 + int(face_box[2] * detect_config.width) - 4
|
||||
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
|
||||
x1 = int(face_box[0] * detect_config.width) + 2
|
||||
y1 = int(face_box[1] * detect_config.height) + 2
|
||||
x2 = x1 + int(face_box[2] * detect_config.width) - 4
|
||||
y2 = y1 + int(face_box[3] * detect_config.height) - 4
|
||||
face = snapshot[y1:y2, x1:x2]
|
||||
|
||||
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 face.size > 0:
|
||||
try:
|
||||
cv2.imwrite(os.path.join(new_file_folder, new_name), face)
|
||||
success = True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not success:
|
||||
return JSONResponse(
|
||||
@@ -1275,10 +1273,7 @@ async def generate_state_examples(request: Request, body: GenerateStateExamplesB
|
||||
if camera_name in request.app.frigate_config.cameras
|
||||
}
|
||||
|
||||
async with example_collection_lock:
|
||||
await asyncio.to_thread(
|
||||
collect_state_classification_examples, model_name, cameras_normalized
|
||||
)
|
||||
collect_state_classification_examples(model_name, cameras_normalized)
|
||||
|
||||
return JSONResponse(
|
||||
content={"success": True, "message": "Example generation completed"},
|
||||
|
||||
@@ -41,9 +41,6 @@ def swap_runtime_config(app: FastAPI, config: FrigateConfig) -> None:
|
||||
"""
|
||||
app.frigate_config = config
|
||||
|
||||
if app.replay_manager is not None:
|
||||
app.replay_manager.update_config(config)
|
||||
|
||||
if app.config_holder is not None:
|
||||
app.config_holder.set(config)
|
||||
|
||||
|
||||
@@ -88,7 +88,7 @@ def create_fastapi_app(
|
||||
logger.info("FastAPI started")
|
||||
asyncio.create_task(
|
||||
debug_replay_auto_stop_watchdog(
|
||||
replay_manager, lambda: app.frigate_config, config_publisher
|
||||
replay_manager, frigate_config, config_publisher
|
||||
)
|
||||
)
|
||||
yield
|
||||
|
||||
@@ -47,10 +47,7 @@ from frigate.const import (
|
||||
STREAM_TYPE_SUB,
|
||||
)
|
||||
from frigate.models import Event, Previews, Recordings, Regions, ReviewSegment
|
||||
from frigate.output.preview import (
|
||||
get_most_recent_preview_frame,
|
||||
is_camera_preview_frame,
|
||||
)
|
||||
from frigate.output.preview import get_most_recent_preview_frame
|
||||
from frigate.track.object_processing import TrackedObjectProcessor
|
||||
from frigate.util.ffmpeg import terminate_ffmpeg_stream
|
||||
from frigate.util.file import (
|
||||
@@ -1609,7 +1606,7 @@ async def preview_gif(
|
||||
camera_files = [
|
||||
entry.name
|
||||
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()
|
||||
|
||||
@@ -1800,7 +1797,7 @@ async def preview_mp4(
|
||||
camera_files = [
|
||||
entry.name
|
||||
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()
|
||||
|
||||
|
||||
@@ -22,7 +22,6 @@ from frigate.api.defs.response.preview_response import (
|
||||
from frigate.api.defs.tags import Tags
|
||||
from frigate.const import BASE_DIR, CACHE_DIR, PREVIEW_FRAME_TYPE
|
||||
from frigate.models import Previews
|
||||
from frigate.output.preview import is_camera_preview_frame
|
||||
from frigate.util.time import get_normalized_tz_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)
|
||||
right = bisect.bisect_right(files, end_file)
|
||||
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(
|
||||
|
||||
+10
-19
@@ -180,8 +180,6 @@ class WebPushClient(Communicator):
|
||||
self.refresh: int = 0
|
||||
self.web_pushers: dict[str, list[WebPusher]] = {}
|
||||
self.expired_subs: dict[str, list[str]] = {}
|
||||
self.expired_subs_lock = threading.Lock()
|
||||
self.cleanup_lock = threading.Lock()
|
||||
self.suspended_cameras: dict[str, int] = {
|
||||
c.name: 0 # type: ignore[misc]
|
||||
for c in self.config.cameras.values()
|
||||
@@ -262,23 +260,15 @@ class WebPushClient(Communicator):
|
||||
self.claim_headers[endpoint] = self.vapid.sign(claim)
|
||||
|
||||
def cleanup_registrations(self) -> None:
|
||||
# concurrent cleanups would each restore what the other removed
|
||||
with self.cleanup_lock:
|
||||
with self.expired_subs_lock:
|
||||
expired_subs, self.expired_subs = self.expired_subs, {}
|
||||
|
||||
for user, expired in expired_subs.items():
|
||||
# delete any expired subs
|
||||
if len(self.expired_subs) > 0:
|
||||
for user, expired in self.expired_subs.items():
|
||||
user_subs = []
|
||||
|
||||
# get all subscriptions, removing ones that are expired
|
||||
stored_user: User | None = User.get_or_none(User.username == user)
|
||||
|
||||
# the user was deleted after the endpoint expired
|
||||
if stored_user is None:
|
||||
continue
|
||||
|
||||
stored_user: User = User.get_by_id(user)
|
||||
for token in stored_user.notification_tokens:
|
||||
if isinstance(token, dict) and token.get("endpoint") in expired:
|
||||
if token["endpoint"] in expired:
|
||||
continue
|
||||
|
||||
user_subs.append(token)
|
||||
@@ -294,6 +284,8 @@ class WebPushClient(Communicator):
|
||||
f"Cleaned up {len(expired)} notification subscriptions for {user}"
|
||||
)
|
||||
|
||||
self.expired_subs = {}
|
||||
|
||||
def suspend_notifications(self, camera: str, minutes: int) -> None:
|
||||
"""Suspend notifications for a specific camera."""
|
||||
suspend_until = int(
|
||||
@@ -468,10 +460,9 @@ class WebPushClient(Communicator):
|
||||
)
|
||||
|
||||
if resp.status_code in (404, 410):
|
||||
with self.expired_subs_lock:
|
||||
self.expired_subs.setdefault(notification.user, []).append(
|
||||
endpoint
|
||||
)
|
||||
self.expired_subs.setdefault(notification.user, []).append(
|
||||
endpoint
|
||||
)
|
||||
logger.debug(
|
||||
f"Notification endpoint expired for {notification.user}, received {resp.status_code}"
|
||||
)
|
||||
|
||||
+12
-7
@@ -40,7 +40,6 @@ from frigate.const import (
|
||||
)
|
||||
from frigate.models import User
|
||||
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
|
||||
|
||||
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
|
||||
# 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(
|
||||
{
|
||||
"stats",
|
||||
@@ -456,14 +455,20 @@ def _materialize_for_ws(
|
||||
return _wrap_envelope(topic, filtered_jobs)
|
||||
|
||||
if kind == "reshape_stats":
|
||||
if "admin" in _ws_valid_roles(ws, config):
|
||||
if _ws_is_unrestricted(ws, config):
|
||||
return full_message
|
||||
if not isinstance(parsed_payload, dict):
|
||||
return None
|
||||
return _wrap_envelope(
|
||||
topic,
|
||||
scope_stats_for_non_admin(parsed_payload, _ws_allowed_cameras(ws, config)),
|
||||
)
|
||||
allowed = _ws_allowed_cameras(ws, config)
|
||||
cameras_block = parsed_payload.get("cameras")
|
||||
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
|
||||
|
||||
|
||||
@@ -88,17 +88,16 @@ class AuthConfig(FrigateBaseModel):
|
||||
f"Invalid role name '{role}'. Must be alphanumeric with underscores."
|
||||
)
|
||||
|
||||
# Proxy role headers match role names case-insensitively, so reserved
|
||||
# names are reserved in every casing and names must differ beyond case
|
||||
used_reserved = sorted(r for r in v if r.lower() in ("admin", "viewer", "none"))
|
||||
# 'none' is the deny sentinel for proxy.default_role, where it is matched
|
||||
# case-insensitively, so every casing of it has to be reserved here
|
||||
used_reserved = sorted(
|
||||
r for r in v if r in ("admin", "viewer") or r.lower() == "none"
|
||||
)
|
||||
if used_reserved:
|
||||
raise ValueError(
|
||||
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
|
||||
for role, allowed_cameras in v.items():
|
||||
if not allowed_cameras:
|
||||
|
||||
@@ -1041,15 +1041,6 @@ class FrigateConfig(FrigateBaseModel):
|
||||
# set notifications state
|
||||
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
|
||||
role_to_name: dict[GenAIRoleEnum, str] = {}
|
||||
for name, genai_cfg in self.genai.items():
|
||||
|
||||
@@ -55,9 +55,10 @@ class ProxyConfig(FrigateBaseModel):
|
||||
@field_validator("default_role", mode="before")
|
||||
@classmethod
|
||||
def normalize_deny_sentinel(cls, v):
|
||||
# Fail closed: "none" in any casing and a null default both deny.
|
||||
# Normalizing null keeps the value through /config, which drops nulls
|
||||
if v is None or (isinstance(v, str) and v.strip().lower() == "none"):
|
||||
# Fail closed on capitalization: an unnormalized "None" would miss the
|
||||
# sentinel and fall back to viewer, granting the access it was meant to
|
||||
# deny. Other role names stay case-sensitive.
|
||||
if isinstance(v, str) and v.strip().lower() == "none":
|
||||
return "none"
|
||||
return v
|
||||
|
||||
|
||||
+14
-31
@@ -11,11 +11,10 @@ import os
|
||||
import shutil
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
|
||||
from ruamel.yaml import YAML
|
||||
|
||||
from frigate.config import CameraConfig, FrigateConfig
|
||||
from frigate.config import FrigateConfig
|
||||
from frigate.config.camera.updater import (
|
||||
CameraConfigUpdateEnum,
|
||||
CameraConfigUpdatePublisher,
|
||||
@@ -62,7 +61,6 @@ class DebugReplayManager:
|
||||
self.start_ts: float | None = None
|
||||
self.end_ts: float | None = None
|
||||
self.session_started_at: float | None = None
|
||||
self._published_camera: CameraConfig | None = None
|
||||
self._job_state_publisher = JobStatePublisher()
|
||||
|
||||
@property
|
||||
@@ -111,13 +109,6 @@ class DebugReplayManager:
|
||||
self.start_ts = None
|
||||
self.end_ts = 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(
|
||||
self,
|
||||
@@ -126,11 +117,10 @@ class DebugReplayManager:
|
||||
clip_path: str,
|
||||
frigate_config: FrigateConfig,
|
||||
config_publisher: CameraConfigUpdatePublisher,
|
||||
) -> bool:
|
||||
) -> None:
|
||||
"""Build the in-memory replay camera config and publish the add event.
|
||||
|
||||
Called by the job runner during the starting_camera phase. Returns
|
||||
False without publishing if the session was stopped meanwhile.
|
||||
Called by the job runner during the starting_camera phase.
|
||||
"""
|
||||
source_config = frigate_config.cameras[source_camera]
|
||||
camera_dict = self._build_camera_config_dict(
|
||||
@@ -150,21 +140,12 @@ class DebugReplayManager:
|
||||
new_config = FrigateConfig.parse_object(config_data)
|
||||
except Exception as 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]
|
||||
|
||||
with self._lock:
|
||||
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
|
||||
config_publisher.publish_update(
|
||||
CameraConfigUpdateTopic(CameraConfigUpdateEnum.add, replay_name),
|
||||
new_config.cameras[replay_name],
|
||||
)
|
||||
|
||||
def stop(
|
||||
self,
|
||||
@@ -186,10 +167,12 @@ class DebugReplayManager:
|
||||
replay_name = self.replay_camera_name
|
||||
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(
|
||||
CameraConfigUpdateTopic(CameraConfigUpdateEnum.remove, replay_name),
|
||||
self._published_camera,
|
||||
frigate_config.cameras[replay_name],
|
||||
)
|
||||
frigate_config.cameras.pop(replay_name, None)
|
||||
|
||||
@@ -379,7 +362,7 @@ def cleanup_replay_cameras() -> None:
|
||||
|
||||
async def debug_replay_auto_stop_watchdog(
|
||||
manager: DebugReplayManager,
|
||||
get_config: Callable[[], FrigateConfig],
|
||||
frigate_config: FrigateConfig,
|
||||
config_publisher: CameraConfigUpdatePublisher,
|
||||
) -> None:
|
||||
"""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
|
||||
await asyncio.to_thread(
|
||||
manager.stop,
|
||||
frigate_config=get_config(),
|
||||
frigate_config=frigate_config,
|
||||
config_publisher=config_publisher,
|
||||
)
|
||||
logger.info(
|
||||
|
||||
+80
-61
@@ -2,11 +2,14 @@
|
||||
|
||||
import datetime
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
from multiprocessing.synchronize import Event as MpEvent
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from frigate.config import FrigateConfig
|
||||
from frigate.const import CLIPS_DIR
|
||||
from frigate.db.sqlitevecq import SqliteVecQueueDatabase
|
||||
from frigate.models import Event, Timeline
|
||||
from frigate.util.file import delete_event_snapshot, delete_event_thumbnail
|
||||
@@ -140,7 +143,7 @@ class EventCleanup(threading.Thread):
|
||||
events_to_update = []
|
||||
|
||||
## 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
|
||||
|
||||
# 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_detection_days,
|
||||
)
|
||||
file_extension = None # mp4 clips are no longer stored in /clips
|
||||
update_params = {"has_clip": False}
|
||||
|
||||
# get expiration time for this label
|
||||
|
||||
expire_after = (
|
||||
datetime.datetime.now() - datetime.timedelta(days=expire_days)
|
||||
).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
|
||||
query = Event.select(Event.id).where(
|
||||
Event.camera.not_in(self.camera_keys),
|
||||
Event.start_time < expire_after,
|
||||
Event.retain_indefinitely == False,
|
||||
Event.has_clip == True,
|
||||
)
|
||||
|
||||
events_to_update = []
|
||||
@@ -241,7 +280,7 @@ class EventCleanup(threading.Thread):
|
||||
now = datetime.datetime.now()
|
||||
|
||||
## 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
|
||||
# in Explore while sub recordings and review items still exist
|
||||
alert_expire_date = (
|
||||
@@ -259,7 +298,6 @@ class EventCleanup(threading.Thread):
|
||||
.where(
|
||||
Event.camera == name,
|
||||
Event.retain_indefinitely == False,
|
||||
Event.has_clip == True,
|
||||
(
|
||||
(
|
||||
(Event.data["max_severity"] != "detection")
|
||||
@@ -297,62 +335,43 @@ class EventCleanup(threading.Thread):
|
||||
|
||||
# only expire events every 5 minutes
|
||||
while not self.stop_event.wait(300):
|
||||
try:
|
||||
self.expire_events()
|
||||
except Exception:
|
||||
logger.exception("Event cleanup failed, retrying next cycle")
|
||||
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:
|
||||
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...")
|
||||
|
||||
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")
|
||||
|
||||
@@ -67,17 +67,6 @@ def _decode_data_uri(url: str) -> tuple[str, bytes] | 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]:
|
||||
"""Convert OpenAI-style message content (str or multimodal list) to Gemini parts."""
|
||||
if isinstance(content, list):
|
||||
@@ -469,7 +458,6 @@ class GeminiClient(GenAIClient):
|
||||
try:
|
||||
# Convert messages to Gemini format
|
||||
gemini_messages: list[types.Content] = []
|
||||
tool_names = _tool_names_by_id(messages)
|
||||
for msg in messages:
|
||||
role = msg.get("role", "user")
|
||||
content = msg.get("content", "")
|
||||
@@ -532,7 +520,6 @@ class GeminiClient(GenAIClient):
|
||||
parts=[
|
||||
types.Part.from_function_response(
|
||||
name=msg.get("name")
|
||||
or tool_names.get(msg.get("tool_call_id") or "")
|
||||
or msg.get("tool_call_id")
|
||||
or "",
|
||||
response=response_payload,
|
||||
@@ -727,7 +714,6 @@ class GeminiClient(GenAIClient):
|
||||
try:
|
||||
# Convert messages to Gemini format
|
||||
gemini_messages: list[types.Content] = []
|
||||
tool_names = _tool_names_by_id(messages)
|
||||
for msg in messages:
|
||||
role = msg.get("role", "user")
|
||||
content = msg.get("content", "")
|
||||
@@ -790,7 +776,6 @@ class GeminiClient(GenAIClient):
|
||||
parts=[
|
||||
types.Part.from_function_response(
|
||||
name=msg.get("name")
|
||||
or tool_names.get(msg.get("tool_call_id") or "")
|
||||
or msg.get("tool_call_id")
|
||||
or "",
|
||||
response=response_payload,
|
||||
|
||||
@@ -110,13 +110,6 @@ class LlamaCppClient(GenAIClient):
|
||||
"""POST with the configured auth headers injected."""
|
||||
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]:
|
||||
"""Fetch /props from a llama.cpp server, with llama-swap fallback.
|
||||
|
||||
@@ -150,10 +143,16 @@ class LlamaCppClient(GenAIClient):
|
||||
self._supports_tools = 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:
|
||||
return None
|
||||
else:
|
||||
base_url = base_url.replace("/v1", "") # Strip /v1 if included in base_url
|
||||
|
||||
if not self.validate_model:
|
||||
# Probe path
|
||||
@@ -507,7 +506,11 @@ class LlamaCppClient(GenAIClient):
|
||||
|
||||
def _fetch_models_data(self) -> list[dict[str, Any]]:
|
||||
"""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:
|
||||
return []
|
||||
|
||||
@@ -8,7 +8,7 @@ from collections.abc import AsyncGenerator
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
from httpx import HTTPError
|
||||
from httpx import RemoteProtocolError, TimeoutException
|
||||
from ollama import AsyncClient as OllamaAsyncClient
|
||||
from ollama import Client as ApiClient
|
||||
from ollama import ResponseError
|
||||
@@ -282,7 +282,12 @@ class OllamaClient(GenAIClient):
|
||||
|
||||
try:
|
||||
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))
|
||||
return None
|
||||
|
||||
@@ -401,7 +406,13 @@ class OllamaClient(GenAIClient):
|
||||
# image items have to bypass it and post the JSON directly.
|
||||
response = self.provider._request_raw("POST", "/api/embed", json=payload)
|
||||
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))
|
||||
return []
|
||||
|
||||
@@ -542,7 +553,7 @@ class OllamaClient(GenAIClient):
|
||||
)
|
||||
response = self.provider.chat(**request_params)
|
||||
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))
|
||||
return {
|
||||
"content": None,
|
||||
@@ -674,7 +685,7 @@ class OllamaClient(GenAIClient):
|
||||
"finish_reason": "stop",
|
||||
},
|
||||
)
|
||||
except (HTTPError, ResponseError, ConnectionError) as e:
|
||||
except (TimeoutException, ResponseError, ConnectionError) as e:
|
||||
logger.warning("Ollama streaming error: %s", str(e))
|
||||
yield (
|
||||
"message",
|
||||
|
||||
@@ -376,16 +376,13 @@ class DebugReplayJobRunner(threading.Thread):
|
||||
self._finalize_cancelled(clip_path)
|
||||
return
|
||||
|
||||
if not self.replay_manager.publish_camera(
|
||||
self.replay_manager.publish_camera(
|
||||
source_camera=self.job.source_camera,
|
||||
replay_name=replay_name,
|
||||
clip_path=clip_path,
|
||||
frigate_config=self.frigate_config,
|
||||
config_publisher=self.config_publisher,
|
||||
):
|
||||
self._finalize_cancelled(clip_path)
|
||||
return
|
||||
|
||||
)
|
||||
self.replay_manager.mark_session_ready(clip_path)
|
||||
|
||||
self.job.status = JobStatusTypesEnum.success
|
||||
|
||||
@@ -487,9 +487,6 @@ def get_export_job_manager(config: FrigateConfig) -> ExportJobManager:
|
||||
with _job_manager_lock:
|
||||
if _job_manager is None:
|
||||
_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()
|
||||
return _job_manager
|
||||
|
||||
|
||||
+17
-27
@@ -28,8 +28,6 @@ _MAX_INTERVAL = 300
|
||||
# Minimum seconds between VLM iterations when woken by detections (no zone filter)
|
||||
_DETECTION_COOLDOWN_WITHOUT_ZONE = 10
|
||||
|
||||
MAX_WATCH_MINUTES = 1440
|
||||
|
||||
# Max user/assistant turn pairs to keep in conversation history
|
||||
_MAX_HISTORY = 10
|
||||
|
||||
@@ -77,17 +75,15 @@ class VLMWatchRunner(threading.Thread):
|
||||
self.conversation: list[dict[str, Any]] = []
|
||||
|
||||
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:
|
||||
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():
|
||||
if time.monotonic() > max_end_time:
|
||||
logger.debug(
|
||||
@@ -208,13 +204,7 @@ class VLMWatchRunner(threading.Thread):
|
||||
)
|
||||
reasoning = str(parsed.get("reasoning", ""))
|
||||
notification_message = str(parsed.get("notification_message", ""))
|
||||
except (
|
||||
json.JSONDecodeError,
|
||||
ValueError,
|
||||
TypeError,
|
||||
AttributeError,
|
||||
OverflowError,
|
||||
) as e:
|
||||
except (json.JSONDecodeError, ValueError, TypeError) as e:
|
||||
logger.warning(
|
||||
"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,
|
||||
)
|
||||
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
|
||||
_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()
|
||||
|
||||
logger.debug(
|
||||
|
||||
+10
-14
@@ -789,16 +789,16 @@ class BirdsEyeFrameManager:
|
||||
force_update = True
|
||||
else:
|
||||
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):
|
||||
camera_state["last_active_frame"] = frame_time
|
||||
# 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
|
||||
|
||||
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
|
||||
now = time.monotonic()
|
||||
@@ -865,10 +865,7 @@ class Birdseye:
|
||||
(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
|
||||
self.restream = config.birdseye.restream
|
||||
|
||||
if self.restream:
|
||||
if config.birdseye.restream:
|
||||
self.birdseye_buffer: Any = self.frame_manager.create(
|
||||
"birdseye",
|
||||
self.birdseye_manager.yuv_shape[0] * self.birdseye_manager.yuv_shape[1],
|
||||
@@ -880,7 +877,7 @@ class Birdseye:
|
||||
def __send_new_frame(self) -> None:
|
||||
frame_bytes = self.birdseye_manager.frame.tobytes()
|
||||
|
||||
if self.restream:
|
||||
if self.config.birdseye.restream:
|
||||
self.birdseye_buffer[:] = frame_bytes
|
||||
|
||||
try:
|
||||
@@ -957,7 +954,6 @@ class Birdseye:
|
||||
>= self._idle_interval
|
||||
):
|
||||
self.__send_new_frame()
|
||||
self.birdseye_manager.last_output_time = now
|
||||
|
||||
def stop(self) -> None:
|
||||
self.review_subscriber.stop()
|
||||
|
||||
+15
-27
@@ -301,13 +301,13 @@ class OnvifController:
|
||||
logger.debug(f"Imaging service not supported for {camera_name}: {e}")
|
||||
imaging = None
|
||||
cam["imaging"] = imaging
|
||||
cam["video_source_token"] = None
|
||||
try:
|
||||
video_sources = await media.GetVideoSources()
|
||||
if video_sources and len(video_sources) > 0:
|
||||
cam["video_source_token"] = video_sources[0].token
|
||||
except Exception as e:
|
||||
logger.debug(f"Unable to get video sources for {camera_name}: {e}")
|
||||
cam["video_source_token"] = None
|
||||
|
||||
# setup continuous moving request
|
||||
move_request = ptz.create_type("ContinuousMove")
|
||||
@@ -660,15 +660,12 @@ class OnvifController:
|
||||
move_request = cam["move_request"]
|
||||
preset_token = cam["presets"][preset]
|
||||
|
||||
try:
|
||||
await cam["ptz"].GotoPreset(
|
||||
{
|
||||
"ProfileToken": move_request.ProfileToken,
|
||||
"PresetToken": preset_token,
|
||||
}
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"Onvif sending preset request to {camera_name} failed: {e}")
|
||||
await cam["ptz"].GotoPreset(
|
||||
{
|
||||
"ProfileToken": move_request.ProfileToken,
|
||||
"PresetToken": preset_token,
|
||||
}
|
||||
)
|
||||
|
||||
cam["active"] = False
|
||||
|
||||
@@ -693,11 +690,7 @@ class OnvifController:
|
||||
elif command == OnvifCommandEnum.zoom_out:
|
||||
move_request.Velocity = {"Zoom": {"x": -0.5}}
|
||||
|
||||
try:
|
||||
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
|
||||
await cam["ptz"].ContinuousMove(move_request)
|
||||
|
||||
async def _zoom_absolute(self, camera_name: str, zoom, speed) -> None:
|
||||
cam = self.cams[camera_name]
|
||||
@@ -736,18 +729,13 @@ class OnvifController:
|
||||
|
||||
logger.debug(f"{camera_name}: Absolute zoom: {zoom}")
|
||||
|
||||
try:
|
||||
await cam["ptz"].AbsoluteMove(
|
||||
{
|
||||
"ProfileToken": cam["move_request"].ProfileToken,
|
||||
"Position": {"Zoom": zoom},
|
||||
"Speed": {"Zoom": speed},
|
||||
}
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
f"Onvif sending absolute zoom request to {camera_name} failed: {e}"
|
||||
)
|
||||
await cam["ptz"].AbsoluteMove(
|
||||
{
|
||||
"ProfileToken": cam["move_request"].ProfileToken,
|
||||
"Position": {"Zoom": zoom},
|
||||
"Speed": {"Zoom": speed},
|
||||
}
|
||||
)
|
||||
|
||||
cam["active"] = False
|
||||
|
||||
|
||||
@@ -261,18 +261,6 @@ def validate_ffmpeg_args(args: str) -> tuple[bool, str]:
|
||||
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):
|
||||
recordings = "recordings"
|
||||
preview = "preview"
|
||||
@@ -339,8 +327,8 @@ class RecordingExporter(threading.Thread):
|
||||
self.end_time = end_time
|
||||
self.playback_source = playback_source
|
||||
self.export_case_id = export_case_id
|
||||
self.ffmpeg_input_args = normalize_ffmpeg_args(ffmpeg_input_args)
|
||||
self.ffmpeg_output_args = normalize_ffmpeg_args(ffmpeg_output_args)
|
||||
self.ffmpeg_input_args = ffmpeg_input_args
|
||||
self.ffmpeg_output_args = ffmpeg_output_args
|
||||
self.cpu_fallback = cpu_fallback
|
||||
self.chapters = chapters
|
||||
self.stream = stream
|
||||
@@ -1345,7 +1333,7 @@ class RecordingExporter(threading.Thread):
|
||||
end_file = f"{file_start}{self.end_time}.{PREVIEW_FRAME_TYPE}"
|
||||
|
||||
for file in sorted(os.listdir(preview_dir)):
|
||||
if not is_camera_preview_frame(file, self.camera):
|
||||
if not file.startswith(file_start):
|
||||
continue
|
||||
|
||||
if file < start_file:
|
||||
|
||||
+6
-3
@@ -137,7 +137,7 @@ class StorageMaintainer(threading.Thread):
|
||||
|
||||
def calculate_camera_bandwidth(self) -> None:
|
||||
"""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
|
||||
if camera.startswith(REPLAY_CAMERA_PREFIX):
|
||||
continue
|
||||
@@ -186,7 +186,7 @@ class StorageMaintainer(threading.Thread):
|
||||
"""Calculate the storage usage of each camera."""
|
||||
usages: dict[str, dict] = {}
|
||||
|
||||
for camera in list(self.config.cameras):
|
||||
for camera in self.config.cameras.keys():
|
||||
# Skip replay cameras
|
||||
if camera.startswith(REPLAY_CAMERA_PREFIX):
|
||||
continue
|
||||
@@ -208,7 +208,10 @@ class StorageMaintainer(threading.Thread):
|
||||
"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()),
|
||||
"bandwidth": self.camera_storage_stats.get(camera, {}).get(
|
||||
"bandwidth", 0
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import copy
|
||||
import json
|
||||
import os
|
||||
from unittest.mock import Mock, patch
|
||||
@@ -32,23 +31,6 @@ class TestHttpApp(BaseTestHttp):
|
||||
response_json = response.json()
|
||||
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):
|
||||
stats = Mock(spec=StatsEmitter)
|
||||
stats.get_latest_stats.return_value = self.test_stats
|
||||
@@ -199,10 +181,6 @@ class TestHttpApp(BaseTestHttp):
|
||||
|
||||
def test_config_response_hides_notification_email_from_viewers(self):
|
||||
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"}):
|
||||
app = super().create_app()
|
||||
@@ -221,165 +199,10 @@ class TestHttpApp(BaseTestHttp):
|
||||
config["cameras"]["front_door"]["notifications"]["email"]
|
||||
== REDACTED_CREDENTIAL_SENTINEL
|
||||
)
|
||||
assert (
|
||||
config["cameras"]["front_door"]["profiles"]["away"]["notifications"][
|
||||
"email"
|
||||
]
|
||||
== REDACTED_CREDENTIAL_SENTINEL
|
||||
)
|
||||
|
||||
response = client.get("/config")
|
||||
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):
|
||||
model_id = "test_plus_reference"
|
||||
model_path = os.path.join(MODEL_CACHE_DIR, model_id)
|
||||
|
||||
@@ -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 unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import numpy as np
|
||||
from unittest.mock import Mock
|
||||
|
||||
from frigate.config import (
|
||||
BirdseyeModeEnum,
|
||||
@@ -609,72 +607,6 @@ class TestBirdseyeModePayload(unittest.TestCase):
|
||||
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):
|
||||
"""Test that review updates drive the per-camera severity map."""
|
||||
|
||||
|
||||
@@ -264,41 +264,3 @@ class TestCameraFileCleanup(unittest.TestCase):
|
||||
]
|
||||
|
||||
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."""
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
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.types import JobStatusTypesEnum
|
||||
from frigate.jobs.vlm_watch import VLMWatchJob
|
||||
|
||||
|
||||
def _request(user: str, role: str) -> SimpleNamespace:
|
||||
@@ -60,51 +58,6 @@ class TestStartCameraWatch(unittest.TestCase):
|
||||
|
||||
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__":
|
||||
unittest.main()
|
||||
|
||||
@@ -22,7 +22,6 @@ from frigate.api.chat import (
|
||||
_execute_pending_tools,
|
||||
_pending_tool_calls_from_tail,
|
||||
_tool_calls_awaiting_approval,
|
||||
_with_server_ids,
|
||||
)
|
||||
from frigate.api.defs.request.chat_body import ChatCompletionRequest
|
||||
from frigate.genai.prompts import (
|
||||
@@ -153,22 +152,6 @@ class TestApprovalHelpers(unittest.TestCase):
|
||||
body = _body(tool_decisions={"c2": "approve", "c3": "reject"})
|
||||
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):
|
||||
def test_rejected_call_is_not_executed(self):
|
||||
|
||||
@@ -7,10 +7,7 @@ from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
|
||||
from frigate.util.classification import (
|
||||
_extract_event_thumbnails,
|
||||
_select_balanced_timestamps,
|
||||
)
|
||||
from frigate.util.classification import _extract_event_thumbnails
|
||||
|
||||
|
||||
class TestExtractEventThumbnails(unittest.TestCase):
|
||||
@@ -32,17 +29,5 @@ class TestExtractEventThumbnails(unittest.TestCase):
|
||||
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__":
|
||||
unittest.main()
|
||||
|
||||
@@ -24,7 +24,6 @@ class TestSwapRuntimeConfig(unittest.TestCase):
|
||||
|
||||
self.assertIs(app.frigate_config, 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)
|
||||
self.assertIs(app.stats_emitter.config, 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")
|
||||
|
||||
camera_config = MagicMock()
|
||||
manager._published_camera = camera_config
|
||||
frigate_config = MagicMock()
|
||||
frigate_config.cameras = {"_replay_front": camera_config}
|
||||
publisher = MagicMock()
|
||||
@@ -170,7 +169,6 @@ class TestDebugReplayManagerPublishCamera(unittest.TestCase):
|
||||
from frigate.debug_replay import DebugReplayManager
|
||||
|
||||
manager = DebugReplayManager()
|
||||
manager.mark_starting("front", "_replay_front", 100.0, 200.0)
|
||||
|
||||
source_config = MagicMock()
|
||||
new_camera_config = MagicMock()
|
||||
@@ -248,103 +246,5 @@ class TestDebugReplayManagerPublishCamera(unittest.TestCase):
|
||||
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__":
|
||||
unittest.main()
|
||||
|
||||
@@ -302,7 +302,7 @@ class TestRunnerHappyPath(unittest.TestCase):
|
||||
patch.object(
|
||||
self.manager,
|
||||
"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.makedirs"),
|
||||
|
||||
@@ -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()
|
||||
@@ -143,37 +143,6 @@ class TestValidateFfmpegArgs(unittest.TestCase):
|
||||
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):
|
||||
"""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."""
|
||||
|
||||
import datetime
|
||||
import io
|
||||
import os
|
||||
import shutil
|
||||
@@ -8,14 +7,11 @@ import tempfile
|
||||
import unittest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from peewee import SqliteDatabase
|
||||
|
||||
from frigate.jobs.export import (
|
||||
PROGRESS_BROADCAST_MIN_INTERVAL,
|
||||
ExportJob,
|
||||
ExportJobManager,
|
||||
)
|
||||
from frigate.models import Previews
|
||||
from frigate.record.export import (
|
||||
ExportStreamEnum,
|
||||
PlaybackSourceEnum,
|
||||
@@ -225,24 +221,6 @@ class TestFfmpegProgressParsing(unittest.TestCase):
|
||||
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):
|
||||
"""Verify ExportJobManager broadcast payload shape and throttling."""
|
||||
|
||||
@@ -579,38 +557,5 @@ class TestChapterMetadataInProgressReview(unittest.TestCase):
|
||||
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__":
|
||||
unittest.main()
|
||||
|
||||
@@ -19,7 +19,6 @@ import unittest
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import httpx
|
||||
import requests
|
||||
|
||||
from frigate.config import GenAIConfig, GenAIProviderEnum
|
||||
@@ -501,42 +500,6 @@ class TestGeminiProvider(unittest.TestCase):
|
||||
final = _final_message(_collect(client, MULTIMODAL_MESSAGES))
|
||||
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):
|
||||
def _client(self, count_tokens):
|
||||
@@ -858,13 +821,6 @@ class TestOllamaProvider(unittest.TestCase):
|
||||
|
||||
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
|
||||
@@ -1019,23 +975,6 @@ class TestLlamaCppProvider(unittest.TestCase):
|
||||
client = self._validated_client(4096, {"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):
|
||||
client = self._client()
|
||||
models_data = [
|
||||
|
||||
@@ -135,31 +135,6 @@ class TestModelDownloadState(unittest.TestCase):
|
||||
self.assertEqual(states[-1]["state"], "error")
|
||||
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 swallowing(path: str) -> None:
|
||||
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()
|
||||
@@ -95,42 +95,6 @@ class TestProxyRoleResolution(unittest.TestCase):
|
||||
role = resolve_role(headers, self.proxy_config, self.config_roles)
|
||||
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):
|
||||
def setUp(self):
|
||||
@@ -226,9 +190,6 @@ class TestDefaultRoleNone(unittest.TestCase):
|
||||
)
|
||||
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):
|
||||
"""Only the deny sentinel is normalized; role names are untouched."""
|
||||
config = ProxyConfig(default_role="Operator")
|
||||
@@ -260,18 +221,8 @@ class TestReservedRoleNames(unittest.TestCase):
|
||||
with self.assertRaises(ValidationError):
|
||||
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):
|
||||
"""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"]})
|
||||
self.assertEqual(config.roles["Operator"], ["front_door"])
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ from unittest.mock import AsyncMock, MagicMock
|
||||
from frigate.camera import PTZMetrics
|
||||
from frigate.config import FrigateConfig
|
||||
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"
|
||||
|
||||
@@ -157,14 +157,6 @@ class TestOnvifInitRequests(unittest.IsolatedAsyncioTestCase):
|
||||
ptz.GetServiceCapabilities.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):
|
||||
"""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"])
|
||||
|
||||
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:
|
||||
# get_camera_status resets stop_time once the camera reports IDLE, so the
|
||||
# autotracking path keeps its motion estimation timestamps
|
||||
|
||||
@@ -440,36 +440,6 @@ class TestHttp(unittest.TestCase):
|
||||
assert usages["front_door"]["usage"] == 0
|
||||
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):
|
||||
"""Ensure that all recordings are cleaned up when necessary."""
|
||||
config = FrigateConfig(**self.minimal_config)
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
"""Tests for expired push subscription cleanup."""
|
||||
|
||||
import threading
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from peewee import SqliteDatabase
|
||||
|
||||
from frigate.comms.webpush import WebPushClient
|
||||
from frigate.models import User
|
||||
|
||||
LIVE = {"endpoint": "https://push.example.com/live", "keys": {}}
|
||||
DEAD = {"endpoint": "https://push.example.com/dead", "keys": {}}
|
||||
|
||||
|
||||
class TestCleanupRegistrations(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.db = SqliteDatabase(":memory:")
|
||||
self.enterContext(self.db.bind_ctx([User]))
|
||||
self.db.create_tables([User])
|
||||
|
||||
User.create(
|
||||
username="alice", password_hash="x", notification_tokens=[LIVE, DEAD]
|
||||
)
|
||||
|
||||
self.client = WebPushClient.__new__(WebPushClient)
|
||||
self.client.web_pushers = {}
|
||||
self.client.expired_subs = {}
|
||||
self.client.expired_subs_lock = threading.Lock()
|
||||
self.client.cleanup_lock = threading.Lock()
|
||||
|
||||
def tearDown(self):
|
||||
self.db.close()
|
||||
|
||||
@patch("frigate.comms.webpush._build_web_pushers", return_value=[])
|
||||
def test_skips_deleted_user_and_prunes_the_rest(self, _build):
|
||||
self.client.expired_subs = {
|
||||
"deleted": ["https://push.example.com/gone"],
|
||||
"alice": [DEAD["endpoint"]],
|
||||
}
|
||||
|
||||
self.client.cleanup_registrations()
|
||||
|
||||
self.assertEqual(User.get_by_id("alice").notification_tokens, [LIVE])
|
||||
self.assertEqual(self.client.expired_subs, {})
|
||||
_build.assert_called_once_with("alice", [LIVE])
|
||||
|
||||
@patch("frigate.comms.webpush._build_web_pushers", return_value=[])
|
||||
def test_keeps_malformed_tokens_and_prunes_expired(self, _build):
|
||||
malformed = [None, {"keys": {}}]
|
||||
User.update(notification_tokens=[LIVE, *malformed, DEAD]).execute()
|
||||
self.client.expired_subs = {"alice": [DEAD["endpoint"]]}
|
||||
|
||||
self.client.cleanup_registrations()
|
||||
|
||||
self.assertEqual(
|
||||
User.get_by_id("alice").notification_tokens, [LIVE, *malformed]
|
||||
)
|
||||
@@ -517,8 +517,6 @@ class TestMaterializeForWs(unittest.TestCase):
|
||||
"garage": {"camera_fps": 5.0, "pid": 1236},
|
||||
},
|
||||
"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"},
|
||||
"camera_fps": 15.0,
|
||||
"detection_fps": 6.0,
|
||||
@@ -542,17 +540,6 @@ class TestMaterializeForWs(unittest.TestCase):
|
||||
self.assertIn("detectors", 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):
|
||||
"""A restricted role whose allow-list contains only nonexistent cameras
|
||||
still gets the global aggregates and service block."""
|
||||
|
||||
@@ -131,34 +131,6 @@ def clean_camera_user_pass(line: str) -> str:
|
||||
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:
|
||||
# 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.
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
"""Utilities for cleaning up camera data from database and filesystem."""
|
||||
|
||||
import glob
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
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 (
|
||||
Event,
|
||||
Export,
|
||||
@@ -113,18 +112,12 @@ def cleanup_camera_files(
|
||||
export_paths: Optional list of export file paths to remove
|
||||
"""
|
||||
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(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:
|
||||
if os.path.exists(dir_path):
|
||||
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)
|
||||
"""
|
||||
model_name = model_name.strip()
|
||||
dataset_dir = os.path.join(CLIPS_DIR, model_name, "dataset")
|
||||
|
||||
# Step 1: Get review items for the cameras
|
||||
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}")
|
||||
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)
|
||||
timestamps = _select_balanced_timestamps(review_items, target_count=100)
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# Step 3: Extract keyframes from recordings with crops applied
|
||||
keyframes = _extract_keyframes(
|
||||
"/usr/lib/ffmpeg/8.0/bin/ffmpeg", timestamps, temp_dir, cameras
|
||||
)
|
||||
# Step 3: Extract keyframes from recordings with crops applied
|
||||
keyframes = _extract_keyframes(
|
||||
"/usr/lib/ffmpeg/8.0/bin/ffmpeg", timestamps, temp_dir, cameras
|
||||
)
|
||||
|
||||
# Step 4: Select 24 most visually distinct images (they're already cropped)
|
||||
distinct_images = _select_distinct_images(keyframes, target_count=24)
|
||||
# Step 4: Select 24 most visually distinct images (they're already cropped)
|
||||
distinct_images = _select_distinct_images(keyframes, target_count=24)
|
||||
|
||||
# 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."""
|
||||
# Step 5: Save to train directory for later classification
|
||||
train_dir = os.path.join(CLIPS_DIR, model_name, "train")
|
||||
if os.path.exists(train_dir):
|
||||
shutil.rmtree(train_dir)
|
||||
os.makedirs(train_dir, exist_ok=True)
|
||||
|
||||
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")
|
||||
try:
|
||||
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:
|
||||
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(
|
||||
@@ -522,20 +524,13 @@ def _select_balanced_timestamps(
|
||||
}
|
||||
)
|
||||
|
||||
# Sample more from larger groups. Zero-length items and timestamps too
|
||||
# close to an existing one never add a sample, so attempts are capped.
|
||||
max_attempts = target_count * 10
|
||||
attempts = 0
|
||||
while (
|
||||
len(timestamps) < target_count
|
||||
and len(timestamps) < len(review_items)
|
||||
and attempts < max_attempts
|
||||
):
|
||||
# If we don't have enough, sample more from larger groups
|
||||
while len(timestamps) < target_count and len(timestamps) < len(review_items):
|
||||
for group_items in grouped.values():
|
||||
if len(timestamps) >= target_count or attempts >= max_attempts:
|
||||
if len(timestamps) >= target_count:
|
||||
break
|
||||
|
||||
attempts += 1
|
||||
# Pick a random item not already sampled
|
||||
item = random.choice(group_items)
|
||||
duration = item.end_time - item.start_time
|
||||
if duration <= 0:
|
||||
@@ -775,6 +770,9 @@ def collect_object_classification_examples(
|
||||
label: Object label to collect (e.g., "person", "car")
|
||||
"""
|
||||
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
|
||||
events = list(
|
||||
@@ -796,21 +794,41 @@ def collect_object_classification_examples(
|
||||
selected_ids = {e.id for e in selected_events}
|
||||
remaining_events = [e for e in events if e.id not in selected_ids]
|
||||
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:
|
||||
thumbnails = _extract_event_thumbnails(
|
||||
selected_events + remaining_events, temp_dir, target_count=100
|
||||
)
|
||||
logger.debug(f"Successfully extracted {len(thumbnails)} thumbnails")
|
||||
# Step 4: Select 24 most visually distinct thumbnails
|
||||
distinct_images = _select_distinct_images(thumbnails, target_count=24)
|
||||
logger.debug(f"Selected {len(distinct_images)} distinct images")
|
||||
|
||||
# Step 4: Select 24 most visually distinct thumbnails
|
||||
distinct_images = _select_distinct_images(thumbnails, target_count=24)
|
||||
logger.debug(f"Selected {len(distinct_images)} distinct images")
|
||||
# Step 5: Save to train directory for later classification
|
||||
train_dir = os.path.join(CLIPS_DIR, model_name, "train")
|
||||
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 = _save_train_examples(model_name, distinct_images)
|
||||
saved_count = 0
|
||||
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(
|
||||
|
||||
+17
-21
@@ -85,35 +85,28 @@ class ModelDownloader:
|
||||
)
|
||||
|
||||
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:
|
||||
path = os.path.join(self.download_path, file_name)
|
||||
lock_path = f"{path}.lock"
|
||||
lock = FileLock(lock_path, cleanup_stale_on_init=True)
|
||||
|
||||
if not os.path.exists(path):
|
||||
try:
|
||||
with lock:
|
||||
if not os.path.exists(path):
|
||||
with lock:
|
||||
if not os.path.exists(path):
|
||||
try:
|
||||
self.download_func(path)
|
||||
except Exception as e:
|
||||
self._report_failure(file_name, _first_line(e))
|
||||
self._send_state(file_name, ModelStatusTypesEnum.error)
|
||||
raise
|
||||
except Exception as e:
|
||||
self._report_failure(file_name, _first_line(e))
|
||||
self._send_state(file_name, ModelStatusTypesEnum.error)
|
||||
raise
|
||||
|
||||
if not os.path.exists(path):
|
||||
self._report_failure(
|
||||
file_name,
|
||||
last_download_error.pop(path, "download failed"),
|
||||
)
|
||||
self._send_state(file_name, ModelStatusTypesEnum.error)
|
||||
continue
|
||||
if not os.path.exists(path):
|
||||
self._report_failure(
|
||||
file_name,
|
||||
last_download_error.pop(path, "download failed"),
|
||||
)
|
||||
self._send_state(file_name, ModelStatusTypesEnum.error)
|
||||
continue
|
||||
|
||||
self._resolve_failure(file_name)
|
||||
self._send_state(file_name, ModelStatusTypesEnum.downloaded)
|
||||
@@ -121,6 +114,9 @@ class ModelDownloader:
|
||||
if self.complete_func:
|
||||
self.complete_func()
|
||||
|
||||
self.requestor.stop()
|
||||
self.download_complete.set()
|
||||
|
||||
@staticmethod
|
||||
def download_from_url(url: str, save_path: str, silent: bool = False) -> Path:
|
||||
temporary_filename = Path(save_path).with_name(
|
||||
|
||||
@@ -262,15 +262,11 @@ def delete_event_snapshot(event: Event) -> bool:
|
||||
def delete_event_thumbnail(event: Event) -> bool:
|
||||
if event.thumbnail:
|
||||
return True
|
||||
|
||||
try:
|
||||
else:
|
||||
Path(os.path.join(THUMB_DIR, event.camera, f"{event.id}.webp")).unlink(
|
||||
missing_ok=True
|
||||
)
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
return True
|
||||
return True
|
||||
|
||||
|
||||
### Training Images
|
||||
|
||||
@@ -91,8 +91,7 @@ def get_categorized_object_names(
|
||||
continue
|
||||
|
||||
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 {
|
||||
label: sorted(label_names)
|
||||
|
||||
@@ -18,9 +18,6 @@ import {
|
||||
} from "@/components/ui/popover";
|
||||
import { getUnitSize } from "@/utils/storageUtil";
|
||||
import { CameraStorage, StreamStorage } from "@/types/stats";
|
||||
import { FrigateConfig } from "@/types/frigateConfig";
|
||||
import { resolveCameraName } from "@/hooks/use-camera-friendly-name";
|
||||
import useSWR from "swr";
|
||||
|
||||
import { CiCircleAlert } from "react-icons/ci";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -54,7 +51,6 @@ export function CombinedStorageGraph({
|
||||
}: CombinedStorageGraphProps) {
|
||||
const { t } = useTranslation(["views/system", "components/player"]);
|
||||
|
||||
const { data: config } = useSWR<FrigateConfig>("config");
|
||||
const { theme, systemTheme } = useTheme();
|
||||
const isDark = (systemTheme || theme) == "dark";
|
||||
|
||||
@@ -201,10 +197,10 @@ export function CombinedStorageGraph({
|
||||
} else if (name == "Other") {
|
||||
return t("label.other", { ns: "common" });
|
||||
} else {
|
||||
return resolveCameraName(config, name);
|
||||
return name.replaceAll("_", " ");
|
||||
}
|
||||
},
|
||||
[t, config],
|
||||
[t],
|
||||
);
|
||||
|
||||
const getStreamSplit = useCallback(
|
||||
|
||||
@@ -61,9 +61,7 @@ export default function CreateRoleDialog({
|
||||
(config.cameras[b]?.ui?.order ?? 0),
|
||||
);
|
||||
|
||||
const existingRoles = Object.keys(config.auth?.roles || {}).map((role) =>
|
||||
role.toLowerCase(),
|
||||
);
|
||||
const existingRoles = Object.keys(config.auth?.roles || {});
|
||||
|
||||
const formSchema = z.object({
|
||||
role: z
|
||||
@@ -72,7 +70,7 @@ export default function CreateRoleDialog({
|
||||
.regex(/^[A-Za-z0-9._]+$/, {
|
||||
message: t("roles.dialog.form.role.roleOnlyInclude"),
|
||||
})
|
||||
.refine((role) => !existingRoles.includes(role.toLowerCase()), {
|
||||
.refine((role) => !existingRoles.includes(role), {
|
||||
message: t("roles.dialog.form.role.roleExists"),
|
||||
}),
|
||||
cameras: z
|
||||
|
||||
+20
-1
@@ -5,11 +5,30 @@ export type VideoResolutionType = {
|
||||
};
|
||||
|
||||
type LiveProducerMetadata = {
|
||||
medias?: string[] | null;
|
||||
type: string;
|
||||
url: string;
|
||||
remote_addr: string;
|
||||
user_agent: string;
|
||||
sdp: string;
|
||||
medias?: string[];
|
||||
receivers?: string[];
|
||||
recv: number;
|
||||
};
|
||||
|
||||
type LiveConsumerMetadata = {
|
||||
type: string;
|
||||
url: string;
|
||||
remote_addr: string;
|
||||
user_agent: string;
|
||||
sdp: string;
|
||||
medias?: string[];
|
||||
senders?: string[];
|
||||
send: number;
|
||||
};
|
||||
|
||||
export type LiveStreamMetadata = {
|
||||
producers: LiveProducerMetadata[];
|
||||
consumers: LiveConsumerMetadata[];
|
||||
};
|
||||
|
||||
// mse-codec is go2rtc's proof that it has no codec this browser plays;
|
||||
|
||||
@@ -16,8 +16,7 @@ export function processCameraName(userInput: string): {
|
||||
} {
|
||||
const normalizedInput = userInput.replace(/\s+/g, "_").toLowerCase();
|
||||
|
||||
// debug replay owns this prefix and deletes data for cameras that use it
|
||||
if (isValidId(normalizedInput) && !isReplayCamera(normalizedInput)) {
|
||||
if (isValidId(normalizedInput)) {
|
||||
return {
|
||||
finalCameraName: normalizedInput,
|
||||
friendlyName: userInput.includes(" ") ? userInput : undefined,
|
||||
|
||||
Reference in New Issue
Block a user