mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-11-24 14:27:06 +03:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
06feb4b591 |
Vendored
+2
@@ -9630,6 +9630,8 @@ components:
|
||||
title: Condition
|
||||
max_duration_minutes:
|
||||
type: integer
|
||||
maximum: 1440.0
|
||||
minimum: 1.0
|
||||
title: Max Duration Minutes
|
||||
default: 60
|
||||
labels:
|
||||
|
||||
+8
-2
@@ -14,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
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from frigate.api.auth import (
|
||||
allow_any_authenticated,
|
||||
@@ -56,6 +56,7 @@ 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,
|
||||
@@ -88,7 +89,7 @@ class VLMMonitorRequest(BaseModel):
|
||||
|
||||
camera: str
|
||||
condition: str
|
||||
max_duration_minutes: int = 60
|
||||
max_duration_minutes: int = Field(default=60, ge=1, le=MAX_WATCH_MINUTES)
|
||||
labels: list[str] = []
|
||||
zones: list[str] = []
|
||||
|
||||
@@ -1030,12 +1031,17 @@ 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."}
|
||||
|
||||
@@ -216,26 +216,28 @@ def train_face(request: Request, name: str, body: dict = None):
|
||||
status_code=404,
|
||||
)
|
||||
|
||||
snapshot = get_event_snapshot(event)
|
||||
face_box = event.data["attributes"][0]["box"]
|
||||
detect_config: DetectConfig = request.app.frigate_config.cameras[
|
||||
event.camera
|
||||
].detect
|
||||
attributes = (event.data or {}).get("attributes") or []
|
||||
snapshot = get_event_snapshot(event) if attributes else None
|
||||
success = False
|
||||
|
||||
# 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
|
||||
if snapshot is not None:
|
||||
face_box = attributes[0]["box"]
|
||||
detect_config: DetectConfig = request.app.frigate_config.cameras[
|
||||
event.camera
|
||||
].detect
|
||||
|
||||
if face.size > 0:
|
||||
try:
|
||||
cv2.imwrite(os.path.join(new_file_folder, new_name), face)
|
||||
success = True
|
||||
except Exception:
|
||||
pass
|
||||
# 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 not success:
|
||||
return JSONResponse(
|
||||
@@ -1273,7 +1275,10 @@ async def generate_state_examples(request: Request, body: GenerateStateExamplesB
|
||||
if camera_name in request.app.frigate_config.cameras
|
||||
}
|
||||
|
||||
collect_state_classification_examples(model_name, cameras_normalized)
|
||||
async with example_collection_lock:
|
||||
await asyncio.to_thread(
|
||||
collect_state_classification_examples, model_name, cameras_normalized
|
||||
)
|
||||
|
||||
return JSONResponse(
|
||||
content={"success": True, "message": "Example generation completed"},
|
||||
|
||||
@@ -20,7 +20,7 @@ from urllib.parse import unquote
|
||||
from peewee import DoesNotExist, Field
|
||||
|
||||
from frigate.config import FrigateConfig
|
||||
from frigate.const import CLIPS_DIR, EXPORT_DIR, SUB_CACHE_TAG
|
||||
from frigate.const import CLIPS_DIR, EXPORT_DIR
|
||||
from frigate.models import Export, User
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -137,12 +137,11 @@ def _resolve_recording(
|
||||
# /recordings/{date} → neutral
|
||||
# /recordings/{date}/{hour} → multi-camera listing
|
||||
# /recordings/{date}/{hour}/{cam}/... → camera
|
||||
# /recordings/{date}/{hour}/{cam}@sub/... → camera (sub stream)
|
||||
if len(parts) <= 2:
|
||||
return MediaAuthResolution.LISTING_NEUTRAL, None
|
||||
if len(parts) == 3:
|
||||
return MediaAuthResolution.LISTING_MULTI_CAMERA, None
|
||||
return MediaAuthResolution.CAMERA, parts[3].removesuffix(SUB_CACHE_TAG)
|
||||
return MediaAuthResolution.CAMERA, parts[3]
|
||||
|
||||
|
||||
def _resolve_clip(
|
||||
@@ -151,7 +150,6 @@ def _resolve_clip(
|
||||
# /clips → multi-camera listing
|
||||
# /clips/thumbs/{cam}/... → camera
|
||||
# /clips/previews/{cam}/... → camera
|
||||
# /clips/triggers/{cam}/... → camera
|
||||
# /clips/review/thumb-{cam}-{review_id}.webp → camera (parsed)
|
||||
# /clips/export/{export_id}.{ext} → camera (DB lookup)
|
||||
# /clips/faces/... → admin-only
|
||||
@@ -165,7 +163,7 @@ def _resolve_clip(
|
||||
|
||||
second = parts[1]
|
||||
|
||||
if second in ("thumbs", "previews", "triggers"):
|
||||
if second in ("thumbs", "previews"):
|
||||
if len(parts) == 2:
|
||||
return MediaAuthResolution.LISTING_MULTI_CAMERA, None
|
||||
return MediaAuthResolution.CAMERA, parts[2]
|
||||
|
||||
@@ -685,7 +685,7 @@ class WebPushClient(Communicator):
|
||||
|
||||
title = f"{name.replace('_', ' ')} triggered on {camera_name}"
|
||||
message = f"{titlecase(trigger_type)} trigger fired for {camera_name} with score {score:.2f}"
|
||||
image = f"api/events/{event_id}/thumbnail.webp"
|
||||
image = f"clips/triggers/{camera}/{event_id}.webp"
|
||||
|
||||
direct_url = f"/explore?event_id={event_id}"
|
||||
ttl = 0
|
||||
|
||||
@@ -110,6 +110,13 @@ 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.
|
||||
|
||||
@@ -143,16 +150,10 @@ class LlamaCppClient(GenAIClient):
|
||||
self._supports_tools = False
|
||||
self._supports_reasoning = False
|
||||
|
||||
base_url = (
|
||||
self.genai_config.base_url.rstrip("/")
|
||||
if self.genai_config.base_url
|
||||
else None
|
||||
)
|
||||
base_url = self._server_url()
|
||||
|
||||
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
|
||||
@@ -506,11 +507,7 @@ 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.genai_config.base_url.rstrip("/")
|
||||
if self.genai_config.base_url
|
||||
else None
|
||||
)
|
||||
base_url = self.provider or self._server_url()
|
||||
|
||||
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 RemoteProtocolError, TimeoutException
|
||||
from httpx import HTTPError
|
||||
from ollama import AsyncClient as OllamaAsyncClient
|
||||
from ollama import Client as ApiClient
|
||||
from ollama import ResponseError
|
||||
@@ -282,12 +282,7 @@ class OllamaClient(GenAIClient):
|
||||
|
||||
try:
|
||||
response = self.provider.chat(**request_params)
|
||||
except (
|
||||
TimeoutException,
|
||||
ResponseError,
|
||||
RemoteProtocolError,
|
||||
ConnectionError,
|
||||
) as e:
|
||||
except (HTTPError, ResponseError, ConnectionError) as e:
|
||||
logger.warning("Ollama returned an error: %s", str(e))
|
||||
return None
|
||||
|
||||
@@ -406,13 +401,7 @@ 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 (
|
||||
TimeoutException,
|
||||
ResponseError,
|
||||
RemoteProtocolError,
|
||||
ConnectionError,
|
||||
ValueError,
|
||||
) as e:
|
||||
except (HTTPError, ResponseError, ConnectionError, ValueError) as e:
|
||||
logger.warning("Ollama embeddings error: %s", str(e))
|
||||
return []
|
||||
|
||||
@@ -553,7 +542,7 @@ class OllamaClient(GenAIClient):
|
||||
)
|
||||
response = self.provider.chat(**request_params)
|
||||
return self._message_from_response(response)
|
||||
except (TimeoutException, ResponseError, ConnectionError) as e:
|
||||
except (HTTPError, ResponseError, ConnectionError) as e:
|
||||
logger.warning("Ollama returned an error: %s", str(e))
|
||||
return {
|
||||
"content": None,
|
||||
@@ -685,7 +674,7 @@ class OllamaClient(GenAIClient):
|
||||
"finish_reason": "stop",
|
||||
},
|
||||
)
|
||||
except (TimeoutException, ResponseError, ConnectionError) as e:
|
||||
except (HTTPError, ResponseError, ConnectionError) as e:
|
||||
logger.warning("Ollama streaming error: %s", str(e))
|
||||
yield (
|
||||
"message",
|
||||
|
||||
+27
-17
@@ -28,6 +28,8 @@ _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
|
||||
|
||||
@@ -75,15 +77,17 @@ 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(
|
||||
@@ -204,7 +208,13 @@ class VLMWatchRunner(threading.Thread):
|
||||
)
|
||||
reasoning = str(parsed.get("reasoning", ""))
|
||||
notification_message = str(parsed.get("notification_message", ""))
|
||||
except (json.JSONDecodeError, ValueError, TypeError) as e:
|
||||
except (
|
||||
json.JSONDecodeError,
|
||||
ValueError,
|
||||
TypeError,
|
||||
AttributeError,
|
||||
OverflowError,
|
||||
) as e:
|
||||
logger.warning(
|
||||
"VLM watch job %s: failed to parse VLM response: %s", self.job.id, e
|
||||
)
|
||||
@@ -403,17 +413,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(
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
"""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 VLMWatchJob
|
||||
from frigate.jobs.vlm_watch import MAX_WATCH_MINUTES, VLMWatchJob, VLMWatchRunner
|
||||
from frigate.types import JobStatusTypesEnum
|
||||
|
||||
|
||||
def _request(user: str, role: str) -> SimpleNamespace:
|
||||
@@ -58,6 +60,51 @@ 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()
|
||||
|
||||
@@ -7,7 +7,10 @@ from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
|
||||
from frigate.util.classification import _extract_event_thumbnails
|
||||
from frigate.util.classification import (
|
||||
_extract_event_thumbnails,
|
||||
_select_balanced_timestamps,
|
||||
)
|
||||
|
||||
|
||||
class TestExtractEventThumbnails(unittest.TestCase):
|
||||
@@ -29,5 +32,17 @@ 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()
|
||||
|
||||
@@ -19,6 +19,7 @@ import unittest
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import httpx
|
||||
import requests
|
||||
|
||||
from frigate.config import GenAIConfig, GenAIProviderEnum
|
||||
@@ -821,6 +822,13 @@ 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
|
||||
@@ -975,6 +983,23 @@ 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 = [
|
||||
|
||||
@@ -122,11 +122,6 @@ class TestResolveMediaUri(unittest.TestCase):
|
||||
MediaAuthResolution.CAMERA,
|
||||
camera="back_door",
|
||||
)
|
||||
self._assert(
|
||||
"/recordings/2026-05-11/14/back_door@sub/00.00.mp4",
|
||||
MediaAuthResolution.CAMERA,
|
||||
camera="back_door",
|
||||
)
|
||||
|
||||
def test_clip_flat_filename_resolves_camera(self):
|
||||
self._assert(
|
||||
@@ -182,14 +177,6 @@ class TestResolveMediaUri(unittest.TestCase):
|
||||
camera="back_door",
|
||||
)
|
||||
|
||||
def test_clip_triggers(self):
|
||||
self._assert("/clips/triggers/", MediaAuthResolution.LISTING_MULTI_CAMERA)
|
||||
self._assert(
|
||||
"/clips/triggers/back_door/abc.webp",
|
||||
MediaAuthResolution.CAMERA,
|
||||
camera="back_door",
|
||||
)
|
||||
|
||||
def test_clip_review_thumbs(self):
|
||||
# Format: /clips/review/thumb-{camera}-{review_id}.webp (frigate/review/maintainer.py).
|
||||
self._assert(
|
||||
@@ -353,14 +340,6 @@ class TestDenyResponseForMediaUri(unittest.TestCase):
|
||||
self.assertIsNone(
|
||||
self._deny("/clips/thumbs/front_door/abc.webp", "limited_user")
|
||||
)
|
||||
self.assertIsNone(
|
||||
self._deny(
|
||||
"/recordings/2026-05-11/14/front_door@sub/00.00.mp4", "limited_user"
|
||||
)
|
||||
)
|
||||
self.assertIsNone(
|
||||
self._deny("/clips/triggers/front_door/abc.webp", "limited_user")
|
||||
)
|
||||
|
||||
def test_restricted_role_blocked_other_camera(self):
|
||||
self.assertEqual(self._deny("/clips/back_door-1.jpg", "limited_user"), 403)
|
||||
@@ -371,15 +350,6 @@ class TestDenyResponseForMediaUri(unittest.TestCase):
|
||||
self.assertEqual(
|
||||
self._deny("/clips/thumbs/back_door/abc.webp", "limited_user"), 403
|
||||
)
|
||||
self.assertEqual(
|
||||
self._deny(
|
||||
"/recordings/2026-05-11/14/back_door@sub/00.00.mp4", "limited_user"
|
||||
),
|
||||
403,
|
||||
)
|
||||
self.assertEqual(
|
||||
self._deny("/clips/triggers/back_door/abc.webp", "limited_user"), 403
|
||||
)
|
||||
|
||||
def test_restricted_role_blocked_admin_only(self):
|
||||
self.assertEqual(self._deny("/clips/faces/train/foo.webp", "limited_user"), 403)
|
||||
|
||||
@@ -1,65 +0,0 @@
|
||||
"""Tests for media sync orphan cleanup."""
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from peewee import SqliteDatabase
|
||||
|
||||
from frigate.models import Export, ExportCase
|
||||
from frigate.util.media import sync_exports
|
||||
|
||||
|
||||
class TestSyncExports(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.db = SqliteDatabase(":memory:")
|
||||
self.enterContext(self.db.bind_ctx([Export, ExportCase]))
|
||||
self.db.create_tables([Export, ExportCase])
|
||||
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.clips_dir = os.path.join(self.tmp.name, "clips")
|
||||
self.export_dir = os.path.join(self.tmp.name, "exports")
|
||||
self.thumb_dir = os.path.join(self.clips_dir, "export")
|
||||
os.makedirs(self.thumb_dir)
|
||||
os.makedirs(self.export_dir)
|
||||
|
||||
patcher_clips = patch("frigate.util.media.CLIPS_DIR", self.clips_dir)
|
||||
patcher_exports = patch("frigate.util.media.EXPORT_DIR", self.export_dir)
|
||||
patcher_clips.start()
|
||||
patcher_exports.start()
|
||||
self.addCleanup(patcher_clips.stop)
|
||||
self.addCleanup(patcher_exports.stop)
|
||||
|
||||
def tearDown(self):
|
||||
self.db.close()
|
||||
self.tmp.cleanup()
|
||||
|
||||
def _touch(self, path: str) -> str:
|
||||
open(path, "wb").close()
|
||||
return path
|
||||
|
||||
def test_orphaned_webp_and_jpg_thumbnails_are_removed(self):
|
||||
for i, ext in enumerate(("webp", "jpg")):
|
||||
Export.insert(
|
||||
id=f"front_{i}",
|
||||
camera="front",
|
||||
name=f"export {i}",
|
||||
date=0,
|
||||
video_path=self._touch(os.path.join(self.export_dir, f"{i}.mp4")),
|
||||
thumb_path=self._touch(os.path.join(self.thumb_dir, f"{i}.{ext}")),
|
||||
in_progress=False,
|
||||
).execute()
|
||||
|
||||
orphan_webp = self._touch(os.path.join(self.thumb_dir, "gone.webp"))
|
||||
orphan_jpg = self._touch(os.path.join(self.thumb_dir, "gone.jpg"))
|
||||
|
||||
result = sync_exports()
|
||||
|
||||
self.assertEqual(sorted(result.orphan_paths), sorted([orphan_jpg, orphan_webp]))
|
||||
self.assertEqual(result.orphans_deleted, 2)
|
||||
self.assertEqual(sorted(os.listdir(self.thumb_dir)), ["0.webp", "1.jpg"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,42 +0,0 @@
|
||||
"""Tests for trigger push notifications."""
|
||||
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from frigate.comms.webpush import WebPushClient
|
||||
|
||||
|
||||
class TestTriggerNotification(unittest.TestCase):
|
||||
def test_image_is_the_triggering_event_thumbnail(self):
|
||||
client = WebPushClient.__new__(WebPushClient)
|
||||
client.config = SimpleNamespace(
|
||||
notifications=SimpleNamespace(email="admin@example.com"),
|
||||
cameras={"front_door": SimpleNamespace(friendly_name=None)},
|
||||
)
|
||||
client.web_pushers = {"admin": []}
|
||||
client.user_cameras = {"admin": {"front_door"}}
|
||||
client.last_camera_notification_time = {}
|
||||
client._within_cooldown = MagicMock(return_value=False)
|
||||
client.check_registrations = MagicMock()
|
||||
client.cleanup_registrations = MagicMock()
|
||||
client.send_push_notification = MagicMock()
|
||||
|
||||
client.send_trigger(
|
||||
{
|
||||
"camera": "front_door",
|
||||
"event_id": "1700000000.0-abc123",
|
||||
"name": "red_car",
|
||||
"type": "thumbnail",
|
||||
"score": 0.9,
|
||||
}
|
||||
)
|
||||
|
||||
self.assertEqual(
|
||||
client.send_push_notification.call_args.kwargs["image"],
|
||||
"api/events/1700000000.0-abc123/thumbnail.webp",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -414,7 +414,6 @@ 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())
|
||||
@@ -429,29 +428,31 @@ 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)
|
||||
|
||||
# Step 3: Extract keyframes from recordings with crops applied
|
||||
keyframes = _extract_keyframes(
|
||||
"/usr/lib/ffmpeg/8.0/bin/ffmpeg", timestamps, temp_dir, cameras
|
||||
)
|
||||
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 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
|
||||
# Step 5: Save to train directory for later classification
|
||||
_save_train_examples(model_name, distinct_images)
|
||||
|
||||
|
||||
def _save_train_examples(model_name: str, image_paths: list[str]) -> int:
|
||||
"""Replace the model's train directory with the given images."""
|
||||
train_dir = os.path.join(CLIPS_DIR, model_name, "train")
|
||||
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(distinct_images):
|
||||
for idx, image_path in enumerate(image_paths):
|
||||
dest_path = os.path.join(train_dir, f"example_{idx:03d}.jpg")
|
||||
try:
|
||||
img = cv2.imread(image_path)
|
||||
@@ -462,10 +463,7 @@ def collect_state_classification_examples(
|
||||
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}")
|
||||
return saved_count
|
||||
|
||||
|
||||
def _select_balanced_timestamps(
|
||||
@@ -524,13 +522,20 @@ def _select_balanced_timestamps(
|
||||
}
|
||||
)
|
||||
|
||||
# If we don't have enough, sample more from larger groups
|
||||
while len(timestamps) < target_count and len(timestamps) < len(review_items):
|
||||
# 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
|
||||
):
|
||||
for group_items in grouped.values():
|
||||
if len(timestamps) >= target_count:
|
||||
if len(timestamps) >= target_count or attempts >= max_attempts:
|
||||
break
|
||||
|
||||
# Pick a random item not already sampled
|
||||
attempts += 1
|
||||
item = random.choice(group_items)
|
||||
duration = item.end_time - item.start_time
|
||||
if duration <= 0:
|
||||
@@ -770,9 +775,6 @@ 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(
|
||||
@@ -794,41 +796,21 @@ 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")
|
||||
|
||||
# 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")
|
||||
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 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 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")
|
||||
|
||||
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)
|
||||
# Step 5: Save to train directory for later classification
|
||||
saved_count = _save_train_examples(model_name, distinct_images)
|
||||
|
||||
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}"
|
||||
)
|
||||
logger.debug(f"Successfully collected {saved_count} classification examples")
|
||||
|
||||
|
||||
def _select_balanced_events(
|
||||
|
||||
@@ -639,7 +639,7 @@ def sync_exports(dry_run: bool = False, force: bool = False) -> SyncResult:
|
||||
"""Sync export files - delete files not referenced by any export record.
|
||||
|
||||
Export videos are stored at: EXPORT_DIR/*.mp4
|
||||
Export thumbnails are stored at: CLIPS_DIR/export/*.webp (legacy *.jpg)
|
||||
Export thumbnails are stored at: CLIPS_DIR/export/*.jpg
|
||||
The paths are stored in Export.video_path and Export.thumb_path
|
||||
"""
|
||||
result = SyncResult(media_type="exports")
|
||||
@@ -667,7 +667,7 @@ def sync_exports(dry_run: bool = False, force: bool = False) -> SyncResult:
|
||||
thumb_files: list[str] = []
|
||||
if os.path.isdir(export_thumb_dir):
|
||||
for file in os.listdir(export_thumb_dir):
|
||||
if file.endswith((".webp", ".jpg")):
|
||||
if file.endswith(".jpg"):
|
||||
file_path = os.path.join(export_thumb_dir, file)
|
||||
thumb_files.append(file_path)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user